@faststore/api 4.0.1-dev.2 → 4.1.0-dev.1

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,9 +1,9 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const xn=require("@graphql-tools/merge"),jn=require("@graphql-tools/schema"),j=require("@graphql-tools/utils"),L=require("@faststore/diagnostics"),nn=require("graphql"),rn=require("cookie"),Ae=require("isomorphic-unfetch"),an=require("dataloader"),Wn=require("p-limit"),Pe=require("sanitize-html"),Cn=require("fast-deep-equal"),ke=require("node:crypto");var Gn=(n=>(n.Accepted="accepted",n.Denied="denied",n.Pending="pending",n))(Gn||{}),Hn=(n=>(n.Brand="Brand",n.Category="Category",n.Cluster="Cluster",n.Collection="Collection",n.Department="Department",n.SubCategory="SubCategory",n))(Hn||{}),Xn=(n=>(n.Boolean="BOOLEAN",n.Range="RANGE",n))(Xn||{}),Yn=(n=>(n.DiscountDesc="discount_desc",n.NameAsc="name_asc",n.NameDesc="name_desc",n.OrdersDesc="orders_desc",n.PriceAsc="price_asc",n.PriceDesc="price_desc",n.ReleaseDesc="release_desc",n.ScoreDesc="score_desc",n))(Yn||{}),Jn=(n=>(n.Error="ERROR",n.Info="INFO",n.Warning="WARNING",n))(Jn||{}),Kn=(n=>(n.Input="Input",n.Output="Output",n))(Kn||{});const Ue=()=>function(e={}){const t=process.env.FS_DISCOVERY_APP_KEY??"",r=process.env.FS_DISCOVERY_APP_TOKEN??"";if(!t||!r)throw new K("No authentication AppKey and AppToken passed.");return{...e,"X-VTEX-API-AppKey":t,"X-VTEX-API-AppToken":r}},_e=async n=>{const{clients:{commerce:e}}=n;try{if((await e.vtexid.validate())?.authStatus?.toLowerCase()!=="success")throw new J("Authentication required")}catch(t){const r=t.extensions?.status??t.status;throw r===401?new J("Authentication required"):r===403?new K("You are not allowed to access this resource"):new J("Authentication required")}},Te="auth",Qn={typeDefs:"directive @auth on FIELD_DEFINITION",transformer:n=>j.mapSchema(n,{[j.MapperKind.OBJECT_FIELD]:e=>{if(j.getDirective(n,e,Te)?.[0]){const r=e.resolve;e.resolve=async(i,a,o,s)=>(await _e(o),r?.(i,a,o,s))}return e}})},Ee="cacheControl",Ne=(n,e)=>{const{scope:t="private",sMaxAge:r=0,staleWhileRevalidate:i=0}=n;return`${e?"private":t}, s-maxage=${r}, stale-while-revalidate=${i}`},An=(n,e)=>typeof n=="number"&&typeof e=="number"?n>e?e:n:typeof n=="number"?n:e,Fe=(n,e)=>typeof n=="string"&&typeof e=="string"?n==="public"&&e==="public"?"public":"private":n||e,Zn={typeDefs:"directive @cacheControl(sMaxAge: Int, staleWhileRevalidate: Int, scope: String) on FIELD_DEFINITION",transformer:n=>j.mapSchema(n,{[j.MapperKind.OBJECT_FIELD]:e=>{const t=j.getDirective(n,e,Ee)?.[0];if(t){const{sMaxAge:r,staleWhileRevalidate:i,scope:a}=t,o=e.resolve;e.resolve=(s,c,d,p)=>(d.cacheControl={sMaxAge:An(d.cacheControl?.sMaxAge,r),staleWhileRevalidate:An(d.cacheControl?.staleWhileRevalidate,i),scope:Fe(d.cacheControl?.scope,a)},o?.(s,c,d,p))}return e}})},ne=n=>(e,t)=>{const r=xn.mergeTypeDefs([...(n??[]).map(({typeDefs:i})=>i),t]);return(n??[]).reduce((i,{transformer:a})=>a?.(i)??i,jn.makeExecutableSchema({typeDefs:r,resolvers:e}))},cn="@faststore/api",ln="4.0.1-dev.1",Pn={name:cn,version:ln},Re=(n,e)=>(t,r,i,a)=>{if((i?.OTEL?.enabled??!1)===!1)return n(t,r,i,a);const o=L.OTELAPI.trace.getTracer(cn,ln),s=L.OTELAPI.propagation.extract(L.OTELAPI.context.active(),i.OTEL);return L.OTELAPI.context.with(s,()=>{const c=o.startSpan(e??"Unknown Graphql Resolver",{startTime:Date.now(),kind:L.OTELAPI.SpanKind.INTERNAL,attributes:{timestamp:Date.now(),"@faststore_version":ln,"@faststore_package_name":cn,"@faststore_account_name":i.account,"@faststore_environment":process.env.NODE_ENV}});if(!c)return n(t,r,i,a);try{const d=n(t,r,i,a);return d instanceof Promise?d.then(p=>(c.end(),p)):(c.end(),d)}catch(d){throw c.end(),console.error(`Error when executing resolver: ${e}`,d),d}})};class H extends Error{constructor(e,t){super(t),this.extensions=e,this.name="FastStoreError"}}class $ extends H{constructor(e){super({status:400,type:"BadRequestError"},e)}}class J extends H{constructor(e){super({status:401,type:"UnauthorizedError"},e)}}class K extends H{constructor(e){super({status:403,type:"ForbiddenError"},e)}}class B extends H{constructor(e){super({status:404,type:"NotFoundError"},e)}}const Le=n=>n?.name==="FastStoreError",Be=n=>n?.extensions?.type==="BadRequestError",Me=n=>n?.extensions?.type==="UnauthorizedError",ee=n=>n?.extensions?.type==="ForbiddenError",te=n=>n?.extensions?.type==="NotFoundError",$e=`${Pn.name}@${Pn.version}`,I=async(n,e,t)=>{const r=await Ae(n,{...e,headers:{...e?.headers??{},"User-Agent":$e}});if(r.ok)return t?.storeCookies&&t.storeCookies(r.headers),r.status!==204?r.json():void 0;console.error(n,e,r);const i=await r.text();if(typeof r?.status=="number")switch(r.status){case 400:throw new $(i);case 401:throw new J(i);case 403:throw new K(i);case 404:throw new B(i);default:throw new H({status:r.status,type:"UnknownError"},i)}throw new Error(i)},re=n=>{if(!n)return n;const e=new Map,t=n.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);e.has(s)||r.push(s),e.set(s,c)}}}),r.map(i=>`${i}=${e.get(i)}`).join("; ")},ze=/^([^=]+)=([^;]*)/,Ve=(n,e)=>{const t=e.match(ze);if(t){const r=t[1],i=t[2];n.storage.cookies.set(r,{value:i,setCookie:e})}},qe=(n,e)=>{e.getSetCookie().forEach(t=>Ve(n,t))},xe=n=>e=>qe(n,e),je=n=>{if(!n.headers?.cookie)return null;const e=re(n.headers.cookie),t=Array.from(n.storage.cookies.entries());return t.length===0?e:t.reduce((r,[i,{value:a}])=>Ge(r,i,a),e)},bn=n=>function(t){const r=je(n);return r?{...t,cookie:r}:t},Dn=(n,e)=>{const t=re(n);return rn.parse(t)[`VtexIdclientAutCookie_${e}`]||""},We=n=>{const e=bn(n);return function(r,i){const a=e({"content-type":"application/json","X-FORWARDED-HOST":r}),o=Dn(n?.headers?.cookie??"",i);return a.VtexIdclientAutCookie=o,a}},Ge=(n,e,t)=>{const r=new RegExp(`(${e})=([^;]*)`),i=n.match(r);return i?n.replace(i[0],`${i[1]}=${t}`):`${n};${e}=${t}`};function wn(n){return n?JSON.parse(Buffer.from(n.split(".")[1],"base64").toString()):null}const Y={method:"POST",headers:{"content-type":"application/json"}},He=({account:n,environment:e,incrementAddress:t,subDomainPrefix:r},i)=>{const a=`https://${n}.${e}.com.br`,o=xe(i),s=bn(i),c=We(i),d=Ue(),p=new Headers(i.headers).get("x-forwarded-host")??i.headers?.host??"",m=r&&r.map(l=>l+".").find(l=>p.includes(l))||"",u=p.replace(m,"");return{catalog:{salesChannel:l=>I(`${a}/api/catalog_system/pub/saleschannel/${l}`,void 0,{storeCookies:o}),brand:{list:()=>I(`${a}/api/catalog_system/pub/brand/list`,void 0,{storeCookies:o})},category:{tree:(l=3)=>I(`${a}/api/catalog_system/pub/category/tree/${l}`,void 0,{storeCookies:o})},portal:{pagetype:l=>I(`${a}/api/catalog_system/pub/portal/pagetype/${l}`,void 0,{storeCookies:o})},products:{crossselling:({type:l,productId:g,groupByProduct:f=!0})=>{const S=new URLSearchParams({sc:i.storage.channel.salesChannel,groupByProduct:f.toString()});return I(`${a}/api/catalog_system/pub/products/crossselling/${l}/${g}?${S}`,void 0,{storeCookies:o})}}},checkout:{simulation:(l,{salesChannel:g}=i.storage.channel)=>{const f=new URLSearchParams({sc:g}),S=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${a}/api/checkout/pub/orderForms/simulation?${f.toString()}`,{...Y,headers:S,body:JSON.stringify(l)},{storeCookies:o})},shippingData:({id:l,index:g,deliveryMode:f,selectedAddresses:S},O)=>{const D=O?{startDateUtc:f?.deliveryWindow?.startDate,endDateUtc:f?.deliveryWindow?.endDate}:null,A={logisticsInfo:Array.from({length:g},(v,k)=>({itemIndex:k,selectedDeliveryChannel:f?.deliveryChannel||null,selectedSla:f?.deliveryMethod||null,deliveryWindow:D})),selectedAddresses:S,clearAddressIfPostalCodeNotFound:t},T=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${a}/api/checkout/pub/orderForm/${l}/attachments/shippingData`,{...Y,headers:T,body:JSON.stringify(A)},{storeCookies:o})},marketingData:({id:l,marketingData:g})=>{const f=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${a}/api/checkout/pub/orderForm/${l}/attachments/marketingData`,{headers:f,body:JSON.stringify(g),method:"POST"},{storeCookies:o})},clientPreferencesData:({id:l,clientPreferencesData:g})=>{const f=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${a}/api/checkout/pub/orderForm/${l}/attachments/clientPreferencesData`,{headers:f,body:JSON.stringify(g),method:"POST"},{storeCookies:o})},orderForm:({id:l,refreshOutdatedData:g=!0,channel:f=i.storage.channel})=>{const{salesChannel:S}=f,O=s({"content-type":"application/json","X-FORWARDED-HOST":u}),D=new URLSearchParams({sc:S});l&&D.set("refreshOutdatedData",g.toString());const A=`${a}/api/checkout/pub/orderForm${l?`/${l}`:""}?${D.toString()}`;return I(A,{...Y,headers:O,...l?{}:{body:"{}"}},{storeCookies:o})},clearOrderFormMessages:({id:l})=>{const g=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${a}/api/checkout/pub/orderForm/${l}/messages/clear`,{...Y,headers:g,body:"{}"})},updateOrderFormItems:({id:l,orderItems:g,allowOutdatedData:f="paymentData",salesChannel:S=i.storage.channel.salesChannel,shouldSplitItem:O=!0})=>{const D=new URLSearchParams({allowOutdatedData:f,sc:S}),A=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${a}/api/checkout/pub/orderForm/${l}/items?${D}`,{headers:A,body:JSON.stringify({orderItems:g,noSplitItem:!O}),method:"PATCH"},{storeCookies:o})},setCustomData:({id:l,appId:g,key:f,value:S})=>{const O=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${a}/api/checkout/pub/orderForm/${l}/customData/${g}/${f}`,{headers:O,body:JSON.stringify({value:S}),method:"PUT"})},region:async({postalCode:l,geoCoordinates:g,country:f,salesChannel:S})=>{const O=new URLSearchParams({country:f,sc:S??""});l?O.append("postalCode",l):O.append("geoCoordinates",`${g?.longitude};${g?.latitude}`);const D=`${a}/api/checkout/pub/regions/?${O.toString()}`,A=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(D,{headers:A},{storeCookies:o})},address:async({postalCode:l,country:g})=>{const f=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${a}/api/checkout/pub/postal-code/${g}/${l}`,{headers:f},{storeCookies:o})},cancelOrder:({orderId:l,customerEmail:g,reason:f})=>{const S=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${a}/api/checkout/pub/orders/${l}/user-cancel-request`,{method:"POST",headers:S,body:JSON.stringify({customerEmail:g,reason:f})},{})},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":u});return I(`${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,shopper.firstName,shopper.lastName,shopper.organizationManager,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 f=s({"content-type":"application/json"}),S=rn.parse(i?.headers?.cookie??"")?.vtex_session;return I(`${a}/api/sessions?${g.toString()}`,{method:S?"PATCH":"POST",headers:f,body:"{}"},{storeCookies:o})},subscribeToNewsletter:l=>I(`${a}/api/dataentities/NL/documents/`,{...Y,body:JSON.stringify({...l,isNewsletterOptIn:!0}),method:"PATCH"},{storeCookies:o}),profile:{addresses:async l=>{const g=c(u,n);return I(`${a}/api/profile-system/pvt/profiles/${l}/addresses`,{headers:g},{storeCookies:o})}},oms:{userOrder:({orderId:l})=>{const g=c(u,n);return I(`${a}/api/oms/user/orders/${l}`,{method:"GET",headers:g},{storeCookies:o})},listUserOrders:({page:l,status:g,dateInitial:f,dateFinal:S,text:O,clientEmail:D,perPage:A,pendingMyApproval:T})=>{const v=new URLSearchParams;if(f){const h=new Date(f).setHours(0,0,0,0);f=new Date(h).toISOString()}if(S){const h=new Date(S).setHours(23,59,59,999);S=new Date(h).toISOString()}O&&v.append("text",O),g&&g.length>0&&v.append("status",g.filter(Boolean).join(",")),f&&S?v.append("creation_date",`creationDate:[${f} TO ${S}]`):f?v.append("creation_date",`creationDate:[${f} TO *]`):S&&v.append("creation_date",`creationDate:[* TO ${S}]`),D&&v.append("clientEmail",D),l&&v.append("page",l.toString()),A&&v.append("per_page",A.toString()),T&&v.append("my_pending_approvals",String(!0));const k=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${a}/api/oms/user/orders?${v.toString()}`,{method:"GET",headers:k},{storeCookies:o})},getCommercialAuthorizationsByOrderId:({orderId:l})=>{const g=c(u,n);return I(`${a}/${n}/commercial-authorizations/order/${l}`,{method:"GET",headers:g},{storeCookies:o})},processOrderAuthorization:async({orderAuthorizationId:l,dimensionId:g,ruleId:f,approved:S})=>{const O=c(u,n),T={params:{ruleId:f,dimensionId:g,score:S?100:0}};return I(`${a}/${n}/commercial-authorizations/${l}/callback`,{method:"POST",headers:O,body:JSON.stringify(T)},{storeCookies:o})}},units:{getUnitByUserId:({userId:l})=>{const g=c(u,n);return I(`${a}/api/units/v1/${l}/unit`,{method:"GET",headers:g},{})},getOrgUnitById:({orgUnitId:l})=>{const g=c(u,n);return I(`${a}/api/units/v1/${l}`,{method:"GET",headers:g},{})},getScopesByOrgUnit:({orgUnitId:l})=>{const g=c(u,n);return I(`${a}/api/units/v1/${l}/scopes`,{method:"GET",headers:g},{})}},licenseManager:{getUserById:({userId:l})=>{const g=c(u,n);return I(`${a}/api/license-manager/users/${l}`,{method:"GET",headers:g},{})},getUserByEmail:({email:l})=>{const g=c(u,n);return I(`${a}/api/license-manager/pvt/users/${l}`,{method:"GET",headers:g},{})}},masterData:{getContractById:({contractId:l})=>{if(!l)throw new $("Missing contractId to fetch CL fields.");const g=d({Accept:"application/json","content-type":"application/json","X-FORWARDED-HOST":u});return I(`${a}/api/dataentities/CL/documents/${l}?_fields=_all`,{method:"GET",headers:g},{})},getShopperById:({userId:l})=>{if(!l)throw new $("Missing userId to fetch shopper name.");const g=d({Accept:"application/json","content-type":"application/json","X-FORWARDED-HOST":u}),f=l.replace(/-/g,"");return I(`${a}/api/dataentities/shopper/search?_where=(userId=${f} OR userId=${l})&_fields=_all&_schema=v1`,{method:"GET",headers:g},{})}},vtexid:{validate:()=>{const l=c(u,n);return I(`${a}/api/vtexid/credential/validate`,{headers:l,body:JSON.stringify({token:l.VtexIdclientAutCookie}),method:"POST"},{storeCookies:o})}}}},dn="trade-policy",un="region-id",pn="fuzzy",gn="operator",mn="pickupPoint",ie="shipping",ae="delivery-options",oe="in-stock",Xe=new Set([dn,un,pn,gn,mn,ie,ae,oe]),Ye=n=>n.key==="fuzzy"&&(n.value==="0"||n.value==="1"||n.value==="auto"),Je=n=>n.key==="operator"&&(n.value==="and"||n.value==="or"),Ke=({account:n,environment:e,hideUnavailableItems:t,simulationBehavior:r,showSponsored:i,subDomainPrefix:a},o)=>{const s=`https://${n}.${e}.com.br/api/io`,c=bn(o),d=new Headers(o.headers).get("x-forwarded-host")??o.headers?.host??"",p=a&&a.map(h=>h+".").find(h=>d.includes(h))||"",m=d.replace(p,""),u=c({"content-type":"application/json","X-FORWARDED-HOST":m}),l=()=>{const{salesChannel:h}=o.storage.channel;return h?{key:dn,value:h}:null},g=()=>{const{regionId:h,seller:C}=o.storage.channel,U=(C?Buffer.from(`SW#${C}`).toString("base64"):null)??h;return U?{key:un,value:U}:null},f=h=>{const C=h.filter(({key:P})=>!Xe.has(P)),b=h.find(({key:P,value:E})=>P===ie&&E!=="all-delivery-methods")??null,U=h.find(({key:P,value:E})=>P===ae&&E!=="all-delivery-options")??null,y=h.find(({key:P})=>P===dn)??l(),w=h.find(({key:P})=>P===un)??g();return b!==null&&C.push(b),U!==null&&C.push(U),y!==null&&C.push(y),w!==null&&C.push(w),C},S=(h,C)=>{const b=h.find(({key:w})=>w===pn)??null,U=h.find(({key:w})=>w===gn)??null,y=h.find(({key:w})=>w===mn)??null;b&&Ye(b)&&C.append(pn,b.value),U&&Je(U)&&C.append(gn,U.value),y&&C.append(mn,y.value)},O=({query:h="",page:C,count:b,sort:U="",selectedFacets:y=[],type:w,showInvisibleItems:P,sponsoredCount:E,hideUnavailableItems:_,allowRedirect:X=!1})=>{const N=new URLSearchParams({page:(C+1).toString(),count:b!==0?b.toString():"1",query:h,sort:U,locale:o.storage.locale});if(S(y,N),P&&N.append("show-invisible-items","true"),t!==void 0){const q=y.find(({key:we})=>we===oe),on=q?q.value:_?.toString()??t.toString();N.append("hideUnavailableItems",on)}r!==void 0&&N.append("simulationBehavior",r.toString()),i!==void 0&&N.append("showSponsored",i.toString()),E!==void 0&&N.append("sponsoredCount",E.toString()),X!==void 0&&N.append("allowRedirect",X.toString());const z=f(y).map(({key:q,value:on})=>`${q}/${on}`).join("/");return I(`${s}/_v/api/intelligent-search/${w}/${z}?${N.toString()}`,{headers:u})};return{facets:h=>O({...h,type:"facets"}),products:h=>O({...h,type:"product_search"}),suggestedTerms:h=>{const C=new URLSearchParams({query:h.query?.toString()??"",locale:o.storage.locale});return I(`${s}/_v/api/intelligent-search/search_suggestions?${C.toString()}`,{headers:u})},topSearches:()=>{const h=new URLSearchParams({locale:o.storage.locale});return I(`${s}/_v/api/intelligent-search/top_searches?${h.toString()}`,{headers:u})},productCount:h=>{const C=new URLSearchParams;return h?.query&&C.append("query",h.query.toString()),I(`${s}/_v/api/intelligent-search/catalog_count?${C.toString()}`,{headers:u})}}},Qe=(n,e)=>{const t=Ke(n,e),r=He(n,e);return{search:t,commerce:r}},Ze=20,nt=new Set(["brand","category","department","subcategory","collection","cluster"]),W=n=>typeof n.pageType=="string"&&nt.has(n.pageType.toLowerCase()),et=(n,e)=>{const t=Wn(Ze),r=async i=>Promise.all(i.map(a=>t(async()=>{const o=await e.commerce.catalog.portal.pagetype(a);if(W(o))return o;throw new B(`Catalog returned ${o.pageType} for slug: ${a}. This usually happens when there is more than one category with the same name in the same category tree level.`)})));return new an(r,{batch:!1})},tt=(n,e)=>{const t=async r=>Promise.all(r.map(i=>e.commerce.catalog.salesChannel(i)));return new an(t)},rt=1,it=(n,e)=>{const t=Wn(rt),r=async a=>{const o=a.reduce((m,{items:u})=>[...m,u],[]),s=[...o.flat()],c=await e.commerce.checkout.simulation({country:a[0].country,postalCode:a[0].postalCode,items:s}),d=c.items.reduce((m,u)=>{const l=u.requestIndex;return typeof l=="number"&&l<m.length&&(m[l]=u),m},Array(s.length).fill(null)),p=o.reduce((m,u)=>[...m,u.length+m[m.length-1]],[0]);return o.map((m,u)=>({...c,items:d.slice(p[u],p[u+1]).filter(l=>!!l)}))},i=async a=>t(r,a);return new an(i,{maxBatchSize:50})},at=(n,e)=>Pe(n,e);function ot(n){return{...n,description:n.description?at(n.description):n.description}}const M=(n,e)=>({...n,isVariantOf:ot(e)}),st=({flags:n},e)=>{const t=async r=>{const i=r.map(p=>p.split("-")[0]),a=r.some(p=>p.split("-")[1]==="invisibleItems"),{products:o}=await e.search.products({query:`sku:${i.join(";")}`,page:0,count:i.length,showInvisibleItems:a,...n?.enableUnavailableItemsOnCart&&{hideUnavailableItems:!1}}),s=o.reduce((p,m)=>{for(const u of m.items)p[u.itemId]=M(u,m);return p},{}),c=i.map(p=>s[p]),d=i.filter(p=>!s[p]);if(d.length>0)throw new B(`Search API did not found the following skus: ${d.join(",")}`);return c};return new an(t,{maxBatchSize:99})},ct=(n,{clients:e})=>{const t=st(n,e),r=it(n,e),i=et(n,e),a=tt(n,e);return{skuLoader:t,simulationLoader:r,collectionLoader:i,salesChannelLoader:a}},V=n=>n.AvailableQuantity>0,G=n=>n.spotPrice??0,lt=n=>n.Price??0,kn=n=>n?"https://schema.org/InStock":"https://schema.org/OutOfStock",se=(n,e)=>V(n)&&!V(e)?-1:!V(n)&&V(e)?1:G(n)-G(e),dt=n=>n==="available",x=(n,e=0,t=1)=>{const r=e/t;return Math.round((n+r)*100)/100},ut=(n,e={includeTaxes:!1})=>{const t=n.filter(V),r=t[t.length-1],i=r?G(r):0;return e.includeTaxes?x(i,r?.Tax,r?.product?.unitMultiplier):i},Un=(n,e={includeTaxes:!1})=>{const[t]=n.filter(V),r=t?G(t):0;return e.includeTaxes?x(r,t?.Tax,t?.product?.unitMultiplier):r},pt={highPrice:n=>ut(n),lowPrice:n=>Un(n),lowPriceWithTaxes:n=>Un(n,{includeTaxes:!0}),offerCount:n=>n.length,priceCurrency:async(n,e,t)=>{const{loaders:{salesChannelLoader:r},storage:{channel:i}}=t;return(await r.load(i.salesChannel)).CurrencyCode??""},offers:n=>n},gt={ratingValue:()=>5,reviewCount:()=>0},_n="ÁÄÂÀÃÅČÇĆĎÉĚËÈÊẼĔȆÍÌÎÏŇÑÓÖÒÔÕØŘŔŠŤÚŮÜÙÛÝŸŽáäâàãåčçćďéěëèêẽĕȇíìîïňñóöòôõøðřŕšťúůüùûýÿžþÞĐđ߯a",mt="AAAAAACCCDEEEEEEEEIIIINNOOOOOORRSTUUUUUYYZaaaaaacccdeeeeeeeeiiiinnooooooorrstuuuuuyyzbBDdBAa",ht=n=>{let e=n.slice(0);for(let t=0;t<_n.length;t++)e=e.replace(new RegExp(_n.charAt(t),"g"),mt.charAt(t));return e},ft=n=>n.replace(/[·/_,:]/,"-");function ce(n){const t=n.replace(/,/g,"").replace(/[*+~.()'"!:@&\[\]`/ %$#?{}><=_^]/g,"-");return ft(ht(t)).toLowerCase()}const Z=n=>n.type==="brand"||W(n)&&n.pageType.toLowerCase()==="brand",hn=n=>W(n)&&n.pageType.toLowerCase()==="collection",sn=n=>Z(n)||hn(n)?ce(n.name):W(n)?new URL(`https://${n.url}`).pathname.slice(1).toLowerCase():new URL(n.url).pathname.slice(1).toLowerCase(),le={id:({id:n})=>n.toString(),slug:n=>sn(n),seo:n=>Z(n)||W(n)?{title:n.title??n.name,description:n.metaTagDescription}:{title:n.Title,description:n.MetaTagDescription},type:n=>Z(n)?"Brand":W(n)?n.pageType:n.level===0?"Department":"Category",meta:n=>{const e=sn(n);return Z(n)?{selectedFacets:[{key:"brand",value:e}]}:hn(n)?{selectedFacets:[{key:"productclusterids",value:n.id}]}:{selectedFacets:e.split("/").map((t,r)=>({key:`category-${r+1}`,value:t}))}},breadcrumbList:async(n,e,t)=>{const{loaders:{collectionLoader:r}}=t,a=sn(n).split("/").filter(c=>!!c),o=a.map((c,d)=>a.slice(0,d+1).join("/")),s=await Promise.all(o.map(async c=>{const d=await r.load(c);return{slug:c,...d}}));return{itemListElement:s.map((c,d)=>({item:hn(c)?`/${c.slug}`:new URL(`https://${c.url}`).pathname.toLowerCase(),name:c.name,position:d+1})),numberOfItems:s.length}}},de={buy:"whoboughtalsobought",view:"whosawalsosaw",similars:"similars",viewAndBought:"whosawalsobought",accessories:"accessories",suggestions:"suggestions"},Tn=({key:n,value:e})=>{switch(n){case"price":return{key:n,value:e.replace("-to-",":")};case"channel":case"locale":case"buy":case"view":case"similars":case"viewAndBought":case"accessories":case"suggestions":return[];default:return{key:n,value:e}}},En=n=>{const e=n.split(":").map(Number);return e.length!==2||Number.isNaN(e[0])||Number.isNaN(e[1])?null:e},St=n=>typeof de[n]=="string",yt=n=>{const e=n?.filter(t=>St(t.key));if(Array.isArray(e)&&e.length>1)throw new $(`You passed ${e.length} cross selling facets but only one is allowed. Please leave one of the following facet: ${e.map(t=>t.key).join(",")}`);return e?.[0]??null},It=n=>n?.find(e=>e.key==="slug")?.value??null,vt=n=>n?.find(e=>e.key==="id")?.value??null,Nn=n=>n?.find(e=>e.key==="locale")?.value??null,Fn=n=>n?.find(e=>e.key==="channel")?.value??null,fn=(n,e)=>{let t=0;for(let r=1;r<n.length;r++)e(n[t],n[r])>0&&(t=r);return n[t]},Ot={__resolveType:({type:n,values:e})=>n!=="TEXT"&&n!=="DELIVERY"?"StoreFacetRange":!e||e.length===0?"StoreFacetBoolean":e.every(t=>t.range)?"StoreFacetRange":"StoreFacetBoolean"},Ct={key:({key:n})=>n,label:({name:n})=>n,values:({values:n})=>n.sort((e,t)=>e.name.localeCompare(t.name))},bt={key:({key:n})=>n,label:({name:n})=>n,min:({values:n,key:e},t,{storage:{searchArgs:r}})=>{const i=En(r?.selectedFacets?.find(s=>s.key===e)?.value??""),o=fn(n,(s,c)=>s.range.from-c.range.from)?.range?.from??0;return{selected:i?.[0]??o,absolute:o}},max:({values:n,key:e},t,{storage:{searchArgs:r}})=>{const i=En(r?.selectedFacets?.find(s=>s.key===e)?.value??""),o=fn(n,(s,c)=>c.range.to-s.range.to)?.range?.to??0;return{selected:i?.[1]??o,absolute:o}}},Dt={value:({value:n})=>n,label:({name:n})=>n||"unknown",selected:({selected:n})=>n,quantity:({quantity:n})=>n},wt=async(n,{data:e},{clients:{commerce:t}})=>{if(!e?.orderId)throw new $("Missing orderId");return{data:(await t.checkout.cancelOrder(e))?.data}};function ue(n){if(!n||n.status!=="pending")return null;for(const e of n.dimensionStatus){if(e.status!=="pending")continue;const t=e.ruleCollection.find(r=>r.status==="pending"&&r.isUserNextAuthorizer);if(t)return{rule:t,orderAuthorizationId:n.id,dimensionId:e.id}}return null}function At(n){if(!n||n.status!=="pending")return!1;const e=n.dimensionStatus.filter(t=>t.status==="pending").flatMap(t=>t.ruleCollection).filter(t=>t.status==="pending");return e.length===0?!1:e.every(t=>!t.isUserNextAuthorizer)}const Pt=async(n,{data:e},{clients:{commerce:t}})=>{const r=await t.oms.processOrderAuthorization(e),i=ue(r);return{isPendingForOtherAuthorizer:!i&&At(r),ruleForAuthorization:i}},kt=async(n,{data:e},{clients:{commerce:t}})=>({id:(await t.subscribeToNewsletter(e))?.Id});class en{static parse(e){try{const t=JSON.parse(e);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(e){return JSON.stringify(e)}}const Sn=(n,e)=>{n.storage.channel=en.parse(e)},yn=(n,e)=>{n.storage.locale=e},pe=n=>ke.createHash("md5").update(n).digest("hex"),Q={attachment:"ATTACHMENT",specification:"SPECIFICATION",attribute:"ATTRIBUTE"};function ge(n){return{name:n.name,value:n.content,valueReference:Q.attachment}}function Ut(n){return{propertyID:n.id,name:n.name,value:n.value,valueReference:{valueReference:Q.attribute,visible:n.visible}}}function me(n){return pe(`${n.name}:${JSON.stringify(n.value)}:${n.valueReference}`)}const _t=n=>{const e=n.postalCode,t=n.geoCoordinates,r={addressType:n.addressType||null,postalCode:e||null,city:null,state:null,country:n.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]},Tt=(n,e,t)=>{const r=e.postalCode,i=e.geoCoordinates,a=n?.shippingData?.availableAddresses??[],o=n?.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},he=(n,e)=>{if(!Et(e))return{updateShipping:!1,addressChanged:!1};if(!Lt(n))return{updateShipping:!1,addressChanged:!1};const[t]=n?.shippingData?.selectedAddresses??[];if(Nt(t,e.postalCode)||Ft(t,e.geoCoordinates)||Rt(t,e.addressType))return{updateShipping:!0,addressChanged:!0};const{logisticsInfo:r}=n.shippingData;return Bt(r,e)?{updateShipping:!0,addressChanged:!1}:{updateShipping:!1,addressChanged:!1}},Et=n=>!!n.postalCode||n.geoCoordinates?.latitude&&n.geoCoordinates?.longitude,Nt=(n,e)=>typeof e=="string"&&n?.postalCode!==e,Ft=(n,e)=>typeof e?.latitude=="number"&&typeof e?.longitude=="number"&&(n?.geoCoordinates[0]!==e?.longitude||n?.geoCoordinates[1]!==e?.latitude),Rt=(n,e)=>typeof e=="string"&&n?.addressType!==e,Lt=n=>n.items.length!==0,Bt=(n,e)=>{const t=e?.deliveryMode?.deliveryChannel,r=e?.deliveryMode?.deliveryMethod,{startDate:i,endDate:a}=e?.deliveryMode?.deliveryWindow||{};return n.some(({selectedDeliveryChannel:o,selectedSla:s,slas:c})=>{const d=t&&o!==t,p=r&&s!==r;return c?.some(m=>d&&m.deliveryChannel===t||p&&m.id===r?!0:i&&a&&m.deliveryChannel===t&&m.id===r&&(!m?.deliveryWindow||m?.deliveryWindow?.startDateUtc!==i||m?.deliveryWindow?.endDateUtc!==a)&&m.availableDeliveryWindows?.some(u=>u?.startDateUtc===i&&u?.endDateUtc===a))})},fe=n=>n.valueReference===Q.attachment,In=n=>[n.itemOffered.sku,n.seller.identifier,n.price<.01?"Gift":void 0,n.itemOffered.additionalProperty?.filter(fe).map(me).join("-")].filter(Boolean).join("::"),tn=(n,e)=>({listPrice:n.listPrice/100,price:n.sellingPrice/100,quantity:n.quantity,seller:{identifier:n.seller},itemOffered:{sku:n.id,image:[],name:n.name,additionalProperty:n.attachments.map(ge)},index:e}),Mt=n=>({quantity:n.quantity,seller:n.seller.identifier,id:n.itemOffered.sku,index:n.index,attachments:(n.itemOffered.additionalProperty?.filter(fe)??[]).map(e=>({name:e.name,content:e.value}))}),Rn=n=>n.reduce((e,t)=>{const r=In(t);return e.has(r)||e.set(r,[]),e.get(r)?.push(t),e},new Map),$t=(n,e)=>{const t=(s,c)=>({...s,itemOffered:{sku:s.itemOffered.sku},index:c}),r=e.items.map(tn).map(t),i=n.acceptedOffer.map(t),a=n.orderNumber===e.orderFormId,o=Cn(r,i);return a&&o};function Se(n,e){return n?.some(t=>t.parentItemIndex!==null&&t.parentItemIndex!==void 0&&n[t.parentItemIndex]?.id===e)}function ye(n,e){return n?.some(t=>t.id===e&&t.parentItemIndex!==null)}const Ln=n=>{const e=n.items.reduce((t,r,i)=>{const a=ye(n.items,r.id)||Se(n.items,r.id)?`${In(tn(r))}::${i}`:In(tn(r));return t[a]||(t[a]=[]),t[a].push(r),t},{});return{...n,items:Object.values(e).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}})}},Bn=async(n,e,t)=>({order:{orderNumber:n.orderFormId,acceptedOffer:n.items.map(async r=>({...r,product:await e.load(`${r.id}-invisibleItems`)})),shouldSplitItem:t},messages:n.messages.map(({text:r,status:i})=>({text:r,status:i.toUpperCase()}))}),Ie=({items:n},e)=>{const t=n.map(r=>({id:r.id,quantity:r.quantity,seller:r.seller,attachments:r.attachments}));return pe(JSON.stringify({sessionId:e?.id??"",items:t}))},Mn=async(n,e,t)=>{try{return await e.checkout.setCustomData({id:n.orderFormId,appId:"faststore",key:"cartEtag",value:Ie(n,t)})}catch(r){throw console.error(`Error while setting custom data to orderForm.
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const xn=require("@graphql-tools/merge"),jn=require("@graphql-tools/schema"),j=require("@graphql-tools/utils"),L=require("@faststore/diagnostics"),nn=require("graphql"),on=require("cookie"),Ae=require("isomorphic-unfetch"),sn=require("dataloader"),Wn=require("p-limit"),Pe=require("sanitize-html"),Dn=require("fast-deep-equal"),Ue=require("node:crypto");var Gn=(n=>(n.Accepted="accepted",n.Denied="denied",n.Pending="pending",n))(Gn||{}),Hn=(n=>(n.Brand="Brand",n.Category="Category",n.Cluster="Cluster",n.Collection="Collection",n.Department="Department",n.SubCategory="SubCategory",n))(Hn||{}),Xn=(n=>(n.Boolean="BOOLEAN",n.Range="RANGE",n))(Xn||{}),Yn=(n=>(n.DiscountDesc="discount_desc",n.NameAsc="name_asc",n.NameDesc="name_desc",n.OrdersDesc="orders_desc",n.PriceAsc="price_asc",n.PriceDesc="price_desc",n.ReleaseDesc="release_desc",n.ScoreDesc="score_desc",n))(Yn||{}),Jn=(n=>(n.Error="ERROR",n.Info="INFO",n.Warning="WARNING",n))(Jn||{}),Kn=(n=>(n.Input="Input",n.Output="Output",n))(Kn||{});const ke=()=>function(e={}){const t=process.env.FS_DISCOVERY_APP_KEY??"",r=process.env.FS_DISCOVERY_APP_TOKEN??"";if(!t||!r)throw new K("No authentication AppKey and AppToken passed.");return{...e,"X-VTEX-API-AppKey":t,"X-VTEX-API-AppToken":r}},Te=async n=>{const{clients:{commerce:e}}=n;try{if((await e.vtexid.validate())?.authStatus?.toLowerCase()!=="success")throw new J("Authentication required")}catch(t){const r=t.extensions?.status??t.status;throw r===401?new J("Authentication required"):r===403?new K("You are not allowed to access this resource"):new J("Authentication required")}},_e="auth",Qn={typeDefs:"directive @auth on FIELD_DEFINITION",transformer:n=>j.mapSchema(n,{[j.MapperKind.OBJECT_FIELD]:e=>{if(j.getDirective(n,e,_e)?.[0]){const r=e.resolve;e.resolve=async(i,a,o,s)=>(await Te(o),r?.(i,a,o,s))}return e}})},Ee="cacheControl",Ne=(n,e)=>{const{scope:t="private",sMaxAge:r=0,staleWhileRevalidate:i=0}=n;return`${e?"private":t}, s-maxage=${r}, stale-while-revalidate=${i}`},An=(n,e)=>typeof n=="number"&&typeof e=="number"?n>e?e:n:typeof n=="number"?n:e,Fe=(n,e)=>typeof n=="string"&&typeof e=="string"?n==="public"&&e==="public"?"public":"private":n||e,Zn={typeDefs:"directive @cacheControl(sMaxAge: Int, staleWhileRevalidate: Int, scope: String) on FIELD_DEFINITION",transformer:n=>j.mapSchema(n,{[j.MapperKind.OBJECT_FIELD]:e=>{const t=j.getDirective(n,e,Ee)?.[0];if(t){const{sMaxAge:r,staleWhileRevalidate:i,scope:a}=t,o=e.resolve;e.resolve=(s,c,d,p)=>(d.cacheControl={sMaxAge:An(d.cacheControl?.sMaxAge,r),staleWhileRevalidate:An(d.cacheControl?.staleWhileRevalidate,i),scope:Fe(d.cacheControl?.scope,a)},o?.(s,c,d,p))}return e}})},ne=n=>(e,t)=>{const r=xn.mergeTypeDefs([...(n??[]).map(({typeDefs:i})=>i),t]);return(n??[]).reduce((i,{transformer:a})=>a?.(i)??i,jn.makeExecutableSchema({typeDefs:r,resolvers:e}))},dn="@faststore/api",un="4.1.0-dev.0",Pn={name:dn,version:un},Re=(n,e)=>(t,r,i,a)=>{if((i?.OTEL?.enabled??!1)===!1)return n(t,r,i,a);const o=L.OTELAPI.trace.getTracer(dn,un),s=L.OTELAPI.propagation.extract(L.OTELAPI.context.active(),i.OTEL);return L.OTELAPI.context.with(s,()=>{const c=o.startSpan(e??"Unknown Graphql Resolver",{startTime:Date.now(),kind:L.OTELAPI.SpanKind.INTERNAL,attributes:{timestamp:Date.now(),"@faststore_version":un,"@faststore_package_name":dn,"@faststore_account_name":i.account,"@faststore_environment":process.env.NODE_ENV}});if(!c)return n(t,r,i,a);try{const d=n(t,r,i,a);return d instanceof Promise?d.then(p=>(c.end(),p)):(c.end(),d)}catch(d){throw c.end(),console.error(`Error when executing resolver: ${e}`,d),d}})};class H extends Error{constructor(e,t){super(t),this.extensions=e,this.name="FastStoreError"}}class $ extends H{constructor(e){super({status:400,type:"BadRequestError"},e)}}class J extends H{constructor(e){super({status:401,type:"UnauthorizedError"},e)}}class K extends H{constructor(e){super({status:403,type:"ForbiddenError"},e)}}class B extends H{constructor(e){super({status:404,type:"NotFoundError"},e)}}const Le=n=>n?.name==="FastStoreError",Be=n=>n?.extensions?.type==="BadRequestError",Me=n=>n?.extensions?.type==="UnauthorizedError",ee=n=>n?.extensions?.type==="ForbiddenError",te=n=>n?.extensions?.type==="NotFoundError",$e=`${Pn.name}@${Pn.version}`,I=async(n,e,t)=>{const r=await Ae(n,{...e,headers:{...e?.headers??{},"User-Agent":$e}});if(r.ok)return t?.storeCookies&&t.storeCookies(r.headers),r.status!==204?r.json():void 0;console.error(n,e,r);const i=await r.text();if(typeof r?.status=="number")switch(r.status){case 400:throw new $(i);case 401:throw new J(i);case 403:throw new K(i);case 404:throw new B(i);default:throw new H({status:r.status,type:"UnknownError"},i)}throw new Error(i)},re=n=>{if(!n)return n;const e=new Map,t=n.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);e.has(s)||r.push(s),e.set(s,c)}}}),r.map(i=>`${i}=${e.get(i)}`).join("; ")},ze=/^([^=]+)=([^;]*)/,Ve=(n,e)=>{const t=e.match(ze);if(t){const r=t[1],i=t[2];n.storage.cookies.set(r,{value:i,setCookie:e})}},qe=(n,e)=>{e.getSetCookie().forEach(t=>Ve(n,t))},xe=n=>e=>qe(n,e),je=n=>{if(!n.headers?.cookie)return null;const e=re(n.headers.cookie),t=Array.from(n.storage.cookies.entries());return t.length===0?e:t.reduce((r,[i,{value:a}])=>Ge(r,i,a),e)},wn=n=>function(t){const r=je(n);return r?{...t,cookie:r}:t},en=(n,e)=>{const t=re(n);return on.parse(t)[`VtexIdclientAutCookie_${e}`]||""},We=n=>{const e=wn(n);return function(r,i){const a=e({"content-type":"application/json","X-FORWARDED-HOST":r}),o=en(n?.headers?.cookie??"",i);return a.VtexIdclientAutCookie=o,a}},Ge=(n,e,t)=>{const r=new RegExp(`(${e})=([^;]*)`),i=n.match(r);return i?n.replace(i[0],`${i[1]}=${t}`):`${n};${e}=${t}`};function tn(n){return n?JSON.parse(Buffer.from(n.split(".")[1],"base64").toString()):null}const Y={method:"POST",headers:{"content-type":"application/json"}},He=({account:n,environment:e,incrementAddress:t,subDomainPrefix:r},i)=>{const a=`https://${n}.${e}.com.br`,o=xe(i),s=wn(i),c=We(i),d=ke(),p=new Headers(i.headers).get("x-forwarded-host")??i.headers?.host??"",m=r&&r.map(l=>l+".").find(l=>p.includes(l))||"",u=p.replace(m,"");return{catalog:{salesChannel:l=>I(`${a}/api/catalog_system/pub/saleschannel/${l}`,void 0,{storeCookies:o}),brand:{list:()=>I(`${a}/api/catalog_system/pub/brand/list`,void 0,{storeCookies:o})},category:{tree:(l=3)=>I(`${a}/api/catalog_system/pub/category/tree/${l}`,void 0,{storeCookies:o})},portal:{pagetype:l=>I(`${a}/api/catalog_system/pub/portal/pagetype/${l}`,void 0,{storeCookies:o})},products:{crossselling:({type:l,productId:g,groupByProduct:f=!0})=>{const S=new URLSearchParams({sc:i.storage.channel.salesChannel,groupByProduct:f.toString()});return I(`${a}/api/catalog_system/pub/products/crossselling/${l}/${g}?${S}`,void 0,{storeCookies:o})}}},checkout:{simulation:(l,{salesChannel:g}=i.storage.channel)=>{const f=new URLSearchParams({sc:g}),S=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${a}/api/checkout/pub/orderForms/simulation?${f.toString()}`,{...Y,headers:S,body:JSON.stringify(l)},{storeCookies:o})},shippingData:({id:l,index:g,deliveryMode:f,selectedAddresses:S},O)=>{const D=O?{startDateUtc:f?.deliveryWindow?.startDate,endDateUtc:f?.deliveryWindow?.endDate}:null,A={logisticsInfo:Array.from({length:g},(v,U)=>({itemIndex:U,selectedDeliveryChannel:f?.deliveryChannel||null,selectedSla:f?.deliveryMethod||null,deliveryWindow:D})),selectedAddresses:S,clearAddressIfPostalCodeNotFound:t},_=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${a}/api/checkout/pub/orderForm/${l}/attachments/shippingData`,{...Y,headers:_,body:JSON.stringify(A)},{storeCookies:o})},marketingData:({id:l,marketingData:g})=>{const f=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${a}/api/checkout/pub/orderForm/${l}/attachments/marketingData`,{headers:f,body:JSON.stringify(g),method:"POST"},{storeCookies:o})},clientPreferencesData:({id:l,clientPreferencesData:g})=>{const f=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${a}/api/checkout/pub/orderForm/${l}/attachments/clientPreferencesData`,{headers:f,body:JSON.stringify(g),method:"POST"},{storeCookies:o})},orderForm:({id:l,refreshOutdatedData:g=!0,channel:f=i.storage.channel})=>{const{salesChannel:S}=f,O=s({"content-type":"application/json","X-FORWARDED-HOST":u}),D=new URLSearchParams({sc:S});l&&D.set("refreshOutdatedData",g.toString());const A=`${a}/api/checkout/pub/orderForm${l?`/${l}`:""}?${D.toString()}`;return I(A,{...Y,headers:O,...l?{}:{body:"{}"}},{storeCookies:o})},clearOrderFormMessages:({id:l})=>{const g=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${a}/api/checkout/pub/orderForm/${l}/messages/clear`,{...Y,headers:g,body:"{}"})},updateOrderFormItems:({id:l,orderItems:g,allowOutdatedData:f="paymentData",salesChannel:S=i.storage.channel.salesChannel,shouldSplitItem:O=!0})=>{const D=new URLSearchParams({allowOutdatedData:f,sc:S}),A=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${a}/api/checkout/pub/orderForm/${l}/items?${D}`,{headers:A,body:JSON.stringify({orderItems:g,noSplitItem:!O}),method:"PATCH"},{storeCookies:o})},setCustomData:({id:l,appId:g,key:f,value:S})=>{const O=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${a}/api/checkout/pub/orderForm/${l}/customData/${g}/${f}`,{headers:O,body:JSON.stringify({value:S}),method:"PUT"})},region:async({postalCode:l,geoCoordinates:g,country:f,salesChannel:S})=>{const O=new URLSearchParams({country:f,sc:S??""});l?O.append("postalCode",l):O.append("geoCoordinates",`${g?.longitude};${g?.latitude}`);const D=`${a}/api/checkout/pub/regions/?${O.toString()}`,A=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(D,{headers:A},{storeCookies:o})},address:async({postalCode:l,country:g})=>{const f=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${a}/api/checkout/pub/postal-code/${g}/${l}`,{headers:f},{storeCookies:o})},cancelOrder:({orderId:l,customerEmail:g,reason:f})=>{const S=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${a}/api/checkout/pub/orders/${l}/user-cancel-request`,{method:"POST",headers:S,body:JSON.stringify({customerEmail:g,reason:f})},{})},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":u});return I(`${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,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 f=s({"content-type":"application/json"}),S=on.parse(i?.headers?.cookie??"")?.vtex_session;return I(`${a}/api/sessions?${g.toString()}`,{method:S?"PATCH":"POST",headers:f,body:"{}"},{storeCookies:o})},subscribeToNewsletter:l=>I(`${a}/api/dataentities/NL/documents/`,{...Y,body:JSON.stringify({...l,isNewsletterOptIn:!0}),method:"PATCH"},{storeCookies:o}),profile:{addresses:async l=>{const g=c(u,n);return I(`${a}/api/profile-system/pvt/profiles/${l}/addresses`,{headers:g},{storeCookies:o})}},oms:{userOrder:({orderId:l})=>{const g=c(u,n);return I(`${a}/api/oms/user/orders/${l}`,{method:"GET",headers:g},{storeCookies:o})},listUserOrders:({page:l,status:g,dateInitial:f,dateFinal:S,text:O,clientEmail:D,perPage:A,pendingMyApproval:_})=>{const v=new URLSearchParams;if(f){const h=new Date(f).setHours(0,0,0,0);f=new Date(h).toISOString()}if(S){const h=new Date(S).setHours(23,59,59,999);S=new Date(h).toISOString()}O&&v.append("text",O),g&&g.length>0&&v.append("status",g.filter(Boolean).join(",")),f&&S?v.append("creation_date",`creationDate:[${f} TO ${S}]`):f?v.append("creation_date",`creationDate:[${f} TO *]`):S&&v.append("creation_date",`creationDate:[* TO ${S}]`),D&&v.append("clientEmail",D),l&&v.append("page",l.toString()),A&&v.append("per_page",A.toString()),_&&v.append("my_pending_approvals",String(!0));const U=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${a}/api/oms/user/orders?${v.toString()}`,{method:"GET",headers:U},{storeCookies:o})},getCommercialAuthorizationsByOrderId:({orderId:l})=>{const g=c(u,n);return I(`${a}/${n}/commercial-authorizations/order/${l}`,{method:"GET",headers:g},{storeCookies:o})},processOrderAuthorization:async({orderAuthorizationId:l,dimensionId:g,ruleId:f,approved:S})=>{const O=c(u,n),_={params:{ruleId:f,dimensionId:g,score:S?100:0}};return I(`${a}/${n}/commercial-authorizations/${l}/callback`,{method:"POST",headers:O,body:JSON.stringify(_)},{storeCookies:o})}},units:{getUnitByUserId:({userId:l})=>{const g=c(u,n);return I(`${a}/api/units/v1/${l}/unit`,{method:"GET",headers:g},{})},getOrgUnitById:({orgUnitId:l})=>{const g=c(u,n);return I(`${a}/api/units/v1/${l}`,{method:"GET",headers:g},{})},getScopesByOrgUnit:({orgUnitId:l})=>{const g=c(u,n);return I(`${a}/api/units/v1/${l}/scopes`,{method:"GET",headers:g},{})}},licenseManager:{getUserById:({userId:l})=>{const g=c(u,n);return I(`${a}/api/license-manager/users/${l}`,{method:"GET",headers:g},{})},getUserByEmail:({email:l})=>{const g=c(u,n);return I(`${a}/api/license-manager/pvt/users/${l}`,{method:"GET",headers:g},{})},getUserRoles:({userId:l})=>{const g=c(u,n);return I(`${a}/api/license-manager/storefront/users/${l}/roles`,{method:"GET",headers:g},{})}},masterData:{getContractById:({contractId:l})=>{if(!l)throw new $("Missing contractId to fetch CL fields.");const g=d({Accept:"application/json","content-type":"application/json","X-FORWARDED-HOST":u});return I(`${a}/api/dataentities/CL/documents/${l}?_fields=_all`,{method:"GET",headers:g},{})},getShopperById:({userId:l})=>{if(!l)throw new $("Missing userId to fetch shopper name.");const g=d({Accept:"application/json","content-type":"application/json","X-FORWARDED-HOST":u}),f=l.replace(/-/g,"");return I(`${a}/api/dataentities/shopper/search?_where=(userId=${f} OR userId=${l})&_fields=_all&_schema=v1`,{method:"GET",headers:g},{})}},vtexid:{validate:()=>{const l=c(u,n);return I(`${a}/api/vtexid/credential/validate`,{headers:l,body:JSON.stringify({token:l.VtexIdclientAutCookie}),method:"POST"},{storeCookies:o})}}}},pn="trade-policy",gn="region-id",mn="fuzzy",hn="operator",fn="pickupPoint",ie="shipping",ae="delivery-options",oe="in-stock",Xe=new Set([pn,gn,mn,hn,fn,ie,ae,oe]),Ye=n=>n.key==="fuzzy"&&(n.value==="0"||n.value==="1"||n.value==="auto"),Je=n=>n.key==="operator"&&(n.value==="and"||n.value==="or"),Ke=({account:n,environment:e,hideUnavailableItems:t,simulationBehavior:r,showSponsored:i,subDomainPrefix:a},o)=>{const s=`https://${n}.${e}.com.br/api/io`,c=wn(o),d=new Headers(o.headers).get("x-forwarded-host")??o.headers?.host??"",p=a&&a.map(h=>h+".").find(h=>d.includes(h))||"",m=d.replace(p,""),u=c({"content-type":"application/json","X-FORWARDED-HOST":m}),l=()=>{const{salesChannel:h}=o.storage.channel;return h?{key:pn,value:h}:null},g=()=>{const{regionId:h,seller:C}=o.storage.channel,k=(C?Buffer.from(`SW#${C}`).toString("base64"):null)??h;return k?{key:gn,value:k}:null},f=h=>{const C=h.filter(({key:P})=>!Xe.has(P)),b=h.find(({key:P,value:E})=>P===ie&&E!=="all-delivery-methods")??null,k=h.find(({key:P,value:E})=>P===ae&&E!=="all-delivery-options")??null,y=h.find(({key:P})=>P===pn)??l(),w=h.find(({key:P})=>P===gn)??g();return b!==null&&C.push(b),k!==null&&C.push(k),y!==null&&C.push(y),w!==null&&C.push(w),C},S=(h,C)=>{const b=h.find(({key:w})=>w===mn)??null,k=h.find(({key:w})=>w===hn)??null,y=h.find(({key:w})=>w===fn)??null;b&&Ye(b)&&C.append(mn,b.value),k&&Je(k)&&C.append(hn,k.value),y&&C.append(fn,y.value)},O=({query:h="",page:C,count:b,sort:k="",selectedFacets:y=[],type:w,showInvisibleItems:P,sponsoredCount:E,hideUnavailableItems:T,allowRedirect:X=!1})=>{const N=new URLSearchParams({page:(C+1).toString(),count:b!==0?b.toString():"1",query:h,sort:k,locale:o.storage.locale});if(S(y,N),P&&N.append("show-invisible-items","true"),t!==void 0){const q=y.find(({key:we})=>we===oe),cn=q?q.value:T?.toString()??t.toString();N.append("hideUnavailableItems",cn)}r!==void 0&&N.append("simulationBehavior",r.toString()),i!==void 0&&N.append("showSponsored",i.toString()),E!==void 0&&N.append("sponsoredCount",E.toString()),X!==void 0&&N.append("allowRedirect",X.toString());const z=f(y).map(({key:q,value:cn})=>`${q}/${cn}`).join("/");return I(`${s}/_v/api/intelligent-search/${w}/${z}?${N.toString()}`,{headers:u})};return{facets:h=>O({...h,type:"facets"}),products:h=>O({...h,type:"product_search"}),suggestedTerms:h=>{const C=new URLSearchParams({query:h.query?.toString()??"",locale:o.storage.locale});return I(`${s}/_v/api/intelligent-search/search_suggestions?${C.toString()}`,{headers:u})},topSearches:()=>{const h=new URLSearchParams({locale:o.storage.locale});return I(`${s}/_v/api/intelligent-search/top_searches?${h.toString()}`,{headers:u})},productCount:h=>{const C=new URLSearchParams;return h?.query&&C.append("query",h.query.toString()),I(`${s}/_v/api/intelligent-search/catalog_count?${C.toString()}`,{headers:u})}}},Qe=(n,e)=>{const t=Ke(n,e),r=He(n,e);return{search:t,commerce:r}},Ze=20,nt=new Set(["brand","category","department","subcategory","collection","cluster"]),W=n=>typeof n.pageType=="string"&&nt.has(n.pageType.toLowerCase()),et=(n,e)=>{const t=Wn(Ze),r=async i=>Promise.all(i.map(a=>t(async()=>{const o=await e.commerce.catalog.portal.pagetype(a);if(W(o))return o;throw new B(`Catalog returned ${o.pageType} for slug: ${a}. This usually happens when there is more than one category with the same name in the same category tree level.`)})));return new sn(r,{batch:!1})},tt=(n,e)=>{const t=async r=>Promise.all(r.map(i=>e.commerce.catalog.salesChannel(i)));return new sn(t)},rt=1,it=(n,e)=>{const t=Wn(rt),r=async a=>{const o=a.reduce((m,{items:u})=>[...m,u],[]),s=[...o.flat()],c=await e.commerce.checkout.simulation({country:a[0].country,postalCode:a[0].postalCode,items:s}),d=c.items.reduce((m,u)=>{const l=u.requestIndex;return typeof l=="number"&&l<m.length&&(m[l]=u),m},Array(s.length).fill(null)),p=o.reduce((m,u)=>[...m,u.length+m[m.length-1]],[0]);return o.map((m,u)=>({...c,items:d.slice(p[u],p[u+1]).filter(l=>!!l)}))},i=async a=>t(r,a);return new sn(i,{maxBatchSize:50})},at=(n,e)=>Pe(n,e);function ot(n){return{...n,description:n.description?at(n.description):n.description}}const M=(n,e)=>({...n,isVariantOf:ot(e)}),st=({flags:n},e)=>{const t=async r=>{const i=r.map(p=>p.split("-")[0]),a=r.some(p=>p.split("-")[1]==="invisibleItems"),{products:o}=await e.search.products({query:`sku:${i.join(";")}`,page:0,count:i.length,showInvisibleItems:a,...n?.enableUnavailableItemsOnCart&&{hideUnavailableItems:!1}}),s=o.reduce((p,m)=>{for(const u of m.items)p[u.itemId]=M(u,m);return p},{}),c=i.map(p=>s[p]),d=i.filter(p=>!s[p]);if(d.length>0)throw new B(`Search API did not found the following skus: ${d.join(",")}`);return c};return new sn(t,{maxBatchSize:99})},ct=(n,{clients:e})=>{const t=st(n,e),r=it(n,e),i=et(n,e),a=tt(n,e);return{skuLoader:t,simulationLoader:r,collectionLoader:i,salesChannelLoader:a}},V=n=>n.AvailableQuantity>0,G=n=>n.spotPrice??0,lt=n=>n.Price??0,Un=n=>n?"https://schema.org/InStock":"https://schema.org/OutOfStock",se=(n,e)=>V(n)&&!V(e)?-1:!V(n)&&V(e)?1:G(n)-G(e),dt=n=>n==="available",x=(n,e=0,t=1)=>{const r=e/t;return Math.round((n+r)*100)/100},ut=(n,e={includeTaxes:!1})=>{const t=n.filter(V),r=t[t.length-1],i=r?G(r):0;return e.includeTaxes?x(i,r?.Tax,r?.product?.unitMultiplier):i},kn=(n,e={includeTaxes:!1})=>{const[t]=n.filter(V),r=t?G(t):0;return e.includeTaxes?x(r,t?.Tax,t?.product?.unitMultiplier):r},pt={highPrice:n=>ut(n),lowPrice:n=>kn(n),lowPriceWithTaxes:n=>kn(n,{includeTaxes:!0}),offerCount:n=>n.length,priceCurrency:async(n,e,t)=>{const{loaders:{salesChannelLoader:r},storage:{channel:i}}=t;return(await r.load(i.salesChannel)).CurrencyCode??""},offers:n=>n},gt={ratingValue:()=>5,reviewCount:()=>0},Tn="ÁÄÂÀÃÅČÇĆĎÉĚËÈÊẼĔȆÍÌÎÏŇÑÓÖÒÔÕØŘŔŠŤÚŮÜÙÛÝŸŽáäâàãåčçćďéěëèêẽĕȇíìîïňñóöòôõøðřŕšťúůüùûýÿžþÞĐđ߯a",mt="AAAAAACCCDEEEEEEEEIIIINNOOOOOORRSTUUUUUYYZaaaaaacccdeeeeeeeeiiiinnooooooorrstuuuuuyyzbBDdBAa",ht=n=>{let e=n.slice(0);for(let t=0;t<Tn.length;t++)e=e.replace(new RegExp(Tn.charAt(t),"g"),mt.charAt(t));return e},ft=n=>n.replace(/[·/_,:]/,"-");function ce(n){const t=n.replace(/,/g,"").replace(/[*+~.()'"!:@&\[\]`/ %$#?{}><=_^]/g,"-");return ft(ht(t)).toLowerCase()}const Z=n=>n.type==="brand"||W(n)&&n.pageType.toLowerCase()==="brand",Sn=n=>W(n)&&n.pageType.toLowerCase()==="collection",ln=n=>Z(n)||Sn(n)?ce(n.name):W(n)?new URL(`https://${n.url}`).pathname.slice(1).toLowerCase():new URL(n.url).pathname.slice(1).toLowerCase(),le={id:({id:n})=>n.toString(),slug:n=>ln(n),seo:n=>Z(n)||W(n)?{title:n.title??n.name,description:n.metaTagDescription}:{title:n.Title,description:n.MetaTagDescription},type:n=>Z(n)?"Brand":W(n)?n.pageType:n.level===0?"Department":"Category",meta:n=>{const e=ln(n);return Z(n)?{selectedFacets:[{key:"brand",value:e}]}:Sn(n)?{selectedFacets:[{key:"productclusterids",value:n.id}]}:{selectedFacets:e.split("/").map((t,r)=>({key:`category-${r+1}`,value:t}))}},breadcrumbList:async(n,e,t)=>{const{loaders:{collectionLoader:r}}=t,a=ln(n).split("/").filter(c=>!!c),o=a.map((c,d)=>a.slice(0,d+1).join("/")),s=await Promise.all(o.map(async c=>{const d=await r.load(c);return{slug:c,...d}}));return{itemListElement:s.map((c,d)=>({item:Sn(c)?`/${c.slug}`:new URL(`https://${c.url}`).pathname.toLowerCase(),name:c.name,position:d+1})),numberOfItems:s.length}}},de={buy:"whoboughtalsobought",view:"whosawalsosaw",similars:"similars",viewAndBought:"whosawalsobought",accessories:"accessories",suggestions:"suggestions"},_n=({key:n,value:e})=>{switch(n){case"price":return{key:n,value:e.replace("-to-",":")};case"channel":case"locale":case"buy":case"view":case"similars":case"viewAndBought":case"accessories":case"suggestions":return[];default:return{key:n,value:e}}},En=n=>{const e=n.split(":").map(Number);return e.length!==2||Number.isNaN(e[0])||Number.isNaN(e[1])?null:e},St=n=>typeof de[n]=="string",yt=n=>{const e=n?.filter(t=>St(t.key));if(Array.isArray(e)&&e.length>1)throw new $(`You passed ${e.length} cross selling facets but only one is allowed. Please leave one of the following facet: ${e.map(t=>t.key).join(",")}`);return e?.[0]??null},It=n=>n?.find(e=>e.key==="slug")?.value??null,vt=n=>n?.find(e=>e.key==="id")?.value??null,Nn=n=>n?.find(e=>e.key==="locale")?.value??null,Fn=n=>n?.find(e=>e.key==="channel")?.value??null,yn=(n,e)=>{let t=0;for(let r=1;r<n.length;r++)e(n[t],n[r])>0&&(t=r);return n[t]},Ot={__resolveType:({type:n,values:e})=>n!=="TEXT"&&n!=="DELIVERY"?"StoreFacetRange":!e||e.length===0?"StoreFacetBoolean":e.every(t=>t.range)?"StoreFacetRange":"StoreFacetBoolean"},Ct={key:({key:n})=>n,label:({name:n})=>n,values:({values:n})=>n.sort((e,t)=>e.name.localeCompare(t.name))},bt={key:({key:n})=>n,label:({name:n})=>n,min:({values:n,key:e},t,{storage:{searchArgs:r}})=>{const i=En(r?.selectedFacets?.find(s=>s.key===e)?.value??""),o=yn(n,(s,c)=>s.range.from-c.range.from)?.range?.from??0;return{selected:i?.[0]??o,absolute:o}},max:({values:n,key:e},t,{storage:{searchArgs:r}})=>{const i=En(r?.selectedFacets?.find(s=>s.key===e)?.value??""),o=yn(n,(s,c)=>c.range.to-s.range.to)?.range?.to??0;return{selected:i?.[1]??o,absolute:o}}},Dt={value:({value:n})=>n,label:({name:n})=>n||"unknown",selected:({selected:n})=>n,quantity:({quantity:n})=>n},wt=async(n,{data:e},{clients:{commerce:t}})=>{if(!e?.orderId)throw new $("Missing orderId");return{data:(await t.checkout.cancelOrder(e))?.data}};function ue(n){if(!n||n.status!=="pending")return null;for(const e of n.dimensionStatus){if(e.status!=="pending")continue;const t=e.ruleCollection.find(r=>r.status==="pending"&&r.isUserNextAuthorizer);if(t)return{rule:t,orderAuthorizationId:n.id,dimensionId:e.id}}return null}function At(n){if(!n||n.status!=="pending")return!1;const e=n.dimensionStatus.filter(t=>t.status==="pending").flatMap(t=>t.ruleCollection).filter(t=>t.status==="pending");return e.length===0?!1:e.every(t=>!t.isUserNextAuthorizer)}const Pt=async(n,{data:e},{clients:{commerce:t}})=>{const r=await t.oms.processOrderAuthorization(e),i=ue(r);return{isPendingForOtherAuthorizer:!i&&At(r),ruleForAuthorization:i}},Ut=async(n,{data:e},{clients:{commerce:t}})=>({id:(await t.subscribeToNewsletter(e))?.Id});class rn{static parse(e){try{const t=JSON.parse(e);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(e){return JSON.stringify(e)}}const In=(n,e)=>{n.storage.channel=rn.parse(e)},vn=(n,e)=>{n.storage.locale=e},pe=n=>Ue.createHash("md5").update(n).digest("hex"),Q={attachment:"ATTACHMENT",specification:"SPECIFICATION",attribute:"ATTRIBUTE"};function ge(n){return{name:n.name,value:n.content,valueReference:Q.attachment}}function kt(n){return{propertyID:n.id,name:n.name,value:n.value,valueReference:{valueReference:Q.attribute,visible:n.visible}}}function me(n){return pe(`${n.name}:${JSON.stringify(n.value)}:${n.valueReference}`)}const Tt=n=>{const e=n.postalCode,t=n.geoCoordinates,r={addressType:n.addressType||null,postalCode:e||null,city:null,state:null,country:n.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]},_t=(n,e,t)=>{const r=e.postalCode,i=e.geoCoordinates,a=n?.shippingData?.availableAddresses??[],o=n?.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},he=(n,e)=>{if(!Et(e))return{updateShipping:!1,addressChanged:!1};if(!Lt(n))return{updateShipping:!1,addressChanged:!1};const[t]=n?.shippingData?.selectedAddresses??[];if(Nt(t,e.postalCode)||Ft(t,e.geoCoordinates)||Rt(t,e.addressType))return{updateShipping:!0,addressChanged:!0};const{logisticsInfo:r}=n.shippingData;return Bt(r,e)?{updateShipping:!0,addressChanged:!1}:{updateShipping:!1,addressChanged:!1}},Et=n=>!!n.postalCode||n.geoCoordinates?.latitude&&n.geoCoordinates?.longitude,Nt=(n,e)=>typeof e=="string"&&n?.postalCode!==e,Ft=(n,e)=>typeof e?.latitude=="number"&&typeof e?.longitude=="number"&&(n?.geoCoordinates[0]!==e?.longitude||n?.geoCoordinates[1]!==e?.latitude),Rt=(n,e)=>typeof e=="string"&&n?.addressType!==e,Lt=n=>n.items.length!==0,Bt=(n,e)=>{const t=e?.deliveryMode?.deliveryChannel,r=e?.deliveryMode?.deliveryMethod,{startDate:i,endDate:a}=e?.deliveryMode?.deliveryWindow||{};return n.some(({selectedDeliveryChannel:o,selectedSla:s,slas:c})=>{const d=t&&o!==t,p=r&&s!==r;return c?.some(m=>d&&m.deliveryChannel===t||p&&m.id===r?!0:i&&a&&m.deliveryChannel===t&&m.id===r&&(!m?.deliveryWindow||m?.deliveryWindow?.startDateUtc!==i||m?.deliveryWindow?.endDateUtc!==a)&&m.availableDeliveryWindows?.some(u=>u?.startDateUtc===i&&u?.endDateUtc===a))})},fe=n=>n.valueReference===Q.attachment,On=n=>[n.itemOffered.sku,n.seller.identifier,n.price<.01?"Gift":void 0,n.itemOffered.additionalProperty?.filter(fe).map(me).join("-")].filter(Boolean).join("::"),an=(n,e)=>({listPrice:n.listPrice/100,price:n.sellingPrice/100,quantity:n.quantity,seller:{identifier:n.seller},itemOffered:{sku:n.id,image:[],name:n.name,additionalProperty:n.attachments.map(ge)},index:e}),Mt=n=>({quantity:n.quantity,seller:n.seller.identifier,id:n.itemOffered.sku,index:n.index,attachments:(n.itemOffered.additionalProperty?.filter(fe)??[]).map(e=>({name:e.name,content:e.value}))}),Rn=n=>n.reduce((e,t)=>{const r=On(t);return e.has(r)||e.set(r,[]),e.get(r)?.push(t),e},new Map),$t=(n,e)=>{const t=(s,c)=>({...s,itemOffered:{sku:s.itemOffered.sku},index:c}),r=e.items.map(an).map(t),i=n.acceptedOffer.map(t),a=n.orderNumber===e.orderFormId,o=Dn(r,i);return a&&o};function Se(n,e){return n?.some(t=>t.parentItemIndex!==null&&t.parentItemIndex!==void 0&&n[t.parentItemIndex]?.id===e)}function ye(n,e){return n?.some(t=>t.id===e&&t.parentItemIndex!==null)}const Ln=n=>{const e=n.items.reduce((t,r,i)=>{const a=ye(n.items,r.id)||Se(n.items,r.id)?`${On(an(r))}::${i}`:On(an(r));return t[a]||(t[a]=[]),t[a].push(r),t},{});return{...n,items:Object.values(e).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}})}},Bn=async(n,e,t)=>({order:{orderNumber:n.orderFormId,acceptedOffer:n.items.map(async r=>({...r,product:await e.load(`${r.id}-invisibleItems`)})),shouldSplitItem:t},messages:n.messages.map(({text:r,status:i})=>({text:r,status:i.toUpperCase()}))}),Ie=({items:n},e)=>{const t=n.map(r=>({id:r.id,quantity:r.quantity,seller:r.seller,attachments:r.attachments}));return pe(JSON.stringify({sessionId:e?.id??"",items:t}))},Mn=async(n,e,t)=>{try{return await e.checkout.setCustomData({id:n.orderFormId,appId:"faststore",key:"cartEtag",value:Ie(n,t)})}catch(r){throw console.error(`Error while setting custom data to orderForm.
2
2
  Make sure to add the following custom app to the orderForm:
3
3
  {"fields":["cartEtag"],"id":"faststore","major":1}.
4
- More info at: https://developers.vtex.com/vtex-rest-api/docs/customizable-fields-with-checkout-api`),r}},zt=(n,e)=>{const r=n.customData?.customApps.find(a=>a.id==="faststore")?.fields?.cartEtag;return r==null?!0:Ie(n,e)!==r},Vt=async(n,{clients:{commerce:e}})=>e.checkout.clearOrderFormMessages({id:n}),$n=async(n,e,{clients:{commerce:t}})=>{if(!e)return n;const{updateShipping:r,addressChanged:i}=he(n,e);if(r){const a=Tt(n,e,i),s=a||_t(e);return!!e.deliveryMode?.deliveryWindow&&await t.checkout.shippingData({id:n.orderFormId,index:n.items.length,deliveryMode:e.deliveryMode,selectedAddresses:s},!1),t.checkout.shippingData({id:n.orderFormId,index:n.items.length,deliveryMode:e.deliveryMode,selectedAddresses:s},!0)}return n},qt=(n,e)=>{if(!n)return"";const r=rn.parse(n)[e];return r?r.split("=")[1]:""},xt=async(n,{cart:{order:e},session:t},r)=>{const i=qt(r.headers.cookie,"checkout.vtex.com"),{clients:{commerce:a},loaders:{skuLoader:o}}=r,s=t?.channel,c=t?.locale;s&&Sn(r,s),c&&yn(r,c);const d=await a.checkout.orderForm({id:i||void 0,channel:r.storage.channel}),p=d.orderFormId;d.messages.length!==0&&await Vt(p,r);const m=rn.parse(r?.headers?.cookie??"")?.vtex_session,u=wn(m),{acceptedOffer:l,shouldSplitItem:g}=e;if(zt(d,u)){const y=await Mn(d,a,u).then(Ln);if(p)return Bn(y,o,g)}const S=Rn(l),O=Rn(d.items.map(tn)),D=Array.from(O.entries()),A=Array.from(S.entries()),{itemsToAdd:T,itemsToUpdate:v}=A.reduce((y,[w,P])=>{const E=O.get(w);if(!E)return P.forEach(z=>y.itemsToAdd.push(z)),y;const[_,...X]=E;if(ye(d.items,_.itemOffered.sku)||Se(d.items,_.itemOffered.sku))return y.itemsToUpdate.push(_),y;const N=P.reduce((z,q)=>z+q.quantity,0);return y.itemsToUpdate.push({..._,quantity:N}),X.forEach(z=>y.itemsToUpdate.push({...z,quantity:0})),y},{itemsToAdd:[],itemsToUpdate:[]}),k=D.filter(([y])=>!S.has(y)).flatMap(([,y])=>y.map(w=>({...w,quantity:0}))),h=[...T,...v,...k].map(Mt),{updateShipping:C}=t?he(d,t):{updateShipping:!1};if(h.length===0&&!C)return null;let b;h.length>0?b=await a.checkout.updateOrderFormItems({id:d.orderFormId,orderItems:h,shouldSplitItem:g}).then(y=>$n(y,t,r)):b=await $n(d,t,r),b=await Promise.resolve(b).then(y=>{if(t?.marketingData){const w={...y.marketingData,...t.marketingData};return a.checkout.marketingData({id:d.orderFormId,marketingData:w})}return y}).then(y=>c&&y.clientPreferencesData?.locale!==c?a.checkout.clientPreferencesData({id:y.orderFormId,clientPreferencesData:{...y.clientPreferencesData,locale:c}}):y).then(y=>Mn(y,a,u)).then(Ln);const U=Cn(d.messages,b.messages);return $t(e,b)&&U?null:Bn(b,o,g)};async function jt(n,e,t){try{const r=await n.commerce.checkout.address({postalCode:t,country:e}),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 (${e}).
5
- `),r}}const Wt=async(n,{session:e,search:t},{clients:r,headers:i,account:a})=>{const o=en.parse(e.channel??""),s=String(e.postalCode??""),c=e.country??"";let d=e.city??null,p=e.geoCoordinates??null;if((!d||!p)&&s!==""&&c!==""){const _=await jt(r,c,s);d=_.city,p=_.geoCoordinates}const u=new URLSearchParams(t);u.has("facets")&&u.delete("facets");const l=u.get("sc")??o.salesChannel;u.set("sc",l),s&&u.set("postalCode",s),c&&u.set("country",c),p&&u.set("geoCoordinates",`${p.longitude},${p.latitude}`),u.set("locale",e.locale);const{marketingData:g}=e,f={utmCampaign:u.get("utm_campaign")??g?.utmCampaign??"",utmMedium:u.get("utm_medium")??g?.utmMedium??"",utmSource:u.get("utm_source")??g?.utmSource??"",utmiCampaign:u.get("utmi_cp")??g?.utmiCampaign??"",utmiPage:u.get("utmi_p")??g?.utmiPage??"",utmiPart:u.get("utmi_pc")??g?.utmiPart??""},S=wn(Dn(i?.cookie??"",a));let O=!1;if(S)try{O=(await r.commerce.vtexid.validate())?.authStatus?.toLowerCase()==="success"}catch(_){console.warn("JWT validation failed:",_),O=!1}const D=O?S?.isRepresentative:!1,A=O?S?.customerId:void 0,T=O?S?.unitId:void 0,v=await r.commerce.session(u.toString()).catch(()=>null),k=v?.namespaces.profile??null,h=v?.namespaces.shopper??null,C=v?.namespaces.store??null,b=v?.namespaces.authentication??null,U=v?.namespaces.checkout??null,y=v?.namespaces.public??null;let w=null;if(D&&k?.id?.value)try{w=await r.commerce.masterData.getContractById({contractId:k.id.value})}catch{console.error(`Error while getting contract data for profile ID (${k.id.value}).
6
- `)}let P;o.seller&&(s||p)&&(P=(await r.commerce.checkout.region({postalCode:s,geoCoordinates:p,country:c,salesChannel:l}))?.[0]?.sellers.find(N=>o.seller===N.id));const E={...e,currency:{code:C?.currencyCode?.value??e.currency.code,symbol:C?.currencySymbol?.value??e.currency.symbol},country:C?.countryCode?.value??c,channel:en.stringify({salesChannel:C?.channel?.value??o.salesChannel,regionId:U?.regionId?.value??o.regionId,seller:P?.id,hasOnlyDefaultSalesChannel:!C?.channel?.value}),b2b:D?{isRepresentative:D??!1,customerId:b?.customerId?.value??A??"",unitName:b?.unitName?.value??"",unitId:b?.unitId?.value??T??"",firstName:typeof h?.firstName?.value=="string"?h.firstName.value:"",lastName:typeof h?.lastName?.value=="string"?h.lastName.value:"",userName:`${typeof h?.firstName?.value=="string"?h.firstName.value:""} ${typeof h?.lastName?.value=="string"?h.lastName.value:""}`.trim(),userEmail:b?.storeUserEmail.value??"",savedPostalCode:y?.postalCode?.value??"",contractName:w?.corporateName??"",organizationManager:h?.organizationManager?.value??!1}:null,marketingData:f,person:k?.id?{id:k.id?.value??"",email:k.email?.value??"",givenName:k.firstName?.value??"",familyName:k.lastName?.value??""}:null,geoCoordinates:p?.latitude&&p?.longitude&&p||null,city:d};return Cn(e,E)?null:E},Gt={validateCart:xt,validateSession:Wt,subscribeToNewsletter:kt,cancelOrder:wt,processOrderAuthorization:Pt};var vn;(function(n){n.NAME="Name",n.DOCUMENT="Document",n.OPERATION_DEFINITION="OperationDefinition",n.VARIABLE_DEFINITION="VariableDefinition",n.SELECTION_SET="SelectionSet",n.FIELD="Field",n.ARGUMENT="Argument",n.FRAGMENT_SPREAD="FragmentSpread",n.INLINE_FRAGMENT="InlineFragment",n.FRAGMENT_DEFINITION="FragmentDefinition",n.VARIABLE="Variable",n.INT="IntValue",n.FLOAT="FloatValue",n.STRING="StringValue",n.BOOLEAN="BooleanValue",n.NULL="NullValue",n.ENUM="EnumValue",n.LIST="ListValue",n.OBJECT="ObjectValue",n.OBJECT_FIELD="ObjectField",n.DIRECTIVE="Directive",n.NAMED_TYPE="NamedType",n.LIST_TYPE="ListType",n.NON_NULL_TYPE="NonNullType",n.SCHEMA_DEFINITION="SchemaDefinition",n.OPERATION_TYPE_DEFINITION="OperationTypeDefinition",n.SCALAR_TYPE_DEFINITION="ScalarTypeDefinition",n.OBJECT_TYPE_DEFINITION="ObjectTypeDefinition",n.FIELD_DEFINITION="FieldDefinition",n.INPUT_VALUE_DEFINITION="InputValueDefinition",n.INTERFACE_TYPE_DEFINITION="InterfaceTypeDefinition",n.UNION_TYPE_DEFINITION="UnionTypeDefinition",n.ENUM_TYPE_DEFINITION="EnumTypeDefinition",n.ENUM_VALUE_DEFINITION="EnumValueDefinition",n.INPUT_OBJECT_TYPE_DEFINITION="InputObjectTypeDefinition",n.DIRECTIVE_DEFINITION="DirectiveDefinition",n.SCHEMA_EXTENSION="SchemaExtension",n.SCALAR_TYPE_EXTENSION="ScalarTypeExtension",n.OBJECT_TYPE_EXTENSION="ObjectTypeExtension",n.INTERFACE_TYPE_EXTENSION="InterfaceTypeExtension",n.UNION_TYPE_EXTENSION="UnionTypeExtension",n.ENUM_TYPE_EXTENSION="EnumTypeExtension",n.INPUT_OBJECT_TYPE_EXTENSION="InputObjectTypeExtension"})(vn||(vn={}));const Ht=n=>typeof n=="string"?ve(n):null;function ve(n){try{return JSON.parse(n)}catch{return n}}const Xt=n=>typeof n=="object"?JSON.stringify(n):typeof n=="string"?n:null,Yt=new nn.GraphQLScalarType({name:"ObjectOrString",description:"A string or the string representation of an object (a stringified object).",parseValue:Ht,serialize:Xt,parseLiteral(n){return n.kind===vn.STRING?ve(n.value):null}}),R=n=>"Price"in n&&"seller"in n&&"product"in n,F=n=>"skuName"in n,Jt={priceCurrency:async(n,e,t)=>{const{loaders:{salesChannelLoader:r},storage:{channel:i}}=t;return(await r.load(i.salesChannel)).CurrencyCode??""},priceValidUntil:n=>R(n)?n.PriceValidUntil??"":F(n)?n.priceValidUntil??"":null,itemCondition:()=>"https://schema.org/NewCondition",availability:async n=>R(n)?kn(V(n)):F(n)?kn(dt(n.availability)):null,seller:(n,e,t)=>R(n)?{identifier:t.storage.channel?.seller||n.seller.sellerId||""}:F(n)?{identifier:n.seller}:null,price:n=>R(n)?G(n):F(n)?n.sellingPrice/100:null,priceWithTaxes:n=>R(n)?x(G(n),n?.Tax,n.product.unitMultiplier):F(n)?x(n.sellingPrice/100,n.tax/100,n.unitMultiplier):null,sellingPrice:n=>R(n)?lt(n):F(n)?n.sellingPrice/100:null,listPrice:n=>R(n)?n.ListPrice??0:F(n)?n.listPrice/100:null,listPriceWithTaxes:n=>R(n)?x(n.ListPrice??0,n?.Tax,n.product.unitMultiplier):F(n)?x(n.listPrice/100,n.tax/100,n.unitMultiplier):null,itemOffered:n=>R(n)?n.product:F(n)?{...n.product,attachmentsValues:n.attachments}:null,quantity:n=>R(n)?n.AvailableQuantity??0:F(n)?n.quantity:null,isGift:n=>F(n)?n.isGift??!1:null},Kt=({linkText:n})=>`/${n}/p`,Qt=({offer:n,seller:e,product:t})=>({...n,product:t,seller:e}),Zt={imageText:"image",imageUrl:"https://storecomponents.vtexassets.com/assets/faststore/images/image___117a6d3e229a96ad0e0d0876352566e2.svg",imageLabel:"label"},Oe=(n,e)=>`${n}-${e}`,nr=(n,e)=>`/${Oe(n,e)}/p`,er=n=>Array.isArray(n)&&n.length>0?n:null;function Ce(n){return n.replace(/^\/+|\/+$/g,"")}const tr=(n,e)=>{const t=n.findIndex(r=>Ce(r).split("/").at(-1)===e);return t<0?0:t},rr={productID:({itemId:n})=>n,name:({isVariantOf:n,name:e})=>e??n.productName,slug:({isVariantOf:{linkText:n},itemId:e})=>Oe(n,e),description:({isVariantOf:{description:n}})=>n,seo:({isVariantOf:n})=>({title:n.productTitle||n.productName,description:n.metaTagDescription||n.description,canonical:Kt(n)}),brand:({isVariantOf:{brand:n}})=>({name:n}),unitMultiplier:({unitMultiplier:n})=>n,breadcrumbList:({isVariantOf:{categories:n,productName:e,linkText:t,categoryId:r,categoriesIds:i},itemId:a})=>{const o=tr(i,r),s=n[o],c=Ce(s).split("/");return{itemListElement:[...c.map((d,p)=>{const m=`/${c.slice(0,p+1).map(ce).join("/")}/`;return{name:d,item:m,position:p+1}}),{name:e,item:nr(t,a),position:c.length+1}],numberOfItems:c.length}},image:({images:n},e)=>{const t=(er(n)??[Zt]).map(({imageUrl:s,imageText:c,imageLabel:d})=>({alternateName:c??"",url:s.replace("vteximg.com.br","vtexassets.com"),keywords:d}));if(typeof e!="object")return t;let{context:r,limit:i}=e;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:n})=>n,gtin:({ean:n,referenceId:e})=>n||(e[0]?.Value??""),mpn:({isVariantOf:{manufacturerCode:n}})=>n??"",review:()=>[],aggregateRating:()=>({}),offers:n=>n.sellers.map(e=>Qt({offer:e.commertialOffer,seller:e,product:n})).sort(se),isVariantOf:n=>n,additionalProperty:({variations:n=[],attachmentsValues:e=[],attributes:t=[]})=>{const r=n.flatMap(({name:o,values:s})=>s.map(c=>({name:o,value:c,valueReference:Q.specification}))),i=e.map(ge),a=t.map(Ut);return[...r,...i,...a]},hasSpecifications:({isVariantOf:n})=>!!n.skuSpecifications?.length,skuSpecifications:({isVariantOf:{skuSpecifications:n}})=>n??[],specificationGroups:({isVariantOf:{specificationGroups:n}})=>n,releaseDate:({isVariantOf:{releaseDate:n}})=>n??"",advertisement:({isVariantOf:{advertisement:n}})=>n,deliveryPromiseBadges:({isVariantOf:{deliveryPromisesBadges:n}})=>n},ir=new Set(["allSpecifications"]),ar={hasVariant:n=>n.isVariantOf.items.map(e=>M(e,n.isVariantOf)),productGroupID:({isVariantOf:n})=>n.productId,name:n=>n.isVariantOf.productName,skuVariants:n=>n,additionalProperty:({isVariantOf:{specificationGroups:n}})=>n.filter(e=>!ir.has(e.name)).flatMap(({specifications:e})=>e.flatMap(({name:t,values:r})=>r.map(i=>({name:t,value:i,valueReference:Q.specification}))))},or={propertyID:n=>n.propertyID||me(n),name:({name:n})=>n,value:({value:n})=>n,valueReference:({valueReference:n})=>n},On=n=>{const e=n.flatMap(r=>r.sellers.map(i=>({offer:i.commertialOffer,sku:r}))),t=fn(e,({offer:r},{offer:i})=>se(r,i));return t?t.sku:n[0]},sr=n=>n!==""&&!Number.isNaN(Number(n)),cr={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:""},lr={product:async(n,{locator:e},t)=>{const r=Fn(e),i=Nn(e),a=vt(e),o=It(e);r&&Sn(t,r),i&&yn(t,i);const{loaders:{skuLoader:s},clients:{commerce:c,search:d}}=t;try{const p=a??o?.split("-").pop()??"";if(!sr(p))throw new Error("Invalid SkuId");const m=await s.load(p);if(o&&m.isVariantOf.linkText&&!o.startsWith(m.isVariantOf.linkText))throw new Error(`Slug was set but the fetched sku does not satisfy the slug condition. slug: ${o}, linkText: ${m.isVariantOf.linkText}`);return m}catch{if(o==null)throw new $("Missing slug or id");const m=await c.catalog.portal.pagetype(`${o}/p`);if(m.pageType!=="Product"||!m.id)throw new B(`No product found for slug ${o}`);const{products:[u]}=await d.products({page:0,count:1,query:`product:${m.id}`,hideUnavailableItems:!1});if(!u)throw new B(`No product found for id ${m.id}`);const l=On(u.items);return M(l,u)}},collection:(n,{slug:e},t)=>{const{loaders:{collectionLoader:r}}=t;return r.load(e)},search:async(n,{first:e,after:t,sort:r,term:i,selectedFacets:a,sponsoredCount:o},s)=>{const c=Fn(a),d=Nn(a),p=yt(a);c&&Sn(s,c),d&&yn(s,d);let m=i;p&&(m=`product:${(await s.clients.commerce.catalog.products.crossselling({type:de[p.key],productId:p.value})).map(S=>S.productId).slice(0,e).join(";")}`);const u=t?Number(t):0,l={page:Math.ceil(u/e)||0,count:e,query:m??void 0,sort:cr[r??"score_desc"],selectedFacets:a?.flatMap(Tn)??[],sponsoredCount:o??void 0},g=s.clients.search.products(l);return{searchArgs:l,productSearchPromise:g}},allProducts:async(n,{first:e,after:t},r)=>{const{clients:{search:i}}=r,a=t?Number(t):0,o=await i.products({page:Math.ceil(a/e),count:e}),s=o.products.flatMap(c=>c.items.map(d=>M(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(n,{productIds:e},t)=>{const{clients:{search:r}}=t;if(!e.length)return[];const i=`id:${e.join(";")}`;return(await r.products({page:0,count:e.length,query:i})).products.flatMap(o=>o.items.map(s=>M(s,o))).filter(o=>e.includes(o.itemId)&&o.sellers.length>0)},allCollections:async(n,{first:e,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=(u,l)=>{c.push({...u,level:l});for(const g of u.children)d(g,l+1)};for(const u of s)d(u,0);const m=[...o.filter(u=>u.isActive).map(u=>({...u,type:"brand"})),...c].filter(u=>!!le.slug(u,null,r,null));return{pageInfo:{hasNextPage:m.length-a>e,hasPreviousPage:a>0,startCursor:"0",endCursor:(Math.min(e,m.length-a)-1).toString(),totalCount:m.length},edges:m.slice(a,a+e).map((u,l)=>({node:u,cursor:(a+l).toString()}))}},shipping:async(n,{country:e,items:t,postalCode:r},i)=>{const{loaders:{simulationLoader:a},clients:{commerce:o}}=i,[s,c]=await Promise.all([a.load({country:e,items:t,postalCode:r}),o.checkout.address({postalCode:r,country:e})]);return{...s,address:c}},redirect:async(n,{term:e,selectedFacets:t},r)=>{if(!e&&(!t||!t.length))return null;const{redirect:i}=await r.clients.search.products({page:1,count:1,query:e??void 0,selectedFacets:t?.flatMap(Tn)??[],allowRedirect:!0});return{url:i}},sellers:async(n,{postalCode:e,geoCoordinates:t,country:r,salesChannel:i},a)=>{const{clients:{commerce:o}}=a,c=(await o.checkout.region({postalCode:e,geoCoordinates:t,country:r,salesChannel:i}))?.[0],{id:d,sellers:p}=c;return{id:d,sellers:p}},profile:async(n,{id:e},t)=>{const{clients:{commerce:r}}=t,i=await r.profile.addresses(e);function a(s){return!s||Object.keys(s).length===0?[]:Object.values(s).map(c=>JSON.parse(c))}return{addresses:a(i)}},productCount:async(n,{term:e},t)=>{const{clients:{search:r}}=t;return await r.productCount({query:e??void 0})},userOrder:async(n,{orderId:e},t)=>{try{if(!e)throw new $("Missing orderId");const{clients:{commerce:r}}=t,i=await r.oms.userOrder({orderId:e});if(!i)throw new B(`No order found for id ${e}`);let a=null;try{const c=await r.oms.getCommercialAuthorizationsByOrderId({orderId:e});a=ue(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 te(r)?new B(`No order found for id ${e}. ${o}.`):ee(r)?new K(`You are forbidden to interact with order with id ${e}. ${o}.`):r}},listUserOrders:async(n,e,t)=>{const{clients:{commerce:r}}=t,i=await r.oms.listUserOrders(e);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}},validateUser:async(n,e,t)=>({isValid:!0}),userDetails:async(n,e,t)=>{const{clients:{commerce:r}}=t,i=await r.session("").catch(()=>null),a=i?.namespaces.shopper??null,o=i?.namespaces.authentication??null;return{name:a?.firstName?.value??"",email:o?.storeUserEmail.value??"",role:["Admin"],orgUnit:o?.unitName?.value??""}},accountProfile:async(n,e,t)=>{const{account:r,headers:i,clients:{commerce:a}}=t,o=wn(Dn(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;return{name:((await a.masterData.getContractById({contractId:d?.id?.value??""}))?.corporateName??`${(d?.firstName?.value??"").trim()} ${(d?.lastName?.value??"").trim()}`.trim())||"",email:d?.email?.value||"",id:d?.id?.value||""}}const s=await a.licenseManager.getUserById({userId:o?.userId}).catch(()=>null);return{name:s?.name||"",email:s?.email||"",id:s?.id||""}},pickupPoints:async(n,{geoCoordinates:e},t)=>{const{clients:{commerce:r}}=t;return await r.checkout.pickupPoints({geoCoordinates:e})}},dr={reviewRating:()=>({ratingValue:5,bestRating:5}),author:()=>({name:""})},ur=(n,e,t)=>e?n.key==="category-1":t?n.key==="brand":!1,pr={suggestions:async(n,e,t)=>{const{clients:{search:r}}=t,{searchArgs:i}=n;if(!i.query)return{terms:(await r.topSearches()).searches.map(m=>({value:m.term,count:m.count})),products:[]};const{productSearchPromise:a}=n,[o,s]=await Promise.all([r.suggestedTerms(i),a]),c=s.products.map(p=>{const m=On(p.items);return m&&M(m,p)}).filter(p=>!!p),{searches:d}=o;return{terms:d.map(p=>({value:p.term,count:p.count})),products:c}},products:async({productSearchPromise:n})=>{const e=await n,t=e.products.map(r=>{const i=On(r.items);return i&&M(i,r)}).filter(r=>!!r);return{pageInfo:{hasNextPage:e.pagination.after.length>0,hasPreviousPage:e.pagination.before.length>0,startCursor:"0",endCursor:e.recordsFiltered.toString(),totalCount:e.recordsFiltered},edges:t.map((r,i)=>({node:r,cursor:i.toString()}))}},facets:async({searchArgs:n},e,t)=>{const{clients:{search:r}}=t;t.storage.searchArgs=n;const{facets:i=[]}=await r.facets(n),a=!n.query,o=n.selectedFacets?.length?n.selectedFacets[0].key==="category-1":!1,s=n.selectedFacets?.length?n.selectedFacets[0].key==="brand":!1;return i.filter(d=>!a||!ur(d,o,s))},metadata:async({productSearchPromise:n})=>{const e=await n;return{isTermMisspelled:e.correction?.misspelled??!1,logicalOperator:e.operator,fuzzy:e.fuzzy}},searchId:async({productSearchPromise:n})=>(await n).searchId},gr={title:({title:n})=>n??"",description:({description:n})=>n??"",canonical:({canonical:n})=>n??"",titleTemplate:()=>""},mr=["bd","d","h","m"],hr=n=>mr.includes(n),fr={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"}},be=n=>{const[e,t]=[n.split(/\D+/)[0],n.split(/[0-9]+/)[1]],r=e!==""&&!Number.isNaN(Number(e)),i=hr(t);if(!r||!i)return"";const a=Number(e)<2?Number(e):"other";return fr[t][a].replace("#",e)??""},Sr={carrier:n=>n?.friendlyName??n?.name??"",price:n=>n?.price?n.price/100:n?.price,localizedEstimates:n=>n?.shippingEstimate?be(n.shippingEstimate):""},zn="skuvariation";function Vn(n,e){const t=`${zn}${e}`.toLowerCase(),r=n.find(a=>a.imageLabel===t);if(r)return r;const i=n.find(a=>a.imageLabel===zn);return i||n[0]}function yr(n,e,t){const r={};return n.forEach(i=>{const a=i.variations;if(a.length===0)return;const o=`${e}-${a.find(c=>c.name===e)?.values[0]??""}`,s=a.reduce((c,d)=>d.name===e?c:c+`-${d.name}-${d.values[0]}`,o);r[s]=`${t}-${i.itemId}`}),r}function qn(n){const e={};return n.forEach(t=>{e[t.name]=t.values[0]}),e}function Ir(n){const e={};return n?.forEach(t=>{e[t.field.originalName??t.field.name]=t.values.map(r=>r.originalName??r.name)}),e}function vr(n,e){return Number.isNaN(Number(n)-Number(e))?n<e?-1:n>e?1:0:Number(n)-Number(e)}function Or(n){const e=n;for(const t in n)n[t].every(i=>!Number.isNaN(Number(i.value)))&&n[t].sort((i,a)=>vr(i.value,a.value));return e}function Cr(n,e,t){const r={},i=new Set;return n.forEach(a=>{if(a.variations.length===0)return;const o=a.variations.find(c=>c.name===e);if(!(o?.values[0]===t)){const c=`${e}-${o?.values[0]}`;if(!o||i.has(c))return;i.add(c);const d=Vn(a.images,e),p={src:d.imageUrl,alt:d.imageLabel??"",label:`${e}: ${o.values[0]}`,value:o.values[0]};r[o.name]?r[o.name].push(p):r[o.name]=[p];return}a.variations.forEach(c=>{const d=`${c.name}-${c.values[0]}`;if(i.has(d))return;i.add(d);const p=Vn(a.images,c.name),m={src:p.imageUrl,alt:p.imageText??"",label:`${c.name}: ${c.values[0]}`,value:c.values[0]};r[c.name]?r[c.name].push(m):r[c.name]=[m]})}),Or(r)}const br={activeVariations:n=>qn(n.variations),allVariantsByName:n=>Ir(n.isVariantOf.skuSpecifications),slugsMap:(n,e)=>yr(n.isVariantOf.items,e.dominantVariantName??n.variations[0]?.name,n.isVariantOf.linkText),availableVariations:(n,e)=>{const t=e.dominantVariantName??n.variations[0]?.name,i=qn(n.variations)[t];return Cr(n.isVariantOf.items,t,i)},allVariantProducts:n=>n.isVariantOf.items.map(e=>M(e,n.isVariantOf))},Dr={"pickup-in-point":"Pickup",delivery:"Delivery",pickup:"Pickup","take-away":"Take away","":""},wr={deliveryOptionsData:n=>{const{shippingData:e,items:t}=n,r=e?.logisticsInfo||[],i=e?.selectedAddresses||e?.availableAddresses||[e?.address],a=r.reduce((d,p)=>{const m=p?.selectedSla||"",u=p?.selectedDeliveryChannel||p?.deliveryChannel||"",l=p?.deliveryCompany||"",g=p?.deliveryWindow,f=p?.pickupStoreInfo,S=p?.shippingEstimate||"",O=p?.shippingEstimate?be(p?.shippingEstimate):"",D=p?.shippingEstimateDate||"",A=p?.addressId||"",T=p?.itemIndex??0,v=t?.[T],k=v?.seller||"",h=`${m}|${u}|${l}|${k}|${S}|${D}|${A}|${g?.startDateUtc}|${g?.endDateUtc}`,C=i?.find(P=>P?.addressId===A),b=`${Dr[u]||""} ${O} ${C?.neighborhood?`to ${C?.neighborhood}`:""}`.trim(),{taxPriceTagsTotal:U,taxPriceTags:y}=Ar(v?.priceTags??[]),w=(v?.sellingPrice??0)*(v?.quantity??0)+(v?.tax??0)+(U??0);return d[h]||(d[h]={selectedSla:m,deliveryChannel:u,deliveryCompany:l,deliveryWindow:g,shippingEstimate:S,shippingEstimateDate:D,seller:k,friendlyShippingEstimate:O,friendlyDeliveryOptionName:b,address:C,pickupStoreInfo:f,quantityOfDifferentItems:0,total:0,items:[]}),d[h]&&(d[h].items?.push({id:v?.id||"",uniqueId:v?.uniqueId||"",name:v?.name||"",quantity:v?.quantity||0,price:v?.price||0,sellingPrice:v?.sellingPrice||0,imageUrl:v?.imageUrl||"",taxPriceTags:y??[],taxPriceTagsTotal:U??0,tax:v?.tax||0,total:w}),d[h].quantityOfDifferentItems=(d[h].quantityOfDifferentItems??0)+1,d[h].total=(d[h].total??0)+w),d},{}),o=Object.values(a),s=e?.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:n=>{const e=n?.customData?.customFields||[];return Object.values(e.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 Ar(n){const t=n.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 Pr={StoreCollection:le,StoreAggregateOffer:pt,StoreProduct:rr,StoreSeo:gr,StoreFacet:Ot,StoreFacetBoolean:Ct,StoreFacetRange:bt,StoreFacetValueBoolean:Dt,StoreOffer:Jt,StoreAggregateRating:gt,StoreReview:dr,StoreProductGroup:ar,StoreSearchResult:pr,StorePropertyValue:or,SkuVariants:br,ShippingSLA:Sr,UserOrderResult:wr,ObjectOrString:Yt,Query:lr,Mutation:Gt},kr=()=>Pr,Ur=`"""
4
+ More info at: https://developers.vtex.com/vtex-rest-api/docs/customizable-fields-with-checkout-api`),r}},zt=(n,e)=>{const r=n.customData?.customApps.find(a=>a.id==="faststore")?.fields?.cartEtag;return r==null?!0:Ie(n,e)!==r},Vt=async(n,{clients:{commerce:e}})=>e.checkout.clearOrderFormMessages({id:n}),$n=async(n,e,{clients:{commerce:t}})=>{if(!e)return n;const{updateShipping:r,addressChanged:i}=he(n,e);if(r){const a=_t(n,e,i),s=a||Tt(e);return!!e.deliveryMode?.deliveryWindow&&await t.checkout.shippingData({id:n.orderFormId,index:n.items.length,deliveryMode:e.deliveryMode,selectedAddresses:s},!1),t.checkout.shippingData({id:n.orderFormId,index:n.items.length,deliveryMode:e.deliveryMode,selectedAddresses:s},!0)}return n},qt=(n,e)=>{if(!n)return"";const r=on.parse(n)[e];return r?r.split("=")[1]:""},xt=async(n,{cart:{order:e},session:t},r)=>{const i=qt(r.headers.cookie,"checkout.vtex.com"),{clients:{commerce:a},loaders:{skuLoader:o}}=r,s=t?.channel,c=t?.locale;s&&In(r,s),c&&vn(r,c);const d=await a.checkout.orderForm({id:i||void 0,channel:r.storage.channel}),p=d.orderFormId;d.messages.length!==0&&await Vt(p,r);const m=on.parse(r?.headers?.cookie??"")?.vtex_session,u=tn(m),{acceptedOffer:l,shouldSplitItem:g}=e;if(zt(d,u)){const y=await Mn(d,a,u).then(Ln);if(p)return Bn(y,o,g)}const S=Rn(l),O=Rn(d.items.map(an)),D=Array.from(O.entries()),A=Array.from(S.entries()),{itemsToAdd:_,itemsToUpdate:v}=A.reduce((y,[w,P])=>{const E=O.get(w);if(!E)return P.forEach(z=>y.itemsToAdd.push(z)),y;const[T,...X]=E;if(ye(d.items,T.itemOffered.sku)||Se(d.items,T.itemOffered.sku))return y.itemsToUpdate.push(T),y;const N=P.reduce((z,q)=>z+q.quantity,0);return y.itemsToUpdate.push({...T,quantity:N}),X.forEach(z=>y.itemsToUpdate.push({...z,quantity:0})),y},{itemsToAdd:[],itemsToUpdate:[]}),U=D.filter(([y])=>!S.has(y)).flatMap(([,y])=>y.map(w=>({...w,quantity:0}))),h=[..._,...v,...U].map(Mt),{updateShipping:C}=t?he(d,t):{updateShipping:!1};if(h.length===0&&!C)return null;let b;h.length>0?b=await a.checkout.updateOrderFormItems({id:d.orderFormId,orderItems:h,shouldSplitItem:g}).then(y=>$n(y,t,r)):b=await $n(d,t,r),b=await Promise.resolve(b).then(y=>{if(t?.marketingData){const w={...y.marketingData,...t.marketingData};return a.checkout.marketingData({id:d.orderFormId,marketingData:w})}return y}).then(y=>c&&y.clientPreferencesData?.locale!==c?a.checkout.clientPreferencesData({id:y.orderFormId,clientPreferencesData:{...y.clientPreferencesData,locale:c}}):y).then(y=>Mn(y,a,u)).then(Ln);const k=Dn(d.messages,b.messages);return $t(e,b)&&k?null:Bn(b,o,g)};async function jt(n,e,t){try{const r=await n.commerce.checkout.address({postalCode:t,country:e}),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 (${e}).
5
+ `),r}}const Wt=async(n,{session:e,search:t},{clients:r,headers:i,account:a})=>{const o=rn.parse(e.channel??""),s=String(e.postalCode??""),c=e.country??"";let d=e.city??null,p=e.geoCoordinates??null;if((!d||!p)&&s!==""&&c!==""){const T=await jt(r,c,s);d=T.city,p=T.geoCoordinates}const u=new URLSearchParams(t);u.has("facets")&&u.delete("facets");const l=u.get("sc")??o.salesChannel;u.set("sc",l),s&&u.set("postalCode",s),c&&u.set("country",c),p&&u.set("geoCoordinates",`${p.longitude},${p.latitude}`),u.set("locale",e.locale);const{marketingData:g}=e,f={utmCampaign:u.get("utm_campaign")??g?.utmCampaign??"",utmMedium:u.get("utm_medium")??g?.utmMedium??"",utmSource:u.get("utm_source")??g?.utmSource??"",utmiCampaign:u.get("utmi_cp")??g?.utmiCampaign??"",utmiPage:u.get("utmi_p")??g?.utmiPage??"",utmiPart:u.get("utmi_pc")??g?.utmiPart??""},S=tn(en(i?.cookie??"",a));let O=!1;if(S)try{O=(await r.commerce.vtexid.validate())?.authStatus?.toLowerCase()==="success"}catch(T){console.warn("JWT validation failed:",T),O=!1}const D=O?S?.isRepresentative:!1,A=O?S?.customerId:void 0,_=O?S?.unitId:void 0,v=await r.commerce.session(u.toString()).catch(()=>null),U=v?.namespaces.profile??null,h=v?.namespaces.shopper??null,C=v?.namespaces.store??null,b=v?.namespaces.authentication??null,k=v?.namespaces.checkout??null,y=v?.namespaces.public??null;let w=null;if(D&&U?.id?.value)try{w=await r.commerce.masterData.getContractById({contractId:U.id.value})}catch{console.error(`Error while getting contract data for profile ID (${U.id.value}).
6
+ `)}let P;o.seller&&(s||p)&&(P=(await r.commerce.checkout.region({postalCode:s,geoCoordinates:p,country:c,salesChannel:l}))?.[0]?.sellers.find(N=>o.seller===N.id));const E={...e,currency:{code:C?.currencyCode?.value??e.currency.code,symbol:C?.currencySymbol?.value??e.currency.symbol},country:C?.countryCode?.value??c,channel:rn.stringify({salesChannel:C?.channel?.value??o.salesChannel,regionId:k?.regionId?.value??o.regionId,seller:P?.id,hasOnlyDefaultSalesChannel:!C?.channel?.value}),b2b:D?{isRepresentative:D??!1,customerId:b?.customerId?.value??A??"",unitName:b?.unitName?.value??"",unitId:b?.unitId?.value??_??"",firstName:typeof h?.firstName?.value=="string"?h.firstName.value:"",lastName:typeof h?.lastName?.value=="string"?h.lastName.value:"",userName:`${typeof h?.firstName?.value=="string"?h.firstName.value:""} ${typeof h?.lastName?.value=="string"?h.lastName.value:""}`.trim(),userEmail:b?.storeUserEmail.value??"",savedPostalCode:y?.postalCode?.value??"",contractName:w?.corporateName??"",organizationManager:h?.organizationManager?.value??!1}:null,marketingData:f,person:U?.id?{id:U.id?.value??"",email:U.email?.value??"",givenName:U.firstName?.value??"",familyName:U.lastName?.value??""}:null,geoCoordinates:p?.latitude&&p?.longitude&&p||null,city:d};return Dn(e,E)?null:E},Gt={validateCart:xt,validateSession:Wt,subscribeToNewsletter:Ut,cancelOrder:wt,processOrderAuthorization:Pt};var Cn;(function(n){n.NAME="Name",n.DOCUMENT="Document",n.OPERATION_DEFINITION="OperationDefinition",n.VARIABLE_DEFINITION="VariableDefinition",n.SELECTION_SET="SelectionSet",n.FIELD="Field",n.ARGUMENT="Argument",n.FRAGMENT_SPREAD="FragmentSpread",n.INLINE_FRAGMENT="InlineFragment",n.FRAGMENT_DEFINITION="FragmentDefinition",n.VARIABLE="Variable",n.INT="IntValue",n.FLOAT="FloatValue",n.STRING="StringValue",n.BOOLEAN="BooleanValue",n.NULL="NullValue",n.ENUM="EnumValue",n.LIST="ListValue",n.OBJECT="ObjectValue",n.OBJECT_FIELD="ObjectField",n.DIRECTIVE="Directive",n.NAMED_TYPE="NamedType",n.LIST_TYPE="ListType",n.NON_NULL_TYPE="NonNullType",n.SCHEMA_DEFINITION="SchemaDefinition",n.OPERATION_TYPE_DEFINITION="OperationTypeDefinition",n.SCALAR_TYPE_DEFINITION="ScalarTypeDefinition",n.OBJECT_TYPE_DEFINITION="ObjectTypeDefinition",n.FIELD_DEFINITION="FieldDefinition",n.INPUT_VALUE_DEFINITION="InputValueDefinition",n.INTERFACE_TYPE_DEFINITION="InterfaceTypeDefinition",n.UNION_TYPE_DEFINITION="UnionTypeDefinition",n.ENUM_TYPE_DEFINITION="EnumTypeDefinition",n.ENUM_VALUE_DEFINITION="EnumValueDefinition",n.INPUT_OBJECT_TYPE_DEFINITION="InputObjectTypeDefinition",n.DIRECTIVE_DEFINITION="DirectiveDefinition",n.SCHEMA_EXTENSION="SchemaExtension",n.SCALAR_TYPE_EXTENSION="ScalarTypeExtension",n.OBJECT_TYPE_EXTENSION="ObjectTypeExtension",n.INTERFACE_TYPE_EXTENSION="InterfaceTypeExtension",n.UNION_TYPE_EXTENSION="UnionTypeExtension",n.ENUM_TYPE_EXTENSION="EnumTypeExtension",n.INPUT_OBJECT_TYPE_EXTENSION="InputObjectTypeExtension"})(Cn||(Cn={}));const Ht=n=>typeof n=="string"?ve(n):null;function ve(n){try{return JSON.parse(n)}catch{return n}}const Xt=n=>typeof n=="object"?JSON.stringify(n):typeof n=="string"?n:null,Yt=new nn.GraphQLScalarType({name:"ObjectOrString",description:"A string or the string representation of an object (a stringified object).",parseValue:Ht,serialize:Xt,parseLiteral(n){return n.kind===Cn.STRING?ve(n.value):null}}),R=n=>"Price"in n&&"seller"in n&&"product"in n,F=n=>"skuName"in n,Jt={priceCurrency:async(n,e,t)=>{const{loaders:{salesChannelLoader:r},storage:{channel:i}}=t;return(await r.load(i.salesChannel)).CurrencyCode??""},priceValidUntil:n=>R(n)?n.PriceValidUntil??"":F(n)?n.priceValidUntil??"":null,itemCondition:()=>"https://schema.org/NewCondition",availability:async n=>R(n)?Un(V(n)):F(n)?Un(dt(n.availability)):null,seller:(n,e,t)=>R(n)?{identifier:t.storage.channel?.seller||n.seller.sellerId||""}:F(n)?{identifier:n.seller}:null,price:n=>R(n)?G(n):F(n)?n.sellingPrice/100:null,priceWithTaxes:n=>R(n)?x(G(n),n?.Tax,n.product.unitMultiplier):F(n)?x(n.sellingPrice/100,n.tax/100,n.unitMultiplier):null,sellingPrice:n=>R(n)?lt(n):F(n)?n.sellingPrice/100:null,listPrice:n=>R(n)?n.ListPrice??0:F(n)?n.listPrice/100:null,listPriceWithTaxes:n=>R(n)?x(n.ListPrice??0,n?.Tax,n.product.unitMultiplier):F(n)?x(n.listPrice/100,n.tax/100,n.unitMultiplier):null,itemOffered:n=>R(n)?n.product:F(n)?{...n.product,attachmentsValues:n.attachments}:null,quantity:n=>R(n)?n.AvailableQuantity??0:F(n)?n.quantity:null,isGift:n=>F(n)?n.isGift??!1:null},Kt=({linkText:n})=>`/${n}/p`,Qt=({offer:n,seller:e,product:t})=>({...n,product:t,seller:e}),Zt={imageText:"image",imageUrl:"https://storecomponents.vtexassets.com/assets/faststore/images/image___117a6d3e229a96ad0e0d0876352566e2.svg",imageLabel:"label"},Oe=(n,e)=>`${n}-${e}`,nr=(n,e)=>`/${Oe(n,e)}/p`,er=n=>Array.isArray(n)&&n.length>0?n:null;function Ce(n){return n.replace(/^\/+|\/+$/g,"")}const tr=(n,e)=>{const t=n.findIndex(r=>Ce(r).split("/").at(-1)===e);return t<0?0:t},rr={productID:({itemId:n})=>n,name:({isVariantOf:n,name:e})=>e??n.productName,slug:({isVariantOf:{linkText:n},itemId:e})=>Oe(n,e),description:({isVariantOf:{description:n}})=>n,seo:({isVariantOf:n})=>({title:n.productTitle||n.productName,description:n.metaTagDescription||n.description,canonical:Kt(n)}),brand:({isVariantOf:{brand:n}})=>({name:n}),unitMultiplier:({unitMultiplier:n})=>n,breadcrumbList:({isVariantOf:{categories:n,productName:e,linkText:t,categoryId:r,categoriesIds:i},itemId:a})=>{const o=tr(i,r),s=n[o],c=Ce(s).split("/");return{itemListElement:[...c.map((d,p)=>{const m=`/${c.slice(0,p+1).map(ce).join("/")}/`;return{name:d,item:m,position:p+1}}),{name:e,item:nr(t,a),position:c.length+1}],numberOfItems:c.length}},image:({images:n},e)=>{const t=(er(n)??[Zt]).map(({imageUrl:s,imageText:c,imageLabel:d})=>({alternateName:c??"",url:s.replace("vteximg.com.br","vtexassets.com"),keywords:d}));if(typeof e!="object")return t;let{context:r,limit:i}=e;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:n})=>n,gtin:({ean:n,referenceId:e})=>n||(e[0]?.Value??""),mpn:({isVariantOf:{manufacturerCode:n}})=>n??"",review:()=>[],aggregateRating:()=>({}),offers:n=>n.sellers.map(e=>Qt({offer:e.commertialOffer,seller:e,product:n})).sort(se),isVariantOf:n=>n,additionalProperty:({variations:n=[],attachmentsValues:e=[],attributes:t=[]})=>{const r=n.flatMap(({name:o,values:s})=>s.map(c=>({name:o,value:c,valueReference:Q.specification}))),i=e.map(ge),a=t.map(kt);return[...r,...i,...a]},hasSpecifications:({isVariantOf:n})=>!!n.skuSpecifications?.length,skuSpecifications:({isVariantOf:{skuSpecifications:n}})=>n??[],specificationGroups:({isVariantOf:{specificationGroups:n}})=>n,releaseDate:({isVariantOf:{releaseDate:n}})=>n??"",advertisement:({isVariantOf:{advertisement:n}})=>n,deliveryPromiseBadges:({isVariantOf:{deliveryPromisesBadges:n}})=>n},ir=new Set(["allSpecifications"]),ar={hasVariant:n=>n.isVariantOf.items.map(e=>M(e,n.isVariantOf)),productGroupID:({isVariantOf:n})=>n.productId,name:n=>n.isVariantOf.productName,skuVariants:n=>n,additionalProperty:({isVariantOf:{specificationGroups:n}})=>n.filter(e=>!ir.has(e.name)).flatMap(({specifications:e})=>e.flatMap(({name:t,values:r})=>r.map(i=>({name:t,value:i,valueReference:Q.specification}))))},or={propertyID:n=>n.propertyID||me(n),name:({name:n})=>n,value:({value:n})=>n,valueReference:({valueReference:n})=>n},bn=n=>{const e=n.flatMap(r=>r.sellers.map(i=>({offer:i.commertialOffer,sku:r}))),t=yn(e,({offer:r},{offer:i})=>se(r,i));return t?t.sku:n[0]},sr=n=>n!==""&&!Number.isNaN(Number(n)),cr={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:""},lr={product:async(n,{locator:e},t)=>{const r=Fn(e),i=Nn(e),a=vt(e),o=It(e);r&&In(t,r),i&&vn(t,i);const{loaders:{skuLoader:s},clients:{commerce:c,search:d}}=t;try{const p=a??o?.split("-").pop()??"";if(!sr(p))throw new Error("Invalid SkuId");const m=await s.load(p);if(o&&m.isVariantOf.linkText&&!o.startsWith(m.isVariantOf.linkText))throw new Error(`Slug was set but the fetched sku does not satisfy the slug condition. slug: ${o}, linkText: ${m.isVariantOf.linkText}`);return m}catch{if(o==null)throw new $("Missing slug or id");const m=await c.catalog.portal.pagetype(`${o}/p`);if(m.pageType!=="Product"||!m.id)throw new B(`No product found for slug ${o}`);const{products:[u]}=await d.products({page:0,count:1,query:`product:${m.id}`,hideUnavailableItems:!1});if(!u)throw new B(`No product found for id ${m.id}`);const l=bn(u.items);return M(l,u)}},collection:(n,{slug:e},t)=>{const{loaders:{collectionLoader:r}}=t;return r.load(e)},search:async(n,{first:e,after:t,sort:r,term:i,selectedFacets:a,sponsoredCount:o},s)=>{const c=Fn(a),d=Nn(a),p=yt(a);c&&In(s,c),d&&vn(s,d);let m=i;p&&(m=`product:${(await s.clients.commerce.catalog.products.crossselling({type:de[p.key],productId:p.value})).map(S=>S.productId).slice(0,e).join(";")}`);const u=t?Number(t):0,l={page:Math.ceil(u/e)||0,count:e,query:m??void 0,sort:cr[r??"score_desc"],selectedFacets:a?.flatMap(_n)??[],sponsoredCount:o??void 0},g=s.clients.search.products(l);return{searchArgs:l,productSearchPromise:g}},allProducts:async(n,{first:e,after:t},r)=>{const{clients:{search:i}}=r,a=t?Number(t):0,o=await i.products({page:Math.ceil(a/e),count:e}),s=o.products.flatMap(c=>c.items.map(d=>M(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(n,{productIds:e},t)=>{const{clients:{search:r}}=t;if(!e.length)return[];const i=`id:${e.join(";")}`;return(await r.products({page:0,count:e.length,query:i})).products.flatMap(o=>o.items.map(s=>M(s,o))).filter(o=>e.includes(o.itemId)&&o.sellers.length>0)},allCollections:async(n,{first:e,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=(u,l)=>{c.push({...u,level:l});for(const g of u.children)d(g,l+1)};for(const u of s)d(u,0);const m=[...o.filter(u=>u.isActive).map(u=>({...u,type:"brand"})),...c].filter(u=>!!le.slug(u,null,r,null));return{pageInfo:{hasNextPage:m.length-a>e,hasPreviousPage:a>0,startCursor:"0",endCursor:(Math.min(e,m.length-a)-1).toString(),totalCount:m.length},edges:m.slice(a,a+e).map((u,l)=>({node:u,cursor:(a+l).toString()}))}},shipping:async(n,{country:e,items:t,postalCode:r},i)=>{const{loaders:{simulationLoader:a},clients:{commerce:o}}=i,[s,c]=await Promise.all([a.load({country:e,items:t,postalCode:r}),o.checkout.address({postalCode:r,country:e})]);return{...s,address:c}},redirect:async(n,{term:e,selectedFacets:t},r)=>{if(!e&&(!t||!t.length))return null;const{redirect:i}=await r.clients.search.products({page:1,count:1,query:e??void 0,selectedFacets:t?.flatMap(_n)??[],allowRedirect:!0});return{url:i}},sellers:async(n,{postalCode:e,geoCoordinates:t,country:r,salesChannel:i},a)=>{const{clients:{commerce:o}}=a,c=(await o.checkout.region({postalCode:e,geoCoordinates:t,country:r,salesChannel:i}))?.[0],{id:d,sellers:p}=c;return{id:d,sellers:p}},profile:async(n,{id:e},t)=>{const{clients:{commerce:r}}=t,i=await r.profile.addresses(e);function a(s){return!s||Object.keys(s).length===0?[]:Object.values(s).map(c=>JSON.parse(c))}return{addresses:a(i)}},productCount:async(n,{term:e},t)=>{const{clients:{search:r}}=t;return await r.productCount({query:e??void 0})},userOrder:async(n,{orderId:e},t)=>{try{if(!e)throw new $("Missing orderId");const{clients:{commerce:r}}=t,i=await r.oms.userOrder({orderId:e});if(!i)throw new B(`No order found for id ${e}`);let a=null;try{const c=await r.oms.getCommercialAuthorizationsByOrderId({orderId:e});a=ue(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 te(r)?new B(`No order found for id ${e}. ${o}.`):ee(r)?new K(`You are forbidden to interact with order with id ${e}. ${o}.`):r}},listUserOrders:async(n,e,t)=>{const{clients:{commerce:r}}=t,i=await r.oms.listUserOrders(e);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}},validateUser:async(n,e,t)=>({isValid:!0}),userDetails:async(n,e,t)=>{const{account:r,headers:i,clients:{commerce:a}}=t,s=tn(en(i?.cookie??"",r))?.userId??"",[c,d,p]=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)]),m=d?.[0],u=c?.namespaces.authentication??null,l=`${(m?.firstName??"").trim()} ${(m?.lastName??"").trim()}`.trim();return{username:u?.storeUserEmail?.value??"",name:l,email:u?.storeUserEmail?.value??"",phone:m?.phone??"",role:p?.Roles?.map(g=>g.Name)??[],orgUnit:u?.unitName?.value??""}},accountProfile:async(n,e,t)=>{const{account:r,headers:i,clients:{commerce:a}}=t,o=tn(en(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;return{name:((await a.masterData.getContractById({contractId:d?.id?.value??""}))?.corporateName??`${(d?.firstName?.value??"").trim()} ${(d?.lastName?.value??"").trim()}`.trim())||"",email:d?.email?.value||"",id:d?.id?.value||""}}const s=await a.licenseManager.getUserById({userId:o?.userId}).catch(()=>null);return{name:s?.name||"",email:s?.email||"",id:s?.id||""}},pickupPoints:async(n,{geoCoordinates:e},t)=>{const{clients:{commerce:r}}=t;return await r.checkout.pickupPoints({geoCoordinates:e})}},dr={reviewRating:()=>({ratingValue:5,bestRating:5}),author:()=>({name:""})},ur=(n,e,t)=>e?n.key==="category-1":t?n.key==="brand":!1,pr={suggestions:async(n,e,t)=>{const{clients:{search:r}}=t,{searchArgs:i}=n;if(!i.query)return{terms:(await r.topSearches()).searches.map(m=>({value:m.term,count:m.count})),products:[]};const{productSearchPromise:a}=n,[o,s]=await Promise.all([r.suggestedTerms(i),a]),c=s.products.map(p=>{const m=bn(p.items);return m&&M(m,p)}).filter(p=>!!p),{searches:d}=o;return{terms:d.map(p=>({value:p.term,count:p.count})),products:c}},products:async({productSearchPromise:n})=>{const e=await n,t=e.products.map(r=>{const i=bn(r.items);return i&&M(i,r)}).filter(r=>!!r);return{pageInfo:{hasNextPage:e.pagination.after.length>0,hasPreviousPage:e.pagination.before.length>0,startCursor:"0",endCursor:e.recordsFiltered.toString(),totalCount:e.recordsFiltered},edges:t.map((r,i)=>({node:r,cursor:i.toString()}))}},facets:async({searchArgs:n},e,t)=>{const{clients:{search:r}}=t;t.storage.searchArgs=n;const{facets:i=[]}=await r.facets(n),a=!n.query,o=n.selectedFacets?.length?n.selectedFacets[0].key==="category-1":!1,s=n.selectedFacets?.length?n.selectedFacets[0].key==="brand":!1;return i.filter(d=>!a||!ur(d,o,s))},metadata:async({productSearchPromise:n})=>{const e=await n;return{isTermMisspelled:e.correction?.misspelled??!1,logicalOperator:e.operator,fuzzy:e.fuzzy}},searchId:async({productSearchPromise:n})=>(await n).searchId},gr={title:({title:n})=>n??"",description:({description:n})=>n??"",canonical:({canonical:n})=>n??"",titleTemplate:()=>""},mr=["bd","d","h","m"],hr=n=>mr.includes(n),fr={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"}},be=n=>{const[e,t]=[n.split(/\D+/)[0],n.split(/[0-9]+/)[1]],r=e!==""&&!Number.isNaN(Number(e)),i=hr(t);if(!r||!i)return"";const a=Number(e)<2?Number(e):"other";return fr[t][a].replace("#",e)??""},Sr={carrier:n=>n?.friendlyName??n?.name??"",price:n=>n?.price?n.price/100:n?.price,localizedEstimates:n=>n?.shippingEstimate?be(n.shippingEstimate):""},zn="skuvariation";function Vn(n,e){const t=`${zn}${e}`.toLowerCase(),r=n.find(a=>a.imageLabel===t);if(r)return r;const i=n.find(a=>a.imageLabel===zn);return i||n[0]}function yr(n,e,t){const r={};return n.forEach(i=>{const a=i.variations;if(a.length===0)return;const o=`${e}-${a.find(c=>c.name===e)?.values[0]??""}`,s=a.reduce((c,d)=>d.name===e?c:c+`-${d.name}-${d.values[0]}`,o);r[s]=`${t}-${i.itemId}`}),r}function qn(n){const e={};return n.forEach(t=>{e[t.name]=t.values[0]}),e}function Ir(n){const e={};return n?.forEach(t=>{e[t.field.originalName??t.field.name]=t.values.map(r=>r.originalName??r.name)}),e}function vr(n,e){return Number.isNaN(Number(n)-Number(e))?n<e?-1:n>e?1:0:Number(n)-Number(e)}function Or(n){const e=n;for(const t in n)n[t].every(i=>!Number.isNaN(Number(i.value)))&&n[t].sort((i,a)=>vr(i.value,a.value));return e}function Cr(n,e,t){const r={},i=new Set;return n.forEach(a=>{if(a.variations.length===0)return;const o=a.variations.find(c=>c.name===e);if(!(o?.values[0]===t)){const c=`${e}-${o?.values[0]}`;if(!o||i.has(c))return;i.add(c);const d=Vn(a.images,e),p={src:d.imageUrl,alt:d.imageLabel??"",label:`${e}: ${o.values[0]}`,value:o.values[0]};r[o.name]?r[o.name].push(p):r[o.name]=[p];return}a.variations.forEach(c=>{const d=`${c.name}-${c.values[0]}`;if(i.has(d))return;i.add(d);const p=Vn(a.images,c.name),m={src:p.imageUrl,alt:p.imageText??"",label:`${c.name}: ${c.values[0]}`,value:c.values[0]};r[c.name]?r[c.name].push(m):r[c.name]=[m]})}),Or(r)}const br={activeVariations:n=>qn(n.variations),allVariantsByName:n=>Ir(n.isVariantOf.skuSpecifications),slugsMap:(n,e)=>yr(n.isVariantOf.items,e.dominantVariantName??n.variations[0]?.name,n.isVariantOf.linkText),availableVariations:(n,e)=>{const t=e.dominantVariantName??n.variations[0]?.name,i=qn(n.variations)[t];return Cr(n.isVariantOf.items,t,i)},allVariantProducts:n=>n.isVariantOf.items.map(e=>M(e,n.isVariantOf))},Dr={"pickup-in-point":"Pickup",delivery:"Delivery",pickup:"Pickup","take-away":"Take away","":""},wr={deliveryOptionsData:n=>{const{shippingData:e,items:t}=n,r=e?.logisticsInfo||[],i=e?.selectedAddresses||e?.availableAddresses||[e?.address],a=r.reduce((d,p)=>{const m=p?.selectedSla||"",u=p?.selectedDeliveryChannel||p?.deliveryChannel||"",l=p?.deliveryCompany||"",g=p?.deliveryWindow,f=p?.pickupStoreInfo,S=p?.shippingEstimate||"",O=p?.shippingEstimate?be(p?.shippingEstimate):"",D=p?.shippingEstimateDate||"",A=p?.addressId||"",_=p?.itemIndex??0,v=t?.[_],U=v?.seller||"",h=`${m}|${u}|${l}|${U}|${S}|${D}|${A}|${g?.startDateUtc}|${g?.endDateUtc}`,C=i?.find(P=>P?.addressId===A),b=`${Dr[u]||""} ${O} ${C?.neighborhood?`to ${C?.neighborhood}`:""}`.trim(),{taxPriceTagsTotal:k,taxPriceTags:y}=Ar(v?.priceTags??[]),w=(v?.sellingPrice??0)*(v?.quantity??0)+(v?.tax??0)+(k??0);return d[h]||(d[h]={selectedSla:m,deliveryChannel:u,deliveryCompany:l,deliveryWindow:g,shippingEstimate:S,shippingEstimateDate:D,seller:U,friendlyShippingEstimate:O,friendlyDeliveryOptionName:b,address:C,pickupStoreInfo:f,quantityOfDifferentItems:0,total:0,items:[]}),d[h]&&(d[h].items?.push({id:v?.id||"",uniqueId:v?.uniqueId||"",name:v?.name||"",quantity:v?.quantity||0,price:v?.price||0,sellingPrice:v?.sellingPrice||0,imageUrl:v?.imageUrl||"",taxPriceTags:y??[],taxPriceTagsTotal:k??0,tax:v?.tax||0,total:w}),d[h].quantityOfDifferentItems=(d[h].quantityOfDifferentItems??0)+1,d[h].total=(d[h].total??0)+w),d},{}),o=Object.values(a),s=e?.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:n=>{const e=n?.customData?.customFields||[];return Object.values(e.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 Ar(n){const t=n.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 Pr={StoreCollection:le,StoreAggregateOffer:pt,StoreProduct:rr,StoreSeo:gr,StoreFacet:Ot,StoreFacetBoolean:Ct,StoreFacetRange:bt,StoreFacetValueBoolean:Dt,StoreOffer:Jt,StoreAggregateRating:gt,StoreReview:dr,StoreProductGroup:ar,StoreSearchResult:pr,StorePropertyValue:or,SkuVariants:br,ShippingSLA:Sr,UserOrderResult:wr,ObjectOrString:Yt,Query:lr,Mutation:Gt},Ur=()=>Pr,kr=`"""
7
7
  Address information.
8
8
  """
9
9
  type Address {
@@ -48,7 +48,7 @@ type Address {
48
48
  """
49
49
  geoCoordinates: [Float]
50
50
  }
51
- `,_r=`"""
51
+ `,Tr=`"""
52
52
  Advertisement information about a specific product in a campaign
53
53
  """
54
54
  type Advertisement {
@@ -73,7 +73,7 @@ type Advertisement {
73
73
  """
74
74
  adResponseId: String!
75
75
  }
76
- `,Tr=`"""
76
+ `,_r=`"""
77
77
  Aggregate offer information, for a given SKU that is available to be fulfilled by multiple sellers.
78
78
  """
79
79
  type StoreAggregateOffer {
@@ -1967,6 +1967,10 @@ type SellerInfo {
1967
1967
  User details information.
1968
1968
  """
1969
1969
  type StoreUserDetails {
1970
+ """
1971
+ User's username (login). May differ from email when Alternative Login is enabled.
1972
+ """
1973
+ username: String
1970
1974
  """
1971
1975
  User's name.
1972
1976
  """
@@ -1976,6 +1980,10 @@ type StoreUserDetails {
1976
1980
  """
1977
1981
  email: String
1978
1982
  """
1983
+ User's phone number.
1984
+ """
1985
+ phone: String
1986
+ """
1979
1987
  User's role.
1980
1988
  """
1981
1989
  role: [String]
@@ -3574,4 +3582,4 @@ type UserOrderBudgetAllocationLinkedEntity {
3574
3582
  type: String
3575
3583
  id: String
3576
3584
  }
3577
- `,di=Object.assign({"./address.graphql":Ur,"./advertisement.graphql":_r,"./aggregateOffer.graphql":Tr,"./aggregateRating.graphql":Er,"./author.graphql":Nr,"./brand.graphql":Fr,"./breadcrumb.graphql":Rr,"./cart.graphql":Lr,"./collection.graphql":Br,"./deliveryPromisesBadge.graphql":Mr,"./facet.graphql":$r,"./image.graphql":zr,"./mutation.graphql":Vr,"./newsletter.graphql":qr,"./objectOrString.graphql":xr,"./offer.graphql":jr,"./order.graphql":Wr,"./orderCommercialAuthorizaton.graphql":Gr,"./organization.graphql":Hr,"./pageInfo.graphql":Xr,"./password.graphql":Yr,"./person.graphql":Jr,"./pickupPoints.graphql":Kr,"./product.graphql":Qr,"./productGroup.graphql":Zr,"./profile.graphql":ni,"./propertyValue.graphql":ei,"./query.graphql":ti,"./review.graphql":ri,"./seo.graphql":ii,"./session.graphql":ai,"./shipping.graphql":oi,"./skuVariants.graphql":si,"./status.graphql":ci,"./userOrder.graphql":li}),ui=nn.print(Object.values(di).map(n=>nn.parse(n)).reduce((n,e)=>xn.mergeTypeDefs([n,e],{sort:!0}))),De=ui,pi=async n=>L.OTELAPI.context.with(L.OTELAPI.propagation.extract(L.OTELAPI.context.active(),n.OTEL),()=>e=>(e.storage={channel:en.parse(n.channel),flags:n.flags??{},locale:n.locale,cookies:new Map},e.clients=Qe(n,e),e.loaders=ct(n,e),e.account=n.account,e.OTEL=n.OTEL,e.discoveryConfig=n.discoveryConfig,e));function gi(){const n=kr(),e={};for(const[t,r]of Object.entries(n))e[t]=Object.fromEntries(Object.entries(r).map(([i,a])=>typeof a!="function"?[i,a]:[i,Re(a,`${t}(${i})`)]));return e}function mi(n){const t=ne([Zn,Qn])(gi(),De);return n&&nn.isSchema(n)?jn.mergeSchemas({schemas:[t,n]}):t}exports.AuthDirective=Qn;exports.BadRequestError=$;exports.CacheControlDirective=Zn;exports.CommercialAuthorizationStatus=Gn;exports.FastStoreError=H;exports.ForbiddenError=K;exports.GraphqlVtexContextFactory=pi;exports.GraphqlVtexSchema=mi;exports.NotFoundError=B;exports.StoreCollectionType=Hn;exports.StoreFacetType=Xn;exports.StoreSort=Yn;exports.StoreStatus=Jn;exports.UnauthorizedError=J;exports.UserOrderInvoiceType=Kn;exports.isBadRequestError=Be;exports.isFastStoreError=Le;exports.isForbiddenError=ee;exports.isNotFoundError=te;exports.isUnauthorizedError=Me;exports.stringifyCacheControl=Ne;exports.typeDefs=De;exports.withDirectives=ne;
3585
+ `,di=Object.assign({"./address.graphql":kr,"./advertisement.graphql":Tr,"./aggregateOffer.graphql":_r,"./aggregateRating.graphql":Er,"./author.graphql":Nr,"./brand.graphql":Fr,"./breadcrumb.graphql":Rr,"./cart.graphql":Lr,"./collection.graphql":Br,"./deliveryPromisesBadge.graphql":Mr,"./facet.graphql":$r,"./image.graphql":zr,"./mutation.graphql":Vr,"./newsletter.graphql":qr,"./objectOrString.graphql":xr,"./offer.graphql":jr,"./order.graphql":Wr,"./orderCommercialAuthorizaton.graphql":Gr,"./organization.graphql":Hr,"./pageInfo.graphql":Xr,"./password.graphql":Yr,"./person.graphql":Jr,"./pickupPoints.graphql":Kr,"./product.graphql":Qr,"./productGroup.graphql":Zr,"./profile.graphql":ni,"./propertyValue.graphql":ei,"./query.graphql":ti,"./review.graphql":ri,"./seo.graphql":ii,"./session.graphql":ai,"./shipping.graphql":oi,"./skuVariants.graphql":si,"./status.graphql":ci,"./userOrder.graphql":li}),ui=nn.print(Object.values(di).map(n=>nn.parse(n)).reduce((n,e)=>xn.mergeTypeDefs([n,e],{sort:!0}))),De=ui,pi=async n=>L.OTELAPI.context.with(L.OTELAPI.propagation.extract(L.OTELAPI.context.active(),n.OTEL),()=>e=>(e.storage={channel:rn.parse(n.channel),flags:n.flags??{},locale:n.locale,cookies:new Map},e.clients=Qe(n,e),e.loaders=ct(n,e),e.account=n.account,e.OTEL=n.OTEL,e.discoveryConfig=n.discoveryConfig,e));function gi(){const n=Ur(),e={};for(const[t,r]of Object.entries(n))e[t]=Object.fromEntries(Object.entries(r).map(([i,a])=>typeof a!="function"?[i,a]:[i,Re(a,`${t}(${i})`)]));return e}function mi(n){const t=ne([Zn,Qn])(gi(),De);return n&&nn.isSchema(n)?jn.mergeSchemas({schemas:[t,n]}):t}exports.AuthDirective=Qn;exports.BadRequestError=$;exports.CacheControlDirective=Zn;exports.CommercialAuthorizationStatus=Gn;exports.FastStoreError=H;exports.ForbiddenError=K;exports.GraphqlVtexContextFactory=pi;exports.GraphqlVtexSchema=mi;exports.NotFoundError=B;exports.StoreCollectionType=Hn;exports.StoreFacetType=Xn;exports.StoreSort=Yn;exports.StoreStatus=Jn;exports.UnauthorizedError=J;exports.UserOrderInvoiceType=Kn;exports.isBadRequestError=Be;exports.isFastStoreError=Le;exports.isForbiddenError=ee;exports.isNotFoundError=te;exports.isUnauthorizedError=Me;exports.stringifyCacheControl=Ne;exports.typeDefs=De;exports.withDirectives=ne;