@faststore/api 4.4.0 → 4.4.1-dev.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/index.js +1 -1
- package/dist/cjs/index.js.map +1 -1
- package/dist/es/index.mjs +1 -1
- package/package.json +3 -3
package/dist/cjs/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const Ge=require("@graphql-tools/merge"),He=require("@graphql-tools/schema"),z=require("@graphql-tools/utils"),N=require("@faststore/diagnostics"),ee=require("graphql"),J=require("cookie"),kn=require("isomorphic-unfetch"),ve=require("p-limit"),ae=require("dataloader"),_n=require("sanitize-html"),Oe=require("fast-deep-equal"),Fn=require("node:crypto");var Xe=(e=>(e.Accepted="accepted",e.Denied="denied",e.Pending="pending",e))(Xe||{}),Ye=(e=>(e.Brand="Brand",e.Category="Category",e.Cluster="Cluster",e.Collection="Collection",e.Department="Department",e.SubCategory="SubCategory",e))(Ye||{}),Je=(e=>(e.Boolean="BOOLEAN",e.Range="RANGE",e))(Je||{}),Ke=(e=>(e.DiscountDesc="discount_desc",e.NameAsc="name_asc",e.NameDesc="name_desc",e.OrdersDesc="orders_desc",e.PriceAsc="price_asc",e.PriceDesc="price_desc",e.ReleaseDesc="release_desc",e.ScoreDesc="score_desc",e))(Ke||{}),Qe=(e=>(e.Error="ERROR",e.Info="INFO",e.Warning="WARNING",e))(Qe||{}),Ze=(e=>(e.Input="Input",e.Output="Output",e))(Ze||{});const Rn=()=>function(n={}){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{...n,"X-VTEX-API-AppKey":t,"X-VTEX-API-AppToken":r}},Nn=async e=>{const{clients:{commerce:n}}=e;try{if((await n.vtexid.validate())?.authStatus?.toLowerCase()!=="success")throw new Y("Authentication required")}catch(t){const r=t.extensions?.status??t.status;throw r===401?new Y("Authentication required"):r===403?new K("You are not allowed to access this resource"):new Y("Authentication required")}},Ln="auth",en={typeDefs:"directive @auth on FIELD_DEFINITION",transformer:e=>z.mapSchema(e,{[z.MapperKind.OBJECT_FIELD]:n=>{if(z.getDirective(e,n,Ln)?.[0]){const r=n.resolve;n.resolve=async(i,a,o,s)=>(await Nn(o),r?.(i,a,o,s))}return n}})},Bn="cacheControl",Mn=(e,n)=>{const{scope:t="private",sMaxAge:r=0,staleWhileRevalidate:i=0}=e;return`${n?"private":t}, s-maxage=${r}, stale-while-revalidate=${i}`},De=(e,n)=>typeof e=="number"&&typeof n=="number"?e>n?n:e:typeof e=="number"?e:n,$n=(e,n)=>typeof e=="string"&&typeof n=="string"?e==="public"&&n==="public"?"public":"private":e||n,nn={typeDefs:"directive @cacheControl(sMaxAge: Int, staleWhileRevalidate: Int, scope: String) on FIELD_DEFINITION",transformer:e=>z.mapSchema(e,{[z.MapperKind.OBJECT_FIELD]:n=>{const t=z.getDirective(e,n,Bn)?.[0];if(t){const{sMaxAge:r,staleWhileRevalidate:i,scope:a}=t,o=n.resolve;n.resolve=(s,l,d,g)=>(d.cacheControl={sMaxAge:De(d.cacheControl?.sMaxAge,r),staleWhileRevalidate:De(d.cacheControl?.staleWhileRevalidate,i),scope:$n(d.cacheControl?.scope,a)},o?.(s,l,d,g))}return n}})},tn=e=>(n,t)=>{const r=Ge.mergeTypeDefs([...(e??[]).map(({typeDefs:i})=>i),t]);return(e??[]).reduce((i,{transformer:a})=>a?.(i)??i,He.makeExecutableSchema({typeDefs:r,resolvers:n}))},ce="@faststore/api",le="4.4.0-dev.6",Pe={name:ce,version:le},zn=(e,n)=>(t,r,i,a)=>{if((i?.OTEL?.enabled??!1)===!1)return e(t,r,i,a);const o=N.OTELAPI.trace.getTracer(ce,le),s=N.OTELAPI.propagation.extract(N.OTELAPI.context.active(),i.OTEL);return N.OTELAPI.context.with(s,()=>{const l=o.startSpan(n??"Unknown Graphql Resolver",{startTime:Date.now(),kind:N.OTELAPI.SpanKind.INTERNAL,attributes:{timestamp:Date.now(),"@faststore_version":le,"@faststore_package_name":ce,"@faststore_account_name":i.account,"@faststore_environment":process.env.NODE_ENV}});if(!l)return e(t,r,i,a);try{const d=e(t,r,i,a);return d instanceof Promise?d.then(g=>(l.end(),g)):(l.end(),d)}catch(d){throw l.end(),console.error(`Error when executing resolver: ${n}`,d),d}})};class q extends Error{constructor(n,t){super(t),this.extensions=n,this.name="FastStoreError"}}class T extends q{constructor(n){super({status:400,type:"BadRequestError"},n)}}class Y extends q{constructor(n){super({status:401,type:"UnauthorizedError"},n)}}class K extends q{constructor(n){super({status:403,type:"ForbiddenError"},n)}}class L extends q{constructor(n){super({status:404,type:"NotFoundError"},n)}}const Vn=e=>e?.name==="FastStoreError",xn=e=>e?.extensions?.type==="BadRequestError",qn=e=>e?.extensions?.type==="UnauthorizedError",rn=e=>e?.extensions?.type==="ForbiddenError",Ce=e=>e?.extensions?.type==="NotFoundError",jn=`${Pe.name}@${Pe.version}`,y=async(e,n,t)=>{const r=await kn(e,{...n,headers:{...n?.headers??{},"User-Agent":jn}});if(r.ok)return t?.storeCookies&&t.storeCookies(r.headers),r.status!==204?r.json():void 0;console.error(e,n,r);const i=await r.text();if(typeof r?.status=="number")switch(r.status){case 400:throw new T(i);case 401:throw new Y(i);case 403:throw new K(i);case 404:throw new L(i);default:throw new q({status:r.status,type:"UnknownError"},i)}throw new Error(i)},an=e=>{if(!e)return e;const n=new Map,t=e.split(";"),r=[];return t.forEach(i=>{const a=i.trim();if(a){const o=a.indexOf("=");if(o>0){const s=a.substring(0,o),l=a.substring(o+1);n.has(s)||r.push(s),n.set(s,l)}}}),r.map(i=>`${i}=${n.get(i)}`).join("; ")},Wn=/^([^=]+)=([^;]*)/,Gn=(e,n)=>{const t=n.match(Wn);if(t){const r=t[1],i=t[2];e.storage.cookies.set(r,{value:i,setCookie:n})}},Hn=(e,n)=>{n.getSetCookie().forEach(t=>Gn(e,t))},Xn=e=>n=>Hn(e,n),on=e=>{if(!e.headers?.cookie)return null;const n=an(e.headers.cookie),t=Array.from(e.storage.cookies.entries());return t.length===0?n:t.reduce((r,[i,{value:a}])=>Yn(r,i,a),n)},sn=e=>function(t){const r=on(e);return r?{...t,cookie:r}:t},ne=(e,n)=>{const t=an(e);return J.parse(t)[`VtexIdclientAutCookie_${n}`]||""},Yn=(e,n,t)=>{const r=new RegExp(`(${n})=([^;]*)`),i=e.match(r);return i?e.replace(i[0],`${i[1]}=${t}`):`${e};${n}=${t}`};function te(e){return e?JSON.parse(Buffer.from(e.split(".")[1],"base64").toString()):null}const G={method:"POST",headers:{"content-type":"application/json"}},Jn=({account:e,environment:n,incrementAddress:t,subDomainPrefix:r},i)=>{const a=`https://${e}.${n}.com.br`,o=Xn(i),s=sn(i),l=Rn(),d=new Headers(i.headers).get("x-forwarded-host")??i.headers?.host??"",g=r&&r.map(c=>c+".").find(c=>d.includes(c))||"",p=d.replace(g,"");return{catalog:{salesChannel:c=>y(`${a}/api/catalog_system/pub/saleschannel/${c}`,void 0,{storeCookies:o}),brand:{list:()=>y(`${a}/api/catalog_system/pub/brand/list`,void 0,{storeCookies:o})},category:{tree:(c=3)=>y(`${a}/api/catalog_system/pub/category/tree/${c}`,void 0,{storeCookies:o})},portal:{pagetype:c=>y(`${a}/api/catalog_system/pub/portal/pagetype/${c}`,void 0,{storeCookies:o})},products:{crossselling:({type:c,productId:u,groupByProduct:m=!0})=>{const S=new URLSearchParams({sc:i.storage.channel.salesChannel,groupByProduct:m.toString()});return y(`${a}/api/catalog_system/pub/products/crossselling/${c}/${u}?${S}`,void 0,{storeCookies:o})}}},checkout:{simulation:(c,{salesChannel:u}=i.storage.channel)=>{const m=new URLSearchParams({sc:u}),S=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${a}/api/checkout/pub/orderForms/simulation?${m.toString()}`,{...G,headers:S,body:JSON.stringify(c)},{storeCookies:o})},shippingData:({id:c,index:u,deliveryMode:m,selectedAddresses:S},f)=>{const I=f?{startDateUtc:m?.deliveryWindow?.startDate,endDateUtc:m?.deliveryWindow?.endDate}:null,D={logisticsInfo:Array.from({length:u},(P,O)=>({itemIndex:O,selectedDeliveryChannel:m?.deliveryChannel||null,selectedSla:m?.deliveryMethod||null,deliveryWindow:I})),selectedAddresses:S,clearAddressIfPostalCodeNotFound:t},E=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${a}/api/checkout/pub/orderForm/${c}/attachments/shippingData`,{...G,headers:E,body:JSON.stringify(D)},{storeCookies:o})},marketingData:({id:c,marketingData:u})=>{const m=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${a}/api/checkout/pub/orderForm/${c}/attachments/marketingData`,{headers:m,body:JSON.stringify(u),method:"POST"},{storeCookies:o})},clientPreferencesData:({id:c,clientPreferencesData:u})=>{const m=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${a}/api/checkout/pub/orderForm/${c}/attachments/clientPreferencesData`,{headers:m,body:JSON.stringify(u),method:"POST"},{storeCookies:o})},orderForm:({id:c,refreshOutdatedData:u=!0,channel:m=i.storage.channel})=>{const{salesChannel:S}=m,f=s({"content-type":"application/json","X-FORWARDED-HOST":p}),I=new URLSearchParams({sc:S});c&&I.set("refreshOutdatedData",u.toString());const D=`${a}/api/checkout/pub/orderForm${c?`/${c}`:""}?${I.toString()}`;return y(D,{...G,headers:f,...c?{}:{body:"{}"}},{storeCookies:o})},clearOrderFormMessages:({id:c})=>{const u=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${a}/api/checkout/pub/orderForm/${c}/messages/clear`,{...G,headers:u,body:"{}"})},updateOrderFormItems:({id:c,orderItems:u,allowOutdatedData:m="paymentData",salesChannel:S=i.storage.channel.salesChannel,shouldSplitItem:f=!0})=>{const I=new URLSearchParams({allowOutdatedData:m,sc:S}),D=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${a}/api/checkout/pub/orderForm/${c}/items?${I}`,{headers:D,body:JSON.stringify({orderItems:u,noSplitItem:!f}),method:"PATCH"},{storeCookies:o})},setCustomData:({id:c,appId:u,key:m,value:S})=>{const f=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${a}/api/checkout/pub/orderForm/${c}/customData/${u}/${m}`,{headers:f,body:JSON.stringify({value:S}),method:"PUT"})},region:async({postalCode:c,geoCoordinates:u,country:m,salesChannel:S})=>{const f=new URLSearchParams({country:m,sc:S??""});c?f.append("postalCode",c):f.append("geoCoordinates",`${u?.longitude};${u?.latitude}`);const I=`${a}/api/checkout/pub/regions/?${f.toString()}`,D=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(I,{headers:D},{storeCookies:o})},address:async({postalCode:c,country:u})=>{const m=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${a}/api/checkout/pub/postal-code/${u}/${c}`,{headers:m},{storeCookies:o})},cancelOrder:({orderId:c,customerEmail:u,reason:m})=>{const S=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${a}/api/checkout/pub/orders/${c}/user-cancel-request`,{method:"POST",headers:S,body:JSON.stringify({customerEmail:u,reason:m})},{})},pickupPoints:({geoCoordinates:c})=>{if(!c)throw new Error("Missing required parameter for listing pickup points.");const u=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${a}/api/logistics-shipping/pickuppoints/_search`,{method:"POST",headers:u,body:JSON.stringify({coordinate:c})},{storeCookies:o})}},session:c=>{const u=new URLSearchParams(c);u.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 m=s({"content-type":"application/json"}),S=J.parse(i?.headers?.cookie??"")?.vtex_session;return y(`${a}/api/sessions?${u.toString()}`,{method:S?"PATCH":"POST",headers:m,body:"{}"},{storeCookies:o})},subscribeToNewsletter:c=>y(`${a}/api/dataentities/NL/documents/`,{...G,body:JSON.stringify({...c,isNewsletterOptIn:!0}),method:"PATCH"},{storeCookies:o}),profile:{addresses:async c=>{const u=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${a}/api/profile-system/pvt/profiles/${c}/addresses`,{headers:u},{storeCookies:o})}},oms:{userOrder:({orderId:c})=>{const u=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${a}/api/oms/user/orders/${c}`,{method:"GET",headers:u},{storeCookies:o})},listUserOrders:({page:c,status:u,dateInitial:m,dateFinal:S,text:f,clientEmail:I,perPage:D,pendingMyApproval:E})=>{const P=new URLSearchParams;if(m){const w=new Date(m).setHours(0,0,0,0);m=new Date(w).toISOString()}if(S){const w=new Date(S).setHours(23,59,59,999);S=new Date(w).toISOString()}f&&P.append("text",f),u&&u.length>0&&P.append("status",u.filter(Boolean).join(",")),m&&S?P.append("creation_date",`creationDate:[${m} TO ${S}]`):m?P.append("creation_date",`creationDate:[${m} TO *]`):S&&P.append("creation_date",`creationDate:[* TO ${S}]`),I&&P.append("clientEmail",I),c&&P.append("page",c.toString()),D&&P.append("per_page",D.toString()),E&&P.append("my_pending_approvals",String(!0));const O=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${a}/api/oms/user/orders?${P.toString()}`,{method:"GET",headers:O},{storeCookies:o})},getCommercialAuthorizationsByOrderId:({orderId:c})=>{const u=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${a}/${e}/commercial-authorizations/order/${c}`,{method:"GET",headers:u},{storeCookies:o})},processOrderAuthorization:async({orderAuthorizationId:c,dimensionId:u,ruleId:m,approved:S})=>{const f=s({"content-type":"application/json","X-FORWARDED-HOST":p}),E={params:{ruleId:m,dimensionId:u,score:S?100:0}};return y(`${a}/${e}/commercial-authorizations/${c}/callback`,{method:"POST",headers:f,body:JSON.stringify(E)},{storeCookies:o})}},units:{getUnitByUserId:({userId:c})=>{const u=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${a}/api/units/v1/${c}/unit`,{method:"GET",headers:u},{})},getOrgUnitById:({orgUnitId:c})=>{const u=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${a}/api/units/v1/${c}`,{method:"GET",headers:u},{})},getScopesByOrgUnit:({orgUnitId:c})=>{const u=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${a}/api/units/v1/${c}/scopes`,{method:"GET",headers:u},{})}},licenseManager:{getUserById:({userId:c})=>{const u=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${a}/api/license-manager/users/${c}`,{method:"GET",headers:u},{})},getUserByEmail:({email:c})=>{const u=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${a}/api/license-manager/pvt/users/${c}`,{method:"GET",headers:u},{})},getUserRoles:({userId:c})=>{const u=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${a}/api/license-manager/storefront/users/${c}/roles`,{method:"GET",headers:u},{})}},masterData:{getContractById:({contractId:c})=>{if(!c)throw new T("Missing contractId to fetch CL fields.");const u=l({Accept:"application/json","content-type":"application/json","X-FORWARDED-HOST":p});return y(`${a}/api/dataentities/CL/documents/${c}?_fields=_all`,{method:"GET",headers:u},{})},getShopperById:({userId:c})=>{if(!c)throw new T("Missing userId to fetch shopper name.");const u=l({Accept:"application/json","content-type":"application/json","X-FORWARDED-HOST":p}),m=c.replace(/-/g,"");return y(`${a}/api/dataentities/shopper/search?_where=(userId=${m} OR userId=${c})&_fields=_all&_schema=v1`,{method:"GET",headers:u},{})}},vtexid:{validate:()=>{const c=s({"content-type":"application/json","X-FORWARDED-HOST":p}),u=ne(on(i)??"",e);return y(`${a}/api/vtexid/credential/validate`,{headers:c,body:JSON.stringify({token:u}),method:"POST"},{storeCookies:o})}},orderEntry:{uploadFile:({fileBuffer:c,fileName:u,mimeType:m})=>{const S=s({"content-type":"application/json","X-FORWARDED-HOST":p}),f=`----FastStoreUploadBoundary${Date.now()}`,I=`\r
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const Ge=require("@graphql-tools/merge"),He=require("@graphql-tools/schema"),z=require("@graphql-tools/utils"),N=require("@faststore/diagnostics"),ee=require("graphql"),J=require("cookie"),kn=require("isomorphic-unfetch"),ve=require("p-limit"),ae=require("dataloader"),_n=require("sanitize-html"),Oe=require("fast-deep-equal"),Fn=require("node:crypto");var Xe=(e=>(e.Accepted="accepted",e.Denied="denied",e.Pending="pending",e))(Xe||{}),Ye=(e=>(e.Brand="Brand",e.Category="Category",e.Cluster="Cluster",e.Collection="Collection",e.Department="Department",e.SubCategory="SubCategory",e))(Ye||{}),Je=(e=>(e.Boolean="BOOLEAN",e.Range="RANGE",e))(Je||{}),Ke=(e=>(e.DiscountDesc="discount_desc",e.NameAsc="name_asc",e.NameDesc="name_desc",e.OrdersDesc="orders_desc",e.PriceAsc="price_asc",e.PriceDesc="price_desc",e.ReleaseDesc="release_desc",e.ScoreDesc="score_desc",e))(Ke||{}),Qe=(e=>(e.Error="ERROR",e.Info="INFO",e.Warning="WARNING",e))(Qe||{}),Ze=(e=>(e.Input="Input",e.Output="Output",e))(Ze||{});const Rn=()=>function(n={}){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{...n,"X-VTEX-API-AppKey":t,"X-VTEX-API-AppToken":r}},Nn=async e=>{const{clients:{commerce:n}}=e;try{if((await n.vtexid.validate())?.authStatus?.toLowerCase()!=="success")throw new Y("Authentication required")}catch(t){const r=t.extensions?.status??t.status;throw r===401?new Y("Authentication required"):r===403?new K("You are not allowed to access this resource"):new Y("Authentication required")}},Ln="auth",en={typeDefs:"directive @auth on FIELD_DEFINITION",transformer:e=>z.mapSchema(e,{[z.MapperKind.OBJECT_FIELD]:n=>{if(z.getDirective(e,n,Ln)?.[0]){const r=n.resolve;n.resolve=async(i,a,o,s)=>(await Nn(o),r?.(i,a,o,s))}return n}})},Bn="cacheControl",Mn=(e,n)=>{const{scope:t="private",sMaxAge:r=0,staleWhileRevalidate:i=0}=e;return`${n?"private":t}, s-maxage=${r}, stale-while-revalidate=${i}`},De=(e,n)=>typeof e=="number"&&typeof n=="number"?e>n?n:e:typeof e=="number"?e:n,$n=(e,n)=>typeof e=="string"&&typeof n=="string"?e==="public"&&n==="public"?"public":"private":e||n,nn={typeDefs:"directive @cacheControl(sMaxAge: Int, staleWhileRevalidate: Int, scope: String) on FIELD_DEFINITION",transformer:e=>z.mapSchema(e,{[z.MapperKind.OBJECT_FIELD]:n=>{const t=z.getDirective(e,n,Bn)?.[0];if(t){const{sMaxAge:r,staleWhileRevalidate:i,scope:a}=t,o=n.resolve;n.resolve=(s,l,d,g)=>(d.cacheControl={sMaxAge:De(d.cacheControl?.sMaxAge,r),staleWhileRevalidate:De(d.cacheControl?.staleWhileRevalidate,i),scope:$n(d.cacheControl?.scope,a)},o?.(s,l,d,g))}return n}})},tn=e=>(n,t)=>{const r=Ge.mergeTypeDefs([...(e??[]).map(({typeDefs:i})=>i),t]);return(e??[]).reduce((i,{transformer:a})=>a?.(i)??i,He.makeExecutableSchema({typeDefs:r,resolvers:n}))},ce="@faststore/api",le="4.4.0",Pe={name:ce,version:le},zn=(e,n)=>(t,r,i,a)=>{if((i?.OTEL?.enabled??!1)===!1)return e(t,r,i,a);const o=N.OTELAPI.trace.getTracer(ce,le),s=N.OTELAPI.propagation.extract(N.OTELAPI.context.active(),i.OTEL);return N.OTELAPI.context.with(s,()=>{const l=o.startSpan(n??"Unknown Graphql Resolver",{startTime:Date.now(),kind:N.OTELAPI.SpanKind.INTERNAL,attributes:{timestamp:Date.now(),"@faststore_version":le,"@faststore_package_name":ce,"@faststore_account_name":i.account,"@faststore_environment":process.env.NODE_ENV}});if(!l)return e(t,r,i,a);try{const d=e(t,r,i,a);return d instanceof Promise?d.then(g=>(l.end(),g)):(l.end(),d)}catch(d){throw l.end(),console.error(`Error when executing resolver: ${n}`,d),d}})};class q extends Error{constructor(n,t){super(t),this.extensions=n,this.name="FastStoreError"}}class T extends q{constructor(n){super({status:400,type:"BadRequestError"},n)}}class Y extends q{constructor(n){super({status:401,type:"UnauthorizedError"},n)}}class K extends q{constructor(n){super({status:403,type:"ForbiddenError"},n)}}class L extends q{constructor(n){super({status:404,type:"NotFoundError"},n)}}const Vn=e=>e?.name==="FastStoreError",xn=e=>e?.extensions?.type==="BadRequestError",qn=e=>e?.extensions?.type==="UnauthorizedError",rn=e=>e?.extensions?.type==="ForbiddenError",Ce=e=>e?.extensions?.type==="NotFoundError",jn=`${Pe.name}@${Pe.version}`,y=async(e,n,t)=>{const r=await kn(e,{...n,headers:{...n?.headers??{},"User-Agent":jn}});if(r.ok)return t?.storeCookies&&t.storeCookies(r.headers),r.status!==204?r.json():void 0;console.error(e,n,r);const i=await r.text();if(typeof r?.status=="number")switch(r.status){case 400:throw new T(i);case 401:throw new Y(i);case 403:throw new K(i);case 404:throw new L(i);default:throw new q({status:r.status,type:"UnknownError"},i)}throw new Error(i)},an=e=>{if(!e)return e;const n=new Map,t=e.split(";"),r=[];return t.forEach(i=>{const a=i.trim();if(a){const o=a.indexOf("=");if(o>0){const s=a.substring(0,o),l=a.substring(o+1);n.has(s)||r.push(s),n.set(s,l)}}}),r.map(i=>`${i}=${n.get(i)}`).join("; ")},Wn=/^([^=]+)=([^;]*)/,Gn=(e,n)=>{const t=n.match(Wn);if(t){const r=t[1],i=t[2];e.storage.cookies.set(r,{value:i,setCookie:n})}},Hn=(e,n)=>{n.getSetCookie().forEach(t=>Gn(e,t))},Xn=e=>n=>Hn(e,n),on=e=>{if(!e.headers?.cookie)return null;const n=an(e.headers.cookie),t=Array.from(e.storage.cookies.entries());return t.length===0?n:t.reduce((r,[i,{value:a}])=>Yn(r,i,a),n)},sn=e=>function(t){const r=on(e);return r?{...t,cookie:r}:t},ne=(e,n)=>{const t=an(e);return J.parse(t)[`VtexIdclientAutCookie_${n}`]||""},Yn=(e,n,t)=>{const r=new RegExp(`(${n})=([^;]*)`),i=e.match(r);return i?e.replace(i[0],`${i[1]}=${t}`):`${e};${n}=${t}`};function te(e){return e?JSON.parse(Buffer.from(e.split(".")[1],"base64").toString()):null}const G={method:"POST",headers:{"content-type":"application/json"}},Jn=({account:e,environment:n,incrementAddress:t,subDomainPrefix:r},i)=>{const a=`https://${e}.${n}.com.br`,o=Xn(i),s=sn(i),l=Rn(),d=new Headers(i.headers).get("x-forwarded-host")??i.headers?.host??"",g=r&&r.map(c=>c+".").find(c=>d.includes(c))||"",p=d.replace(g,"");return{catalog:{salesChannel:c=>y(`${a}/api/catalog_system/pub/saleschannel/${c}`,void 0,{storeCookies:o}),brand:{list:()=>y(`${a}/api/catalog_system/pub/brand/list`,void 0,{storeCookies:o})},category:{tree:(c=3)=>y(`${a}/api/catalog_system/pub/category/tree/${c}`,void 0,{storeCookies:o})},portal:{pagetype:c=>y(`${a}/api/catalog_system/pub/portal/pagetype/${c}`,void 0,{storeCookies:o})},products:{crossselling:({type:c,productId:u,groupByProduct:m=!0})=>{const S=new URLSearchParams({sc:i.storage.channel.salesChannel,groupByProduct:m.toString()});return y(`${a}/api/catalog_system/pub/products/crossselling/${c}/${u}?${S}`,void 0,{storeCookies:o})}}},checkout:{simulation:(c,{salesChannel:u}=i.storage.channel)=>{const m=new URLSearchParams({sc:u}),S=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${a}/api/checkout/pub/orderForms/simulation?${m.toString()}`,{...G,headers:S,body:JSON.stringify(c)},{storeCookies:o})},shippingData:({id:c,index:u,deliveryMode:m,selectedAddresses:S},f)=>{const I=f?{startDateUtc:m?.deliveryWindow?.startDate,endDateUtc:m?.deliveryWindow?.endDate}:null,D={logisticsInfo:Array.from({length:u},(P,O)=>({itemIndex:O,selectedDeliveryChannel:m?.deliveryChannel||null,selectedSla:m?.deliveryMethod||null,deliveryWindow:I})),selectedAddresses:S,clearAddressIfPostalCodeNotFound:t},E=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${a}/api/checkout/pub/orderForm/${c}/attachments/shippingData`,{...G,headers:E,body:JSON.stringify(D)},{storeCookies:o})},marketingData:({id:c,marketingData:u})=>{const m=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${a}/api/checkout/pub/orderForm/${c}/attachments/marketingData`,{headers:m,body:JSON.stringify(u),method:"POST"},{storeCookies:o})},clientPreferencesData:({id:c,clientPreferencesData:u})=>{const m=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${a}/api/checkout/pub/orderForm/${c}/attachments/clientPreferencesData`,{headers:m,body:JSON.stringify(u),method:"POST"},{storeCookies:o})},orderForm:({id:c,refreshOutdatedData:u=!0,channel:m=i.storage.channel})=>{const{salesChannel:S}=m,f=s({"content-type":"application/json","X-FORWARDED-HOST":p}),I=new URLSearchParams({sc:S});c&&I.set("refreshOutdatedData",u.toString());const D=`${a}/api/checkout/pub/orderForm${c?`/${c}`:""}?${I.toString()}`;return y(D,{...G,headers:f,...c?{}:{body:"{}"}},{storeCookies:o})},clearOrderFormMessages:({id:c})=>{const u=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${a}/api/checkout/pub/orderForm/${c}/messages/clear`,{...G,headers:u,body:"{}"})},updateOrderFormItems:({id:c,orderItems:u,allowOutdatedData:m="paymentData",salesChannel:S=i.storage.channel.salesChannel,shouldSplitItem:f=!0})=>{const I=new URLSearchParams({allowOutdatedData:m,sc:S}),D=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${a}/api/checkout/pub/orderForm/${c}/items?${I}`,{headers:D,body:JSON.stringify({orderItems:u,noSplitItem:!f}),method:"PATCH"},{storeCookies:o})},setCustomData:({id:c,appId:u,key:m,value:S})=>{const f=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${a}/api/checkout/pub/orderForm/${c}/customData/${u}/${m}`,{headers:f,body:JSON.stringify({value:S}),method:"PUT"})},region:async({postalCode:c,geoCoordinates:u,country:m,salesChannel:S})=>{const f=new URLSearchParams({country:m,sc:S??""});c?f.append("postalCode",c):f.append("geoCoordinates",`${u?.longitude};${u?.latitude}`);const I=`${a}/api/checkout/pub/regions/?${f.toString()}`,D=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(I,{headers:D},{storeCookies:o})},address:async({postalCode:c,country:u})=>{const m=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${a}/api/checkout/pub/postal-code/${u}/${c}`,{headers:m},{storeCookies:o})},cancelOrder:({orderId:c,customerEmail:u,reason:m})=>{const S=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${a}/api/checkout/pub/orders/${c}/user-cancel-request`,{method:"POST",headers:S,body:JSON.stringify({customerEmail:u,reason:m})},{})},pickupPoints:({geoCoordinates:c})=>{if(!c)throw new Error("Missing required parameter for listing pickup points.");const u=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${a}/api/logistics-shipping/pickuppoints/_search`,{method:"POST",headers:u,body:JSON.stringify({coordinate:c})},{storeCookies:o})}},session:c=>{const u=new URLSearchParams(c);u.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 m=s({"content-type":"application/json"}),S=J.parse(i?.headers?.cookie??"")?.vtex_session;return y(`${a}/api/sessions?${u.toString()}`,{method:S?"PATCH":"POST",headers:m,body:"{}"},{storeCookies:o})},subscribeToNewsletter:c=>y(`${a}/api/dataentities/NL/documents/`,{...G,body:JSON.stringify({...c,isNewsletterOptIn:!0}),method:"PATCH"},{storeCookies:o}),profile:{addresses:async c=>{const u=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${a}/api/profile-system/pvt/profiles/${c}/addresses`,{headers:u},{storeCookies:o})}},oms:{userOrder:({orderId:c})=>{const u=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${a}/api/oms/user/orders/${c}`,{method:"GET",headers:u},{storeCookies:o})},listUserOrders:({page:c,status:u,dateInitial:m,dateFinal:S,text:f,clientEmail:I,perPage:D,pendingMyApproval:E})=>{const P=new URLSearchParams;if(m){const w=new Date(m).setHours(0,0,0,0);m=new Date(w).toISOString()}if(S){const w=new Date(S).setHours(23,59,59,999);S=new Date(w).toISOString()}f&&P.append("text",f),u&&u.length>0&&P.append("status",u.filter(Boolean).join(",")),m&&S?P.append("creation_date",`creationDate:[${m} TO ${S}]`):m?P.append("creation_date",`creationDate:[${m} TO *]`):S&&P.append("creation_date",`creationDate:[* TO ${S}]`),I&&P.append("clientEmail",I),c&&P.append("page",c.toString()),D&&P.append("per_page",D.toString()),E&&P.append("my_pending_approvals",String(!0));const O=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${a}/api/oms/user/orders?${P.toString()}`,{method:"GET",headers:O},{storeCookies:o})},getCommercialAuthorizationsByOrderId:({orderId:c})=>{const u=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${a}/${e}/commercial-authorizations/order/${c}`,{method:"GET",headers:u},{storeCookies:o})},processOrderAuthorization:async({orderAuthorizationId:c,dimensionId:u,ruleId:m,approved:S})=>{const f=s({"content-type":"application/json","X-FORWARDED-HOST":p}),E={params:{ruleId:m,dimensionId:u,score:S?100:0}};return y(`${a}/${e}/commercial-authorizations/${c}/callback`,{method:"POST",headers:f,body:JSON.stringify(E)},{storeCookies:o})}},units:{getUnitByUserId:({userId:c})=>{const u=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${a}/api/units/v1/${c}/unit`,{method:"GET",headers:u},{})},getOrgUnitById:({orgUnitId:c})=>{const u=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${a}/api/units/v1/${c}`,{method:"GET",headers:u},{})},getScopesByOrgUnit:({orgUnitId:c})=>{const u=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${a}/api/units/v1/${c}/scopes`,{method:"GET",headers:u},{})}},licenseManager:{getUserById:({userId:c})=>{const u=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${a}/api/license-manager/users/${c}`,{method:"GET",headers:u},{})},getUserByEmail:({email:c})=>{const u=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${a}/api/license-manager/pvt/users/${c}`,{method:"GET",headers:u},{})},getUserRoles:({userId:c})=>{const u=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${a}/api/license-manager/storefront/users/${c}/roles`,{method:"GET",headers:u},{})}},masterData:{getContractById:({contractId:c})=>{if(!c)throw new T("Missing contractId to fetch CL fields.");const u=l({Accept:"application/json","content-type":"application/json","X-FORWARDED-HOST":p});return y(`${a}/api/dataentities/CL/documents/${c}?_fields=_all`,{method:"GET",headers:u},{})},getShopperById:({userId:c})=>{if(!c)throw new T("Missing userId to fetch shopper name.");const u=l({Accept:"application/json","content-type":"application/json","X-FORWARDED-HOST":p}),m=c.replace(/-/g,"");return y(`${a}/api/dataentities/shopper/search?_where=(userId=${m} OR userId=${c})&_fields=_all&_schema=v1`,{method:"GET",headers:u},{})}},vtexid:{validate:()=>{const c=s({"content-type":"application/json","X-FORWARDED-HOST":p}),u=ne(on(i)??"",e);return y(`${a}/api/vtexid/credential/validate`,{headers:c,body:JSON.stringify({token:u}),method:"POST"},{storeCookies:o})}},orderEntry:{uploadFile:({fileBuffer:c,fileName:u,mimeType:m})=>{const S=s({"content-type":"application/json","X-FORWARDED-HOST":p}),f=`----FastStoreUploadBoundary${Date.now()}`,I=`\r
|
|
2
2
|
`,E=/^[a-zA-Z0-9][a-zA-Z0-9!#$&\-.^_]*\/[a-zA-Z0-9][a-zA-Z0-9!#$&\-.^_+]*$/.test(m)?m:"application/octet-stream",P=u.replaceAll(/[\r\n"]/g,"_"),O=[`--${f}`,`Content-Disposition: form-data; name="file"; filename="${P}"`,`Content-Type: ${E}`,"",""].join(I),w=`${I}--${f}--${I}`,h=Buffer.from(O),b=Buffer.from(w),C=new Uint8Array(h.byteLength+c.byteLength+b.byteLength);let A=0;return C.set(h,A),A+=h.byteLength,C.set(c,A),A+=c.byteLength,C.set(b,A),y(`${a}/api/order-entry/upload?an=${e}`,{method:"POST",headers:{...S,"content-type":`multipart/form-data; boundary=${f}`},body:C.buffer},{})},startOperation:({objectKey:c,orderFormId:u,sessionToken:m})=>{const S=s({"content-type":"application/json","X-FORWARDED-HOST":p}),f=JSON.stringify({objectKey:c,orderFormId:u,operation:"CreateCart",...m?{sessionToken:m}:{}});return y(`${a}/api/order-entry/operation?an=${e}`,{method:"POST",headers:S,body:f},{})},getOperation:({operationId:c})=>{const u=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${a}/api/order-entry/operation/${c}?an=${e}`,{method:"GET",headers:u},{})},createOrderForm:()=>{const c=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${a}/api/checkout/pub/orderForm?sc=${i.storage.channel.salesChannel}`,{method:"POST",headers:c,body:"{}"},{})},getOrderFormItems:({orderFormId:c})=>{const u=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${a}/api/checkout/pub/orderForm/${c}`,{method:"GET",headers:u},{})}}}},de="fuzzy",ue="operator",pe="pickupPoint",we="shipping",Ae="delivery-options",Kn="in-stock",Qn="trade-policy",Zn="region-id",et=new Set([Qn,Zn,de,ue,pe]),nt=new Set(["zip-code","pickupPoint","country","coordinates","deliveryZonesHash","pickupPointsHash"]),tt=new Set(["productClusterIds"]),Ee=e=>encodeURI(decodeURI(e)),rt=e=>encodeURIComponent(decodeURIComponent(e).normalize("NFD").replaceAll(/[\u0300-\u036f]/g,"")),it=/^pickup-in-point-(.+)$/;function cn(e){if(!e)return{};try{const t=J.parse(e).vtex_segment;if(!t)return{};const r=Buffer.from(t,"base64").toString("utf-8");return JSON.parse(r)}catch{return{}}}function at(e){const n={},t={},r=[];for(const i of e.split(";")){const a=i.indexOf("=");if(a<0)continue;const o=i.slice(0,a),s=i.slice(a+1);!o||!s||(nt.has(o)?n[o]=s:tt.has(o)?t[o]=s:r.push({key:o,value:s}))}return{shipping:n,queryParams:t,extraFacets:r}}function ot(e){const n=typeof e.facets=="string"?e.facets:"",{shipping:t,queryParams:r,extraFacets:i}=at(n);return{segmentParams:{sc:e.channel,regionId:e.regionId,country:e.countryCode??t.country,locale:e.cultureInfo,"zip-code":t["zip-code"],coordinates:t.coordinates,pickupPoint:t.pickupPoint,deliveryZonesHash:t.deliveryZonesHash,pickupPointHash:t.pickupPointsHash,utmSource:e.utm_source??void 0,utmCampaign:e.utm_campaign??void 0,utmiCampaign:e.utmi_campaign??void 0,campaigns:typeof e.campaigns=="string"?e.campaigns:void 0,priceTables:e.priceTables??void 0,productClusterIds:r.productClusterIds},extraFacets:i}}function ln(e,n){const t=[["sc",n.sc],["regionId",n.regionId],["country",n.country],["locale",n.locale],["zip-code",n["zip-code"]],["coordinates",n.coordinates],["pickupPoint",n.pickupPoint],["deliveryZonesHash",n.deliveryZonesHash],["pickupPointHash",n.pickupPointHash],["utmSource",n.utmSource],["utmCampaign",n.utmCampaign],["utmiCampaign",n.utmiCampaign],["campaigns",n.campaigns],["priceTables",n.priceTables],["productClusterId",n.productClusterIds]];for(const[r,i]of t)i!=null&&i!==""&&e.append(r,String(i))}function dn(e){return it.exec(e)?.[1]}function st(e){const n=e.find(r=>r.key==="shipping"),t=n?dn(n.value):void 0;if(t!==void 0)try{return decodeURIComponent(t)}catch{return t}}function ct(e,n){const t=st(n);return t===void 0?e:{...e,pickupPoint:t}}function lt(e){return e.map(n=>n.key!=="shipping"||dn(n.value)===void 0?n:{...n,value:"pickup-in-point"})}function dt(e,n){let t=[...e];const r=t.some(i=>i.key==="shipping");for(const i of n)(!r||i.key!=="shipping")&&t.push(i);return t.some(i=>i.key==="shipping"&&i.value==="ignore")&&(t=t.filter(i=>i.key!=="shipping")),lt(t)}function ut(e){return e.reduce((n,t)=>{let{key:r,value:i}=t;return r==="priceRange"&&(r="price",i=i.replace(" TO ",":")),r==="ft"?n:`${n}${Ee(r)}/${rt(Ee(i)).replaceAll(/ |%20/g,"-")}/`},"")}const pt=e=>e.key==="fuzzy"&&(e.value==="0"||e.value==="1"||e.value==="auto"),gt=e=>e.key==="operator"&&(e.value==="and"||e.value==="or");function mt(e,n){const{segmentParams:t,extraFacets:r}=ot(e??{}),i=n?.salesChannel??t.sc,a=n?.regionId??t.regionId,o=n?.locale??t.locale??"";return{segmentParams:{...t,...i?{sc:i}:{},...a?{regionId:a}:{},locale:o},extraFacets:r}}function ht(e,n){const t=e.filter(({key:l})=>!et.has(l)),r=e.find(({key:l,value:d})=>l===we&&d!=="all-delivery-methods")??null,i=e.find(({key:l,value:d})=>l===Ae&&d!=="all-delivery-options")??null,a=[...t],o=a.some(({key:l})=>l===we),s=a.some(({key:l})=>l===Ae);return r!==null&&!o&&a.push(r),i!==null&&!s&&a.push(i),dt(a,n)}function ft(e,n){const t=e.find(({key:a})=>a===de)??null,r=e.find(({key:a})=>a===ue)??null,i=e.find(({key:a})=>a===pe)??null;t&&pt(t)&&n.append(de,t.value),r&>(r)&&n.append(ue,r.value),i&&n.append(pe,i.value)}function Te(e,n,t,r){const{query:i="",page:a,count:o,sort:s,selectedFacets:l=[],showInvisibleItems:d,sponsoredCount:g,hideUnavailableItems:p,allowRedirect:c=!1}=e,u=new URLSearchParams;if(r.includePagination&&a!==void 0&&o!==void 0){const f=a*o,I=o===0?f:f+o-1;u.append("from",f.toString()),u.append("to",I.toString())}i&&u.append("query",i),r.includeSort&&s&&u.append("sort",s);const m=ct(t.segmentParams,l);if(ln(u,m??t.segmentParams),ft(l,u),d&&u.append("show-invisible-items","true"),n?.hideUnavailableItems!==void 0){const f=l.find(({key:D})=>D===Kn),I=f?f.value:p?.toString()??n.hideUnavailableItems.toString();u.append("hideUnavailableItems",I)}n?.simulationBehavior!==void 0&&u.append("simulationBehavior",n.simulationBehavior.toString()),n?.showSponsored!==void 0&&u.append("showSponsored",n.showSponsored.toString()),g!==void 0&&u.append("sponsoredCount",g.toString()),c!==void 0&&u.append("allowRedirect",c.toString());const S=ut(ht(l,t.extraFacets));return{params:u,path:S}}function St(e,n){const{field:t,value:r,hideUnavailableItems:i,showInvisibleItems:a}=e,o=new URLSearchParams({field:t??"",value:r??""});return ln(o,n),i&&o.append("hideUnavailableItems","true"),a&&o.append("show-invisible-items","true"),o}function H(e,n){return{path:e,params:n,toString(){const t=n.toString();return e?t?`${e}?${t}`:e:t?`?${t}`:""}}}function X(e){const{endpoint:n,segment:t,defaults:r,args:i={}}=e,a=mt(t,r);switch(n){case"product-search":case"facets":{const{params:o,path:s}=Te(i,r,a,{includePagination:!0,includeSort:!0});return H(s,o)}case"catalog-count":{const{params:o,path:s}=Te(i,r,a,{includePagination:!1,includeSort:!1});return H(s,o)}case"products":{const o=St(i,a.segmentParams);return H("",o)}case"search-suggestions":{const o=new URLSearchParams({query:i.query?.toString()??"",locale:r?.locale??a.segmentParams.locale??""});return H("",o)}case"top-searches":{const o=new URLSearchParams({locale:r?.locale??a.segmentParams.locale??""});return H("",o)}default:{const o=n;throw new Error(`Unknown intelligent-search endpoint: ${o}`)}}}const yt=10;function It(e){const{regionId:n,seller:t}=e.storage.channel;return(t?Buffer.from(`SW#${t}`).toString("base64"):void 0)??(n||void 0)}function vt(e){const n=cn(e.headers?.cookie);return e.storage.locale||n.cultureInfo||""}const Ot=({account:e,environment:n,hideUnavailableItems:t,simulationBehavior:r,showSponsored:i,subDomainPrefix:a},o)=>{const s=`https://${e}.${n}.com.br`,l=sn(o),d=cn(o.headers?.cookie),g=()=>({salesChannel:o.storage.channel.salesChannel,regionId:It(o),locale:vt(o),hideUnavailableItems:t,simulationBehavior:r,showSponsored:i}),p=new Headers(o.headers).get("x-forwarded-host")??o.headers?.host??"",c=a&&a.map(h=>h+".").find(h=>p.includes(h))||"",u=p.replace(c,""),m=l({"content-type":"application/json","X-FORWARDED-HOST":u}),S=({type:h,...b})=>{const C=h==="facets"?"facets":"product-search",A=X({endpoint:C,segment:d,defaults:g(),args:b});return y(`${s}/api/intelligent-search/v1/${C}/${A.path}?${A.params.toString()}`,{headers:m})},f=h=>S({...h,type:"product_search"}),I=({field:h,value:b,hideUnavailableItems:C,showInvisibleItems:A})=>{const v=X({endpoint:"products",segment:d,defaults:g(),args:{field:h,value:b,hideUnavailableItems:C,showInvisibleItems:A}});return y(`${s}/api/intelligent-search/v1/products?${v.params.toString()}`,{headers:m})};return{facets:h=>S({...h,type:"facets"}),products:f,fetchProduct:I,productsByIdentifier:async({field:h,values:b,showInvisibleItems:C,hideUnavailableItems:A})=>{const v=ve(yt);return(await Promise.all(b.map(_=>v(async()=>{try{return await I({field:h,value:_,hideUnavailableItems:A,showInvisibleItems:C})}catch{return null}})))).filter(_=>_!==null)},suggestedTerms:h=>{const b=X({endpoint:"search-suggestions",segment:d,defaults:g(),args:{query:h.query}});return y(`${s}/api/intelligent-search/v1/search-suggestions?${b.params.toString()}`,{headers:m})},topSearches:()=>{const h=X({endpoint:"top-searches",segment:d,defaults:g()});return y(`${s}/api/intelligent-search/v1/top-searches?${h.params.toString()}`,{headers:m})},productCount:h=>{const b=X({endpoint:"catalog-count",segment:d,defaults:g(),args:h});return y(`${s}/api/intelligent-search/v1/catalog-count/${b.path}?${b.params.toString()}`,{headers:m})}}},Ct=(e,n)=>{const t=Ot(e,n),r=Jn(e,n);return{search:t,commerce:r}},bt=20,Dt=new Set(["brand","category","department","subcategory","collection","cluster"]),V=e=>typeof e.pageType=="string"&&Dt.has(e.pageType.toLowerCase()),Pt=(e,n)=>{const t=ve(bt),r=async i=>Promise.all(i.map(a=>t(async()=>{const o=await n.commerce.catalog.portal.pagetype(a);if(V(o))return o;throw new L(`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 ae(r,{batch:!1})},wt=(e,n)=>{const t=async r=>Promise.all(r.map(i=>n.commerce.catalog.salesChannel(i)));return new ae(t)},At=1,Et=(e,n)=>{const t=ve(At),r=async a=>{const o=a.reduce((p,{items:c})=>[...p,c],[]),s=[...o.flat()],l=await n.commerce.checkout.simulation({country:a[0].country,postalCode:a[0].postalCode,items:s}),d=l.items.reduce((p,c)=>{const u=c.requestIndex;return typeof u=="number"&&u<p.length&&(p[u]=c),p},Array(s.length).fill(null)),g=o.reduce((p,c)=>[...p,c.length+p[p.length-1]],[0]);return o.map((p,c)=>({...l,items:d.slice(g[c],g[c+1]).filter(u=>!!u)}))},i=async a=>t(r,a);return new ae(i,{maxBatchSize:50})},Tt=(e,n)=>_n(e,n);function Ut(e){return{...e,description:e.description?Tt(e.description):e.description}}const B=(e,n)=>({...e,isVariantOf:Ut(n)}),kt=({flags:e},n)=>{const t=async r=>{const i=r.map(g=>g.split("-")[0]),a=r.some(g=>g.split("-")[1]==="invisibleItems"),s=(await n.search.productsByIdentifier({field:"sku",values:i,showInvisibleItems:a,...e?.enableUnavailableItemsOnCart&&{hideUnavailableItems:!1}})).reduce((g,p)=>{for(const c of p.items)g[c.itemId]=B(c,p);return g},{}),l=i.map(g=>s[g]),d=i.filter(g=>!s[g]);if(d.length>0)throw new L(`Search API did not found the following skus: ${d.join(",")}`);return l};return new ae(t,{maxBatchSize:99})},_t=(e,{clients:n})=>{const t=kt(e,n),r=Et(e,n),i=Pt(e,n),a=wt(e,n);return{skuLoader:t,simulationLoader:r,collectionLoader:i,salesChannelLoader:a}},M=e=>e.AvailableQuantity>0,x=e=>e.spotPrice??0,Ft=e=>e.Price??0,Ue=e=>e?"https://schema.org/InStock":"https://schema.org/OutOfStock",un=(e,n)=>M(e)&&!M(n)?-1:!M(e)&&M(n)?1:x(e)-x(n),Rt=e=>e==="available",$=(e,n=0,t=1)=>{const r=n/t;return Math.round((e+r)*100)/100},Nt=(e,n={includeTaxes:!1})=>{const t=e.filter(M),r=t[t.length-1],i=r?x(r):0;return n.includeTaxes?$(i,r?.Tax,r?.product?.unitMultiplier):i},ke=(e,n={includeTaxes:!1})=>{const[t]=e.filter(M),r=t?x(t):0;return n.includeTaxes?$(r,t?.Tax,t?.product?.unitMultiplier):r},Lt={highPrice:e=>Nt(e),lowPrice:e=>ke(e),lowPriceWithTaxes:e=>ke(e,{includeTaxes:!0}),offerCount:e=>e.length,priceCurrency:async(e,n,t)=>{const{loaders:{salesChannelLoader:r},storage:{channel:i}}=t;return(await r.load(i.salesChannel)).CurrencyCode??""},offers:e=>e},Bt={ratingValue:()=>5,reviewCount:()=>0},_e="ÁÄÂÀÃÅČÇĆĎÉĚËÈÊẼĔȆÍÌÎÏŇÑÓÖÒÔÕØŘŔŠŤÚŮÜÙÛÝŸŽáäâàãåčçćďéěëèêẽĕȇíìîïňñóöòôõøðřŕšťúůüùûýÿžþÞĐđ߯a",Mt="AAAAAACCCDEEEEEEEEIIIINNOOOOOORRSTUUUUUYYZaaaaaacccdeeeeeeeeiiiinnooooooorrstuuuuuyyzbBDdBAa",$t=e=>{let n=e.slice(0);for(let t=0;t<_e.length;t++)n=n.replace(new RegExp(_e.charAt(t),"g"),Mt.charAt(t));return n},zt=e=>e.replace(/[·/_,:]/,"-");function pn(e){const t=e.replace(/,/g,"").replace(/[*+~.()'"!:@&\[\]`/ %$#?{}><=_^]/g,"-");return zt($t(t)).toLowerCase()}const Z=e=>e.type==="brand"||V(e)&&e.pageType.toLowerCase()==="brand",ge=e=>V(e)&&e.pageType.toLowerCase()==="collection",se=e=>Z(e)||ge(e)?pn(e.name):V(e)?new URL(`https://${e.url}`).pathname.slice(1).toLowerCase():new URL(e.url).pathname.slice(1).toLowerCase(),gn={id:({id:e})=>e.toString(),slug:e=>se(e),seo:e=>Z(e)||V(e)?{title:e.title??e.name,description:e.metaTagDescription}:{title:e.Title,description:e.MetaTagDescription},type:e=>Z(e)?"Brand":V(e)?e.pageType:e.level===0?"Department":"Category",meta:e=>{const n=se(e);return Z(e)?{selectedFacets:[{key:"brand",value:n}]}:ge(e)?{selectedFacets:[{key:"productclusterids",value:e.id}]}:{selectedFacets:n.split("/").map((t,r)=>({key:`category-${r+1}`,value:t}))}},breadcrumbList:async(e,n,t)=>{const{loaders:{collectionLoader:r}}=t,a=se(e).split("/").filter(l=>!!l),o=a.map((l,d)=>a.slice(0,d+1).join("/")),s=await Promise.all(o.map(async l=>{const d=await r.load(l);return{slug:l,...d}}));return{itemListElement:s.map((l,d)=>({item:ge(l)?`/${l.slug}`:new URL(`https://${l.url}`).pathname.toLowerCase(),name:l.name,position:d+1})),numberOfItems:s.length}}},mn={buy:"whoboughtalsobought",view:"whosawalsosaw",similars:"similars",viewAndBought:"whosawalsobought",accessories:"accessories",suggestions:"suggestions"},Fe=({key:e,value:n})=>{switch(e){case"price":return{key:e,value:n.replace("-to-",":")};case"channel":case"locale":case"buy":case"view":case"similars":case"viewAndBought":case"accessories":case"suggestions":return[];default:return{key:e,value:n}}},Re=e=>{const n=e.split(":").map(Number);return n.length!==2||Number.isNaN(n[0])||Number.isNaN(n[1])?null:n},Vt=e=>typeof mn[e]=="string",xt=e=>{const n=e?.filter(t=>Vt(t.key));if(Array.isArray(n)&&n.length>1)throw new T(`You passed ${n.length} cross selling facets but only one is allowed. Please leave one of the following facet: ${n.map(t=>t.key).join(",")}`);return n?.[0]??null},qt=e=>e?.find(n=>n.key==="slug")?.value??null,jt=e=>e?.find(n=>n.key==="id")?.value??null,Ne=e=>e?.find(n=>n.key==="locale")?.value??null,Le=e=>e?.find(n=>n.key==="channel")?.value??null,me=(e,n)=>{let t=0;for(let r=1;r<e.length;r++)n(e[t],e[r])>0&&(t=r);return e[t]},Wt={__resolveType:({type:e,values:n})=>e!=="TEXT"&&e!=="DELIVERY"?"StoreFacetRange":!n||n.length===0?"StoreFacetBoolean":n.every(t=>t.range)?"StoreFacetRange":"StoreFacetBoolean"},Gt={key:({key:e})=>e,label:({name:e})=>e,values:({values:e})=>e.sort((n,t)=>n.name.localeCompare(t.name))},Ht={key:({key:e})=>e,label:({name:e})=>e,min:({values:e,key:n},t,{storage:{searchArgs:r}})=>{const i=Re(r?.selectedFacets?.find(s=>s.key===n)?.value??""),o=me(e,(s,l)=>s.range.from-l.range.from)?.range?.from??0;return{selected:i?.[0]??o,absolute:o}},max:({values:e,key:n},t,{storage:{searchArgs:r}})=>{const i=Re(r?.selectedFacets?.find(s=>s.key===n)?.value??""),o=me(e,(s,l)=>l.range.to-s.range.to)?.range?.to??0;return{selected:i?.[1]??o,absolute:o}}},Xt={value:({value:e})=>e,label:({name:e})=>e||"unknown",selected:({selected:e})=>e,quantity:({quantity:e})=>e},Yt=async(e,{data:n},{clients:{commerce:t}})=>{if(!n?.orderId)throw new T("Missing orderId");return{data:(await t.checkout.cancelOrder(n))?.data}};function hn(e){if(!e||e.status!=="pending")return null;for(const n of e.dimensionStatus){if(n.status!=="pending")continue;const t=n.ruleCollection.find(r=>r.status==="pending"&&r.isUserNextAuthorizer);if(t)return{rule:t,orderAuthorizationId:e.id,dimensionId:n.id}}return null}function Jt(e){if(!e||e.status!=="pending")return!1;const n=e.dimensionStatus.filter(t=>t.status==="pending").flatMap(t=>t.ruleCollection).filter(t=>t.status==="pending");return n.length===0?!1:n.every(t=>!t.isUserNextAuthorizer)}const Kt=async(e,{data:n},{clients:{commerce:t}})=>{const r=await t.oms.processOrderAuthorization(n),i=hn(r);return{isPendingForOtherAuthorizer:!i&&Jt(r),ruleForAuthorization:i}},Qt=async(e,{data:n},{clients:{commerce:t}})=>{if(!n?.objectKey)throw new T("Missing objectKey");const r=n.orderFormId||(await t.orderEntry.createOrderForm()).orderFormId;return t.orderEntry.startOperation({objectKey:n.objectKey,orderFormId:r,sessionToken:n.sessionToken??void 0})},Zt=async(e,{data:n},{clients:{commerce:t}})=>({id:(await t.subscribeToNewsletter(n))?.Id}),er=async(e,{data:n},{clients:{commerce:t}})=>{const{fileContent:r,fileName:i,mimeType:a}=n;if(!r||!i||!a)throw new T("Missing required fields: fileContent, fileName, mimeType");const o=r.replaceAll(/\s/g,""),s=5*1024*1024;if(Math.floor(o.length*3/4)>s)throw new T("File exceeds maximum allowed size of 5MB");if(!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(o))throw new T("Invalid Base64 fileContent");const g=Buffer.from(o,"base64");return await t.orderEntry.uploadFile({fileBuffer:g,fileName:i,mimeType:a})};class re{static parse(n){try{const t=JSON.parse(n);return{seller:t.seller??"",regionId:t.regionId??"",salesChannel:t.salesChannel??"",hasOnlyDefaultSalesChannel:t.hasOnlyDefaultSalesChannel??!0}}catch(t){throw console.error(t),new Error("Malformed channel string")}}static stringify(n){return JSON.stringify(n)}}const he=(e,n)=>{e.storage.channel=re.parse(n)},fe=(e,n)=>{e.storage.locale=n},fn=e=>Fn.createHash("md5").update(e).digest("hex"),Q={attachment:"ATTACHMENT",specification:"SPECIFICATION",attribute:"ATTRIBUTE"};function Sn(e){return{name:e.name,value:e.content,valueReference:Q.attachment}}function nr(e){return{propertyID:e.id,name:e.name,value:e.value,valueReference:{valueReference:Q.attribute,visible:e.visible}}}function yn(e){return fn(`${e.name}:${JSON.stringify(e.value)}:${e.valueReference}`)}const tr=e=>{const n=e.postalCode,t=e.geoCoordinates,r={addressType:e.addressType||null,postalCode:n||null,city:null,state:null,country:e.country||null,street:null,number:null,neighborhood:null,complement:null,reference:null,geoCoordinates:[]};if(t){const i=typeof t=="object"&&"latitude"in t?t.latitude:null,a=typeof t=="object"&&"longitude"in t?t.longitude:null;r.geoCoordinates=i!==null&&a!==null?[a,i]:[]}return[r]},rr=(e,n,t)=>{const r=n.postalCode,i=n.geoCoordinates,a=e?.shippingData?.availableAddresses??[],o=e?.shippingData?.selectedAddresses??[];if(!t&&o.length>0)return[o[0]];if(t&&a.length>0)for(const s of a){if(r&&i&&(s.postalCode===r||s.geoCoordinates[0]===i.longitude&&s.geoCoordinates[1]===i.latitude))return[s];if(r&&!i&&s.postalCode===r)return[s];if(i&&!r&&s.geoCoordinates[0]===i.longitude&&s.geoCoordinates[1]===i.latitude)return[s]}return null},In=(e,n)=>{if(!ir(n))return{updateShipping:!1,addressChanged:!1};if(!cr(e))return{updateShipping:!1,addressChanged:!1};const[t]=e?.shippingData?.selectedAddresses??[];if(ar(t,n.postalCode)||or(t,n.geoCoordinates)||sr(t,n.addressType))return{updateShipping:!0,addressChanged:!0};const{logisticsInfo:r}=e.shippingData;return lr(r,n)?{updateShipping:!0,addressChanged:!1}:{updateShipping:!1,addressChanged:!1}},ir=e=>!!e.postalCode||e.geoCoordinates?.latitude&&e.geoCoordinates?.longitude,ar=(e,n)=>typeof n=="string"&&e?.postalCode!==n,or=(e,n)=>typeof n?.latitude=="number"&&typeof n?.longitude=="number"&&(e?.geoCoordinates[0]!==n?.longitude||e?.geoCoordinates[1]!==n?.latitude),sr=(e,n)=>typeof n=="string"&&e?.addressType!==n,cr=e=>e.items.length!==0,lr=(e,n)=>{const t=n?.deliveryMode?.deliveryChannel,r=n?.deliveryMode?.deliveryMethod,{startDate:i,endDate:a}=n?.deliveryMode?.deliveryWindow||{};return e.some(({selectedDeliveryChannel:o,selectedSla:s,slas:l})=>{const d=t&&o!==t,g=r&&s!==r;return l?.some(p=>d&&p.deliveryChannel===t||g&&p.id===r?!0:i&&a&&p.deliveryChannel===t&&p.id===r&&(!p?.deliveryWindow||p?.deliveryWindow?.startDateUtc!==i||p?.deliveryWindow?.endDateUtc!==a)&&p.availableDeliveryWindows?.some(c=>c?.startDateUtc===i&&c?.endDateUtc===a))})},vn=e=>e.valueReference===Q.attachment,Se=e=>[e.itemOffered.sku,e.seller.identifier,e.price<.01?"Gift":void 0,e.itemOffered.additionalProperty?.filter(vn).map(yn).join("-")].filter(Boolean).join("::"),ie=(e,n)=>({listPrice:e.listPrice/100,price:e.sellingPrice/100,quantity:e.quantity,seller:{identifier:e.seller},itemOffered:{sku:e.id,image:[],name:e.name,additionalProperty:e.attachments.map(Sn)},index:n}),dr=e=>({quantity:e.quantity,seller:e.seller.identifier,id:e.itemOffered.sku,index:e.index,attachments:(e.itemOffered.additionalProperty?.filter(vn)??[]).map(n=>({name:n.name,content:n.value}))}),Be=e=>e.reduce((n,t)=>{const r=Se(t);return n.has(r)||n.set(r,[]),n.get(r)?.push(t),n},new Map),ur=(e,n)=>{const t=(s,l)=>({...s,itemOffered:{sku:s.itemOffered.sku},index:l}),r=n.items.map(ie).map(t),i=e.acceptedOffer.map(t),a=e.orderNumber===n.orderFormId,o=Oe(r,i);return a&&o};function On(e,n){return e?.some(t=>t.parentItemIndex!==null&&t.parentItemIndex!==void 0&&e[t.parentItemIndex]?.id===n)}function Cn(e,n){return e?.some(t=>t.id===n&&t.parentItemIndex!==null)}const Me=e=>{const n=e.items.reduce((t,r,i)=>{const a=Cn(e.items,r.id)||On(e.items,r.id)?`${Se(ie(r))}::${i}`:Se(ie(r));return t[a]||(t[a]=[]),t[a].push(r),t},{});return{...e,items:Object.values(n).map(t=>{const[r]=t,i=t.reduce((o,s)=>o+s.quantity,0),a=t.reduce((o,s)=>o+(s?.priceDefinition?.total??(s?.quantity??0)*(s?.sellingPrice??0)),0);return{...r,quantity:i,sellingPrice:a/i}})}},$e=async(e,n,t)=>({order:{orderNumber:e.orderFormId,acceptedOffer:e.items.map(async r=>({...r,product:await n.load(`${r.id}-invisibleItems`)})),shouldSplitItem:t},messages:e.messages.map(({text:r,status:i})=>({text:r,status:i.toUpperCase()}))}),bn=({items:e},n)=>{const t=e.map(r=>({id:r.id,quantity:r.quantity,seller:r.seller,attachments:r.attachments}));return fn(JSON.stringify({sessionId:n?.id??"",items:t}))},ze=async(e,n,t)=>{try{return await n.checkout.setCustomData({id:e.orderFormId,appId:"faststore",key:"cartEtag",value:bn(e,t)})}catch(r){throw console.error(`Error while setting custom data to orderForm.
|
|
3
3
|
Make sure to add the following custom app to the orderForm:
|
|
4
4
|
{"fields":["cartEtag"],"id":"faststore","major":1}.
|