@faststore/api 4.6.0 → 4.7.0-dev.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cjs/index.js CHANGED
@@ -1,12 +1,12 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const on=require("@graphql-tools/merge"),an=require("@graphql-tools/schema"),z=require("@graphql-tools/utils"),se=require("graphql"),B=require("@faststore/diagnostics"),Gn=require("isomorphic-unfetch"),ne=require("cookie"),Pe=require("p-limit"),pe=require("dataloader"),Hn=require("sanitize-html"),Ae=require("fast-deep-equal"),Xn=require("node:crypto");var sn=(e=>(e.Accepted="accepted",e.Denied="denied",e.Pending="pending",e))(sn||{}),cn=(e=>(e.Brand="Brand",e.Category="Category",e.Cluster="Cluster",e.Collection="Collection",e.Department="Department",e.SubCategory="SubCategory",e))(cn||{}),ln=(e=>(e.Boolean="BOOLEAN",e.Range="RANGE",e))(ln||{}),dn=(e=>(e.DiscountDesc="discount_desc",e.NameAsc="name_asc",e.NameDesc="name_desc",e.OrdersDesc="orders_desc",e.PriceAsc="price_asc",e.PriceDesc="price_desc",e.ReleaseDesc="release_desc",e.ScoreDesc="score_desc",e))(dn||{}),un=(e=>(e.Error="ERROR",e.Info="INFO",e.Warning="WARNING",e))(un||{}),pn=(e=>(e.Input="Input",e.Output="Output",e))(pn||{});const Yn=()=>function(n={}){const t=process.env.FS_DISCOVERY_APP_KEY??"",r=process.env.FS_DISCOVERY_APP_TOKEN??"";if(!t||!r)throw new x("No authentication AppKey and AppToken passed.");return{...n,"X-VTEX-API-AppKey":t,"X-VTEX-API-AppToken":r}},Jn=async e=>{const{clients:{commerce:n}}=e;try{if((await n.vtexid.validate())?.authStatus?.toLowerCase()!=="success")throw new K("Authentication required")}catch(t){const r=t.extensions?.status??t.status;throw r===401?new K("Authentication required"):r===403?new x("You are not allowed to access this resource"):new K("Authentication required")}},Kn="auth",gn={typeDefs:"directive @auth on FIELD_DEFINITION",transformer:e=>z.mapSchema(e,{[z.MapperKind.OBJECT_FIELD]:n=>{if(z.getDirective(e,n,Kn)?.[0]){const r=n.resolve;n.resolve=async(i,o,a,s)=>(await Jn(a),r?.(i,o,a,s))}return n}})},Qn="cacheControl",Zn=(e,n)=>{const{scope:t="private",sMaxAge:r=0,staleWhileRevalidate:i=0}=e;return`${n?"private":t}, s-maxage=${r}, stale-while-revalidate=${i}`},Ue=(e,n)=>typeof e=="number"&&typeof n=="number"?e>n?n:e:typeof e=="number"?e:n,et=(e,n)=>typeof e=="string"&&typeof n=="string"?e==="public"&&n==="public"?"public":"private":e||n,mn={typeDefs:"directive @cacheControl(sMaxAge: Int, staleWhileRevalidate: Int, scope: String) on FIELD_DEFINITION",transformer:e=>z.mapSchema(e,{[z.MapperKind.OBJECT_FIELD]:n=>{const t=z.getDirective(e,n,Qn)?.[0];if(t){const{sMaxAge:r,staleWhileRevalidate:i,scope:o}=t,a=n.resolve;n.resolve=(s,c,d,u)=>(d.cacheControl={sMaxAge:Ue(d.cacheControl?.sMaxAge,r),staleWhileRevalidate:Ue(d.cacheControl?.staleWhileRevalidate,i),scope:et(d.cacheControl?.scope,o)},a?.(s,c,d,u))}return n}})},hn=e=>(n,t)=>{const r=on.mergeTypeDefs([...(e??[]).map(({typeDefs:i})=>i),t]);return(e??[]).reduce((i,{transformer:o})=>o?.(i)??i,an.makeExecutableSchema({typeDefs:r,resolvers:n}))},fn="@faststore/api",Sn="4.6.0-dev.6",ke={name:fn,version:Sn},nt=B.logger("@faststore/api"),tt=(e,n="Unknown Graphql Resolver")=>(t,r,i,o)=>{if(!i?.OTEL_ENABLED)return e(t,r,i,o);const a=B.OTELAPI.trace.getTracer("Graphql").startSpan(n,{kind:B.OTELAPI.SpanKind.INTERNAL,attributes:{timestamp:Date.now(),"@faststore_version":Sn,"@faststore_package_name":fn,"@faststore_account_name":i.account,"@faststore_environment":process.env.NODE_ENV,"@faststore_resolver_parent_type":o?.parentType?.name,"@faststore_resolver_field_name":o?.fieldName}}),s=B.OTELAPI.trace.setSpan(B.OTELAPI.context.active(),a);try{const c=B.OTELAPI.context.with(s,()=>e(t,r,i,o));return c instanceof Promise?c.then(d=>(a.end(),d),d=>_e(d,a,n)):(a.end(),c)}catch(c){return _e(c,a,n)}};function _e(e,n,t){throw n.setStatus({code:B.OTELAPI.SpanStatusCode.ERROR}),n.recordException(e),n.end(),console.error(`Error at resolver: ${t}:
2
- %o`,e),nt("error",`Error at resolver: %s
3
- %o`,t,e),e}class W extends Error{constructor(n,t){super(t),this.extensions=n,this.name="FastStoreError"}}class T extends W{constructor(n){super({status:400,type:"BadRequestError"},n)}}class K extends W{constructor(n){super({status:401,type:"UnauthorizedError"},n)}}class x extends W{constructor(n){super({status:403,type:"ForbiddenError"},n)}}class N extends W{constructor(n){super({status:404,type:"NotFoundError"},n)}}const rt=e=>e?.name==="FastStoreError",it=e=>e?.extensions?.type==="BadRequestError",ot=e=>e?.extensions?.type==="UnauthorizedError",yn=e=>e?.extensions?.type==="ForbiddenError",q=e=>e?.extensions?.type==="NotFoundError",at=`${ke.name}@${ke.version}`,y=async(e,n,t)=>{const r=await Gn(e,{...n,headers:{...n?.headers??{},"User-Agent":at}});if(r.ok)return t?.storeCookies&&t.storeCookies(r.headers),r.status!==204?r.json():void 0;console.error(e,n,r);const i=await r.text();if(typeof r?.status=="number")switch(r.status){case 400:throw new T(i);case 401:throw new K(i);case 403:throw new x(i);case 404:throw new N(i);default:throw new W({status:r.status,type:"UnknownError"},i)}throw new Error(i)},st=({account:e,environment:n})=>{const t=`https://${e}.${n}.com.br`;return{getLocalizedProduct:(r,i)=>y(`${t}/api/catalog-dataplane/product/${r}`,{method:"GET",headers:{"Accept-Language":i,"Content-Type":"application/json"}})}},In=e=>{if(!e)return e;const n=new Map,t=e.split(";"),r=[];return t.forEach(i=>{const o=i.trim();if(o){const a=o.indexOf("=");if(a>0){const s=o.substring(0,a),c=o.substring(a+1);n.has(s)||r.push(s),n.set(s,c)}}}),r.map(i=>`${i}=${n.get(i)}`).join("; ")},ct=/^([^=]+)=([^;]*)/,lt=(e,n)=>{const t=n.match(ct);if(t){const r=t[1],i=t[2];e.storage.cookies.set(r,{value:i,setCookie:n})}},dt=(e,n)=>{n.getSetCookie().forEach(t=>lt(e,t))},ut=e=>n=>dt(e,n),me=e=>{if(!e.headers?.cookie)return null;const n=In(e.headers.cookie),t=Array.from(e.storage.cookies.entries());return t.length===0?n:t.reduce((r,[i,{value:o}])=>pt(r,i,o),n)},vn=e=>function(t){const r=me(e);return r?{...t,cookie:r}:t},V=(e,n)=>{const t=In(e);return ne.parse(t)[`VtexIdclientAutCookie_${n}`]||""},pt=(e,n,t)=>{const r=new RegExp(`(${n})=([^;]*)`),i=e.match(r);return i?e.replace(i[0],`${i[1]}=${t}`):`${e};${n}=${t}`};function Q(e){return e?JSON.parse(Buffer.from(e.split(".")[1],"base64").toString()):null}const gt="storefront/faststore.recommendation-shelf@v4",H={method:"POST",headers:{"content-type":"application/json"}},mt=e=>e.split("/").map(encodeURIComponent).join("/"),ge=e=>e?{headers:{"Accept-Language":e}}:void 0,ht=/^\d{4}-\d{2}-\d{2}$/,ft=new Set(["Draft","Requested","InReview","Reviewed","Approved","Declined","Expired","ConvertedToCart","ConvertedToOrder"]);function St({page:e,perPage:n,status:t,createdAtFrom:r,createdAtTo:i,expiresAtFrom:o,expiresAtTo:a}){if(e!==void 0&&(!Number.isInteger(e)||e<1))throw new Error(`listUserQuotes: invalid page "${e}" — must be a positive integer`);if(n!==void 0&&(!Number.isInteger(n)||n<1))throw new Error(`listUserQuotes: invalid perPage "${n}" — must be a positive integer`);for(const[s,c]of[["createdAtFrom",r],["createdAtTo",i],["expiresAtFrom",o],["expiresAtTo",a]])if(c&&!ht.test(c))throw new Error(`listUserQuotes: invalid ${s} "${c}" — must be YYYY-MM-DD`);if(t&&t.length>0){const s=t.filter(c=>!ft.has(c));if(s.length>0)throw new Error(`listUserQuotes: invalid status values: ${s.join(", ")}`)}}function yt({page:e,perPage:n,status:t,createdAtFrom:r,createdAtTo:i,expiresAtFrom:o,expiresAtTo:a,label:s}){const c=new URLSearchParams;return e&&c.append("pageNumber",e.toString()),n&&c.append("pageSize",n.toString()),t?.forEach(d=>c.append("status",d)),r&&c.append("createdAtFrom",r),i&&c.append("createdAtTo",i),o&&c.append("expiresAtFrom",o),a&&c.append("expiresAtTo",a),s?.trim()&&c.append("label",s.trim()),c}const It=({account:e,environment:n,incrementAddress:t,subDomainPrefix:r},i)=>{const o=`https://${e}.${n}.com.br`,a=ut(i),s=vn(i),c=Yn(),d=new Headers(i.headers).get("x-forwarded-host")??i.headers?.host??"",u=r&&r.map(l=>l+".").find(l=>d.includes(l))||"",p=d.replace(u,""),f=`${o}/api/recommend-bff/v2`,h=s({accept:"application/json","content-type":"application/json","x-vtex-rec-origin":`${e}/${gt}`}),v=(l={})=>{const g=V(me(i)??"",e);return s({...l,"X-FORWARDED-HOST":p,...g?{[`VtexIdclientAutCookie_${e}`]:g}:{}})};return{catalog:{salesChannel:l=>y(`${o}/api/catalog_system/pub/saleschannel/${l}`,void 0,{storeCookies:a}),brand:{list:()=>y(`${o}/api/catalog_system/pub/brand/list`,void 0,{storeCookies:a})},category:{tree:(l=3)=>y(`${o}/api/catalog_system/pub/category/tree/${l}`,void 0,{storeCookies:a})},portal:{pagetype:l=>y(`${o}/api/catalog_system/pub/portal/pagetype/${l}`,void 0,{storeCookies:a})},byLinkId:{category:async(l,g)=>{try{return await y(`${o}/api/catalog_system/pub/category/by-linkid/${mt(l)}`,ge(g))}catch(m){if(q(m))return null;throw m}},brand:async(l,g)=>{try{return await y(`${o}/api/catalog_system/pub/brand/by-linkid/${encodeURIComponent(l)}`,ge(g))}catch(m){if(q(m))return null;throw m}},collection:async(l,g)=>{try{return await y(`${o}/api/catalog_system/pub/collection/by-linkid/${encodeURIComponent(l)}`,ge(g))}catch(m){if(q(m))return null;throw m}}},products:{crossselling:({type:l,productId:g,groupByProduct:m=!0})=>{const S=new URLSearchParams({sc:i.storage.channel.salesChannel,groupByProduct:m.toString()});return y(`${o}/api/catalog_system/pub/products/crossselling/${l}/${g}?${S}`,void 0,{storeCookies:a})}}},checkout:{simulation:(l,{salesChannel:g}=i.storage.channel)=>{const m=new URLSearchParams({sc:g}),S=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${o}/api/checkout/pub/orderForms/simulation?${m.toString()}`,{...H,headers:S,body:JSON.stringify(l)},{storeCookies:a})},shippingData:({id:l,index:g,deliveryMode:m,selectedAddresses:S},O)=>{const w=O?{startDateUtc:m?.deliveryWindow?.startDate,endDateUtc:m?.deliveryWindow?.endDate}:null,b={logisticsInfo:Array.from({length:g},(I,D)=>({itemIndex:D,selectedDeliveryChannel:m?.deliveryChannel||null,selectedSla:m?.deliveryMethod||null,deliveryWindow:w})),selectedAddresses:S,clearAddressIfPostalCodeNotFound:t},U=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${o}/api/checkout/pub/orderForm/${l}/attachments/shippingData`,{...H,headers:U,body:JSON.stringify(b)},{storeCookies:a})},marketingData:({id:l,marketingData:g})=>{const m=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${o}/api/checkout/pub/orderForm/${l}/attachments/marketingData`,{headers:m,body:JSON.stringify(g),method:"POST"},{storeCookies:a})},clientPreferencesData:({id:l,clientPreferencesData:g})=>{const m=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${o}/api/checkout/pub/orderForm/${l}/attachments/clientPreferencesData`,{headers:m,body:JSON.stringify(g),method:"POST"},{storeCookies:a})},orderForm:({id:l,refreshOutdatedData:g=!0,channel:m=i.storage.channel,preserveSalesChannel:S=!1})=>{const{salesChannel:O}=m,w=s({"content-type":"application/json","X-FORWARDED-HOST":p}),b=new URLSearchParams;(!S||!l)&&b.set("sc",O),l&&b.set("refreshOutdatedData",g.toString());const U=l?`/${l}`:"",I=`${o}/api/checkout/pub/orderForm${U}?${b}`;return y(I,{...H,headers:w,...l?{}:{body:"{}"}},{storeCookies:a})},clearOrderFormMessages:({id:l})=>{const g=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${o}/api/checkout/pub/orderForm/${l}/messages/clear`,{...H,headers:g,body:"{}"})},updateOrderFormItems:({id:l,orderItems:g,allowOutdatedData:m="paymentData",salesChannel:S=i.storage.channel.salesChannel,shouldSplitItem:O=!0})=>{const w=new URLSearchParams({allowOutdatedData:m,sc:S}),b=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${o}/api/checkout/pub/orderForm/${l}/items?${w}`,{headers:b,body:JSON.stringify({orderItems:g,noSplitItem:!O}),method:"PATCH"},{storeCookies:a})},setCustomData:({id:l,appId:g,key:m,value:S})=>{const O=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${o}/api/checkout/pub/orderForm/${l}/customData/${g}/${m}`,{headers:O,body:JSON.stringify({value:S}),method:"PUT"})},region:async({postalCode:l,geoCoordinates:g,country:m,salesChannel:S})=>{const O=new URLSearchParams({country:m,sc:S??""});l?O.append("postalCode",l):O.append("geoCoordinates",`${g?.longitude};${g?.latitude}`);const w=`${o}/api/checkout/pub/regions/?${O.toString()}`,b=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(w,{headers:b},{storeCookies:a})},address:async({postalCode:l,country:g})=>{const m=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${o}/api/checkout/pub/postal-code/${g}/${l}`,{headers:m},{storeCookies:a})},cancelOrder:({orderId:l,customerEmail:g,reason:m})=>{const S=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${o}/api/checkout/pub/orders/${l}/user-cancel-request`,{method:"POST",headers:S,body:JSON.stringify({customerEmail:g,reason:m})},{})},pickupPoints:({geoCoordinates:l})=>{if(!l)throw new Error("Missing required parameter for listing pickup points.");const g=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${o}/api/logistics-shipping/pickuppoints/_search`,{method:"POST",headers:g,body:JSON.stringify({coordinate:l})},{storeCookies:a})}},session:l=>{const g=new URLSearchParams(l);g.set("items","profile.id,profile.email,profile.firstName,profile.lastName,profile.phone,shopper.firstName,shopper.lastName,shopper.organizationManager,shopper.availableContracts,shopper.activeContractId,store.channel,store.countryCode,store.cultureInfo,store.currencyCode,store.currencySymbol,authentication.customerId,authentication.storeUserId,authentication.storeUserEmail,authentication.unitId,authentication.unitName,checkout.regionId,public.postalCode");const m=s({"content-type":"application/json"}),S=ne.parse(i?.headers?.cookie??"")?.vtex_session;return y(`${o}/api/sessions?${g.toString()}`,{method:S?"PATCH":"POST",headers:m,body:"{}"},{storeCookies:a})},subscribeToNewsletter:l=>y(`${o}/api/dataentities/NL/documents/`,{...H,body:JSON.stringify({...l,isNewsletterOptIn:!0}),method:"PATCH"},{storeCookies:a}),profile:{addresses:async l=>{const g=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${o}/api/profile-system/pvt/profiles/${l}/addresses`,{headers:g},{storeCookies:a})}},oms:{userOrder:({orderId:l})=>{const g=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${o}/api/oms/user/orders/${l}`,{method:"GET",headers:g},{storeCookies:a})},listUserOrders:({page:l,status:g,dateInitial:m,dateFinal:S,text:O,clientEmail:w,perPage:b,pendingMyApproval:U})=>{const I=new URLSearchParams;if(m){const P=new Date(m).setHours(0,0,0,0);m=new Date(P).toISOString()}if(S){const P=new Date(S).setHours(23,59,59,999);S=new Date(P).toISOString()}O&&I.append("text",O),g&&g.length>0&&I.append("status",g.filter(Boolean).join(",")),m&&S?I.append("creation_date",`creationDate:[${m} TO ${S}]`):m?I.append("creation_date",`creationDate:[${m} TO *]`):S&&I.append("creation_date",`creationDate:[* TO ${S}]`),w&&I.append("clientEmail",w),l&&I.append("page",l.toString()),b&&I.append("per_page",b.toString()),U&&I.append("my_pending_approvals",String(!0));const D=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${o}/api/oms/user/orders?${I.toString()}`,{method:"GET",headers:D},{storeCookies:a})},getCommercialAuthorizationsByOrderId:({orderId:l})=>{const g=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${o}/${e}/commercial-authorizations/order/${l}`,{method:"GET",headers:g},{storeCookies:a})},processOrderAuthorization:async({orderAuthorizationId:l,dimensionId:g,ruleId:m,approved:S})=>{const O=s({"content-type":"application/json","X-FORWARDED-HOST":p}),U={params:{ruleId:m,dimensionId:g,score:S?100:0}};return y(`${o}/${e}/commercial-authorizations/${l}/callback`,{method:"POST",headers:O,body:JSON.stringify(U)},{storeCookies:a})}},units:{getUnitByUserId:({userId:l})=>{const g=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${o}/api/units/v1/${l}/unit`,{method:"GET",headers:g},{})},getOrgUnitById:({orgUnitId:l})=>{const g=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${o}/api/units/v1/${l}`,{method:"GET",headers:g},{})},getScopesByOrgUnit:({orgUnitId:l})=>{const g=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${o}/api/units/v1/${l}/scopes`,{method:"GET",headers:g},{})}},licenseManager:{getUserById:({userId:l})=>{const g=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${o}/api/license-manager/users/${l}`,{method:"GET",headers:g},{})},getUserByEmail:({email:l})=>{const g=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${o}/api/license-manager/pvt/users/${l}`,{method:"GET",headers:g},{})},getUserRoles:({userId:l})=>{const g=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${o}/api/license-manager/storefront/users/${l}/roles`,{method:"GET",headers:g},{})}},masterData:{getContractById:({contractId:l})=>{if(!l)throw new T("Missing contractId to fetch CL fields.");const g=v({Accept:"application/json","content-type":"application/json"});return y(`${o}/api/dataentities/CL/documents/${l}?_fields=_all`,{method:"GET",headers:g},{})},getShopperById:({userId:l})=>{if(!l)throw new T("Missing userId to fetch shopper name.");const g=c({Accept:"application/json","content-type":"application/json","X-FORWARDED-HOST":p}),m=l.replace(/-/g,"");return y(`${o}/api/dataentities/shopper/search?_where=(userId=${m} OR userId=${l})&_fields=_all&_schema=v1`,{method:"GET",headers:g},{})}},quotes:{listUserQuotes:l=>{St(l);const g=yt(l),m=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${o}/api/quoting/quotes?${g.toString()}`,{method:"GET",headers:m},{storeCookies:a})}},vtexid:{validate:()=>{const l=s({"content-type":"application/json","X-FORWARDED-HOST":p}),g=V(me(i)??"",e);return y(`${o}/api/vtexid/credential/validate`,{headers:l,body:JSON.stringify({token:g}),method:"POST"},{storeCookies:a})}},orderEntry:{uploadFile:({fileBuffer:l,fileName:g,mimeType:m})=>{const S=s({"content-type":"application/json","X-FORWARDED-HOST":p}),O=`----FastStoreUploadBoundary${Date.now()}`,w=`\r
4
- `,U=/^[a-zA-Z0-9][a-zA-Z0-9!#$&\-.^_]*\/[a-zA-Z0-9][a-zA-Z0-9!#$&\-.^_+]*$/.test(m)?m:"application/octet-stream",I=g.replaceAll(/[\r\n"]/g,"_"),D=[`--${O}`,`Content-Disposition: form-data; name="file"; filename="${I}"`,`Content-Type: ${U}`,"",""].join(w),P=`${w}--${O}--${w}`,E=Buffer.from(D),A=Buffer.from(P),R=new Uint8Array(E.byteLength+l.byteLength+A.byteLength);let C=0;return R.set(E,C),C+=E.byteLength,R.set(l,C),C+=l.byteLength,R.set(A,C),y(`${o}/api/order-entry/upload?an=${e}`,{method:"POST",headers:{...S,"content-type":`multipart/form-data; boundary=${O}`},body:R.buffer},{})},startOperation:({objectKey:l,orderFormId:g,sessionToken:m})=>{const S=s({"content-type":"application/json","X-FORWARDED-HOST":p}),O=JSON.stringify({objectKey:l,orderFormId:g,operation:"CreateCart",...m?{sessionToken:m}:{}});return y(`${o}/api/order-entry/operation?an=${e}`,{method:"POST",headers:S,body:O},{})},getOperation:({operationId:l})=>{const g=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${o}/api/order-entry/operation/${l}?an=${e}`,{method:"GET",headers:g},{})},createOrderForm:()=>{const l=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${o}/api/checkout/pub/orderForm?sc=${i.storage.channel.salesChannel}`,{method:"POST",headers:l,body:"{}"},{})},getOrderFormItems:({orderFormId:l})=>{const g=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${o}/api/checkout/pub/orderForm/${l}`,{method:"GET",headers:g},{})}},recommendation:{recommendations:({campaignVrn:l,userId:g,products:m=[],salesChannel:S,locale:O})=>{const w=new URLSearchParams({an:e,campaignVrn:l});return g&&w.append("userId",g),m.length>0&&w.append("products",m.join(",")),S&&w.append("salesChannel",S),O&&w.append("locale",O),y(`${f}/recommendations?${w.toString()}`,{headers:h},{storeCookies:a})},startRecommendationSession:()=>{const l=new URLSearchParams({an:e});return y(`${f}/users/start-session?${l.toString()}`,{method:"POST",headers:h},{storeCookies:a})}}}},Z=e=>e.discoveryConfig?.localization??{},ee=e=>Z(e).enabled===!0,vt=e=>Object.keys(Z(e).locales??{}),Ot=e=>Z(e).defaultLocale,oe=e=>ee(e)&&e.storage.locale||void 0,he="fuzzy",fe="operator",Se="pickupPoint",Re="shipping",Fe="delivery-options",Ct="in-stock",bt="trade-policy",wt="region-id",Dt=new Set([bt,wt,he,fe,Se]),Pt=new Set(["zip-code","pickupPoint","country","coordinates","deliveryZonesHash","pickupPointsHash"]),Ne=e=>encodeURI(decodeURI(e)),At=e=>encodeURIComponent(decodeURIComponent(e).normalize("NFD").replaceAll(/[\u0300-\u036f]/g,"")),Et=/^pickup-in-point-(.+)$/;function On(e){if(!e)return{};try{const t=ne.parse(e).vtex_segment;if(!t)return{};const r=Buffer.from(t,"base64").toString("utf-8");return JSON.parse(r)}catch{return{}}}function Tt(e){const n={},t=[];for(const r of e.split(";")){const i=r.indexOf("=");if(i<0)continue;const o=r.slice(0,i),a=r.slice(i+1);!o||!a||(Pt.has(o)?n[o]=a:t.push({key:o,value:a}))}return{shipping:n,extraFacets:t}}function Ut(e){const n=typeof e.facets=="string"?e.facets:"",{shipping:t,extraFacets:r}=Tt(n);return{segmentParams:{sc:e.channel,regionId:e.regionId,country:e.countryCode??t.country,locale:e.cultureInfo,"zip-code":t["zip-code"],coordinates:t.coordinates,pickupPoint:t.pickupPoint,deliveryZonesHash:t.deliveryZonesHash,pickupPointHash:t.pickupPointsHash,utmSource:e.utm_source??void 0,utmCampaign:e.utm_campaign??void 0,utmiCampaign:e.utmi_campaign??void 0,campaigns:typeof e.campaigns=="string"?e.campaigns:void 0,priceTables:e.priceTables??void 0},extraFacets:r}}function Cn(e,n){const t=[["sc",n.sc],["regionId",n.regionId],["country",n.country],["locale",n.locale],["zip-code",n["zip-code"]],["coordinates",n.coordinates],["pickupPoint",n.pickupPoint],["deliveryZonesHash",n.deliveryZonesHash],["pickupPointHash",n.pickupPointHash],["utmSource",n.utmSource],["utmCampaign",n.utmCampaign],["utmiCampaign",n.utmiCampaign],["campaigns",n.campaigns],["priceTables",n.priceTables]];for(const[r,i]of t)i!=null&&i!==""&&e.append(r,String(i))}function bn(e){return Et.exec(e)?.[1]}function kt(e){const n=e.find(r=>r.key==="shipping"),t=n?bn(n.value):void 0;if(t!==void 0)try{return decodeURIComponent(t)}catch{return t}}function _t(e,n){const t=kt(n);return t===void 0?e:{...e,pickupPoint:t}}function Rt(e){return e.map(n=>n.key!=="shipping"||bn(n.value)===void 0?n:{...n,value:"pickup-in-point"})}function Ft(e,n){let t=[...e];const r=t.some(i=>i.key==="shipping");for(const i of n)(!r||i.key!=="shipping")&&t.push(i);return t.some(i=>i.key==="shipping"&&i.value==="ignore")&&(t=t.filter(i=>i.key!=="shipping")),Rt(t)}function Nt(e){return e.reduce((n,t)=>{let{key:r,value:i}=t;return r==="priceRange"&&(r="price",i=i.replace(" TO ",":")),r==="ft"?n:`${n}${Ne(r)}/${At(Ne(i)).replaceAll(/ |%20/g,"-")}/`},"")}const Lt=e=>e.key==="fuzzy"&&(e.value==="0"||e.value==="1"||e.value==="auto"),Bt=e=>e.key==="operator"&&(e.value==="and"||e.value==="or");function $t(e,n){const{segmentParams:t,extraFacets:r}=Ut(e??{}),i=n?.salesChannel??t.sc,o=n?.regionId??t.regionId,a=n?.locale??t.locale??"";return{segmentParams:{...t,...i?{sc:i}:{},...o?{regionId:o}:{},locale:a},extraFacets:r}}function Mt(e,n){const t=e.filter(({key:c})=>!Dt.has(c)),r=e.find(({key:c,value:d})=>c===Re&&d!=="all-delivery-methods")??null,i=e.find(({key:c,value:d})=>c===Fe&&d!=="all-delivery-options")??null,o=[...t],a=o.some(({key:c})=>c===Re),s=o.some(({key:c})=>c===Fe);return r!==null&&!a&&o.push(r),i!==null&&!s&&o.push(i),Ft(o,n)}function zt(e,n){const t=e.find(({key:o})=>o===he)??null,r=e.find(({key:o})=>o===fe)??null,i=e.find(({key:o})=>o===Se)??null;t&&Lt(t)&&n.append(he,t.value),r&&Bt(r)&&n.append(fe,r.value),i&&n.append(Se,i.value)}function Le(e,n,t,r){const{query:i="",page:o,count:a,sort:s,selectedFacets:c=[],showInvisibleItems:d,sponsoredCount:u,hideUnavailableItems:p,allowRedirect:f=!1}=e,h=new URLSearchParams;if(r.includePagination&&o!==void 0&&a!==void 0){const g=o*a,m=a===0?g:g+a-1;h.append("from",g.toString()),h.append("to",m.toString())}i&&h.append("query",i),r.includeSort&&s&&h.append("sort",s);const v=_t(t.segmentParams,c);if(Cn(h,v??t.segmentParams),zt(c,h),d&&h.append("show-invisible-items","true"),n?.hideUnavailableItems!==void 0){const g=c.find(({key:S})=>S===Ct),m=g?g.value:p?.toString()??n.hideUnavailableItems.toString();h.append("hideUnavailableItems",m)}n?.simulationBehavior!==void 0&&h.append("simulationBehavior",n.simulationBehavior.toString()),n?.showSponsored!==void 0&&h.append("showSponsored",n.showSponsored.toString()),u!==void 0&&h.append("sponsoredCount",u.toString()),f!==void 0&&h.append("allowRedirect",f.toString());const l=Nt(Mt(c,t.extraFacets));return{params:h,path:l}}function qt(e,n){const{field:t,value:r,hideUnavailableItems:i,showInvisibleItems:o}=e,a=new URLSearchParams({field:t??"",value:r??""});return Cn(a,n),i&&a.append("hideUnavailableItems","true"),o&&a.append("show-invisible-items","true"),a}function X(e,n){return{path:e,params:n,toString(){const t=n.toString();return e?t?`${e}?${t}`:e:t?`?${t}`:""}}}function Y(e){const{endpoint:n,segment:t,defaults:r,args:i={}}=e,o=$t(t,r);switch(n){case"product-search":case"facets":{const{params:a,path:s}=Le(i,r,o,{includePagination:!0,includeSort:!0});return X(s,a)}case"catalog-count":{const{params:a,path:s}=Le(i,r,o,{includePagination:!1,includeSort:!1});return X(s,a)}case"products":{const a=qt(i,o.segmentParams);return X("",a)}case"search-suggestions":{const a=new URLSearchParams({query:i.query?.toString()??"",locale:r?.locale??o.segmentParams.locale??""});return X("",a)}case"top-searches":{const a=new URLSearchParams({locale:r?.locale??o.segmentParams.locale??""});return X("",a)}default:{const a=n;throw new Error(`Unknown intelligent-search endpoint: ${a}`)}}}const Vt=10;function xt(e){const{regionId:n,seller:t}=e.storage.channel;return(t?Buffer.from(`SW#${t}`).toString("base64"):void 0)??(n||void 0)}function jt(e){const t=On(e.headers?.cookie).cultureInfo||"";return ee(e)?e.storage.locale||t:t||e.storage.locale||""}const Wt=({account:e,environment:n,hideUnavailableItems:t,simulationBehavior:r,showSponsored:i,subDomainPrefix:o},a)=>{const s=`https://${e}.${n}.com.br`,c=vn(a),d=On(a.headers?.cookie),u=()=>({salesChannel:a.storage.channel.salesChannel,regionId:xt(a),locale:jt(a),hideUnavailableItems:t,simulationBehavior:r,showSponsored:i}),p=new Headers(a.headers).get("x-forwarded-host")??a.headers?.host??"",f=o&&o.map(I=>I+".").find(I=>p.includes(I))||"",h=p.replace(f,""),v=c({"content-type":"application/json","X-FORWARDED-HOST":h}),l=({type:I,...D})=>{const P=I==="facets"?"facets":"product-search",E=Y({endpoint:P,segment:d,defaults:u(),args:D});return y(`${s}/api/intelligent-search/v1/${P}/${E.path}?${E.params.toString()}`,{headers:v})},g=I=>l({...I,type:"product_search"}),m=({field:I,value:D,hideUnavailableItems:P,showInvisibleItems:E})=>{const A=Y({endpoint:"products",segment:d,defaults:u(),args:{field:I,value:D,hideUnavailableItems:P,showInvisibleItems:E}});return y(`${s}/api/intelligent-search/v1/products?${A.params.toString()}`,{headers:v})};return{facets:I=>l({...I,type:"facets"}),products:g,fetchProduct:m,productsByIdentifier:async({field:I,values:D,showInvisibleItems:P,hideUnavailableItems:E})=>{const A=Pe(Vt);return(await Promise.all(D.map(C=>A(async()=>{try{return await m({field:I,value:C,hideUnavailableItems:E,showInvisibleItems:P})}catch{return null}})))).filter(C=>C!==null)},suggestedTerms:I=>{const D=Y({endpoint:"search-suggestions",segment:d,defaults:u(),args:{query:I.query}});return y(`${s}/api/intelligent-search/v1/search-suggestions?${D.params.toString()}`,{headers:v})},topSearches:()=>{const I=Y({endpoint:"top-searches",segment:d,defaults:u()});return y(`${s}/api/intelligent-search/v1/top-searches?${I.params.toString()}`,{headers:v})},productCount:I=>{const D=Y({endpoint:"catalog-count",segment:d,defaults:u(),args:I});return y(`${s}/api/intelligent-search/v1/catalog-count/${D.path}?${D.params.toString()}`,{headers:v})}}},Gt=(e,n)=>{const t=Wt(e,n),r=It(e,n),i=st(e);return{search:t,commerce:r,catalog:i}},Ht=20,Xt=e=>e.entityType==="category",ye=e=>e.entityType==="brand",Be=e=>e.entityType==="collection",Yt=(e,n)=>{const t=Pe(Ht),r=async i=>Promise.all(i.map(o=>t(async()=>{const a=o.slug.toLowerCase(),s=o.locale,c=await n.commerce.catalog.byLinkId.category(a,s);if(c)return{...c,entityType:"category",slug:a};const d=await n.commerce.catalog.byLinkId.brand(a,s);if(d)return{...d,entityType:"brand"};const u=await n.commerce.catalog.byLinkId.collection(a,s);if(u)return{...u,entityType:"collection"};throw new N(`No catalog entity found for slug: ${o.slug}. Cascade exhausted (category → brand → collection).`)})));return new pe(r,{batch:!1,cacheKeyFn:({slug:i,locale:o})=>`${i.toLowerCase()}::${o??""}`})},Jt=(e,n)=>{const t=async r=>Promise.all(r.map(i=>n.commerce.catalog.salesChannel(i)));return new pe(t)},Kt=1,Qt=(e,n)=>{const t=Pe(Kt),r=async o=>{const a=o.reduce((p,{items:f})=>[...p,f],[]),s=[...a.flat()],c=await n.commerce.checkout.simulation({country:o[0].country,postalCode:o[0].postalCode,items:s}),d=c.items.reduce((p,f)=>{const h=f.requestIndex;return typeof h=="number"&&h<p.length&&(p[h]=f),p},Array(s.length).fill(null)),u=a.reduce((p,f)=>[...p,f.length+p[p.length-1]],[0]);return a.map((p,f)=>({...c,items:d.slice(u[f],u[f+1]).filter(h=>!!h)}))},i=async o=>t(r,o);return new pe(i,{maxBatchSize:50})},Zt=(e,n)=>Hn(e,n);function er(e){return{...e,description:e.description?Zt(e.description):e.description}}const F=(e,n)=>({...e,isVariantOf:er(n)}),nr=({flags:e},n)=>{const t=async r=>{const i=r.map(u=>u.split("-")[0]),o=r.some(u=>u.split("-")[1]==="invisibleItems"),s=(await n.search.productsByIdentifier({field:"sku",values:i,showInvisibleItems:o,...e?.enableUnavailableItemsOnCart&&{hideUnavailableItems:!1}})).reduce((u,p)=>{for(const f of p.items)u[f.itemId]=F(f,p);return u},{}),c=i.map(u=>s[u]),d=i.filter(u=>!s[u]);if(d.length>0)throw new N(`Search API did not found the following skus: ${d.join(",")}`);return c};return new pe(t,{maxBatchSize:99})},tr=(e,n)=>{const{clients:t}=n,r=nr(e,t),i=Qt(e,t),o=Yt(e,t),a=Jt(e,t);return{skuLoader:r,simulationLoader:i,collectionLoader:o,salesChannelLoader:a}},$=e=>e.AvailableQuantity>0,j=e=>e.spotPrice??0,rr=e=>e.Price??0,$e=e=>e?"https://schema.org/InStock":"https://schema.org/OutOfStock",wn=(e,n)=>$(e)&&!$(n)?-1:!$(e)&&$(n)?1:j(e)-j(n),ir=e=>e==="available",M=(e,n=0,t=1)=>{const r=n/t;return Math.round((e+r)*100)/100},or=(e,n={includeTaxes:!1})=>{const t=e.filter($),r=t[t.length-1],i=r?j(r):0;return n.includeTaxes?M(i,r?.Tax,r?.product?.unitMultiplier):i},Me=(e,n={includeTaxes:!1})=>{const[t]=e.filter($),r=t?j(t):0;return n.includeTaxes?M(r,t?.Tax,t?.product?.unitMultiplier):r},ar={highPrice:e=>or(e),lowPrice:e=>Me(e),lowPriceWithTaxes:e=>Me(e,{includeTaxes:!0}),offerCount:e=>e.length,priceCurrency:async(e,n,t)=>{const{loaders:{salesChannelLoader:r},storage:{channel:i}}=t;return(await r.load(i.salesChannel)).CurrencyCode??""},offers:e=>e},sr={ratingValue:()=>5,reviewCount:()=>0},ze="ÁÄÂÀÃÅČÇĆĎÉĚËÈÊẼĔȆÍÌÎÏŇÑÓÖÒÔÕØŘŔŠŤÚŮÜÙÛÝŸŽáäâàãåčçćďéěëèêẽĕȇíìîïňñóöòôõøðřŕšťúůüùûýÿžþÞĐđ߯a",cr="AAAAAACCCDEEEEEEEEIIIINNOOOOOORRSTUUUUUYYZaaaaaacccdeeeeeeeeiiiinnooooooorrstuuuuuyyzbBDdBAa",lr=e=>{let n=e.slice(0);for(let t=0;t<ze.length;t++)n=n.replace(new RegExp(ze.charAt(t),"g"),cr.charAt(t));return n},dr=e=>e.replace(/[·/_,:]/,"-");function ce(e){const t=e.replace(/,/g,"").replace(/[*+~.()'"!:@&\[\]`/ %$#?{}><=_^]/g,"-");return dr(lr(t)).toLowerCase()}const J=e=>Xt(e)?e.slug:ye(e)?e.linkId:e.linkId??ce(e.name),Dn={id:({id:e})=>e.toString(),slug:e=>J(e),seo:e=>({title:e.title??e.name,description:e.metaTagDescription??e.description}),type:e=>ye(e)?"Brand":Be(e)?"Collection":e.fatherCategoryId===null?"Department":"Category",meta:async(e,n,t)=>{const r=J(e);if(ye(e))return{selectedFacets:[{key:"brand",value:r}]};if(Be(e))return{selectedFacets:[{key:"productclusterids",value:e.id}]};const{defaultLocale:i}=Z(t),o=r.split("/").filter(Boolean),a=o.map((d,u)=>o.slice(0,u+1).join("/")),{loaders:{collectionLoader:s}}=t;return{selectedFacets:(await Promise.all(a.map(d=>s.load({slug:d,locale:oe(t)})))).map((d,u)=>({key:`category-${u+1}`,value:i&&d.availableLinkIds?.[i]||d.linkId}))}},breadcrumbList:async(e,n,t)=>{const{loaders:{collectionLoader:r}}=t,o=J(e).split("/").filter(Boolean),a=o.map((c,d)=>o.slice(0,d+1).join("/")),s=await Promise.all(a.map(c=>r.load({slug:c,locale:oe(t)})));return{itemListElement:s.map((c,d)=>({item:`/${J(c)}`,name:c.name,position:d+1})),numberOfItems:s.length}},otherLocales:async(e,n,t)=>{const r=Z(t);if(!r.enabled)return null;const i=Object.keys(r.locales??{});if(i.length===0)return null;const o=t.storage.locale,a=J(e),s=a.split("/").filter(Boolean);if(s.length===0)return null;const{loaders:{collectionLoader:c}}=t,d=s.map((p,f)=>s.slice(0,f+1).join("/"));let u;try{u=await Promise.all(d.map(p=>c.load({slug:p,locale:oe(t)})))}catch(p){return console.warn("[otherLocales] failed to load collection entities:",p),null}return i.map(p=>{if(p===o)return{locale:p,slug:a};const f=[];for(const h of u){const v=h.availableLinkIds?.[p];if(!v)return null;f.push(v)}return f.length>0?{locale:p,slug:f.join("/")}:null}).filter(p=>p!==null)}},Pn={buy:"whoboughtalsobought",view:"whosawalsosaw",similars:"similars",viewAndBought:"whosawalsobought",accessories:"accessories",suggestions:"suggestions"},qe=({key:e,value:n})=>{switch(e){case"price":return{key:e,value:n.replace("-to-",":")};case"channel":case"locale":case"buy":case"view":case"similars":case"viewAndBought":case"accessories":case"suggestions":return[];default:return{key:e,value:n}}},Ve=e=>{const n=e.split(":").map(Number);return n.length!==2||Number.isNaN(n[0])||Number.isNaN(n[1])?null:n},ur=e=>typeof Pn[e]=="string",pr=e=>{const n=e?.filter(t=>ur(t.key));if(Array.isArray(n)&&n.length>1)throw new T(`You passed ${n.length} cross selling facets but only one is allowed. Please leave one of the following facet: ${n.map(t=>t.key).join(",")}`);return n?.[0]??null},gr=e=>e?.find(n=>n.key==="slug")?.value??null,mr=e=>e?.find(n=>n.key==="id")?.value??null,xe=e=>e?.find(n=>n.key==="locale")?.value??null,je=e=>e?.find(n=>n.key==="channel")?.value??null,Ie=(e,n)=>{let t=0;for(let r=1;r<e.length;r++)n(e[t],e[r])>0&&(t=r);return e[t]},hr={__resolveType:({type:e,values:n})=>e!=="TEXT"&&e!=="DELIVERY"?"StoreFacetRange":!n||n.length===0?"StoreFacetBoolean":n.every(t=>t.range)?"StoreFacetRange":"StoreFacetBoolean"},fr={key:({key:e})=>e,label:({name:e})=>e,values:({values:e})=>e.sort((n,t)=>n.name.localeCompare(t.name))},Sr={key:({key:e})=>e,label:({name:e})=>e,min:({values:e,key:n},t,{storage:{searchArgs:r}})=>{const i=Ve(r?.selectedFacets?.find(s=>s.key===n)?.value??""),a=Ie(e,(s,c)=>s.range.from-c.range.from)?.range?.from??0;return{selected:i?.[0]??a,absolute:a}},max:({values:e,key:n},t,{storage:{searchArgs:r}})=>{const i=Ve(r?.selectedFacets?.find(s=>s.key===n)?.value??""),a=Ie(e,(s,c)=>c.range.to-s.range.to)?.range?.to??0;return{selected:i?.[1]??a,absolute:a}}},yr={value:({value:e})=>e,label:({name:e})=>e||"unknown",selected:({selected:e})=>e,quantity:({quantity:e})=>e},Ir=async(e,{data:n},{clients:{commerce:t}})=>{if(!n?.orderId)throw new T("Missing orderId");return{data:(await t.checkout.cancelOrder(n))?.data}};function An(e){if(!e||e.status!=="pending")return null;for(const n of e.dimensionStatus){if(n.status!=="pending")continue;const t=n.ruleCollection.find(r=>r.status==="pending"&&r.isUserNextAuthorizer);if(t)return{rule:t,orderAuthorizationId:e.id,dimensionId:n.id}}return null}function vr(e){if(!e||e.status!=="pending")return!1;const n=e.dimensionStatus.filter(t=>t.status==="pending").flatMap(t=>t.ruleCollection).filter(t=>t.status==="pending");return n.length===0?!1:n.every(t=>!t.isUserNextAuthorizer)}const Or=async(e,{data:n},{clients:{commerce:t}})=>{const r=await t.oms.processOrderAuthorization(n),i=An(r);return{isPendingForOtherAuthorizer:!i&&vr(r),ruleForAuthorization:i}},Cr=async(e,{data:n},{clients:{commerce:t}})=>{if(!n?.objectKey)throw new T("Missing objectKey");const r=n.orderFormId||(await t.orderEntry.createOrderForm()).orderFormId;return t.orderEntry.startOperation({objectKey:n.objectKey,orderFormId:r,sessionToken:n.sessionToken??void 0})},br=async(e,n,t)=>{if(!(await t.clients.commerce.recommendation.startRecommendationSession())?.recommendationsUserId)throw new Error("Failed to start recommendation session: no session data returned");return!0},wr=async(e,{data:n},{clients:{commerce:t}})=>({id:(await t.subscribeToNewsletter(n))?.Id}),Dr=async(e,{data:n},{clients:{commerce:t}})=>{const{fileContent:r,fileName:i,mimeType:o}=n;if(!r||!i||!o)throw new T("Missing required fields: fileContent, fileName, mimeType");const a=r.replaceAll(/\s/g,""),s=5*1024*1024;if(Math.floor(a.length*3/4)>s)throw new T("File exceeds maximum allowed size of 5MB");if(!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(a))throw new T("Invalid Base64 fileContent");const u=Buffer.from(a,"base64");return await t.orderEntry.uploadFile({fileBuffer:u,fileName:i,mimeType:o})};class te{static parse(n){try{const t=JSON.parse(n);return{seller:t.seller??"",regionId:t.regionId??"",salesChannel:t.salesChannel??"",hasOnlyDefaultSalesChannel:t.hasOnlyDefaultSalesChannel??!0}}catch(t){throw console.error(t),new Error("Malformed channel string")}}static stringify(n){return JSON.stringify(n)}}function Pr(e,n){return n==null||n===""||String(n)===String(e.salesChannel??"")?null:te.stringify({...e,salesChannel:String(n),hasOnlyDefaultSalesChannel:!1})}const le=(e,n)=>{e.storage.channel=te.parse(n)},ve=(e,n)=>{e.storage.locale=n},En=e=>Xn.createHash("md5").update(e).digest("hex"),re={attachment:"ATTACHMENT",specification:"SPECIFICATION",attribute:"ATTRIBUTE"};function Tn(e){return{name:e.name,value:e.content,valueReference:re.attachment}}function Ar(e){return{propertyID:e.id,name:e.name,value:e.value,valueReference:{valueReference:re.attribute,visible:e.visible}}}function Un(e){return En(`${e.name}:${JSON.stringify(e.value)}:${e.valueReference}`)}const Er=e=>{const n=e.postalCode,t=e.geoCoordinates,r={addressType:e.addressType||null,postalCode:n||null,city:null,state:null,country:e.country||null,street:null,number:null,neighborhood:null,complement:null,reference:null,geoCoordinates:[]};if(t){const i=typeof t=="object"&&"latitude"in t?t.latitude:null,o=typeof t=="object"&&"longitude"in t?t.longitude:null;r.geoCoordinates=i!==null&&o!==null?[o,i]:[]}return[r]},Tr=(e,n,t)=>{const r=n.postalCode,i=n.geoCoordinates,o=e?.shippingData?.availableAddresses??[],a=e?.shippingData?.selectedAddresses??[];if(!t&&a.length>0)return[a[0]];if(t&&o.length>0)for(const s of o){if(r&&i&&(s.postalCode===r||s.geoCoordinates[0]===i.longitude&&s.geoCoordinates[1]===i.latitude))return[s];if(r&&!i&&s.postalCode===r)return[s];if(i&&!r&&s.geoCoordinates[0]===i.longitude&&s.geoCoordinates[1]===i.latitude)return[s]}return null},kn=(e,n)=>{if(!Ur(n))return{updateShipping:!1,addressChanged:!1};if(!Fr(e))return{updateShipping:!1,addressChanged:!1};const[t]=e?.shippingData?.selectedAddresses??[];if(kr(t,n.postalCode)||_r(t,n.geoCoordinates)||Rr(t,n.addressType))return{updateShipping:!0,addressChanged:!0};const{logisticsInfo:r}=e.shippingData;return Nr(r,n)?{updateShipping:!0,addressChanged:!1}:{updateShipping:!1,addressChanged:!1}},Ur=e=>!!e.postalCode||e.geoCoordinates?.latitude&&e.geoCoordinates?.longitude,kr=(e,n)=>typeof n=="string"&&e?.postalCode!==n,_r=(e,n)=>typeof n?.latitude=="number"&&typeof n?.longitude=="number"&&(e?.geoCoordinates[0]!==n?.longitude||e?.geoCoordinates[1]!==n?.latitude),Rr=(e,n)=>typeof n=="string"&&e?.addressType!==n,Fr=e=>e.items.length!==0,Nr=(e,n)=>{const t=n?.deliveryMode?.deliveryChannel,r=n?.deliveryMode?.deliveryMethod,{startDate:i,endDate:o}=n?.deliveryMode?.deliveryWindow||{};return e.some(({selectedDeliveryChannel:a,selectedSla:s,slas:c})=>{const d=t&&a!==t,u=r&&s!==r;return c?.some(p=>d&&p.deliveryChannel===t||u&&p.id===r?!0:i&&o&&p.deliveryChannel===t&&p.id===r&&(!p?.deliveryWindow||p?.deliveryWindow?.startDateUtc!==i||p?.deliveryWindow?.endDateUtc!==o)&&p.availableDeliveryWindows?.some(f=>f?.startDateUtc===i&&f?.endDateUtc===o))})},_n=e=>e.valueReference===re.attachment,Oe=e=>[e.itemOffered.sku,e.seller.identifier,e.price<.01?"Gift":void 0,e.itemOffered.additionalProperty?.filter(_n).map(Un).join("-")].filter(Boolean).join("::"),de=(e,n)=>({listPrice:e.listPrice/100,price:e.sellingPrice/100,quantity:e.quantity,seller:{identifier:e.seller},itemOffered:{sku:e.id,image:[],name:e.name,additionalProperty:e.attachments.map(Tn)},index:n}),Lr=e=>({quantity:e.quantity,seller:e.seller.identifier,id:e.itemOffered.sku,index:e.index,attachments:(e.itemOffered.additionalProperty?.filter(_n)??[]).map(n=>({name:n.name,content:n.value})),...e.priceToken?{priceToken:e.priceToken}:{}}),We=e=>e.reduce((n,t)=>{const r=Oe(t);return n.has(r)||n.set(r,[]),n.get(r)?.push(t),n},new Map),Br=(e,n)=>{const t=({priceToken:s,...c},d)=>({...c,itemOffered:{sku:c.itemOffered.sku},index:d}),r=n.items.map(de).map(t),i=e.acceptedOffer.map(t),o=e.orderNumber===n.orderFormId,a=Ae(r,i);return o&&a};function Rn(e,n){return e?.some(t=>t.parentItemIndex!==null&&t.parentItemIndex!==void 0&&e[t.parentItemIndex]?.id===n)}function Fn(e,n){return e?.some(t=>t.id===n&&t.parentItemIndex!==null)}const Ge=e=>{const n=e.items.reduce((t,r,i)=>{const o=Fn(e.items,r.id)||Rn(e.items,r.id)?`${Oe(de(r))}::${i}`:Oe(de(r));return t[o]||(t[o]=[]),t[o].push(r),t},{});return{...e,items:Object.values(n).map(t=>{const[r]=t,i=t.reduce((a,s)=>a+s.quantity,0),o=t.reduce((a,s)=>a+(s?.priceDefinition?.total??(s?.quantity??0)*(s?.sellingPrice??0)),0);return{...r,quantity:i,sellingPrice:o/i}})}},Ce=async(e,n,t,r)=>({order:{orderNumber:e.orderFormId,acceptedOffer:e.items.map(async i=>({...i,product:await n.load(`${i.id}-invisibleItems`)})),shouldSplitItem:t,...r?{salesChannel:r}:{}},messages:e.messages.map(({text:i,status:o})=>({text:i,status:o.toUpperCase()}))}),Nn=({items:e},n)=>{const t=e.map(r=>({id:r.id,quantity:r.quantity,seller:r.seller,attachments:r.attachments}));return En(JSON.stringify({sessionId:n?.id??"",items:t}))},He=async(e,n,t)=>{try{return await n.checkout.setCustomData({id:e.orderFormId,appId:"faststore",key:"cartEtag",value:Nn(e,t)})}catch(r){throw console.error(`Error while setting custom data to orderForm.
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const an=require("@graphql-tools/merge"),on=require("@graphql-tools/schema"),V=require("@graphql-tools/utils"),se=require("graphql"),B=require("@faststore/diagnostics"),Hn=require("isomorphic-unfetch"),ne=require("cookie"),Ae=require("p-limit"),pe=require("dataloader"),Xn=require("sanitize-html"),Pe=require("fast-deep-equal"),Yn=require("node:crypto");var sn=(e=>(e.Personal="personal",e.Shared="shared",e))(sn||{}),cn=(e=>(e.Accepted="accepted",e.Denied="denied",e.Pending="pending",e))(cn||{}),ln=(e=>(e.Brand="Brand",e.Category="Category",e.Cluster="Cluster",e.Collection="Collection",e.Department="Department",e.SubCategory="SubCategory",e))(ln||{}),dn=(e=>(e.Boolean="BOOLEAN",e.Range="RANGE",e))(dn||{}),un=(e=>(e.DiscountDesc="discount_desc",e.NameAsc="name_asc",e.NameDesc="name_desc",e.OrdersDesc="orders_desc",e.PriceAsc="price_asc",e.PriceDesc="price_desc",e.ReleaseDesc="release_desc",e.ScoreDesc="score_desc",e))(un||{}),pn=(e=>(e.Error="ERROR",e.Info="INFO",e.Warning="WARNING",e))(pn||{}),gn=(e=>(e.Input="Input",e.Output="Output",e))(gn||{});const Jn=()=>function(n={}){const t=process.env.FS_DISCOVERY_APP_KEY??"",r=process.env.FS_DISCOVERY_APP_TOKEN??"";if(!t||!r)throw new j("No authentication AppKey and AppToken passed.");return{...n,"X-VTEX-API-AppKey":t,"X-VTEX-API-AppToken":r}},Kn=async e=>{const{clients:{commerce:n}}=e;try{if((await n.vtexid.validate())?.authStatus?.toLowerCase()!=="success")throw new Q("Authentication required")}catch(t){const r=t.extensions?.status??t.status;throw r===401?new Q("Authentication required"):r===403?new j("You are not allowed to access this resource"):new Q("Authentication required")}},Qn="auth",mn={typeDefs:"directive @auth on FIELD_DEFINITION",transformer:e=>V.mapSchema(e,{[V.MapperKind.OBJECT_FIELD]:n=>{if(V.getDirective(e,n,Qn)?.[0]){const r=n.resolve;n.resolve=async(i,a,o,s)=>(await Kn(o),r?.(i,a,o,s))}return n}})},Zn="cacheControl",et=(e,n)=>{const{scope:t="private",sMaxAge:r=0,staleWhileRevalidate:i=0}=e;return`${n?"private":t}, s-maxage=${r}, stale-while-revalidate=${i}`},_e=(e,n)=>typeof e=="number"&&typeof n=="number"?e>n?n:e:typeof e=="number"?e:n,nt=(e,n)=>typeof e=="string"&&typeof n=="string"?e==="public"&&n==="public"?"public":"private":e||n,hn={typeDefs:"directive @cacheControl(sMaxAge: Int, staleWhileRevalidate: Int, scope: String) on FIELD_DEFINITION",transformer:e=>V.mapSchema(e,{[V.MapperKind.OBJECT_FIELD]:n=>{const t=V.getDirective(e,n,Zn)?.[0];if(t){const{sMaxAge:r,staleWhileRevalidate:i,scope:a}=t,o=n.resolve;n.resolve=(s,c,d,u)=>(d.cacheControl={sMaxAge:_e(d.cacheControl?.sMaxAge,r),staleWhileRevalidate:_e(d.cacheControl?.staleWhileRevalidate,i),scope:nt(d.cacheControl?.scope,a)},o?.(s,c,d,u))}return n}})},fn=e=>(n,t)=>{const r=an.mergeTypeDefs([...(e??[]).map(({typeDefs:i})=>i),t]);return(e??[]).reduce((i,{transformer:a})=>a?.(i)??i,on.makeExecutableSchema({typeDefs:r,resolvers:n}))},Sn="@faststore/api",yn="4.6.1-dev.0",ke={name:Sn,version:yn},tt=B.logger("@faststore/api"),rt=(e,n="Unknown Graphql Resolver")=>(t,r,i,a)=>{if(!i?.OTEL_ENABLED)return e(t,r,i,a);const o=B.OTELAPI.trace.getTracer("Graphql").startSpan(n,{kind:B.OTELAPI.SpanKind.INTERNAL,attributes:{timestamp:Date.now(),"@faststore_version":yn,"@faststore_package_name":Sn,"@faststore_account_name":i.account,"@faststore_environment":process.env.NODE_ENV,"@faststore_resolver_parent_type":a?.parentType?.name,"@faststore_resolver_field_name":a?.fieldName}}),s=B.OTELAPI.trace.setSpan(B.OTELAPI.context.active(),o);try{const c=B.OTELAPI.context.with(s,()=>e(t,r,i,a));return c instanceof Promise?c.then(d=>(o.end(),d),d=>Ue(d,o,n)):(o.end(),c)}catch(c){return Ue(c,o,n)}};function Ue(e,n,t){throw n.setStatus({code:B.OTELAPI.SpanStatusCode.ERROR}),n.recordException(e),n.end(),console.error(`Error at resolver: ${t}:
2
+ %o`,e),tt("error",`Error at resolver: %s
3
+ %o`,t,e),e}class G extends Error{constructor(n,t){super(t),this.extensions=n,this.name="FastStoreError"}}class T extends G{constructor(n){super({status:400,type:"BadRequestError"},n)}}class Q extends G{constructor(n){super({status:401,type:"UnauthorizedError"},n)}}class j extends G{constructor(n){super({status:403,type:"ForbiddenError"},n)}}class N extends G{constructor(n){super({status:404,type:"NotFoundError"},n)}}const it=e=>e?.name==="FastStoreError",at=e=>e?.extensions?.type==="BadRequestError",ot=e=>e?.extensions?.type==="UnauthorizedError",In=e=>e?.extensions?.type==="ForbiddenError",x=e=>e?.extensions?.type==="NotFoundError",st=`${ke.name}@${ke.version}`,y=async(e,n,t)=>{const r=await Hn(e,{...n,headers:{...n?.headers??{},"User-Agent":st}});if(r.ok)return t?.storeCookies&&t.storeCookies(r.headers),r.status!==204?r.json():void 0;console.error(e,n,r);const i=await r.text();if(typeof r?.status=="number")switch(r.status){case 400:throw new T(i);case 401:throw new Q(i);case 403:throw new j(i);case 404:throw new N(i);default:throw new G({status:r.status,type:"UnknownError"},i)}throw new Error(i)},ct=({account:e,environment:n})=>{const t=`https://${e}.${n}.com.br`;return{getLocalizedProduct:(r,i)=>y(`${t}/api/catalog-dataplane/product/${r}`,{method:"GET",headers:{"Accept-Language":i,"Content-Type":"application/json"}})}},vn=e=>{if(!e)return e;const n=new Map,t=e.split(";"),r=[];return t.forEach(i=>{const a=i.trim();if(a){const o=a.indexOf("=");if(o>0){const s=a.substring(0,o),c=a.substring(o+1);n.has(s)||r.push(s),n.set(s,c)}}}),r.map(i=>`${i}=${n.get(i)}`).join("; ")},lt=/^([^=]+)=([^;]*)/,dt=(e,n)=>{const t=n.match(lt);if(t){const r=t[1],i=t[2];e.storage.cookies.set(r,{value:i,setCookie:n})}},ut=(e,n)=>{n.getSetCookie().forEach(t=>dt(e,t))},pt=e=>n=>ut(e,n),me=e=>{if(!e.headers?.cookie)return null;const n=vn(e.headers.cookie),t=Array.from(e.storage.cookies.entries());return t.length===0?n:t.reduce((r,[i,{value:a}])=>gt(r,i,a),n)},On=e=>function(t){const r=me(e);return r?{...t,cookie:r}:t},$=(e,n)=>{const t=vn(e);return ne.parse(t)[`VtexIdclientAutCookie_${n}`]||""},gt=(e,n,t)=>{const r=new RegExp(`(${n})=([^;]*)`),i=e.match(r);return i?e.replace(i[0],`${i[1]}=${t}`):`${e};${n}=${t}`};function z(e){if(!e)return null;try{return JSON.parse(Buffer.from(e.split(".")[1],"base64").toString())}catch{return null}}const mt="storefront/faststore.recommendation-shelf@v4",X={method:"POST",headers:{"content-type":"application/json"}},ht=e=>e.split("/").map(encodeURIComponent).join("/"),ge=e=>e?{headers:{"Accept-Language":e}}:void 0,ft=/^\d{4}-\d{2}-\d{2}$/,St=new Set(["Draft","Requested","InReview","Reviewed","Approved","Declined","Expired","ConvertedToCart","ConvertedToOrder"]);function yt({page:e,perPage:n,status:t,createdAtFrom:r,createdAtTo:i,expiresAtFrom:a,expiresAtTo:o}){if(e!==void 0&&(!Number.isInteger(e)||e<1))throw new Error(`listUserQuotes: invalid page "${e}" — must be a positive integer`);if(n!==void 0&&(!Number.isInteger(n)||n<1))throw new Error(`listUserQuotes: invalid perPage "${n}" — must be a positive integer`);for(const[s,c]of[["createdAtFrom",r],["createdAtTo",i],["expiresAtFrom",a],["expiresAtTo",o]])if(c&&!ft.test(c))throw new Error(`listUserQuotes: invalid ${s} "${c}" — must be YYYY-MM-DD`);if(t&&t.length>0){const s=t.filter(c=>!St.has(c));if(s.length>0)throw new Error(`listUserQuotes: invalid status values: ${s.join(", ")}`)}}function It({page:e,perPage:n,status:t,createdAtFrom:r,createdAtTo:i,expiresAtFrom:a,expiresAtTo:o,label:s}){const c=new URLSearchParams;return e&&c.append("pageNumber",e.toString()),n&&c.append("pageSize",n.toString()),t?.forEach(d=>c.append("status",d)),r&&c.append("createdAtFrom",r),i&&c.append("createdAtTo",i),a&&c.append("expiresAtFrom",a),o&&c.append("expiresAtTo",o),s?.trim()&&c.append("label",s.trim()),c}const vt=({account:e,environment:n,incrementAddress:t,subDomainPrefix:r},i)=>{const a=`https://${e}.${n}.com.br`,o=pt(i),s=On(i),c=Jn(),d=new Headers(i.headers).get("x-forwarded-host")??i.headers?.host??"",u=r&&r.map(l=>l+".").find(l=>d.includes(l))||"",p=d.replace(u,""),f=`${a}/api/recommend-bff/v2`,h=s({accept:"application/json","content-type":"application/json","x-vtex-rec-origin":`${e}/${mt}`}),v=(l={})=>{const g=$(me(i)??"",e);return s({...l,"X-FORWARDED-HOST":p,...g?{[`VtexIdclientAutCookie_${e}`]:g}:{}})};return{catalog:{salesChannel:l=>y(`${a}/api/catalog_system/pub/saleschannel/${l}`,void 0,{storeCookies:o}),brand:{list:()=>y(`${a}/api/catalog_system/pub/brand/list`,void 0,{storeCookies:o})},category:{tree:(l=3)=>y(`${a}/api/catalog_system/pub/category/tree/${l}`,void 0,{storeCookies:o})},portal:{pagetype:l=>y(`${a}/api/catalog_system/pub/portal/pagetype/${l}`,void 0,{storeCookies:o})},byLinkId:{category:async(l,g)=>{try{return await y(`${a}/api/catalog_system/pub/category/by-linkid/${ht(l)}`,ge(g))}catch(m){if(x(m))return null;throw m}},brand:async(l,g)=>{try{return await y(`${a}/api/catalog_system/pub/brand/by-linkid/${encodeURIComponent(l)}`,ge(g))}catch(m){if(x(m))return null;throw m}},collection:async(l,g)=>{try{return await y(`${a}/api/catalog_system/pub/collection/by-linkid/${encodeURIComponent(l)}`,ge(g))}catch(m){if(x(m))return null;throw m}}},products:{crossselling:({type:l,productId:g,groupByProduct:m=!0})=>{const S=new URLSearchParams({sc:i.storage.channel.salesChannel,groupByProduct:m.toString()});return y(`${a}/api/catalog_system/pub/products/crossselling/${l}/${g}?${S}`,void 0,{storeCookies:o})}}},checkout:{simulation:(l,{salesChannel:g}=i.storage.channel)=>{const m=new URLSearchParams({sc:g}),S=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${a}/api/checkout/pub/orderForms/simulation?${m.toString()}`,{...X,headers:S,body:JSON.stringify(l)},{storeCookies:o})},shippingData:({id:l,index:g,deliveryMode:m,selectedAddresses:S},O)=>{const w=O?{startDateUtc:m?.deliveryWindow?.startDate,endDateUtc:m?.deliveryWindow?.endDate}:null,b={logisticsInfo:Array.from({length:g},(I,D)=>({itemIndex:D,selectedDeliveryChannel:m?.deliveryChannel||null,selectedSla:m?.deliveryMethod||null,deliveryWindow:w})),selectedAddresses:S,clearAddressIfPostalCodeNotFound:t},_=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${a}/api/checkout/pub/orderForm/${l}/attachments/shippingData`,{...X,headers:_,body:JSON.stringify(b)},{storeCookies:o})},marketingData:({id:l,marketingData:g})=>{const m=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${a}/api/checkout/pub/orderForm/${l}/attachments/marketingData`,{headers:m,body:JSON.stringify(g),method:"POST"},{storeCookies:o})},clientPreferencesData:({id:l,clientPreferencesData:g})=>{const m=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${a}/api/checkout/pub/orderForm/${l}/attachments/clientPreferencesData`,{headers:m,body:JSON.stringify(g),method:"POST"},{storeCookies:o})},orderForm:({id:l,refreshOutdatedData:g=!0,channel:m=i.storage.channel,preserveSalesChannel:S=!1})=>{const{salesChannel:O}=m,w=s({"content-type":"application/json","X-FORWARDED-HOST":p}),b=new URLSearchParams;(!S||!l)&&b.set("sc",O),l&&b.set("refreshOutdatedData",g.toString());const _=l?`/${l}`:"",I=`${a}/api/checkout/pub/orderForm${_}?${b}`;return y(I,{...X,headers:w,...l?{}:{body:"{}"}},{storeCookies:o})},clearOrderFormMessages:({id:l})=>{const g=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${a}/api/checkout/pub/orderForm/${l}/messages/clear`,{...X,headers:g,body:"{}"})},updateOrderFormItems:({id:l,orderItems:g,allowOutdatedData:m="paymentData",salesChannel:S=i.storage.channel.salesChannel,shouldSplitItem:O=!0})=>{const w=new URLSearchParams({allowOutdatedData:m,sc:S}),b=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${a}/api/checkout/pub/orderForm/${l}/items?${w}`,{headers:b,body:JSON.stringify({orderItems:g,noSplitItem:!O}),method:"PATCH"},{storeCookies:o})},setCustomData:({id:l,appId:g,key:m,value:S})=>{const O=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${a}/api/checkout/pub/orderForm/${l}/customData/${g}/${m}`,{headers:O,body:JSON.stringify({value:S}),method:"PUT"})},region:async({postalCode:l,geoCoordinates:g,country:m,salesChannel:S})=>{const O=new URLSearchParams({country:m,sc:S??""});l?O.append("postalCode",l):O.append("geoCoordinates",`${g?.longitude};${g?.latitude}`);const w=`${a}/api/checkout/pub/regions/?${O.toString()}`,b=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(w,{headers:b},{storeCookies:o})},address:async({postalCode:l,country:g})=>{const m=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${a}/api/checkout/pub/postal-code/${g}/${l}`,{headers:m},{storeCookies:o})},cancelOrder:({orderId:l,customerEmail:g,reason:m})=>{const S=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${a}/api/checkout/pub/orders/${l}/user-cancel-request`,{method:"POST",headers:S,body:JSON.stringify({customerEmail:g,reason:m})},{})},pickupPoints:({geoCoordinates:l})=>{if(!l)throw new Error("Missing required parameter for listing pickup points.");const g=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${a}/api/logistics-shipping/pickuppoints/_search`,{method:"POST",headers:g,body:JSON.stringify({coordinate:l})},{storeCookies:o})}},session:l=>{const g=new URLSearchParams(l);g.set("items","profile.id,profile.email,profile.firstName,profile.lastName,profile.phone,shopper.firstName,shopper.lastName,shopper.organizationManager,shopper.availableContracts,shopper.activeContractId,store.channel,store.countryCode,store.cultureInfo,store.currencyCode,store.currencySymbol,authentication.customerId,authentication.storeUserId,authentication.storeUserEmail,authentication.unitId,authentication.unitName,checkout.regionId,public.postalCode");const m=s({"content-type":"application/json"}),S=ne.parse(i?.headers?.cookie??"")?.vtex_session;return y(`${a}/api/sessions?${g.toString()}`,{method:S?"PATCH":"POST",headers:m,body:"{}"},{storeCookies:o})},subscribeToNewsletter:l=>y(`${a}/api/dataentities/NL/documents/`,{...X,body:JSON.stringify({...l,isNewsletterOptIn:!0}),method:"PATCH"},{storeCookies:o}),profile:{addresses:async l=>{const g=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${a}/api/profile-system/pvt/profiles/${l}/addresses`,{headers:g},{storeCookies:o})}},oms:{userOrder:({orderId:l})=>{const g=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${a}/api/oms/user/orders/${l}`,{method:"GET",headers:g},{storeCookies:o})},listUserOrders:({page:l,status:g,dateInitial:m,dateFinal:S,text:O,clientEmail:w,perPage:b,pendingMyApproval:_})=>{const I=new URLSearchParams;if(m){const A=new Date(m).setHours(0,0,0,0);m=new Date(A).toISOString()}if(S){const A=new Date(S).setHours(23,59,59,999);S=new Date(A).toISOString()}O&&I.append("text",O),g&&g.length>0&&I.append("status",g.filter(Boolean).join(",")),m&&S?I.append("creation_date",`creationDate:[${m} TO ${S}]`):m?I.append("creation_date",`creationDate:[${m} TO *]`):S&&I.append("creation_date",`creationDate:[* TO ${S}]`),w&&I.append("clientEmail",w),l&&I.append("page",l.toString()),b&&I.append("per_page",b.toString()),_&&I.append("my_pending_approvals",String(!0));const D=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${a}/api/oms/user/orders?${I.toString()}`,{method:"GET",headers:D},{storeCookies:o})},getCommercialAuthorizationsByOrderId:({orderId:l})=>{const g=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${a}/${e}/commercial-authorizations/order/${l}`,{method:"GET",headers:g},{storeCookies:o})},processOrderAuthorization:async({orderAuthorizationId:l,dimensionId:g,ruleId:m,approved:S})=>{const O=s({"content-type":"application/json","X-FORWARDED-HOST":p}),_={params:{ruleId:m,dimensionId:g,score:S?100:0}};return y(`${a}/${e}/commercial-authorizations/${l}/callback`,{method:"POST",headers:O,body:JSON.stringify(_)},{storeCookies:o})}},savedCards:{listCreditCards:()=>{const l=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${a}/api/saved-cards/credit-card?an=${e}`,{method:"GET",headers:l},{storeCookies:o})}},units:{getUnitByUserId:({userId:l})=>{const g=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${a}/api/units/v1/${l}/unit`,{method:"GET",headers:g},{})},getOrgUnitById:({orgUnitId:l})=>{const g=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${a}/api/units/v1/${l}`,{method:"GET",headers:g},{})},getScopesByOrgUnit:({orgUnitId:l})=>{const g=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${a}/api/units/v1/${l}/scopes`,{method:"GET",headers:g},{})}},licenseManager:{getUserById:({userId:l})=>{const g=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${a}/api/license-manager/users/${l}`,{method:"GET",headers:g},{})},getUserByEmail:({email:l})=>{const g=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${a}/api/license-manager/pvt/users/${l}`,{method:"GET",headers:g},{})},getUserRoles:({userId:l})=>{const g=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${a}/api/license-manager/storefront/users/${l}/roles`,{method:"GET",headers:g},{})},isResourceGranted:({userId:l,resourceKey:g})=>{const m=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${a}/api/license-manager/storefront/bff/users/${l}/resources/${g}/granted?an=${e}`,{method:"GET",headers:m},{})}},masterData:{getContractById:({contractId:l})=>{if(!l)throw new T("Missing contractId to fetch CL fields.");const g=v({Accept:"application/json","content-type":"application/json"});return y(`${a}/api/dataentities/CL/documents/${l}?_fields=_all`,{method:"GET",headers:g},{})},getShopperById:({userId:l})=>{if(!l)throw new T("Missing userId to fetch shopper name.");const g=c({Accept:"application/json","content-type":"application/json","X-FORWARDED-HOST":p}),m=l.replace(/-/g,"");return y(`${a}/api/dataentities/shopper/search?_where=(userId=${m} OR userId=${l})&_fields=_all&_schema=v1`,{method:"GET",headers:g},{})}},quotes:{listUserQuotes:l=>{yt(l);const g=It(l),m=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${a}/api/quoting/quotes?${g.toString()}`,{method:"GET",headers:m},{storeCookies:o})}},vtexid:{validate:()=>{const l=s({"content-type":"application/json","X-FORWARDED-HOST":p}),g=$(me(i)??"",e);return y(`${a}/api/vtexid/credential/validate`,{headers:l,body:JSON.stringify({token:g}),method:"POST"},{storeCookies:o})}},orderEntry:{uploadFile:({fileBuffer:l,fileName:g,mimeType:m})=>{const S=s({"content-type":"application/json","X-FORWARDED-HOST":p}),O=`----FastStoreUploadBoundary${Date.now()}`,w=`\r
4
+ `,_=/^[a-zA-Z0-9][a-zA-Z0-9!#$&\-.^_]*\/[a-zA-Z0-9][a-zA-Z0-9!#$&\-.^_+]*$/.test(m)?m:"application/octet-stream",I=g.replaceAll(/[\r\n"]/g,"_"),D=[`--${O}`,`Content-Disposition: form-data; name="file"; filename="${I}"`,`Content-Type: ${_}`,"",""].join(w),A=`${w}--${O}--${w}`,E=Buffer.from(D),P=Buffer.from(A),R=new Uint8Array(E.byteLength+l.byteLength+P.byteLength);let C=0;return R.set(E,C),C+=E.byteLength,R.set(l,C),C+=l.byteLength,R.set(P,C),y(`${a}/api/order-entry/upload?an=${e}`,{method:"POST",headers:{...S,"content-type":`multipart/form-data; boundary=${O}`},body:R.buffer},{})},startOperation:({objectKey:l,orderFormId:g,sessionToken:m})=>{const S=s({"content-type":"application/json","X-FORWARDED-HOST":p}),O=JSON.stringify({objectKey:l,orderFormId:g,operation:"CreateCart",...m?{sessionToken:m}:{}});return y(`${a}/api/order-entry/operation?an=${e}`,{method:"POST",headers:S,body:O},{})},getOperation:({operationId:l})=>{const g=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${a}/api/order-entry/operation/${l}?an=${e}`,{method:"GET",headers:g},{})},createOrderForm:()=>{const l=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${a}/api/checkout/pub/orderForm?sc=${i.storage.channel.salesChannel}`,{method:"POST",headers:l,body:"{}"},{})},getOrderFormItems:({orderFormId:l})=>{const g=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${a}/api/checkout/pub/orderForm/${l}`,{method:"GET",headers:g},{})}},recommendation:{recommendations:({campaignVrn:l,userId:g,products:m=[],salesChannel:S,locale:O})=>{const w=new URLSearchParams({an:e,campaignVrn:l});return g&&w.append("userId",g),m.length>0&&w.append("products",m.join(",")),S&&w.append("salesChannel",S),O&&w.append("locale",O),y(`${f}/recommendations?${w.toString()}`,{headers:h},{storeCookies:o})},startRecommendationSession:()=>{const l=new URLSearchParams({an:e});return y(`${f}/users/start-session?${l.toString()}`,{method:"POST",headers:h},{storeCookies:o})}}}},Z=e=>e.discoveryConfig?.localization??{},ee=e=>Z(e).enabled===!0,Ot=e=>Object.keys(Z(e).locales??{}),Ct=e=>Z(e).defaultLocale,ae=e=>ee(e)&&e.storage.locale||void 0,he="fuzzy",fe="operator",Se="pickupPoint",Re="shipping",Fe="delivery-options",bt="in-stock",wt="trade-policy",Dt="region-id",At=new Set([wt,Dt,he,fe,Se]),Pt=new Set(["zip-code","pickupPoint","country","coordinates","deliveryZonesHash","pickupPointsHash"]),Ne=e=>encodeURI(decodeURI(e)),Et=e=>encodeURIComponent(decodeURIComponent(e).normalize("NFD").replaceAll(/[\u0300-\u036f]/g,"")),Tt=/^pickup-in-point-(.+)$/;function Cn(e){if(!e)return{};try{const t=ne.parse(e).vtex_segment;if(!t)return{};const r=Buffer.from(t,"base64").toString("utf-8");return JSON.parse(r)}catch{return{}}}function _t(e){const n={},t=[];for(const r of e.split(";")){const i=r.indexOf("=");if(i<0)continue;const a=r.slice(0,i),o=r.slice(i+1);!a||!o||(Pt.has(a)?n[a]=o:t.push({key:a,value:o}))}return{shipping:n,extraFacets:t}}function kt(e){const n=typeof e.facets=="string"?e.facets:"",{shipping:t,extraFacets:r}=_t(n);return{segmentParams:{sc:e.channel,regionId:e.regionId,country:e.countryCode??t.country,locale:e.cultureInfo,"zip-code":t["zip-code"],coordinates:t.coordinates,pickupPoint:t.pickupPoint,deliveryZonesHash:t.deliveryZonesHash,pickupPointHash:t.pickupPointsHash,utmSource:e.utm_source??void 0,utmCampaign:e.utm_campaign??void 0,utmiCampaign:e.utmi_campaign??void 0,campaigns:typeof e.campaigns=="string"?e.campaigns:void 0,priceTables:e.priceTables??void 0},extraFacets:r}}function bn(e,n){const t=[["sc",n.sc],["regionId",n.regionId],["country",n.country],["locale",n.locale],["zip-code",n["zip-code"]],["coordinates",n.coordinates],["pickupPoint",n.pickupPoint],["deliveryZonesHash",n.deliveryZonesHash],["pickupPointHash",n.pickupPointHash],["utmSource",n.utmSource],["utmCampaign",n.utmCampaign],["utmiCampaign",n.utmiCampaign],["campaigns",n.campaigns],["priceTables",n.priceTables]];for(const[r,i]of t)i!=null&&i!==""&&e.append(r,String(i))}function wn(e){return Tt.exec(e)?.[1]}function Ut(e){const n=e.find(r=>r.key==="shipping"),t=n?wn(n.value):void 0;if(t!==void 0)try{return decodeURIComponent(t)}catch{return t}}function Rt(e,n){const t=Ut(n);return t===void 0?e:{...e,pickupPoint:t}}function Ft(e){return e.map(n=>n.key!=="shipping"||wn(n.value)===void 0?n:{...n,value:"pickup-in-point"})}function Nt(e,n){let t=[...e];const r=t.some(i=>i.key==="shipping");for(const i of n)(!r||i.key!=="shipping")&&t.push(i);return t.some(i=>i.key==="shipping"&&i.value==="ignore")&&(t=t.filter(i=>i.key!=="shipping")),Ft(t)}function Lt(e){return e.reduce((n,t)=>{let{key:r,value:i}=t;return r==="priceRange"&&(r="price",i=i.replace(" TO ",":")),r==="ft"?n:`${n}${Ne(r)}/${Et(Ne(i)).replaceAll(/ |%20/g,"-")}/`},"")}const Bt=e=>e.key==="fuzzy"&&(e.value==="0"||e.value==="1"||e.value==="auto"),$t=e=>e.key==="operator"&&(e.value==="and"||e.value==="or");function Mt(e,n){const{segmentParams:t,extraFacets:r}=kt(e??{}),i=n?.salesChannel??t.sc,a=n?.regionId??t.regionId,o=n?.locale??t.locale??"";return{segmentParams:{...t,...i?{sc:i}:{},...a?{regionId:a}:{},locale:o},extraFacets:r}}function zt(e,n){const t=e.filter(({key:c})=>!At.has(c)),r=e.find(({key:c,value:d})=>c===Re&&d!=="all-delivery-methods")??null,i=e.find(({key:c,value:d})=>c===Fe&&d!=="all-delivery-options")??null,a=[...t],o=a.some(({key:c})=>c===Re),s=a.some(({key:c})=>c===Fe);return r!==null&&!o&&a.push(r),i!==null&&!s&&a.push(i),Nt(a,n)}function qt(e,n){const t=e.find(({key:a})=>a===he)??null,r=e.find(({key:a})=>a===fe)??null,i=e.find(({key:a})=>a===Se)??null;t&&Bt(t)&&n.append(he,t.value),r&&$t(r)&&n.append(fe,r.value),i&&n.append(Se,i.value)}function Le(e,n,t,r){const{query:i="",page:a,count:o,sort:s,selectedFacets:c=[],showInvisibleItems:d,sponsoredCount:u,hideUnavailableItems:p,allowRedirect:f=!1}=e,h=new URLSearchParams;if(r.includePagination&&a!==void 0&&o!==void 0){const g=a*o,m=o===0?g:g+o-1;h.append("from",g.toString()),h.append("to",m.toString())}i&&h.append("query",i),r.includeSort&&s&&h.append("sort",s);const v=Rt(t.segmentParams,c);if(bn(h,v??t.segmentParams),qt(c,h),d&&h.append("show-invisible-items","true"),n?.hideUnavailableItems!==void 0){const g=c.find(({key:S})=>S===bt),m=g?g.value:p?.toString()??n.hideUnavailableItems.toString();h.append("hideUnavailableItems",m)}n?.simulationBehavior!==void 0&&h.append("simulationBehavior",n.simulationBehavior.toString()),n?.showSponsored!==void 0&&h.append("showSponsored",n.showSponsored.toString()),u!==void 0&&h.append("sponsoredCount",u.toString()),f!==void 0&&h.append("allowRedirect",f.toString());const l=Lt(zt(c,t.extraFacets));return{params:h,path:l}}function Vt(e,n){const{field:t,value:r,hideUnavailableItems:i,showInvisibleItems:a}=e,o=new URLSearchParams({field:t??"",value:r??""});return bn(o,n),i&&o.append("hideUnavailableItems","true"),a&&o.append("show-invisible-items","true"),o}function Y(e,n){return{path:e,params:n,toString(){const t=n.toString();return e?t?`${e}?${t}`:e:t?`?${t}`:""}}}function J(e){const{endpoint:n,segment:t,defaults:r,args:i={}}=e,a=Mt(t,r);switch(n){case"product-search":case"facets":{const{params:o,path:s}=Le(i,r,a,{includePagination:!0,includeSort:!0});return Y(s,o)}case"catalog-count":{const{params:o,path:s}=Le(i,r,a,{includePagination:!1,includeSort:!1});return Y(s,o)}case"products":{const o=Vt(i,a.segmentParams);return Y("",o)}case"search-suggestions":{const o=new URLSearchParams({query:i.query?.toString()??"",locale:r?.locale??a.segmentParams.locale??""});return Y("",o)}case"top-searches":{const o=new URLSearchParams({locale:r?.locale??a.segmentParams.locale??""});return Y("",o)}default:{const o=n;throw new Error(`Unknown intelligent-search endpoint: ${o}`)}}}const xt=10;function jt(e){const{regionId:n,seller:t}=e.storage.channel;return(t?Buffer.from(`SW#${t}`).toString("base64"):void 0)??(n||void 0)}function Wt(e){const t=Cn(e.headers?.cookie).cultureInfo||"";return ee(e)?e.storage.locale||t:t||e.storage.locale||""}const Gt=({account:e,environment:n,hideUnavailableItems:t,simulationBehavior:r,showSponsored:i,subDomainPrefix:a},o)=>{const s=`https://${e}.${n}.com.br`,c=On(o),d=Cn(o.headers?.cookie),u=()=>({salesChannel:o.storage.channel.salesChannel,regionId:jt(o),locale:Wt(o),hideUnavailableItems:t,simulationBehavior:r,showSponsored:i}),p=new Headers(o.headers).get("x-forwarded-host")??o.headers?.host??"",f=a&&a.map(I=>I+".").find(I=>p.includes(I))||"",h=p.replace(f,""),v=c({"content-type":"application/json","X-FORWARDED-HOST":h}),l=({type:I,...D})=>{const A=I==="facets"?"facets":"product-search",E=J({endpoint:A,segment:d,defaults:u(),args:D});return y(`${s}/api/intelligent-search/v1/${A}/${E.path}?${E.params.toString()}`,{headers:v})},g=I=>l({...I,type:"product_search"}),m=({field:I,value:D,hideUnavailableItems:A,showInvisibleItems:E})=>{const P=J({endpoint:"products",segment:d,defaults:u(),args:{field:I,value:D,hideUnavailableItems:A,showInvisibleItems:E}});return y(`${s}/api/intelligent-search/v1/products?${P.params.toString()}`,{headers:v})};return{facets:I=>l({...I,type:"facets"}),products:g,fetchProduct:m,productsByIdentifier:async({field:I,values:D,showInvisibleItems:A,hideUnavailableItems:E})=>{const P=Ae(xt);return(await Promise.all(D.map(C=>P(async()=>{try{return await m({field:I,value:C,hideUnavailableItems:E,showInvisibleItems:A})}catch{return null}})))).filter(C=>C!==null)},suggestedTerms:I=>{const D=J({endpoint:"search-suggestions",segment:d,defaults:u(),args:{query:I.query}});return y(`${s}/api/intelligent-search/v1/search-suggestions?${D.params.toString()}`,{headers:v})},topSearches:()=>{const I=J({endpoint:"top-searches",segment:d,defaults:u()});return y(`${s}/api/intelligent-search/v1/top-searches?${I.params.toString()}`,{headers:v})},productCount:I=>{const D=J({endpoint:"catalog-count",segment:d,defaults:u(),args:I});return y(`${s}/api/intelligent-search/v1/catalog-count/${D.path}?${D.params.toString()}`,{headers:v})}}},Ht=(e,n)=>{const t=Gt(e,n),r=vt(e,n),i=ct(e);return{search:t,commerce:r,catalog:i}},Xt=20,Yt=e=>e.entityType==="category",ye=e=>e.entityType==="brand",Be=e=>e.entityType==="collection",Jt=(e,n)=>{const t=Ae(Xt),r=async i=>Promise.all(i.map(a=>t(async()=>{const o=a.slug.toLowerCase(),s=a.locale,c=await n.commerce.catalog.byLinkId.category(o,s);if(c)return{...c,entityType:"category",slug:o};const d=await n.commerce.catalog.byLinkId.brand(o,s);if(d)return{...d,entityType:"brand"};const u=await n.commerce.catalog.byLinkId.collection(o,s);if(u)return{...u,entityType:"collection"};throw new N(`No catalog entity found for slug: ${a.slug}. Cascade exhausted (category → brand → collection).`)})));return new pe(r,{batch:!1,cacheKeyFn:({slug:i,locale:a})=>`${i.toLowerCase()}::${a??""}`})},Kt=(e,n)=>{const t=async r=>Promise.all(r.map(i=>n.commerce.catalog.salesChannel(i)));return new pe(t)},Qt=1,Zt=(e,n)=>{const t=Ae(Qt),r=async a=>{const o=a.reduce((p,{items:f})=>[...p,f],[]),s=[...o.flat()],c=await n.commerce.checkout.simulation({country:a[0].country,postalCode:a[0].postalCode,items:s}),d=c.items.reduce((p,f)=>{const h=f.requestIndex;return typeof h=="number"&&h<p.length&&(p[h]=f),p},Array(s.length).fill(null)),u=o.reduce((p,f)=>[...p,f.length+p[p.length-1]],[0]);return o.map((p,f)=>({...c,items:d.slice(u[f],u[f+1]).filter(h=>!!h)}))},i=async a=>t(r,a);return new pe(i,{maxBatchSize:50})},er=(e,n)=>Xn(e,n);function nr(e){return{...e,description:e.description?er(e.description):e.description}}const F=(e,n)=>({...e,isVariantOf:nr(n)}),tr=({flags:e},n)=>{const t=async r=>{const i=r.map(u=>u.split("-")[0]),a=r.some(u=>u.split("-")[1]==="invisibleItems"),s=(await n.search.productsByIdentifier({field:"sku",values:i,showInvisibleItems:a,...e?.enableUnavailableItemsOnCart&&{hideUnavailableItems:!1}})).reduce((u,p)=>{for(const f of p.items)u[f.itemId]=F(f,p);return u},{}),c=i.map(u=>s[u]),d=i.filter(u=>!s[u]);if(d.length>0)throw new N(`Search API did not found the following skus: ${d.join(",")}`);return c};return new pe(t,{maxBatchSize:99})},rr=(e,n)=>{const{clients:t}=n,r=tr(e,t),i=Zt(e,t),a=Jt(e,t),o=Kt(e,t);return{skuLoader:r,simulationLoader:i,collectionLoader:a,salesChannelLoader:o}},M=e=>e.AvailableQuantity>0,W=e=>e.spotPrice??0,ir=e=>e.Price??0,$e=e=>e?"https://schema.org/InStock":"https://schema.org/OutOfStock",Dn=(e,n)=>M(e)&&!M(n)?-1:!M(e)&&M(n)?1:W(e)-W(n),ar=e=>e==="available",q=(e,n=0,t=1)=>{const r=n/t;return Math.round((e+r)*100)/100},or=(e,n={includeTaxes:!1})=>{const t=e.filter(M),r=t[t.length-1],i=r?W(r):0;return n.includeTaxes?q(i,r?.Tax,r?.product?.unitMultiplier):i},Me=(e,n={includeTaxes:!1})=>{const[t]=e.filter(M),r=t?W(t):0;return n.includeTaxes?q(r,t?.Tax,t?.product?.unitMultiplier):r},sr={highPrice:e=>or(e),lowPrice:e=>Me(e),lowPriceWithTaxes:e=>Me(e,{includeTaxes:!0}),offerCount:e=>e.length,priceCurrency:async(e,n,t)=>{const{loaders:{salesChannelLoader:r},storage:{channel:i}}=t;return(await r.load(i.salesChannel)).CurrencyCode??""},offers:e=>e},cr={ratingValue:()=>5,reviewCount:()=>0},ze="ÁÄÂÀÃÅČÇĆĎÉĚËÈÊẼĔȆÍÌÎÏŇÑÓÖÒÔÕØŘŔŠŤÚŮÜÙÛÝŸŽáäâàãåčçćďéěëèêẽĕȇíìîïňñóöòôõøðřŕšťúůüùûýÿžþÞĐđ߯a",lr="AAAAAACCCDEEEEEEEEIIIINNOOOOOORRSTUUUUUYYZaaaaaacccdeeeeeeeeiiiinnooooooorrstuuuuuyyzbBDdBAa",dr=e=>{let n=e.slice(0);for(let t=0;t<ze.length;t++)n=n.replace(new RegExp(ze.charAt(t),"g"),lr.charAt(t));return n},ur=e=>e.replace(/[·/_,:]/,"-");function ce(e){const t=e.replace(/,/g,"").replace(/[*+~.()'"!:@&\[\]`/ %$#?{}><=_^]/g,"-");return ur(dr(t)).toLowerCase()}const K=e=>Yt(e)?e.slug:ye(e)?e.linkId:e.linkId??ce(e.name),An={id:({id:e})=>e.toString(),slug:e=>K(e),seo:e=>({title:e.title??e.name,description:e.metaTagDescription??e.description}),type:e=>ye(e)?"Brand":Be(e)?"Collection":e.fatherCategoryId===null?"Department":"Category",meta:async(e,n,t)=>{const r=K(e);if(ye(e))return{selectedFacets:[{key:"brand",value:r}]};if(Be(e))return{selectedFacets:[{key:"productclusterids",value:e.id}]};const{defaultLocale:i}=Z(t),a=r.split("/").filter(Boolean),o=a.map((d,u)=>a.slice(0,u+1).join("/")),{loaders:{collectionLoader:s}}=t;return{selectedFacets:(await Promise.all(o.map(d=>s.load({slug:d,locale:ae(t)})))).map((d,u)=>({key:`category-${u+1}`,value:i&&d.availableLinkIds?.[i]||d.linkId}))}},breadcrumbList:async(e,n,t)=>{const{loaders:{collectionLoader:r}}=t,a=K(e).split("/").filter(Boolean),o=a.map((c,d)=>a.slice(0,d+1).join("/")),s=await Promise.all(o.map(c=>r.load({slug:c,locale:ae(t)})));return{itemListElement:s.map((c,d)=>({item:`/${K(c)}`,name:c.name,position:d+1})),numberOfItems:s.length}},otherLocales:async(e,n,t)=>{const r=Z(t);if(!r.enabled)return null;const i=Object.keys(r.locales??{});if(i.length===0)return null;const a=t.storage.locale,o=K(e),s=o.split("/").filter(Boolean);if(s.length===0)return null;const{loaders:{collectionLoader:c}}=t,d=s.map((p,f)=>s.slice(0,f+1).join("/"));let u;try{u=await Promise.all(d.map(p=>c.load({slug:p,locale:ae(t)})))}catch(p){return console.warn("[otherLocales] failed to load collection entities:",p),null}return i.map(p=>{if(p===a)return{locale:p,slug:o};const f=[];for(const h of u){const v=h.availableLinkIds?.[p];if(!v)return null;f.push(v)}return f.length>0?{locale:p,slug:f.join("/")}:null}).filter(p=>p!==null)}},Pn={buy:"whoboughtalsobought",view:"whosawalsosaw",similars:"similars",viewAndBought:"whosawalsobought",accessories:"accessories",suggestions:"suggestions"},qe=({key:e,value:n})=>{switch(e){case"price":return{key:e,value:n.replace("-to-",":")};case"channel":case"locale":case"buy":case"view":case"similars":case"viewAndBought":case"accessories":case"suggestions":return[];default:return{key:e,value:n}}},Ve=e=>{const n=e.split(":").map(Number);return n.length!==2||Number.isNaN(n[0])||Number.isNaN(n[1])?null:n},pr=e=>typeof Pn[e]=="string",gr=e=>{const n=e?.filter(t=>pr(t.key));if(Array.isArray(n)&&n.length>1)throw new T(`You passed ${n.length} cross selling facets but only one is allowed. Please leave one of the following facet: ${n.map(t=>t.key).join(",")}`);return n?.[0]??null},mr=e=>e?.find(n=>n.key==="slug")?.value??null,hr=e=>e?.find(n=>n.key==="id")?.value??null,xe=e=>e?.find(n=>n.key==="locale")?.value??null,je=e=>e?.find(n=>n.key==="channel")?.value??null,Ie=(e,n)=>{let t=0;for(let r=1;r<e.length;r++)n(e[t],e[r])>0&&(t=r);return e[t]},fr={__resolveType:({type:e,values:n})=>e!=="TEXT"&&e!=="DELIVERY"?"StoreFacetRange":!n||n.length===0?"StoreFacetBoolean":n.every(t=>t.range)?"StoreFacetRange":"StoreFacetBoolean"},Sr={key:({key:e})=>e,label:({name:e})=>e,values:({values:e})=>e.sort((n,t)=>n.name.localeCompare(t.name))},yr={key:({key:e})=>e,label:({name:e})=>e,min:({values:e,key:n},t,{storage:{searchArgs:r}})=>{const i=Ve(r?.selectedFacets?.find(s=>s.key===n)?.value??""),o=Ie(e,(s,c)=>s.range.from-c.range.from)?.range?.from??0;return{selected:i?.[0]??o,absolute:o}},max:({values:e,key:n},t,{storage:{searchArgs:r}})=>{const i=Ve(r?.selectedFacets?.find(s=>s.key===n)?.value??""),o=Ie(e,(s,c)=>c.range.to-s.range.to)?.range?.to??0;return{selected:i?.[1]??o,absolute:o}}},Ir={value:({value:e})=>e,label:({name:e})=>e||"unknown",selected:({selected:e})=>e,quantity:({quantity:e})=>e},vr=async(e,{data:n},{clients:{commerce:t}})=>{if(!n?.orderId)throw new T("Missing orderId");return{data:(await t.checkout.cancelOrder(n))?.data}};function En(e){if(!e||e.status!=="pending")return null;for(const n of e.dimensionStatus){if(n.status!=="pending")continue;const t=n.ruleCollection.find(r=>r.status==="pending"&&r.isUserNextAuthorizer);if(t)return{rule:t,orderAuthorizationId:e.id,dimensionId:n.id}}return null}function Or(e){if(!e||e.status!=="pending")return!1;const n=e.dimensionStatus.filter(t=>t.status==="pending").flatMap(t=>t.ruleCollection).filter(t=>t.status==="pending");return n.length===0?!1:n.every(t=>!t.isUserNextAuthorizer)}const Cr=async(e,{data:n},{clients:{commerce:t}})=>{const r=await t.oms.processOrderAuthorization(n),i=En(r);return{isPendingForOtherAuthorizer:!i&&Or(r),ruleForAuthorization:i}},br=async(e,{data:n},{clients:{commerce:t}})=>{if(!n?.objectKey)throw new T("Missing objectKey");const r=n.orderFormId||(await t.orderEntry.createOrderForm()).orderFormId;return t.orderEntry.startOperation({objectKey:n.objectKey,orderFormId:r,sessionToken:n.sessionToken??void 0})},wr=async(e,n,t)=>{if(!(await t.clients.commerce.recommendation.startRecommendationSession())?.recommendationsUserId)throw new Error("Failed to start recommendation session: no session data returned");return!0},Dr=async(e,{data:n},{clients:{commerce:t}})=>({id:(await t.subscribeToNewsletter(n))?.Id}),Ar=async(e,{data:n},{clients:{commerce:t}})=>{const{fileContent:r,fileName:i,mimeType:a}=n;if(!r||!i||!a)throw new T("Missing required fields: fileContent, fileName, mimeType");const o=r.replaceAll(/\s/g,""),s=5*1024*1024;if(Math.floor(o.length*3/4)>s)throw new T("File exceeds maximum allowed size of 5MB");if(!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(o))throw new T("Invalid Base64 fileContent");const u=Buffer.from(o,"base64");return await t.orderEntry.uploadFile({fileBuffer:u,fileName:i,mimeType:a})};class te{static parse(n){try{const t=JSON.parse(n);return{seller:t.seller??"",regionId:t.regionId??"",salesChannel:t.salesChannel??"",hasOnlyDefaultSalesChannel:t.hasOnlyDefaultSalesChannel??!0}}catch(t){throw console.error(t),new Error("Malformed channel string")}}static stringify(n){return JSON.stringify(n)}}function Pr(e,n){return n==null||n===""||String(n)===String(e.salesChannel??"")?null:te.stringify({...e,salesChannel:String(n),hasOnlyDefaultSalesChannel:!1})}const le=(e,n)=>{e.storage.channel=te.parse(n)},ve=(e,n)=>{e.storage.locale=n},Tn=e=>Yn.createHash("md5").update(e).digest("hex"),re={attachment:"ATTACHMENT",specification:"SPECIFICATION",attribute:"ATTRIBUTE"};function _n(e){return{name:e.name,value:e.content,valueReference:re.attachment}}function Er(e){return{propertyID:e.id,name:e.name,value:e.value,valueReference:{valueReference:re.attribute,visible:e.visible}}}function kn(e){return Tn(`${e.name}:${JSON.stringify(e.value)}:${e.valueReference}`)}const Tr=e=>{const n=e.postalCode,t=e.geoCoordinates,r={addressType:e.addressType||null,postalCode:n||null,city:null,state:null,country:e.country||null,street:null,number:null,neighborhood:null,complement:null,reference:null,geoCoordinates:[]};if(t){const i=typeof t=="object"&&"latitude"in t?t.latitude:null,a=typeof t=="object"&&"longitude"in t?t.longitude:null;r.geoCoordinates=i!==null&&a!==null?[a,i]:[]}return[r]},_r=(e,n,t)=>{const r=n.postalCode,i=n.geoCoordinates,a=e?.shippingData?.availableAddresses??[],o=e?.shippingData?.selectedAddresses??[];if(!t&&o.length>0)return[o[0]];if(t&&a.length>0)for(const s of a){if(r&&i&&(s.postalCode===r||s.geoCoordinates[0]===i.longitude&&s.geoCoordinates[1]===i.latitude))return[s];if(r&&!i&&s.postalCode===r)return[s];if(i&&!r&&s.geoCoordinates[0]===i.longitude&&s.geoCoordinates[1]===i.latitude)return[s]}return null},Un=(e,n)=>{if(!kr(n))return{updateShipping:!1,addressChanged:!1};if(!Nr(e))return{updateShipping:!1,addressChanged:!1};const[t]=e?.shippingData?.selectedAddresses??[];if(Ur(t,n.postalCode)||Rr(t,n.geoCoordinates)||Fr(t,n.addressType))return{updateShipping:!0,addressChanged:!0};const{logisticsInfo:r}=e.shippingData;return Lr(r,n)?{updateShipping:!0,addressChanged:!1}:{updateShipping:!1,addressChanged:!1}},kr=e=>!!e.postalCode||e.geoCoordinates?.latitude&&e.geoCoordinates?.longitude,Ur=(e,n)=>typeof n=="string"&&e?.postalCode!==n,Rr=(e,n)=>typeof n?.latitude=="number"&&typeof n?.longitude=="number"&&(e?.geoCoordinates[0]!==n?.longitude||e?.geoCoordinates[1]!==n?.latitude),Fr=(e,n)=>typeof n=="string"&&e?.addressType!==n,Nr=e=>e.items.length!==0,Lr=(e,n)=>{const t=n?.deliveryMode?.deliveryChannel,r=n?.deliveryMode?.deliveryMethod,{startDate:i,endDate:a}=n?.deliveryMode?.deliveryWindow||{};return e.some(({selectedDeliveryChannel:o,selectedSla:s,slas:c})=>{const d=t&&o!==t,u=r&&s!==r;return c?.some(p=>d&&p.deliveryChannel===t||u&&p.id===r?!0:i&&a&&p.deliveryChannel===t&&p.id===r&&(!p?.deliveryWindow||p?.deliveryWindow?.startDateUtc!==i||p?.deliveryWindow?.endDateUtc!==a)&&p.availableDeliveryWindows?.some(f=>f?.startDateUtc===i&&f?.endDateUtc===a))})},Rn=e=>e.valueReference===re.attachment,Oe=e=>[e.itemOffered.sku,e.seller.identifier,e.price<.01?"Gift":void 0,e.itemOffered.additionalProperty?.filter(Rn).map(kn).join("-")].filter(Boolean).join("::"),de=(e,n)=>({listPrice:e.listPrice/100,price:e.sellingPrice/100,quantity:e.quantity,seller:{identifier:e.seller},itemOffered:{sku:e.id,image:[],name:e.name,additionalProperty:e.attachments.map(_n)},index:n}),Br=e=>({quantity:e.quantity,seller:e.seller.identifier,id:e.itemOffered.sku,index:e.index,attachments:(e.itemOffered.additionalProperty?.filter(Rn)??[]).map(n=>({name:n.name,content:n.value})),...e.priceToken?{priceToken:e.priceToken}:{}}),We=e=>e.reduce((n,t)=>{const r=Oe(t);return n.has(r)||n.set(r,[]),n.get(r)?.push(t),n},new Map),$r=(e,n)=>{const t=({priceToken:s,...c},d)=>({...c,itemOffered:{sku:c.itemOffered.sku},index:d}),r=n.items.map(de).map(t),i=e.acceptedOffer.map(t),a=e.orderNumber===n.orderFormId,o=Pe(r,i);return a&&o};function Fn(e,n){return e?.some(t=>t.parentItemIndex!==null&&t.parentItemIndex!==void 0&&e[t.parentItemIndex]?.id===n)}function Nn(e,n){return e?.some(t=>t.id===n&&t.parentItemIndex!==null)}const Ge=e=>{const n=e.items.reduce((t,r,i)=>{const a=Nn(e.items,r.id)||Fn(e.items,r.id)?`${Oe(de(r))}::${i}`:Oe(de(r));return t[a]||(t[a]=[]),t[a].push(r),t},{});return{...e,items:Object.values(n).map(t=>{const[r]=t,i=t.reduce((o,s)=>o+s.quantity,0),a=t.reduce((o,s)=>o+(s?.priceDefinition?.total??(s?.quantity??0)*(s?.sellingPrice??0)),0);return{...r,quantity:i,sellingPrice:a/i}})}},Ce=async(e,n,t,r)=>({order:{orderNumber:e.orderFormId,acceptedOffer:e.items.map(async i=>({...i,product:await n.load(`${i.id}-invisibleItems`)})),shouldSplitItem:t,...r?{salesChannel:r}:{}},messages:e.messages.map(({text:i,status:a})=>({text:i,status:a.toUpperCase()}))}),Ln=({items:e},n)=>{const t=e.map(r=>({id:r.id,quantity:r.quantity,seller:r.seller,attachments:r.attachments}));return Tn(JSON.stringify({sessionId:n?.id??"",items:t}))},He=async(e,n,t)=>{try{return await n.checkout.setCustomData({id:e.orderFormId,appId:"faststore",key:"cartEtag",value:Ln(e,t)})}catch(r){throw console.error(`Error while setting custom data to orderForm.
5
5
  Make sure to add the following custom app to the orderForm:
6
6
  {"fields":["cartEtag"],"id":"faststore","major":1}.
7
- More info at: https://developers.vtex.com/vtex-rest-api/docs/customizable-fields-with-checkout-api`),r}},$r=(e,n)=>{const r=e.customData?.customApps.find(o=>o.id==="faststore")?.fields?.cartEtag;return r==null?!0:Nn(e,n)!==r},Mr=async(e,{clients:{commerce:n}})=>n.checkout.clearOrderFormMessages({id:e}),Xe=async(e,n,{clients:{commerce:t}})=>{if(!n)return e;const{updateShipping:r,addressChanged:i}=kn(e,n);if(r){const o=Tr(e,n,i),s=o||Er(n);return!!n.deliveryMode?.deliveryWindow&&await t.checkout.shippingData({id:e.orderFormId,index:e.items.length,deliveryMode:n.deliveryMode,selectedAddresses:s},!1),t.checkout.shippingData({id:e.orderFormId,index:e.items.length,deliveryMode:n.deliveryMode,selectedAddresses:s},!0)}return e},zr=(e,n)=>{if(!e)return"";const r=ne.parse(e)[n];return r?r.split("=")[1]:""},Ye=(e,n)=>{const t=Pr(e.storage.channel,n.salesChannel);return t?(le(e,t),n.salesChannel?String(n.salesChannel):null):null},Je=(e,n,t,r)=>r?Ce(e,n,t,r):null,qr=async(e,{cart:{order:n},session:t},r)=>{const i=zr(r.headers.cookie,"checkout.vtex.com"),{clients:{commerce:o},loaders:{skuLoader:a}}=r,s=t?.channel,c=t?.locale;s&&le(r,s),c&&ve(r,c);const d=i||void 0,u=await o.checkout.orderForm({id:d,channel:r.storage.channel,preserveSalesChannel:!!d}),p=u.orderFormId;u.messages.length!==0&&await Mr(p,r);const f=ne.parse(r?.headers?.cookie??"")?.vtex_session,h=Q(f),{acceptedOffer:v,shouldSplitItem:l}=n;if($r(u,h)){const C=Ye(r,u),L=await He(u,o,h).then(Ge);if(p)return Ce(L,a,l,C)}const m=Ye(r,u),S=We(v),O=We(u.items.map(de)),w=Array.from(O.entries()),b=Array.from(S.entries()),{itemsToAdd:U,itemsToUpdate:I}=b.reduce((C,[L,Ee])=>{const Te=O.get(L);if(!Te)return Ee.forEach(G=>C.itemsToAdd.push(G)),C;const[ie,...xn]=Te;if(Fn(u.items,ie.itemOffered.sku)||Rn(u.items,ie.itemOffered.sku))return C.itemsToUpdate.push(ie),C;const jn=Ee.reduce((G,Wn)=>G+Wn.quantity,0);return C.itemsToUpdate.push({...ie,quantity:jn}),xn.forEach(G=>C.itemsToUpdate.push({...G,quantity:0})),C},{itemsToAdd:[],itemsToUpdate:[]}),D=w.filter(([C])=>!S.has(C)).flatMap(([,C])=>C.map(L=>({...L,quantity:0}))),P=[...U,...I,...D].map(Lr),{updateShipping:E}=t?kn(u,t):{updateShipping:!1};if(P.length===0&&!E)return Je(u,a,l,m);let A;P.length>0?A=await o.checkout.updateOrderFormItems({id:u.orderFormId,orderItems:P,shouldSplitItem:l}).then(C=>Xe(C,t,r)):A=await Xe(u,t,r),A=await Promise.resolve(A).then(C=>{if(t?.marketingData){const L={...C.marketingData,...t.marketingData};return o.checkout.marketingData({id:u.orderFormId,marketingData:L})}return C}).then(C=>c&&C.clientPreferencesData?.locale!==c?o.checkout.clientPreferencesData({id:C.orderFormId,clientPreferencesData:{...C.clientPreferencesData,locale:c}}):C).then(C=>He(C,o,h)).then(Ge);const R=Ae(u.messages,A.messages);return Br(n,A)&&R?Je(A,a,l,m):Ce(A,a,l,m)};function Vr(e,n,t,r){const i=e.hasOnlyDefaultSalesChannel===!1,o=n??void 0,a=t??e.regionId;return te.stringify({salesChannel:i?e.salesChannel||o:o??e.salesChannel,regionId:a??void 0,seller:r,hasOnlyDefaultSalesChannel:i?!1:!o})}const xr=e=>{const n=(e?.corporateName??"").trim();return n||(e?.firstName??"").trim()},jr=e=>{if(!e||typeof e!="object")return!1;const n=e;return typeof n.customerId=="string"&&n.customerId.trim()!==""&&typeof n.contractName=="string"&&typeof n.isActive=="boolean"&&typeof n.isCurrent=="boolean"},Wr=e=>{const n=e?.availableContracts?.value;return Array.isArray(n)?n.filter(jr):[]},Gr=e=>e?.customerId?!!((e.contractName??"").trim()&&e.isActive):!1,Ke=e=>e?.namespaces?.shopper?.activeContractId?.value?.trim()??e?.namespaces?.authentication?.customerId?.value?.trim()??e?.namespaces?.profile?.id?.value?.trim()??"",Hr=(e,n="")=>{const t=n.trim();return e.filter(Gr).map(r=>({id:r.customerId,corporateName:r.contractName.trim(),isActive:t?r.customerId===t:r.isCurrent}))},Ln=(e,n)=>{const t=xr(e);return t||(n?.firstName?.value??"").trim()};async function Xr(e,n,t){try{const r=await e.commerce.checkout.address({postalCode:t,country:n}),i=r.geoCoordinates?{latitude:r.geoCoordinates[1],longitude:r.geoCoordinates[0]}:null;return{city:r.city,geoCoordinates:i}}catch(r){throw console.error(`Error while getting geo coordinates for the current postal code (${t}) and country (${n}).
8
- `),r}}function Yr(e,n,t,r,i,o){const a=new URLSearchParams(e);return a.has("facets")&&a.delete("facets"),a.set("sc",a.get("sc")??n.salesChannel),t&&a.set("postalCode",t),r&&a.set("country",r),i&&a.set("geoCoordinates",`${i.longitude},${i.latitude}`),a.set("locale",o),a}function Jr(e,n){return{utmCampaign:e.get("utm_campaign")??n?.utmCampaign??"",utmMedium:e.get("utm_medium")??n?.utmMedium??"",utmSource:e.get("utm_source")??n?.utmSource??"",utmiCampaign:e.get("utmi_cp")??n?.utmiCampaign??"",utmiPage:e.get("utmi_p")??n?.utmiPage??"",utmiPart:e.get("utmi_pc")??n?.utmiPart??""}}async function Kr(e,n,t){const r=Q(V(n??"",t));let i=!1;if(r)try{i=(await e.commerce.vtexid.validate())?.authStatus?.toLowerCase()==="success"}catch(o){console.warn("JWT validation failed:",o),i=!1}return{isRepresentative:i?!!r?.isRepresentative:!1,customerId:i?r?.customerId:void 0,unitId:i?r?.unitId:void 0}}async function Qr(e,n,t,r,i,o){return!n.seller||!(t||r)?void 0:(await e.commerce.checkout.region({postalCode:t,geoCoordinates:r,country:i,salesChannel:o}))?.[0]?.sellers.find(c=>n.seller===c.id)?.id}function Qe(e){return typeof e?.value=="string"?e.value:""}function Zr(e){if(!e.isRepresentative)return null;const n=Qe(e.shopper?.firstName),t=Qe(e.shopper?.lastName);return{isRepresentative:!0,customerId:e.authentication?.customerId?.value??e.customerId??"",unitName:e.authentication?.unitName?.value??"",unitId:e.authentication?.unitId?.value??e.unitId??"",firstName:n,lastName:t,userName:`${n} ${t}`.trim(),userEmail:e.authentication?.storeUserEmail?.value??"",savedPostalCode:e.publicData?.postalCode?.value??"",contractName:Ln(e.contract,e.profile),organizationManager:e.shopper?.organizationManager?.value??!1}}function ei(e){return e?.id?{id:e.id?.value??"",email:e.email?.value??"",givenName:e.firstName?.value??"",familyName:e.lastName?.value??""}:null}const ni=async(e,{session:n,search:t},{clients:r,headers:i,account:o})=>{const a=te.parse(n.channel??""),s=String(n.postalCode??""),c=n.country??"";let d=n.city??null,u=n.geoCoordinates??null;if((!d||!u)&&s!==""&&c!==""){const A=await Xr(r,c,s);d=A.city,u=A.geoCoordinates}const f=Yr(t,a,s,c,u,n.locale),h=Jr(f,n.marketingData),{isRepresentative:v,customerId:l,unitId:g}=await Kr(r,i?.cookie,o),m=await r.commerce.session(f.toString()).catch(()=>null),S=m?.namespaces.profile??null,O=m?.namespaces.shopper??null,w=m?.namespaces.store??null,b=m?.namespaces.authentication??null,U=m?.namespaces.checkout??null,I=m?.namespaces.public??null;let D=null;if(v&&S?.id?.value)try{D=await r.commerce.masterData.getContractById({contractId:S.id.value})}catch{console.error(`Error while getting contract data for profile ID (${S.id.value}).
9
- `)}const P=await Qr(r,a,s,u,c,f.get("sc")??a.salesChannel),E={...n,currency:{code:w?.currencyCode?.value??n.currency.code,symbol:w?.currencySymbol?.value??n.currency.symbol},country:w?.countryCode?.value??c,channel:Vr(a,w?.channel?.value,U?.regionId?.value,P),b2b:Zr({isRepresentative:v,authentication:b,shopper:O,publicData:I,profile:S,contract:D,customerId:l,unitId:g}),marketingData:h,person:ei(S),geoCoordinates:u?.latitude&&u?.longitude&&u||null,city:d};return Ae(n,E)?null:E},ti={validateCart:qr,validateSession:ni,subscribeToNewsletter:wr,cancelOrder:Ir,processOrderAuthorization:Or,uploadFileToOrderEntry:Dr,startOrderEntryOperation:Cr,startRecommendationSession:br};var be;(function(e){e.NAME="Name",e.DOCUMENT="Document",e.OPERATION_DEFINITION="OperationDefinition",e.VARIABLE_DEFINITION="VariableDefinition",e.SELECTION_SET="SelectionSet",e.FIELD="Field",e.ARGUMENT="Argument",e.FRAGMENT_SPREAD="FragmentSpread",e.INLINE_FRAGMENT="InlineFragment",e.FRAGMENT_DEFINITION="FragmentDefinition",e.VARIABLE="Variable",e.INT="IntValue",e.FLOAT="FloatValue",e.STRING="StringValue",e.BOOLEAN="BooleanValue",e.NULL="NullValue",e.ENUM="EnumValue",e.LIST="ListValue",e.OBJECT="ObjectValue",e.OBJECT_FIELD="ObjectField",e.DIRECTIVE="Directive",e.NAMED_TYPE="NamedType",e.LIST_TYPE="ListType",e.NON_NULL_TYPE="NonNullType",e.SCHEMA_DEFINITION="SchemaDefinition",e.OPERATION_TYPE_DEFINITION="OperationTypeDefinition",e.SCALAR_TYPE_DEFINITION="ScalarTypeDefinition",e.OBJECT_TYPE_DEFINITION="ObjectTypeDefinition",e.FIELD_DEFINITION="FieldDefinition",e.INPUT_VALUE_DEFINITION="InputValueDefinition",e.INTERFACE_TYPE_DEFINITION="InterfaceTypeDefinition",e.UNION_TYPE_DEFINITION="UnionTypeDefinition",e.ENUM_TYPE_DEFINITION="EnumTypeDefinition",e.ENUM_VALUE_DEFINITION="EnumValueDefinition",e.INPUT_OBJECT_TYPE_DEFINITION="InputObjectTypeDefinition",e.DIRECTIVE_DEFINITION="DirectiveDefinition",e.SCHEMA_EXTENSION="SchemaExtension",e.SCALAR_TYPE_EXTENSION="ScalarTypeExtension",e.OBJECT_TYPE_EXTENSION="ObjectTypeExtension",e.INTERFACE_TYPE_EXTENSION="InterfaceTypeExtension",e.UNION_TYPE_EXTENSION="UnionTypeExtension",e.ENUM_TYPE_EXTENSION="EnumTypeExtension",e.INPUT_OBJECT_TYPE_EXTENSION="InputObjectTypeExtension"})(be||(be={}));const ri=e=>typeof e=="string"?Bn(e):null;function Bn(e){try{return JSON.parse(e)}catch{return e}}const ii=e=>typeof e=="object"?JSON.stringify(e):typeof e=="string"?e:null,oi=new se.GraphQLScalarType({name:"ObjectOrString",description:"A string or the string representation of an object (a stringified object).",parseValue:ri,serialize:ii,parseLiteral(e){return e.kind===be.STRING?Bn(e.value):null}}),k=e=>"Price"in e&&"seller"in e&&"product"in e,_=e=>"skuName"in e,ai={priceCurrency:async(e,n,t)=>{const{loaders:{salesChannelLoader:r},storage:{channel:i}}=t;return(await r.load(i.salesChannel)).CurrencyCode??""},priceValidUntil:e=>k(e)?e.PriceValidUntil??"":_(e)?e.priceValidUntil??"":null,itemCondition:()=>"https://schema.org/NewCondition",availability:async e=>k(e)?$e($(e)):_(e)?$e(ir(e.availability)):null,seller:(e,n,t)=>k(e)?{identifier:t.storage.channel?.seller||e.seller.sellerId||""}:_(e)?{identifier:e.seller}:null,price:e=>k(e)?j(e):_(e)?e.sellingPrice/100:null,priceWithTaxes:e=>k(e)?M(j(e),e?.Tax,e.product.unitMultiplier):_(e)?M(e.sellingPrice/100,e.tax/100,e.unitMultiplier):null,sellingPrice:e=>k(e)?rr(e):_(e)?e.sellingPrice/100:null,listPrice:e=>k(e)?e.ListPrice??0:_(e)?e.listPrice/100:null,listPriceWithTaxes:e=>k(e)?M(e.ListPrice??0,e?.Tax,e.product.unitMultiplier):_(e)?M(e.listPrice/100,e.tax/100,e.unitMultiplier):null,itemOffered:e=>k(e)?e.product:_(e)?{...e.product,attachmentsValues:e.attachments}:null,quantity:e=>k(e)?e.AvailableQuantity??0:_(e)?e.quantity:null,isGift:e=>_(e)?e.isGift??!1:null,priceToken:e=>k(e)?e.PriceToken??null:null},si=({linkText:e})=>`/${e}/p`,ci=({offer:e,seller:n,product:t})=>({...e,product:t,seller:n}),li={imageText:"image",imageUrl:"https://storecomponents.vtexassets.com/assets/faststore/images/image___117a6d3e229a96ad0e0d0876352566e2.svg",imageLabel:"label"},ae=(e,n)=>`${e}-${n}`,Ze=(e,n)=>`/${ae(e,n)}/p`,di=e=>Array.isArray(e)&&e.length>0?e:null;function we(e){return e.replace(/^\/+|\/+$/g,"")}async function De(e,n,t){const r=`${n}:${t}`;e.storage.productTranslationsCache??=new Map;const i=e.storage.productTranslationsCache,o=i.get(r);if(o)return o;const a=(async()=>{try{const s=await e.clients.catalog.getLocalizedProduct(n,t);return{linkId:s.linkId,categories:s.categories??[],availableLinkIds:s.availableLinkIds??{}}}catch{return null}})();return i.set(r,a),a}const ui=(e,n)=>{const t=e.findIndex(r=>we(r).split("/").at(-1)===n);return t<0?0:t},pi={productID:({itemId:e})=>e,name:({isVariantOf:e,name:n})=>n??e.productName,slug:({isVariantOf:{linkText:e},itemId:n})=>ae(e,n),description:({isVariantOf:{description:e}})=>e,seo:({isVariantOf:e})=>({title:e.productTitle||e.productName,description:e.metaTagDescription||e.description,canonical:si(e)}),brand:({isVariantOf:{brand:e}})=>({name:e}),unitMultiplier:({unitMultiplier:e})=>e,breadcrumbList:async(e,n,t)=>{const{isVariantOf:{categories:r,productName:i,linkText:o,categoryId:a,categoriesIds:s,productId:c},itemId:d}=e,u=ui(s,a),p=r[u],f=we(p).split("/"),h=t.storage.locale;if(ee(t)&&h){const v=await De(t,c,h);if(v){const l=new Set(we(s[u]).split("/").filter(Boolean)),g=v.categories.filter(S=>l.has(S.id.toString())).sort((S,O)=>S.fullPath.split("/").length-O.fullPath.split("/").length);if(g.length===f.length)return{itemListElement:[...g.map((S,O)=>({name:S.name,item:`/${S.fullPathUriName}/`,position:O+1})),{name:i,item:Ze(v.linkId,d),position:f.length+1}],numberOfItems:f.length}}}return{itemListElement:[...f.map((v,l)=>{const g=`/${f.slice(0,l+1).map(ce).join("/")}/`;return{name:v,item:g,position:l+1}}),{name:i,item:Ze(o,d),position:f.length+1}],numberOfItems:f.length}},image:({images:e},n)=>{const t=(di(e)??[li]).map(({imageUrl:s,imageText:c,imageLabel:d})=>({alternateName:c??"",url:s.replace("vteximg.com.br","vtexassets.com"),keywords:d}));if(typeof n!="object")return t;let{context:r,limit:i}=n;const o=r!=="generic";i=i||-1,i=i<=-1?void 0:i;let a=o?t.filter(({keywords:s})=>s===r):t;return a=a.length===0?t:a,a.slice(0,i)},sku:({itemId:e})=>e,gtin:({ean:e,referenceId:n})=>e||(n[0]?.Value??""),mpn:({isVariantOf:{manufacturerCode:e}})=>e??"",review:()=>[],aggregateRating:()=>({}),offers:e=>e.sellers.map(n=>ci({offer:n.commertialOffer,seller:n,product:e})).sort(wn),isVariantOf:e=>e,additionalProperty:({variations:e=[],attachmentsValues:n=[],attributes:t=[]})=>{const r=e.flatMap(({name:a,values:s})=>s.map(c=>({name:a,value:c,valueReference:re.specification}))),i=n.map(Tn),o=t.map(Ar);return[...r,...i,...o]},hasSpecifications:({isVariantOf:e})=>!!e.skuSpecifications?.length,skuSpecifications:({isVariantOf:{skuSpecifications:e}})=>e??[],specificationGroups:({isVariantOf:{specificationGroups:e}})=>e,releaseDate:({isVariantOf:{releaseDate:e}})=>e??"",advertisement:({isVariantOf:{advertisement:e}})=>e,deliveryPromiseBadges:({isVariantOf:{deliveryPromisesBadges:e}})=>e,otherLocales:async(e,n,t)=>{if(!ee(t))return null;const r=vt(t);if(r.length===0)return null;const i=e.isVariantOf.productId,o=e.itemId,a=t.storage.locale,s=Ot(t),c=await De(t,i,a);if(!c?.availableLinkIds)return null;const{availableLinkIds:d}=c,{linkText:u}=e.isVariantOf;return r.map(p=>{if(p===s)return{locale:p,slug:ae(u,o)};const f=d[p];return f?{locale:p,slug:ae(f,o)}:null}).filter(p=>p!==null)}},gi=new Set(["allSpecifications"]),mi={hasVariant:e=>e.isVariantOf.items.map(n=>F(n,e.isVariantOf)),productGroupID:({isVariantOf:e})=>e.productId,name:e=>e.isVariantOf.productName,skuVariants:e=>e,additionalProperty:({isVariantOf:{specificationGroups:e}})=>e.filter(n=>!gi.has(n.name)).flatMap(({specifications:n})=>n.flatMap(({name:t,values:r})=>r.map(i=>({name:t,value:i,valueReference:re.specification}))))},hi={propertyID:e=>e.propertyID||Un(e),name:({name:e})=>e,value:({value:e})=>e,valueReference:({valueReference:e})=>e},ue=e=>{const n=e.flatMap(r=>r.sellers.map(i=>({offer:i.commertialOffer,sku:r}))),t=Ie(n,({offer:r},{offer:i})=>wn(r,i));return t?t.sku:e[0]},$n=e=>e!==""&&!Number.isNaN(Number(e)),fi=/^vrn:recommendations:[^:]+:[^:]+:[^:]+$/,Si=async(e,{campaignVrn:n,userId:t,products:r},i)=>{const{clients:{commerce:o}}=i,{salesChannel:a}=i.storage.channel,s=n?.trim();if(!s||!fi.test(s))throw new T(`Invalid campaignVrn: "${n}"`);const c=t?.trim();if(t!=null&&!c)throw new T("Invalid userId: must be a non-empty string");if(r!=null&&(!Array.isArray(r)||r.some(h=>!h?.trim())))throw new T("Invalid products: must be an array of non-empty strings");const d=await o.recommendation.recommendations({campaignVrn:s,userId:c||void 0,products:r??[],salesChannel:a??void 0,locale:i.storage.locale}),{campaign:u,correlationId:p}=d;return{products:(d.products??[]).map(h=>{const v=ue(h.items);return v?F(v,h):null}).filter(h=>!!h),correlationId:p,campaign:u}},en={price_desc:"price:desc",price_asc:"price:asc",orders_desc:"orders:desc",name_desc:"name:desc",name_asc:"name:asc",release_desc:"release:desc",discount_desc:"discount:desc",score_desc:""},yi=async(e,{operationId:n},{clients:{commerce:t}})=>{if(!n)throw new T("Missing operationId");return t.orderEntry.getOperation({operationId:n})},Ii=async(e,{orderFormId:n},{clients:{commerce:t}})=>{if(!n)throw new T("Missing orderFormId");const{items:r}=await t.orderEntry.getOrderFormItems({orderFormId:n});return(r??[]).map(i=>({id:i.id,name:i.name,price:i.price,listPrice:i.listPrice,quantity:i.quantity,imageUrl:i.imageUrl??null,availability:i.availability,seller:i.seller,unitMultiplier:i.unitMultiplier??1}))};async function vi(e,n,t,r){const i=n.slice(0,n.lastIndexOf("-"));return(await De(e,t,r))?.linkId===i}const Mn="Invalid SkuId",zn="Slug was set but the fetched sku does not satisfy the slug condition.",Oi=e=>q(e)||e instanceof Error&&(e.message===Mn||e.message.startsWith(zn));async function Ci(e,n,t,r){const{linkText:i,productId:o}=n.isVariantOf;if(!(!t||!i||t.startsWith(i)||ee(e)&&r&&$n(t.split("-").pop()??"")&&await vi(e,t,o,r)))throw new Error(`${zn} slug: ${t}, linkText: ${i}`)}async function bi(e,n){if(n==null)throw new T("Missing slug or id");const{clients:{commerce:t,search:r}}=e,i=await t.catalog.portal.pagetype(`${n}/p`);if(i.pageType!=="Product"||!i.id)throw new N(`No product found for slug ${n}`);const o=await r.fetchProduct({field:"id",value:String(i.id)}).catch(()=>null);if(!o)throw new N(`No product found for id ${i.id}`);return F(ue(o.items),o)}const wi={product:async(e,{locator:n},t)=>{const r=je(n),i=xe(n),o=mr(n),a=gr(n);r&&le(t,r),i&&ve(t,i);const{loaders:{skuLoader:s}}=t;try{const c=o??a?.split("-").pop()??"";if(!$n(c))throw new Error(Mn);const d=await s.load(c);return await Ci(t,d,a,i),d}catch(c){if(!Oi(c))throw c;return bi(t,a)}},collection:(e,{slug:n},t)=>{const{loaders:{collectionLoader:r}}=t;return r.load({slug:n,locale:oe(t)})},search:async(e,{first:n,after:t,sort:r,term:i,selectedFacets:o,sponsoredCount:a},s)=>{const c=je(o),d=xe(o),u=pr(o);c&&le(s,c),d&&ve(s,d);const p=t?Number(t):0,f={page:Math.ceil(p/n)||0,count:n,query:i??void 0,sort:en[r??"score_desc"]??en.score_desc,selectedFacets:o?.flatMap(qe)??[],sponsoredCount:a??void 0};if(u){const l=(await s.clients.commerce.catalog.products.crossselling({type:Pn[u.key],productId:u.value})).map(m=>m.productId).slice(0,n),g=s.clients.search.productsByIdentifier({field:"id",values:l}).then(m=>({products:m,recordsFiltered:m.length,pagination:{count:m.length,current:{index:0,proxyURL:""},before:[],after:[],perPage:n,next:{index:0,proxyURL:""},previous:{index:0,proxyURL:""},first:{index:0,proxyURL:""},last:{index:0,proxyURL:""}},sampling:!1,options:{sorts:[],counts:[]},translated:!1,locale:"",query:"",operator:"and",fuzzy:"0",searchId:""}));return{searchArgs:f,productSearchPromise:g}}const h=s.clients.search.products(f);return{searchArgs:f,productSearchPromise:h}},allProducts:async(e,{first:n,after:t},r)=>{const{clients:{search:i}}=r,o=t?Number(t):0,a=await i.products({page:Math.ceil(o/n),count:n}),s=a.products.flatMap(c=>c.items.map(d=>F(d,c))).filter(c=>c.sellers.length>0);return{pageInfo:{hasNextPage:a.pagination.after.length>0,hasPreviousPage:a.pagination.before.length>0,startCursor:"0",endCursor:a.recordsFiltered.toString(),totalCount:a.recordsFiltered},edges:s.map((c,d)=>({node:c,cursor:(o+d).toString()}))}},products:async(e,{productIds:n},t)=>{const{clients:{search:r}}=t;return n.length?(await r.productsByIdentifier({field:"id",values:n})).flatMap(o=>o.items.map(a=>F(a,o))).filter(o=>n.includes(o.itemId)&&o.sellers.length>0):[]},allCollections:async(e,{first:n,after:t},r)=>{const{clients:{commerce:i}}=r,o=t?Number(t):0,[a,s]=await Promise.all([i.catalog.brand.list(),i.catalog.category.tree()]),c=[],d=(h,v)=>{c.push({id:h.id,name:h.name,fatherCategoryId:v,linkId:ce(h.name),title:h.Title,description:null,metaTagDescription:h.MetaTagDescription,availableLinkIds:null,entityType:"category",slug:new URL(h.url).pathname.slice(1).toLowerCase()});for(const l of h.children)d(l,h.id)};for(const h of s)d(h,null);const f=[...a.filter(h=>h.isActive).map(h=>({id:h.id,name:h.name,linkId:ce(h.name),title:h.title,description:null,metaTagDescription:h.metaTagDescription,availableLinkIds:null,entityType:"brand"})),...c].filter(h=>!!Dn.slug(h,null,r,null));return{pageInfo:{hasNextPage:f.length-o>n,hasPreviousPage:o>0,startCursor:"0",endCursor:(Math.min(n,f.length-o)-1).toString(),totalCount:f.length},edges:f.slice(o,o+n).map((h,v)=>({node:h,cursor:(o+v).toString()}))}},shipping:async(e,{country:n,items:t,postalCode:r},i)=>{const{loaders:{simulationLoader:o},clients:{commerce:a}}=i,[s,c]=await Promise.all([o.load({country:n,items:t,postalCode:r}),a.checkout.address({postalCode:r,country:n})]);return{...s,address:c}},redirect:async(e,{term:n,selectedFacets:t},r)=>{if(!n&&(!t||!t.length))return null;const{redirect:i}=await r.clients.search.products({page:1,count:1,query:n??void 0,selectedFacets:t?.flatMap(qe)??[],allowRedirect:!0});return{url:i}},sellers:async(e,{postalCode:n,geoCoordinates:t,country:r,salesChannel:i},o)=>{const{clients:{commerce:a}}=o,c=(await a.checkout.region({postalCode:n,geoCoordinates:t,country:r,salesChannel:i}))?.[0],{id:d,sellers:u}=c;return{id:d,sellers:u}},profile:async(e,{id:n},t)=>{const{clients:{commerce:r}}=t,i=await r.profile.addresses(n);function o(s){return!s||Object.keys(s).length===0?[]:Object.values(s).map(c=>JSON.parse(c))}return{addresses:o(i)}},productCount:async(e,{term:n},t)=>{const{clients:{search:r}}=t;return await r.productCount({query:n??void 0})},userOrder:async(e,{orderId:n},t)=>{try{if(!n)throw new T("Missing orderId");const{clients:{commerce:r}}=t,i=await r.oms.userOrder({orderId:n});if(!i)throw new N(`No order found for id ${n}`);let o=null;try{const c=await r.oms.getCommercialAuthorizationsByOrderId({orderId:n});o=An(c)}catch{}const s=(await r.masterData.getShopperById({userId:i.purchaseAgentData?.purchaseAgents?.[0]?.userId??""})??[])[0]??{};return{orderId:i.orderId,creationDate:i.creationDate,totals:i.totals,items:i.items,shippingData:i.shippingData,paymentData:i.paymentData,customData:i.customData,status:i.status,statusDescription:i.statusDescription,allowCancellation:i.allowCancellation,storePreferencesData:i.storePreferencesData,clientProfileData:i.clientProfileData,canProcessOrderAuthorization:(i.status==="waiting-for-confirmation"||i.status==="waiting-for-authorization")&&!!o,ruleForAuthorization:o,shopper:{firstName:s?.firstName||"",lastName:s?.lastName||"",email:s?.email||"",phone:s?.phone||""},budgetData:i.budgetData??{budgets:[]}}}catch(r){const i=r.message;let o={};try{const s=JSON.parse(i);o=s.error||s}catch{o={message:i}}const a=o?.message||i;throw q(r)?new N(`No order found for id ${n}. ${a}.`):yn(r)?new x(`You are forbidden to interact with order with id ${n}. ${a}.`):r}},listUserOrders:async(e,n,t)=>{const{clients:{commerce:r}}=t,i=await r.oms.listUserOrders(n);return{list:i.list?.map(o=>({orderId:o.orderId,creationDate:o.creationDate,clientName:o.clientName,items:o.items,totalValue:o.totalValue,status:o.status,statusDescription:o.statusDescription,ShippingEstimatedDate:o.ShippingEstimatedDate,customFields:o.customFields,currencyCode:o.currencyCode})),paging:i.paging}},listUserQuotes:async(e,n,t)=>{const{clients:{commerce:r}}=t,i=await r.quotes.listUserQuotes(n),o=[...new Set(i.items.map(c=>c.createdBy).filter(Boolean))],a=new Map;return await Promise.all(o.map(async c=>{try{const[d]=await r.masterData.getShopperById({userId:c});if(d){const u=[d.firstName,d.lastName].filter(Boolean).join(" ");u&&a.set(c,u)}}catch{}})),{list:i.items.map(c=>({id:c.id,status:c.status,label:c.label??null,createdAt:c.createdAt,expiresAt:c.expiresAt,amount:c.amount,createdBy:c.createdBy?a.get(c.createdBy)??c.createdBy:null})),paging:{total:i.totalItems,currentPage:i.pageNumber,perPage:i.pageSize}}},validateUser:async(e,n,t)=>({isValid:!0}),isOrganizationMember:async(e,n,t)=>{const{clients:{commerce:r}}=t;return!!(await r.session("").catch(()=>null))?.namespaces.authentication?.unitId?.value},userDetails:async(e,n,t)=>{const{account:r,headers:i,clients:{commerce:o}}=t,s=Q(V(i?.cookie??"",r))?.userId??"",[c,d,u]=await Promise.all([o.session("").catch(()=>null),s?o.masterData.getShopperById({userId:s}).catch(()=>null):Promise.resolve(null),s?o.licenseManager.getUserRoles({userId:s}).catch(()=>null):Promise.resolve(null)]),p=d?.[0],f=c?.namespaces.authentication??null,h=`${(p?.firstName??"").trim()} ${(p?.lastName??"").trim()}`.trim();return{username:f?.storeUserEmail?.value??"",name:h,email:f?.storeUserEmail?.value??"",phone:p?.phone??"",role:u?.Roles?.map(v=>v.Name)??[],orgUnit:f?.unitName?.value??""}},accountProfile:async(e,n,t)=>{const{account:r,headers:i,clients:{commerce:o}}=t,a=Q(V(i?.cookie??"",r));if(!a?.userId)return null;if(a?.isRepresentative){const c=await o.session("").catch(()=>null);if(!c)return null;const d=c.namespaces.profile??null,u=c.namespaces.shopper??null,p=c.namespaces.authentication??null,f=Ke(c)||a?.customerId?.trim()||"";let h=null;if(f)try{h=await o.masterData.getContractById({contractId:f})}catch(g){console.error(`Error while getting contract data for contract ID (${f}).`,g)}const v=`${(u?.firstName?.value??"").trim()} ${(u?.lastName?.value??"").trim()}`.trim();return{name:Ln(h,d)||v||"",email:d?.email?.value||p?.storeUserEmail?.value||"",id:d?.id?.value||p?.customerId?.value||a?.customerId?.trim()||""}}const s=await o.licenseManager.getUserById({userId:a?.userId}).catch(()=>null);return{name:s?.name||"",email:s?.email||"",id:s?.id||""}},availableContracts:async(e,{orgUnitId:n},t)=>{if(!n)throw new T("Missing orgUnitId");const{account:r,headers:i,clients:{commerce:o}}=t,a=await o.session("").catch(()=>null),s=V(i?.cookie??"",r);let c=null;try{c=s?Q(s):null}catch{c=null}const d=a?.namespaces.authentication?.unitId?.value?.trim()??c?.unitId?.trim()??"";if(!d||d!==n)throw new x("You are not allowed to list contracts for this organization unit");const u=Wr(a?.namespaces.shopper),p=Ke(a)||c?.customerId?.trim()||"";return Hr(u,p)},pickupPoints:async(e,{geoCoordinates:n},t)=>{const{clients:{commerce:r}}=t;return await r.checkout.pickupPoints({geoCoordinates:n})},orderEntryOperation:yi,orderFormItems:Ii,recommendations:Si},Di={reviewRating:()=>({ratingValue:5,bestRating:5}),author:()=>({name:""})},Pi=(e,n,t)=>n?e.key==="category-1":t?e.key==="brand":!1,Ai={suggestions:async(e,n,t)=>{const{clients:{search:r}}=t,{searchArgs:i}=e;if(!i.query)return{terms:(await r.topSearches()).searches.map(p=>({value:p.term,count:p.count})),products:[]};const{productSearchPromise:o}=e,[a,s]=await Promise.all([r.suggestedTerms(i),o]),c=s.products.map(u=>{const p=ue(u.items);return p&&F(p,u)}).filter(u=>!!u),{searches:d}=a;return{terms:d.map(u=>({value:u.term,count:u.count})),products:c}},products:async({productSearchPromise:e})=>{const n=await e,t=n.products.map(r=>{const i=ue(r.items);return i&&F(i,r)}).filter(r=>!!r);return{pageInfo:{hasNextPage:n.pagination.after.length>0,hasPreviousPage:n.pagination.before.length>0,startCursor:"0",endCursor:n.recordsFiltered.toString(),totalCount:n.recordsFiltered},edges:t.map((r,i)=>({node:r,cursor:i.toString()}))}},facets:async({searchArgs:e},n,t)=>{const{clients:{search:r}}=t;t.storage.searchArgs=e;const{facets:i=[]}=await r.facets(e),o=!e.query,a=e.selectedFacets?.length?e.selectedFacets[0].key==="category-1":!1,s=e.selectedFacets?.length?e.selectedFacets[0].key==="brand":!1;return i.filter(d=>!o||!Pi(d,a,s))},metadata:async({productSearchPromise:e})=>{const n=await e;return{isTermMisspelled:n.correction?.misspelled??!1,logicalOperator:n.operator,fuzzy:n.fuzzy}},searchId:async({productSearchPromise:e})=>(await e).searchId},Ei={title:({title:e})=>e??"",description:({description:e})=>e??"",canonical:({canonical:e})=>e??"",titleTemplate:()=>""},Ti=["bd","d","h","m"],Ui=e=>Ti.includes(e),ki={bd:{0:"Today",1:"In 1 business day",other:"Up to # business days"},d:{0:"Today",1:"In 1 day",other:"Up to # days"},h:{0:"Now",1:"In 1 hour",other:"Up to # hours"},m:{0:"Now",1:"In 1 minute",other:"Up to # minutes"}},qn=e=>{const[n,t]=[e.split(/\D+/)[0],e.split(/[0-9]+/)[1]],r=n!==""&&!Number.isNaN(Number(n)),i=Ui(t);if(!r||!i)return"";const o=Number(n)<2?Number(n):"other";return ki[t][o].replace("#",n)??""},_i={carrier:e=>e?.friendlyName??e?.name??"",price:e=>e?.price?e.price/100:e?.price,localizedEstimates:e=>e?.shippingEstimate?qn(e.shippingEstimate):""},nn="skuvariation";function tn(e,n){const t=`${nn}${n}`.toLowerCase(),r=e.find(o=>o.imageLabel===t);if(r)return r;const i=e.find(o=>o.imageLabel===nn);return i||e[0]}function Ri(e,n,t){const r={};return e.forEach(i=>{const o=i.variations;if(o.length===0)return;const a=`${n}-${o.find(c=>c.name===n)?.values[0]??""}`,s=o.reduce((c,d)=>d.name===n?c:c+`-${d.name}-${d.values[0]}`,a);r[s]=`${t}-${i.itemId}`}),r}function rn(e){const n={};return e.forEach(t=>{n[t.name]=t.values[0]}),n}function Fi(e){const n={};return e?.forEach(t=>{n[t.field.originalName??t.field.name]=t.values.map(r=>r.originalName??r.name)}),n}function Ni(e,n){return Number.isNaN(Number(e)-Number(n))?e<n?-1:e>n?1:0:Number(e)-Number(n)}function Li(e){const n=e;for(const t in e)e[t].every(i=>!Number.isNaN(Number(i.value)))&&e[t].sort((i,o)=>Ni(i.value,o.value));return n}function Bi(e,n,t){const r={},i=new Set;return e.forEach(o=>{if(o.variations.length===0)return;const a=o.variations.find(c=>c.name===n);if(!(a?.values[0]===t)){const c=`${n}-${a?.values[0]}`;if(!a||i.has(c))return;i.add(c);const d=tn(o.images,n),u={src:d.imageUrl,alt:d.imageLabel??"",label:`${n}: ${a.values[0]}`,value:a.values[0]};r[a.name]?r[a.name].push(u):r[a.name]=[u];return}o.variations.forEach(c=>{const d=`${c.name}-${c.values[0]}`;if(i.has(d))return;i.add(d);const u=tn(o.images,c.name),p={src:u.imageUrl,alt:u.imageText??"",label:`${c.name}: ${c.values[0]}`,value:c.values[0]};r[c.name]?r[c.name].push(p):r[c.name]=[p]})}),Li(r)}const $i={activeVariations:e=>rn(e.variations),allVariantsByName:e=>Fi(e.isVariantOf.skuSpecifications),slugsMap:(e,n)=>Ri(e.isVariantOf.items,n.dominantVariantName??e.variations[0]?.name,e.isVariantOf.linkText),availableVariations:(e,n)=>{const t=n.dominantVariantName??e.variations[0]?.name,i=rn(e.variations)[t];return Bi(e.isVariantOf.items,t,i)},allVariantProducts:e=>e.isVariantOf.items.map(n=>F(n,e.isVariantOf))},Mi={"pickup-in-point":"Pickup",delivery:"Delivery",pickup:"Pickup","take-away":"Take away","":""},zi={deliveryOptionsData:e=>{const{shippingData:n,items:t}=e,r=n?.logisticsInfo||[],i=n?.selectedAddresses||n?.availableAddresses||[n?.address],o=r.reduce((d,u)=>{const p=u?.selectedSla||"",f=u?.selectedDeliveryChannel||u?.deliveryChannel||"",h=u?.deliveryCompany||"",v=u?.deliveryWindow,l=u?.pickupStoreInfo,g=u?.shippingEstimate||"",m=u?.shippingEstimate?qn(u?.shippingEstimate):"",S=u?.shippingEstimateDate||"",O=u?.addressId||"",w=u?.itemIndex??0,b=t?.[w],U=b?.seller||"",I=`${p}|${f}|${h}|${U}|${g}|${S}|${O}|${v?.startDateUtc}|${v?.endDateUtc}`,D=i?.find(C=>C?.addressId===O),P=`${Mi[f]||""} ${m} ${D?.neighborhood?`to ${D?.neighborhood}`:""}`.trim(),{taxPriceTagsTotal:E,taxPriceTags:A}=qi(b?.priceTags??[]),R=(b?.sellingPrice??0)*(b?.quantity??0)+(b?.tax??0)+(E??0);return d[I]||(d[I]={selectedSla:p,deliveryChannel:f,deliveryCompany:h,deliveryWindow:v,shippingEstimate:g,shippingEstimateDate:S,seller:U,friendlyShippingEstimate:m,friendlyDeliveryOptionName:P,address:D,pickupStoreInfo:l,quantityOfDifferentItems:0,total:0,items:[]}),d[I]&&(d[I].items?.push({id:b?.id||"",uniqueId:b?.uniqueId||"",name:b?.name||"",quantity:b?.quantity||0,price:b?.price||0,sellingPrice:b?.sellingPrice||0,imageUrl:b?.imageUrl||"",taxPriceTags:A??[],taxPriceTagsTotal:E??0,tax:b?.tax||0,total:R}),d[I].quantityOfDifferentItems=(d[I].quantityOfDifferentItems??0)+1,d[I].total=(d[I].total??0)+R),d},{}),a=Object.values(o),s=n?.contactInformation?.[0],c={name:`${s?.firstName??""} ${s?.lastName??""}`.trim()||a?.[0]?.address?.receiverName||"",email:s?.email||"",phone:s?.phone||""};return{deliveryOptions:a,contact:c}},customFields:e=>{const n=e?.customData?.customFields||[];return Object.values(n.reduce((t,r)=>{const i=r?.linkedEntity?.type||"",o=r?.linkedEntity?.id||"",a=`${i}|${o||""}`;return t[a]||(t[a]={type:i,id:o,fields:[]}),t[a].fields.push(...r?.fields||[]),t},{}))||[]}};function qi(e){const t=e.filter(i=>i?.name?.includes("TAX")),r=t.reduce((i,o)=>i+(o.rawValue?o.rawValue*100:0),0);return{taxPriceTags:t,taxPriceTagsTotal:r}}const Vi={StoreCollection:Dn,StoreAggregateOffer:ar,StoreProduct:pi,StoreSeo:Ei,StoreFacet:hr,StoreFacetBoolean:fr,StoreFacetRange:Sr,StoreFacetValueBoolean:yr,StoreOffer:ai,StoreAggregateRating:sr,StoreReview:Di,StoreProductGroup:mi,StoreSearchResult:Ai,StorePropertyValue:hi,SkuVariants:$i,ShippingSLA:_i,UserOrderResult:zi,ObjectOrString:oi,Query:wi,Mutation:ti},xi=()=>Vi,ji=`"""
7
+ More info at: https://developers.vtex.com/vtex-rest-api/docs/customizable-fields-with-checkout-api`),r}},Mr=(e,n)=>{const r=e.customData?.customApps.find(a=>a.id==="faststore")?.fields?.cartEtag;return r==null?!0:Ln(e,n)!==r},zr=async(e,{clients:{commerce:n}})=>n.checkout.clearOrderFormMessages({id:e}),Xe=async(e,n,{clients:{commerce:t}})=>{if(!n)return e;const{updateShipping:r,addressChanged:i}=Un(e,n);if(r){const a=_r(e,n,i),s=a||Tr(n);return!!n.deliveryMode?.deliveryWindow&&await t.checkout.shippingData({id:e.orderFormId,index:e.items.length,deliveryMode:n.deliveryMode,selectedAddresses:s},!1),t.checkout.shippingData({id:e.orderFormId,index:e.items.length,deliveryMode:n.deliveryMode,selectedAddresses:s},!0)}return e},qr=(e,n)=>{if(!e)return"";const r=ne.parse(e)[n];return r?r.split("=")[1]:""},Ye=(e,n)=>{const t=Pr(e.storage.channel,n.salesChannel);return t?(le(e,t),n.salesChannel?String(n.salesChannel):null):null},Je=(e,n,t,r)=>r?Ce(e,n,t,r):null,Vr=async(e,{cart:{order:n},session:t},r)=>{const i=qr(r.headers.cookie,"checkout.vtex.com"),{clients:{commerce:a},loaders:{skuLoader:o}}=r,s=t?.channel,c=t?.locale;s&&le(r,s),c&&ve(r,c);const d=i||void 0,u=await a.checkout.orderForm({id:d,channel:r.storage.channel,preserveSalesChannel:!!d}),p=u.orderFormId;u.messages.length!==0&&await zr(p,r);const f=ne.parse(r?.headers?.cookie??"")?.vtex_session,h=z(f),{acceptedOffer:v,shouldSplitItem:l}=n;if(Mr(u,h)){const C=Ye(r,u),L=await He(u,a,h).then(Ge);if(p)return Ce(L,o,l,C)}const m=Ye(r,u),S=We(v),O=We(u.items.map(de)),w=Array.from(O.entries()),b=Array.from(S.entries()),{itemsToAdd:_,itemsToUpdate:I}=b.reduce((C,[L,Ee])=>{const Te=O.get(L);if(!Te)return Ee.forEach(H=>C.itemsToAdd.push(H)),C;const[ie,...jn]=Te;if(Nn(u.items,ie.itemOffered.sku)||Fn(u.items,ie.itemOffered.sku))return C.itemsToUpdate.push(ie),C;const Wn=Ee.reduce((H,Gn)=>H+Gn.quantity,0);return C.itemsToUpdate.push({...ie,quantity:Wn}),jn.forEach(H=>C.itemsToUpdate.push({...H,quantity:0})),C},{itemsToAdd:[],itemsToUpdate:[]}),D=w.filter(([C])=>!S.has(C)).flatMap(([,C])=>C.map(L=>({...L,quantity:0}))),A=[..._,...I,...D].map(Br),{updateShipping:E}=t?Un(u,t):{updateShipping:!1};if(A.length===0&&!E)return Je(u,o,l,m);let P;A.length>0?P=await a.checkout.updateOrderFormItems({id:u.orderFormId,orderItems:A,shouldSplitItem:l}).then(C=>Xe(C,t,r)):P=await Xe(u,t,r),P=await Promise.resolve(P).then(C=>{if(t?.marketingData){const L={...C.marketingData,...t.marketingData};return a.checkout.marketingData({id:u.orderFormId,marketingData:L})}return C}).then(C=>c&&C.clientPreferencesData?.locale!==c?a.checkout.clientPreferencesData({id:C.orderFormId,clientPreferencesData:{...C.clientPreferencesData,locale:c}}):C).then(C=>He(C,a,h)).then(Ge);const R=Pe(u.messages,P.messages);return $r(n,P)&&R?Je(P,o,l,m):Ce(P,o,l,m)};function xr(e,n,t,r){const i=e.hasOnlyDefaultSalesChannel===!1,a=n??void 0,o=t??e.regionId;return te.stringify({salesChannel:i?e.salesChannel||a:a??e.salesChannel,regionId:o??void 0,seller:r,hasOnlyDefaultSalesChannel:i?!1:!a})}const jr=e=>{const n=(e?.corporateName??"").trim();return n||(e?.firstName??"").trim()},Wr=e=>{if(!e||typeof e!="object")return!1;const n=e;return typeof n.customerId=="string"&&n.customerId.trim()!==""&&typeof n.contractName=="string"&&typeof n.isActive=="boolean"&&typeof n.isCurrent=="boolean"},Gr=e=>{const n=e?.availableContracts?.value;return Array.isArray(n)?n.filter(Wr):[]},Hr=e=>e?.customerId?!!((e.contractName??"").trim()&&e.isActive):!1,Ke=e=>e?.namespaces?.shopper?.activeContractId?.value?.trim()??e?.namespaces?.authentication?.customerId?.value?.trim()??e?.namespaces?.profile?.id?.value?.trim()??"",Xr=(e,n="")=>{const t=n.trim();return e.filter(Hr).map(r=>({id:r.customerId,corporateName:r.contractName.trim(),isActive:t?r.customerId===t:r.isCurrent}))},Bn=(e,n)=>{const t=jr(e);return t||(n?.firstName?.value??"").trim()};async function Yr(e,n,t){try{const r=await e.commerce.checkout.address({postalCode:t,country:n}),i=r.geoCoordinates?{latitude:r.geoCoordinates[1],longitude:r.geoCoordinates[0]}:null;return{city:r.city,geoCoordinates:i}}catch(r){throw console.error(`Error while getting geo coordinates for the current postal code (${t}) and country (${n}).
8
+ `),r}}function Jr(e,n,t,r,i,a){const o=new URLSearchParams(e);return o.has("facets")&&o.delete("facets"),o.set("sc",o.get("sc")??n.salesChannel),t&&o.set("postalCode",t),r&&o.set("country",r),i&&o.set("geoCoordinates",`${i.longitude},${i.latitude}`),o.set("locale",a),o}function Kr(e,n){return{utmCampaign:e.get("utm_campaign")??n?.utmCampaign??"",utmMedium:e.get("utm_medium")??n?.utmMedium??"",utmSource:e.get("utm_source")??n?.utmSource??"",utmiCampaign:e.get("utmi_cp")??n?.utmiCampaign??"",utmiPage:e.get("utmi_p")??n?.utmiPage??"",utmiPart:e.get("utmi_pc")??n?.utmiPart??""}}async function Qr(e,n,t){const r=z($(n??"",t));let i=!1;if(r)try{i=(await e.commerce.vtexid.validate())?.authStatus?.toLowerCase()==="success"}catch(a){console.warn("JWT validation failed:",a),i=!1}return{isRepresentative:i?!!r?.isRepresentative:!1,customerId:i?r?.customerId:void 0,unitId:i?r?.unitId:void 0}}async function Zr(e,n,t,r,i,a){return!n.seller||!(t||r)?void 0:(await e.commerce.checkout.region({postalCode:t,geoCoordinates:r,country:i,salesChannel:a}))?.[0]?.sellers.find(c=>n.seller===c.id)?.id}function Qe(e){return typeof e?.value=="string"?e.value:""}function ei(e){if(!e.isRepresentative)return null;const n=Qe(e.shopper?.firstName),t=Qe(e.shopper?.lastName);return{isRepresentative:!0,customerId:e.authentication?.customerId?.value??e.customerId??"",unitName:e.authentication?.unitName?.value??"",unitId:e.authentication?.unitId?.value??e.unitId??"",firstName:n,lastName:t,userName:`${n} ${t}`.trim(),userEmail:e.authentication?.storeUserEmail?.value??"",savedPostalCode:e.publicData?.postalCode?.value??"",contractName:Bn(e.contract,e.profile),organizationManager:e.shopper?.organizationManager?.value??!1}}function ni(e){return e?.id?{id:e.id?.value??"",email:e.email?.value??"",givenName:e.firstName?.value??"",familyName:e.lastName?.value??""}:null}const ti=async(e,{session:n,search:t},{clients:r,headers:i,account:a})=>{const o=te.parse(n.channel??""),s=String(n.postalCode??""),c=n.country??"";let d=n.city??null,u=n.geoCoordinates??null;if((!d||!u)&&s!==""&&c!==""){const P=await Yr(r,c,s);d=P.city,u=P.geoCoordinates}const f=Jr(t,o,s,c,u,n.locale),h=Kr(f,n.marketingData),{isRepresentative:v,customerId:l,unitId:g}=await Qr(r,i?.cookie,a),m=await r.commerce.session(f.toString()).catch(()=>null),S=m?.namespaces.profile??null,O=m?.namespaces.shopper??null,w=m?.namespaces.store??null,b=m?.namespaces.authentication??null,_=m?.namespaces.checkout??null,I=m?.namespaces.public??null;let D=null;if(v&&S?.id?.value)try{D=await r.commerce.masterData.getContractById({contractId:S.id.value})}catch{console.error(`Error while getting contract data for profile ID (${S.id.value}).
9
+ `)}const A=await Zr(r,o,s,u,c,f.get("sc")??o.salesChannel),E={...n,currency:{code:w?.currencyCode?.value??n.currency.code,symbol:w?.currencySymbol?.value??n.currency.symbol},country:w?.countryCode?.value??c,channel:xr(o,w?.channel?.value,_?.regionId?.value,A),b2b:ei({isRepresentative:v,authentication:b,shopper:O,publicData:I,profile:S,contract:D,customerId:l,unitId:g}),marketingData:h,person:ni(S),geoCoordinates:u?.latitude&&u?.longitude&&u||null,city:d};return Pe(n,E)?null:E},ri={validateCart:Vr,validateSession:ti,subscribeToNewsletter:Dr,cancelOrder:vr,processOrderAuthorization:Cr,uploadFileToOrderEntry:Ar,startOrderEntryOperation:br,startRecommendationSession:wr};var be;(function(e){e.NAME="Name",e.DOCUMENT="Document",e.OPERATION_DEFINITION="OperationDefinition",e.VARIABLE_DEFINITION="VariableDefinition",e.SELECTION_SET="SelectionSet",e.FIELD="Field",e.ARGUMENT="Argument",e.FRAGMENT_SPREAD="FragmentSpread",e.INLINE_FRAGMENT="InlineFragment",e.FRAGMENT_DEFINITION="FragmentDefinition",e.VARIABLE="Variable",e.INT="IntValue",e.FLOAT="FloatValue",e.STRING="StringValue",e.BOOLEAN="BooleanValue",e.NULL="NullValue",e.ENUM="EnumValue",e.LIST="ListValue",e.OBJECT="ObjectValue",e.OBJECT_FIELD="ObjectField",e.DIRECTIVE="Directive",e.NAMED_TYPE="NamedType",e.LIST_TYPE="ListType",e.NON_NULL_TYPE="NonNullType",e.SCHEMA_DEFINITION="SchemaDefinition",e.OPERATION_TYPE_DEFINITION="OperationTypeDefinition",e.SCALAR_TYPE_DEFINITION="ScalarTypeDefinition",e.OBJECT_TYPE_DEFINITION="ObjectTypeDefinition",e.FIELD_DEFINITION="FieldDefinition",e.INPUT_VALUE_DEFINITION="InputValueDefinition",e.INTERFACE_TYPE_DEFINITION="InterfaceTypeDefinition",e.UNION_TYPE_DEFINITION="UnionTypeDefinition",e.ENUM_TYPE_DEFINITION="EnumTypeDefinition",e.ENUM_VALUE_DEFINITION="EnumValueDefinition",e.INPUT_OBJECT_TYPE_DEFINITION="InputObjectTypeDefinition",e.DIRECTIVE_DEFINITION="DirectiveDefinition",e.SCHEMA_EXTENSION="SchemaExtension",e.SCALAR_TYPE_EXTENSION="ScalarTypeExtension",e.OBJECT_TYPE_EXTENSION="ObjectTypeExtension",e.INTERFACE_TYPE_EXTENSION="InterfaceTypeExtension",e.UNION_TYPE_EXTENSION="UnionTypeExtension",e.ENUM_TYPE_EXTENSION="EnumTypeExtension",e.INPUT_OBJECT_TYPE_EXTENSION="InputObjectTypeExtension"})(be||(be={}));const ii=e=>typeof e=="string"?$n(e):null;function $n(e){try{return JSON.parse(e)}catch{return e}}const ai=e=>typeof e=="object"?JSON.stringify(e):typeof e=="string"?e:null,oi=new se.GraphQLScalarType({name:"ObjectOrString",description:"A string or the string representation of an object (a stringified object).",parseValue:ii,serialize:ai,parseLiteral(e){return e.kind===be.STRING?$n(e.value):null}}),k=e=>"Price"in e&&"seller"in e&&"product"in e,U=e=>"skuName"in e,si={priceCurrency:async(e,n,t)=>{const{loaders:{salesChannelLoader:r},storage:{channel:i}}=t;return(await r.load(i.salesChannel)).CurrencyCode??""},priceValidUntil:e=>k(e)?e.PriceValidUntil??"":U(e)?e.priceValidUntil??"":null,itemCondition:()=>"https://schema.org/NewCondition",availability:async e=>k(e)?$e(M(e)):U(e)?$e(ar(e.availability)):null,seller:(e,n,t)=>k(e)?{identifier:t.storage.channel?.seller||e.seller.sellerId||""}:U(e)?{identifier:e.seller}:null,price:e=>k(e)?W(e):U(e)?e.sellingPrice/100:null,priceWithTaxes:e=>k(e)?q(W(e),e?.Tax,e.product.unitMultiplier):U(e)?q(e.sellingPrice/100,e.tax/100,e.unitMultiplier):null,sellingPrice:e=>k(e)?ir(e):U(e)?e.sellingPrice/100:null,listPrice:e=>k(e)?e.ListPrice??0:U(e)?e.listPrice/100:null,listPriceWithTaxes:e=>k(e)?q(e.ListPrice??0,e?.Tax,e.product.unitMultiplier):U(e)?q(e.listPrice/100,e.tax/100,e.unitMultiplier):null,itemOffered:e=>k(e)?e.product:U(e)?{...e.product,attachmentsValues:e.attachments}:null,quantity:e=>k(e)?e.AvailableQuantity??0:U(e)?e.quantity:null,isGift:e=>U(e)?e.isGift??!1:null,priceToken:e=>k(e)?e.PriceToken??null:null},ci=({linkText:e})=>`/${e}/p`,li=({offer:e,seller:n,product:t})=>({...e,product:t,seller:n}),di={imageText:"image",imageUrl:"https://storecomponents.vtexassets.com/assets/faststore/images/image___117a6d3e229a96ad0e0d0876352566e2.svg",imageLabel:"label"},oe=(e,n)=>`${e}-${n}`,Ze=(e,n)=>`/${oe(e,n)}/p`,ui=e=>Array.isArray(e)&&e.length>0?e:null;function we(e){return e.replace(/^\/+|\/+$/g,"")}async function De(e,n,t){const r=`${n}:${t}`;e.storage.productTranslationsCache??=new Map;const i=e.storage.productTranslationsCache,a=i.get(r);if(a)return a;const o=(async()=>{try{const s=await e.clients.catalog.getLocalizedProduct(n,t);return{linkId:s.linkId,categories:s.categories??[],availableLinkIds:s.availableLinkIds??{}}}catch{return null}})();return i.set(r,o),o}const pi=(e,n)=>{const t=e.findIndex(r=>we(r).split("/").at(-1)===n);return t<0?0:t},gi={productID:({itemId:e})=>e,name:({isVariantOf:e,name:n})=>n??e.productName,slug:({isVariantOf:{linkText:e},itemId:n})=>oe(e,n),description:({isVariantOf:{description:e}})=>e,seo:({isVariantOf:e})=>({title:e.productTitle||e.productName,description:e.metaTagDescription||e.description,canonical:ci(e)}),brand:({isVariantOf:{brand:e}})=>({name:e}),unitMultiplier:({unitMultiplier:e})=>e,breadcrumbList:async(e,n,t)=>{const{isVariantOf:{categories:r,productName:i,linkText:a,categoryId:o,categoriesIds:s,productId:c},itemId:d}=e,u=pi(s,o),p=r[u],f=we(p).split("/"),h=t.storage.locale;if(ee(t)&&h){const v=await De(t,c,h);if(v){const l=new Set(we(s[u]).split("/").filter(Boolean)),g=v.categories.filter(S=>l.has(S.id.toString())).sort((S,O)=>S.fullPath.split("/").length-O.fullPath.split("/").length);if(g.length===f.length)return{itemListElement:[...g.map((S,O)=>({name:S.name,item:`/${S.fullPathUriName}/`,position:O+1})),{name:i,item:Ze(v.linkId,d),position:f.length+1}],numberOfItems:f.length}}}return{itemListElement:[...f.map((v,l)=>{const g=`/${f.slice(0,l+1).map(ce).join("/")}/`;return{name:v,item:g,position:l+1}}),{name:i,item:Ze(a,d),position:f.length+1}],numberOfItems:f.length}},image:({images:e},n)=>{const t=(ui(e)??[di]).map(({imageUrl:s,imageText:c,imageLabel:d})=>({alternateName:c??"",url:s.replace("vteximg.com.br","vtexassets.com"),keywords:d}));if(typeof n!="object")return t;let{context:r,limit:i}=n;const a=r!=="generic";i=i||-1,i=i<=-1?void 0:i;let o=a?t.filter(({keywords:s})=>s===r):t;return o=o.length===0?t:o,o.slice(0,i)},sku:({itemId:e})=>e,gtin:({ean:e,referenceId:n})=>e||(n[0]?.Value??""),mpn:({isVariantOf:{manufacturerCode:e}})=>e??"",review:()=>[],aggregateRating:()=>({}),offers:e=>e.sellers.map(n=>li({offer:n.commertialOffer,seller:n,product:e})).sort(Dn),isVariantOf:e=>e,additionalProperty:({variations:e=[],attachmentsValues:n=[],attributes:t=[]})=>{const r=e.flatMap(({name:o,values:s})=>s.map(c=>({name:o,value:c,valueReference:re.specification}))),i=n.map(_n),a=t.map(Er);return[...r,...i,...a]},hasSpecifications:({isVariantOf:e})=>!!e.skuSpecifications?.length,skuSpecifications:({isVariantOf:{skuSpecifications:e}})=>e??[],specificationGroups:({isVariantOf:{specificationGroups:e}})=>e,releaseDate:({isVariantOf:{releaseDate:e}})=>e??"",advertisement:({isVariantOf:{advertisement:e}})=>e,deliveryPromiseBadges:({isVariantOf:{deliveryPromisesBadges:e}})=>e,otherLocales:async(e,n,t)=>{if(!ee(t))return null;const r=Ot(t);if(r.length===0)return null;const i=e.isVariantOf.productId,a=e.itemId,o=t.storage.locale,s=Ct(t),c=await De(t,i,o);if(!c?.availableLinkIds)return null;const{availableLinkIds:d}=c,{linkText:u}=e.isVariantOf;return r.map(p=>{if(p===s)return{locale:p,slug:oe(u,a)};const f=d[p];return f?{locale:p,slug:oe(f,a)}:null}).filter(p=>p!==null)}},mi=new Set(["allSpecifications"]),hi={hasVariant:e=>e.isVariantOf.items.map(n=>F(n,e.isVariantOf)),productGroupID:({isVariantOf:e})=>e.productId,name:e=>e.isVariantOf.productName,skuVariants:e=>e,additionalProperty:({isVariantOf:{specificationGroups:e}})=>e.filter(n=>!mi.has(n.name)).flatMap(({specifications:n})=>n.flatMap(({name:t,values:r})=>r.map(i=>({name:t,value:i,valueReference:re.specification}))))},fi={propertyID:e=>e.propertyID||kn(e),name:({name:e})=>e,value:({value:e})=>e,valueReference:({valueReference:e})=>e},ue=e=>{const n=e.flatMap(r=>r.sellers.map(i=>({offer:i.commertialOffer,sku:r}))),t=Ie(n,({offer:r},{offer:i})=>Dn(r,i));return t?t.sku:e[0]},Mn=e=>e!==""&&!Number.isNaN(Number(e)),Si=/^vrn:recommendations:[^:]+:[^:]+:[^:]+$/,yi=async(e,{campaignVrn:n,userId:t,products:r},i)=>{const{clients:{commerce:a}}=i,{salesChannel:o}=i.storage.channel,s=n?.trim();if(!s||!Si.test(s))throw new T(`Invalid campaignVrn: "${n}"`);const c=t?.trim();if(t!=null&&!c)throw new T("Invalid userId: must be a non-empty string");if(r!=null&&(!Array.isArray(r)||r.some(h=>!h?.trim())))throw new T("Invalid products: must be an array of non-empty strings");const d=await a.recommendation.recommendations({campaignVrn:s,userId:c||void 0,products:r??[],salesChannel:o??void 0,locale:i.storage.locale}),{campaign:u,correlationId:p}=d;return{products:(d.products??[]).map(h=>{const v=ue(h.items);return v?F(v,h):null}).filter(h=>!!h),correlationId:p,campaign:u}},en={price_desc:"price:desc",price_asc:"price:asc",orders_desc:"orders:desc",name_desc:"name:desc",name_asc:"name:asc",release_desc:"release:desc",discount_desc:"discount:desc",score_desc:""},Ii=async(e,{operationId:n},{clients:{commerce:t}})=>{if(!n)throw new T("Missing operationId");return t.orderEntry.getOperation({operationId:n})},vi=async(e,{orderFormId:n},{clients:{commerce:t}})=>{if(!n)throw new T("Missing orderFormId");const{items:r}=await t.orderEntry.getOrderFormItems({orderFormId:n});return(r??[]).map(i=>({id:i.id,name:i.name,price:i.price,listPrice:i.listPrice,quantity:i.quantity,imageUrl:i.imageUrl??null,availability:i.availability,seller:i.seller,unitMultiplier:i.unitMultiplier??1}))};async function Oi(e,n,t,r){const i=n.slice(0,n.lastIndexOf("-"));return(await De(e,t,r))?.linkId===i}const zn="Invalid SkuId",qn="Slug was set but the fetched sku does not satisfy the slug condition.",Ci="UseAdHocCard",bi=e=>x(e)||e instanceof Error&&(e.message===zn||e.message.startsWith(qn));async function wi(e,n,t,r){const{linkText:i,productId:a}=n.isVariantOf;if(!(!t||!i||t.startsWith(i)||ee(e)&&r&&Mn(t.split("-").pop()??"")&&await Oi(e,t,a,r)))throw new Error(`${qn} slug: ${t}, linkText: ${i}`)}async function Di(e,n){if(n==null)throw new T("Missing slug or id");const{clients:{commerce:t,search:r}}=e,i=await t.catalog.portal.pagetype(`${n}/p`);if(i.pageType!=="Product"||!i.id)throw new N(`No product found for slug ${n}`);const a=await r.fetchProduct({field:"id",value:String(i.id)}).catch(()=>null);if(!a)throw new N(`No product found for id ${i.id}`);return F(ue(a.items),a)}const Ai={product:async(e,{locator:n},t)=>{const r=je(n),i=xe(n),a=hr(n),o=mr(n);r&&le(t,r),i&&ve(t,i);const{loaders:{skuLoader:s}}=t;try{const c=a??o?.split("-").pop()??"";if(!Mn(c))throw new Error(zn);const d=await s.load(c);return await wi(t,d,o,i),d}catch(c){if(!bi(c))throw c;return Di(t,o)}},collection:(e,{slug:n},t)=>{const{loaders:{collectionLoader:r}}=t;return r.load({slug:n,locale:ae(t)})},search:async(e,{first:n,after:t,sort:r,term:i,selectedFacets:a,sponsoredCount:o},s)=>{const c=je(a),d=xe(a),u=gr(a);c&&le(s,c),d&&ve(s,d);const p=t?Number(t):0,f={page:Math.ceil(p/n)||0,count:n,query:i??void 0,sort:en[r??"score_desc"]??en.score_desc,selectedFacets:a?.flatMap(qe)??[],sponsoredCount:o??void 0};if(u){const l=(await s.clients.commerce.catalog.products.crossselling({type:Pn[u.key],productId:u.value})).map(m=>m.productId).slice(0,n),g=s.clients.search.productsByIdentifier({field:"id",values:l}).then(m=>({products:m,recordsFiltered:m.length,pagination:{count:m.length,current:{index:0,proxyURL:""},before:[],after:[],perPage:n,next:{index:0,proxyURL:""},previous:{index:0,proxyURL:""},first:{index:0,proxyURL:""},last:{index:0,proxyURL:""}},sampling:!1,options:{sorts:[],counts:[]},translated:!1,locale:"",query:"",operator:"and",fuzzy:"0",searchId:""}));return{searchArgs:f,productSearchPromise:g}}const h=s.clients.search.products(f);return{searchArgs:f,productSearchPromise:h}},allProducts:async(e,{first:n,after:t},r)=>{const{clients:{search:i}}=r,a=t?Number(t):0,o=await i.products({page:Math.ceil(a/n),count:n}),s=o.products.flatMap(c=>c.items.map(d=>F(d,c))).filter(c=>c.sellers.length>0);return{pageInfo:{hasNextPage:o.pagination.after.length>0,hasPreviousPage:o.pagination.before.length>0,startCursor:"0",endCursor:o.recordsFiltered.toString(),totalCount:o.recordsFiltered},edges:s.map((c,d)=>({node:c,cursor:(a+d).toString()}))}},products:async(e,{productIds:n},t)=>{const{clients:{search:r}}=t;return n.length?(await r.productsByIdentifier({field:"id",values:n})).flatMap(a=>a.items.map(o=>F(o,a))).filter(a=>n.includes(a.itemId)&&a.sellers.length>0):[]},allCollections:async(e,{first:n,after:t},r)=>{const{clients:{commerce:i}}=r,a=t?Number(t):0,[o,s]=await Promise.all([i.catalog.brand.list(),i.catalog.category.tree()]),c=[],d=(h,v)=>{c.push({id:h.id,name:h.name,fatherCategoryId:v,linkId:ce(h.name),title:h.Title,description:null,metaTagDescription:h.MetaTagDescription,availableLinkIds:null,entityType:"category",slug:new URL(h.url).pathname.slice(1).toLowerCase()});for(const l of h.children)d(l,h.id)};for(const h of s)d(h,null);const f=[...o.filter(h=>h.isActive).map(h=>({id:h.id,name:h.name,linkId:ce(h.name),title:h.title,description:null,metaTagDescription:h.metaTagDescription,availableLinkIds:null,entityType:"brand"})),...c].filter(h=>!!An.slug(h,null,r,null));return{pageInfo:{hasNextPage:f.length-a>n,hasPreviousPage:a>0,startCursor:"0",endCursor:(Math.min(n,f.length-a)-1).toString(),totalCount:f.length},edges:f.slice(a,a+n).map((h,v)=>({node:h,cursor:(a+v).toString()}))}},shipping:async(e,{country:n,items:t,postalCode:r},i)=>{const{loaders:{simulationLoader:a},clients:{commerce:o}}=i,[s,c]=await Promise.all([a.load({country:n,items:t,postalCode:r}),o.checkout.address({postalCode:r,country:n})]);return{...s,address:c}},redirect:async(e,{term:n,selectedFacets:t},r)=>{if(!n&&(!t||!t.length))return null;const{redirect:i}=await r.clients.search.products({page:1,count:1,query:n??void 0,selectedFacets:t?.flatMap(qe)??[],allowRedirect:!0});return{url:i}},sellers:async(e,{postalCode:n,geoCoordinates:t,country:r,salesChannel:i},a)=>{const{clients:{commerce:o}}=a,c=(await o.checkout.region({postalCode:n,geoCoordinates:t,country:r,salesChannel:i}))?.[0],{id:d,sellers:u}=c;return{id:d,sellers:u}},profile:async(e,{id:n},t)=>{const{clients:{commerce:r}}=t,i=await r.profile.addresses(n);function a(s){return!s||Object.keys(s).length===0?[]:Object.values(s).map(c=>JSON.parse(c))}return{addresses:a(i)}},productCount:async(e,{term:n},t)=>{const{clients:{search:r}}=t;return await r.productCount({query:n??void 0})},userOrder:async(e,{orderId:n},t)=>{try{if(!n)throw new T("Missing orderId");const{clients:{commerce:r}}=t,i=await r.oms.userOrder({orderId:n});if(!i)throw new N(`No order found for id ${n}`);let a=null;try{const c=await r.oms.getCommercialAuthorizationsByOrderId({orderId:n});a=En(c)}catch{}const s=(await r.masterData.getShopperById({userId:i.purchaseAgentData?.purchaseAgents?.[0]?.userId??""})??[])[0]??{};return{orderId:i.orderId,creationDate:i.creationDate,totals:i.totals,items:i.items,shippingData:i.shippingData,paymentData:i.paymentData,customData:i.customData,status:i.status,statusDescription:i.statusDescription,allowCancellation:i.allowCancellation,storePreferencesData:i.storePreferencesData,clientProfileData:i.clientProfileData,canProcessOrderAuthorization:(i.status==="waiting-for-confirmation"||i.status==="waiting-for-authorization")&&!!a,ruleForAuthorization:a,shopper:{firstName:s?.firstName||"",lastName:s?.lastName||"",email:s?.email||"",phone:s?.phone||""},budgetData:i.budgetData??{budgets:[]}}}catch(r){const i=r.message;let a={};try{const s=JSON.parse(i);a=s.error||s}catch{a={message:i}}const o=a?.message||i;throw x(r)?new N(`No order found for id ${n}. ${o}.`):In(r)?new j(`You are forbidden to interact with order with id ${n}. ${o}.`):r}},listUserOrders:async(e,n,t)=>{const{clients:{commerce:r}}=t,i=await r.oms.listUserOrders(n);return{list:i.list?.map(a=>({orderId:a.orderId,creationDate:a.creationDate,clientName:a.clientName,items:a.items,totalValue:a.totalValue,status:a.status,statusDescription:a.statusDescription,ShippingEstimatedDate:a.ShippingEstimatedDate,customFields:a.customFields,currencyCode:a.currencyCode})),paging:i.paging}},listCreditCards:async(e,n,t)=>{const{clients:{commerce:r}}=t;return{list:(await r.savedCards.listCreditCards())?.map(a=>({accountId:a.accountId,bin:a.bin,cardNumber:a.cardNumber,cardLabel:a.cardLabel,paymentSystem:a.paymentSystem,paymentSystemName:a.paymentSystemName,isDefault:a.isDefault,isActive:a.isActive,origin:a.origin}))}},hasAdHocCardAccess:async(e,n,t)=>{const{account:r,headers:i,clients:{commerce:a}}=t,s=z($(i?.cookie??"",r))?.userId??"";if(!s)return!0;const c=await a.licenseManager.isResourceGranted({userId:s,resourceKey:Ci}).catch(()=>null);return typeof c=="boolean"?c:!0},listUserQuotes:async(e,n,t)=>{const{clients:{commerce:r}}=t,i=await r.quotes.listUserQuotes(n),a=[...new Set(i.items.map(c=>c.createdBy).filter(Boolean))],o=new Map;return await Promise.all(a.map(async c=>{try{const[d]=await r.masterData.getShopperById({userId:c});if(d){const u=[d.firstName,d.lastName].filter(Boolean).join(" ");u&&o.set(c,u)}}catch{}})),{list:i.items.map(c=>({id:c.id,status:c.status,label:c.label??null,createdAt:c.createdAt,expiresAt:c.expiresAt,amount:c.amount,createdBy:c.createdBy?o.get(c.createdBy)??c.createdBy:null})),paging:{total:i.totalItems,currentPage:i.pageNumber,perPage:i.pageSize}}},validateUser:async(e,n,t)=>({isValid:!0}),isOrganizationMember:async(e,n,t)=>{const{clients:{commerce:r}}=t;return!!(await r.session("").catch(()=>null))?.namespaces.authentication?.unitId?.value},userDetails:async(e,n,t)=>{const{account:r,headers:i,clients:{commerce:a}}=t,s=z($(i?.cookie??"",r))?.userId??"",[c,d,u]=await Promise.all([a.session("").catch(()=>null),s?a.masterData.getShopperById({userId:s}).catch(()=>null):Promise.resolve(null),s?a.licenseManager.getUserRoles({userId:s}).catch(()=>null):Promise.resolve(null)]),p=d?.[0],f=c?.namespaces.authentication??null,h=`${(p?.firstName??"").trim()} ${(p?.lastName??"").trim()}`.trim();return{username:f?.storeUserEmail?.value??"",name:h,email:f?.storeUserEmail?.value??"",phone:p?.phone??"",role:u?.Roles?.map(v=>v.Name)??[],orgUnit:f?.unitName?.value??""}},accountProfile:async(e,n,t)=>{const{account:r,headers:i,clients:{commerce:a}}=t,o=z($(i?.cookie??"",r));if(!o?.userId)return null;if(o?.isRepresentative){const c=await a.session("").catch(()=>null);if(!c)return null;const d=c.namespaces.profile??null,u=c.namespaces.shopper??null,p=c.namespaces.authentication??null,f=Ke(c)||o?.customerId?.trim()||"";let h=null;if(f)try{h=await a.masterData.getContractById({contractId:f})}catch(g){console.error(`Error while getting contract data for contract ID (${f}).`,g)}const v=`${(u?.firstName?.value??"").trim()} ${(u?.lastName?.value??"").trim()}`.trim();return{name:Bn(h,d)||v||"",email:d?.email?.value||p?.storeUserEmail?.value||"",id:d?.id?.value||p?.customerId?.value||o?.customerId?.trim()||""}}const s=await a.licenseManager.getUserById({userId:o?.userId}).catch(()=>null);return{name:s?.name||"",email:s?.email||"",id:s?.id||""}},availableContracts:async(e,{orgUnitId:n},t)=>{if(!n)throw new T("Missing orgUnitId");const{account:r,headers:i,clients:{commerce:a}}=t,o=await a.session("").catch(()=>null),s=$(i?.cookie??"",r);let c=null;try{c=s?z(s):null}catch{c=null}const d=o?.namespaces.authentication?.unitId?.value?.trim()??c?.unitId?.trim()??"";if(!d||d!==n)throw new j("You are not allowed to list contracts for this organization unit");const u=Gr(o?.namespaces.shopper),p=Ke(o)||c?.customerId?.trim()||"";return Xr(u,p)},pickupPoints:async(e,{geoCoordinates:n},t)=>{const{clients:{commerce:r}}=t;return await r.checkout.pickupPoints({geoCoordinates:n})},orderEntryOperation:Ii,orderFormItems:vi,recommendations:yi},Pi={reviewRating:()=>({ratingValue:5,bestRating:5}),author:()=>({name:""})},Ei=(e,n,t)=>n?e.key==="category-1":t?e.key==="brand":!1,Ti={suggestions:async(e,n,t)=>{const{clients:{search:r}}=t,{searchArgs:i}=e;if(!i.query)return{terms:(await r.topSearches()).searches.map(p=>({value:p.term,count:p.count})),products:[]};const{productSearchPromise:a}=e,[o,s]=await Promise.all([r.suggestedTerms(i),a]),c=s.products.map(u=>{const p=ue(u.items);return p&&F(p,u)}).filter(u=>!!u),{searches:d}=o;return{terms:d.map(u=>({value:u.term,count:u.count})),products:c}},products:async({productSearchPromise:e})=>{const n=await e,t=n.products.map(r=>{const i=ue(r.items);return i&&F(i,r)}).filter(r=>!!r);return{pageInfo:{hasNextPage:n.pagination.after.length>0,hasPreviousPage:n.pagination.before.length>0,startCursor:"0",endCursor:n.recordsFiltered.toString(),totalCount:n.recordsFiltered},edges:t.map((r,i)=>({node:r,cursor:i.toString()}))}},facets:async({searchArgs:e},n,t)=>{const{clients:{search:r}}=t;t.storage.searchArgs=e;const{facets:i=[]}=await r.facets(e),a=!e.query,o=e.selectedFacets?.length?e.selectedFacets[0].key==="category-1":!1,s=e.selectedFacets?.length?e.selectedFacets[0].key==="brand":!1;return i.filter(d=>!a||!Ei(d,o,s))},metadata:async({productSearchPromise:e})=>{const n=await e;return{isTermMisspelled:n.correction?.misspelled??!1,logicalOperator:n.operator,fuzzy:n.fuzzy}},searchId:async({productSearchPromise:e})=>(await e).searchId},_i={title:({title:e})=>e??"",description:({description:e})=>e??"",canonical:({canonical:e})=>e??"",titleTemplate:()=>""},ki=["bd","d","h","m"],Ui=e=>ki.includes(e),Ri={bd:{0:"Today",1:"In 1 business day",other:"Up to # business days"},d:{0:"Today",1:"In 1 day",other:"Up to # days"},h:{0:"Now",1:"In 1 hour",other:"Up to # hours"},m:{0:"Now",1:"In 1 minute",other:"Up to # minutes"}},Vn=e=>{const[n,t]=[e.split(/\D+/)[0],e.split(/[0-9]+/)[1]],r=n!==""&&!Number.isNaN(Number(n)),i=Ui(t);if(!r||!i)return"";const a=Number(n)<2?Number(n):"other";return Ri[t][a].replace("#",n)??""},Fi={carrier:e=>e?.friendlyName??e?.name??"",price:e=>e?.price?e.price/100:e?.price,localizedEstimates:e=>e?.shippingEstimate?Vn(e.shippingEstimate):""},nn="skuvariation";function tn(e,n){const t=`${nn}${n}`.toLowerCase(),r=e.find(a=>a.imageLabel===t);if(r)return r;const i=e.find(a=>a.imageLabel===nn);return i||e[0]}function Ni(e,n,t){const r={};return e.forEach(i=>{const a=i.variations;if(a.length===0)return;const o=`${n}-${a.find(c=>c.name===n)?.values[0]??""}`,s=a.reduce((c,d)=>d.name===n?c:c+`-${d.name}-${d.values[0]}`,o);r[s]=`${t}-${i.itemId}`}),r}function rn(e){const n={};return e.forEach(t=>{n[t.name]=t.values[0]}),n}function Li(e){const n={};return e?.forEach(t=>{n[t.field.originalName??t.field.name]=t.values.map(r=>r.originalName??r.name)}),n}function Bi(e,n){return Number.isNaN(Number(e)-Number(n))?e<n?-1:e>n?1:0:Number(e)-Number(n)}function $i(e){const n=e;for(const t in e)e[t].every(i=>!Number.isNaN(Number(i.value)))&&e[t].sort((i,a)=>Bi(i.value,a.value));return n}function Mi(e,n,t){const r={},i=new Set;return e.forEach(a=>{if(a.variations.length===0)return;const o=a.variations.find(c=>c.name===n);if(!(o?.values[0]===t)){const c=`${n}-${o?.values[0]}`;if(!o||i.has(c))return;i.add(c);const d=tn(a.images,n),u={src:d.imageUrl,alt:d.imageLabel??"",label:`${n}: ${o.values[0]}`,value:o.values[0]};r[o.name]?r[o.name].push(u):r[o.name]=[u];return}a.variations.forEach(c=>{const d=`${c.name}-${c.values[0]}`;if(i.has(d))return;i.add(d);const u=tn(a.images,c.name),p={src:u.imageUrl,alt:u.imageText??"",label:`${c.name}: ${c.values[0]}`,value:c.values[0]};r[c.name]?r[c.name].push(p):r[c.name]=[p]})}),$i(r)}const zi={activeVariations:e=>rn(e.variations),allVariantsByName:e=>Li(e.isVariantOf.skuSpecifications),slugsMap:(e,n)=>Ni(e.isVariantOf.items,n.dominantVariantName??e.variations[0]?.name,e.isVariantOf.linkText),availableVariations:(e,n)=>{const t=n.dominantVariantName??e.variations[0]?.name,i=rn(e.variations)[t];return Mi(e.isVariantOf.items,t,i)},allVariantProducts:e=>e.isVariantOf.items.map(n=>F(n,e.isVariantOf))},qi={"pickup-in-point":"Pickup",delivery:"Delivery",pickup:"Pickup","take-away":"Take away","":""},Vi={deliveryOptionsData:e=>{const{shippingData:n,items:t}=e,r=n?.logisticsInfo||[],i=n?.selectedAddresses||n?.availableAddresses||[n?.address],a=r.reduce((d,u)=>{const p=u?.selectedSla||"",f=u?.selectedDeliveryChannel||u?.deliveryChannel||"",h=u?.deliveryCompany||"",v=u?.deliveryWindow,l=u?.pickupStoreInfo,g=u?.shippingEstimate||"",m=u?.shippingEstimate?Vn(u?.shippingEstimate):"",S=u?.shippingEstimateDate||"",O=u?.addressId||"",w=u?.itemIndex??0,b=t?.[w],_=b?.seller||"",I=`${p}|${f}|${h}|${_}|${g}|${S}|${O}|${v?.startDateUtc}|${v?.endDateUtc}`,D=i?.find(C=>C?.addressId===O),A=`${qi[f]||""} ${m} ${D?.neighborhood?`to ${D?.neighborhood}`:""}`.trim(),{taxPriceTagsTotal:E,taxPriceTags:P}=xi(b?.priceTags??[]),R=(b?.sellingPrice??0)*(b?.quantity??0)+(b?.tax??0)+(E??0);return d[I]||(d[I]={selectedSla:p,deliveryChannel:f,deliveryCompany:h,deliveryWindow:v,shippingEstimate:g,shippingEstimateDate:S,seller:_,friendlyShippingEstimate:m,friendlyDeliveryOptionName:A,address:D,pickupStoreInfo:l,quantityOfDifferentItems:0,total:0,items:[]}),d[I]&&(d[I].items?.push({id:b?.id||"",uniqueId:b?.uniqueId||"",name:b?.name||"",quantity:b?.quantity||0,price:b?.price||0,sellingPrice:b?.sellingPrice||0,imageUrl:b?.imageUrl||"",taxPriceTags:P??[],taxPriceTagsTotal:E??0,tax:b?.tax||0,total:R}),d[I].quantityOfDifferentItems=(d[I].quantityOfDifferentItems??0)+1,d[I].total=(d[I].total??0)+R),d},{}),o=Object.values(a),s=n?.contactInformation?.[0],c={name:`${s?.firstName??""} ${s?.lastName??""}`.trim()||o?.[0]?.address?.receiverName||"",email:s?.email||"",phone:s?.phone||""};return{deliveryOptions:o,contact:c}},customFields:e=>{const n=e?.customData?.customFields||[];return Object.values(n.reduce((t,r)=>{const i=r?.linkedEntity?.type||"",a=r?.linkedEntity?.id||"",o=`${i}|${a||""}`;return t[o]||(t[o]={type:i,id:a,fields:[]}),t[o].fields.push(...r?.fields||[]),t},{}))||[]}};function xi(e){const t=e.filter(i=>i?.name?.includes("TAX")),r=t.reduce((i,a)=>i+(a.rawValue?a.rawValue*100:0),0);return{taxPriceTags:t,taxPriceTagsTotal:r}}const ji={StoreCollection:An,StoreAggregateOffer:sr,StoreProduct:gi,StoreSeo:_i,StoreFacet:fr,StoreFacetBoolean:Sr,StoreFacetRange:yr,StoreFacetValueBoolean:Ir,StoreOffer:si,StoreAggregateRating:cr,StoreReview:Pi,StoreProductGroup:hi,StoreSearchResult:Ti,StorePropertyValue:fi,SkuVariants:zi,ShippingSLA:Fi,UserOrderResult:Vi,ObjectOrString:oi,Query:Ai,Mutation:ri},Wi=()=>ji,Gi=`"""
10
10
  Address information.
11
11
  """
12
12
  type Address {
@@ -51,7 +51,7 @@ type Address {
51
51
  """
52
52
  geoCoordinates: [Float]
53
53
  }
54
- `,Wi=`"""
54
+ `,Hi=`"""
55
55
  Advertisement information about a specific product in a campaign
56
56
  """
57
57
  type Advertisement {
@@ -76,7 +76,7 @@ type Advertisement {
76
76
  """
77
77
  adResponseId: String!
78
78
  }
79
- `,Gi=`"""
79
+ `,Xi=`"""
80
80
  Aggregate offer information, for a given SKU that is available to be fulfilled by multiple sellers.
81
81
  """
82
82
  type StoreAggregateOffer {
@@ -105,7 +105,7 @@ type StoreAggregateOffer {
105
105
  """
106
106
  offers: [StoreOffer!]!
107
107
  }
108
- `,Hi=`"""
108
+ `,Yi=`"""
109
109
  Average rating, based on multiple ratings or reviews.
110
110
  """
111
111
  type StoreAggregateRating {
@@ -118,7 +118,7 @@ type StoreAggregateRating {
118
118
  """
119
119
  reviewCount: Int!
120
120
  }
121
- `,Xi=`"""
121
+ `,Ji=`"""
122
122
  information about the author of a product review or rating.
123
123
  """
124
124
  type StoreAuthor {
@@ -127,7 +127,7 @@ type StoreAuthor {
127
127
  """
128
128
  name: String!
129
129
  }
130
- `,Yi=`"""
130
+ `,Ki=`"""
131
131
  Brand of a given product.
132
132
  """
133
133
  type StoreBrand {
@@ -136,7 +136,7 @@ type StoreBrand {
136
136
  """
137
137
  name: String!
138
138
  }
139
- `,Ji=`"""
139
+ `,Qi=`"""
140
140
  Item of a list.
141
141
  """
142
142
  type StoreListItem {
@@ -167,7 +167,7 @@ type StoreBreadcrumbList {
167
167
  """
168
168
  numberOfItems: Int!
169
169
  }
170
- `,Ki=`"""
170
+ `,Zi=`"""
171
171
  Shopping cart message.
172
172
  """
173
173
  type StoreCartMessage {
@@ -204,7 +204,7 @@ input IStoreCart {
204
204
  """
205
205
  order: IStoreOrder!
206
206
  }
207
- `,Qi=`"""
207
+ `,ea=`"""
208
208
  Product collection type. Possible values are \`Department\`, \`Category\`, \`Brand\` or \`Collection\`.
209
209
 
210
210
  \`SubCategory\` and \`Cluster\` are still declared for backward compatibility but are
@@ -319,7 +319,7 @@ type StoreCollectionLocale {
319
319
  """
320
320
  slug: String!
321
321
  }
322
- `,Zi=`"""
322
+ `,na=`"""
323
323
  Delivery Promise badge.
324
324
  """
325
325
  type DeliveryPromiseBadge {
@@ -328,7 +328,7 @@ type DeliveryPromiseBadge {
328
328
  """
329
329
  typeName: String
330
330
  }
331
- `,eo=`union StoreFacet = StoreFacetRange | StoreFacetBoolean
331
+ `,ta=`union StoreFacet = StoreFacetRange | StoreFacetBoolean
332
332
 
333
333
  """
334
334
  Search facet range information.
@@ -405,7 +405,7 @@ type StoreFacetValueBoolean {
405
405
  """
406
406
  quantity: Int
407
407
  }
408
- `,no=`"""
408
+ `,ra=`"""
409
409
  Image.
410
410
  """
411
411
  type StoreImage {
@@ -432,7 +432,7 @@ input IStoreImage {
432
432
  """
433
433
  alternateName: String!
434
434
  }
435
- `,to=`type Mutation {
435
+ `,ia=`type Mutation {
436
436
  """
437
437
  Checks for changes between the cart presented in the UI and the cart stored in the ecommerce platform. If changes are detected, it returns the cart stored on the platform. Otherwise, it returns \`null\`.
438
438
  """
@@ -474,7 +474,7 @@ input IStoreImage {
474
474
  """
475
475
  startRecommendationSession: Boolean!
476
476
  }
477
- `,ro=`"""
477
+ `,aa=`"""
478
478
  Newsletter information.
479
479
  """
480
480
  type PersonNewsletter {
@@ -497,8 +497,8 @@ input IPersonNewsletter {
497
497
  """
498
498
  email: String!
499
499
  }
500
- `,io=`scalar ObjectOrString
501
- `,oo=`"""
500
+ `,oa=`scalar ObjectOrString
501
+ `,sa=`"""
502
502
  Offer information.
503
503
  """
504
504
  type StoreOffer {
@@ -591,7 +591,7 @@ input IStoreOffer {
591
591
  """
592
592
  priceToken: String
593
593
  }
594
- `,ao=`"""
594
+ `,ca=`"""
595
595
  Information of a specific order.
596
596
  """
597
597
  type StoreOrder {
@@ -632,7 +632,7 @@ input IStoreOrder {
632
632
  """
633
633
  shouldSplitItem: Boolean
634
634
  }
635
- `,so=`"""
635
+ `,la=`"""
636
636
  Commercial Authorization response.
637
637
  """
638
638
  type CommercialAuthorizationResponse {
@@ -1031,7 +1031,7 @@ type ProcessOrderAuthorizationRule {
1031
1031
  """
1032
1032
  rule: CommercialAuthorizationRule!
1033
1033
  }
1034
- `,co=`"""
1034
+ `,da=`"""
1035
1035
  Input for uploading a file to the Order Entry Service.
1036
1036
  The file is transmitted as a Base64-encoded string so it can travel
1037
1037
  through the standard GraphQL JSON pipeline without multipart support.
@@ -1092,7 +1092,7 @@ type StoreOrderFormCartItem {
1092
1092
  seller: String!
1093
1093
  unitMultiplier: Float
1094
1094
  }
1095
- `,lo=`"""
1095
+ `,ua=`"""
1096
1096
  Organization.
1097
1097
  """
1098
1098
  type StoreOrganization {
@@ -1129,7 +1129,7 @@ type StoreContract {
1129
1129
  """
1130
1130
  isActive: Boolean!
1131
1131
  }
1132
- `,uo=`"""
1132
+ `,pa=`"""
1133
1133
  Whenever you make a query that allows for pagination, such as \`allProducts\` or \`allCollections\`, you can check \`StorePageInfo\` to learn more about the complete set of items and use it to paginate your queries.
1134
1134
  """
1135
1135
  type StorePageInfo {
@@ -1154,7 +1154,7 @@ type StorePageInfo {
1154
1154
  """
1155
1155
  totalCount: Int!
1156
1156
  }
1157
- `,po=`"""
1157
+ `,ga=`"""
1158
1158
  Input type for setting a new password.
1159
1159
  """
1160
1160
  input ISetPassword {
@@ -1197,7 +1197,7 @@ type SetPasswordResponse {
1197
1197
  """
1198
1198
  message: String
1199
1199
  }
1200
- `,go=`"""
1200
+ `,ma=`"""
1201
1201
  Client profile data.
1202
1202
  """
1203
1203
  type StorePerson {
@@ -1240,7 +1240,7 @@ input IStorePerson {
1240
1240
  """
1241
1241
  familyName: String!
1242
1242
  }
1243
- `,mo=`type PickupPointAddress {
1243
+ `,ha=`type PickupPointAddress {
1244
1244
  """
1245
1245
  Address city.
1246
1246
  """
@@ -1319,7 +1319,7 @@ type PickupPoints {
1319
1319
  """
1320
1320
  pickupPointsHash: String
1321
1321
  }
1322
- `,ho=`"""
1322
+ `,fa=`"""
1323
1323
  Product information. Products are variants within product groups, equivalent to VTEX [SKUs](https://help.vtex.com/en/tutorial/what-is-an-sku--1K75s4RXAQyOuGUYKMM68u#). For example, you may have a **Shirt** product group with associated products such as **Blue shirt size L**, **Green shirt size XL** and so on.
1324
1324
  """
1325
1325
  type StoreProduct {
@@ -1487,7 +1487,7 @@ input IStoreProduct {
1487
1487
  """
1488
1488
  additionalProperty: [IStorePropertyValue!]
1489
1489
  }
1490
- `,fo=`"""
1490
+ `,Sa=`"""
1491
1491
  Product group information. Product groups are catalog entities that may contain variants. They are equivalent to VTEX [Products](https://help.vtex.com/en/tutorial/what-is-a-product--2zrB2gFCHyQokCKKE8kuAw#), whereas each variant is equivalent to a VTEX [SKU](https://help.vtex.com/en/tutorial/what-is-an-sku--1K75s4RXAQyOuGUYKMM68u#). For example, you may have a **Shirt** product group with associated products such as **Blue shirt size L**, **Green shirt size XL** and so on.
1492
1492
  """
1493
1493
  type StoreProductGroup {
@@ -1514,7 +1514,7 @@ type StoreProductGroup {
1514
1514
  """
1515
1515
  skuVariants: SkuVariants
1516
1516
  }
1517
- `,So=`type Profile {
1517
+ `,ya=`type Profile {
1518
1518
  """
1519
1519
  Collection of user's address
1520
1520
  """
@@ -1575,7 +1575,7 @@ type ProfileAddress {
1575
1575
  """
1576
1576
  geoCoordinate: [Float]
1577
1577
  }
1578
- `,yo=`"""
1578
+ `,Ia=`"""
1579
1579
  Properties that can be associated with products and products groups.
1580
1580
  """
1581
1581
  type StorePropertyValue {
@@ -1615,7 +1615,7 @@ input IStorePropertyValue {
1615
1615
  """
1616
1616
  valueReference: ObjectOrString!
1617
1617
  }
1618
- `,Io=`"""
1618
+ `,va=`"""
1619
1619
  Each product edge contains a \`node\`, with product information, and a \`cursor\`, that can be used as a reference for pagination.
1620
1620
  """
1621
1621
  type StoreProductEdge {
@@ -2007,6 +2007,25 @@ type Query {
2007
2007
  @auth
2008
2008
  @cacheControl(scope: "private", sMaxAge: 300, staleWhileRevalidate: 3600)
2009
2009
 
2010
+ """
2011
+ Returns the list of saved credit cards for the current user.
2012
+ """
2013
+ listCreditCards: SavedCardListResult
2014
+ @auth
2015
+ @cacheControl(scope: "private", sMaxAge: 300, staleWhileRevalidate: 3600)
2016
+
2017
+ """
2018
+ Whether the current user holds the ad-hoc card platform permission, which
2019
+ gates personal card management for Unit/Contract-affiliated buyers.
2020
+
2021
+ Resolved from the user's roles by License Manager — it is not a session token
2022
+ claim. Fails open (\`true\`) when the permission service is unreachable, so an
2023
+ outage never locks buyers out of their own cards.
2024
+ """
2025
+ hasAdHocCardAccess: Boolean!
2026
+ @auth
2027
+ @cacheControl(scope: "private", sMaxAge: 60, staleWhileRevalidate: 300)
2028
+
2010
2029
  """
2011
2030
  Returns the list of Orders that the User can view.
2012
2031
  """
@@ -2245,7 +2264,7 @@ type StoreAccountProfile {
2245
2264
  email: String
2246
2265
  id: String
2247
2266
  }
2248
- `,vo=`"""
2267
+ `,Oa=`"""
2249
2268
  Summary of a quote returned in list results.
2250
2269
  """
2251
2270
  type UserQuoteSummary {
@@ -2310,7 +2329,7 @@ type UserQuoteListPaging {
2310
2329
  """
2311
2330
  perPage: Int!
2312
2331
  }
2313
- `,Oo=`type RecommendationResponse {
2332
+ `,Ca=`type RecommendationResponse {
2314
2333
  products: [StoreProduct!]!
2315
2334
  correlationId: String!
2316
2335
  campaign: RecommendationCampaign!
@@ -2321,7 +2340,7 @@ type RecommendationCampaign {
2321
2340
  title: String
2322
2341
  type: String!
2323
2342
  }
2324
- `,Co=`"""
2343
+ `,ba=`"""
2325
2344
  Information of a given review rating.
2326
2345
  """
2327
2346
  type StoreReviewRating {
@@ -2348,7 +2367,71 @@ type StoreReview {
2348
2367
  """
2349
2368
  author: StoreAuthor!
2350
2369
  }
2351
- `,bo=`"""
2370
+ `,wa=`"""
2371
+ Whether a saved card is personally owned by the buyer or shared by their
2372
+ Organization/Contract. Resolved server-side by the Saved-cards service from
2373
+ the buyer's \`useAdHocCard\` role — never inferred client-side.
2374
+ """
2375
+ enum CardOrigin {
2376
+ personal
2377
+ shared
2378
+ }
2379
+
2380
+ """
2381
+ A saved payment card returned by the Saved-cards service.
2382
+ """
2383
+ type SavedCard {
2384
+ """
2385
+ Account identifier that owns the card.
2386
+ """
2387
+ accountId: String
2388
+ """
2389
+ First digits of the card (BIN).
2390
+ """
2391
+ bin: String
2392
+ """
2393
+ Masked card number, per PCI display rules.
2394
+ """
2395
+ cardNumber: String
2396
+ """
2397
+ Buyer- or admin-assigned nickname for the card (e.g. "Team lunch card"), when
2398
+ the Saved-cards service has one on file. Absent for most cards — callers
2399
+ should fall back to \`paymentSystemName\` for display.
2400
+ """
2401
+ cardLabel: String
2402
+ """
2403
+ Numeric payment system identifier.
2404
+ """
2405
+ paymentSystem: String
2406
+ """
2407
+ Human-readable payment system name (e.g. Visa, Mastercard).
2408
+ """
2409
+ paymentSystemName: String
2410
+ """
2411
+ Whether this card is the account default.
2412
+ """
2413
+ isDefault: Boolean
2414
+ """
2415
+ Whether this card is active.
2416
+ """
2417
+ isActive: Boolean
2418
+ """
2419
+ Whether this card is personally owned by the buyer or shared by their
2420
+ Organization/Contract.
2421
+ """
2422
+ origin: CardOrigin!
2423
+ }
2424
+
2425
+ """
2426
+ Result of listing the current user's saved credit cards.
2427
+ """
2428
+ type SavedCardListResult {
2429
+ """
2430
+ The list of saved credit cards.
2431
+ """
2432
+ list: [SavedCard!]
2433
+ }
2434
+ `,Da=`"""
2352
2435
  Search Engine Optimization (SEO) tags data.
2353
2436
  """
2354
2437
  type StoreSeo {
@@ -2369,7 +2452,7 @@ type StoreSeo {
2369
2452
  """
2370
2453
  canonical: String!
2371
2454
  }
2372
- `,wo=`"""
2455
+ `,Aa=`"""
2373
2456
  Currency information.
2374
2457
  """
2375
2458
  type StoreCurrency {
@@ -2644,7 +2727,7 @@ input IStoreSession {
2644
2727
  """
2645
2728
  refreshAfter: String
2646
2729
  }
2647
- `,Do=`"""
2730
+ `,Pa=`"""
2648
2731
  Shipping Simulation item input.
2649
2732
  """
2650
2733
  input IShippingItem {
@@ -2975,7 +3058,7 @@ type MessageFields {
2975
3058
  """
2976
3059
  skuName: String
2977
3060
  }
2978
- `,Po=`type SkuVariants {
3061
+ `,Ea=`type SkuVariants {
2979
3062
  """
2980
3063
  SKU property values for the current SKU.
2981
3064
  """
@@ -3070,7 +3153,7 @@ Example:
3070
3153
  \`\`\`
3071
3154
  """
3072
3155
  scalar FormattedVariants
3073
- `,Ao=`"""
3156
+ `,Ta=`"""
3074
3157
  Status used to indicate a message type. For instance, a shopping cart informative or error message.
3075
3158
  """
3076
3159
  enum StoreStatus {
@@ -3078,7 +3161,7 @@ enum StoreStatus {
3078
3161
  WARNING
3079
3162
  ERROR
3080
3163
  }
3081
- `,Eo=`scalar JSONObject
3164
+ `,_a=`scalar JSONObject
3082
3165
 
3083
3166
  type UserOrder {
3084
3167
  orderId: String
@@ -3902,4 +3985,4 @@ type UserOrderBudgetAllocationLinkedEntity {
3902
3985
  type: String
3903
3986
  id: String
3904
3987
  }
3905
- `,To=Object.assign({"./address.graphql":ji,"./advertisement.graphql":Wi,"./aggregateOffer.graphql":Gi,"./aggregateRating.graphql":Hi,"./author.graphql":Xi,"./brand.graphql":Yi,"./breadcrumb.graphql":Ji,"./cart.graphql":Ki,"./collection.graphql":Qi,"./deliveryPromisesBadge.graphql":Zi,"./facet.graphql":eo,"./image.graphql":no,"./mutation.graphql":to,"./newsletter.graphql":ro,"./objectOrString.graphql":io,"./offer.graphql":oo,"./order.graphql":ao,"./orderCommercialAuthorizaton.graphql":so,"./orderEntry.graphql":co,"./organization.graphql":lo,"./pageInfo.graphql":uo,"./password.graphql":po,"./person.graphql":go,"./pickupPoints.graphql":mo,"./product.graphql":ho,"./productGroup.graphql":fo,"./profile.graphql":So,"./propertyValue.graphql":yo,"./query.graphql":Io,"./quote.graphql":vo,"./recommendation.graphql":Oo,"./review.graphql":Co,"./seo.graphql":bo,"./session.graphql":wo,"./shipping.graphql":Do,"./skuVariants.graphql":Po,"./status.graphql":Ao,"./userOrder.graphql":Eo}),Uo=se.print(Object.values(To).map(e=>se.parse(e)).reduce((e,n)=>on.mergeTypeDefs([e,n],{sort:!0}))),Vn=Uo,ko=async e=>n=>(n.storage={channel:te.parse(e.channel),flags:e.flags??{},locale:e.locale,cookies:new Map},n.account=e.account,n.OTEL_ENABLED=e.OTEL_ENABLED,n.discoveryConfig=e.discoveryConfig,n.clients=Gt(e,n),n.loaders=tr(e,n),n);function _o(){const e=xi(),n={};for(const[t,r]of Object.entries(e))n[t]=Object.fromEntries(Object.entries(r).map(([i,o])=>typeof o!="function"?[i,o]:[i,tt(o,`${t}(${i})`)]));return n}function Ro(e){const t=hn([mn,gn])(_o(),Vn);return e&&se.isSchema(e)?an.mergeSchemas({schemas:[t,e]}):t}exports.AuthDirective=gn;exports.BadRequestError=T;exports.CacheControlDirective=mn;exports.CommercialAuthorizationStatus=sn;exports.FastStoreError=W;exports.ForbiddenError=x;exports.GraphqlVtexContextFactory=ko;exports.GraphqlVtexSchema=Ro;exports.NotFoundError=N;exports.StoreCollectionType=cn;exports.StoreFacetType=ln;exports.StoreSort=dn;exports.StoreStatus=un;exports.UnauthorizedError=K;exports.UserOrderInvoiceType=pn;exports.isBadRequestError=it;exports.isFastStoreError=rt;exports.isForbiddenError=yn;exports.isNotFoundError=q;exports.isUnauthorizedError=ot;exports.stringifyCacheControl=Zn;exports.typeDefs=Vn;exports.withDirectives=hn;
3988
+ `,ka=Object.assign({"./address.graphql":Gi,"./advertisement.graphql":Hi,"./aggregateOffer.graphql":Xi,"./aggregateRating.graphql":Yi,"./author.graphql":Ji,"./brand.graphql":Ki,"./breadcrumb.graphql":Qi,"./cart.graphql":Zi,"./collection.graphql":ea,"./deliveryPromisesBadge.graphql":na,"./facet.graphql":ta,"./image.graphql":ra,"./mutation.graphql":ia,"./newsletter.graphql":aa,"./objectOrString.graphql":oa,"./offer.graphql":sa,"./order.graphql":ca,"./orderCommercialAuthorizaton.graphql":la,"./orderEntry.graphql":da,"./organization.graphql":ua,"./pageInfo.graphql":pa,"./password.graphql":ga,"./person.graphql":ma,"./pickupPoints.graphql":ha,"./product.graphql":fa,"./productGroup.graphql":Sa,"./profile.graphql":ya,"./propertyValue.graphql":Ia,"./query.graphql":va,"./quote.graphql":Oa,"./recommendation.graphql":Ca,"./review.graphql":ba,"./savedCard.graphql":wa,"./seo.graphql":Da,"./session.graphql":Aa,"./shipping.graphql":Pa,"./skuVariants.graphql":Ea,"./status.graphql":Ta,"./userOrder.graphql":_a}),Ua=se.print(Object.values(ka).map(e=>se.parse(e)).reduce((e,n)=>an.mergeTypeDefs([e,n],{sort:!0}))),xn=Ua,Ra=async e=>n=>(n.storage={channel:te.parse(e.channel),flags:e.flags??{},locale:e.locale,cookies:new Map},n.account=e.account,n.OTEL_ENABLED=e.OTEL_ENABLED,n.discoveryConfig=e.discoveryConfig,n.clients=Ht(e,n),n.loaders=rr(e,n),n);function Fa(){const e=Wi(),n={};for(const[t,r]of Object.entries(e))n[t]=Object.fromEntries(Object.entries(r).map(([i,a])=>typeof a!="function"?[i,a]:[i,rt(a,`${t}(${i})`)]));return n}function Na(e){const t=fn([hn,mn])(Fa(),xn);return e&&se.isSchema(e)?on.mergeSchemas({schemas:[t,e]}):t}exports.AuthDirective=mn;exports.BadRequestError=T;exports.CacheControlDirective=hn;exports.CardOrigin=sn;exports.CommercialAuthorizationStatus=cn;exports.FastStoreError=G;exports.ForbiddenError=j;exports.GraphqlVtexContextFactory=Ra;exports.GraphqlVtexSchema=Na;exports.NotFoundError=N;exports.StoreCollectionType=ln;exports.StoreFacetType=dn;exports.StoreSort=un;exports.StoreStatus=pn;exports.UnauthorizedError=Q;exports.UserOrderInvoiceType=gn;exports.isBadRequestError=at;exports.isFastStoreError=it;exports.isForbiddenError=In;exports.isNotFoundError=x;exports.isUnauthorizedError=ot;exports.stringifyCacheControl=et;exports.typeDefs=xn;exports.withDirectives=fn;