id
stringlengths 12
53
| messages
listlengths 3
3
|
|---|---|
code_minicart_83cc131d
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of minicart/react/typings/global.d.ts from the minicart VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { FC } from 'react'\n\ndeclare global {\n interface StoreFunctionComponent<P = {}> extends FC<P> {\n schema?: object\n }\n\n type QuantityDisplayType = 'always' | 'never' | 'not-empty'\n\n type MinicartTotalItemsType =\n | 'total'\n | 'distinct'\n | 'totalAvailable'\n | 'distinctAvailable'\n\n type SlideDirectionType =\n | 'horizontal'\n | 'vertical'\n | 'rightToLeft'\n | 'leftToRight'\n\n type MinicartVariationType =\n | 'popup'\n | 'drawer'\n | 'link'\n | 'popupWithLink'\n | 'block'\n}\n\n```"
}
] |
code_minicart_b60c8966
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of minicart/react/legacy/minicart.css from the minicart VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```css\n.container {\n}\n.label {\n}\n.itemImage {\n}\n.item {\n}\n.itemContainer {\n}\n.itemDeleteIcon {\n}\n.itemDeleteIcon {\n}\n.itemDeleteIconLoader {\n}\n.content {\n}\n.contentDiscount {\n}\n.contentPrice {\n}\n.itemName {\n}\n.itemNameLarge {\n}\n.itemFooter {\n}\n.imgContainer {\n}\n.itemRemoveBtn {\n}\n.sidebarScrim {\n}\n.sidebarHeader {\n}\n\n.contentSmall {\n max-height: 383px;\n}\n\n.contentLarge {\n max-height: stretch;\n}\n\n.badge {\n top: -0.7rem;\n right: -0.8rem;\n}\n\n.arrowUp {\n right: 7px;\n}\n\n.box {\n width: 364px;\n top: 100%;\n}\n\n.itemImageLoader {\n width: 100%;\n height: 100%;\n}\n\n.contentFooter {\n}\n\n.footerSpacer {\n}\n\n.footerShippingPriceContainer {\n}\n\n.footerShippingPriceLabelContainer {\n}\n\n.popupContentContainer {\n}\n\n.popupChildrenContainer {\n}\n\n.sidebarRightCaretContainer {\n}\n\n.sidebarItemQuantityContainer {\n}\n\n.labelDiscountText{\n}\n\n@media only screen and (max-width: 40rem) {\n body.sidebarOpen {\n overflow: hidden;\n }\n}\n\n@media only screen and (min-width: 40em) {\n .sidebar {\n width: 340px;\n }\n}\n\n```"
}
] |
code_minicart_373bd826
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of minicart/react/components/DrawerMode.tsx from the minicart VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React, { FC } from 'react'\nimport { Drawer, BackdropMode } from 'vtex.store-drawer'\nimport { ResponsiveValuesTypes } from 'vtex.responsive-values'\nimport { PixelEventTypes } from 'vtex.pixel-manager'\n\nimport MinicartIconButton from './MinicartIconButton'\nimport { useMinicartCssHandles } from './CssHandlesContext'\n\nconst DRAWER_CLOSE_ICON_HEIGHT = 58\n\nexport const CSS_HANDLES = ['minicartSideBarContentWrapper'] as const\n\ninterface Props {\n Icon: React.ComponentType\n maxDrawerWidth: number | string\n drawerSlideDirection: SlideDirectionType\n quantityDisplay: QuantityDisplayType\n itemCountMode: MinicartTotalItemsType\n backdropMode?: ResponsiveValuesTypes.ResponsiveValue<BackdropMode>\n customPixelEventId?: string\n customPixelEventName?: PixelEventTypes.EventName\n onVisibilityChanged?: (visible: boolean) => void\n}\n\nconst DrawerMode: FC<Props> = ({\n Icon,\n children,\n maxDrawerWidth,\n quantityDisplay,\n itemCountMode,\n drawerSlideDirection,\n backdropMode = 'visible',\n customPixelEventId,\n customPixelEventName,\n onVisibilityChanged,\n}) => {\n const { handles } = useMinicartCssHandles()\n\n return (\n <Drawer\n maxWidth={maxDrawerWidth}\n backdropMode={backdropMode}\n slideDirection={drawerSlideDirection}\n customPixelEventId={customPixelEventId}\n customPixelEventName={customPixelEventName}\n onVisibilityChanged={onVisibilityChanged}\n customIcon={\n <MinicartIconButton\n Icon={Icon}\n itemCountMode={itemCountMode}\n quantityDisplay={quantityDisplay}\n />\n }\n >\n <div\n className={`${handles.minicartSideBarContentWrapper} flex flex-column w-100 h-100`}\n style={{\n height: window.innerHeight - DRAWER_CLOSE_ICON_HEIGHT,\n }}\n >\n {children}\n </div>\n </Drawer>\n )\n}\n\nexport default DrawerMode\n\n```"
}
] |
code_minicart_e8b3c9b0
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of minicart/react/components/Popup.tsx from the minicart VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React, { FC } from 'react'\nimport { Overlay } from 'vtex.react-portal'\nimport { usePixelEventCallback, PixelEventTypes } from 'vtex.pixel-manager'\n\nimport MinicartIconButton from './MinicartIconButton'\nimport { useMinicartCssHandles } from './CssHandlesContext'\nimport { useMinicartState, useMinicartDispatch } from '../MinicartContext'\nimport styles from '../styles.css'\n\nexport const CSS_HANDLES = [\n 'popupWrapper',\n 'popupContentContainer',\n 'arrowUp',\n 'popupChildrenContainer',\n] as const\n\ninterface Props {\n Icon: React.ComponentType\n quantityDisplay: QuantityDisplayType\n itemCountMode: MinicartTotalItemsType\n customPixelEventId?: string\n customPixelEventName?: PixelEventTypes.EventName\n variation?: string\n}\n\nconst PopupMode: FC<Props> = props => {\n const {\n children,\n quantityDisplay,\n Icon,\n itemCountMode,\n customPixelEventId,\n customPixelEventName,\n variation,\n } = props\n\n const {\n open,\n openBehavior,\n hasBeenOpened,\n openOnHoverProp,\n } = useMinicartState()\n\n const dispatch = useMinicartDispatch()\n const { handles } = useMinicartCssHandles()\n\n usePixelEventCallback({\n eventId: customPixelEventId,\n eventName: customPixelEventName,\n handler: () => {\n dispatch({ type: 'OPEN_MINICART' })\n },\n })\n\n const handleClick = () => {\n if (openOnHoverProp) {\n dispatch({ type: 'SET_OPEN_BEHAVIOR', value: 'hover' })\n }\n\n dispatch({ type: 'CLOSE_MINICART' })\n }\n\n const handleMouseLeave = () => {\n dispatch({ type: 'CLOSE_MINICART' })\n }\n\n return (\n <div onMouseLeave={openBehavior === 'hover' ? handleMouseLeave : undefined}>\n <MinicartIconButton\n variation={variation}\n Icon={Icon}\n itemCountMode={itemCountMode}\n quantityDisplay={quantityDisplay}\n />\n {open && (\n <Overlay>\n {openBehavior === 'click' && (\n // eslint-disable-next-line jsx-a11y/click-events-have-key-events,jsx-a11y/no-static-element-interactions\n <div\n className=\"fixed top-0 left-0 w-100 h-100\"\n onClick={handleClick}\n />\n )}\n <div\n className={`${handles.popupWrapper} ${styles.popupBoxPosition} absolute z-max flex flex-column`}\n >\n <div\n className={`${handles.popupContentContainer} w-100 shadow-3 bg-base`}\n >\n <div\n className={`${handles.arrowUp} ${styles.popupArrowUp} absolute top-0 bg-base h1 w1 pa4 rotate-45`}\n />\n <div\n className={`${handles.popupChildrenContainer} mt3 bg-base relative flex flex-column ph5 pv3`}\n >\n {hasBeenOpened && children}\n </div>\n </div>\n </div>\n </Overlay>\n )}\n </div>\n )\n}\n\nexport default PopupMode\n\n```"
}
] |
code_minicart_62dbbe46
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of minicart/react/components/CssHandlesContext.ts from the minicart VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { createCssHandlesContext } from 'vtex.css-handles'\n\nimport { CSS_HANDLES as MinicartCssHandles } from '../Minicart'\n\nconst { CssHandlesProvider, useContextCssHandles } = createCssHandlesContext(\n MinicartCssHandles\n)\n\nexport {\n CssHandlesProvider as MinicartCssHandlesProvider,\n useContextCssHandles as useMinicartCssHandles,\n}\n\n```"
}
] |
code_minicart_eda49dcc
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of minicart/react/components/MinicartIconButton.tsx from the minicart VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\nimport { ButtonWithIcon } from 'vtex.styleguide'\nimport { useOrderForm } from 'vtex.order-manager/OrderForm'\nimport { useCheckoutURL } from 'vtex.checkout-resources/Utils'\n\nimport styles from '../styles.css'\nimport { useMinicartCssHandles } from './CssHandlesContext'\nimport { useMinicartDispatch, useMinicartState } from '../MinicartContext'\nimport useCheckout from '../modules/checkoutHook'\n\nexport const CSS_HANDLES = [\n 'minicartIconContainer',\n 'minicartQuantityBadge',\n] as const\n\ninterface Props {\n Icon: React.ComponentType\n quantityDisplay: QuantityDisplayType\n itemCountMode: MinicartTotalItemsType\n variation?: string\n}\n\nconst countCartItems = (\n countMode: MinicartTotalItemsType,\n allItems: OrderFormItem[]\n) => {\n // Filter only main products, remove assembly items from the count\n const items = allItems.filter(item => item.parentItemIndex === null)\n\n if (countMode === 'distinctAvailable') {\n return items.reduce((itemQuantity: number, item) => {\n if (item.availability === 'available') {\n return itemQuantity + 1\n }\n return itemQuantity\n }, 0)\n }\n\n if (countMode === 'totalAvailable') {\n return items.reduce((itemQuantity: number, item) => {\n if (item.availability === 'available') {\n return itemQuantity + item.quantity\n }\n return itemQuantity\n }, 0)\n }\n\n if (countMode === 'total') {\n return items.reduce((itemQuantity: number, item) => {\n return itemQuantity + item.quantity\n }, 0)\n }\n\n // countMode === 'distinct'\n return items.length\n}\n\nconst MinicartIconButton: React.FC<Props> = props => {\n const { Icon, itemCountMode, quantityDisplay, variation } = props\n const { orderForm, loading }: OrderFormContext = useOrderForm()\n const { handles } = useMinicartCssHandles()\n const { open, openBehavior, openOnHoverProp } = useMinicartState()\n const dispatch = useMinicartDispatch()\n const quantity = countCartItems(itemCountMode, orderForm.items)\n const itemQuantity = loading ? 0 : quantity\n const { url: checkoutUrl } = useCheckoutURL()\n const goToCheckout = useCheckout()\n\n const handleClick = () => {\n if (openOnHoverProp) {\n if (variation === 'popupWithLink') {\n goToCheckout(checkoutUrl)\n }\n\n if (openBehavior === 'hover') {\n dispatch({\n type: 'SET_OPEN_BEHAVIOR',\n value: 'click',\n })\n\n return\n }\n dispatch({ type: 'CLOSE_MINICART' })\n dispatch({\n type: 'SET_OPEN_BEHAVIOR',\n value: 'hover',\n })\n\n return\n }\n\n dispatch({ type: open ? 'CLOSE_MINICART' : 'OPEN_MINICART' })\n }\n\n const showQuantityBadge =\n (itemQuantity > 0 && quantityDisplay === 'not-empty') ||\n quantityDisplay === 'always'\n\n return (\n <ButtonWithIcon\n icon={\n <span className={`${handles.minicartIconContainer} gray relative`}>\n <Icon />\n {showQuantityBadge && (\n <span\n style={{ userSelect: 'none' }}\n className={`${handles.minicartQuantityBadge} ${styles.minicartQuantityBadgeDefault} c-on-emphasis absolute t-mini bg-emphasis br4 w1 h1 pa1 flex justify-center items-center lh-solid`}\n >\n {itemQuantity}\n </span>\n )}\n </span>\n }\n variation=\"tertiary\"\n onMouseEnter={\n openBehavior === 'hover'\n ? () => dispatch({ type: 'OPEN_MINICART' })\n : undefined\n }\n onClick={handleClick}\n />\n )\n}\n\nexport default MinicartIconButton\n\n```"
}
] |
code_minicart_cd9be866
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of minicart/react/modules/useCartIdPixel.tsx from the minicart VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport { useEffect } from 'react'\nimport { usePixel } from 'vtex.pixel-manager'\n\nconst useCartIdPixel = (orderFormId?: string) => {\n const { push } = usePixel()\n\n useEffect(() => {\n if (!orderFormId) {\n return\n }\n\n push({\n event: 'cartId',\n cartId: orderFormId,\n })\n }, [push, orderFormId])\n}\n\nexport default useCartIdPixel\n\n```"
}
] |
code_minicart_23495505
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of minicart/react/modules/pixelHelper.ts from the minicart VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nexport function mapCartItemToPixel(item: CartItem): PixelCartItem {\n return {\n skuId: item.id,\n variant: item.skuName,\n price: item.sellingPrice,\n priceIsInt: true,\n name: getNameWithoutVariant(item),\n quantity: item.quantity,\n productId: item.productId,\n productRefId: item.productRefId,\n brand: item.additionalInfo ? item.additionalInfo.brandName : '',\n category: productCategory(item),\n detailUrl: item.detailUrl,\n imageUrl: item.imageUrls\n ? fixUrlProtocol(item.imageUrls.at3x)\n : item.imageUrl ?? '',\n referenceId: item.refId,\n }\n}\n\nexport function mapBuyButtonItemToPixel(item: BuyButtonItem): PixelCartItem {\n // Change this `/Apparel & Accessories/Clothing/Tops/`\n // to this `Apparel & Accessories/Clothing/Tops`\n const category = item.category ? item.category.slice(1, -1) : ''\n\n return {\n skuId: item.id,\n variant: item.skuName,\n price: item.sellingPrice,\n priceIsInt: true,\n name: item.name,\n quantity: item.quantity,\n productId: item.productId,\n productRefId: item.productRefId,\n brand: item.brand,\n category,\n detailUrl: item.detailUrl,\n imageUrl: item.imageUrl,\n referenceId: item.refId,\n }\n}\n\n/**\n * URL comes like \"//storecomponents.vteximg.com.br/arquivos/ids/155491\"\n * this function guarantees it comes with protocol in it.\n */\nfunction fixUrlProtocol(url: string) {\n if (!url || url.indexOf('http') === 0) {\n return url\n }\n\n return `https:${url}`\n}\n\n/**\n * Remove the variant from the end of the name.\n * Ex: from \"Classic Shoes Pink\" to \"Classic Shoes\"\n * Ps: Some products has the name of the variation the same as the item\n */\nfunction getNameWithoutVariant(item: CartItem) {\n if (\n (item?.name && !item.name.includes(item.skuName)) ||\n item.name === item.skuName\n ) {\n return item.name\n }\n\n const leadingSpace = 1\n const variantLength = leadingSpace + item.skuName.length\n\n return item.name.slice(0, item.name.length - variantLength)\n}\n\nfunction productCategory(item: CartItem) {\n try {\n const categoryIds = item.productCategoryIds.split('/').filter(c => c.length)\n const category = categoryIds.map(id => item.productCategories[id]).join('/')\n\n return category\n } catch {\n return ''\n }\n}\n\nexport function transformOrderFormItems(orderFormItems: OrderForm['items']) {\n if (!orderFormItems || !orderFormItems.length) return []\n return orderFormItems.map(item => mapCartItemToPixel(item))\n}\n\nexport interface PixelCartItem {\n skuId: string\n variant: string\n price: number\n priceIsInt: boolean\n name: string\n quantity: number\n productId: string\n productRefId: string\n brand: string\n category: string\n detailUrl: string\n imageUrl: string\n referenceId: string\n}\n\ninterface BuyButtonItem {\n id: string\n skuName: string\n sellingPrice: number\n name: string\n quantity: number\n productId: string\n productRefId: string\n brand: string\n category: string\n detailUrl: string\n imageUrl: string\n refId: string\n}\n\ninterface CartItem {\n id: string\n skuName: string\n sellingPrice: number\n name: string\n quantity: number\n productId: string\n productRefId: string\n additionalInfo: {\n brandName: string\n }\n productCategoryIds: string\n productCategories: Record<string, string>\n detailUrl: string\n // Field from the usual orderForm API\n imageUrl?: string\n // Field from the order-manager orderForm API\n imageUrls?: {\n at1x: string\n at2x: string\n at3x: string\n }\n refId: string\n}\n\n```"
}
] |
code_minicart_8e75f451
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of minicart/react/modules/useViewCartPixel.tsx from the minicart VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport { useCallback, useEffect } from 'react'\nimport { usePixel } from 'vtex.pixel-manager'\nimport { debounce } from 'debounce'\n\nimport { PixelCartItem, transformOrderFormItems } from './pixelHelper'\n\nconst useViewCartPixel = (\n isOpen: boolean,\n orderFormItems: OrderForm['items']\n) => {\n const { push } = usePixel()\n\n const transformedItems = transformOrderFormItems(orderFormItems)\n\n const pushViewCart = useCallback(\n debounce((items: PixelCartItem[]) => {\n push({\n event: 'viewCart',\n items,\n })\n }, 1000),\n [push]\n )\n\n useEffect(() => {\n if (!isOpen) {\n return\n }\n\n pushViewCart(transformedItems)\n }, [pushViewCart, isOpen, transformedItems])\n}\n\nexport default useViewCartPixel\n\n```"
}
] |
code_minicart_162b7e07
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of minicart/react/modules/debouncedPixelHook.ts from the minicart VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { useRef } from 'react'\nimport { usePixel } from 'vtex.pixel-manager'\nimport debounce from 'debounce'\n\nexport default function useDebouncedPush() {\n const { push } = usePixel()\n const debouncedPush = useRef<typeof push>(debounce(push, 600))\n\n return debouncedPush.current\n}\n\n```"
}
] |
code_minicart_3e09bb5b
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of minicart/react/modules/checkoutHook.ts from the minicart VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { useCheckoutURL } from 'vtex.checkout-resources/Utils'\nimport { useRuntime } from 'vtex.render-runtime'\n\nexport default function useCheckout() {\n const { url: checkoutUrl, major } = useCheckoutURL()\n const { navigate, rootPath = '' } = useRuntime()\n\n const goToCheckout = (url: string) => {\n if (major > 0 && url === checkoutUrl) {\n navigate({ to: url })\n } else {\n window.location.href = `${rootPath}${url}`\n }\n }\n\n return goToCheckout\n}\n\n```"
}
] |
code_minicart_0ad07f9d
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of minicart/react/legacy/__fixtures__/emptyOrderForm.js from the minicart VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nexport default {\n cacheId: '3335fe72057045398dd28bd2fa203b21',\n orderFormId: '3335fe72057045398dd28bd2fa203b21',\n value: 0,\n totalizers: [\n {\n id: 'Items',\n name: 'Items Total',\n value: 0,\n __typename: 'vtex_storegraphql_2_51_0_Totalizer',\n },\n {\n id: 'Shipping',\n name: 'Shipping Total',\n value: 0,\n __typename: 'vtex_storegraphql_2_51_0_Totalizer',\n },\n ],\n items: [],\n shippingData: {\n address: {\n id: null,\n neighborhood: 'Botafogo',\n complement: '',\n number: '300',\n street: 'Praia de Botafogo',\n postalCode: '22250-040',\n city: 'Rio de Janeiro',\n reference: null,\n addressName: null,\n addressType: 'residential',\n __typename: 'vtex_storegraphql_2_51_0_Address',\n },\n availableAddresses: [\n {\n id: null,\n neighborhood: 'Botafogo',\n complement: '',\n number: '300',\n street: 'Praia de Botafogo',\n postalCode: '22250-040',\n city: 'Rio de Janeiro',\n reference: null,\n addressName: null,\n addressType: 'residential',\n __typename: 'vtex_storegraphql_2_51_0_Address',\n },\n ],\n __typename: 'vtex_storegraphql_2_51_0_OrderFormShippingData',\n },\n clientProfileData: null,\n storePreferencesData: {\n countryCode: 'BRA',\n currencyCode: 'BRL',\n timeZone: 'E. South America Standard Time',\n },\n itemMetadata: {\n items: [],\n },\n}\n\n```"
}
] |
code_minicart_0f5cb4c9
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of minicart/react/legacy/__fixtures__/orderFormAttachments.json from the minicart VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"data\": {\n \"orderForm\": {\n \"cacheId\": \"3335fe72057045398dd28bd2fa203b21\",\n \"orderFormId\": \"3335fe72057045398dd28bd2fa203b21\",\n \"value\": 22.400000000000002,\n \"totalizers\": [\n {\n \"id\": \"Items\",\n \"name\": \"Items Total\",\n \"value\": 2240,\n \"__typename\": \"vtex_storegraphql_2_51_0_Totalizer\"\n },\n {\n \"id\": \"Shipping\",\n \"name\": \"Shipping Total\",\n \"value\": 0,\n \"__typename\": \"vtex_storegraphql_2_51_0_Totalizer\"\n }\n ],\n \"items\": [\n {\n \"id\": \"17\",\n \"name\": \"Pepperoni Small\",\n \"imageUrl\": \"http://delivery.vteximg.com.br/arquivos/ids/155439-55-55/pepperoni-feast.0e1c4c9e7b8900d08cc51ff285fd9ae3.1.jpg?v=636770441237070000\",\n \"detailUrl\": \"/pizza-pepperoni/p\",\n \"skuName\": \"Small\",\n \"quantity\": 1,\n \"sellingPrice\": 14.9,\n \"listPrice\": 14.9,\n \"parentItemIndex\": null,\n \"parentAssemblyBinding\": null,\n \"assemblyOptions\": {\n \"added\": [\n {\n \"item\": {\n \"name\": \"Classic Crust\",\n \"sellingPrice\": 0,\n \"quantity\": 1,\n \"__typename\": \"vtex_storegraphql_2_51_0_OrderFormItem\"\n },\n \"normalizedQuantity\": 1,\n \"choiceType\": \"SINGLE\",\n \"extraQuantity\": 0,\n \"__typename\": \"vtex_storegraphql_2_51_0_AddedOptionItem\"\n },\n {\n \"item\": {\n \"name\": \"Pepperoni\",\n \"sellingPrice\": 0,\n \"quantity\": 1,\n \"__typename\": \"vtex_storegraphql_2_51_0_OrderFormItem\"\n },\n \"normalizedQuantity\": 1,\n \"choiceType\": \"TOGGLE\",\n \"extraQuantity\": 0,\n \"__typename\": \"vtex_storegraphql_2_51_0_AddedOptionItem\"\n },\n {\n \"item\": {\n \"name\": \"Ham\",\n \"sellingPrice\": 1.5,\n \"quantity\": 3,\n \"__typename\": \"vtex_storegraphql_2_51_0_OrderFormItem\"\n },\n \"normalizedQuantity\": 3,\n \"choiceType\": \"MULTIPLE\",\n \"extraQuantity\": 3,\n \"__typename\": \"vtex_storegraphql_2_51_0_AddedOptionItem\"\n },\n {\n \"item\": {\n \"name\": \"Pineapple\",\n \"sellingPrice\": 1,\n \"quantity\": 3,\n \"__typename\": \"vtex_storegraphql_2_51_0_OrderFormItem\"\n },\n \"normalizedQuantity\": 3,\n \"choiceType\": \"MULTIPLE\",\n \"extraQuantity\": 3,\n \"__typename\": \"vtex_storegraphql_2_51_0_AddedOptionItem\"\n }\n ],\n \"removed\": [\n {\n \"removedQuantity\": 1,\n \"initialQuantity\": 1,\n \"name\": \"Onion\",\n \"__typename\": \"vtex_storegraphql_2_51_0_RemovedOptionItem\"\n }\n ],\n \"parentPrice\": 14.9,\n \"__typename\": \"vtex_storegraphql_2_51_0_AssemblyOptionItem\"\n },\n \"__typename\": \"vtex_storegraphql_2_51_0_OrderFormItem\"\n },\n {\n \"id\": \"14\",\n \"name\": \"Classic Crust\",\n \"imageUrl\": \"http://delivery.vteximg.com.br/arquivos/ids/155413-55-55/classic.png?v=636759866429100000\",\n \"detailUrl\": \"/classic-crust/p\",\n \"skuName\": \"Classic Crust\",\n \"quantity\": 1,\n \"sellingPrice\": 0,\n \"listPrice\": 0,\n \"parentItemIndex\": 0,\n \"parentAssemblyBinding\": \"Pepperoni - Small_Crust\",\n \"assemblyOptions\": {\n \"added\": [],\n \"removed\": [],\n \"parentPrice\": 0,\n \"__typename\": \"vtex_storegraphql_2_51_0_AssemblyOptionItem\"\n },\n \"__typename\": \"vtex_storegraphql_2_51_0_OrderFormItem\"\n },\n {\n \"id\": \"9\",\n \"name\": \"Pepperoni\",\n \"imageUrl\": \"http://delivery.vteximg.com.br/arquivos/ids/155428-55-55/Topping_Pepperoni.jpg.png?v=636766047561270000\",\n \"detailUrl\": \"/pepperoni/p\",\n \"skuName\": \"Pepperoni\",\n \"quantity\": 1,\n \"sellingPrice\": 0,\n \"listPrice\": 0,\n \"parentItemIndex\": 0,\n \"parentAssemblyBinding\": \"Pepperoni - Small_Basic Toppings\",\n \"assemblyOptions\": {\n \"added\": [],\n \"removed\": [],\n \"parentPrice\": 0,\n \"__typename\": \"vtex_storegraphql_2_51_0_AssemblyOptionItem\"\n },\n \"__typename\": \"vtex_storegraphql_2_51_0_OrderFormItem\"\n },\n {\n \"id\": \"8\",\n \"name\": \"Ham\",\n \"imageUrl\": \"http://delivery.vteximg.com.br/arquivos/ids/155432-55-55/Topping_Jamon.jpg.png?v=636766052579200000\",\n \"detailUrl\": \"/ham/p\",\n \"skuName\": \"Ham\",\n \"quantity\": 3,\n \"sellingPrice\": 1.5,\n \"listPrice\": 1.5,\n \"parentItemIndex\": 0,\n \"parentAssemblyBinding\": \"Pepperoni - Small_Toppings\",\n \"assemblyOptions\": {\n \"added\": [],\n \"removed\": [],\n \"parentPrice\": 1.5,\n \"__typename\": \"vtex_storegraphql_2_51_0_AssemblyOptionItem\"\n },\n \"__typename\": \"vtex_storegraphql_2_51_0_OrderFormItem\"\n },\n {\n \"id\": \"38\",\n \"name\": \"Pineapple\",\n \"imageUrl\": \"http://delivery.vteximg.com.br/arquivos/ids/155435-55-55/Topping_Pina.jpg.png?v=636766056177370000\",\n \"detailUrl\": \"/pineapple/p\",\n \"skuName\": \"Pineapple\",\n \"quantity\": 3,\n \"sellingPrice\": 1,\n \"listPrice\": 1,\n \"parentItemIndex\": 0,\n \"parentAssemblyBinding\": \"Pepperoni - Small_Toppings\",\n \"assemblyOptions\": {\n \"added\": [],\n \"removed\": [],\n \"parentPrice\": 1,\n \"__typename\": \"vtex_storegraphql_2_51_0_AssemblyOptionItem\"\n },\n \"__typename\": \"vtex_storegraphql_2_51_0_OrderFormItem\"\n }\n ],\n \"shippingData\": {\n \"address\": {\n \"id\": null,\n \"neighborhood\": \"Botafogo\",\n \"complement\": \"\",\n \"number\": \"300\",\n \"street\": \"Praia de Botafogo\",\n \"postalCode\": \"22250-040\",\n \"city\": \"Rio de Janeiro\",\n \"reference\": null,\n \"addressName\": null,\n \"addressType\": \"residential\",\n \"__typename\": \"vtex_storegraphql_2_51_0_Address\"\n },\n \"availableAddresses\": [\n {\n \"id\": null,\n \"neighborhood\": \"Botafogo\",\n \"complement\": \"\",\n \"number\": \"300\",\n \"street\": \"Praia de Botafogo\",\n \"postalCode\": \"22250-040\",\n \"city\": \"Rio de Janeiro\",\n \"reference\": null,\n \"addressName\": null,\n \"addressType\": \"residential\",\n \"__typename\": \"vtex_storegraphql_2_51_0_Address\"\n }\n ],\n \"__typename\": \"vtex_storegraphql_2_51_0_OrderFormShippingData\"\n },\n \"clientProfileData\": null,\n \"storePreferencesData\": {\n \"countryCode\": \"BRA\",\n \"currencyCode\": \"BRL\",\n \"timeZone\": \"E. South America Standard Time\",\n \"__typename\": \"vtex_storegraphql_2_51_0_StorePreferencesData\"\n },\n \"itemMetadata\": {\n \"items\": [\n {\n \"id\": \"17\",\n \"name\": \"Pepperoni Small\",\n \"skuName\": \"Small\",\n \"productId\": \"13\",\n \"refId\": \"1111\",\n \"ean\": null,\n \"imageUrl\": \"http://delivery.vteximg.com.br/arquivos/ids/155439-55-55/pepperoni-feast.0e1c4c9e7b8900d08cc51ff285fd9ae3.1.jpg?v=636770441237070000\",\n \"detailUrl\": \"/pizza-pepperoni/p\",\n \"assemblyOptions\": [\n {\n \"id\": \"Pepperoni - Small_Crust\",\n \"name\": \"Pepperoni - Small\",\n \"required\": true,\n \"composition\": {\n \"minQuantity\": 1,\n \"maxQuantity\": 1,\n \"items\": [\n {\n \"maxQuantity\": 1,\n \"initialQuantity\": 1,\n \"id\": \"14\",\n \"__typename\": \"vtex_storegraphql_2_51_0_CompositionItem\"\n }\n ],\n \"__typename\": \"vtex_storegraphql_2_51_0_CompositionType\"\n },\n \"__typename\": \"vtex_storegraphql_2_51_0_AssemblyOption\"\n },\n {\n \"id\": \"Pepperoni - Small_Toppings\",\n \"name\": \"Pepperoni - Small\",\n \"required\": true,\n \"composition\": {\n \"minQuantity\": 0,\n \"maxQuantity\": 10,\n \"items\": [\n {\n \"maxQuantity\": 3,\n \"initialQuantity\": 0,\n \"id\": \"8\",\n \"__typename\": \"vtex_storegraphql_2_51_0_CompositionItem\"\n },\n {\n \"maxQuantity\": 3,\n \"initialQuantity\": 0,\n \"id\": \"9\",\n \"__typename\": \"vtex_storegraphql_2_51_0_CompositionItem\"\n },\n {\n \"maxQuantity\": 3,\n \"initialQuantity\": 0,\n \"id\": \"10\",\n \"__typename\": \"vtex_storegraphql_2_51_0_CompositionItem\"\n },\n {\n \"maxQuantity\": 3,\n \"initialQuantity\": 0,\n \"id\": \"11\",\n \"__typename\": \"vtex_storegraphql_2_51_0_CompositionItem\"\n },\n {\n \"maxQuantity\": 3,\n \"initialQuantity\": 0,\n \"id\": \"36\",\n \"__typename\": \"vtex_storegraphql_2_51_0_CompositionItem\"\n },\n {\n \"maxQuantity\": 3,\n \"initialQuantity\": 0,\n \"id\": \"37\",\n \"__typename\": \"vtex_storegraphql_2_51_0_CompositionItem\"\n },\n {\n \"maxQuantity\": 3,\n \"initialQuantity\": 0,\n \"id\": \"38\",\n \"__typename\": \"vtex_storegraphql_2_51_0_CompositionItem\"\n }\n ],\n \"__typename\": \"vtex_storegraphql_2_51_0_CompositionType\"\n },\n \"__typename\": \"vtex_storegraphql_2_51_0_AssemblyOption\"\n },\n {\n \"id\": \"Pepperoni - Small_Basic Toppings\",\n \"name\": \"Pepperoni - Small\",\n \"required\": true,\n \"composition\": {\n \"minQuantity\": 1,\n \"maxQuantity\": 2,\n \"items\": [\n {\n \"maxQuantity\": 1,\n \"initialQuantity\": 1,\n \"id\": \"9\",\n \"__typename\": \"vtex_storegraphql_2_51_0_CompositionItem\"\n },\n {\n \"maxQuantity\": 1,\n \"initialQuantity\": 1,\n \"id\": \"11\",\n \"__typename\": \"vtex_storegraphql_2_51_0_CompositionItem\"\n }\n ],\n \"__typename\": \"vtex_storegraphql_2_51_0_CompositionType\"\n },\n \"__typename\": \"vtex_storegraphql_2_51_0_AssemblyOption\"\n }\n ],\n \"__typename\": \"vtex_storegraphql_2_51_0_ItemMetadataUnit\"\n },\n {\n \"id\": \"14\",\n \"name\": \"Classic Crust\",\n \"skuName\": \"Classic Crust\",\n \"productId\": \"12\",\n \"refId\": \"14\",\n \"ean\": null,\n \"imageUrl\": \"http://delivery.vteximg.com.br/arquivos/ids/155413-55-55/classic.png?v=636759866429100000\",\n \"detailUrl\": \"/classic-crust/p\",\n \"assemblyOptions\": [],\n \"__typename\": \"vtex_storegraphql_2_51_0_ItemMetadataUnit\"\n },\n {\n \"id\": \"8\",\n \"name\": \"Ham\",\n \"skuName\": \"Ham\",\n \"productId\": \"6\",\n \"refId\": \"2\",\n \"ean\": null,\n \"imageUrl\": \"http://delivery.vteximg.com.br/arquivos/ids/155432-55-55/Topping_Jamon.jpg.png?v=636766052579200000\",\n \"detailUrl\": \"/ham/p\",\n \"assemblyOptions\": [],\n \"__typename\": \"vtex_storegraphql_2_51_0_ItemMetadataUnit\"\n },\n {\n \"id\": \"9\",\n \"name\": \"Pepperoni\",\n \"skuName\": \"Pepperoni\",\n \"productId\": \"7\",\n \"refId\": \"3\",\n \"ean\": null,\n \"imageUrl\": \"http://delivery.vteximg.com.br/arquivos/ids/155428-55-55/Topping_Pepperoni.jpg.png?v=636766047561270000\",\n \"detailUrl\": \"/pepperoni/p\",\n \"assemblyOptions\": [],\n \"__typename\": \"vtex_storegraphql_2_51_0_ItemMetadataUnit\"\n },\n {\n \"id\": \"10\",\n \"name\": \"Champignon\",\n \"skuName\": \"Champignon\",\n \"productId\": \"8\",\n \"refId\": \"4\",\n \"ean\": null,\n \"imageUrl\": \"http://delivery.vteximg.com.br/arquivos/ids/155436-55-55/Topping_Champinones.png?v=636766057405600000\",\n \"detailUrl\": \"/champignon/p\",\n \"assemblyOptions\": [],\n \"__typename\": \"vtex_storegraphql_2_51_0_ItemMetadataUnit\"\n },\n {\n \"id\": \"11\",\n \"name\": \"Onion\",\n \"skuName\": \"Onion\",\n \"productId\": \"9\",\n \"refId\": \"5\",\n \"ean\": null,\n \"imageUrl\": \"http://delivery.vteximg.com.br/arquivos/ids/155427-55-55/Topping_Cebolla.jpg.png?v=636766046799500000\",\n \"detailUrl\": \"/onion/p\",\n \"assemblyOptions\": [],\n \"__typename\": \"vtex_storegraphql_2_51_0_ItemMetadataUnit\"\n },\n {\n \"id\": \"36\",\n \"name\": \"Black Olives\",\n \"skuName\": \"Black Olives\",\n \"productId\": \"23\",\n \"refId\": \"151113\",\n \"ean\": null,\n \"imageUrl\": \"http://delivery.vteximg.com.br/arquivos/ids/155430-55-55/Topping_Aceitunas-Negras.jpg.png?v=636766049376970000\",\n \"detailUrl\": \"/black-olives/p\",\n \"assemblyOptions\": [],\n \"__typename\": \"vtex_storegraphql_2_51_0_ItemMetadataUnit\"\n },\n {\n \"id\": \"37\",\n \"name\": \"Green Pepper\",\n \"skuName\": \"Green Pepper\",\n \"productId\": \"24\",\n \"refId\": \"123123\",\n \"ean\": null,\n \"imageUrl\": \"http://delivery.vteximg.com.br/arquivos/ids/155431-55-55/PIMIENTO-VERDE.png?v=636766050771230000\",\n \"detailUrl\": \"/green-pepper/p\",\n \"assemblyOptions\": [],\n \"__typename\": \"vtex_storegraphql_2_51_0_ItemMetadataUnit\"\n },\n {\n \"id\": \"38\",\n \"name\": \"Pineapple\",\n \"skuName\": \"Pineapple\",\n \"productId\": \"25\",\n \"refId\": \"121211\",\n \"ean\": null,\n \"imageUrl\": \"http://delivery.vteximg.com.br/arquivos/ids/155435-55-55/Topping_Pina.jpg.png?v=636766056177370000\",\n \"detailUrl\": \"/pineapple/p\",\n \"assemblyOptions\": [],\n \"__typename\": \"vtex_storegraphql_2_51_0_ItemMetadataUnit\"\n }\n ],\n \"__typename\": \"vtex_storegraphql_2_51_0_ItemMetadata\"\n },\n \"__typename\": \"vtex_storegraphql_2_51_0_OrderForm\"\n }\n }\n}\n\n```"
}
] |
code_minicart_06efea55
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of minicart/react/legacy/__fixtures__/orderForm.js from the minicart VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nexport default {\n cacheId: '3335fe72057045398dd28bd2fa203b21',\n orderFormId: '3335fe72057045398dd28bd2fa203b21',\n value: 22.400000000000002,\n totalizers: [\n {\n id: 'Items',\n name: 'Items Total',\n value: 2240,\n __typename: 'vtex_storegraphql_2_51_0_Totalizer',\n },\n {\n id: 'Shipping',\n name: 'Shipping Total',\n value: 0,\n __typename: 'vtex_storegraphql_2_51_0_Totalizer',\n },\n ],\n items: [\n {\n id: '17',\n name: 'Pepperoni Small',\n imageUrl:\n 'http://delivery.vteximg.com.br/arquivos/ids/155439-55-55/pepperoni-feast.0e1c4c9e7b8900d08cc51ff285fd9ae3.1.jpg?v=636770441237070000',\n detailUrl: '/pizza-pepperoni/p',\n skuName: 'Small',\n quantity: 2,\n productRefId: 'PSMALL',\n additionalInfo: {\n brandName: 'PizzaHut',\n },\n productCategoryIds: '/1/',\n productCategories: { 1: 'Pizza' },\n sellingPrice: 14.9,\n listPrice: 14.9,\n parentItemIndex: null,\n parentAssemblyBinding: null,\n assemblyOptions: {\n added: [\n {\n item: {\n name: 'Classic Crust',\n sellingPrice: 0,\n quantity: 1,\n __typename: 'vtex_storegraphql_2_51_0_OrderFormItem',\n },\n normalizedQuantity: 1,\n choiceType: 'SINGLE',\n extraQuantity: 0,\n __typename: 'vtex_storegraphql_2_51_0_AddedOptionItem',\n },\n {\n item: {\n name: 'Pepperoni',\n sellingPrice: 0,\n quantity: 1,\n __typename: 'vtex_storegraphql_2_51_0_OrderFormItem',\n },\n normalizedQuantity: 1,\n choiceType: 'TOGGLE',\n extraQuantity: 0,\n __typename: 'vtex_storegraphql_2_51_0_AddedOptionItem',\n },\n {\n item: {\n name: 'Ham',\n sellingPrice: 1.5,\n quantity: 3,\n __typename: 'vtex_storegraphql_2_51_0_OrderFormItem',\n },\n normalizedQuantity: 3,\n choiceType: 'MULTIPLE',\n extraQuantity: 3,\n __typename: 'vtex_storegraphql_2_51_0_AddedOptionItem',\n },\n {\n item: {\n name: 'Pineapple',\n sellingPrice: 1,\n quantity: 3,\n __typename: 'vtex_storegraphql_2_51_0_OrderFormItem',\n },\n normalizedQuantity: 3,\n choiceType: 'MULTIPLE',\n extraQuantity: 3,\n __typename: 'vtex_storegraphql_2_51_0_AddedOptionItem',\n },\n ],\n removed: [\n {\n removedQuantity: 1,\n initialQuantity: 1,\n name: 'Onion',\n __typename: 'vtex_storegraphql_2_51_0_RemovedOptionItem',\n },\n ],\n parentPrice: 14.9,\n __typename: 'vtex_storegraphql_2_51_0_AssemblyOptionItem',\n },\n __typename: 'vtex_storegraphql_2_51_0_OrderFormItem',\n },\n {\n id: '14',\n name: 'Classic Crust',\n imageUrl:\n 'http://delivery.vteximg.com.br/arquivos/ids/155413-55-55/classic.png?v=636759866429100000',\n detailUrl: '/classic-crust/p',\n skuName: 'Classic Crust',\n quantity: 1,\n productRefId: 'CLASSICCRUST',\n additionalInfo: {\n brandName: 'PizzaHut',\n },\n productCategoryIds: '/1/',\n productCategories: { 1: 'Pizza' },\n sellingPrice: 0,\n listPrice: 0,\n parentItemIndex: 0,\n parentAssemblyBinding: 'Pepperoni - Small_Crust',\n assemblyOptions: {\n added: [],\n removed: [],\n parentPrice: 0,\n __typename: 'vtex_storegraphql_2_51_0_AssemblyOptionItem',\n },\n __typename: 'vtex_storegraphql_2_51_0_OrderFormItem',\n },\n {\n id: '9',\n name: 'Pepperoni',\n imageUrl:\n 'http://delivery.vteximg.com.br/arquivos/ids/155428-55-55/Topping_Pepperoni.jpg.png?v=636766047561270000',\n detailUrl: '/pepperoni/p',\n skuName: 'Pepperoni',\n quantity: 1,\n productRefId: 'PEPPERONI',\n additionalInfo: {\n brandName: 'PizzaHut',\n },\n productCategoryIds: '/1/',\n productCategories: { 1: 'Pizza' },\n sellingPrice: 0,\n listPrice: 0,\n parentItemIndex: 0,\n parentAssemblyBinding: 'Pepperoni - Small_Basic Toppings',\n assemblyOptions: {\n added: [],\n removed: [],\n parentPrice: 0,\n __typename: 'vtex_storegraphql_2_51_0_AssemblyOptionItem',\n },\n __typename: 'vtex_storegraphql_2_51_0_OrderFormItem',\n },\n {\n id: '8',\n name: 'Ham',\n imageUrl:\n 'http://delivery.vteximg.com.br/arquivos/ids/155432-55-55/Topping_Jamon.jpg.png?v=636766052579200000',\n detailUrl: '/ham/p',\n skuName: 'Ham',\n quantity: 3,\n productRefId: 'HAM',\n additionalInfo: {\n brandName: 'PizzaHut',\n },\n productCategoryIds: '/1/',\n productCategories: { 1: 'Pizza' },\n sellingPrice: 1.5,\n listPrice: 1.5,\n parentItemIndex: 0,\n parentAssemblyBinding: 'Pepperoni - Small_Toppings',\n assemblyOptions: {\n added: [],\n removed: [],\n parentPrice: 1.5,\n __typename: 'vtex_storegraphql_2_51_0_AssemblyOptionItem',\n },\n __typename: 'vtex_storegraphql_2_51_0_OrderFormItem',\n },\n {\n id: '38',\n name: 'Pineapple',\n imageUrl:\n 'http://delivery.vteximg.com.br/arquivos/ids/155435-55-55/Topping_Pina.jpg.png?v=636766056177370000',\n detailUrl: '/pineapple/p',\n skuName: 'Pineapple',\n quantity: 3,\n productRefId: 'PINEAPPLE',\n additionalInfo: {\n brandName: 'PizzaHut',\n },\n productCategoryIds: '/1/',\n productCategories: { 1: 'Pizza' },\n sellingPrice: 1,\n listPrice: 1,\n parentItemIndex: 0,\n parentAssemblyBinding: 'Pepperoni - Small_Toppings',\n assemblyOptions: {\n added: [],\n removed: [],\n parentPrice: 1,\n __typename: 'vtex_storegraphql_2_51_0_AssemblyOptionItem',\n },\n __typename: 'vtex_storegraphql_2_51_0_OrderFormItem',\n },\n ],\n shippingData: {\n address: {\n id: null,\n neighborhood: 'Botafogo',\n complement: '',\n number: '300',\n street: 'Praia de Botafogo',\n postalCode: '22250-040',\n city: 'Rio de Janeiro',\n reference: null,\n addressName: null,\n addressType: 'residential',\n __typename: 'vtex_storegraphql_2_51_0_Address',\n },\n availableAddresses: [\n {\n id: null,\n neighborhood: 'Botafogo',\n complement: '',\n number: '300',\n street: 'Praia de Botafogo',\n postalCode: '22250-040',\n city: 'Rio de Janeiro',\n reference: null,\n addressName: null,\n addressType: 'residential',\n __typename: 'vtex_storegraphql_2_51_0_Address',\n },\n ],\n __typename: 'vtex_storegraphql_2_51_0_OrderFormShippingData',\n },\n clientProfileData: null,\n storePreferencesData: {\n countryCode: 'BRA',\n currencyCode: 'BRL',\n timeZone: 'E. South America Standard Time',\n __typename: 'vtex_storegraphql_2_51_0_StorePreferencesData',\n },\n itemMetadata: {\n items: [\n {\n id: '17',\n name: 'Pepperoni Small',\n skuName: 'Small',\n productId: '13',\n refId: '1111',\n ean: null,\n imageUrl:\n 'http://delivery.vteximg.com.br/arquivos/ids/155439-55-55/pepperoni-feast.0e1c4c9e7b8900d08cc51ff285fd9ae3.1.jpg?v=636770441237070000',\n detailUrl: '/pizza-pepperoni/p',\n assemblyOptions: [\n {\n id: 'Pepperoni - Small_Crust',\n name: 'Pepperoni - Small',\n required: true,\n composition: {\n minQuantity: 1,\n maxQuantity: 1,\n items: [\n {\n maxQuantity: 1,\n initialQuantity: 1,\n id: '14',\n __typename: 'vtex_storegraphql_2_51_0_CompositionItem',\n },\n ],\n __typename: 'vtex_storegraphql_2_51_0_CompositionType',\n },\n __typename: 'vtex_storegraphql_2_51_0_AssemblyOption',\n },\n {\n id: 'Pepperoni - Small_Toppings',\n name: 'Pepperoni - Small',\n required: true,\n composition: {\n minQuantity: 0,\n maxQuantity: 10,\n items: [\n {\n maxQuantity: 3,\n initialQuantity: 0,\n id: '8',\n __typename: 'vtex_storegraphql_2_51_0_CompositionItem',\n },\n {\n maxQuantity: 3,\n initialQuantity: 0,\n id: '9',\n __typename: 'vtex_storegraphql_2_51_0_CompositionItem',\n },\n {\n maxQuantity: 3,\n initialQuantity: 0,\n id: '10',\n __typename: 'vtex_storegraphql_2_51_0_CompositionItem',\n },\n {\n maxQuantity: 3,\n initialQuantity: 0,\n id: '11',\n __typename: 'vtex_storegraphql_2_51_0_CompositionItem',\n },\n {\n maxQuantity: 3,\n initialQuantity: 0,\n id: '36',\n __typename: 'vtex_storegraphql_2_51_0_CompositionItem',\n },\n {\n maxQuantity: 3,\n initialQuantity: 0,\n id: '37',\n __typename: 'vtex_storegraphql_2_51_0_CompositionItem',\n },\n {\n maxQuantity: 3,\n initialQuantity: 0,\n id: '38',\n __typename: 'vtex_storegraphql_2_51_0_CompositionItem',\n },\n ],\n __typename: 'vtex_storegraphql_2_51_0_CompositionType',\n },\n __typename: 'vtex_storegraphql_2_51_0_AssemblyOption',\n },\n {\n id: 'Pepperoni - Small_Basic Toppings',\n name: 'Pepperoni - Small',\n required: true,\n composition: {\n minQuantity: 1,\n maxQuantity: 2,\n items: [\n {\n maxQuantity: 1,\n initialQuantity: 1,\n id: '9',\n __typename: 'vtex_storegraphql_2_51_0_CompositionItem',\n },\n {\n maxQuantity: 1,\n initialQuantity: 1,\n id: '11',\n __typename: 'vtex_storegraphql_2_51_0_CompositionItem',\n },\n ],\n __typename: 'vtex_storegraphql_2_51_0_CompositionType',\n },\n __typename: 'vtex_storegraphql_2_51_0_AssemblyOption',\n },\n ],\n __typename: 'vtex_storegraphql_2_51_0_ItemMetadataUnit',\n },\n {\n id: '14',\n name: 'Classic Crust',\n skuName: 'Classic Crust',\n productId: '12',\n refId: '14',\n ean: null,\n imageUrl:\n 'http://delivery.vteximg.com.br/arquivos/ids/155413-55-55/classic.png?v=636759866429100000',\n detailUrl: '/classic-crust/p',\n assemblyOptions: [],\n __typename: 'vtex_storegraphql_2_51_0_ItemMetadataUnit',\n },\n {\n id: '8',\n name: 'Ham',\n skuName: 'Ham',\n productId: '6',\n refId: '2',\n ean: null,\n imageUrl:\n 'http://delivery.vteximg.com.br/arquivos/ids/155432-55-55/Topping_Jamon.jpg.png?v=636766052579200000',\n detailUrl: '/ham/p',\n assemblyOptions: [],\n __typename: 'vtex_storegraphql_2_51_0_ItemMetadataUnit',\n },\n {\n id: '9',\n name: 'Pepperoni',\n skuName: 'Pepperoni',\n productId: '7',\n refId: '3',\n ean: null,\n imageUrl:\n 'http://delivery.vteximg.com.br/arquivos/ids/155428-55-55/Topping_Pepperoni.jpg.png?v=636766047561270000',\n detailUrl: '/pepperoni/p',\n assemblyOptions: [],\n __typename: 'vtex_storegraphql_2_51_0_ItemMetadataUnit',\n },\n {\n id: '10',\n name: 'Champignon',\n skuName: 'Champignon',\n productId: '8',\n refId: '4',\n ean: null,\n imageUrl:\n 'http://delivery.vteximg.com.br/arquivos/ids/155436-55-55/Topping_Champinones.png?v=636766057405600000',\n detailUrl: '/champignon/p',\n assemblyOptions: [],\n __typename: 'vtex_storegraphql_2_51_0_ItemMetadataUnit',\n },\n {\n id: '11',\n name: 'Onion',\n skuName: 'Onion',\n productId: '9',\n refId: '5',\n ean: null,\n imageUrl:\n 'http://delivery.vteximg.com.br/arquivos/ids/155427-55-55/Topping_Cebolla.jpg.png?v=636766046799500000',\n detailUrl: '/onion/p',\n assemblyOptions: [],\n __typename: 'vtex_storegraphql_2_51_0_ItemMetadataUnit',\n },\n {\n id: '36',\n name: 'Black Olives',\n skuName: 'Black Olives',\n productId: '23',\n refId: '151113',\n ean: null,\n imageUrl:\n 'http://delivery.vteximg.com.br/arquivos/ids/155430-55-55/Topping_Aceitunas-Negras.jpg.png?v=636766049376970000',\n detailUrl: '/black-olives/p',\n assemblyOptions: [],\n __typename: 'vtex_storegraphql_2_51_0_ItemMetadataUnit',\n },\n {\n id: '37',\n name: 'Green Pepper',\n skuName: 'Green Pepper',\n productId: '24',\n refId: '123123',\n ean: null,\n imageUrl:\n 'http://delivery.vteximg.com.br/arquivos/ids/155431-55-55/PIMIENTO-VERDE.png?v=636766050771230000',\n detailUrl: '/green-pepper/p',\n assemblyOptions: [],\n __typename: 'vtex_storegraphql_2_51_0_ItemMetadataUnit',\n },\n {\n id: '38',\n name: 'Pineapple',\n skuName: 'Pineapple',\n productId: '25',\n refId: '121211',\n ean: null,\n imageUrl:\n 'http://delivery.vteximg.com.br/arquivos/ids/155435-55-55/Topping_Pina.jpg.png?v=636766056177370000',\n detailUrl: '/pineapple/p',\n assemblyOptions: [],\n __typename: 'vtex_storegraphql_2_51_0_ItemMetadataUnit',\n },\n ],\n __typename: 'vtex_storegraphql_2_51_0_ItemMetadata',\n },\n __typename: 'vtex_storegraphql_2_51_0_OrderForm',\n}\n\nexport const fullItems = {\n cacheId: '3335fe72057045398dd28bd2fa203b21',\n orderFormId: '3335fe72057045398dd28bd2fa203b21',\n value: 22.400000000000002,\n totalizers: [\n {\n id: 'Items',\n name: 'Items Total',\n value: 2240,\n __typename: 'vtex_storegraphql_2_51_0_Totalizer',\n },\n {\n id: 'Shipping',\n name: 'Shipping Total',\n value: 0,\n __typename: 'vtex_storegraphql_2_51_0_Totalizer',\n },\n ],\n items: [\n {\n id: '17',\n name: 'Pepperoni Small',\n imageUrl:\n 'http://delivery.vteximg.com.br/arquivos/ids/155439-55-55/pepperoni-feast.0e1c4c9e7b8900d08cc51ff285fd9ae3.1.jpg?v=636770441237070000',\n detailUrl: '/pizza-pepperoni/p',\n skuName: 'Small',\n quantity: 1,\n productRefId: 'PSMALL',\n additionalInfo: {\n brandName: 'PizzaHut',\n },\n productCategoryIds: '/1/',\n productCategories: { 1: 'Pizza' },\n sellingPrice: 14.9,\n listPrice: 14.9,\n parentItemIndex: null,\n parentAssemblyBinding: null,\n assemblyOptions: {\n added: [\n {\n item: {\n name: 'Classic Crust',\n sellingPrice: 0,\n quantity: 1,\n __typename: 'vtex_storegraphql_2_51_0_OrderFormItem',\n },\n normalizedQuantity: 1,\n choiceType: 'SINGLE',\n extraQuantity: 0,\n __typename: 'vtex_storegraphql_2_51_0_AddedOptionItem',\n },\n {\n item: {\n name: 'Pepperoni',\n sellingPrice: 0,\n quantity: 1,\n __typename: 'vtex_storegraphql_2_51_0_OrderFormItem',\n },\n normalizedQuantity: 1,\n choiceType: 'TOGGLE',\n extraQuantity: 0,\n __typename: 'vtex_storegraphql_2_51_0_AddedOptionItem',\n },\n {\n item: {\n name: 'Ham',\n sellingPrice: 1.5,\n quantity: 3,\n __typename: 'vtex_storegraphql_2_51_0_OrderFormItem',\n },\n normalizedQuantity: 3,\n choiceType: 'MULTIPLE',\n extraQuantity: 3,\n __typename: 'vtex_storegraphql_2_51_0_AddedOptionItem',\n },\n {\n item: {\n name: 'Pineapple',\n sellingPrice: 1,\n quantity: 3,\n __typename: 'vtex_storegraphql_2_51_0_OrderFormItem',\n },\n normalizedQuantity: 3,\n choiceType: 'MULTIPLE',\n extraQuantity: 3,\n __typename: 'vtex_storegraphql_2_51_0_AddedOptionItem',\n },\n ],\n removed: [\n {\n removedQuantity: 1,\n initialQuantity: 1,\n name: 'Onion',\n __typename: 'vtex_storegraphql_2_51_0_RemovedOptionItem',\n },\n ],\n parentPrice: 14.9,\n __typename: 'vtex_storegraphql_2_51_0_AssemblyOptionItem',\n },\n __typename: 'vtex_storegraphql_2_51_0_OrderFormItem',\n },\n {\n id: '14',\n name: 'Classic Crust',\n imageUrl:\n 'http://delivery.vteximg.com.br/arquivos/ids/155413-55-55/classic.png?v=636759866429100000',\n detailUrl: '/classic-crust/p',\n skuName: 'Classic Crust',\n quantity: 1,\n productRefId: 'CLASSICCRUST',\n additionalInfo: {\n brandName: 'PizzaHut',\n },\n productCategoryIds: '/1/',\n productCategories: { 1: 'Pizza' },\n sellingPrice: 0,\n listPrice: 0,\n parentItemIndex: null,\n parentAssemblyBinding: null,\n assemblyOptions: {\n added: [],\n removed: [],\n parentPrice: 0,\n __typename: 'vtex_storegraphql_2_51_0_AssemblyOptionItem',\n },\n __typename: 'vtex_storegraphql_2_51_0_OrderFormItem',\n },\n {\n id: '9',\n name: 'Pepperoni',\n imageUrl:\n 'http://delivery.vteximg.com.br/arquivos/ids/155428-55-55/Topping_Pepperoni.jpg.png?v=636766047561270000',\n detailUrl: '/pepperoni/p',\n skuName: 'Pepperoni',\n quantity: 1,\n productRefId: 'PEPPERONI',\n additionalInfo: {\n brandName: 'PizzaHut',\n },\n productCategoryIds: '/1/',\n productCategories: { 1: 'Pizza' },\n sellingPrice: 0,\n listPrice: 0,\n parentItemIndex: null,\n parentAssemblyBinding: null,\n assemblyOptions: {\n added: [],\n removed: [],\n parentPrice: 0,\n __typename: 'vtex_storegraphql_2_51_0_AssemblyOptionItem',\n },\n __typename: 'vtex_storegraphql_2_51_0_OrderFormItem',\n },\n {\n id: '8',\n name: 'Ham',\n imageUrl:\n 'http://delivery.vteximg.com.br/arquivos/ids/155432-55-55/Topping_Jamon.jpg.png?v=636766052579200000',\n detailUrl: '/ham/p',\n skuName: 'Ham',\n quantity: 3,\n productRefId: 'HAM',\n additionalInfo: {\n brandName: 'PizzaHut',\n },\n productCategoryIds: '/1/',\n productCategories: { 1: 'Pizza' },\n sellingPrice: 1.5,\n listPrice: 1.5,\n parentItemIndex: null,\n parentAssemblyBinding: null,\n assemblyOptions: {\n added: [],\n removed: [],\n parentPrice: 1.5,\n __typename: 'vtex_storegraphql_2_51_0_AssemblyOptionItem',\n },\n __typename: 'vtex_storegraphql_2_51_0_OrderFormItem',\n },\n {\n id: '38',\n name: 'Pineapple',\n imageUrl:\n 'http://delivery.vteximg.com.br/arquivos/ids/155435-55-55/Topping_Pina.jpg.png?v=636766056177370000',\n detailUrl: '/pineapple/p',\n skuName: 'Pineapple',\n quantity: 3,\n productRefId: 'PINEAPPLE',\n additionalInfo: {\n brandName: 'PizzaHut',\n },\n productCategoryIds: '/1/',\n productCategories: { 1: 'Pizza' },\n sellingPrice: 1,\n listPrice: 1,\n parentItemIndex: null,\n parentAssemblyBinding: null,\n assemblyOptions: {\n added: [],\n removed: [],\n parentPrice: 1,\n __typename: 'vtex_storegraphql_2_51_0_AssemblyOptionItem',\n },\n __typename: 'vtex_storegraphql_2_51_0_OrderFormItem',\n },\n ],\n shippingData: {\n address: {\n id: null,\n neighborhood: 'Botafogo',\n complement: '',\n number: '300',\n street: 'Praia de Botafogo',\n postalCode: '22250-040',\n city: 'Rio de Janeiro',\n reference: null,\n addressName: null,\n addressType: 'residential',\n __typename: 'vtex_storegraphql_2_51_0_Address',\n },\n availableAddresses: [\n {\n id: null,\n neighborhood: 'Botafogo',\n complement: '',\n number: '300',\n street: 'Praia de Botafogo',\n postalCode: '22250-040',\n city: 'Rio de Janeiro',\n reference: null,\n addressName: null,\n addressType: 'residential',\n __typename: 'vtex_storegraphql_2_51_0_Address',\n },\n ],\n __typename: 'vtex_storegraphql_2_51_0_OrderFormShippingData',\n },\n clientProfileData: null,\n storePreferencesData: {\n countryCode: 'BRA',\n currencyCode: 'BRL',\n timeZone: 'E. South America Standard Time',\n __typename: 'vtex_storegraphql_2_51_0_StorePreferencesData',\n },\n itemMetadata: {\n items: [\n {\n id: '17',\n name: 'Pepperoni Small',\n skuName: 'Small',\n productId: '13',\n refId: '1111',\n ean: null,\n imageUrl:\n 'http://delivery.vteximg.com.br/arquivos/ids/155439-55-55/pepperoni-feast.0e1c4c9e7b8900d08cc51ff285fd9ae3.1.jpg?v=636770441237070000',\n detailUrl: '/pizza-pepperoni/p',\n assemblyOptions: [\n {\n id: 'Pepperoni - Small_Crust',\n name: 'Pepperoni - Small',\n required: true,\n composition: {\n minQuantity: 1,\n maxQuantity: 1,\n items: [\n {\n maxQuantity: 1,\n initialQuantity: 1,\n id: '14',\n __typename: 'vtex_storegraphql_2_51_0_CompositionItem',\n },\n ],\n __typename: 'vtex_storegraphql_2_51_0_CompositionType',\n },\n __typename: 'vtex_storegraphql_2_51_0_AssemblyOption',\n },\n {\n id: 'Pepperoni - Small_Toppings',\n name: 'Pepperoni - Small',\n required: true,\n composition: {\n minQuantity: 0,\n maxQuantity: 10,\n items: [\n {\n maxQuantity: 3,\n initialQuantity: 0,\n id: '8',\n __typename: 'vtex_storegraphql_2_51_0_CompositionItem',\n },\n {\n maxQuantity: 3,\n initialQuantity: 0,\n id: '9',\n __typename: 'vtex_storegraphql_2_51_0_CompositionItem',\n },\n {\n maxQuantity: 3,\n initialQuantity: 0,\n id: '10',\n __typename: 'vtex_storegraphql_2_51_0_CompositionItem',\n },\n {\n maxQuantity: 3,\n initialQuantity: 0,\n id: '11',\n __typename: 'vtex_storegraphql_2_51_0_CompositionItem',\n },\n {\n maxQuantity: 3,\n initialQuantity: 0,\n id: '36',\n __typename: 'vtex_storegraphql_2_51_0_CompositionItem',\n },\n {\n maxQuantity: 3,\n initialQuantity: 0,\n id: '37',\n __typename: 'vtex_storegraphql_2_51_0_CompositionItem',\n },\n {\n maxQuantity: 3,\n initialQuantity: 0,\n id: '38',\n __typename: 'vtex_storegraphql_2_51_0_CompositionItem',\n },\n ],\n __typename: 'vtex_storegraphql_2_51_0_CompositionType',\n },\n __typename: 'vtex_storegraphql_2_51_0_AssemblyOption',\n },\n {\n id: 'Pepperoni - Small_Basic Toppings',\n name: 'Pepperoni - Small',\n required: true,\n composition: {\n minQuantity: 1,\n maxQuantity: 2,\n items: [\n {\n maxQuantity: 1,\n initialQuantity: 1,\n id: '9',\n __typename: 'vtex_storegraphql_2_51_0_CompositionItem',\n },\n {\n maxQuantity: 1,\n initialQuantity: 1,\n id: '11',\n __typename: 'vtex_storegraphql_2_51_0_CompositionItem',\n },\n ],\n __typename: 'vtex_storegraphql_2_51_0_CompositionType',\n },\n __typename: 'vtex_storegraphql_2_51_0_AssemblyOption',\n },\n ],\n __typename: 'vtex_storegraphql_2_51_0_ItemMetadataUnit',\n },\n {\n id: '14',\n name: 'Classic Crust',\n skuName: 'Classic Crust',\n productId: '12',\n refId: '14',\n ean: null,\n imageUrl:\n 'http://delivery.vteximg.com.br/arquivos/ids/155413-55-55/classic.png?v=636759866429100000',\n detailUrl: '/classic-crust/p',\n assemblyOptions: [],\n __typename: 'vtex_storegraphql_2_51_0_ItemMetadataUnit',\n },\n {\n id: '8',\n name: 'Ham',\n skuName: 'Ham',\n productId: '6',\n refId: '2',\n ean: null,\n imageUrl:\n 'http://delivery.vteximg.com.br/arquivos/ids/155432-55-55/Topping_Jamon.jpg.png?v=636766052579200000',\n detailUrl: '/ham/p',\n assemblyOptions: [],\n __typename: 'vtex_storegraphql_2_51_0_ItemMetadataUnit',\n },\n {\n id: '9',\n name: 'Pepperoni',\n skuName: 'Pepperoni',\n productId: '7',\n refId: '3',\n ean: null,\n imageUrl:\n 'http://delivery.vteximg.com.br/arquivos/ids/155428-55-55/Topping_Pepperoni.jpg.png?v=636766047561270000',\n detailUrl: '/pepperoni/p',\n assemblyOptions: [],\n __typename: 'vtex_storegraphql_2_51_0_ItemMetadataUnit',\n },\n {\n id: '10',\n name: 'Champignon',\n skuName: 'Champignon',\n productId: '8',\n refId: '4',\n ean: null,\n imageUrl:\n 'http://delivery.vteximg.com.br/arquivos/ids/155436-55-55/Topping_Champinones.png?v=636766057405600000',\n detailUrl: '/champignon/p',\n assemblyOptions: [],\n __typename: 'vtex_storegraphql_2_51_0_ItemMetadataUnit',\n },\n {\n id: '11',\n name: 'Onion',\n skuName: 'Onion',\n productId: '9',\n refId: '5',\n ean: null,\n imageUrl:\n 'http://delivery.vteximg.com.br/arquivos/ids/155427-55-55/Topping_Cebolla.jpg.png?v=636766046799500000',\n detailUrl: '/onion/p',\n assemblyOptions: [],\n __typename: 'vtex_storegraphql_2_51_0_ItemMetadataUnit',\n },\n {\n id: '36',\n name: 'Black Olives',\n skuName: 'Black Olives',\n productId: '23',\n refId: '151113',\n ean: null,\n imageUrl:\n 'http://delivery.vteximg.com.br/arquivos/ids/155430-55-55/Topping_Aceitunas-Negras.jpg.png?v=636766049376970000',\n detailUrl: '/black-olives/p',\n assemblyOptions: [],\n __typename: 'vtex_storegraphql_2_51_0_ItemMetadataUnit',\n },\n {\n id: '37',\n name: 'Green Pepper',\n skuName: 'Green Pepper',\n productId: '24',\n refId: '123123',\n ean: null,\n imageUrl:\n 'http://delivery.vteximg.com.br/arquivos/ids/155431-55-55/PIMIENTO-VERDE.png?v=636766050771230000',\n detailUrl: '/green-pepper/p',\n assemblyOptions: [],\n __typename: 'vtex_storegraphql_2_51_0_ItemMetadataUnit',\n },\n {\n id: '38',\n name: 'Pineapple',\n skuName: 'Pineapple',\n productId: '25',\n refId: '121211',\n ean: null,\n imageUrl:\n 'http://delivery.vteximg.com.br/arquivos/ids/155435-55-55/Topping_Pina.jpg.png?v=636766056177370000',\n detailUrl: '/pineapple/p',\n assemblyOptions: [],\n __typename: 'vtex_storegraphql_2_51_0_ItemMetadataUnit',\n },\n ],\n __typename: 'vtex_storegraphql_2_51_0_ItemMetadata',\n },\n __typename: 'vtex_storegraphql_2_51_0_OrderForm',\n}\n\n```"
}
] |
code_minicart_fe300cec
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of minicart/react/legacy/utils/itemsHelper.js from the minicart VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nconst isParentItem = ({ parentItemIndex, parentAssemblyBinding }) =>\n parentItemIndex == null && parentAssemblyBinding == null\n\nexport const shouldShowItem = item => !!item.quantity && isParentItem(item)\n\n```"
}
] |
code_minicart_037a43ca
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of minicart/react/legacy/utils/propTypes.js from the minicart VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport PropTypes from 'prop-types'\n\nexport const MiniCartPropTypes = {\n /* Set the minicart type */\n type: PropTypes.oneOf(['popup', 'sidebar']),\n /* Set the content visibility */\n hideContent: PropTypes.bool,\n /* Label that will appear when the minicart is empty */\n labelMiniCartEmpty: PropTypes.string,\n /* Finish shopping button label */\n labelButtonFinishShopping: PropTypes.string,\n linkButtonFinishShopping: PropTypes.string,\n /* Icon's classnames */\n iconClasses: PropTypes.string,\n /* Icon's size */\n iconSize: PropTypes.number,\n /* Icon's label */\n iconLabel: PropTypes.object,\n /* Label's classnames */\n labelClasses: PropTypes.string,\n /* Set the discount visibility */\n showDiscount: PropTypes.bool,\n /* Set the shipping fee visibility */\n showShippingCost: PropTypes.bool,\n}\n\n```"
}
] |
code_minicart_5a6d3469
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of minicart/react/legacy/utils/urlHelpers.js from the minicart VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nexport const DEFAULT_WIDTH = 'auto'\nexport const DEFAULT_HEIGHT = 'auto'\nexport const MAX_WIDTH = 3000\nexport const MAX_HEIGHT = 4000\n\n/**\n * Having the url below as base for the LEGACY file manager,\n * https://storecomponents.vteximg.com.br/arquivos/ids/155472/Frame-3.jpg?v=636793763985400000\n * the following regex will match https://storecomponents.vteximg.com.br/arquivos/ids/155472\n *\n * Also matches urls with defined sizes like:\n * https://storecomponents.vteximg.com.br/arquivos/ids/155473-160-auto\n * @type {RegExp}\n *\n * On the new vtex.file-manager isn't necessary replace the URL, just add the param on the querystring, like:\n * \"?width=WIDTH&height=HEIGHT&aspect=true\"\n *\n */\nconst baseUrlRegex = new RegExp(/.+ids\\/(\\d+)/)\n\nconst httpRegex = new RegExp(/http:\\/\\//)\n\nexport function toHttps(url) {\n if (!url) return ''\n return url.replace(httpRegex, 'https://')\n}\n\nexport function cleanImageUrl(imageUrl) {\n const result = baseUrlRegex.exec(imageUrl)\n if (result.length > 0) return result[0]\n}\n\nfunction replaceLegacyFileManagerUrl(imageUrl, width, height) {\n const legacyUrlPattern = '/arquivos/ids/'\n const isLegacyUrl = imageUrl.includes(legacyUrlPattern)\n if (!isLegacyUrl) return imageUrl\n return `${cleanImageUrl(imageUrl)}-${width}-${height}`\n}\n\nexport function changeImageUrlSize(\n imageUrl,\n width = DEFAULT_WIDTH,\n height = DEFAULT_HEIGHT\n) {\n if (!imageUrl) return\n typeof width === 'number' && (width = Math.min(width, MAX_WIDTH))\n typeof height === 'number' && (height = Math.min(height, MAX_HEIGHT))\n\n const normalizedImageUrl = replaceLegacyFileManagerUrl(\n imageUrl,\n width,\n height\n )\n const queryStringSeparator = normalizedImageUrl.includes('?') ? '&' : '?'\n\n return `${normalizedImageUrl}${queryStringSeparator}width=${width}&height=${height}&aspect=true`\n}\n\n```"
}
] |
code_minicart_bc6f90c9
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of minicart/react/legacy/localState/index.jsx from the minicart VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```jsx\n// eslint-disable-next-line no-restricted-imports\nimport { head, mergeDeepRight, values } from 'ramda'\nimport updateOrderFormShipping from 'vtex.store-resources/MutationUpdateOrderFormShipping'\nimport updateOrderFormCheckin from 'vtex.store-resources/MutationUpdateOrderFormCheckin'\n\nimport fullMinicartQuery from './graphql/fullMinicartQuery.gql'\n\nexport const ITEMS_STATUS = {\n NONE: 'NONE',\n MODIFIED: 'MODIFIED',\n LOCAL_ITEM: 'LOCAL_ITEM',\n}\n\nexport default function (client) {\n const replayOrderFormServerMutation = mutation => async (\n _,\n variables,\n { cache }\n ) => {\n const response = await client.mutate({\n variables,\n mutation,\n })\n\n const updatedOrderForm = head(values(response.data))\n\n const data = cache.readQuery({ query: fullMinicartQuery })\n\n const orderForm = JSON.stringify(\n mergeDeepRight(JSON.parse(data.minicart.orderForm), updatedOrderForm)\n )\n cache.writeQuery({\n query: fullMinicartQuery,\n data: {\n ...data,\n minicart: {\n __typename: 'Minicart',\n ...data.minicart,\n orderForm,\n },\n },\n })\n return orderForm\n }\n\n const resolvers = {\n Mutation: {\n addToCart: (_, { items }, { cache }) => {\n const data = cache.readQuery({ query: fullMinicartQuery })\n\n const cartItems = JSON.parse(data.minicart.items)\n // We will only add items that are not already in cart or might have attachment.\n const newItems = items.filter(\n item =>\n !cartItems.find(\n cartItem =>\n cartItem.id === item.id &&\n cartItem.seller === item.seller &&\n !cartItem.canHaveAttachment\n )\n )\n\n const writeItems = cartItems.concat(\n newItems.map(item => ({\n ...item,\n localStatus: navigator.onLine\n ? ITEMS_STATUS.MODIFIED\n : ITEMS_STATUS.LOCAL_ITEM,\n }))\n )\n\n cache.writeQuery({\n query: fullMinicartQuery,\n data: {\n ...data,\n minicart: {\n __typename: 'Minicart',\n ...data.minicart,\n items: JSON.stringify(writeItems),\n },\n },\n })\n\n return writeItems\n },\n updateItems: (_, { items: newItems }, { cache }) => {\n const data = cache.readQuery({ query: fullMinicartQuery })\n\n const cartItems = JSON.parse(data.minicart.items)\n\n // Items provided to this function MUST have a valid index property\n const cleanNewItems = newItems.filter(({ index }) => index != null)\n const items = [...cartItems]\n\n for (const newItem of cleanNewItems) {\n const { index } = newItem\n const prevItem = cartItems[index]\n items[index] = mergeDeepRight(prevItem, {\n ...newItem,\n localStatus: ITEMS_STATUS.MODIFIED,\n })\n }\n\n const newCartItems = items.filter(Boolean)\n\n cache.writeQuery({\n query: fullMinicartQuery,\n data: {\n ...data,\n minicart: {\n __typename: 'Minicart',\n ...data.minicart,\n items: JSON.stringify(newCartItems),\n },\n },\n })\n return newCartItems\n },\n updateLocalItems: (_, { items }, { cache }) => {\n const data = cache.readQuery({ query: fullMinicartQuery })\n\n const itemsToRemove = items.filter(({ quantity }) => quantity === 0)\n const itemsToUpdate = items.filter(({ quantity }) => quantity > 0)\n\n const updatedItems = JSON.parse(data.minicart.items)\n .map((item, index) => {\n const updateItem = itemsToUpdate.find(\n currentItem => currentItem.index === index\n )\n\n if (updateItem) {\n return {\n ...item,\n ...updateItem,\n }\n }\n\n return item\n })\n .filter(\n (_item, index) =>\n itemsToRemove.findIndex(\n removedItem => removedItem.index === index\n ) === -1\n )\n\n cache.writeQuery({\n query: fullMinicartQuery,\n data: {\n ...data,\n minicart: {\n __typename: 'Minicart',\n ...data.minicart,\n items: JSON.stringify(updatedItems),\n },\n },\n })\n\n return updatedItems\n },\n updateOrderForm: (\n _,\n { orderForm, forceUpdateItems = false },\n { cache }\n ) => {\n const data = cache.readQuery({ query: fullMinicartQuery })\n\n const prevItems = JSON.parse(data.minicart.items)\n const orderFormItems = (orderForm.items || []).map(item => ({\n ...item,\n localStatus: ITEMS_STATUS.NONE,\n }))\n\n const currentItems = forceUpdateItems\n ? prevItems.map(item => ({\n ...item,\n localStatus:\n item.localStatus === ITEMS_STATUS.MODIFIED\n ? ITEMS_STATUS.NONE\n : item.localStatus,\n }))\n : prevItems\n\n const updatedItems = [\n ...orderFormItems,\n ...currentItems.filter(\n ({ localStatus }) => localStatus !== ITEMS_STATUS.NONE\n ),\n ]\n\n cache.writeQuery({\n query: fullMinicartQuery,\n data: {\n ...data,\n minicart: {\n __typename: 'Minicart',\n ...data.minicart,\n orderForm: JSON.stringify(orderForm),\n items: JSON.stringify(updatedItems),\n },\n },\n })\n\n return orderForm\n },\n updateLocalItemStatus: (_, __, { cache }) => {\n const data = cache.readQuery({ query: fullMinicartQuery })\n const prevItems = JSON.parse(data.minicart.items)\n\n const updatedItems = prevItems.map(item => ({\n ...item,\n localStatus:\n item.localStatus === ITEMS_STATUS.LOCAL_ITEM\n ? ITEMS_STATUS.MODIFIED\n : item.localStatus,\n }))\n\n cache.writeQuery({\n query: fullMinicartQuery,\n data: {\n ...data,\n minicart: {\n __typename: 'Minicart',\n ...data.minicart,\n items: JSON.stringify(updatedItems),\n },\n },\n })\n\n return true\n },\n updateOrderFormShipping: replayOrderFormServerMutation(\n updateOrderFormShipping\n ),\n updateOrderFormCheckin: replayOrderFormServerMutation(\n updateOrderFormCheckin\n ),\n setMinicartOpen: (_, { isOpen }, { cache }) => {\n const data = cache.readQuery({ query: fullMinicartQuery })\n cache.writeQuery({\n query: fullMinicartQuery,\n data: {\n ...data,\n minicart: {\n __typename: 'Minicart',\n ...data.minicart,\n isOpen,\n },\n },\n })\n return true\n },\n },\n }\n\n const initialState = {\n minicart: {\n __typename: 'Minicart',\n items: '[]',\n orderForm: null,\n isOpen: false,\n },\n }\n\n return { resolvers, initialState }\n}\n\n```"
}
] |
code_minicart_922650e9
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of minicart/react/legacy/components/Popup.jsx from the minicart VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```jsx\n/* eslint-disable jsx-a11y/click-events-have-key-events */\n/* eslint-disable jsx-a11y/no-static-element-interactions */\nimport React from 'react'\nimport PropTypes from 'prop-types'\nimport { Overlay } from 'vtex.react-portal'\n\nimport minicart from '../minicart.css'\n\nconst boxPositionStyle = {\n right: -40,\n}\n\n/**\n * Pop-up component.\n */\nconst Popup = ({ children, onOutsideClick }) => {\n return (\n <Overlay>\n <div\n className=\"fixed top-0 left-0 w-100 h-100\"\n onClick={onOutsideClick}\n />\n <div\n className={`${minicart.box} dn db-ns absolute z-max flex flex-colunm`}\n style={boxPositionStyle}\n >\n <div className={`${minicart.popupContentContainer} shadow-3`}>\n <div\n className={`${minicart.arrowUp} absolute top-0 shadow-3 bg-base h1 w1 pa4 rotate-45`}\n />\n <div\n className={`${minicart.popupChildrenContainer} mt3 bg-base relative flex flex-column`}\n >\n {children}\n </div>\n </div>\n </div>\n </Overlay>\n )\n}\n\nPopup.propTypes = {\n /* The pop-up's content */\n children: PropTypes.object,\n /* Offset width to set the arrow position */\n buttonOffsetWidth: PropTypes.number,\n /* Function to be called when click occurs outside the popup */\n onOutsideClick: PropTypes.func,\n}\n\nexport default Popup\n\n```"
}
] |
code_minicart_4b1ee791
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of minicart/react/legacy/components/MiniCartFooter.jsx from the minicart VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```jsx\nimport React, { Fragment, memo } from 'react'\nimport classNames from 'classnames'\nimport ProductPrice from 'vtex.store-components/ProductPrice'\nimport { Button, Spinner } from 'vtex.styleguide'\nimport { FormattedMessage } from 'react-intl'\nimport PropTypes from 'prop-types'\nimport { useRuntime, ExtensionPoint } from 'vtex.render-runtime'\n\nimport { MiniCartPropTypes } from '../utils/propTypes'\nimport minicart from '../minicart.css'\n\nconst MiniCartFooter = ({\n shippingCost,\n isSizeLarge,\n isUpdating,\n totalValue,\n buttonLabel,\n buttonLink,\n showDiscount,\n discount,\n labelDiscount,\n showShippingCost,\n}) => {\n const { rootPath = '' } = useRuntime()\n const handleClickButton = () => window.location.assign(rootPath + buttonLink)\n\n const priceAndDiscountClasses = classNames(\n `${minicart.contentDiscount} w-100 flex justify-end items-center mb3`,\n {\n pv3: isSizeLarge,\n }\n )\n\n const checkoutButtonClasses = classNames({\n 'bb bw4 bw2-m b--transparent': isSizeLarge,\n })\n\n const shouldShowShippingCost = showShippingCost && shippingCost > 0\n\n const footerClasses = classNames(\n `${minicart.contentFooter} w-100 bg-base pa4 pv5 flex flex-column items-end`,\n {\n 'bt b--muted-3': shouldShowShippingCost || isSizeLarge,\n }\n )\n\n return (\n <Fragment>\n {shouldShowShippingCost && (\n <div\n className={`${minicart.footerShippingPriceContainer} flex items-center justify-between ma5`}\n >\n <div\n className={`${minicart.footerShippingPriceLabelContainer} t-body c-muted-1`}\n >\n <FormattedMessage id=\"store/minicart.shipping-cost\" />\n </div>\n <ProductPrice\n sellingPriceClass=\"t-heading-5-ns b c-on-base ph2 dib\"\n sellingPrice={shippingCost}\n showLabels={false}\n showListPrice={false}\n />\n </div>\n )}\n <div\n className={minicart.footerSpacer}\n style={{\n marginTop: 'auto',\n }}\n />\n <ExtensionPoint id=\"sandbox\" />\n <div className={footerClasses}>\n {!isUpdating && showDiscount && discount > 0 && (\n <div className={priceAndDiscountClasses}>\n <span\n className={`${minicart.labelDiscountText} ttl c-action-primary`}\n >\n {labelDiscount}\n </span>\n <ProductPrice\n sellingPriceClass=\"c-action-primary t-body ph2 dib\"\n sellingPrice={discount}\n listPrice={discount}\n showLabels={false}\n showListPrice={false}\n />\n </div>\n )}\n <div className={`${minicart.contentPrice} mb3`}>\n {isUpdating ? (\n <Spinner size={18} />\n ) : (\n <ProductPrice\n sellingPriceClass=\"t-heading-5-ns c-on-base b ph2 dib\"\n sellingPrice={totalValue}\n listPrice={totalValue}\n showLabels={false}\n showListPrice={false}\n />\n )}\n </div>\n <div className={checkoutButtonClasses}>\n <Button variation=\"primary\" size=\"small\" onClick={handleClickButton}>\n {buttonLabel}\n </Button>\n </div>\n </div>\n </Fragment>\n )\n}\n\nMiniCartFooter.propTypes = {\n shippingCost: PropTypes.number,\n isSizeLarge: PropTypes.bool,\n isUpdating: PropTypes.bool,\n totalValue: PropTypes.number.isRequired,\n buttonLink: PropTypes.string,\n buttonLabel: PropTypes.string.isRequired,\n showDiscount: MiniCartPropTypes.showDiscount,\n discount: PropTypes.number,\n labelDiscount: PropTypes.string,\n showShippingCost: MiniCartPropTypes.showShippingCost,\n}\n\nexport default memo(MiniCartFooter)\n\n```"
}
] |
code_minicart_b3fa3287
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of minicart/react/legacy/components/MiniCartContent.jsx from the minicart VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```jsx\n/* eslint-disable react/no-access-state-in-setstate */\nimport PropTypes from 'prop-types'\n// eslint-disable-next-line no-restricted-imports\nimport { reduceBy, values, clone, find, propEq, compose } from 'ramda'\nimport React, { Component, Fragment } from 'react'\nimport { graphql } from 'react-apollo'\nimport { injectIntl } from 'react-intl'\nimport classNames from 'classnames'\nimport { withPixel } from 'vtex.pixel-manager/PixelContext'\nimport { ExtensionPoint } from 'vtex.render-runtime'\nimport { ButtonWithIcon, Spinner } from 'vtex.styleguide'\nimport { IconDelete } from 'vtex.store-icons'\n\nimport { MiniCartPropTypes } from '../utils/propTypes'\nimport { toHttps, changeImageUrlSize } from '../utils/urlHelpers'\nimport { mapCartItemToPixel } from '../../modules/pixelHelper'\nimport { ITEMS_STATUS } from '../localState/index'\nimport updateItemsMutation from '../localState/graphql/updateItemsMutation.gql'\nimport updateLocalItemsMutation from '../localState/graphql/updateLocalItemsMutation.gql'\nimport styles from '../minicart.css'\nimport MiniCartFooter from './MiniCartFooter'\n\n/**\n * Minicart content component\n */\n\nclass MiniCartContent extends Component {\n static propTypes = {\n /* Set the mini cart content size */\n isSizeLarge: PropTypes.bool,\n /** Define a function that is executed when the item is clicked */\n onClickAction: PropTypes.func,\n /* Update Items mutation */\n updateItems: PropTypes.func.isRequired,\n updateLocalItems: PropTypes.func.isRequired,\n /* Determines if the orderform is updating */\n updatingOrderForm: PropTypes.bool,\n /* Reused props */\n orderForm: PropTypes.object,\n loading: PropTypes.bool,\n labelMiniCartEmpty: MiniCartPropTypes.labelMiniCartEmpty,\n linkButton: MiniCartPropTypes.linkButtonFinishShopping,\n labelButton: MiniCartPropTypes.labelButtonFinishShopping,\n showDiscount: MiniCartPropTypes.showDiscount,\n showShippingCost: MiniCartPropTypes.showShippingCost,\n itemsToShow: PropTypes.arrayOf(PropTypes.object),\n /* Pixel push */\n push: PropTypes.func.isRequired,\n /** Props to passed to icons from store-icons */\n iconsProps: PropTypes.shape({\n viewBox: PropTypes.string,\n size: PropTypes.number,\n }),\n intl: PropTypes.any,\n }\n\n state = { isUpdating: [] }\n\n sumItemsPrice = items =>\n items.reduce(\n (sum, { sellingPrice, quantity }) => sum + sellingPrice * quantity,\n 0\n )\n\n getGroupedItems = () =>\n values(\n reduceBy(\n (acc, item) =>\n acc ? { ...acc, quantity: acc.quantity + item.quantity } : item,\n undefined,\n item => item.id,\n this.props.orderForm.items\n )\n )\n\n getShippingCost = orderForm => {\n const totalizer = find(propEq('id', 'Shipping'))(orderForm.totalizers || [])\n return (totalizer && totalizer.value / 100) || 0\n }\n\n calculateDiscount = items =>\n items.reduce(\n (sum, { listPrice, sellingPrice, quantity }) =>\n sum + (listPrice - sellingPrice) * quantity,\n 0\n )\n\n handleItemRemoval = async (item, index) => {\n const { updateItems, updateLocalItems } = this.props\n const updatedItems = [\n {\n id: item.id,\n index: item.cartIndex != null ? item.cartIndex : index,\n quantity: 0,\n },\n ]\n\n try {\n if (item.cartIndex != null) {\n await updateItems(updatedItems)\n } else {\n await updateLocalItems(updatedItems)\n }\n\n this.props.push({\n event: 'removeFromCart',\n items: [mapCartItemToPixel(item)],\n })\n } catch (error) {\n // TODO: Toast error message\n console.error(error)\n }\n }\n\n updateItemLoad = (itemId, newStatus) => {\n const isUpdating = clone(this.state.isUpdating)\n isUpdating[itemId] = newStatus\n this.setState({ isUpdating })\n }\n\n calculateTotalValue = orderForm =>\n this.getShippingCost(orderForm)\n ? orderForm.value\n : this.sumItemsPrice(orderForm.items)\n\n getItemCategory = item => {\n if (!item.productCategoryIds || !item.productCategories) {\n return ''\n }\n\n return item.productCategoryIds\n .split('/')\n .reduce((acc, id) => acc.concat(item.productCategories[id]), [])\n .join('/')\n .slice(1, -1)\n }\n\n createProductShapeFromItem = item => {\n return {\n productName: item.name,\n brand: item.additionalInfo ? item.additionalInfo.brandName : undefined,\n category: this.getItemCategory(item),\n productRefId: item.productRefId,\n linkText: item.detailUrl.replace(/^\\//, '').replace(/\\/p$/, ''),\n sku: {\n seller: {\n commertialOffer: {\n Price: item.sellingPriceWithAssemblies * item.quantity,\n ListPrice: item.listPrice,\n },\n sellerId: item.seller,\n },\n name: item.skuName,\n itemId: item.id,\n image: {\n imageUrl: changeImageUrlSize(toHttps(item ? item.imageUrl : ''), 240),\n },\n },\n assemblyOptions: item.assemblyOptions,\n quantity: item.quantity,\n cartIndex: item.cartIndex,\n }\n }\n\n get isUpdating() {\n const { isUpdating } = this.state\n const {\n orderForm: { items },\n updatingOrderForm,\n } = this.props\n return (\n updatingOrderForm ||\n items.some(item => item.quantity === 0) ||\n isUpdating.some(status => status)\n )\n }\n\n renderWithoutItems = label => (\n <div\n className={`${styles.item} pa9 flex items-center justify-center relative bg-base`}\n >\n <span className=\"t-body\">{label}</span>\n </div>\n )\n\n renderMiniCartWithItems = (\n orderForm,\n itemsToShow,\n label,\n labelDiscount,\n showDiscount,\n onClickAction,\n isUpdating,\n isSizeLarge,\n showShippingCost,\n iconsProps\n ) => {\n const MIN_ITEMS_TO_SCROLL = 2\n\n const classes = classNames(`${styles.content} overflow-x-hidden pa1`, {\n [`${styles.contentSmall} bg-base`]: !isSizeLarge,\n [`${styles.contentLarge}`]: isSizeLarge,\n 'overflow-y-scroll':\n itemsToShow.length > MIN_ITEMS_TO_SCROLL && !isSizeLarge,\n })\n\n return (\n <Fragment>\n <div className={classes}>\n {itemsToShow.map((item, index) => (\n <Fragment key={item.id}>\n <section className={`${styles.itemContainer} relative flex`}>\n <div\n className={`${styles.itemDeleteIcon} fr absolute top-0 right-0`}\n >\n {isUpdating[item.id] ? (\n <div className={`${styles.itemDeleteIconLoader} ma4`}>\n <Spinner size={18} />\n </div>\n ) : (\n <ButtonWithIcon\n icon={\n <IconDelete\n size={15}\n activeClassName=\"c-muted-2\"\n {...iconsProps}\n />\n }\n variation=\"tertiary\"\n onClick={() => this.handleItemRemoval(item, index)}\n />\n )}\n </div>\n <ExtensionPoint\n id=\"product-summary\"\n showBorders\n product={this.createProductShapeFromItem(item)}\n name={item.name}\n displayMode=\"inlinePrice\"\n showListPrice={false}\n showBadge={false}\n showInstallments={false}\n showLabels={false}\n actionOnClick={onClickAction}\n muted={item.localStatus !== ITEMS_STATUS.NONE}\n index={index}\n />\n </section>\n </Fragment>\n ))}\n </div>\n <MiniCartFooter\n shippingCost={this.getShippingCost(orderForm)}\n isUpdating={this.isUpdating}\n totalValue={this.calculateTotalValue(orderForm)}\n discount={this.calculateDiscount(orderForm.items)}\n buttonLink={this.props.linkButton}\n buttonLabel={label}\n isSizeLarge={isSizeLarge}\n labelDiscount={labelDiscount}\n showDiscount={showDiscount}\n showShippingCost={showShippingCost}\n />\n </Fragment>\n )\n }\n\n renderLoading = () => (\n <div\n className={`${styles.item} pa4 flex items-center justify-center relative bg-base`}\n >\n <Spinner />\n </div>\n )\n\n render() {\n const {\n itemsToShow,\n labelMiniCartEmpty,\n labelButton,\n intl,\n showDiscount,\n onClickAction,\n isSizeLarge,\n showShippingCost,\n orderForm,\n loading,\n iconsProps,\n } = this.props\n const { isUpdating } = this.state\n\n if (loading) {\n return this.renderLoading()\n }\n\n if (!orderForm || !itemsToShow.length) {\n const label =\n labelMiniCartEmpty || intl.formatMessage({ id: 'store/minicart-empty' })\n return this.renderWithoutItems(label)\n }\n\n const label =\n labelButton ||\n intl.formatMessage({ id: 'store/finish-shopping-button-label' })\n const labelDiscount = intl.formatMessage({\n id: 'store/minicart-content-footer-discount',\n })\n\n return this.renderMiniCartWithItems(\n orderForm,\n itemsToShow,\n label,\n labelDiscount,\n showDiscount,\n onClickAction,\n isUpdating,\n isSizeLarge,\n showShippingCost,\n iconsProps\n )\n }\n}\n\nconst withUpdateItemsMutation = graphql(updateItemsMutation, {\n name: 'updateItems',\n props: ({ updateItems }) => ({\n updateItems: items => updateItems({ variables: { items } }),\n }),\n})\n\nconst withUpdateLocalItemsMutation = graphql(updateLocalItemsMutation, {\n name: 'updateLocalItems',\n props: ({ updateLocalItems }) => ({\n updateLocalItems: items => updateLocalItems({ variables: { items } }),\n }),\n})\n\nexport default compose(\n injectIntl,\n withUpdateItemsMutation,\n withUpdateLocalItemsMutation,\n withPixel\n)(MiniCartContent)\n\n```"
}
] |
code_minicart_70e1c84d
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of minicart/react/legacy/components/Sidebar.jsx from the minicart VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```jsx\n/* eslint-disable jsx-a11y/click-events-have-key-events */\n/* eslint-disable jsx-a11y/no-static-element-interactions */\nimport React, { Component } from 'react'\nimport PropTypes from 'prop-types'\nimport { IconCaret, IconCart } from 'vtex.store-icons'\nimport { injectIntl } from 'react-intl'\nimport OutsideClickHandler from 'react-outside-click-handler'\nimport Animation from 'vtex.store-components/Animation'\nimport classNames from 'classnames'\nimport { Overlay } from 'vtex.react-portal'\n\nimport minicart from '../minicart.css'\n\nconst OPEN_SIDEBAR_CLASS = minicart.sidebarOpen\n\n/* SideBar component */\nclass Sidebar extends Component {\n updateComponent() {\n if (this.props.isOpen) {\n document.body.classList.add(OPEN_SIDEBAR_CLASS)\n } else {\n document.body.classList.remove(OPEN_SIDEBAR_CLASS)\n }\n }\n\n componentDidMount() {\n this.updateComponent()\n }\n\n componentDidUpdate() {\n this.updateComponent()\n }\n\n componentWillUnmount() {\n document.body.classList.remove(OPEN_SIDEBAR_CLASS)\n }\n\n render() {\n const {\n isOpen,\n onOutsideClick,\n intl,\n iconSize,\n quantity,\n iconsProps,\n } = this.props\n\n if (typeof document === 'undefined') {\n return null\n }\n\n const scrimClasses = classNames(\n `${minicart.sidebarScrim} fixed dim bg-base--inverted top-0 left-0 z-9999 w-100 vh-100 o-40`,\n {\n dn: !isOpen,\n }\n )\n\n return (\n <Overlay fullWidth>\n <OutsideClickHandler onOutsideClick={onOutsideClick}>\n <div\n style={{ willChange: 'opacity' }}\n className={scrimClasses}\n onClick={onOutsideClick}\n />\n\n <Animation\n className={`${minicart.sidebar} w-80 w-auto-ns h-100 fixed top-0 right-0 z-9999 bg-base shadow-2 flex flex-column`}\n isActive={isOpen}\n type=\"drawerLeft\"\n >\n <div\n className={`${minicart.sidebarHeader} pointer flex flex-row items-center pa5 h3 bg-base w-100 z-max bb b--muted-3 bw1`}\n >\n <div\n className={`${minicart.sidebarRightCaretContainer} c-muted-1 pa4 flex items-center`}\n onClick={onOutsideClick}\n >\n <IconCaret orientation=\"right\" size={17} {...iconsProps} />\n </div>\n <div\n className={`${minicart.sidebarItemQuantityContainer} relative c-muted-1`}\n >\n <IconCart size={iconSize} {...iconsProps} />\n {quantity > 0 && (\n <span\n className={`${minicart.badge} c-on-emphasis absolute t-mini bg-emphasis br4 w1 h1 pa1 flex justify-center items-center lh-solid`}\n >\n {quantity}\n </span>\n )}\n </div>\n <span\n className={`${minicart.label} dn-m db-l t-action--small pl${\n quantity > 0 ? '6' : '4'\n } c-muted-1`}\n >\n {intl.formatMessage({ id: 'store/sidebar-title' })}\n </span>\n </div>\n {this.props.children}\n </Animation>\n </OutsideClickHandler>\n </Overlay>\n )\n }\n}\n\nSidebar.propTypes = {\n /* Set the sideBar visibility */\n isOpen: PropTypes.bool,\n /* Sidebar content */\n children: PropTypes.object.isRequired,\n /* Function to be called when click in the close sidebar button or outside the sidebar */\n onOutsideClick: PropTypes.func,\n /* Items quantity */\n quantity: PropTypes.number.isRequired,\n /* Cart icon size */\n iconSize: PropTypes.number,\n /** Props to passed to icons from store-icons */\n iconsProps: PropTypes.shape({\n viewBox: PropTypes.string,\n size: PropTypes.number,\n }),\n intl: PropTypes.any,\n}\n\nexport default injectIntl(Sidebar)\n\n```"
}
] |
code_minicart_eb20d966
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of minicart/react/legacy/__tests__/MiniCart.test.jsx from the minicart VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```jsx\nimport React from 'react'\nimport { render, fireEvent, wait } from '@vtex/test-tools/react'\nimport orderFormQuery from 'vtex.store-resources/QueryOrderForm'\nimport orderForm from '../__fixtures__/orderForm'\nimport emptyOrderForm from '../__fixtures__/emptyOrderForm'\nimport MiniCart from '../../index'\nimport { transformOrderFormItems } from '../../modules/pixelHelper'\n\nconst mockedUsePixelPush = jest.fn()\n\njest.mock('vtex.pixel-manager', () => ({\n usePixel: () => ({ push: mockedUsePixelPush }),\n}))\n\nconst mocks = [\n {\n request: {\n query: orderFormQuery,\n },\n result: {\n data: {\n orderForm,\n },\n },\n },\n]\n\nconst emptyMock = [\n {\n request: {\n query: orderFormQuery,\n },\n result: {\n data: {\n orderForm: emptyOrderForm,\n },\n },\n },\n]\n\ndescribe('<MiniCart />', () => {\n beforeEach(() => {\n jest.useFakeTimers()\n })\n\n afterEach(() => {\n mockedUsePixelPush.mockClear()\n })\n\n it('should render popup onClick', async () => {\n const { getByText, baseElement } = render(\n <MiniCart type=\"popup\" hideContent={false} />\n )\n\n await wait(() => {\n jest.runAllTimers()\n })\n\n let box = baseElement.querySelector('.box')\n let sidebar = baseElement.querySelector('.sidebar')\n\n // Expect box be null before click\n expect(box).toBeNull()\n // Sidebar should not exist before and after click\n expect(sidebar).toBeNull()\n\n await wait(() => {\n fireEvent.click(getByText(/button test/i))\n })\n\n await wait(() => {\n jest.runAllTimers()\n })\n\n box = baseElement.querySelector('.box')\n sidebar = baseElement.querySelector('.sidebar')\n\n // Expect Minicart Popup redered\n expect(box).toBeDefined()\n expect(box).not.toBeNull()\n // Expect sidebar still not rendered\n expect(sidebar).toBeNull()\n })\n\n it('should display sidebar onClick', async () => {\n const { getByText, baseElement } = render(\n <MiniCart type=\"sidebar\" hideContent={false} />\n )\n\n await wait(() => {\n jest.runAllTimers()\n })\n\n let box = baseElement.querySelector('.box')\n let sidebar = baseElement.querySelector('.sidebarScrim.dn')\n\n // Expect box be null before and after click\n expect(box).toBeNull()\n // Sidebar should have diplay none class before click\n expect(sidebar).toBeDefined()\n expect(sidebar).not.toBeNull()\n\n await wait(() => {\n fireEvent.click(getByText(/button test/i))\n })\n\n await wait(() => {\n jest.runAllTimers()\n })\n\n box = baseElement.querySelector('.box')\n sidebar = baseElement.querySelector('.sidebarScrim.dn')\n\n // Expect sidebar dont have display none after click\n expect(sidebar).toBeNull()\n expect(box).toBeNull()\n })\n\n it('should match the snapshot in popup mode', async () => {\n const leftClick = { button: 0 }\n\n const { getByText, asFragment } = render(\n <MiniCart type=\"popup\" hideContent={false} />,\n { graphql: { mocks } }\n )\n\n await wait(() => {\n jest.runAllTimers()\n })\n\n await wait(() => {\n fireEvent.click(getByText(/button test/i), leftClick)\n })\n\n await wait(() => {\n jest.runAllTimers()\n })\n\n expect(asFragment()).toMatchSnapshot()\n })\n\n it('should match the snapshot in sidebar mode', async () => {\n const { baseElement } = render(\n <MiniCart type=\"sidebar\" hideContent={false} />,\n { graphql: { mocks } }\n )\n\n await wait(async () => {\n jest.runAllTimers()\n })\n\n expect(baseElement).toMatchSnapshot()\n })\n\n it('should be editable in Site Editor', () => {\n const schema = MiniCart.schema || MiniCart.getSchema({})\n expect(schema).toEqual(\n expect.objectContaining({ title: expect.any(String) })\n )\n })\n\n it('should not show item quantity if there are no items in cart', async () => {\n const { queryByTestId } = render(\n <MiniCart type=\"sidebar\" hideContent={false} showTotalItemsQty={false} />,\n { graphql: { mocks: emptyMock } }\n )\n\n await wait(() => {\n jest.runAllTimers()\n })\n\n expect(queryByTestId('item-qty')).toBeNull()\n })\n\n it('should show the quantity of different items in cart', async () => {\n const { getByTestId } = render(\n <MiniCart type=\"sidebar\" hideContent={false} showTotalItemsQty={false} />,\n { graphql: { mocks } }\n )\n\n await wait(() => {\n jest.runAllTimers()\n })\n\n expect(getByTestId('item-qty').textContent).toBe('1')\n })\n\n it('should show the total quantity of items in cart', async () => {\n const { getByTestId } = render(\n <MiniCart type=\"sidebar\" hideContent={false} showTotalItemsQty />,\n { graphql: { mocks } }\n )\n\n await wait(() => {\n jest.runAllTimers()\n })\n\n expect(getByTestId('item-qty').textContent).toBe('2')\n })\n\n it('should not show price if showPrice is false', async () => {\n const { queryByTestId } = render(\n <MiniCart type=\"sidebar\" hideContent={false} showPrice={false} />,\n { graphql: { mocks } }\n )\n await wait(() => {\n jest.runAllTimers()\n })\n expect(queryByTestId('total-price')).toBeNull()\n })\n\n it('should not show price if there are no items in the cart', async () => {\n const { queryByTestId } = render(\n <MiniCart type=\"sidebar\" hideContent={false} showPrice />,\n { graphql: { mocks: emptyMock } }\n )\n await wait(() => {\n jest.runAllTimers()\n })\n\n expect(queryByTestId('total-price')).toBeNull()\n })\n\n it('should show price if there are items in the cart', async () => {\n const { getByTestId } = render(\n <MiniCart type=\"sidebar\" hideContent={false} showPrice />,\n { graphql: { mocks } }\n )\n await wait(() => {\n jest.runAllTimers()\n })\n expect(getByTestId('total-price')).toBeInTheDocument()\n })\n\n it('should trigger vtex:viewCart when cart is opened', async () => {\n const { container } = render(\n <MiniCart type=\"sidebar\" hideContent={false} />,\n { graphql: { mocks } }\n )\n\n const cartButton = container.getElementsByClassName('IconCart')[0]\n\n await wait(() => {\n jest.runAllTimers()\n })\n \n await wait(() => {\n fireEvent.click(cartButton)\n })\n\n await wait(() => {\n jest.runAllTimers()\n })\n\n const expectedPixelEvent = {\n event: 'viewCart',\n items: transformOrderFormItems(orderForm.items),\n }\n\n expect(mockedUsePixelPush).toHaveBeenCalledWith(expectedPixelEvent)\n })\n\n it('should trigger vtex:viewCart when cart is opened with no items', async () => {\n const { getByText } = render(\n <MiniCart type=\"sidebar\" hideContent={false} />,\n { graphql: { mocks: emptyMock } }\n )\n\n await wait(() => {\n jest.runAllTimers()\n })\n \n await wait(() => {\n fireEvent.click(getByText(/button test/i))\n })\n\n await wait(() => {\n jest.runAllTimers()\n })\n\n const expectedPixelEvent = {\n event: 'viewCart',\n items: [],\n }\n\n expect(mockedUsePixelPush).toHaveBeenCalledWith(expectedPixelEvent)\n })\n})\n\n```"
}
] |
code_minicart_02bd360b
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of minicart/react/legacy/__tests__/localState.test.js from the minicart VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport { InMemoryCache } from 'apollo-cache-inmemory'\nimport { ApolloClient } from 'apollo-client'\nimport { ApolloLink } from 'apollo-link'\nimport gql from 'graphql-tag'\n\nimport createLocalState, { ITEMS_STATUS } from '../localState/index'\nimport addToCartMutation from '../localState/graphql/addToCartMutation.gql'\nimport updateItemsMutation from '../localState/graphql/updateItemsMutation.gql'\n\ndescribe('Local State', () => {\n let cache\n let client\n\n beforeEach(() => {\n cache = new InMemoryCache()\n client = new ApolloClient({\n link: ApolloLink.empty(),\n cache,\n })\n\n const { resolvers, initialState } = createLocalState(client)\n\n client.addResolvers(resolvers)\n cache.writeData({ data: initialState })\n })\n\n it('should append new items to end of cart', async () => {\n const items = [\n {\n id: '100',\n name: 'Chiclete',\n imageUrl: 'imageUrl',\n detailUrl: '/chiclete/p',\n skuName: 'chiclete',\n quantity: 1,\n sellingPrice: 0,\n listPrice: 0,\n parentItemIndex: null,\n parentAssemblyBinding: null,\n assemblyOptions: {\n added: [],\n removed: [],\n parentPrice: 0,\n },\n },\n {\n id: '101',\n name: 'Chiclete de menta',\n imageUrl: 'imageUrl',\n detailUrl: '/chiclete-de-menta/p',\n skuName: 'chiclete de menta',\n quantity: 1,\n sellingPrice: 0,\n listPrice: 0,\n parentItemIndex: null,\n parentAssemblyBinding: null,\n assemblyOptions: {\n added: [],\n removed: [],\n parentPrice: 0,\n },\n },\n ]\n\n await client.mutate({ mutation: addToCartMutation, variables: { items } })\n\n const queryResult = client.readQuery({\n query: gql`\n query {\n minicart @client {\n items\n }\n }\n `,\n })\n\n const cacheItems = JSON.parse(queryResult.minicart.items)\n\n // assert that the cache items contains all items of the mutation\n expect(cacheItems).toEqual(\n expect.arrayContaining(items.map(expect.objectContaining))\n )\n\n cacheItems.forEach(item => {\n expect(item).toHaveProperty('localStatus', ITEMS_STATUS.MODIFIED)\n })\n })\n\n it('should update quantity of item in cart', async () => {\n const item = {\n id: '100',\n name: 'Chiclete',\n imageUrl: 'imageUrl',\n detailUrl: '/chiclete/p',\n skuName: 'chiclete',\n quantity: 1,\n sellingPrice: 0,\n listPrice: 0,\n parentItemIndex: null,\n parentAssemblyBinding: null,\n assemblyOptions: {\n added: [],\n removed: [],\n parentPrice: 0,\n },\n }\n\n cache.writeData({\n data: {\n minicart: {\n __typename: 'Minicart',\n items: JSON.stringify([item]),\n },\n },\n })\n\n const updateItemsPayload = [{ index: 0, quantity: 2, id: item.id }]\n\n await client.mutate({\n mutation: updateItemsMutation,\n variables: { items: updateItemsPayload },\n })\n\n const queryResult = client.readQuery({\n query: gql`\n query {\n minicart @client {\n items\n }\n }\n `,\n })\n\n const cacheItems = JSON.parse(queryResult.minicart.items)\n\n expect(cacheItems).toEqual(\n expect.arrayContaining(\n updateItemsPayload.map(currentItem =>\n expect.objectContaining({\n id: currentItem.id,\n localStatus: ITEMS_STATUS.MODIFIED,\n })\n )\n )\n )\n\n expect(cacheItems).toEqual(\n expect.arrayContaining(\n updateItemsPayload.map(currentItem =>\n expect.objectContaining({\n id: currentItem.id,\n quantity: currentItem.quantity,\n })\n )\n )\n )\n })\n\n it('should update quantity of more than one item in cart', async () => {\n const items = [\n {\n id: '100',\n name: 'Chiclete',\n imageUrl: 'imageUrl',\n detailUrl: '/chiclete/p',\n skuName: 'chiclete',\n quantity: 1,\n sellingPrice: 0,\n listPrice: 0,\n parentItemIndex: null,\n parentAssemblyBinding: null,\n assemblyOptions: {\n added: [],\n removed: [],\n parentPrice: 0,\n },\n },\n {\n id: '101',\n name: 'Chiclete de menta',\n imageUrl: 'imageUrl',\n detailUrl: '/chiclete-de-menta/p',\n skuName: 'chiclete de menta',\n quantity: 1,\n sellingPrice: 0,\n listPrice: 0,\n parentItemIndex: null,\n parentAssemblyBinding: null,\n assemblyOptions: {\n added: [],\n removed: [],\n parentPrice: 0,\n },\n },\n ]\n\n cache.writeData({\n data: {\n minicart: {\n __typename: 'Minicart',\n items: JSON.stringify(items),\n },\n },\n })\n\n const updateItemsPayload = [\n { index: 0, quantity: 2, id: items[0].id },\n { index: 1, quantity: 9, id: items[1].id },\n ]\n\n await client.mutate({\n mutation: updateItemsMutation,\n variables: { items: updateItemsPayload },\n })\n\n const queryResult = client.readQuery({\n query: gql`\n query {\n minicart @client {\n items\n }\n }\n `,\n })\n\n const cacheItems = JSON.parse(queryResult.minicart.items)\n\n expect(cacheItems).toEqual(\n expect.arrayContaining(\n updateItemsPayload.map(item =>\n expect.objectContaining({\n id: item.id,\n localStatus: ITEMS_STATUS.MODIFIED,\n })\n )\n )\n )\n\n expect(cacheItems).toEqual(\n expect.arrayContaining(\n updateItemsPayload.map(item =>\n expect.objectContaining({ id: item.id, quantity: item.quantity })\n )\n )\n )\n })\n})\n\n```"
}
] |
code_minicart_a4812d0f
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of minicart/react/legacy/__tests__/MiniCartV2.test.jsx from the minicart VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```jsx\n/* eslint-disable global-require */\nimport React from 'react'\nimport { render, wait } from '@vtex/test-tools/react'\n\nimport { Minicart } from '../../Minicart'\nimport { MinicartStateContext } from '../../MinicartContext'\nimport { transformOrderFormItems } from '../../modules/pixelHelper'\nimport orderForm from '../__fixtures__/orderForm'\n\nconst mockedUsePixelPush = jest.fn()\n\njest.mock('vtex.pixel-manager', () => ({\n usePixel: () => ({ push: mockedUsePixelPush }),\n}))\n\njest.mock('vtex.order-manager/OrderForm', () => {\n const mockData = require('../__fixtures__/orderForm')\n\n return {\n useOrderForm: jest\n .fn(() => ({\n orderForm: mockData.default,\n }))\n .mockImplementationOnce(() => ({\n orderForm: [],\n })),\n }\n})\n\nconst minicartMockContextValue = {\n variation: 'drawer',\n open: true,\n hasBeenOpened: false,\n openOnHoverProp: false,\n openBehavior: 'click',\n}\n\ndescribe('<MiniCart /> v2', () => {\n beforeEach(() => {\n jest.useFakeTimers()\n })\n\n it('should trigger vtex:viewCart when cart is opened and match items when cart is empty', async () => {\n render(\n <MinicartStateContext.Provider value={minicartMockContextValue}>\n <Minicart variation=\"drawer\" />\n </MinicartStateContext.Provider>\n )\n\n await wait(async () => {\n jest.runAllTimers()\n })\n\n const expectedPixelEvent = {\n event: 'viewCart',\n items: [],\n }\n\n expect(mockedUsePixelPush).toHaveBeenCalledWith(expectedPixelEvent)\n })\n\n it('should trigger vtex:viewCart when cart is opened and match items when cart is with products', async () => {\n render(\n <MinicartStateContext.Provider value={minicartMockContextValue}>\n <Minicart variation=\"drawer\" />\n </MinicartStateContext.Provider>\n )\n\n await wait(async () => {\n jest.runAllTimers()\n })\n\n const expectedPixelEvent = {\n event: 'viewCart',\n items: transformOrderFormItems(orderForm.items),\n }\n\n expect(mockedUsePixelPush).toHaveBeenCalledWith(expectedPixelEvent)\n })\n})\n\n```"
}
] |
code_minicart_39a6d505
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of minicart/react/legacy/hooks/useMarketingSessionParams.jsx from the minicart VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```jsx\nimport { useEffect, useState } from 'react'\n// eslint-disable-next-line no-restricted-imports\nimport { path, pathOr } from 'ramda'\n\nconst getUtmParams = publicFields => ({\n source: path(['utm_source', 'value'], publicFields),\n medium: path(['utm_medium', 'value'], publicFields),\n campaign: path(['utm_campaign', 'value'], publicFields),\n})\n\nconst getUtmiParams = publicFields => ({\n campaign: path(['utmi_cp', 'value'], publicFields),\n page: path(['utmi_p', 'value'], publicFields),\n part: path(['utmi_pc', 'value'], publicFields),\n})\n\nconst getSessionPromiseFromWindow = () =>\n !window.__RENDER_8_SESSION__ || !window.__RENDER_8_SESSION__.sessionPromise\n ? Promise.resolve(null)\n : window.__RENDER_8_SESSION__.sessionPromise\n\nconst useMarketingSessionParams = () => {\n const [utmParams, setUtmParams] = useState(undefined)\n const [utmiParams, setUtmiParams] = useState(undefined)\n\n useEffect(() => {\n getSessionPromiseFromWindow()\n .then(data => {\n const publicFields = pathOr(\n {},\n ['response', 'namespaces', 'public'],\n data\n )\n if (Object.keys(publicFields).length === 0) {\n return\n }\n\n setUtmParams(getUtmParams(publicFields))\n setUtmiParams(getUtmiParams(publicFields))\n })\n .catch(() => {\n // Do nothing!\n })\n }, [])\n\n return { utmParams, utmiParams }\n}\n\nexport default useMarketingSessionParams\n\n```"
}
] |
code_minicart_86e0ab93
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of minicart/react/legacy/localState/graphql/updateLocalItemStatusMutation.gql from the minicart VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```graphql\nmutation updateLocalItemStatus {\n updateLocalItemStatus @client\n}\n\n```"
}
] |
code_minicart_c445512e
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of minicart/react/legacy/localState/graphql/addToCartMutation.gql from the minicart VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```graphql\nmutation addToCart($items: [MinicartItem]) {\n addToCart(items: $items) @client\n}\n\n```"
}
] |
code_minicart_90ebe9d6
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of minicart/react/legacy/localState/graphql/updateLocalItemsMutation.gql from the minicart VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```graphql\nmutation UpdateLocalItems($items: [MinicartItem]) {\n updateLocalItems(items: $items) @client\n}\n\n```"
}
] |
code_minicart_1af7095f
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of minicart/react/legacy/localState/graphql/fullMinicartQuery.gql from the minicart VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```graphql\nquery {\n minicart @client {\n items\n orderForm\n isOpen\n }\n}\n\n```"
}
] |
code_minicart_8193929b
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of minicart/react/legacy/localState/graphql/minicartOrderFormQuery.gql from the minicart VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```graphql\nquery orderForm {\n minicart @client {\n orderForm\n }\n}\n\n```"
}
] |
code_minicart_f6e282ff
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of minicart/react/legacy/localState/graphql/updateOrderFormMutation.gql from the minicart VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```graphql\nmutation updateOrderForm(\n $orderForm: [OrderForm]\n $forceUpdateItems: Boolean = false\n) {\n updateOrderForm(orderForm: $orderForm, forceUpdateItems: $forceUpdateItems)\n @client\n}\n\n```"
}
] |
code_minicart_f7f3a612
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of minicart/react/legacy/localState/graphql/updateItemsMutation.gql from the minicart VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```graphql\nmutation updateItems($items: [MinicartItem]) {\n updateItems(items: $items) @client\n}\n\n```"
}
] |
code_minicart_c3636d36
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of minicart/react/legacy/localState/graphql/setMinicartOpenMutation.gql from the minicart VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```graphql\nmutation setMinicartOpen($isOpen: Boolean!) {\n setMinicartOpen(isOpen: $isOpen) @client\n}\n\n```"
}
] |
code_minicart_25003461
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of minicart/react/legacy/__tests__/hooks/useMarketingSessionParams.test.js from the minicart VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport { renderHook, wait } from '@vtex/test-tools/react'\n\nimport useMarketingSessionParams from '../../hooks/useMarketingSessionParams'\n\nconst fakeSessionWithData = {\n response: {\n namespaces: {\n public: {\n utm_source: {\n value: 'utmSource',\n },\n utm_medium: {\n value: 'utmMedium',\n },\n utm_campaign: {\n value: 'utmCampaign',\n },\n utmi_cp: {\n value: 'utmiCampaign',\n },\n utmi_p: {\n value: 'utmiPage',\n },\n utmi_pc: {\n value: 'utmiPart',\n },\n },\n },\n },\n}\n\nconst fakeSessionNoData = {\n response: {\n namespaces: {\n public: {},\n },\n },\n}\n\ntest('if session has correct data, get and format input correctly', async () => {\n window.__RENDER_8_SESSION__ = {}\n window.__RENDER_8_SESSION__.sessionPromise = new Promise(resolve =>\n resolve(fakeSessionWithData)\n )\n const { result } = renderHook(() => useMarketingSessionParams())\n\n await wait()\n\n const { utmParams, utmiParams } = result.current\n expect(utmParams).toMatchObject({\n source: 'utmSource',\n medium: 'utmMedium',\n campaign: 'utmCampaign',\n })\n expect(utmiParams).toMatchObject({\n campaign: 'utmiCampaign',\n page: 'utmiPage',\n part: 'utmiPart',\n })\n})\n\ntest('if session does not have data, leave object as undefined', async () => {\n window.__RENDER_8_SESSION__ = {}\n window.__RENDER_8_SESSION__.sessionPromise = new Promise(resolve =>\n resolve(fakeSessionNoData)\n )\n const { result } = renderHook(() => useMarketingSessionParams())\n\n await wait()\n\n const { utmParams, utmiParams } = result.current\n expect(utmParams).toBeUndefined()\n expect(utmiParams).toBeUndefined()\n})\n\ntest('if session promise rejects, everything still works, response is undefined', async () => {\n window.__RENDER_8_SESSION__ = {}\n window.__RENDER_8_SESSION__.sessionPromise = new Promise((_, reject) =>\n reject()\n )\n const { result } = renderHook(() => useMarketingSessionParams())\n\n await wait()\n\n const { utmParams, utmiParams } = result.current\n expect(utmParams).toBeUndefined()\n expect(utmiParams).toBeUndefined()\n})\n\n```"
}
] |
code_instore-stone-fields_b6481990
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of instore-stone-fields/messages/pt.json from the instore-stone-fields VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"instore-stone-fields.stone-code\": \"Stone Code*\",\n \"instore-stone-fields.mothers-name\": \"Nome da mãe\",\n \"instore-stone-fields.business-name\": \"Nome do negócio\"\n}\n\n```"
}
] |
code_instore-stone-fields_b9b2f783
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of instore-stone-fields/messages/en.json from the instore-stone-fields VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"instore-stone-fields.stone-code\": \"Stone Code*\",\n \"instore-stone-fields.mothers-name\": \"Mother's name\",\n \"instore-stone-fields.business-name\": \"Business name\"\n}\n\n```"
}
] |
code_instore-stone-fields_6ae5ae1a
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of instore-stone-fields/messages/es.json from the instore-stone-fields VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"instore-stone-fields.stone-code\": \"Stone Code*\",\n \"instore-stone-fields.mothers-name\": \"Nombre de la Madre\",\n \"instore-stone-fields.business-name\": \"Nombre del Negocio\"\n}\n\n```"
}
] |
code_instore-stone-fields_8bbe2b24
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of instore-stone-fields/docs/README.md from the instore-stone-fields VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```markdown\n# Instore Stone Fields\n\nRefer to [Instore Form Fields](https://github.com/vtex-apps/instore-form-fields)\n\nApparently you had to declare another \"index\" extension, even if it rendered nothing, otherwise locales wouldn't load :(\n```"
}
] |
code_instore-stone-fields_32287be3
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of instore-stone-fields/pages/pages.json from the instore-stone-fields VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"extensions\": {\n \"registration-container/index\": {\n \"component\": \"index\"\n },\n \"registration-container/1\": {\n \"component\": \"vtex.instore-form-fields/FormInput\",\n \"props\": {\n \"ffor\": \"customsenha\",\n \"nameKey\": \"instore-stone-fields.stone-code\",\n \"isRequired\": true\n }\n },\n \"registration-container/2\": {\n \"component\": \"vtex.instore-form-fields/FormInput\",\n \"props\": {\n \"ffor\": \"customnomemae\",\n \"nameKey\": \"instore-stone-fields.mothers-name\",\n \"isRequired\": false\n }\n },\n \"registration-container/3\": {\n \"component\": \"vtex.instore-form-fields/FormInput\",\n \"props\": {\n \"ffor\": \"nomefantasiapessoal\",\n \"nameKey\": \"instore-stone-fields.business-name\",\n \"isRequired\": false\n }\n }\n }\n}\n\n```"
}
] |
code_instore-stone-fields_5699f38b
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of instore-stone-fields/react/index.js from the instore-stone-fields VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport React from 'react'\nimport FormInput from 'vtex.instore-form-fields/FormInput'\n\nclass StoneFields extends React.Component {\n render() {\n return null\n }\n}\n\nexport default StoneFields\n\n```"
}
] |
code_external-prices-node-template_03aec823
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of external-prices-node-template/docs/README.md from the external-prices-node-template VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```markdown\n# External Price App\n\nA reference IO app to integrate external price sources with VTEX Pricing Hub.\n\n## Implementation\n\n1. Fork this app.\n2. In the `manifest.json` file:\n * Change the `vendor` field to the name of the account you are using.\n * Change the `name` field to one of your choosing.\n * Add your service host (e.g. `myhost.com`) in an `outbound-access` policy.\n3. In the `node/env.ts` file, add your service endpoint as follows:\n\n ```\n const ENV = {\n SERVICE_ENDPOINT: 'http://myservice.com',\n }\n \n export default ENV\n ```\n \n4. Change the ` node/clients/externalPrice.ts` file to parse data received by the external pricing app and return it in a way that Pricing Hub can understand. See more details on the specification of this format in the [Pricing Hub documentation](https://developers.vtex.com/vtex-rest-api/docs/pricing-hub).\n\n\n> ⛔ Do not change the `\"routes\"` in `node/service.json` nor the files in `node/typings/`, since they were created to reflect Pricing Hub behavior.\n\n\n```"
}
] |
code_external-prices-node-template_deb3b242
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of external-prices-node-template/node/service.json from the external-prices-node-template VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"memory\": 256,\n \"ttl\": 10,\n \"timeout\": 2,\n \"minReplicas\": 2,\n \"maxReplicas\": 4,\n \"workers\": 1,\n \"routes\": {\n \"price\": {\n \"path\": \"/_v/external-prices/price\",\n \"public\": false,\n \"access\": \"authorized\",\n \"policies\": [\n {\n \"effect\": \"allow\",\n \"actions\": [\n \"post\"\n ],\n \"principals\": [\n \"vrn:vtex.vtex-id:*:*:*:user/vtexappkey-appvtex\"\n ]\n }\n ]\n }\n }\n}\n\n```"
}
] |
code_external-prices-node-template_7c31ce72
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of external-prices-node-template/node/package.json from the external-prices-node-template VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"dependencies\": {\n \"co-body\": \"^6.0.0\",\n \"ramda\": \"^0.25.0\"\n },\n \"devDependencies\": {\n \"@types/co-body\": \"^0.0.3\",\n \"@types/jest\": \"^24.0.18\",\n \"@types/node\": \"^12.0.0\",\n \"@types/node-fetch\": \"^2.5.8\",\n \"@types/ramda\": \"types/npm-ramda#dist\",\n \"@vtex/api\": \"6.41.0\",\n \"@vtex/test-tools\": \"^1.0.0\",\n \"@vtex/tsconfig\": \"^0.5.6\",\n \"typescript\": \"3.9.7\"\n },\n \"scripts\": {\n \"lint\": \"tsc --noEmit --pretty\"\n },\n \"version\": \"0.3.2\"\n}\n\n```"
}
] |
code_external-prices-node-template_a17faee2
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of external-prices-node-template/node/index.ts from the external-prices-node-template VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport type { ClientsConfig } from '@vtex/api'\nimport { LRUCache, method, Service } from '@vtex/api'\n\nimport { Clients } from './clients'\nimport { validate } from './handlers/validate'\nimport { fetchPrice } from './handlers/fetchPrice'\nimport { formatResponse } from './handlers/formatResponse'\n\nconst TIMEOUT_MS = 800\nconst memoryCache = new LRUCache<string, never>({ max: 5000 })\n\nconst clients: ClientsConfig<Clients> = {\n implementation: Clients,\n options: {\n default: {\n retries: 2,\n timeout: TIMEOUT_MS,\n },\n status: {\n memoryCache,\n },\n },\n}\n\nexport default new Service({\n clients,\n routes: {\n price: method({\n POST: [validate, fetchPrice, formatResponse],\n }),\n },\n})\n\n```"
}
] |
code_external-prices-node-template_9988b4bb
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of external-prices-node-template/node/env.ts from the external-prices-node-template VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\n//App Settings\nconst ENV = {\n SERVICE_ENDPOINT: 'YOUR_SERVICE_ENDPOINT',\n}\n\nexport default ENV\n\n```"
}
] |
code_external-prices-node-template_3086a89d
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of external-prices-node-template/node/clients/externalPrice.ts from the external-prices-node-template VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport type { InstanceOptions, IOContext } from '@vtex/api'\nimport { ExternalClient } from '@vtex/api'\n\nimport type { InputItem } from '../typings/externalPrice'\nimport ENV from '../env'\n\nexport interface ExternalPriceClient {\n getPrice: (item: InputItem) => Promise<number | undefined>\n}\n\nexport default class ExternalPrice\n extends ExternalClient\n implements ExternalPriceClient {\n constructor(context: IOContext, options?: InstanceOptions) {\n super(ENV.SERVICE_ENDPOINT, context, options)\n }\n\n public async getPrice(item: InputItem): Promise<number | undefined> {\n try {\n return await this.http.get(item.skuId, {\n metric: 'get-price',\n })\n } catch (e) {\n if (e.response.status === 404) {\n return undefined\n }\n\n throw e\n }\n }\n}\n\n```"
}
] |
code_external-prices-node-template_a67fd552
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of external-prices-node-template/node/clients/externalPriceMock.ts from the external-prices-node-template VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { IOClient } from '@vtex/api'\n\nimport type { ExternalPriceClient, } from './externalPrice'\nimport type { InputItem } from '../typings/externalPrice'\n\nexport default class ExternalPrice extends IOClient implements ExternalPriceClient {\n public async getPrice(item: InputItem): Promise<number | undefined> {\n return Number(item.skuId) * 10\n }\n}\n\n```"
}
] |
code_external-prices-node-template_c2892414
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of external-prices-node-template/node/clients/index.ts from the external-prices-node-template VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { IOClients } from '@vtex/api'\n\nimport ExternalPrice from './externalPriceMock'\n\n// Extend the default IOClients implementation with our own custom clients.\nexport class Clients extends IOClients {\n public get externalPrice() {\n return this.getOrSet('externalPrice', ExternalPrice)\n }\n}\n\n```"
}
] |
code_external-prices-node-template_b96d9e7c
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of external-prices-node-template/node/typings/externalPrice.d.ts from the external-prices-node-template VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport type { Maybe } from '@vtex/api'\n\nexport type Quote = {\n skuId: string\n price: number\n}\n\nexport type InputItem = {\n skuId: string\n quantity: number\n index: number\n}\n\nexport type ExternalPriceInput = {\n context: Record<string, unknown>\n item: InputItem\n}\n\nexport type ExternalPriceResponse = {\n message: string\n item: {\n index: number\n skuId: string\n price: number\n costPrice: Maybe<number>\n listPrice: Maybe<number>\n priceValidUntil: Maybe<number>\n priceTables: string\n }\n}\n\n```"
}
] |
code_external-prices-node-template_ca73e7e6
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of external-prices-node-template/node/typings/global.d.ts from the external-prices-node-template VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport type { RecorderState, ServiceContext } from '@vtex/api'\nimport type { Clients } from '../clients'\nimport type { Quote, ExternalPriceInput } from './externalPrice'\n\ndeclare global {\n type Context<TState extends State = State> = ServiceContext<Clients, TState>\n\n interface State extends RecorderState {\n quote?: Quote\n body: ExternalPriceInput\n }\n\n type Next = () => Promise<void>\n}\n\n```"
}
] |
code_external-prices-node-template_2a5eb06a
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of external-prices-node-template/node/__tests__/simple.test.ts from the external-prices-node-template VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\n// You can import your files here for testing them\n//\n// More info: https://github.com/sapegin/jest-cheat-sheet\n\ndescribe('simpleTest', () => {\n it('one test case', async () => {\n expect(0.2 + 0.1).not.toBe(0.3)\n })\n})\n\n```"
}
] |
code_external-prices-node-template_f7235248
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of external-prices-node-template/node/handlers/formatResponse.ts from the external-prices-node-template VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport type { ExternalPriceResponse, Quote } from '../typings/externalPrice'\n\nexport async function formatResponse(ctx: Context) {\n const { state, body } = ctx\n\n const quote = state.quote as Quote\n\n const response: ExternalPriceResponse = {\n message: 'Price quoted successfully.',\n item: {\n costPrice: null,\n listPrice: null,\n priceTables: '',\n priceValidUntil: null,\n index: body.item.index,\n ...quote,\n },\n }\n\n ctx.body = response\n ctx.status = 200\n}\n\n```"
}
] |
code_external-prices-node-template_8d124072
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of external-prices-node-template/node/handlers/validate.ts from the external-prices-node-template VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { json } from 'co-body'\nimport { UserInputError } from '@vtex/api'\n\nexport async function validate(ctx: Context, next: Next) {\n ctx.body = await json(ctx.req)\n\n const { item } = ctx.body\n\n if (!item?.skuId) throw new UserInputError('Item.SkuId is required')\n\n await next()\n}\n\n```"
}
] |
code_external-prices-node-template_4763073d
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of external-prices-node-template/node/handlers/fetchPrice.ts from the external-prices-node-template VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { NotFoundError } from '@vtex/api'\n\nexport async function fetchPrice(\n ctx: Context,\n next: Next\n) {\n const { clients, body } = ctx\n\n const { externalPrice } = clients\n\n const price = await externalPrice.getPrice(body.item)\n\n if (!price) throw new NotFoundError('Price not found')\n\n ctx.state.quote = {\n skuId: body.item.skuId,\n price,\n }\n\n await next()\n}\n\n```"
}
] |
code_store-sitemap_17b122cb
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-sitemap/docs/README.md from the store-sitemap VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```markdown\n# Sitemap\n\nThe Sitemap app allows you to generate a `sitemap.xml` file for your store website. After deploying and installing the app on your account, you can create a sitemap to improve store visibility on search engines such as Google. \n\nTo learn how to generate a sitemap, follow the instructions below.\n\n## Before you begin\n\n- This app is available for stores using `vtex.edition-store@3.x` or a later version of the [Edition App](https://developers.vtex.com/docs/guides/vtex-io-documentation-edition-app).\n To check which Edition App is installed on your account, run `vtex edition get`. If it's an older edition, please [open a ticket](https://help-tickets.vtex.com/smartlink/sso/login/zendesk) with VTEX Support asking for the installation of the `vtex.edition-store@5.x` Edition App.\n\n- Adjust the products, navigation, and custom routes that will be included in the sitemap. Check the [Advanced Configuration section](#advanced-configuration) for more information.\n\n## Instructions\n\n1. Using your terminal and the [VTEX IO CLI](https://vtex.io/docs/recipes/development/vtex-io-cli-installation-and-command-reference/), log in to your account.\n \n2. Run `vtex use {workspaceName} --production` to use a production workspace or [create a production workspace](https://vtex.io/docs/recipes/development/creating-a-production-workspace/) from scratch.\n\n >⚠️ Remember to replace the values between the curly brackets with the corresponding values of your environment.\n\n3. Run `vtex install vtex.store-sitemap@2.x` to install the Sitemap app.\n\n > ℹ️ If you're using `vtex.edition-store@5.x`, skip step 3, as the `vtex.store-sitemap@2.x` app is installed by default with this version. Check our [Edition App documentation](https://developers.vtex.com/docs/guides/vtex-io-documentation-edition-app) to learn more about the different versions.\n\n4. Run `vtex install vtex.admin-graphql-ide@3.x` to install the GraphQL admin IDE.\n \n5. In your browser, access the Admin and go to **Store Setting > Storefront > GraphQL IDE**.\n\n6. From the dropdown list, choose the `vtex.routes-bootstrap@0.x` app.\n\n7. If this isn't the first time you're generating the store sitemap or if no changes have been made to the store routes since the last time you generated the store sitemap, go to step 8. Otherwise, run the following query:\n\n ```gql \n {\n bootstrap {\n brands\n categories\n }\n }\n ```\n\n The expected response body is\n \n ```json\n {\n \"data\":{\n \"bootstrap\": {\n \"brands\": true,\n \"categories\": true\n }\n }\n }\n ```\n\n8. Now, from the GraphQL IDE dropdown list, select the `vtex.store-sitemap@2.x` app.\n\n9. Run the following query:\n\n > ℹ️ If your store is **not** cross-border, the sitemap will be automatically updated daily. \n > In this case, running this GraphQL query is not necessary and will have no effect on the sitemap generation.\n\n ```gql\n {\n generateSitemap\n }\n ```\n\n The expected response body is\n\n ```json\n {\n \"data\": {\n \"generateSitemap\": true\n }\n }\n ```\n\n This means your sitemap will be available in some minutes, after being processed and saved on our database.\n\n >ℹ️ The time taken to generate a sitemap is proportional to the number of products. For example, the average time to generate a sitemap for a store with 60k products is 30 minutes. For 5k products, the duration should be about 5 minutes.\n \n If you attempt to send a new request to the Sitemap API during store sitemap generation, the following message will be displayed:\n\n ```\n Sitemap generation already in place\n Next generation available: <End-date>\n ```\n \n To force a restart, add the `force` argument to the query, as in `generateSitemap(force: true)`. This will cancel the previous process.\n\n10. Check the sitemap generated for the current workspace you're working on by accessing `https://{workspace}--{account}.myvtex.com/sitemap.xml` on your browser. Keep in mind that if you have a cross-border store, you’ll first see an index with a sitemap for each locale.\n\n >ℹ️ Different `.xml` files are generated based on their entity type (product, category, subcategory, user routes, brand, and department), and each `.xml` file supports a maximum of 5k routes.\n\n11. If you're happy with the results, run `vtex promote` to promote your workspace and include your sitemap in your master workspace.\n\n Once you’ve promoted your workspace, no further actions are needed on your part: you’re ready to check the store sitemap by accessing `https://{account}.myvtex.com/sitemap.xml` on your browser.\n\n### Advanced configuration\n\n#### Managing routes\n\nYou can manage whether to include products, navigation, apps, and/or routes containing a specific term in your sitemap. To do that, follow the instructions below:\n\n1. In your browser, type `{workspace}--{account}.myvtex.com/admin`, replacing the values between curly brackets with the corresponding values of your environment, to access the account's Admin of the production workspace you're working on.\n \n2. Go to **Account settings > Apps > My apps** and search for **Sitemap** app.\n\n3. Enable or disable products, navigation, apps, or routes containing a specific term for your scenario.\n \n \n\n#### Enabling custom routes\n\nIf you have [custom pages](https://developers.vtex.com/vtex-developer-docs/docs/vtex-io-documentation-creating-a-new-custom-page) configured in a `routes.json` file and want them to be included in the store sitemap, add `isSitemapEntry=true` as a prop of the routes you want to include in the sitemap. Example:\n\n ```json\n {\n \"store.custom#about-us\": {\n \"path\": \"/about-us\",\n \"isSitemapEntry\": true\n }\n }\n ```\n\nOnce everything is set up, go back to **step 4** of the [Instructions](#instructions).\n\n#### Extending the sitemap\n\nTo add custom routes created by an app (for example, the ones created by [`store-locator`](https://github.com/vtex-apps/store-locator)) to the store sitemap, the app must respond to an XML file containing a list of the routes created by that app. Lastly, you must include the path to the XML file that your app responds to as an index of the store sitemap.\n\nFor implementation details, check the following instructions:\n\n1. Create or modify your app to respond to the following route `/sitemap/{index-name}.xml` and to return an XML file containing the data that you want the search engine (for example, Google) to index. Replace the values between the curly brackets according to your scenario.\n\n >ℹ️ We recommend using a pre-generated XML file. Otherwise, the XML file will be built from scratch for every request, consuming more time to complete the task.\n\n2. [Publish](https://developers.vtex.com/vtex-developer-docs/docs/vtex-io-documentation-publishing-an-app) and install your app in a production workspace.\n\n3. To make your index available in the sitemap root file (`/sitemap.xml`), access the account Admin of the workspace you're working on, and select the GraphQL IDE.\n\n4. From the dropdown list, choose the `vtex.store-sitemap@2.x` app and perform the following mutation, adapting it to your scenario:\n\n ```gql\n mutation {\n saveIndex(index: \"{index-name}\")\n }\n ```\n\n >ℹ️ If you have a [cross-border](https://developers.vtex.com/docs/guides/vtex-io-cross-border-stores) store, the `saveIndex` mutation also accepts the `binding` ID as an argument, which means that by specifying the `binding` ID, you can add your new index to the sitemap of the desired binding. If the `binding` ID is not specified, the mutation will consider the default binding of the store.\n\n5. Check the updated sitemap for the current workspace you're working on by accessing `https://{workspace}--{account}.myvtex.com/sitemap.xml` in your browser.\n\n6. If you're happy with the results, run `vtex promote` to promote your workspace and include the sitemap in your master workspace.\n\n#### Removing a custom route\n\nIf you ever want to remove a custom route, you can execute the following mutation, which takes the same arguments as `saveIndex`:\n\n ```gql\n mutation {\n deleteIndex(index: \"{index-name}\")\n }\n ```\n\n### Using Sitemap API Endpoints\n\nBeyond generating a complete sitemap, this app exposes specific API endpoints that can be used to get route information for external sitemap generation or other needs.\n\n#### Available Endpoints\n\nThe following endpoint provides combined route information in JSON format:\n\n1. **Custom Routes**\n - Endpoint: `/_v/public/sitemap/custom-routes`\n - Description: Returns a combination of routes defined via CMS and internal pages (excluding product, brands and category routes) and routes defined by installed apps in their `build.json` files.\n - **Important**: The generation of custom-routes is capped under a certain limit. If you notice missing routes in your custom-routes file, please contact VTEX Support.\n - Example response:\n ```json\n [\n {\n \"name\": \"apps-routes\",\n \"routes\": [\"/store-locator/ny\", \"/store-locator/ca\"]\n },\n {\n \"name\": \"user-routes\",\n \"routes\": [\"/about-us\", \"/contact\", \"/faq\"]\n }\n ]\n ```\n\n#### Using the Endpoint\n\nThis endpoint can be accessed via an HTTP GET request to:\n- `https://{workspace}--{account}.myvtex.com/_v/public/sitemap/custom-routes`\n\n```"
}
] |
code_store-sitemap_cac5e129
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-sitemap/graphql/schema.graphql from the store-sitemap VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```graphql\ntype Query {\n generateSitemap(force: Boolean): Boolean! @requiresAuth\n}\n\ntype Mutation {\n saveIndex(index: String!, binding: String): Boolean!\n deleteIndex(index: String!, binding: String): Boolean!\n}\n\n```"
}
] |
code_store-sitemap_80b950e9
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-sitemap/node/utils.test.ts from the store-sitemap VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { Binding, Events, IOContext, Logger, VBase, VBaseSaveResponse } from '@vtex/api'\nimport * as TypeMoq from 'typemoq'\n\nimport { MultipleSitemapGenerationError } from './errors'\nimport { CONFIG_BUCKET, GENERATION_CONFIG_FILE, startSitemapGeneration } from './utils'\n\nimport { Clients } from './clients'\n\nconst eventsTypeMock = TypeMoq.Mock.ofInstance(Events)\nconst vbaseTypeMock = TypeMoq.Mock.ofInstance(VBase)\nconst contextMock = TypeMoq.Mock.ofType<Context>()\nconst ioContext = TypeMoq.Mock.ofType<IOContext>()\nconst state = TypeMoq.Mock.ofType<State>()\nconst loggerMock = TypeMoq.Mock.ofType<Logger>()\n\nconst oneHourFromNowMS = () => `${new Date(Date.now() + 1 * 60 * 60 * 1000)}`\nconst minusOneHourFromNowMS = () => `${new Date(Date.now() - 1 * 60 * 60 * 1000)}`\n\nconst eventSent = jest.fn()\n\nconst DEFAULT_CONFIG = {\n endDate: oneHourFromNowMS(),\n generationId: '10',\n}\n\ndescribe('Test startSitemapGeneration', () => {\n let context: Context\n\n const vbase = class VBaseMock extends vbaseTypeMock.object {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private jsonData: Record<string, any> = {}\n\n constructor() {\n super(ioContext.object)\n }\n\n public getJSON = async <T>(\n bucket: string,\n file: string,\n nullOrUndefined?: boolean | undefined\n ): Promise<T> => {\n if (!this.jsonData[bucket]?.[file] && nullOrUndefined) {\n return (null as unknown) as T\n }\n return Promise.resolve(this.jsonData[bucket][file] as T)\n }\n\n public saveJSON = async <T>(\n bucket: string,\n file: string,\n data: T\n ): Promise<VBaseSaveResponse> => {\n if (!this.jsonData[bucket]) {\n this.jsonData[bucket] = {}\n }\n this.jsonData[bucket][file] = data\n return Promise.resolve([{ path: file, hash: 'mocked-hash' }])\n }\n }\n\n // tslint:disable-next-line:max-classes-per-file\n const events = class EventsMock extends eventsTypeMock.object {\n constructor() {\n super(ioContext.object)\n }\n\n public sendEvent = async (_: any, __:string, ___: any, ____: any) => {\n eventSent()\n }\n }\n\n beforeEach(() => {\n // tslint:disable-next-line: max-classes-per-file\n const ClientsImpl = class ClientsMock extends Clients {\n get vbase() {\n return this.getOrSet('vbase', vbase)\n }\n\n get events() {\n return this.getOrSet('events', events)\n }\n }\n\n context = {\n ...contextMock.object,\n clients: new ClientsImpl({}, ioContext.object),\n query: {},\n state: {\n ...state.object,\n binding: {\n id: '1',\n } as Binding,\n bucket: 'bucket',\n forwardedHost: 'www.host.com',\n forwardedPath: '/sitemap/file1.xml',\n rootPath: '',\n },\n vtex: {\n ...ioContext.object,\n logger: loggerMock.object,\n },\n }\n })\n\n it('Should not start a generation if has already started', async () => {\n const { vbase: vbaseClient } = context.clients\n await vbaseClient.saveJSON(CONFIG_BUCKET, GENERATION_CONFIG_FILE, DEFAULT_CONFIG)\n try {\n await startSitemapGeneration(context)\n expect(true).toBe(false)\n } catch(err) {\n expect(err instanceof MultipleSitemapGenerationError).toBe(true)\n }\n })\n\n it('Should start a generation if date is expired', async () => {\n const { vbase: vbaseClient } = context.clients\n await vbaseClient.saveJSON(CONFIG_BUCKET, GENERATION_CONFIG_FILE, {\n ...DEFAULT_CONFIG,\n endDate: minusOneHourFromNowMS(),\n })\n await startSitemapGeneration(context)\n expect(eventSent).toBeCalled()\n })\n\n it('Should start a generation if date is invalid', async () => {\n const { vbase: vbaseClient } = context.clients\n await vbaseClient.saveJSON(CONFIG_BUCKET, GENERATION_CONFIG_FILE, {\n ...DEFAULT_CONFIG,\n endDate: 'INVALID',\n })\n await startSitemapGeneration(context)\n expect(eventSent).toBeCalled()\n })\n\n it('Should start a generation with the force param', async () => {\n const { vbase: vbaseClient } = context.clients\n await vbaseClient.saveJSON(CONFIG_BUCKET, GENERATION_CONFIG_FILE, DEFAULT_CONFIG)\n await startSitemapGeneration(context, true)\n expect(eventSent).toBeCalled()\n })\n\n it('Should start a generation', async () => {\n await startSitemapGeneration(context)\n expect(eventSent).toBeCalled()\n })\n})\n\n```"
}
] |
code_store-sitemap_9123f8b3
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-sitemap/node/errors.ts from the store-sitemap VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nexport class MultipleSitemapGenerationError extends Error {\n constructor(endDate: string) {\n super()\n this.message = `Sitemap generation already in place\\nNext generation available: ${endDate}`\n }\n}\n\nexport class MultipleCustomRoutesGenerationError extends Error {\n constructor(endDate: string, account: string) {\n super()\n this.message = `Custom routes generation already in progress for account ${account}\\nNext generation available: ${endDate}`\n }\n}\n\n```"
}
] |
code_store-sitemap_69d71c7f
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-sitemap/node/service.json from the store-sitemap VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"memory\": 512,\n \"ttl\": 60,\n \"timeout\": 55,\n \"minReplicas\": 2,\n \"maxReplicas\": 10,\n \"workers\": 4,\n \"routes\": {\n \"sitemap\": {\n \"path\": \"/sitemap.xml\",\n \"public\": true\n },\n \"sitemapEntry\": {\n \"path\": \"/sitemap/:path\",\n \"public\": true\n },\n \"generateSitemap\": {\n \"path\": \"/generate-sitemap\",\n \"public\": false\n },\n \"robots\": {\n \"path\": \"/robots.txt\",\n \"public\": true\n },\n \"customRoutes\": {\n \"path\": \"/_v/public/sitemap/custom-routes\",\n \"public\": true,\n \"smartcache\": true\n }\n },\n \"events\": {\n \"generateSitemap\": {\n \"sender\": \"vtex.store-sitemap\",\n \"keys\": [\"sitemap.generate\"]\n },\n \"generateRewriterRoutes\": {\n \"sender\": \"vtex.store-sitemap\",\n \"keys\": [\"sitemap.generate:rewriter-routes\"]\n },\n \"generateProductRoutes\": {\n \"sender\": \"vtex.store-sitemap\",\n \"keys\": [\"sitemap.generate:product-routes\"]\n },\n \"generateAppsRoutes\": {\n \"sender\": \"vtex.store-sitemap\",\n \"keys\": [\"sitemap.generate:apps-routes\"]\n },\n \"groupEntries\": {\n \"sender\": \"vtex.store-sitemap\",\n \"keys\": [\"sitemap.generate:group-entries\"]\n }\n }\n}\n\n```"
}
] |
code_store-sitemap_be596f65
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-sitemap/node/utils.ts from the store-sitemap VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { Binding, LINKED, TenantClient } from '@vtex/api'\nimport { any, startsWith } from 'ramda'\n\nimport { MultipleSitemapGenerationError } from './errors'\nimport { GENERATE_SITEMAP_EVENT } from './middlewares/generateMiddlewares/utils'\n\nexport const CONFIG_BUCKET = `${LINKED ? 'linked' : ''}configuration`\nexport const CONFIG_FILE = 'config.json'\nexport const GENERATION_CONFIG_FILE = 'generation.json'\nexport const CUSTOM_ROUTES_GENERATION_FILE = 'customRoutesGeneration.json'\nexport const EXTENDED_INDEX_FILE = 'extendedIndex.json'\nexport const MAX_CALL_STACK_SIZE = 1000\n\nexport const CUSTOM_ROUTES_BUCKET = 'custom-routes'\nexport const CUSTOM_ROUTES_FILENAME = 'custom-routes.json'\nexport const CUSTOM_ROUTES_GENERATION_LOCK_FILENAME = 'generation-lock.json'\n\nexport const TENANT_CACHE_TTL_S = 60 * 10\n\nexport const STORE_PRODUCT = 'vtex-storefront'\n\nconst fiveDaysFromNowMS = () => `${new Date(Date.now() + 5 * 24 * 60 * 60 * 1000)}`\n\nconst validBinding = (path: string) => (binding: Binding) => {\n const isStoreBinding = binding.targetProduct === STORE_PRODUCT\n const matchesPath = any(startsWith(path), [\n binding.canonicalBaseAddress,\n ...binding.alternateBaseAddresses,\n ])\n\n return matchesPath && isStoreBinding\n}\n\nexport const xmlTruncateNodes = ( xml: string[], limit: number = MAX_CALL_STACK_SIZE) =>\n xml.slice(0, limit).join('\\n')\n\nexport const notFound = <T>(fallback: T) => (error: any): T => {\n if (error.response && error.response.status === 404) {\n return fallback\n }\n throw error\n}\n\nexport class SitemapNotFound extends Error {}\n\nexport const SITEMAP_URL = '/sitemap/:path'\n\nexport const getMatchingBindings = async (\n path: string,\n tenant: TenantClient\n) => {\n const pathWithoutWorkspace = path.replace(/^(.)+--/, '')\n const tenantInfo = await tenant.info({\n forceMaxAge: TENANT_CACHE_TTL_S,\n })\n // gets bindings that matches path\n return tenantInfo.bindings.filter(validBinding(pathWithoutWorkspace))\n}\n\nexport const hashString = (str: string) => {\n let hash = 0\n for (let i = 0; i < str.length; i++) {\n hash += (str.charCodeAt(i) * 31) ** (str.length - i)\n // tslint:disable-next-line:no-bitwise\n hash &= hash\n }\n return hash.toString()\n}\n\nexport const getBucket = (prefix: string, bucketName: string) => `${prefix}_${bucketName}`\n\nexport const startSitemapGeneration = async (ctx: Context, force?: boolean) => {\n const { clients: { vbase, events }, vtex: { logger } } = ctx\n const config = await vbase.getJSON<GenerationConfig>(CONFIG_BUCKET, GENERATION_CONFIG_FILE, true)\n if (config && validDate(config.endDate) && !force) {\n throw new MultipleSitemapGenerationError(config.endDate)\n }\n const generationId = (Math.random() * 10000).toString()\n const caller = ctx.request.header['x-vtex-caller']\n logger.info({ message: `New generation started by ${caller}`, generationId })\n await vbase.saveJSON<GenerationConfig>(CONFIG_BUCKET, GENERATION_CONFIG_FILE, {\n endDate: fiveDaysFromNowMS(),\n generationId,\n })\n events.sendEvent('', GENERATE_SITEMAP_EVENT, { generationId })\n}\n\nexport const validDate = (endDate: string) => {\n const date = new Date(endDate)\n if ((date && date <= new Date()) || date.toString() === 'Invalid Date') {\n return false\n }\n return true\n}\n\nexport const getStoreBindings = async (tenant: TenantClient) => {\n const { bindings } = await tenant.info({\n forceMaxAge: TENANT_CACHE_TTL_S,\n })\n const storeBindings = bindings.filter(binding => binding.targetProduct === STORE_PRODUCT)\n return storeBindings\n}\n\n```"
}
] |
code_store-sitemap_99a2c5dc
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-sitemap/node/package.json from the store-sitemap VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"jest\": {\n \"transform\": {\n \"^.+\\\\.tsx?$\": \"ts-jest\"\n },\n \"testMatch\": [\n \"**/__tests__/**/*.(js|ts)?\",\n \"**/?(*.)+(spec|test).(js|ts)\"\n ],\n \"moduleFileExtensions\": [\n \"ts\",\n \"js\"\n ],\n \"setupFiles\": [\n \"<rootDir>/jest/setEnvVars.js\"\n ]\n },\n \"dependencies\": {\n \"apollo-datasource-rest\": \"^0.2.1\",\n \"apollo-server-caching\": \"^0.2.1\",\n \"bluebird\": \"^3.5.0\",\n \"cheerio\": \"^1.0.0-rc.2\",\n \"co-body\": \"^6.0.0\",\n \"graphql\": \"^14.5.8\",\n \"graphql-tools\": \"^4.0.6\",\n \"query-string\": \"^6.12.0\",\n \"ramda\": \"^0.26.1\",\n \"route-parser\": \"^0.0.5\"\n },\n \"devDependencies\": {\n \"@types/bluebird\": \"^3.5.8\",\n \"@types/cheerio\": \"^0.22.8\",\n \"@types/co-body\": \"^0.0.3\",\n \"@types/jest\": \"~25.1.4\",\n \"@types/koa\": \"^2.0.48\",\n \"@types/node\": \"^12.0.0\",\n \"@types/ramda\": \"^0.26.8\",\n \"@types/route-parser\": \"^0.1.2\",\n \"@vtex/api\": \"6.50.1\",\n \"gocommerce.sitemap-app\": \"http://gocommerce.vtexassets.com/_v/public/typings/v1/gocommerce.sitemap-app@1.2.1/public/_types/react\",\n \"jest\": \"^25.1.0\",\n \"ts-jest\": \"^25.2.1\",\n \"tslint\": \"^5.11.0\",\n \"tslint-config-vtex\": \"^2.1.0\",\n \"typemoq\": \"^2.1.0\",\n \"typescript\": \"3.9.7\",\n \"vtex.catalog-api-proxy\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.catalog-api-proxy@0.10.4/public/_types/react\",\n \"vtex.catalog-graphql\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.catalog-graphql@1.103.1/public/@types/vtex.catalog-graphql\",\n \"vtex.graphql-server\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.graphql-server@1.69.0/public/_types/react\",\n \"vtex.messages\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.messages@1.69.0/public/@types/vtex.messages\",\n \"vtex.rewriter\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.rewriter@1.65.1/public/@types/vtex.rewriter\",\n \"vtex.routes-bootstrap\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.routes-bootstrap@0.5.1/public/@types/vtex.routes-bootstrap\",\n \"vtex.store-sitemap\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.store-sitemap@2.16.6/public/@types/vtex.store-sitemap\"\n },\n \"resolutions\": {\n \"**/lodash\": \"^4.17.11\"\n },\n \"scripts\": {\n \"lint\": \"tsc --noEmit --pretty && tslint -c tslint.json --fix './**/*.ts'\",\n \"test\": \"jest\"\n },\n \"version\": \"2.18.3\"\n}\n\n```"
}
] |
code_store-sitemap_1adeaf1a
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-sitemap/node/globals.ts from the store-sitemap VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport {\n Binding,\n EventContext as ColossusEventContext,\n RecorderState,\n ServiceContext,\n} from '@vtex/api'\nimport { Settings } from './middlewares/settings'\n\nimport { Clients } from './clients'\n\ndeclare global {\n interface State extends RecorderState {\n settings: Settings\n enabledIndexFiles: string[]\n platform?: string\n binding: Binding\n bucket: string\n forwardedHost: string\n forwardedPath: string\n rootPath: string\n matchingBindings: Binding[]\n bindingAddress?: string\n isCrossBorder: boolean\n nextEvent: {\n event: string,\n payload: Events\n }\n useLongCacheControl?: boolean\n }\n\n type Context = ServiceContext<Clients, State>\n\n type EventContext = ColossusEventContext<Clients, State>\n\n type Maybe<T> = T | null | undefined\n\n type Middleware = (ctx: Context) => Promise<void>\n\n interface CatalogPageTypeResponse {\n pageType: string\n }\n\n interface Route {\n id: string\n path: string,\n alternates?: AlternateRoute[]\n imagePath?: string\n imageTitle?: string\n }\n\n interface AlternateRoute {\n bindingId: string\n path: string\n }\n\n interface Config {\n productionPrefix: string\n generationPrefix: string\n }\n\n interface GenerationConfig {\n generationId: string\n endDate: string\n }\n\n type Events = RewriterRoutesGenerationEvent | ProductRoutesGenerationEvent | GroupEntriesEvent\n\n interface DefaultEvent {\n generationId: string\n }\n\n interface GroupEntriesEvent extends DefaultEvent {\n indexFile: string\n from: number\n }\n\n interface RewriterRoutesGenerationEvent extends DefaultEvent {\n next: Maybe<string>\n report: Record<string, number>\n count: number\n disableRoutesTerm: string\n }\n\n interface ProductRoutesGenerationEvent extends DefaultEvent {\n page: number\n processedProducts: number\n invalidProducts: number\n }\n\n interface CustomRoutesData {\n timestamp: number\n data: Array<{\n name: string\n routes: string[]\n }>\n }\n}\n\n```"
}
] |
code_store-sitemap_017d02f4
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-sitemap/node/index.ts from the store-sitemap VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport './globals'\n\nimport {\n Cached,\n ClientsConfig,\n LRUCache,\n method,\n MetricsAccumulator,\n ParamsContext,\n Service,\n} from '@vtex/api'\n\nimport { Clients } from './clients'\nimport { Authorization } from './directives/auth'\nimport { binding } from './middlewares/binding'\nimport { cache } from './middlewares/cache'\nimport { errors } from './middlewares/errors'\nimport { generateAppsRoutes } from './middlewares/generateMiddlewares/generateAppsRoutes'\nimport { generateProductRoutes } from './middlewares/generateMiddlewares/generateProductRoutes'\nimport { generateRewriterRoutes } from './middlewares/generateMiddlewares/generateRewriterRoutes'\nimport {\n generateSitemap,\n generateSitemapFromREST,\n} from './middlewares/generateMiddlewares/generateSitemap'\nimport { groupEntries } from './middlewares/generateMiddlewares/groupEntries'\nimport { isCrossBorder } from './middlewares/generateMiddlewares/isCrossBorder'\nimport { prepare as generationPrepare } from './middlewares/generateMiddlewares/prepare'\nimport { sendNextEvent } from './middlewares/generateMiddlewares/sendNextEvent'\nimport { methodNotAllowed } from './middlewares/methods'\nimport { prepare } from './middlewares/prepare'\nimport { robots } from './middlewares/robots'\nimport { settings } from './middlewares/settings'\nimport { sitemap } from './middlewares/sitemap'\nimport { sitemapEntry } from './middlewares/sitemapEntry'\nimport { tenant } from './middlewares/tenant'\nimport { throttle } from './middlewares/throttle'\nimport { resolvers } from './resolvers'\nimport { customRoutes } from './middlewares/customRoutes'\nimport { sitemapErrors } from './middlewares/sitemapErrors'\n\nconst THREE_SECONDS_MS = 3 * 1000\nconst EIGHT_SECOND_MS = 8 * 1000\nconst TEN_SECONDS_MS = 10 * 1000\n\nconst tenantCacheStorage = new LRUCache<string, Cached>({\n max: 3000,\n})\n\nconst vbaseCacheStorage = new LRUCache<string, Cached>({\n max: 3000,\n})\n\nif (!global.metrics) {\n global.metrics = new MetricsAccumulator()\n}\n\nmetrics.trackCache('tenant', tenantCacheStorage)\nmetrics.trackCache('vbase', vbaseCacheStorage)\n\nconst clients: ClientsConfig<Clients> = {\n implementation: Clients,\n options: {\n catalog: {\n timeout: EIGHT_SECOND_MS,\n },\n catalogGraphQL: {\n concurrency: 10,\n },\n default: {\n concurrency: 5,\n retries: 1,\n timeout: THREE_SECONDS_MS,\n },\n events: {\n timeout: EIGHT_SECOND_MS,\n },\n graphqlServer: {\n concurrency: 10,\n retries: 1,\n timeout: EIGHT_SECOND_MS,\n },\n messages: {\n timeout: EIGHT_SECOND_MS,\n },\n rewriter: {\n timeout: TEN_SECONDS_MS,\n },\n tenant: {\n memoryCache: tenantCacheStorage,\n },\n vbase: {\n memoryCache: vbaseCacheStorage,\n retries: 3,\n },\n },\n}\n\nconst sitemapPipeline = [\n sitemapErrors,\n settings,\n isCrossBorder,\n prepare,\n sitemap,\n]\nconst sitemapEntryPipeline = [\n sitemapErrors,\n prepare,\n isCrossBorder,\n sitemapEntry,\n]\n\nexport default new Service<Clients, State, ParamsContext>({\n clients,\n events: {\n /**\n * @deprecated This event is being deprecated. Sitemap generation in this major version will not be triggered by events.\n * Use the `/sitemap/apps-routes` endpoint instead.\n */\n generateAppsRoutes: [\n throttle,\n errors,\n isCrossBorder,\n generationPrepare,\n generateAppsRoutes,\n ],\n /**\n * @deprecated This event is being deprecated. Sitemap generation in this major version will not be triggered by events.\n * Use the REST API endpoints instead.\n */\n generateProductRoutes: [\n throttle,\n errors,\n isCrossBorder,\n generationPrepare,\n tenant,\n generateProductRoutes,\n sendNextEvent,\n ],\n /**\n * @deprecated This event is being deprecated. Sitemap generation in this major version will not be triggered by events.\n * Use the `/sitemap/user-routes` endpoint instead.\n */\n generateRewriterRoutes: [\n throttle,\n errors,\n isCrossBorder,\n generationPrepare,\n generateRewriterRoutes,\n sendNextEvent,\n ],\n /**\n * @deprecated This event is being deprecated. Sitemap generation in this major version will not be triggered by events.\n * Use the REST API endpoints instead.\n */\n generateSitemap: [\n settings,\n isCrossBorder,\n generationPrepare,\n generateSitemap,\n ],\n /**\n * @deprecated This event is being deprecated. Sitemap generation in this major version will not be triggered by events.\n * Use the REST API endpoints instead.\n */\n groupEntries: [\n throttle,\n errors,\n settings,\n isCrossBorder,\n generationPrepare,\n groupEntries,\n sendNextEvent,\n ],\n },\n graphql: {\n resolvers,\n schemaDirectives: {\n requiresAuth: Authorization,\n },\n },\n routes: {\n generateSitemap: generateSitemapFromREST,\n robots: method({\n DEFAULT: methodNotAllowed,\n GET: [cache, binding, robots],\n }),\n sitemap: sitemapPipeline,\n sitemapEntry: sitemapEntryPipeline,\n customRoutes: method({\n GET: [cache, binding, customRoutes],\n }),\n },\n})\n\n```"
}
] |
code_store-sitemap_d167cd51
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-sitemap/node/directives/auth.test.ts from the store-sitemap VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { IOContext, Logger, Sphinx } from '@vtex/api'\nimport * as TypeMoq from 'typemoq'\n\nimport { Clients } from '../clients'\nimport { VtexID } from '../clients/id'\nimport { authFromCookie } from './auth'\n\nconst vtexIDTypeMock = TypeMoq.Mock.ofInstance(VtexID)\nconst SphinxTypeMock = TypeMoq.Mock.ofInstance(Sphinx)\nconst contextMock = TypeMoq.Mock.ofType<Context>()\nconst ioContext = TypeMoq.Mock.ofType<IOContext>()\nconst state = TypeMoq.Mock.ofType<State>()\nconst loggerMock = TypeMoq.Mock.ofType<Logger>()\n\ndescribe('Test auth directive code', () => {\n let context: Context\n\n const vtexID = class VtexIDMock extends vtexIDTypeMock.object {\n constructor() {\n super(ioContext.object)\n }\n\n public getIdUser = async (_: string, token: string) => {\n switch (token) {\n case '1':\n return { user: 'email@test.com' }\n case '2':\n return { user: 'email2@test.com' }\n case '3':\n return { user: 'email@vtex.com' }\n default:\n return {}\n }\n }\n }\n\n // tslint:disable-next-line:max-classes-per-file\n const sphinx = class SphinxMock extends SphinxTypeMock.object {\n constructor() {\n super(ioContext.object)\n }\n\n public isAdmin = async (email: string) => {\n switch (email) {\n case 'email@test.com':\n return true\n default:\n return false\n }\n }\n }\n\n beforeEach(() => {\n // tslint:disable-next-line: max-classes-per-file\n const ClientsImpl = class ClientsMock extends Clients {\n get vtexID() {\n return this.getOrSet('vtexID', vtexID)\n }\n\n get sphinx() {\n return this.getOrSet('sphinx', sphinx)\n }\n }\n const cookies: Record<string, string> = { 'VtexIdclientAutCookie': '1' }\n\n context = {\n ...contextMock.object,\n clients: new ClientsImpl({}, ioContext.object),\n cookies: {\n get: (key: string) => cookies[key],\n } as any,\n state: {\n ...state.object,\n },\n vtex: {\n ...ioContext.object,\n authToken: '3',\n logger: loggerMock.object,\n },\n }\n\n })\n\n it('Should authorize vtex email', async () => {\n const authrorized = await authFromCookie(context)\n expect(authrorized).toBe(true)\n })\n\n it('Should throw error when VtexIdclientAutCookie is not found', async () => {\n context.cookies = {\n get: (_: string) => undefined,\n } as any\n const authorized = await authFromCookie(context)\n expect(authorized).toBe('VtexIdclientAutCookie not found.')\n })\n\n it('Should throw error when user is not found', async () => {\n context.vtex.authToken = '4'\n const authorized = await authFromCookie(context)\n expect(authorized).toBe('Could not find user specified by token.')\n })\n\n it('Should throw error if user is not admin', async () => {\n context.vtex.authToken = '2'\n const authorized = await authFromCookie(context)\n expect(authorized).toBe('User is not admin and can not access resource.')\n })\n it('Should authorize admins', async () => {\n context.vtex.authToken = '1'\n const authorized = await authFromCookie(context)\n expect(authorized).toBe(true)\n })\n})\n\n```"
}
] |
code_store-sitemap_72f0e4ae
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-sitemap/node/directives/auth.ts from the store-sitemap VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { defaultFieldResolver, GraphQLField } from 'graphql'\nimport { SchemaDirectiveVisitor } from 'graphql-tools'\n\nconst canBypass = (email: string) => {\n return email.includes('@vtex.com')\n}\n\nexport const authFromCookie = async (ctx: Context) => {\n const {\n clients: { sphinx, vtexID },\n vtex: { authToken },\n } = ctx\n\n const vtexIdToken = ctx.cookies.get('VtexIdclientAutCookie')\n if (!vtexIdToken) {\n return 'VtexIdclientAutCookie not found.'\n }\n\n const { user: email } =\n (await vtexID.getIdUser(vtexIdToken, authToken)) || { user: '' }\n if (!email) {\n return 'Could not find user specified by token.'\n }\n\n if (canBypass(email)) {\n return true\n }\n\n const isAdminUser = await sphinx.isAdmin(email)\n if (!isAdminUser) {\n return 'User is not admin and can not access resource.'\n }\n\n return true\n}\n\nexport class Authorization extends SchemaDirectiveVisitor {\n public visitFieldDefinition(field: GraphQLField<any, any>) {\n const { resolve = defaultFieldResolver } = field\n field.resolve = async (root, args, ctx, info) => {\n const cookieAllowsAccess = await authFromCookie(ctx)\n\n if (cookieAllowsAccess !== true) {\n throw new Error(cookieAllowsAccess)\n }\n\n return resolve(root, args, ctx, info)\n }\n }\n}\n\n```"
}
] |
code_store-sitemap_37b2f8e8
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-sitemap/node/clients/robots.ts from the store-sitemap VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { ExternalClient, InstanceOptions, IOContext } from '@vtex/api'\n\nexport class Robots extends ExternalClient {\n constructor (context: IOContext, options?: InstanceOptions) {\n super('http://janus-edge.vtex.com.br', context, options)\n }\n\n public fromLegacy = (account: string) => this.http.get<string>(`/robots.txt?an=${account}`)\n}\n\n```"
}
] |
code_store-sitemap_1cd519ec
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-sitemap/node/clients/messages.ts from the store-sitemap VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { MessagesGraphQL } from '@vtex/api'\nimport { Query, TranslateArgs } from 'vtex.messages'\n\ninterface Response {\n translate: Query['translate']\n}\n\ninterface Variables {\n args: TranslateArgs\n}\n\nexport class Messages extends MessagesGraphQL {\n public async translateNoCache(args: TranslateArgs) {\n const response = await this.graphql.query<Response, Variables>(\n {\n query: `query Translate($args: TranslateArgs!) {\n translate(args: $args)\n }`,\n variables: { args },\n },\n {\n headers: {\n 'cache-control': 'no-cache',\n },\n metric: 'messages-translate-v2',\n }\n )\n return response.data!.translate as string[]\n }\n}\n\n```"
}
] |
code_store-sitemap_a87f58e4
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-sitemap/node/clients/graphqlServer.ts from the store-sitemap VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport {\n AppClient,\n GraphQLClient,\n InstanceOptions,\n IOContext,\n} from '@vtex/api'\nimport { any } from 'ramda'\n\n\nexport class ProductNotFound extends Error {\n public graphQLErrors: any\n\n constructor(graphQLErrors: any[]) {\n super()\n this.graphQLErrors = graphQLErrors\n }\n}\n\nconst handleNotFoundErrror = (error: any) => {\n if (error.graphQLErrors && error.graphQLErrors.length === 1) {\n const hasNotFounError = any((err: any )=> err.message.startsWith('No product was found'), error.graphQLErrors)\n if (hasNotFounError) {\n throw new ProductNotFound(error.graphQLErrors)\n }\n }\n\n throw error\n}\n\n// tslint:disable-next-line:max-classes-per-file\nexport class GraphQLServer extends AppClient {\n protected graphql: GraphQLClient\n\n constructor(ctx: IOContext, opts?: InstanceOptions) {\n super('vtex.graphql-server@1.x', ctx, opts)\n this.graphql = new GraphQLClient(this.http)\n }\n\n public query = async (query: string, variables: any, extensions: any) => {\n return this.graphql.query(\n {\n extensions,\n query,\n variables,\n },\n {\n params: {\n locale: this.context.locale,\n },\n url: '/graphql',\n }\n ).catch(err => handleNotFoundErrror(err))\n }\n}\n\n```"
}
] |
code_store-sitemap_ac33029a
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-sitemap/node/clients/vbase.ts from the store-sitemap VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { ConflictsResolver, inflightURL, InstanceOptions, IOContext, IOResponse, RequestTracingConfig, VBase } from '@vtex/api'\nimport { AxiosError } from 'axios'\n\ninterface Headers { [key: string]: string | number }\nconst appId = process.env.VTEX_APP_ID\nconst [runningAppName] = appId ? appId.split('@') : ['']\n\nconst routes = {\n Bucket: (bucket: string) => `/buckets/${runningAppName}/${bucket}`,\n File: (bucket: string, path: string) => `${routes.Bucket(bucket)}/files/${path}`,\n}\n\nexport class CVBase extends VBase {\n constructor (context: IOContext, options?: InstanceOptions) {\n super(context, options)\n }\n\n public getRawJSON = <T>(bucket: string, path: string, nullIfNotFound?: boolean, conflictsResolver?: ConflictsResolver<T>, tracingConfig?: RequestTracingConfig) => {\n const headers: Headers = { 'Cache-Control': 'no-cache' }\n if (conflictsResolver) {\n headers['X-Vtex-Detect-Conflicts'] = 'true'\n }\n const inflightKey = inflightURL\n const metric = 'vbase-get-json'\n return this.http.getRaw<T>(routes.File(bucket, path), {\n headers, inflightKey, metric, nullIfNotFound, tracing: {\n requestSpanNameSuffix: metric,\n ...tracingConfig?.tracing,\n },\n })\n .catch(async (error: AxiosError<T>) => {\n const { response } = error\n if (response && response.status === 409 && conflictsResolver) {\n return { ...response, data: await conflictsResolver.resolve() } as IOResponse<T>\n }\n throw error\n })\n }\n}\n\n```"
}
] |
code_store-sitemap_f07205ae
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-sitemap/node/clients/rewriter.ts from the store-sitemap VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { AppGraphQLClient, InstanceOptions, IOContext } from '@vtex/api'\nimport {\n EntityLocator,\n Internal,\n ListInternalsResponse,\n RoutesByBinding,\n} from 'vtex.rewriter'\n\nconst MAX_RETRIES = 3\nconst RETRY_DELAY_MS = 2000\n\nexport class Rewriter extends AppGraphQLClient {\n constructor(ctx: IOContext, opts?: InstanceOptions) {\n super('vtex.rewriter@1.x', ctx, opts)\n }\n\n public listInternals = (\n limit: number,\n next: Maybe<string>\n ): Promise<ListInternalsResponse> =>\n this.graphql\n .query<\n { internal: { listInternals: { next: string; routes: Internal[] } } },\n { next: Maybe<string>; limit: number }\n >(\n {\n query: `\n query ListInternals($limit: Int, $next: String) {\n internal {\n listInternals(limit: $limit, next: $next) {\n routes {\n binding\n from\n type\n endDate\n imagePath\n imageTitle\n id\n disableSitemapEntry\n }\n next\n }\n }\n }\n `,\n variables: { limit, next },\n },\n {\n headers: {\n 'cache-control': 'no-cache',\n },\n metric: 'rewriter-get-internals',\n }\n )\n .then(res => res.data?.internal?.listInternals) as Promise<\n ListInternalsResponse\n >\n\n /**\n * List internals with automatic retry on timeout errors.\n *\n * Wraps listInternals with retry logic that:\n * - Detects timeout-specific error messages and codes\n * - Preserves the pagination cursor across retries\n * - Uses exponential backoff (2s, 4s, 6s)\n * - Logs retry attempts if logger is available\n * - Maximum of 3 retry attempts\n *\n * @param limit - Maximum number of results per request\n * @param cursor - Pagination cursor (preserved across retries)\n * @param retryCount - Internal retry counter (do not set manually)\n * @returns Promise resolving to ListInternalsResponse\n * @throws Original error if not a timeout or max retries exceeded\n */\n public listInternalsWithRetry = async (\n limit: number,\n cursor: Maybe<string>,\n retryCount = 0\n ): Promise<ListInternalsResponse> => {\n try {\n return await this.listInternals(limit, cursor)\n } catch (error) {\n if (retryCount < MAX_RETRIES) {\n const delay = RETRY_DELAY_MS * (retryCount + 1) // Exponential backoff\n\n // Log warning if logger is available in context\n if (this.context?.logger) {\n this.context.logger.warn({\n message: 'listInternals error, retrying',\n attempt: retryCount + 1,\n maxRetries: MAX_RETRIES,\n delayMs: delay,\n cursor: cursor ?? 'initial',\n error: error?.message,\n })\n }\n\n // Wait before retrying\n await new Promise(resolve => setTimeout(resolve, delay))\n\n // Retry with the same cursor\n return this.listInternalsWithRetry(limit, cursor, retryCount + 1)\n }\n\n // Max retries reached, throw the error\n throw error\n }\n }\n\n public routesById = (locator: EntityLocator): Promise<RoutesByBinding[]> =>\n this.graphql\n .query<\n { internal: { routes: RoutesByBinding[] } },\n { locator: EntityLocator }\n >(\n {\n query: `\n query Routes($locator: EntityLocator!) {\n internal {\n routes(locator: $locator) {\n route\n binding\n }\n }\n }\n `,\n variables: { locator },\n },\n {\n metric: 'rewriter-get-internals',\n }\n )\n .then(res => res.data?.internal?.routes) as Promise<RoutesByBinding[]>\n}\n\n```"
}
] |
code_store-sitemap_6b6f4751
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-sitemap/node/clients/index.ts from the store-sitemap VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { IOClients, Sphinx, VBase } from '@vtex/api'\n\nimport { Catalog } from './catalog'\nimport { GraphQLServer } from './graphqlServer'\nimport { VtexID } from './id'\nimport { Messages } from './messages'\nimport { Rewriter } from './rewriter'\nimport { Robots } from './robots'\nimport { RobotsGC } from './robotsGC'\nimport { CVBase } from './vbase'\n\nexport class Clients extends IOClients {\n public get vbase() {\n return this.getOrSet('vbase', CVBase)\n }\n\n public get vbaseWithCache() {\n return this.getOrSet('vbaseWithCache', VBase)\n }\n\n public get robots() {\n return this.getOrSet('robots', Robots)\n }\n\n public get robotsGC() {\n return this.getOrSet('robotsGC', RobotsGC)\n }\n\n public get rewriter() {\n return this.getOrSet('rewriter', Rewriter)\n }\n\n get catalog() {\n return this.getOrSet('catalog', Catalog)\n }\n\n get messages() {\n return this.getOrSet('messages', Messages)\n }\n\n public get graphqlServer(): GraphQLServer {\n return this.getOrSet('graphqlServer', GraphQLServer)\n }\n\n public get vtexID() {\n return this.getOrSet('vtexID', VtexID)\n }\n\n public get sphinx() {\n return this.getOrSet('sphinx', Sphinx)\n }\n\n}\n\n```"
}
] |
code_store-sitemap_19e75dfb
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-sitemap/node/clients/robotsGC.ts from the store-sitemap VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { AppClient, InstanceOptions, IOContext } from '@vtex/api'\n\nexport class RobotsGC extends AppClient {\n constructor (context: IOContext, options?: InstanceOptions) {\n super(`gocommerce.sitemap-app`, context, options)\n }\n\n public fromLegacy = (account: string) => this.http.get<string>(`/robots.txt?an=${account}`)\n}\n\n```"
}
] |
code_store-sitemap_d32119a3
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-sitemap/node/clients/id.ts from the store-sitemap VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { ExternalClient, InstanceOptions, IOContext } from '@vtex/api'\n\nconst userAgent = process.env.VTEX_APP_ID!\n\nexport class VtexID extends ExternalClient {\n public constructor(context: IOContext, options?: InstanceOptions) {\n super('http://vtexid.vtex.com.br/api/vtexid', context, options)\n }\n\n public getIdUser = (token: string, authToken: string) =>\n this.http.get(`pub/authenticated/user`, {\n headers: {\n Accept: 'application/json',\n Authorization: authToken,\n 'Content-Type': 'application/json',\n 'User-Agent': userAgent,\n 'X-VTEX-Proxy-To': 'https://vtexid.vtex.com.br',\n 'X-Vtex-Use-Https': true,\n },\n metric: 'vtexid-authtoken',\n params: {\n authToken: token,\n },\n })\n}\n\n```"
}
] |
code_store-sitemap_2f7fedc2
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-sitemap/node/clients/catalog.ts from the store-sitemap VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport {\n ExternalClient,\n FORWARDED_HOST_HEADER,\n InstanceOptions,\n IOContext,\n} from '@vtex/api'\n\nimport { CatalogSitemapError } from '../errors/CatalogSitemapError'\n\nexport interface GetProductsAndSkuIdsReponse {\n items: number[]\n paging: {\n total: number\n page: number\n perPage: number\n pages: number\n }\n}\n\nconst PAGE_SIZE = 100\n\nexport class Catalog extends ExternalClient {\n constructor(protected context: IOContext, options?: InstanceOptions) {\n super(`http://${context.account}.vtexcommercestable.com.br`, context, {\n ...(options ?? {}),\n headers: {\n ...(options?.headers ?? {}),\n 'Content-Type': 'application/json',\n VtexIdclientAutCookie: context.authToken,\n 'X-Vtex-Use-Https': 'true',\n },\n })\n }\n\n public getProductsIds(\n page: number,\n salesChannels?: string[]\n ): Promise<GetProductsAndSkuIdsReponse> {\n return this.http.get('/api/catalog_system/pvt/products/GetProductsIds', {\n params: {\n ...(salesChannels ? { SalesChannelId: salesChannels.join(',') } : {}),\n Active: true,\n Page: page,\n pageSize: PAGE_SIZE,\n },\n })\n }\n\n public async getSitemap(host: string, path = 'sitemap.xml') {\n try {\n return await this.http.get(path, {\n headers: {\n [FORWARDED_HOST_HEADER]: host,\n },\n })\n } catch (error) {\n throw new CatalogSitemapError(\n `Failed to fetch catalog sitemap: ${error.message}`,\n error\n )\n }\n }\n}\n\n```"
}
] |
code_store-sitemap_c9a2ede1
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-sitemap/node/resources/bindings.ts from the store-sitemap VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { Binding, PUBLIC_DOMAINS, Tenant } from '@vtex/api'\nimport { TENANT_CACHE_TTL_S } from '../utils'\n\nexport interface BindingDiscoveryResult {\n binding: Binding | null\n tenant: Tenant | null\n}\n\ninterface BindingDiscoveryOptions {\n tenantCacheTTL?: number\n}\n\nconst TEN_MINUTES_S = 10 * 60\n\nconst defaultOptions: BindingDiscoveryOptions = {\n tenantCacheTTL: TEN_MINUTES_S,\n}\n\nconst ensureEndingSlash = (address: string) => {\n return address.endsWith('/') ? address : `${address}/`\n}\n\nconst getStoreBinding = (bindings: Binding[]) => {\n const storeBinding = bindings.find(b => b.targetProduct === 'vtex-storefront')\n if (!storeBinding) {\n throw new Error('No binding found')\n }\n return storeBinding\n}\n\n\nexport const getDefaultStoreBinding = async (ctx: Context) => {\n const {\n clients: { tenant },\n } = ctx\n\n const { bindings = [] } = await tenant.info({\n forceMaxAge: TENANT_CACHE_TTL_S,\n })\n const defaultStoreBinding = getStoreBinding(bindings)\n return defaultStoreBinding.id\n}\n\nexport class BindingResolver {\n constructor(private options: BindingDiscoveryOptions = defaultOptions) {}\n\n public async discover(ctx: Context): Promise<Binding> {\n const {\n clients: { tenant: tenantClient },\n vtex: { account },\n } = ctx\n\n const tenantInfo = await tenantClient\n .info({\n forceMaxAge: this.options.tenantCacheTTL,\n nullIfNotFound: true,\n params: {\n q: account,\n },\n })\n\n const matchingBinding = this.resolve(ctx, tenantInfo.bindings)\n\n return matchingBinding\n }\n\n protected findMatchingBinding(\n account: string,\n hostAndPath: string,\n bindings: Binding[]\n ): Binding | null {\n const matching = bindings.reduce((currentWinner, candidate) => {\n const { canonicalBaseAddress, alternateBaseAddresses } = candidate\n const allCandidateAddresses = [\n canonicalBaseAddress,\n ...alternateBaseAddresses,\n ...PUBLIC_DOMAINS.map(\n domain => `${account}.${domain}/${canonicalBaseAddress}`\n ),\n ].map(ensureEndingSlash)\n const allMatchingAddress = allCandidateAddresses.filter(address =>\n hostAndPath.startsWith(address)\n )\n if (allMatchingAddress.length === 0) {\n return currentWinner\n }\n\n const [bestMatchingAddress] =\n allMatchingAddress.length === 1\n ? allMatchingAddress\n : allMatchingAddress.sort(\n (addressA, addressB) => addressB.length - addressA.length\n )\n\n const currentWinnerScore = currentWinner?.matchingAddress.length ?? 0\n\n return bestMatchingAddress.length > currentWinnerScore\n ? { matchingAddress: bestMatchingAddress, binding: candidate }\n : currentWinner\n }, null as { binding: Binding; matchingAddress: string } | null)\n\n return matching?.binding ?? null\n }\n\n protected mountHostAndPath(ctx: Context): string {\n const {\n vtex: { account, workspace },\n } = ctx\n const workspacePrefix = `${workspace}--`\n const rootPath = ctx.get('x-vtex-root-path')\n const forwardedHost = ctx.get('x-forwarded-host')\n const forwardedPath = ctx.get('x-forwarded-path')\n const isInternalPublicDomain = PUBLIC_DOMAINS.some(domain =>\n forwardedHost.endsWith(`${account}.${domain}`)\n )\n const bindingPath = isInternalPublicDomain\n ? this.toBindingPath(forwardedPath)\n : this.toBindingPath(rootPath)\n const resolvedHost =\n isInternalPublicDomain && forwardedHost.startsWith(workspacePrefix)\n ? forwardedHost.replace(`${workspace}--`, '')\n : forwardedHost\n return `${resolvedHost}${bindingPath}`\n }\n\n protected toBindingPath(path?: string): string {\n let resultPath = path?.split('?')[0] ?? '/'\n if (!resultPath.startsWith('/')) {\n resultPath = `/${resultPath}`\n }\n\n if (!resultPath.endsWith('/')) {\n resultPath += '/'\n }\n\n return resultPath\n }\n\n private resolve(ctx: Context, bindings: Binding[]): Binding {\n const {\n vtex: { account, binding, logger },\n query: { __bindingAddress, __bindingId },\n } = ctx\n const bindingId = binding?.id ?? __bindingId\n if (bindingId) {\n return this.getBindingById(bindingId, bindings)\n }\n\n if (__bindingAddress) {\n return this.getBindingByAddress(__bindingAddress, bindings)\n }\n\n const hostAndPath = this.mountHostAndPath(ctx)\n const matching = this.findMatchingBinding(account, hostAndPath, bindings)\n if (matching) {\n return matching\n }\n\n logger.warn({\n headers: ctx.request.headers,\n message: 'No binding found, falling back to the first store binding',\n })\n return getStoreBinding(bindings)\n }\n\n private getBindingById(bindingId: string, bindings: Binding[]): Binding {\n const binding = bindings.find(item => item.id === bindingId)\n if (!binding) {\n throw new Error(`Unable to find binding for id ${bindingId}`)\n }\n\n return binding\n }\n\n private getBindingByAddress(\n bindindAddress: string,\n bindings: Binding[]\n ): Binding {\n const binding = bindings.find(\n item => item.canonicalBaseAddress === bindindAddress\n )\n if (!binding) {\n throw new Error(`Unable to find binding for address ${bindindAddress}`)\n }\n\n return binding\n }\n}\n\n```"
}
] |
code_store-sitemap_02da358a
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-sitemap/node/middlewares/robots.ts from the store-sitemap VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { Apps } from '@vtex/api'\n\nimport { notFound } from '../utils'\n\nconst TEN_MINUTES_S = 10 * 60\n\ninterface RobotsFile {\n robots: Record<string, string>\n}\n\nconst SITEMAP_BUILD_FILE = 'dist/vtex.store-sitemap/build.json'\n\nconst getRobotForBinding = async (\n bindingId: string,\n account: string,\n apps: Apps\n) => {\n const appId = `${account}.robots@0.x`\n\n try {\n await apps.getApp(appId)\n } catch (err) {\n notFound(undefined)(err)\n }\n\n const buildFile = await apps.getAppJSON<Partial<RobotsFile> | null>(\n appId,\n SITEMAP_BUILD_FILE,\n true\n )\n\n return buildFile?.robots?.[bindingId]\n}\n\nexport async function robots(ctx: Context) {\n const {\n vtex: { account, production, platform },\n state: { binding },\n } = ctx\n\n let data: string | undefined\n\n const { clients } = ctx\n const robotsDataSource =\n platform === 'gocommerce' ? clients.robotsGC : clients.robots\n\n if (binding?.id) {\n data = await getRobotForBinding(binding.id, account, clients.apps)\n }\n if (!data || !binding?.id) {\n data = await robotsDataSource.fromLegacy(account)\n }\n\n ctx.set('Content-Type', 'text/plain')\n ctx.body = data\n ctx.status = 200\n ctx.set(\n 'cache-control',\n production ? `public, max-age=${TEN_MINUTES_S}` : 'no-cache'\n )\n}\n\n```"
}
] |
code_store-sitemap_dbb36ebf
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-sitemap/node/middlewares/prepare.ts from the store-sitemap VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { parse } from 'query-string'\n\nimport { BindingResolver } from '../resources/bindings'\nimport { CONFIG_BUCKET, CONFIG_FILE, getBucket, getMatchingBindings, hashString, startSitemapGeneration } from '../utils'\nimport { DEFAULT_CONFIG } from './generateMiddlewares/utils'\n\nconst ONE_DAY_S = 24 * 60 * 60\nconst FORWARDED_HOST_HEADER = 'x-forwarded-host'\nconst VTEX_ROOT_PATH_HEADER = 'x-vtex-root-path'\n\nexport async function prepare(ctx: Context, next: () => Promise<void>) {\n const {\n vtex: { production },\n clients: { vbase, tenant },\n } = ctx\n const forwardedHost = ctx.get('x-forwarded-host')\n let rootPath = ctx.get('x-vtex-root-path')\n // Defend against malformed root path. It should always start with `/`.\n if (rootPath && !rootPath.startsWith('/')) {\n rootPath = `/${rootPath}`\n }\n if (rootPath === '/') {\n rootPath = ''\n }\n const [forwardedPath, queryString] = ctx.get('x-forwarded-path').split('?')\n const matchingBindings = await getMatchingBindings(forwardedHost, tenant)\n const bindingResolver = new BindingResolver()\n const binding = await bindingResolver.discover(ctx)\n if (!binding) {\n throw new Error(`Binding from context not found`)\n }\n\n const query = parse(queryString)\n\n const { productionPrefix } = await vbase.getJSON<Config>(CONFIG_BUCKET, CONFIG_FILE, true) || DEFAULT_CONFIG\n\n const bucket = getBucket(productionPrefix, hashString(binding.id))\n\n ctx.state = {\n ...ctx.state,\n binding,\n bindingAddress: query.__bindingAddress as string | undefined,\n bucket,\n forwardedHost,\n forwardedPath,\n matchingBindings,\n rootPath,\n }\n\n await next()\n\n ctx.set('Content-Type', 'text/xml')\n ctx.status = 200\n ctx.set(\n 'cache-control',\n production ? `public, max-age=${ONE_DAY_S}` : 'no-cache'\n )\n if (production) {\n startSitemapGeneration(ctx)\n }\n ctx.vary(FORWARDED_HOST_HEADER)\n ctx.vary(VTEX_ROOT_PATH_HEADER)\n\n return\n}\n\n```"
}
] |
code_store-sitemap_1c638273
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-sitemap/node/middlewares/throttle.ts from the store-sitemap VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { TooManyRequestsError } from '@vtex/api'\nimport { sleep } from './generateMiddlewares/utils'\n\nconst MAX_REQUEST = 4\nlet COUNTER = 0\n\nexport async function throttle(\n _: EventContext,\n next: () => Promise<void>\n) {\n COUNTER++\n try {\n if (COUNTER > MAX_REQUEST) {\n const timeToSleep = Math.ceil(Math.random() * 100)\n await sleep(timeToSleep)\n throw new TooManyRequestsError()\n }\n await next()\n } finally {\n COUNTER--\n }\n}\n\n```"
}
] |
code_store-sitemap_a3adbc56
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-sitemap/node/middlewares/binding.ts from the store-sitemap VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { BindingResolver } from '../resources/bindings'\n\nexport async function binding(ctx: Context, next: () => Promise<any>) {\n const bindingResolver = new BindingResolver()\n ctx.state.binding = await bindingResolver.discover(ctx)\n await next()\n}\n\n```"
}
] |
code_store-sitemap_062e0c28
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-sitemap/node/middlewares/sitemapEntry.test.ts from the store-sitemap VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { Binding, IOContext, Logger, VBase } from '@vtex/api'\nimport * as TypeMoq from 'typemoq'\n\nimport { Clients } from '../clients'\nimport { sitemapEntry, URLEntry } from './sitemapEntry'\n\nconst vbaseTypeMock = TypeMoq.Mock.ofInstance(VBase)\nconst contextMock = TypeMoq.Mock.ofType<Context>()\nconst ioContext = TypeMoq.Mock.ofType<IOContext>()\nconst state = TypeMoq.Mock.ofType<State>()\nconst loggerMock = TypeMoq.Mock.ofType<Logger>()\n\nconst removeSpaces = (str: string) => str.replace(/(\\r\\n|\\n|\\r|\\s)/gm, '')\n\ndescribe('Test sitemap entry', () => {\n let context: Context\n\n\n const vbase = class VBaseMock extends vbaseTypeMock.object {\n constructor() {\n super(ioContext.object)\n }\n\n public getJSON = async <T>(\n _: string,\n file: string,\n __?: boolean | undefined\n ): Promise<T> => {\n switch (file) {\n case 'file1':\n return {\n lastUpdated: '2019-12-04',\n routes: [\n {\n id: 1,\n path: '/banana',\n },\n {\n id: 1,\n imagePath: 'image',\n imageTitle: 'title',\n path: '/watermelon',\n },\n ],\n } as unknown as T\n default:\n return null as unknown as T\n }\n }\n }\n\n // tslint:disable-next-line:no-empty\n const next = async (): Promise<void> => {\n }\n\n const defaultRoute: Route = {\n id: '2',\n path: '/pear',\n }\n\n const defaultLastUpdated = '2019-12-04'\n\n beforeEach(() => {\n // tslint:disable-next-line: max-classes-per-file\n const ClientsImpl = class ClientsMock extends Clients {\n get vbase() {\n return this.getOrSet('vbase', vbase)\n }\n }\n\n context = {\n ...contextMock.object,\n clients: new ClientsImpl({}, ioContext.object),\n state: {\n ...state.object,\n binding: {\n id: '1',\n } as Binding,\n bucket: 'bucket',\n forwardedHost: 'host.com',\n forwardedPath: '/sitemap/file1.xml',\n matchingBindings: [\n {\n canonicalBaseAddress: 'www.host.com',\n defaultLocale: 'en-US',\n id: '1',\n },\n {\n canonicalBaseAddress: 'www.host.com/br',\n defaultLocale: 'pt-BR',\n id: '2',\n },\n {\n canonicalBaseAddress: 'www.host.com/de',\n defaultLocale: 'de-DE',\n id: '3',\n },\n ] as Binding[],\n rootPath: '',\n },\n vtex: {\n ...ioContext.object,\n logger: loggerMock.object,\n },\n }\n })\n\n it('Should return 404 when entry is not found', async () => {\n const thisContext = {\n ...context,\n state: {\n ...context.state,\n forwardedPath: '/sitemap/not-existent-file.xml',\n },\n }\n await sitemapEntry(thisContext, next)\n expect(thisContext.status).toStrictEqual(404)\n })\n\n it('Should return 404 when url does not match', async () => {\n const thisContext = {\n ...context,\n state: {\n ...context.state,\n forwardedPath: '/not-sitemap/not-existent-file.xml',\n },\n }\n await sitemapEntry(thisContext, next).catch(_ => null)\n expect(thisContext.status).toStrictEqual(404)\n })\n\n it('Should create corrects sitemap entries', async () => {\n await sitemapEntry(context, next)\n expect(removeSpaces(context.body)).toStrictEqual(removeSpaces(\n `<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\" xmlns:xhtml=\"http://www.w3.org/1999/xhtml\">\n <url>\n <loc>https://host.com/banana</loc>\n <lastmod>2019-12-04</lastmod>\n </url><url>\n <image:image>\n <image:loc>image</image:loc>\n <image:title>title</image:title>\n </image:image>\n\n <loc>https://host.com/watermelon</loc>\n <lastmod>2019-12-04</lastmod>\n </url>\n </urlset>`\n ))\n })\n\n it('Should create a correct sitemap entry with localization', async () => {\n const alternates: AlternateRoute[] = [\n {\n bindingId: '1',\n path: '/pear',\n },\n {\n bindingId: '2',\n path: '/pera',\n },\n {\n bindingId: '3',\n path: '/brine',\n },\n ]\n const route: Route = {\n ...defaultRoute,\n alternates,\n }\n const entry = URLEntry(context, route, defaultLastUpdated)\n expect(removeSpaces(entry)).toStrictEqual(removeSpaces(\n `<url>\n <loc>https://host.com/pear</loc>\n <xhtml:link rel=\"alternate\" hreflang=\"pt-BR\" href=\"https://www.host.com/br/pera\"/>\n <xhtml:link rel=\"alternate\" hreflang=\"de-DE\" href=\"https://www.host.com/de/brine\"/>\n <lastmod>2019-12-04</lastmod>\n </url>`\n ))\n })\n\n it('Should create a correct sitemap entry with localization with binding address querystring', async () => {\n const alternates: AlternateRoute[] = [\n {\n bindingId: '1',\n path: '/pear',\n },\n {\n bindingId: '2',\n path: '/pera',\n },\n {\n bindingId: '3',\n path: '/brine',\n },\n ]\n const route: Route = {\n ...defaultRoute,\n alternates,\n }\n const thisContext = {\n ...context,\n state: {\n ...context.state,\n bindingAddress: 'www.host.com/es',\n },\n }\n const entry = URLEntry(thisContext, route, defaultLastUpdated)\n expect(removeSpaces(entry)).toStrictEqual(removeSpaces(\n `<url>\n <loc>https://host.com/pear?__bindingAddress=www.host.com/es</loc>\n <xhtml:link rel=\"alternate\" hreflang=\"pt-BR\" href=\"https://host.com/pera?__bindingAddress=www.host.com/br\"/>\n <xhtml:link rel=\"alternate\" hreflang=\"de-DE\" href=\"https://host.com/brine?__bindingAddress=www.host.com/de\"/>\n <lastmod>2019-12-04</lastmod>\n </url>`\n ))\n })\n\n it('Should create a correct sitemap entry with root path', async () => {\n const thisContext = {\n ...context,\n state: {\n ...context.state,\n rootPath: '/es',\n },\n }\n const entry = URLEntry(thisContext, defaultRoute, defaultLastUpdated)\n expect(removeSpaces(entry)).toStrictEqual(removeSpaces(\n `<url>\n <loc>https://host.com/es/pear</loc>\n <lastmod>2019-12-04</lastmod>\n </url>`\n ))\n })\n\n it('Should create a correct sitemap entry with binding adress querystring', async () => {\n const thisContext = {\n ...context,\n state: {\n ...context.state,\n bindingAddress: 'www.host.com/es',\n },\n }\n const entry = URLEntry(thisContext, defaultRoute, defaultLastUpdated)\n expect(removeSpaces(entry)).toStrictEqual(removeSpaces(\n `<url>\n <loc>https://host.com/pear?__bindingAddress=www.host.com/es</loc>\n <lastmod>2019-12-04</lastmod>\n </url>`\n ))\n })\n\n it('Should create a correct sitemap entry with image path and title', async () => {\n const route: Route = {\n ...defaultRoute,\n imagePath: 'image',\n imageTitle: 'title',\n }\n const entry = URLEntry(context, route, defaultLastUpdated)\n expect(removeSpaces(entry)).toStrictEqual(removeSpaces(\n `<url>\n <image:image>\n <image:loc>image</image:loc>\n <image:title>title</image:title>\n </image:image>\n <loc>https://host.com/pear</loc>\n <lastmod>2019-12-04</lastmod>\n </url>`\n ))\n })\n})\n\n```"
}
] |
code_store-sitemap_b10354ae
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-sitemap/node/middlewares/errors.ts from the store-sitemap VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { TooManyRequestsError } from '@vtex/api'\nimport { any } from 'ramda'\n\nconst ERROR_429 = 'E_HTTP_429'\n\nconst isTooManyRequestError = (error: any) => {\n // Checks if has one error and it is the TooManyRequestError\n if (error.graphQLErrors && error.graphQLErrors.length === 1) {\n return any((err: any )=> err.extensions?.exception?.code === ERROR_429 , error.graphQLErrors)\n }\n return false\n}\n\nexport async function errors(_: EventContext, next: () => Promise<void>) {\n try {\n await next()\n } catch (error) {\n if (isTooManyRequestError(error)) {\n throw new TooManyRequestsError()\n }\n throw error\n }\n}\n\n```"
}
] |
code_store-sitemap_1de8cf06
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-sitemap/node/middlewares/sitemapErrors.ts from the store-sitemap VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { CatalogSitemapError } from '../errors/CatalogSitemapError'\n\n/**\n * Error handling middleware specifically for sitemap pipelines.\n * Catches errors and returns appropriate HTTP responses with proper content types\n * instead of allowing errors to bubble up and potentially return XML error content.\n */\nexport async function sitemapErrors(ctx: Context, next: () => Promise<void>) {\n try {\n await next()\n } catch (error) {\n const {\n vtex: { logger },\n } = ctx\n\n // Log the error for debugging\n logger.error({\n message: 'Sitemap pipeline error',\n payload: {\n error: error.message,\n method: ctx.method,\n path: ctx.path,\n stack: error.stack,\n ...(error instanceof CatalogSitemapError && {\n statusCode: error.statusCode,\n originalError: error.originalError?.message,\n }),\n },\n })\n\n // Set content type to text/plain to ensure browsers handle it properly\n ctx.type = 'text/plain; charset=utf-8'\n\n if (error instanceof CatalogSitemapError) {\n // Use the actual HTTP status code from the catalog API response\n ctx.status = error.statusCode\n ctx.body = 'Error fetching sitemap data'\n return\n }\n\n // Default error handling for unknown errors\n ctx.status = 500\n ctx.body = 'Internal Server Error'\n }\n}\n\n```"
}
] |
code_store-sitemap_3dbf5096
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-sitemap/node/middlewares/settings.ts from the store-sitemap VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { appIdToAppAtMajor } from '@vtex/api'\nimport {\n APPS_ROUTES_INDEX,\n PRODUCT_ROUTES_INDEX,\n REWRITER_ROUTES_INDEX,\n} from './generateMiddlewares/utils'\n\nexport interface Settings {\n enableAppsRoutes: boolean\n enableProductRoutes: boolean\n enableNavigationRoutes: boolean\n ignoreBindings: boolean\n disableRoutesTerm: string\n}\n\nconst VTEX_APP_ID = process.env.VTEX_APP_ID!\nconst VTEX_APP_AT_MAJOR = appIdToAppAtMajor(VTEX_APP_ID)\n\nconst DEFAULT_SETTINGS = {\n disableRoutesTerm: '',\n enableAppsRoutes: true,\n enableNavigationRoutes: true,\n enableProductRoutes: true,\n ignoreBindings: false,\n}\n\nconst INDEX_MAP = {\n disableRoutesTerm: '',\n enableAppsRoutes: APPS_ROUTES_INDEX,\n enableNavigationRoutes: REWRITER_ROUTES_INDEX,\n enableProductRoutes: PRODUCT_ROUTES_INDEX,\n ignoreBindings: '',\n}\n\nexport async function settings(\n ctx: Context | EventContext,\n next: () => Promise<void>\n) {\n const {\n clients: { apps },\n } = ctx\n\n const appSettings: Settings = {\n ...DEFAULT_SETTINGS,\n ...(await apps.getAppSettings(VTEX_APP_AT_MAJOR)),\n }\n const keys = Object.keys(appSettings) as Array<keyof Settings>\n const enabledIndexFiles = keys.reduce((acc, key) => {\n if (appSettings[key] && INDEX_MAP[key]) {\n acc.push(INDEX_MAP[key])\n }\n return acc\n }, [] as string[])\n\n ctx.state = {\n ...ctx.state,\n enabledIndexFiles,\n settings: appSettings,\n }\n\n await next()\n}\n\n```"
}
] |
code_store-sitemap_9325f9c7
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-sitemap/node/middlewares/sitemap.test.ts from the store-sitemap VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { Binding, IOContext, Logger, VBase } from '@vtex/api'\nimport * as TypeMoq from 'typemoq'\n\nimport {\n APPS_ROUTES_INDEX,\n PRODUCT_ROUTES_INDEX,\n REWRITER_ROUTES_INDEX,\n} from './generateMiddlewares/utils'\n\nimport { Clients } from '../clients'\nimport { EXTENDED_INDEX_FILE } from '../utils'\nimport { sitemap } from './sitemap'\n\nconst vbaseTypeMock = TypeMoq.Mock.ofInstance(VBase)\nconst contextMock = TypeMoq.Mock.ofType<Context>()\nconst ioContext = TypeMoq.Mock.ofType<IOContext>()\nconst state = TypeMoq.Mock.ofType<State>()\nconst loggerMock = TypeMoq.Mock.ofType<Logger>()\n\nconst removeSpaces = (str: string) => str.replace(/(\\r\\n|\\n|\\r|\\s)/gm, '')\n\ndescribe('Test sitemap middleware', () => {\n let context: Context\n let hasExtendedFiles: boolean\n\n const vbase = class VBaseMock extends vbaseTypeMock.object {\n constructor() {\n super(ioContext.object)\n }\n\n public getJSON = async <T>(\n _: string,\n file: string,\n __?: boolean | undefined\n ): Promise<T> => {\n switch (file) {\n case APPS_ROUTES_INDEX:\n return ({\n index: ['appsRoutes-0'],\n lastUpdated: '2019-12-04',\n } as unknown) as T\n case REWRITER_ROUTES_INDEX:\n return ({\n index: ['brand-0', 'department-0'],\n lastUpdated: '2019-12-04',\n } as unknown) as T\n case PRODUCT_ROUTES_INDEX:\n return ({\n index: ['product-0'],\n lastUpdated: '2019-12-04',\n } as unknown) as T\n case EXTENDED_INDEX_FILE:\n return ((hasExtendedFiles\n ? {\n index: ['extra-0'],\n lastUpdated: '2019-12-04',\n }\n : null) as unknown) as T\n default:\n return (null as unknown) as T\n }\n }\n }\n\n const next = jest.fn()\n\n const matchingBindings = [\n {\n canonicalBaseAddress: 'www.host.com',\n defaultLocale: 'en-US',\n id: '1',\n },\n {\n canonicalBaseAddress: 'www.host.com/br',\n defaultLocale: 'pt-BR',\n id: '2',\n },\n {\n canonicalBaseAddress: 'www.host.com/de',\n defaultLocale: 'de-DE',\n id: '3',\n },\n ] as Binding[]\n\n beforeEach(() => {\n // tslint:disable-next-line: max-classes-per-file\n const ClientsImpl = class ClientsMock extends Clients {\n get vbase() {\n return this.getOrSet('vbase', vbase)\n }\n }\n\n hasExtendedFiles = false\n context = {\n ...contextMock.object,\n clients: new ClientsImpl({}, ioContext.object),\n state: {\n ...state.object,\n binding: {\n id: '1',\n } as Binding,\n bucket: 'bucket',\n enabledIndexFiles: [\n APPS_ROUTES_INDEX,\n REWRITER_ROUTES_INDEX,\n PRODUCT_ROUTES_INDEX,\n ],\n forwardedHost: 'www.host.com',\n forwardedPath: '/sitemap/file1.xml',\n matchingBindings: [matchingBindings[0]],\n rootPath: '',\n settings: {\n disableRoutesTerm: '',\n enableAppsRoutes: true,\n enableNavigationRoutes: true,\n enableProductRoutes: true,\n ignoreBindings: false,\n },\n },\n vtex: {\n ...ioContext.object,\n logger: loggerMock.object,\n },\n }\n })\n\n it('Should return binding index if it has multiple bindings', async () => {\n const thisContext = {\n ...context,\n state: {\n ...context.state,\n matchingBindings,\n },\n }\n await sitemap(thisContext, next)\n expect(\n thisContext.body.includes(\n '<loc>https://www.host.com/sitemap.xml?__bindingAddress=www.host.com</loc>'\n )\n ).toBeTruthy()\n expect(\n thisContext.body.includes(\n '<loc>https://www.host.com/sitemap.xml?__bindingAddress=www.host.com/br</loc>'\n )\n ).toBeTruthy()\n expect(\n thisContext.body.includes(\n '<loc>https://www.host.com/sitemap.xml?__bindingAddress=www.host.com/de</loc>'\n )\n ).toBeTruthy()\n })\n\n it('Should return binding index with canonical if it has multiple bindings in production', async () => {\n const thisContext = {\n ...context,\n state: {\n ...context.state,\n matchingBindings,\n },\n vtex: {\n ...context.vtex,\n production: true,\n },\n }\n\n await sitemap(thisContext, next)\n expect(\n thisContext.body.includes('<loc>https://www.host.com/sitemap.xml</loc>')\n ).toBeTruthy()\n expect(\n thisContext.body.includes(\n '<loc>https://www.host.com/br/sitemap.xml</loc>'\n )\n ).toBeTruthy()\n expect(\n thisContext.body.includes(\n '<loc>https://www.host.com/de/sitemap.xml</loc>'\n )\n ).toBeTruthy()\n })\n\n it('Should return index if it doesnt have multiple bindings', async () => {\n await sitemap(context, next)\n expect(removeSpaces(context.body)).toStrictEqual(\n removeSpaces(\n `<sitemapindex xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">\n <sitemap>\n <loc>https://www.host.com/sitemap/appsRoutes-0.xml</loc>\n <lastmod>2019-12-04</lastmod>\n </sitemap>\n <sitemap>\n <loc>https://www.host.com/sitemap/brand-0.xml</loc>\n <lastmod>2019-12-04</lastmod>\n </sitemap>\n <sitemap>\n <loc>https://www.host.com/sitemap/department-0.xml</loc>\n <lastmod>2019-12-04</lastmod>\n </sitemap>\n <sitemap>\n <loc>https://www.host.com/sitemap/product-0.xml</loc>\n <lastmod>2019-12-04</lastmod>\n </sitemap>\n </sitemapindex>`\n )\n )\n })\n\n it('Should return only enabled index', async () => {\n context.state.enabledIndexFiles = [APPS_ROUTES_INDEX, PRODUCT_ROUTES_INDEX]\n await sitemap(context, next)\n expect(removeSpaces(context.body)).toStrictEqual(\n removeSpaces(\n `<sitemapindex xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">\n <sitemap>\n <loc>https://www.host.com/sitemap/appsRoutes-0.xml</loc>\n <lastmod>2019-12-04</lastmod>\n </sitemap>\n <sitemap>\n <loc>https://www.host.com/sitemap/product-0.xml</loc>\n <lastmod>2019-12-04</lastmod>\n </sitemap>\n </sitemapindex>`\n )\n )\n\n context.state.enabledIndexFiles = [\n REWRITER_ROUTES_INDEX,\n 'non-existant-index',\n ]\n await sitemap(context, next)\n expect(removeSpaces(context.body)).toStrictEqual(\n removeSpaces(\n `<sitemapindex xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">\n <sitemap>\n <loc>https://www.host.com/sitemap/brand-0.xml</loc>\n <lastmod>2019-12-04</lastmod>\n </sitemap>\n <sitemap>\n <loc>https://www.host.com/sitemap/department-0.xml</loc>\n <lastmod>2019-12-04</lastmod>\n </sitemap>\n </sitemapindex>`\n )\n )\n })\n\n it('Should return binding index with bindingAddress', async () => {\n const thisContext = {\n ...context,\n state: {\n ...context.state,\n bindingAddress: 'www.host.com/en',\n },\n }\n await sitemap(thisContext, next)\n expect(removeSpaces(thisContext.body)).toStrictEqual(\n removeSpaces(\n `<sitemapindex xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">\n <sitemap>\n <loc>https://www.host.com/sitemap/appsRoutes-0.xml?__bindingAddress=www.host.com/en</loc>\n <lastmod>2019-12-04</lastmod>\n </sitemap>\n <sitemap>\n <loc>https://www.host.com/sitemap/brand-0.xml?__bindingAddress=www.host.com/en</loc>\n <lastmod>2019-12-04</lastmod>\n </sitemap>\n <sitemap>\n <loc>https://www.host.com/sitemap/department-0.xml?__bindingAddress=www.host.com/en</loc>\n <lastmod>2019-12-04</lastmod>\n </sitemap>\n <sitemap>\n <loc>https://www.host.com/sitemap/product-0.xml?__bindingAddress=www.host.com/en</loc>\n <lastmod>2019-12-04</lastmod>\n </sitemap>\n </sitemapindex>`\n )\n )\n })\n\n it('Should return bindinig index with rootPath', async () => {\n const thisContext = {\n ...context,\n state: {\n ...context.state,\n rootPath: '/en',\n },\n }\n await sitemap(thisContext, next)\n expect(removeSpaces(thisContext.body)).toStrictEqual(\n removeSpaces(\n `<sitemapindex xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">\n <sitemap>\n <loc>https://www.host.com/en/sitemap/appsRoutes-0.xml</loc>\n <lastmod>2019-12-04</lastmod>\n </sitemap>\n <sitemap>\n <loc>https://www.host.com/en/sitemap/brand-0.xml</loc>\n <lastmod>2019-12-04</lastmod>\n </sitemap>\n <sitemap>\n <loc>https://www.host.com/en/sitemap/department-0.xml</loc>\n <lastmod>2019-12-04</lastmod>\n </sitemap>\n <sitemap>\n <loc>https://www.host.com/en/sitemap/product-0.xml</loc>\n <lastmod>2019-12-04</lastmod>\n </sitemap>\n </sitemapindex>`\n )\n )\n })\n\n it('Should return extra index if any', async () => {\n hasExtendedFiles = true\n await sitemap(context, next)\n expect(removeSpaces(context.body)).toStrictEqual(\n removeSpaces(\n `<sitemapindex xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">\n <sitemap>\n <loc>https://www.host.com/sitemap/appsRoutes-0.xml</loc>\n <lastmod>2019-12-04</lastmod>\n </sitemap>\n <sitemap>\n <loc>https://www.host.com/sitemap/brand-0.xml</loc>\n <lastmod>2019-12-04</lastmod>\n </sitemap>\n <sitemap>\n <loc>https://www.host.com/sitemap/department-0.xml</loc>\n <lastmod>2019-12-04</lastmod>\n </sitemap>\n <sitemap>\n <loc>https://www.host.com/sitemap/product-0.xml</loc>\n <lastmod>2019-12-04</lastmod>\n </sitemap>\n <sitemap>\n <loc>https://www.host.com/sitemap/extra-0.xml</loc>\n <lastmod>2019-12-04</lastmod>\n </sitemap>\n </sitemapindex>`\n )\n )\n })\n})\n\n```"
}
] |
code_store-sitemap_d90d2e28
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-sitemap/node/middlewares/settings.test.ts from the store-sitemap VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { Apps, IOContext, Logger, RequestTracingConfig } from '@vtex/api'\nimport * as TypeMoq from 'typemoq'\n\nimport { Clients } from '../clients'\nimport { APPS_ROUTES_INDEX, PRODUCT_ROUTES_INDEX, REWRITER_ROUTES_INDEX } from './generateMiddlewares/utils'\nimport { settings } from './settings'\n\nconst appsTypeMock = TypeMoq.Mock.ofInstance(Apps)\nconst contextMock = TypeMoq.Mock.ofType<Context>()\nconst ioContext = TypeMoq.Mock.ofType<IOContext>()\nconst state = TypeMoq.Mock.ofType<State>()\nconst loggerMock = TypeMoq.Mock.ofType<Logger>()\n\ndescribe('Test settings middleware', () => {\n let context: Context\n\n const apps = class AppsMock extends appsTypeMock.object {\n public settings = {\n enableAppsRoutes: true,\n enableNavigationRoutes: true,\n enableProductRoutes: true,\n }\n\n constructor() {\n super(ioContext.object)\n }\n\n public getAppSettings = async (_: string, __?: RequestTracingConfig) => this.settings\n }\n\n const next = jest.fn()\n\n beforeEach(() => {\n // tslint:disable-next-line: max-classes-per-file\n const ClientsImpl = class ClientsMock extends Clients {\n get apps() {\n return this.getOrSet('apps', apps)\n }\n }\n\n context = {\n ...contextMock.object,\n clients: new ClientsImpl({}, ioContext.object),\n state: {\n ...state.object,\n },\n vtex: {\n ...ioContext.object,\n logger: loggerMock.object,\n },\n }\n })\n\n it('Should get correct apps index files', async () => {\n await settings(context, next)\n expect(context.state.enabledIndexFiles).toStrictEqual([APPS_ROUTES_INDEX, REWRITER_ROUTES_INDEX, PRODUCT_ROUTES_INDEX])\n\n let appClient = context.clients.apps as any\n appClient.settings = {\n enableAppsRoutes: true,\n enableNavigationRoutes: true,\n enableProductRoutes: false,\n }\n await settings(context, next)\n expect(context.state.enabledIndexFiles).toStrictEqual([APPS_ROUTES_INDEX, REWRITER_ROUTES_INDEX])\n\n appClient = context.clients.apps as any\n appClient.settings = {\n enableAppsRoutes: false,\n enableNavigationRoutes: false,\n enableProductRoutes: true,\n }\n await settings(context, next)\n expect(context.state.enabledIndexFiles).toStrictEqual([PRODUCT_ROUTES_INDEX])\n\n appClient = context.clients.apps as any\n appClient.settings = {\n enableAppsRoutes: false,\n enableNavigationRoutes: false,\n enableProductRoutes: false,\n }\n await settings(context, next)\n expect(context.state.enabledIndexFiles).toStrictEqual([])\n })\n})\n\n```"
}
] |
code_store-sitemap_acaa10d9
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-sitemap/node/middlewares/cache.ts from the store-sitemap VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { endsWith } from 'ramda'\n\nconst TEN_SECONDS_S = 10\nconst TEN_MINUTES_S = 10 * 60\nconst FIVE_MINUTES_S = 5 * 60\nconst THIRTY_SECONDS = 30\nconst TEN_SECONDS = 10\nconst TWENTY_HOURS = 20 * 60 * 60\nconst ONE_DAY = 24 * 60 * 60\n\nconst publicEndpoint = `.${process.env.VTEX_PUBLIC_ENDPOINT ?? 'myvtex.com'}`\n\nconst isPrivateHost = (host: string) => endsWith(publicEndpoint, host)\n\nconst from0To30 = () => Math.round(Math.random() * 30)\n\nexport async function cache(ctx: Context, next: () => Promise<void>) {\n const {\n vtex: { production, logger },\n request: {\n headers: { 'x-forwarded-host': originalHost },\n },\n query: { __disableSSR: disableSSR },\n } = ctx\n\n try {\n await next()\n } catch (err) {\n logger.error(err)\n ctx.body =\n ctx.body || `Something exploded: operationId=${ctx.vtex.operationId}`\n ctx.status = 500\n } finally {\n const shouldCache = 200 <= ctx.status && ctx.status < 300 && production\n const maxAge = isPrivateHost(originalHost ?? '')\n ? TEN_SECONDS\n : THIRTY_SECONDS + from0To30()\n\n if (shouldCache) {\n if (ctx.state.useLongCacheControl) {\n ctx.set(\n 'cache-control',\n `public, max-age=${TWENTY_HOURS}, stale-while-revalidate=${ONE_DAY}`\n )\n } else {\n ctx.set(\n 'cache-control',\n `public, max-age=${maxAge}, stale-while-revalidate=${TEN_SECONDS_S}, stale-if-error=${TEN_MINUTES_S}`\n )\n }\n } else {\n ctx.set('cache-control', 'no-store, no-cache')\n }\n\n if (!disableSSR) {\n ctx.set('x-vtex-etag-control', `public, max-age=${FIVE_MINUTES_S}`)\n }\n }\n}\n\n```"
}
] |
code_store-sitemap_22fd453d
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-sitemap/node/middlewares/sitemap.ts from the store-sitemap VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport * as cheerio from 'cheerio'\n\nimport { MultipleSitemapGenerationError } from '../errors'\nimport {\n EXTENDED_INDEX_FILE,\n xmlTruncateNodes,\n getBucket,\n hashString,\n SitemapNotFound,\n startSitemapGeneration,\n} from '../utils'\nimport { currentDate, SitemapIndex } from './generateMiddlewares/utils'\n\nconst sitemapIndexEntry = (\n forwardedHost: string,\n rootPath: string,\n entry: string,\n lastUpdated: string,\n bindingAddress?: string\n) => {\n const querystring = bindingAddress\n ? `?__bindingAddress=${bindingAddress}`\n : ''\n return `<sitemap>\n <loc>https://${forwardedHost}${rootPath}/sitemap/${entry}.xml${querystring}</loc>\n <lastmod>${lastUpdated}</lastmod>\n </sitemap>`\n}\n\nconst sitemapBindingEntry = (\n host: string,\n lastUpdated: string,\n bindingAddress?: string\n) => {\n const querystring = bindingAddress\n ? `?__bindingAddress=${bindingAddress}`\n : ''\n return `<sitemap>\n <loc>https://${host}/sitemap.xml${querystring}</loc>\n <lastmod>${lastUpdated}</lastmod>\n </sitemap>`\n}\n\nconst sitemapIndex = async (ctx: Context) => {\n const {\n state: {\n enabledIndexFiles,\n forwardedHost,\n binding,\n bucket,\n rootPath,\n bindingAddress,\n },\n clients: { vbase },\n } = ctx\n\n const $ = cheerio.load(\n '<sitemapindex xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">',\n {\n xmlMode: true,\n }\n )\n\n const rawIndexFiles = await Promise.all([\n ...enabledIndexFiles.map(indexFile =>\n vbase.getJSON<SitemapIndex>(bucket, indexFile, true)\n ),\n vbase.getJSON<SitemapIndex>(\n getBucket('', hashString(binding.id)),\n EXTENDED_INDEX_FILE,\n true\n ),\n ])\n\n const indexFiles = rawIndexFiles.filter(Boolean)\n\n if (indexFiles.length === 0) {\n throw new SitemapNotFound('Sitemap not found')\n }\n\n const index = [\n ...new Set(\n indexFiles.reduce(\n (acc, { index: fileIndex }) => acc.concat(fileIndex),\n [] as string[]\n )\n ),\n ]\n\n const lastUpdated = indexFiles[0].lastUpdated\n\n const indexXML = index.map(entry =>\n sitemapIndexEntry(\n forwardedHost,\n rootPath,\n entry,\n lastUpdated,\n bindingAddress\n )\n )\n $('sitemapindex').append(xmlTruncateNodes(indexXML))\n return $\n}\n\nconst sitemapBindingIndex = async (ctx: Context) => {\n const {\n state: { forwardedHost, matchingBindings: bindings },\n vtex: { production },\n } = ctx\n\n const $ = cheerio.load(\n '<sitemapindex xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">',\n {\n xmlMode: true,\n }\n )\n\n const date = currentDate()\n const bindingsIndexXML = bindings.map(binding =>\n sitemapBindingEntry(\n production ? binding.canonicalBaseAddress : forwardedHost,\n date,\n production ? '' : binding.canonicalBaseAddress\n )\n )\n $('sitemapindex').append(xmlTruncateNodes(bindingsIndexXML))\n return $\n}\n\nexport async function sitemap(ctx: Context, next: () => Promise<void>) {\n const {\n state: { isCrossBorder },\n } = ctx\n\n if (isCrossBorder) {\n await legacySitemap(ctx)\n } else {\n await catalogSitemap(ctx)\n }\n\n next()\n}\n\nasync function legacySitemap(ctx: Context) {\n const {\n state: {\n isCrossBorder,\n matchingBindings,\n bindingAddress,\n rootPath,\n settings,\n },\n vtex: { logger },\n } = ctx\n\n logger.info({\n message: 'Fetching legacy sitemap',\n payload: {\n isCrossBorder,\n matchingBindings,\n bindingAddress,\n rootPath,\n ignoreBindings: settings.ignoreBindings,\n },\n })\n\n const hasBindingIdentifier = rootPath || bindingAddress\n let $: any\n try {\n if (hasBindingIdentifier || settings.ignoreBindings) {\n $ = await sitemapIndex(ctx)\n } else {\n const hasMultipleMatchingBindings = matchingBindings.length > 1\n $ = hasMultipleMatchingBindings\n ? await sitemapBindingIndex(ctx)\n : await sitemapIndex(ctx)\n }\n } catch (err) {\n if (err instanceof SitemapNotFound) {\n ctx.status = 404\n ctx.body = 'Generating sitemap...'\n ctx.vtex.logger.error(err.message)\n await startSitemapGeneration(ctx).catch(err => {\n if (!(err instanceof MultipleSitemapGenerationError)) {\n throw err\n }\n })\n }\n throw err\n }\n\n ctx.body = $.xml()\n}\n\nasync function catalogSitemap(ctx: Context) {\n const {\n clients: { catalog },\n headers: { 'x-forwarded-host': forwardedHost },\n state: { isCrossBorder, forwardedPath },\n vtex: { logger },\n } = ctx\n\n logger.info({\n message: 'Fetching catalog sitemap',\n payload: {\n forwardedHost,\n forwardedPath,\n isCrossBorder,\n },\n })\n\n const sitemapData = await catalog.getSitemap(forwardedHost, forwardedPath)\n ctx.body = sitemapData\n}\n\n```"
}
] |
code_store-sitemap_1416a127
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-sitemap/node/middlewares/sitemapEntry.ts from the store-sitemap VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { Binding } from '@vtex/api'\nimport * as cheerio from 'cheerio'\nimport RouteParser from 'route-parser'\n\nimport { SITEMAP_URL } from '../utils'\nimport { SitemapEntry } from './generateMiddlewares/utils'\n\nconst getBinding = (bindingId: string, bindings: Binding[]) =>\n bindings.find(binding => binding.id === bindingId)\n\nexport const URLEntry = (\n ctx: Context,\n route: Route,\n lastUpdated: string\n): string => {\n const { state: {\n binding,\n bindingAddress,\n forwardedHost,\n rootPath,\n matchingBindings,\n },\n } = ctx\n const querystring = bindingAddress\n ? `?__bindingAddress=${bindingAddress}`\n : ''\n const loc = `https://${forwardedHost}${rootPath}${route.path}${querystring}`\n const localization = route.alternates && route.alternates.length > 1\n ? route.alternates.map(\n ({ bindingId, path }) => {\n const alternateBinding = getBinding(bindingId, matchingBindings)\n if (bindingId === binding.id || !alternateBinding) {\n return ''\n }\n const { canonicalBaseAddress, defaultLocale: locale } = alternateBinding\n const href = querystring\n ? `https://${forwardedHost}${path}?__bindingAddress=${canonicalBaseAddress}`\n : `https://${canonicalBaseAddress}${path}`\n return `<xhtml:link rel=\"alternate\" hreflang=\"${locale}\" href=\"${href}\"/>`\n }\n )\n .join('\\n')\n : ''\n let entry = `\n <loc>${loc}</loc>\n ${localization}\n <lastmod>${lastUpdated}</lastmod>\n `\n if (route.imagePath && route.imageTitle) {\n // add image metainfo\n entry = `\n <image:image>\n <image:loc>${route.imagePath}</image:loc>\n <image:title>${route.imageTitle}</image:title>\n </image:image>\n ${entry}`\n }\n return `<url>${entry}</url>`\n}\n\nexport async function sitemapEntry(ctx: Context, next: () => Promise<void>) {\n const {\n state: { isCrossBorder },\n } = ctx\n\n if (!isCrossBorder) {\n await catalogSitemapEntry(ctx)\n } else {\n await legacySitemapEntry(ctx)\n next()\n }\n}\n\nasync function legacySitemapEntry(ctx: Context) {\n const {\n clients: { vbase },\n state: { forwardedPath, bucket },\n vtex: { logger },\n } = ctx\n\n const sitemapRoute = new RouteParser(SITEMAP_URL)\n const sitemapParams = sitemapRoute.match(forwardedPath)\n\n logger.info({\n message: 'Fetching legacy sitemap entry',\n payload: {\n forwardedPath,\n bucket,\n },\n })\n\n if (!sitemapParams) {\n ctx.status = 404\n ctx.body = `Sitemap not found the URL must be: ${SITEMAP_URL}`\n throw new Error(`URL differs from the expected, ${forwardedPath}`)\n }\n\n const { path } = sitemapParams\n\n const $: any = cheerio.load(\n '<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\" xmlns:xhtml=\"http://www.w3.org/1999/xhtml\">',\n {\n xmlMode: true,\n }\n )\n\n const fileName = path.split('.')[0]\n const maybeRoutesInfo = await vbase.getJSON<SitemapEntry>(\n bucket,\n fileName,\n true\n )\n\n if (!maybeRoutesInfo) {\n ctx.status = 404\n ctx.body = 'Sitemap entry not found'\n ctx.vtex.logger.error({\n message: 'Sitemap entry not found',\n payload: {\n bucket,\n fileName,\n },\n })\n\n return\n }\n\n const { routes, lastUpdated } = maybeRoutesInfo as SitemapEntry\n const entryXML = routes.map((route: Route) =>\n URLEntry(ctx, route, lastUpdated)\n )\n\n $('urlset').append(entryXML.join('\\n'))\n\n ctx.body = $.xml()\n}\n\nasync function catalogSitemapEntry(ctx: Context) {\n const {\n clients: { catalog },\n headers: { 'x-forwarded-host': forwardedHost },\n state: { forwardedPath },\n vtex: { logger },\n } = ctx\n\n logger.info({\n message: 'Fetching catalog sitemap entry',\n payload: {\n forwardedHost,\n forwardedPath,\n },\n })\n\n ctx.body = await catalog.getSitemap(forwardedHost, forwardedPath)\n ctx.status = 200\n}\n\n```"
}
] |
code_store-sitemap_61279bf6
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-sitemap/node/middlewares/customRoutes.ts from the store-sitemap VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { Logger, VBase } from '@vtex/api'\n\nimport { MultipleCustomRoutesGenerationError } from '../errors'\nimport { generateCustomRoutes } from './generateMiddlewares/generateCustomRoutes'\nimport {\n CONFIG_BUCKET,\n CUSTOM_ROUTES_BUCKET,\n CUSTOM_ROUTES_FILENAME,\n CUSTOM_ROUTES_GENERATION_LOCK_FILENAME,\n validDate,\n} from '../utils'\n\nconst ONE_DAY_MS = 24 * 60 * 60 * 1000\nconst TWENTY_THREE_HOURS_MS = 23 * 60 * 60 * 1000\n\nconst twentyThreeHoursFromNowMS = () =>\n `${new Date(Date.now() + TWENTY_THREE_HOURS_MS)}`\n\nconst metricsConfig = {\n customRoutes: {\n failed: 'customRoutes-failed',\n success: 'customRoutes-success',\n cached: 'customRoutes-cached',\n notFound: 'customRoutes-notFound',\n generating: 'customRoutes-generating',\n },\n}\n\nconst startCustomRoutesGeneration = async (ctx: Context) => {\n const {\n clients: { vbase },\n vtex: { logger, account },\n } = ctx\n\n logger.info({\n message: 'Checking for existing custom routes generation lock',\n type: 'custom-routes-lock-check',\n lockFile: CUSTOM_ROUTES_GENERATION_LOCK_FILENAME,\n bucket: CONFIG_BUCKET,\n })\n\n const lockFile = await vbase.getJSON<GenerationConfig>(\n CONFIG_BUCKET,\n CUSTOM_ROUTES_GENERATION_LOCK_FILENAME,\n true\n )\n\n if (lockFile && validDate(lockFile.endDate)) {\n logger.warn({\n message: 'Custom routes generation lock found - generation skipped',\n type: 'custom-routes-lock-found',\n existingGenerationId: lockFile.generationId,\n lockExpiresAt: lockFile.endDate,\n lockFile: CUSTOM_ROUTES_GENERATION_LOCK_FILENAME,\n })\n throw new MultipleCustomRoutesGenerationError(lockFile.endDate, account)\n }\n\n if (lockFile) {\n logger.info({\n message: 'Lock found but expired - proceeding with generation',\n type: 'custom-routes-lock-expired',\n expiredLock: lockFile,\n })\n } else {\n logger.info({\n message: 'No lock found - proceeding with generation',\n type: 'custom-routes-no-lock',\n lockFile: CUSTOM_ROUTES_GENERATION_LOCK_FILENAME,\n })\n }\n\n const generationId = (Math.random() * 10000).toString()\n const caller = ctx.request?.header?.['x-vtex-caller'] || 'unknown'\n const endDate = twentyThreeHoursFromNowMS()\n\n logger.info({\n message: `Custom routes generation started by ${caller}`,\n type: 'custom-routes-generation-started',\n generationId,\n caller,\n lockExpiresAt: endDate,\n })\n\n try {\n await vbase.saveJSON<GenerationConfig>(\n CONFIG_BUCKET,\n CUSTOM_ROUTES_GENERATION_LOCK_FILENAME,\n {\n endDate,\n generationId,\n }\n )\n } catch (error) {\n throw error\n }\n\n logger.info({\n message: 'Generation lock file created',\n type: 'custom-routes-lock-created',\n lockFile: CUSTOM_ROUTES_GENERATION_LOCK_FILENAME,\n generationId,\n expiresAt: endDate,\n })\n\n // Execute generation in background - don't await\n generateCustomRoutes(ctx).catch(error => {\n logger.error({\n message: 'Background custom routes generation failed',\n type: 'custom-routes-background-error',\n generationId,\n error,\n })\n })\n\n logger.info({\n message: 'Custom routes generation started in background',\n type: 'custom-routes-background-started',\n generationId,\n })\n}\n\nexport const clearCustomRoutesGenerationLock = async (\n vbase: VBase,\n logger: Logger\n) => {\n logger.info({\n message: 'Attempting to clear custom routes generation lock',\n type: 'custom-routes-lock-clear-attempt',\n lockFile: CUSTOM_ROUTES_GENERATION_LOCK_FILENAME,\n bucket: CONFIG_BUCKET,\n })\n\n try {\n await vbase.deleteFile(\n CONFIG_BUCKET,\n CUSTOM_ROUTES_GENERATION_LOCK_FILENAME\n )\n logger.info({\n message: 'Custom routes generation lock cleared successfully',\n type: 'custom-routes-lock-cleared',\n lockFile: CUSTOM_ROUTES_GENERATION_LOCK_FILENAME,\n })\n } catch (error) {\n // File might not exist, ignore error but log it\n logger.info({\n message: 'Lock file not found or already cleared',\n type: 'custom-routes-lock-clear-skipped',\n lockFile: CUSTOM_ROUTES_GENERATION_LOCK_FILENAME,\n error: error.message || error,\n })\n }\n}\n\nasync function triggerCustomRoutesGeneration(ctx: Context) {\n const {\n vtex: { logger },\n } = ctx\n\n try {\n await startCustomRoutesGeneration(ctx)\n logger.info({\n message: 'Custom routes generation event triggered',\n type: 'custom-routes-trigger',\n })\n } catch (error) {\n if (error instanceof MultipleCustomRoutesGenerationError) {\n logger.info({\n message: 'Custom routes generation already in progress',\n type: 'custom-routes-already-generating',\n })\n throw error\n }\n logger.error({\n message: 'Failed to trigger custom routes generation',\n error,\n type: 'custom-routes-trigger-error',\n })\n throw error\n }\n}\n\nexport async function customRoutes(ctx: Context, next: () => Promise<void>) {\n const startTime = process.hrtime()\n\n const {\n vtex: { logger },\n clients: { vbase },\n } = ctx\n\n try {\n // Get pre-compiled custom routes from VBase\n const cachedData = await vbase.getJSON<CustomRoutesData>(\n CUSTOM_ROUTES_BUCKET,\n CUSTOM_ROUTES_FILENAME,\n true\n )\n\n if (!cachedData) {\n // No cached data exists - trigger generation and return 404\n logger.info({\n message: 'No cached custom routes found, triggering generation',\n type: 'custom-routes-not-found',\n fileName: CUSTOM_ROUTES_FILENAME,\n })\n\n try {\n await triggerCustomRoutesGeneration(ctx)\n\n ctx.status = 404\n ctx.body = {\n message:\n 'Custom routes not available. Generation has been triggered.',\n }\n\n const diffTime = process.hrtime(startTime)\n metrics.batch(metricsConfig.customRoutes.notFound, diffTime)\n logger.info({\n type: metricsConfig.customRoutes.notFound,\n })\n } catch (error) {\n if (error instanceof MultipleCustomRoutesGenerationError) {\n // Generation already in progress - return 404\n ctx.status = 404\n ctx.body = {\n message: error.message,\n }\n\n const diffTime = process.hrtime(startTime)\n metrics.batch(metricsConfig.customRoutes.generating, diffTime)\n logger.info({\n type: metricsConfig.customRoutes.generating,\n })\n } else {\n throw error\n }\n }\n\n await next()\n return\n }\n\n // Check if data is older than 1 day\n const dataAge = Date.now() - cachedData.timestamp\n const isOld = dataAge >= ONE_DAY_MS\n\n if (isOld) {\n // Data exists but is old - trigger regeneration in background\n logger.info({\n message: 'Cached custom routes are old, triggering regeneration',\n type: 'custom-routes-stale',\n ageInHours: Math.floor(dataAge / (60 * 60 * 1000)),\n })\n\n // Fire and forget - don't await\n triggerCustomRoutesGeneration(ctx)\n }\n\n // Return cached data\n ctx.status = 200\n ctx.body = cachedData.data\n ctx.state.useLongCacheControl = true\n\n const diffTime = process.hrtime(startTime)\n metrics.batch(metricsConfig.customRoutes.cached, diffTime)\n logger.info({\n message: 'Custom routes served from cache',\n type: metricsConfig.customRoutes.cached,\n ageInHours: Math.floor(dataAge / (60 * 60 * 1000)),\n isStale: isOld,\n })\n } catch (error) {\n ctx.status = 500\n ctx.body = {\n success: false,\n error: 'Failed to retrieve custom routes',\n }\n\n const diffTime = process.hrtime(startTime)\n metrics.batch(metricsConfig.customRoutes.failed, diffTime)\n logger.error({\n message: 'Error retrieving custom routes',\n error,\n type: metricsConfig.customRoutes.failed,\n })\n }\n\n await next()\n}\n\n```"
}
] |
code_store-sitemap_4cc1ca9f
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-sitemap/node/middlewares/sitemapErrors.test.ts from the store-sitemap VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { CatalogSitemapError } from '../errors/CatalogSitemapError'\nimport { sitemapErrors } from './sitemapErrors'\n\n// Mock a minimal context for testing\nconst createTestContext = (): Context => {\n return ({\n method: 'GET',\n path: '/sitemap.xml',\n vtex: {\n logger: {\n debug: jest.fn(),\n error: jest.fn(),\n info: jest.fn(),\n warn: jest.fn(),\n },\n },\n } as unknown) as Context\n}\n\ndescribe('sitemapErrors middleware', () => {\n let context: Context\n let next: jest.Mock\n\n beforeEach(() => {\n context = createTestContext()\n next = jest.fn()\n })\n\n it('should call next when no error occurs', async () => {\n await sitemapErrors(context, next)\n\n expect(next).toHaveBeenCalledTimes(1)\n expect(context.status).toBeUndefined()\n expect(context.type).toBeUndefined()\n expect(context.body).toBeUndefined()\n })\n\n it('should handle CatalogSitemapError with default 500 status', async () => {\n const originalError = new Error('Catalog API error')\n const error = new CatalogSitemapError(\n 'Failed to fetch catalog sitemap',\n originalError\n )\n next.mockRejectedValue(error)\n\n await sitemapErrors(context, next)\n\n expect(context.status).toBe(500)\n expect(context.type).toBe('text/plain; charset=utf-8')\n expect(context.body).toBe('Error fetching sitemap data')\n expect(context.vtex.logger.error).toHaveBeenCalledWith({\n message: 'Sitemap pipeline error',\n payload: {\n error: error.message,\n method: 'GET',\n originalError: originalError.message,\n path: '/sitemap.xml',\n stack: error.stack,\n statusCode: 500,\n },\n })\n })\n\n it('should handle CatalogSitemapError with custom HTTP status code', async () => {\n const originalError = {\n message: 'Not Found',\n response: { status: 404 },\n }\n const error = new CatalogSitemapError(\n 'Failed to fetch catalog sitemap',\n (originalError as unknown) as Error\n )\n next.mockRejectedValue(error)\n\n await sitemapErrors(context, next)\n\n expect(context.status).toBe(404)\n expect(context.type).toBe('text/plain; charset=utf-8')\n expect(context.body).toBe('Error fetching sitemap data')\n expect(context.vtex.logger.error).toHaveBeenCalledWith({\n message: 'Sitemap pipeline error',\n payload: {\n error: error.message,\n method: 'GET',\n originalError: originalError.message,\n path: '/sitemap.xml',\n stack: error.stack,\n statusCode: 404,\n },\n })\n })\n\n it('should extract status code from error response object', async () => {\n const originalError = {\n message: 'Bad Request',\n response: { status: 400 },\n }\n const error = new CatalogSitemapError(\n 'Failed to fetch catalog sitemap',\n (originalError as unknown) as Error\n )\n next.mockRejectedValue(error)\n\n await sitemapErrors(context, next)\n\n expect(context.status).toBe(400)\n expect(context.type).toBe('text/plain; charset=utf-8')\n expect(context.body).toBe('Error fetching sitemap data')\n expect(context.vtex.logger.error).toHaveBeenCalledWith({\n message: 'Sitemap pipeline error',\n payload: {\n error: error.message,\n method: 'GET',\n originalError: originalError.message,\n path: '/sitemap.xml',\n stack: error.stack,\n statusCode: 400,\n },\n })\n })\n\n it('should handle generic errors with 500 status', async () => {\n const error = new Error('Some unexpected error')\n next.mockRejectedValue(error)\n\n await sitemapErrors(context, next)\n\n expect(context.status).toBe(500)\n expect(context.type).toBe('text/plain; charset=utf-8')\n expect(context.body).toBe('Internal Server Error')\n expect(context.vtex.logger.error).toHaveBeenCalledWith({\n message: 'Sitemap pipeline error',\n payload: {\n error: error.message,\n method: 'GET',\n path: '/sitemap.xml',\n stack: error.stack,\n },\n })\n })\n\n it('should log error details with correct structure', async () => {\n const error = new Error('Test error')\n error.stack = 'Error: Test error\\n at Object.<anonymous> (/test.js:1:1)'\n next.mockRejectedValue(error)\n\n await sitemapErrors(context, next)\n\n expect(context.vtex.logger.error).toHaveBeenCalledWith({\n message: 'Sitemap pipeline error',\n payload: {\n error: 'Test error',\n method: 'GET',\n path: '/sitemap.xml',\n stack: 'Error: Test error\\n at Object.<anonymous> (/test.js:1:1)',\n },\n })\n })\n\n it('should set correct content type for CatalogSitemapError', async () => {\n const error = new CatalogSitemapError(\n 'Catalog error',\n new Error('Original')\n )\n const testContext = createTestContext()\n const testNext = jest.fn().mockRejectedValue(error)\n\n await sitemapErrors(testContext, testNext)\n\n expect(testContext.type).toBe('text/plain; charset=utf-8')\n })\n\n it('should set correct content type for generic errors', async () => {\n const error = new Error('Generic error')\n const testContext = createTestContext()\n const testNext = jest.fn().mockRejectedValue(error)\n\n await sitemapErrors(testContext, testNext)\n\n expect(testContext.type).toBe('text/plain; charset=utf-8')\n })\n\n it('should set correct content type for TypeError', async () => {\n const error = new TypeError('Type error')\n const testContext = createTestContext()\n const testNext = jest.fn().mockRejectedValue(error)\n\n await sitemapErrors(testContext, testNext)\n\n expect(testContext.type).toBe('text/plain; charset=utf-8')\n })\n})\n\n```"
}
] |
code_store-sitemap_a0f4dcf4
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-sitemap/node/middlewares/methods.ts from the store-sitemap VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nconst TEN_SECONDS_S = 10\n\nexport function methodNotAllowed(ctx: Context) {\n ctx.status = 405\n ctx.set('cache-control', `max-age=${TEN_SECONDS_S}`)\n}\n\n```"
}
] |
code_store-sitemap_84067f57
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-sitemap/node/middlewares/tenant.ts from the store-sitemap VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { TENANT_CACHE_TTL_S } from './../utils'\n\nexport async function tenant(ctx: EventContext, next: () => Promise<void>) {\n const {\n clients: { tenant: tenantClient },\n } = ctx\n const tenantInfo = await tenantClient.info({\n forceMaxAge: TENANT_CACHE_TTL_S,\n })\n\n const locale = tenantInfo.defaultLocale\n\n ctx.vtex.locale = locale\n ctx.vtex.tenant = { locale }\n\n await next()\n}\n\n```"
}
] |
code_store-sitemap_cd2aee2c
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-sitemap/node/resolvers/mutations.ts from the store-sitemap VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { CVBase } from '../clients/vbase'\nimport { EXTENDED_INDEX_FILE, getBucket, hashString } from '../utils'\nimport {\n currentDate,\n SitemapIndex,\n} from './../middlewares/generateMiddlewares/utils'\nimport { getDefaultStoreBinding } from './../resources/bindings'\n\nconst getBucketName = async (ctx: Context, binding?: string) => {\n if (!binding) {\n binding = await getDefaultStoreBinding(ctx)\n }\n return getBucket('', hashString(binding))\n}\n\nconst getExtendedIndexes = async (bucket: string, vbase: CVBase) => {\n const { index } = (await vbase.getJSON<SitemapIndex>(\n bucket,\n EXTENDED_INDEX_FILE,\n true\n )) || { index: [] }\n\n return index\n}\n\nconst saveBucket = (\n bucket: string,\n extendedIndexes: string[],\n vbase: CVBase\n) => {\n return vbase\n .saveJSON(bucket, EXTENDED_INDEX_FILE, {\n index: [...new Set(extendedIndexes)],\n lastUpdated: currentDate(),\n })\n .then(() => true)\n .catch(() => false)\n}\n\nexport const saveIndex = async (\n _: {},\n { index, binding }: { index: string; binding?: string },\n ctx: Context\n) => {\n const {\n clients: { vbase },\n } = ctx\n const bucket = await getBucketName(ctx, binding)\n const extendedIndexes = await getExtendedIndexes(bucket, vbase)\n\n // check if index is already in the extendedIndexes\n if (!extendedIndexes.includes(index)) {\n extendedIndexes.push(index)\n }\n\n return saveBucket(bucket, extendedIndexes, vbase)\n}\n\nexport const deleteIndex = async (\n _: {},\n { index, binding }: { index: string; binding?: string },\n ctx: Context\n) => {\n const {\n clients: { vbase },\n } = ctx\n const bucket = await getBucketName(ctx, binding)\n const extendedIndexes = await getExtendedIndexes(bucket, vbase)\n\n // if index is not in the extendedIndexes, treat as success\n if (!extendedIndexes.includes(index)) {\n return true\n }\n\n // remove index from extendedIndexes\n // and use set to eliminate any duplicates that may have been added previously\n const newExtendedIndexes = extendedIndexes.filter(i => i !== index)\n\n return saveBucket(bucket, newExtendedIndexes, vbase)\n}\n\n```"
}
] |
code_store-sitemap_1b0e87e9
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-sitemap/node/resolvers/index.ts from the store-sitemap VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { startSitemapGeneration } from '../utils'\nimport { deleteIndex, saveIndex } from './mutations'\n\nexport const resolvers = {\n Mutation: {\n deleteIndex,\n saveIndex,\n },\n Query: {\n generateSitemap: async (\n _: {},\n { force }: { force?: boolean },\n ctx: Context\n ) => {\n await startSitemapGeneration(ctx, force)\n return true\n },\n },\n}\n\n```"
}
] |
code_store-sitemap_1b08730b
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-sitemap/node/errors/CatalogSitemapError.ts from the store-sitemap VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\ninterface ErrorWithResponse {\n response?: {\n status?: number\n }\n}\n\nexport class CatalogSitemapError extends Error {\n public statusCode: number\n\n constructor(message: string, public originalError?: Error) {\n super(message)\n this.name = 'CatalogSitemapError'\n\n this.statusCode = this.extractStatusCodeFromError(originalError) ?? 500\n }\n\n private extractStatusCodeFromError(error?: Error): number | null {\n if (!error) {\n return null\n }\n\n // Type guard to check if error has response property with status\n if (this.hasResponseWithStatus(error)) {\n return error.response?.status ?? null\n }\n\n return null\n }\n\n private hasResponseWithStatus(error: unknown): error is ErrorWithResponse {\n if (!error || typeof error !== 'object') {\n return false\n }\n\n const errorObj = error as Record<string, unknown>\n const hasResponseProperty = 'response' in errorObj\n if (!hasResponseProperty) {\n return false\n }\n\n const responseValue = (errorObj as { response?: unknown }).response\n const responseIsNonNullObject =\n typeof responseValue === 'object' && responseValue !== null\n\n if (!responseIsNonNullObject) {\n return false\n }\n\n const hasStatusProperty =\n 'status' in (responseValue as Record<string, unknown>)\n\n if (!hasStatusProperty) {\n return false\n }\n\n const statusValue = (responseValue as { status?: unknown }).status\n const statusIsNumber = typeof statusValue === 'number'\n\n return statusIsNumber\n }\n}\n\n```"
}
] |
code_store-sitemap_04f503c0
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-sitemap/node/errors/CatalogSitemapError.test.ts from the store-sitemap VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { CatalogSitemapError } from './CatalogSitemapError'\n\ndescribe('CatalogSitemapError', () => {\n it('should create error with default 500 status code', () => {\n const error = new CatalogSitemapError('Test error')\n\n expect(error.message).toBe('Test error')\n expect(error.name).toBe('CatalogSitemapError')\n expect(error.statusCode).toBe(500)\n expect(error.originalError).toBeUndefined()\n })\n\n it('should use default status code when no original error provided', () => {\n const originalError = new Error('Original error')\n const error = new CatalogSitemapError('Test error', originalError)\n\n expect(error.message).toBe('Test error')\n expect(error.name).toBe('CatalogSitemapError')\n expect(error.statusCode).toBe(500)\n expect(error.originalError).toBe(originalError)\n })\n\n it('should extract status code from original error response', () => {\n const originalError = {\n message: 'API Error',\n response: { status: 403 },\n }\n const error = new CatalogSitemapError(\n 'Test error',\n (originalError as unknown) as Error\n )\n\n expect(error.message).toBe('Test error')\n expect(error.name).toBe('CatalogSitemapError')\n expect(error.statusCode).toBe(403)\n expect(error.originalError).toBe(originalError)\n })\n\n it('should default to 500 when original error has no response', () => {\n const originalError = new Error('Simple error')\n const error = new CatalogSitemapError('Test error', originalError)\n\n expect(error.message).toBe('Test error')\n expect(error.name).toBe('CatalogSitemapError')\n expect(error.statusCode).toBe(500)\n expect(error.originalError).toBe(originalError)\n })\n\n it('should default to 500 when original error response has no status', () => {\n const originalError = {\n message: 'API Error',\n response: {},\n }\n const error = new CatalogSitemapError(\n 'Test error',\n (originalError as unknown) as Error\n )\n\n expect(error.message).toBe('Test error')\n expect(error.name).toBe('CatalogSitemapError')\n expect(error.statusCode).toBe(500)\n expect(error.originalError).toBe(originalError)\n })\n})\n\n```"
}
] |
code_store-sitemap_3b35992f
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-sitemap/node/services/routes.ts from the store-sitemap VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { Internal, ListInternalsResponse } from 'vtex.rewriter'\nimport { flatten } from 'ramda'\n\nimport { SitemapIndex } from '../middlewares/generateMiddlewares/utils'\nimport { EXTENDED_INDEX_FILE, getBucket, hashString } from '../utils'\n\nconst STORE_SITEMAP_BUILD_FILE = '/dist/vtex.store-sitemap/build.json'\n\nconst LIST_LIMIT = 300\nconst MAX_PAGES = 50\n\nconst isValidRoute = (internalRoute: Internal) =>\n !internalRoute.disableSitemapEntry &&\n !internalRoute.type.startsWith('notFound') &&\n internalRoute.type !== 'product'\n\nasync function fetchInternalRoutes(ctx: Context, limit: number) {\n const {\n clients: { rewriter },\n vtex: { logger },\n } = ctx\n\n const internalRoutes = []\n let nextCursor\n let pageCount = 0\n\n do {\n pageCount++\n // eslint-disable-next-line no-await-in-loop\n const response: ListInternalsResponse = await rewriter.listInternalsWithRetry(\n limit,\n nextCursor\n )\n internalRoutes.push(...(response.routes?.filter(isValidRoute) ?? []))\n nextCursor = response.next\n\n if (pageCount >= MAX_PAGES && nextCursor) {\n logger.warn({\n message: 'Maximum page limit reached for internal routes',\n type: 'internal-routes-max-pages',\n pageCount,\n totalRoutes: internalRoutes.length,\n hasMorePages: true,\n })\n break\n }\n } while (nextCursor)\n\n return internalRoutes\n}\n\nasync function fetchExtendedRoutes(ctx: Context) {\n const {\n state: { binding },\n clients: { vbase },\n vtex: { logger },\n } = ctx\n\n // Extended routes require a binding context\n if (!binding) {\n logger.info({\n message: 'Skipping extended routes fetch - no binding context available',\n type: 'extended-routes-skip',\n })\n return []\n }\n\n const extendedIndex = await vbase.getJSON<SitemapIndex>(\n getBucket('', hashString(binding.id)),\n EXTENDED_INDEX_FILE,\n true\n )\n\n const extendedEntries = extendedIndex?.index.map(\n entry => `/sitemap/${entry.replace(/^\\//, '')}.xml`\n )\n\n return extendedEntries || []\n}\n\nexport async function getUserRoutes(ctx: Context) {\n const [internalRoutes, extendedRoutes] = await Promise.all([\n fetchInternalRoutes(ctx, LIST_LIMIT),\n fetchExtendedRoutes(ctx),\n ])\n\n const validInternalRoutes = internalRoutes\n .filter(isValidRoute)\n .map(route => route.from)\n\n const userRoutes = [...validInternalRoutes, ...extendedRoutes]\n\n return userRoutes\n}\n\nexport async function getAppsRoutes(ctx: Context) {\n const {\n clients: { apps },\n } = ctx\n\n const deps = await apps.getAppsMetaInfos()\n const routes = await Promise.all(\n deps.map(async dep => {\n const build = await apps.getAppJSON<{ entries: string[] }>(\n dep.id,\n STORE_SITEMAP_BUILD_FILE,\n true\n )\n\n return build?.entries || []\n })\n )\n\n return flatten<string>(routes)\n}\n\n```"
}
] |
code_store-sitemap_3ae7f850
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-sitemap/node/jest/setEnvVars.js from the store-sitemap VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nprocess.env.VTEX_APP_ID = 'vtex.store-sitemap@2.3.5'\nprocess.env.VTEX_APP_VERSION = '2.3.5'\nprocess.env.VTEX_APP_NAME = 'vtex.store-sitemap'\nprocess.env.VTEX_APP_VENDOR = 'vtex'\n\n```"
}
] |
code_store-sitemap_0d7420f3
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of store-sitemap/node/middlewares/generateMiddlewares/generateProductRoutes.ts from the store-sitemap VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { Binding, Logger, VBase } from '@vtex/api'\nimport { isEmpty, zipObj } from 'ramda'\nimport { Product } from 'vtex.catalog-graphql'\n\nimport {\n getBucket,\n getStoreBindings,\n hashString,\n TENANT_CACHE_TTL_S,\n} from '../../utils'\nimport { GraphQLServer, ProductNotFound } from '../../clients/graphqlServer'\nimport {\n createFileName,\n createTranslator,\n currentDate,\n filterBindingsBySalesChannel,\n GENERATE_PRODUCT_ROUTES_EVENT,\n getAccountSalesChannels,\n GROUP_ENTRIES_EVENT,\n initializeSitemap,\n Message,\n PRODUCT_ROUTES_INDEX,\n RAW_DATA_PREFIX,\n SitemapEntry,\n SitemapIndex,\n slugify,\n Translator,\n} from './utils'\n\nconst PRODUCT_QUERY = `query Product($identifier: ProductUniqueIdentifier) {\n product(identifier: $identifier) @context(provider: \"vtex.search-graphql\") {\n\t\tproductId\n }\n}`\n\ntype ProductInfo = Array<[Binding, Product]>\ntype MessagesByBinding = Record<\n string,\n { bindingLocale: string; messages: Message[] }\n>\n\nconst isProductSearchResponseEmpty = async (\n productId: string,\n graphqlServer: GraphQLServer,\n logger: Logger\n) => {\n const searchResponse = await graphqlServer\n .query(\n PRODUCT_QUERY,\n { identifier: { field: 'id', value: productId } },\n {\n persistedQuery: {\n provider: 'vtex.search-graphql@0.x',\n sender: 'vtex.store-sitemap@2.x',\n },\n }\n )\n .catch(error => {\n if (error instanceof ProductNotFound) {\n return null\n }\n logger.error({\n error,\n message: 'Error in product search',\n productId,\n })\n return null\n })\n return searchResponse !== null\n}\n\nconst getProductInfo = (\n storeBindings: Binding[],\n hasSalesChannels: boolean,\n ctx: EventContext\n) => async (productId: string): Promise<ProductInfo | undefined> => {\n const {\n clients: { catalogGraphQL, graphqlServer },\n vtex: { logger },\n } = ctx\n const [catalogResponse, hasSearchResponse] = await Promise.all([\n catalogGraphQL.product(productId),\n isProductSearchResponseEmpty(productId, graphqlServer, logger),\n ])\n const product = catalogResponse?.product\n if (!product || !product.isActive || !hasSearchResponse) {\n return\n }\n\n const bindings = hasSalesChannels\n ? filterBindingsBySalesChannel(\n storeBindings,\n product.salesChannel as Product['salesChannel']\n )\n : storeBindings\n\n return bindings.map(binding => [binding, product] as [Binding, Product])\n}\n\nconst getMessagesFromProductsInfo = (\n productsInfo: Array<ProductInfo | undefined>\n) =>\n productsInfo.reduce(\n (acc, productInfo) => {\n const { messagesByBinding } = acc\n if (!productInfo) {\n acc.currentInvalidProducts++\n return acc\n }\n acc.currentProcessedProducts++\n productInfo.forEach(([binding, product]) => {\n const message: Message = {\n content: product.linkId!,\n context: product.id,\n }\n if (messagesByBinding[binding.id]) {\n messagesByBinding[binding.id].messages = messagesByBinding[\n binding.id\n ].messages.concat(message)\n } else {\n messagesByBinding[binding.id] = {\n bindingLocale: binding.defaultLocale,\n messages: [message],\n }\n }\n })\n return acc\n },\n {\n currentInvalidProducts: 0,\n currentProcessedProducts: 0,\n messagesByBinding: {} as MessagesByBinding,\n }\n )\n\nconst createRoutes = (\n messagesByBinding: MessagesByBinding,\n tenantLocale: string,\n pathsDictionary: Record<string, string>,\n translate: Translator\n) => async (bindingId: string) => {\n const { messages, bindingLocale } = messagesByBinding[bindingId]\n const translatedSlugs = await translate(tenantLocale, bindingLocale, messages)\n const ids = messages.map(message => message.context)\n const pathById = zipObj(ids, translatedSlugs)\n const routes: Route[] = Object.keys(pathById).map(id => {\n const slug = pathById[id]\n const path = `/${slugify(slug).toLowerCase()}/p`\n const key = `${bindingId}_${id}`\n pathsDictionary[key] = path\n return { path, id }\n })\n return routes\n}\n\nconst completeRoutes = (\n pathsDictionary: Record<string, string>,\n bindingIds: string[]\n) => (route: Route): Route => {\n const alternates: AlternateRoute[] = bindingIds.map(id => ({\n bindingId: id,\n path: pathsDictionary[`${id}_${route.id}`],\n }))\n return {\n ...route,\n alternates,\n }\n}\n\nconst saveRoutes = (\n routesByBinding: Record<string, Route[]>,\n pathsDictionary: Record<string, string>,\n bindingsIds: string[],\n entry: string,\n vbase: VBase\n) => async (bindingId: string) => {\n const routes = routesByBinding[bindingId].map(\n completeRoutes(pathsDictionary, bindingsIds)\n )\n const bucket = getBucket(RAW_DATA_PREFIX, hashString(bindingId))\n const { index } = await vbase.getJSON<SitemapIndex>(\n bucket,\n PRODUCT_ROUTES_INDEX\n )\n index.push(entry)\n const lastUpdated = currentDate()\n await vbase.saveJSON<SitemapEntry>(bucket, entry, {\n lastUpdated,\n routes,\n })\n await vbase.saveJSON<SitemapIndex>(bucket, PRODUCT_ROUTES_INDEX, {\n index,\n lastUpdated,\n })\n}\n\nconst pageWasProcessed = async (\n entry: string,\n bindingId: string,\n vbase: VBase\n) => {\n const bucket = getBucket(RAW_DATA_PREFIX, hashString(bindingId))\n const { index } = await vbase.getJSON<SitemapIndex>(\n bucket,\n PRODUCT_ROUTES_INDEX\n )\n if (index.includes(entry)) {\n return true\n }\n return false\n}\n\nexport async function generateProductRoutes(\n ctx: EventContext,\n next: () => Promise<void>\n) {\n if (ctx.body.page === 1) {\n await initializeSitemap(ctx, PRODUCT_ROUTES_INDEX)\n }\n const {\n clients: { catalog, vbase, messages: messagesClient, tenant },\n body,\n vtex: { logger },\n } = ctx\n\n const tenantInfo = await tenant.info({\n forceMaxAge: TENANT_CACHE_TTL_S,\n })\n\n const {\n page,\n generationId,\n processedProducts,\n invalidProducts,\n }: ProductRoutesGenerationEvent = body!\n\n const entry = createFileName('product', page)\n const storeBindings = await getStoreBindings(tenant)\n const salesChannels = getAccountSalesChannels(storeBindings)\n const hasSalesChannels = !!salesChannels?.length\n\n if (await pageWasProcessed(entry, storeBindings[0].id, vbase)) {\n logger.error({ message: 'Page already processed', page })\n return\n }\n\n const {\n items,\n paging: { pages: totalPages, total },\n } = await catalog.getProductsIds(page, salesChannels)\n\n const productsWithError: Array<{\n productId: string\n error: unknown\n }> = []\n\n const getProductInfoFn = getProductInfo(storeBindings, hasSalesChannels, ctx)\n const productsInfo = await Promise.all(\n items.map((productId: { toString: () => string }) =>\n getProductInfoFn(productId.toString()).catch(error => {\n productsWithError.push({ productId: productId.toString(), error })\n return undefined\n })\n )\n )\n\n if (!isEmpty(productsWithError)) {\n logger.error({\n message: `Error in product search, ${productsWithError.length} failed when adding into sitemap`,\n productsWithError,\n })\n }\n\n const {\n currentInvalidProducts,\n currentProcessedProducts,\n messagesByBinding,\n } = getMessagesFromProductsInfo(productsInfo)\n\n const translate = createTranslator(messagesClient)\n const tenantLocale = tenantInfo.defaultLocale\n\n const pathsDictionary: Record<string, string> = {}\n const routesList = await Promise.all(\n Object.keys(messagesByBinding).map(\n createRoutes(messagesByBinding, tenantLocale, pathsDictionary, translate)\n )\n )\n\n const bindingsIds = Object.keys(messagesByBinding)\n const routesByBinding: Record<string, Route[]> = zipObj(\n bindingsIds,\n routesList\n )\n await Promise.all(\n Object.keys(routesByBinding).map(\n saveRoutes(routesByBinding, pathsDictionary, bindingsIds, entry, vbase)\n )\n )\n\n const payload: ProductRoutesGenerationEvent = {\n generationId,\n invalidProducts: invalidProducts + currentInvalidProducts,\n page: page + 1,\n processedProducts: processedProducts + currentProcessedProducts,\n }\n ctx.state.nextEvent = {\n event: GENERATE_PRODUCT_ROUTES_EVENT,\n payload,\n }\n if (page >= totalPages) {\n logger.info({\n invalidProducts: payload.invalidProducts,\n message: `Product routes complete`,\n page,\n processedProducts: payload.processedProducts,\n total,\n totalPages,\n type: 'product-routes',\n })\n ctx.state.nextEvent = {\n event: GROUP_ENTRIES_EVENT,\n payload: {\n from: 0,\n generationId,\n indexFile: PRODUCT_ROUTES_INDEX,\n },\n }\n }\n\n await next()\n}\n\n```"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.