id
stringlengths
12
53
messages
listlengths
3
3
code_shipping-option-components_933a8b7d
[ { "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 shipping-option-components/react/components/PinIcon.tsx from the shipping-option-components VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\nimport { useCssHandles } from 'vtex.css-handles'\n\ninterface Props {\n filled?: boolean\n width?: number\n height?: number\n}\n\nconst CSS_HANDLES = ['pinIconPath', 'pinIconSVG'] as const\n\nconst PinIcon = ({ filled = true, width = 16, height = 16 }: Props) => {\n const handles = useCssHandles(CSS_HANDLES)\n\n return filled ? (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n xmlnsXlink=\"http://www.w3.org/1999/xlink\"\n version=\"1.1\"\n width={width}\n height={height}\n viewBox=\"0 0 256 256\"\n xmlSpace=\"preserve\"\n className={handles.pinIconSVG}\n >\n <defs />\n <g\n transform=\"translate(1.4065934065934016 1.4065934065934016) scale(2.81 2.81)\"\n style={{\n stroke: 'none',\n strokeWidth: 0,\n strokeDasharray: 'none',\n strokeLinecap: 'butt',\n strokeLinejoin: 'miter',\n strokeMiterlimit: 10,\n fill: 'none',\n fillRule: 'nonzero',\n opacity: 1,\n }}\n >\n <path\n style={{\n stroke: 'none',\n strokeWidth: 1,\n strokeDasharray: 'none',\n strokeLinecap: 'butt',\n strokeLinejoin: 'miter',\n strokeMiterlimit: 10,\n fill: '#727273',\n fillRule: 'nonzero',\n opacity: 1,\n }}\n d=\"M 45 0 C 25.463 0 9.625 15.838 9.625 35.375 c 0 8.722 3.171 16.693 8.404 22.861 L 45 90 l 26.97 -31.765 c 5.233 -6.167 8.404 -14.139 8.404 -22.861 C 80.375 15.838 64.537 0 45 0 z M 45 48.705 c -8.035 0 -14.548 -6.513 -14.548 -14.548 c 0 -8.035 6.513 -14.548 14.548 -14.548 s 14.548 6.513 14.548 14.548 C 59.548 42.192 53.035 48.705 45 48.705 z\"\n transform=\" matrix(1 0 0 1 0 0) \"\n strokeLinecap=\"round\"\n className={handles.pinIconPath}\n />\n </g>\n </svg>\n ) : (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width={width}\n height={height}\n viewBox=\"0 0 25 25\"\n fill=\"none\"\n className={handles.pinIconSVG}\n >\n <path\n d=\"M12.7082 1.04199C13.8985 1.08233 15.0692 1.3569 16.1533 1.85001C17.2375 2.34312 18.2138 3.04509 19.0264 3.91578C19.8391 4.78648 20.4721 5.80882 20.8894 6.92435C21.3066 8.03988 21.4999 9.22671 21.4582 10.417C21.4582 15.6253 14.5832 23.9587 12.4998 23.9587C10.4165 23.9587 3.5415 15.417 3.5415 10.417C3.55147 7.96947 4.51399 5.62199 6.22511 3.87198C7.93623 2.12198 10.2615 1.10695 12.7082 1.04199ZM12.4998 13.542C12.9931 13.5448 13.4819 13.4496 13.9382 13.2622C14.3944 13.0747 14.8089 12.7986 15.1576 12.4498C15.5064 12.101 15.7825 11.6865 15.97 11.2303C16.1575 10.7741 16.2526 10.2852 16.2498 9.79199C16.2319 8.83834 15.859 7.92565 15.2041 7.23221C14.5492 6.53877 13.6592 6.1144 12.7082 6.04199C12.1992 6.01665 11.6903 6.09474 11.2124 6.27155C10.7344 6.44836 10.2972 6.72022 9.92727 7.07071C9.5573 7.4212 9.26223 7.84305 9.05986 8.31077C8.85749 8.77849 8.75202 9.28237 8.74984 9.79199C8.81348 10.7656 9.229 11.6829 9.91895 12.3729C10.6089 13.0628 11.5262 13.4783 12.4998 13.542Z\"\n stroke=\"#505050\"\n strokeWidth=\"1.5\"\n strokeMiterlimit=\"10\"\n className={handles.pinIconPath}\n />\n </svg>\n )\n}\n\nexport default PinIcon\n\n```" } ]
code_shipping-option-components_bc981ef4
[ { "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 shipping-option-components/react/components/PostalCodeHelpLink.tsx from the shipping-option-components VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React, { useEffect, useState } from 'react'\nimport { useIntl } from 'react-intl'\nimport { AddressRules, helpers } from 'vtex.address-form'\nimport { Link } from 'vtex.styleguide'\nimport { useCssHandles } from 'vtex.css-handles'\n\nimport messages from '../messages'\nimport { getCountryCode } from '../utils/cookie'\n\nconst POSTAL_CODE_FIELD = 'postalCode'\n\nconst CSS_HANDLES = ['postalCodeHelpLink'] as const\n\ninterface Props {\n rules?: any\n}\n\nconst HelpLink = helpers.injectRules(({ rules }: Props) => {\n const intl = useIntl()\n const handles = useCssHandles(CSS_HANDLES)\n\n let postalCodeFinderURL\n\n if (rules) {\n const postalCodeField = rules.fields?.find(\n (field: any) => field.name === POSTAL_CODE_FIELD\n )\n\n postalCodeFinderURL = postalCodeField?.forgottenURL\n }\n\n if (!postalCodeFinderURL) {\n return null\n }\n\n return (\n <Link\n href={postalCodeFinderURL}\n target=\"_blank\"\n className={`${handles.postalCodeHelpLink}`}\n >\n {intl.formatMessage(messages.popoverPostalCodeLink)}\n </Link>\n )\n})\n\nconst PostalCodeHelpLink = () => {\n const [countryCode, setCountryCode] = useState('')\n\n useEffect(() => {\n setCountryCode(getCountryCode())\n }, [])\n\n return (\n <AddressRules country={countryCode} shouldUseIOFetching>\n <HelpLink />\n </AddressRules>\n )\n}\n\nexport default PostalCodeHelpLink\n\n```" } ]
code_shipping-option-components_af0e5531
[ { "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 shipping-option-components/react/components/PostalCodeInput.tsx from the shipping-option-components VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\nimport { Input, IconClear } from 'vtex.styleguide'\nimport { useCssHandles } from 'vtex.css-handles'\n\nimport '../styles.css'\n\nconst CSS_HANDLES = [\n 'postalCodeInputClearButton',\n 'postalCodeInputContainer',\n] as const\n\ninterface Props {\n onSubmit: (zipcode: string) => void\n onChange: (zipcode: string) => void\n zipcode: string\n errorMessage?: string\n showClearButton?: boolean\n placeholder?: string\n}\n\nconst postalCodeInputClearButton = {\n backgroundColor: 'unset',\n width: '32px',\n height: '32px',\n}\n\nconst PostalCodeInput = ({\n zipcode,\n errorMessage,\n onSubmit,\n onChange,\n showClearButton = false,\n placeholder,\n}: Props) => {\n const handles = useCssHandles(CSS_HANDLES)\n\n return (\n <div className={`w-100 ${handles.postalCodeInputContainer}`}>\n <Input\n autFocus\n onChange={(e: React.ChangeEvent<HTMLInputElement>) =>\n onChange(e.target.value.replace(/[^0-9]/g, ''))\n }\n onKeyDown={(e: { key: string }) => {\n if (e.key === 'Enter') {\n onSubmit(zipcode ?? '')\n }\n }}\n value={zipcode}\n errorMessage={errorMessage}\n placeholder={placeholder}\n suffix={\n showClearButton ? (\n <button\n style={postalCodeInputClearButton}\n className={`bn pointer flex justify-center items-center pa3 ${handles.postalCodeInputClearButton}`}\n onClick={() => {\n onChange('')\n }}\n >\n <IconClear />\n </button>\n ) : null\n }\n />\n </div>\n )\n}\n\nexport default PostalCodeInput\n\n```" } ]
code_shipping-option-components_65d85cf6
[ { "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 shipping-option-components/react/components/PickupModal.tsx from the shipping-option-components VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\nimport { useIntl } from 'react-intl'\n\nimport Modal from './Modal'\nimport messages from '../messages'\nimport PickupSelection from './PickupSelection'\n\ninterface Props {\n isOpen: boolean\n onClose: () => void\n pickupProps: React.ComponentProps<typeof PickupSelection>\n}\n\nconst PickupModal = ({ isOpen, onClose, pickupProps }: Props) => {\n const intl = useIntl()\n\n const {\n onSelectPickup,\n onSubmit,\n pickups,\n inputErrorMessage,\n selectedPickup,\n selectedZipcode,\n isLoading,\n } = pickupProps\n\n return (\n <Modal\n showArrowBack={false}\n isTopCloseButton={false}\n title={intl.formatMessage(messages.deliverToButtonPlaceholder)}\n isOpen={isOpen}\n onClose={onClose}\n >\n <PickupSelection\n onSelectPickup={onSelectPickup}\n onSubmit={onSubmit}\n pickups={pickups}\n inputErrorMessage={inputErrorMessage}\n selectedPickup={selectedPickup}\n selectedZipcode={selectedZipcode}\n isLoading={isLoading}\n />\n </Modal>\n )\n}\n\nexport default PickupModal\n\n```" } ]
code_shipping-option-components_eb1f3497
[ { "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 shipping-option-components/react/components/ShippingOptionButton.tsx from the shipping-option-components VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React, { useEffect, useRef } from 'react'\nimport { useCssHandles } from 'vtex.css-handles'\nimport { Spinner } from 'vtex.styleguide'\nimport { usePopoverStore } from '@ariakit/react'\n\nimport DeliveryPopover from './DeliveryPopover'\n\nconst CSS_HANDLES = [\n 'buttonWrapper',\n 'buttonLabel',\n 'buttonValue',\n 'shippingButtonContainer',\n] as const\n\ninterface ShippingOptionButtonProps {\n onClick: () => void\n loading: boolean\n placeholder: string\n value?: React.ReactNode\n selectedZipcode?: string\n onSubmit?: (zipCode: string) => void\n inputErrorMessage?: string\n callToAction?: CallToAction\n mode: Mode\n icon: React.ReactNode\n showLocationDetectorButton?: boolean\n}\n\nconst ShippingOptionButton = ({\n onClick,\n loading,\n value,\n placeholder,\n selectedZipcode,\n onSubmit,\n inputErrorMessage,\n callToAction,\n mode,\n icon,\n showLocationDetectorButton,\n}: ShippingOptionButtonProps) => {\n const handles = useCssHandles(CSS_HANDLES)\n const popoverStore = usePopoverStore({ defaultOpen: false })\n const anchorRef = useRef(null)\n\n const popoverOverlay =\n callToAction === 'popover-button' || callToAction === 'popover-input'\n ? callToAction\n : undefined\n\n useEffect(() => {\n if (anchorRef.current) {\n popoverStore.setAnchorElement(anchorRef.current)\n }\n }, [popoverStore])\n\n return (\n <div\n className={`${handles.shippingButtonContainer} flex items-center h-100`}\n >\n <button\n ref={anchorRef}\n onClick={onClick}\n className={`${handles.buttonWrapper} flex items-center br3 pt4 pr4 pb4 pl0 b--none`}\n >\n {loading ? (\n <div className=\"ml4\">\n <Spinner size={14} />\n </div>\n ) : mode === 'default' ? (\n <p className={`${handles.buttonValue} ma0 f6 fw6 c-action-primary`}>\n {value ?? placeholder}\n </p>\n ) : (\n icon\n )}\n </button>\n {popoverOverlay && (\n <DeliveryPopover\n onClick={onClick}\n onSubmit={onSubmit ?? (() => {})}\n isLoading={loading}\n inputErrorMessage={inputErrorMessage}\n selectedZipcode={selectedZipcode}\n variant={popoverOverlay}\n popoverStore={popoverStore}\n showLocationDetectorButton={showLocationDetectorButton}\n />\n )}\n </div>\n )\n}\n\nexport default ShippingOptionButton\n\n```" } ]
code_shipping-option-components_d64823f7
[ { "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 shipping-option-components/react/components/LocationDetectorButton.tsx from the shipping-option-components VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React, { useEffect, useState } from 'react'\nimport { useRuntime } from 'vtex.render-runtime'\nimport { useIntl } from 'react-intl'\nimport { useCssHandles } from 'vtex.css-handles'\n\nimport EmptyState from './EmptyState'\nimport PinIcon from './PinIcon'\nimport messages from '../messages'\n\nconst CSS_HANDLES = [\n 'locationDetectorButton',\n 'locationDetectorButtonContainer',\n 'locationDetectorButtonIcon',\n] as const\n\nconst getGeolocation = async (): Promise<any> => {\n if (!navigator?.geolocation) {\n throw new Error('Geolocation not supported')\n }\n\n return new Promise((resolve, reject) => {\n navigator.geolocation.getCurrentPosition(resolve, reject)\n })\n}\n\nconst LocationDetectorButton: React.FC = () => {\n const [regionId, setRegionId] = useState<string>('')\n const [error, setError] = useState<boolean>(false)\n const handles = useCssHandles(CSS_HANDLES)\n\n const {\n culture: { country },\n route: { path, queryString },\n } = useRuntime()\n\n const intl = useIntl()\n\n useEffect(() => {\n const getCurrentPosition = async (): Promise<void> => {\n try {\n const position = await getGeolocation()\n const { latitude, longitude } = position.coords\n\n const response = await fetch(\n `https://nominatim.openstreetmap.org/reverse?format=json&lat=${latitude}&lon=${longitude}`\n )\n\n if (!response.ok) {\n throw new Error(`HTTP error! status: ${response.status}`)\n }\n\n const data = await response.json()\n const postcode = data.address?.postcode || data.address?.postal_code\n\n if (postcode) {\n const cep = postcode.replace(/-/g, '')\n const newRegionId = btoa(`vtex:${country}:${cep}`)\n\n setRegionId(newRegionId)\n setError(false)\n }\n } catch (err) {\n setError(true)\n }\n }\n\n if (regionId || !navigator?.geolocation) return\n\n getCurrentPosition()\n }, [country, regionId])\n\n if (queryString?.region_id) {\n return null\n }\n\n if (!regionId || error) {\n return (\n <div className={`${handles.locationDetectorButtonContainer}`}>\n <EmptyState\n description={intl.formatMessage(\n error\n ? messages.LocationDetectorButtonErrorDescription\n : messages.LocationDetectorButtonLoadingDescription\n )}\n variant=\"secondary\"\n iconProps={{ useIcon: !!error, width: '20', height: '20' }}\n />\n </div>\n )\n }\n\n const separator = Object.keys(queryString).length === 0 ? '?' : '&'\n const href = `${path}${separator}region_id=${regionId}`\n\n return (\n <a\n href={href}\n className={`${handles.locationDetectorButton} no-underline flex items-center c-link hover-c-link`}\n >\n <span className={handles.locationDetectorButtonIcon}>\n <PinIcon filled={false} />\n </span>\n {intl.formatMessage(messages.LocationDetectorButtonTitle)}\n </a>\n )\n}\n\nexport default LocationDetectorButton\n\n```" } ]
code_shipping-option-components_6ba66072
[ { "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 shipping-option-components/react/components/DeliveryPopover.tsx from the shipping-option-components VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React, { useEffect, useState } from 'react'\nimport type { PopoverStore } from '@ariakit/react'\nimport { Popover, PopoverArrow } from '@ariakit/react'\nimport { useIntl } from 'react-intl'\nimport { Button } from 'vtex.styleguide'\nimport { useCssHandles } from 'vtex.css-handles'\n\nimport PostalCodeInput from './PostalCodeInput'\nimport messages from '../messages'\nimport PostalCodeHelpLink from './PostalCodeHelpLink'\nimport LocationDetectorButton from './LocationDetectorButton'\n\nconst CSS_HANDLES = [\n 'deliveryPopover',\n 'deliveryPopoverText',\n 'deliveryPopoverArrow',\n 'popoverInputContainer',\n] as const\n\ninterface DeliveryPopoverProps {\n onClick: () => void\n variant?: 'popover-button' | 'popover-input'\n onSubmit: (zipcode: string) => void\n isLoading?: boolean\n inputErrorMessage?: string\n popoverStore: PopoverStore\n selectedZipcode?: string\n showLocationDetectorButton?: boolean\n}\n\nconst DeliveryPopover = ({\n onClick,\n variant = 'popover-input',\n onSubmit,\n isLoading,\n inputErrorMessage,\n popoverStore,\n selectedZipcode,\n showLocationDetectorButton,\n}: DeliveryPopoverProps) => {\n const [zipcode, setZipcode] = useState<string>('')\n const [alreadyOpen, setAlreadyOpen] = useState<boolean>(false)\n const handles = useCssHandles(CSS_HANDLES)\n const intl = useIntl()\n\n const isFirstLoading = !zipcode && isLoading\n\n const openPopover = !isFirstLoading && !selectedZipcode && !alreadyOpen\n\n useEffect(() => {\n if (openPopover) {\n popoverStore.setOpen(true)\n setAlreadyOpen(true)\n }\n }, [openPopover, popoverStore])\n\n const handlePopoverClick = () => {\n onClick()\n popoverStore.setOpen(false)\n }\n\n return (\n <Popover\n className={handles.deliveryPopover}\n hideOnInteractOutside\n autoFocusOnShow={false}\n store={popoverStore}\n >\n <p className={`${handles.deliveryPopoverText} ma0`}>\n {`${intl.formatMessage(messages.popoverDescription)} `}\n <PostalCodeHelpLink />\n </p>\n\n {variant === 'popover-button' ? (\n <Button onClick={handlePopoverClick}>\n {intl.formatMessage(messages.popoverButtonLabel)}\n </Button>\n ) : (\n <div className={`${handles.popoverInputContainer} flex`}>\n <PostalCodeInput\n onChange={(value: string) => setZipcode(value)}\n zipcode={zipcode}\n onSubmit={onSubmit}\n errorMessage={inputErrorMessage}\n showClearButton={false}\n placeholder={intl.formatMessage(\n messages.popoverPostalCodeInputPlaceHolder\n )}\n />\n <Button isLoading={isLoading} onClick={() => onSubmit(zipcode)}>\n {intl.formatMessage(messages.popoverSubmitButtonLabel)}\n </Button>\n </div>\n )}\n\n {showLocationDetectorButton && <LocationDetectorButton />}\n\n <PopoverArrow className=\"deliveryPopoverArrow\" />\n </Popover>\n )\n}\n\nexport default DeliveryPopover\n\n```" } ]
code_shipping-option-components_77034fe0
[ { "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 shipping-option-components/react/components/Modal.tsx from the shipping-option-components VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport type { PropsWithChildren } from 'react'\nimport React from 'react'\nimport ReactModalComponent from 'react-modal'\nimport { useCssHandles } from 'vtex.css-handles'\nimport { useDevice } from 'vtex.device-detector'\nimport { IconClose, IconArrowBack } from 'vtex.styleguide'\n\n// Work around type issues with react-modal in React 16\nconst ReactModal = ReactModalComponent as any\n\ninterface Props {\n onClose: () => void\n isOpen: boolean\n title: string\n showArrowBack: boolean\n isTopCloseButton: boolean\n nonDismissible?: boolean\n nonDismissibleModal?: boolean // Add support for the existing prop name\n onArrowBack?: () => void\n}\n\nconst customStyles = {\n content: {\n top: '50%',\n left: '50%',\n right: 'auto',\n bottom: 'auto',\n marginRight: '-50%',\n padding: '40px 40px 64px 40px',\n transform: 'translate(-50%, -50%)',\n borderRadius: '12px',\n minHeight: '388px',\n maxHeight: '640px',\n width: 'unset',\n minWidth: 'unset',\n display: 'flex',\n 'flex-direction': 'column',\n },\n overlay: {\n backgroundColor: 'rgba(3, 4, 78, 0.55)',\n zIndex: '99999',\n width: '100vw',\n height: '100vh',\n },\n}\n\nconst CSS_HANDLES = [\n 'modalBackButton',\n 'modalCloseButton',\n 'shippingMethodModalTitle',\n]\n\nconst headerActionButtonStyle: React.CSSProperties = {\n cursor: 'pointer',\n backgroundColor: 'unset',\n border: 0,\n}\n\nconst Modal = ({\n children,\n onClose,\n isOpen,\n title,\n onArrowBack,\n showArrowBack,\n isTopCloseButton,\n nonDismissible = false,\n nonDismissibleModal = false,\n}: PropsWithChildren<Props>) => {\n const handles = useCssHandles(CSS_HANDLES)\n const { isMobile } = useDevice()\n\n // Support both prop names for backward compatibility\n const isNonDismissible = nonDismissible || nonDismissibleModal\n\n if (isMobile) {\n customStyles.content.width = '100%'\n } else {\n customStyles.content.width = '522px'\n customStyles.content.minWidth = '522px'\n }\n\n if (isNonDismissible) {\n customStyles.content.padding = '64px 40px'\n } else {\n customStyles.content.padding = '40px 40px 64px 40px'\n }\n\n return (\n <ReactModal\n style={customStyles}\n isOpen={isOpen}\n onRequestClose={isNonDismissible ? undefined : onClose}\n shouldCloseOnOverlayClick={!isNonDismissible}\n shouldCloseOnEsc={!isNonDismissible}\n ariaHideApp={false}\n >\n <>\n <div\n className={`flex justify-between items-center mb3 ${\n isTopCloseButton ? 'flex-column-reverse' : 'flex-row'\n }`}\n >\n <div className=\"flex items-center self-start flex-row\">\n {showArrowBack && onArrowBack && (\n <button\n className={`pa0 mr4 ${handles.modalBackButton}`}\n onClick={onArrowBack}\n >\n <IconArrowBack />\n </button>\n )}\n <p className={`f3 fw6 ma0 ${handles.shippingMethodModalTitle}`}>\n {title}\n </p>\n </div>\n\n {!isNonDismissible && (\n <div className=\"flex justify-end self-end\">\n <button\n onClick={onClose}\n className={handles.modalCloseButton}\n style={headerActionButtonStyle}\n >\n <IconClose size={24} />\n </button>\n </div>\n )}\n </div>\n {children}\n </>\n </ReactModal>\n )\n}\n\nexport default Modal\n\n```" } ]
code_shipping-option-components_3194cbe0
[ { "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 shipping-option-components/react/components/EmptyState.tsx from the shipping-option-components VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\nimport { Button } from 'vtex.styleguide'\nimport { useCssHandles } from 'vtex.css-handles'\n\nimport PinSlashIcon from './PinSlashIcon'\n\nconst CSS_HANDLES = ['noPickupsStateContent'] as const\n\ninterface Props {\n onClick?: () => void\n title?: string\n description?: string\n buttonLabel?: string\n variant?: 'primary' | 'secondary'\n iconProps?: IconProps\n}\n\ninterface IconProps {\n width?: string\n height?: string\n useIcon?: boolean\n}\n\nconst EmptyState = ({\n onClick,\n title,\n description,\n buttonLabel,\n variant = 'primary',\n iconProps = { useIcon: true },\n}: Props) => {\n const handle = useCssHandles(CSS_HANDLES)\n\n return (\n <div className=\"flex-auto flex flex-column\">\n <div\n style={{ margin: 'auto 0' }}\n className={`flex ${title ? 'flex-column' : 'flex-row'} ${\n variant === 'primary' ? 'items-center' : 'items-start'\n } ${handle.noPickupsStateContent}`}\n >\n {iconProps.useIcon && (\n <PinSlashIcon\n color={variant === 'primary' ? '#979899' : '#000000'}\n width={iconProps?.width}\n height={iconProps?.height}\n />\n )}\n {title && <p className=\"f3 fw6 mb0 mt5\">{title}</p>}\n {description && (\n <p className=\"t-small mt1 ml3 mb0 c-muted-1\">{description}</p>\n )}\n </div>\n {onClick && (\n <div className=\"mt8\">\n <Button block onClick={onClick}>\n {buttonLabel}\n </Button>\n </div>\n )}\n </div>\n )\n}\n\nexport default EmptyState\n\n```" } ]
code_shipping-option-components_372ef23e
[ { "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 shipping-option-components/react/__tests__/AvailabilityBadges.test.tsx from the shipping-option-components VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\nimport { ProductSummaryContext } from 'vtex.product-summary-context'\nimport { render } from '@vtex/test-tools/react'\nimport * as reactIntl from 'react-intl'\n\nimport AvailabilityBadges from '../AvailabilityBadges'\n\nconst messages = {\n 'store/shipping-option-zipcode.availabilityBadge.deliveryAvailable':\n 'Delivery available',\n 'store/shipping-option-zipcode.availabilityBadge.deliveryUnavailable':\n 'Delivery unavailable',\n 'store/shipping-option-zipcode.availabilityBadge.pickupAt': 'Pickup at',\n 'store/shipping-option-zipcode.availabilityBadge.pickupUnavailable':\n 'Pickup unavailable',\n} as const\n\nconst COMMON_BADGE_STYLE = 'br-pill mr3'\nconst AVAILABLE_BADGE_STYLE = 'bg-green'\nconst UNAVAILABLE_BADGE_STYLE = ['bg-white', 'ba']\n\nconst mockUseShippingOptionState = jest.fn()\nconst mockUseProductSummary =\n ProductSummaryContext.useProductSummary as jest.Mock\n\nconst mockIntl = {\n formatMessage: ({ id }: { id: string }) =>\n messages[id as keyof typeof messages] || id,\n} as reactIntl.IntlShape\n\njest.mock('../context', () => ({\n useShippingOptionState: () => mockUseShippingOptionState(),\n}))\n\njest.mock('../PickupModal', () => {\n const MockPickupModal = (props: { isOpen: boolean; onClose: () => void }) => (\n <div\n data-testid=\"pickup-modal\"\n onClick={props.onClose}\n onKeyDown={(e) => e.key === 'Enter' && props.onClose()}\n role=\"button\"\n tabIndex={0}\n >\n {props.isOpen ? 'Modal Open' : 'Modal Closed'}\n </div>\n )\n\n return MockPickupModal\n})\n\ndescribe('AvailabilityBadges', () => {\n beforeEach(() => {\n jest.clearAllMocks()\n mockUseProductSummary.mockReturnValue({\n product: { deliveryPromisesBadges: [] },\n })\n\n jest.spyOn(reactIntl, 'useIntl').mockImplementation(() => mockIntl)\n })\n\n describe('Initial render conditions', () => {\n it('renders nothing if zipcode is missing', () => {\n mockUseShippingOptionState.mockReturnValue({ zipcode: null })\n\n const { container } = render(<AvailabilityBadges />)\n\n expect(container.firstChild).toBeNull()\n })\n\n it('renders nothing if deliveryPromisesBadges is null', () => {\n mockUseShippingOptionState.mockReturnValue({ zipcode: '12345' })\n mockUseProductSummary.mockReturnValue({\n product: { deliveryPromisesBadges: null },\n })\n\n const { container } = render(<AvailabilityBadges />)\n\n expect(container.firstChild).toBeNull()\n })\n })\n\n describe('Delivery badge states and styles', () => {\n beforeEach(() => {\n mockUseShippingOptionState.mockReturnValue({ zipcode: '12345' })\n })\n\n it('renders unavailable badges if deliveryPromisesBadges is empty', () => {\n // Setup mock data\n mockUseProductSummary.mockReturnValue({\n product: { deliveryPromisesBadges: [] },\n })\n\n // Render component and get text elements\n const { getByText } = render(<AvailabilityBadges />)\n const deliveryText = getByText('Delivery unavailable')\n const pickupText = getByText('Pickup unavailable')\n\n // Check if text elements are rendered\n expect(deliveryText).toBeInTheDocument()\n expect(pickupText).toBeInTheDocument()\n\n // Get badge elements\n const deliveryBadge = deliveryText.closest('div')?.querySelector('div')\n const pickupBadge = pickupText.closest('div')?.querySelector('div')\n\n // Check delivery badge styles (should be unavailable)\n expect(deliveryBadge).toHaveClass(\n COMMON_BADGE_STYLE,\n ...UNAVAILABLE_BADGE_STYLE\n )\n expect(deliveryBadge).not.toHaveClass(AVAILABLE_BADGE_STYLE)\n\n // Check pickup badge styles (should be unavailable)\n expect(pickupBadge).toHaveClass(\n COMMON_BADGE_STYLE,\n ...UNAVAILABLE_BADGE_STYLE\n )\n expect(pickupBadge).not.toHaveClass(AVAILABLE_BADGE_STYLE)\n })\n\n it('renders available badges when only delivery is available', () => {\n mockUseProductSummary.mockReturnValue({\n product: {\n deliveryPromisesBadges: [{ typeName: 'delivery' }],\n },\n })\n\n const { getByText } = render(<AvailabilityBadges />)\n\n const deliveryText = getByText('Delivery available')\n const pickupText = getByText('Pickup unavailable')\n\n expect(deliveryText).toBeInTheDocument()\n expect(pickupText).toBeInTheDocument()\n\n // Get badge elements and check their styles\n const deliveryBadge = deliveryText.closest('div')?.querySelector('div')\n const pickupBadge = pickupText.closest('div')?.querySelector('div')\n\n // Delivery badge should be styled as available\n expect(deliveryBadge).toHaveClass(\n COMMON_BADGE_STYLE,\n AVAILABLE_BADGE_STYLE\n )\n expect(deliveryBadge).not.toHaveClass(...UNAVAILABLE_BADGE_STYLE)\n\n // Pickup badge should be styled as unavailable\n expect(pickupBadge).toHaveClass(\n COMMON_BADGE_STYLE,\n ...UNAVAILABLE_BADGE_STYLE\n )\n expect(pickupBadge).not.toHaveClass(AVAILABLE_BADGE_STYLE)\n })\n\n it('renders both available badges and pickup button', () => {\n mockUseProductSummary.mockReturnValue({\n product: {\n deliveryPromisesBadges: [\n { typeName: 'delivery' },\n { typeName: 'pickup-in-point', pickupName: 'Store 1' },\n ],\n },\n })\n\n const { getByText } = render(<AvailabilityBadges />)\n\n const deliveryText = getByText('Delivery available')\n const pickupText = getByText('Pickup at')\n const pickupLocation = getByText('Store 1')\n\n expect(deliveryText).toBeInTheDocument()\n expect(pickupText).toBeInTheDocument()\n expect(pickupLocation).toBeInTheDocument()\n\n // Get badge elements and check their styles\n const deliveryBadge = deliveryText.closest('div')?.querySelector('div')\n const pickupBadge = pickupText.closest('div')?.querySelector('div')\n\n // Both badges should be styled as available\n expect(deliveryBadge).toHaveClass(\n COMMON_BADGE_STYLE,\n AVAILABLE_BADGE_STYLE\n )\n expect(deliveryBadge).not.toHaveClass(...UNAVAILABLE_BADGE_STYLE)\n\n expect(pickupBadge).toHaveClass(COMMON_BADGE_STYLE, AVAILABLE_BADGE_STYLE)\n expect(pickupBadge).not.toHaveClass(...UNAVAILABLE_BADGE_STYLE)\n })\n })\n\n describe('Pickup modal behavior', () => {\n beforeEach(() => {\n mockUseShippingOptionState.mockReturnValue({ zipcode: '12345' })\n })\n\n it('opens pickup modal when clicking on pickup location', () => {\n mockUseProductSummary.mockReturnValue({\n product: {\n deliveryPromisesBadges: [\n { typeName: 'pickup-in-point', pickupName: 'Store 1' },\n ],\n },\n })\n\n // Render component and get elements\n const { getByText, getByTestId } = render(<AvailabilityBadges />)\n const pickupButton = getByText('Store 1')\n\n // Trigger click event\n pickupButton.click()\n\n // Check if modal is open\n expect(getByTestId('pickup-modal')).toHaveTextContent('Modal Open')\n })\n\n it('closes pickup modal when clicking close button', () => {\n mockUseProductSummary.mockReturnValue({\n product: {\n deliveryPromisesBadges: [\n { typeName: 'pickup-in-point', pickupName: 'Store 1' },\n ],\n },\n })\n\n // Render component and get elements\n const { getByText, getByTestId } = render(<AvailabilityBadges />)\n const pickupButton = getByText('Store 1')\n\n // Open modal\n pickupButton.click()\n const modal = getByTestId('pickup-modal')\n\n // Close modal\n modal.click()\n\n // Check if modal is closed\n expect(modal).toHaveTextContent('Modal Closed')\n })\n })\n\n describe('Event handling', () => {\n beforeEach(() => {\n mockUseShippingOptionState.mockReturnValue({ zipcode: '12345' })\n })\n\n it('stops event propagation when clicking on the container', () => {\n mockUseProductSummary.mockReturnValue({\n product: { deliveryPromisesBadges: [] },\n })\n\n // Render component and get container element\n const { container } = render(<AvailabilityBadges />)\n const divElement = container.firstChild as HTMLElement\n\n // Create click event and spy on stopPropagation\n const clickEvent = new MouseEvent('click', { bubbles: true })\n const stopPropagation = jest.spyOn(clickEvent, 'stopPropagation')\n\n // Trigger click event\n divElement.dispatchEvent(clickEvent)\n\n // Check if event propagation was stopped\n expect(stopPropagation).toHaveBeenCalled()\n })\n\n it('allows clicking on pickup button without event propagation', () => {\n // Setup mock data\n mockUseProductSummary.mockReturnValue({\n product: {\n deliveryPromisesBadges: [\n { typeName: 'pickup-in-point', pickupName: 'Store 1' },\n ],\n },\n })\n\n // Render component and get elements\n const { getByText, getByTestId } = render(<AvailabilityBadges />)\n const pickupButton = getByText('Store 1')\n\n // Trigger click event\n pickupButton.click()\n\n // Check if modal was opened\n expect(getByTestId('pickup-modal')).toBeInTheDocument()\n })\n })\n})\n\n```" } ]
code_shipping-option-components_39c62234
[ { "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 shipping-option-components/react/__tests__/UseShippingOption.test.tsx from the shipping-option-components VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\nimport { render, fireEvent, waitFor } from '@vtex/test-tools/react'\nimport * as reactIntl from 'react-intl'\n\nimport { useShippingOption } from '../context/useShippingOption'\nimport * as client from '../client'\n\nconst mockIntl = {\n formatMessage: ({ id }: { id: string }) => String(id),\n} as unknown as reactIntl.IntlShape\n\njest.spyOn(reactIntl, 'useIntl').mockImplementation(() => mockIntl)\n\nfunction ActionRunner({\n actions,\n}: {\n actions: Array<{ type: string; args?: unknown }>\n}) {\n const { dispatch } = useShippingOption()\n\n return (\n <button\n data-testid=\"btn\"\n onClick={async () => {\n for (const action of actions) {\n // eslint-disable-next-line no-await-in-loop\n await dispatch(action as never)\n }\n }}\n >\n go\n </button>\n )\n}\n\ndescribe('useShippingOption actions and behavior', () => {\n beforeEach(() => {\n jest.clearAllMocks()\n jest.spyOn(client, 'updateSession').mockResolvedValue(undefined)\n jest.spyOn(client, 'getAddress').mockResolvedValue({\n city: 'City',\n geoCoordinates: [1, 2],\n } as never)\n\n jest\n .spyOn(client, 'getCatalogCount')\n .mockResolvedValue({ total: 1 } as never)\n jest.spyOn(client, 'updateOrderForm').mockResolvedValue(undefined as never)\n jest.spyOn(client, 'getCartProducts').mockResolvedValue([] as never)\n jest\n .spyOn(client, 'validateProductAvailability')\n .mockResolvedValue({ unavailableProducts: [] } as never)\n\n const renderRuntime = jest.requireMock('vtex.render-runtime') as {\n useSSR: () => boolean\n useRuntime: () => { account: string }\n }\n\n jest.spyOn(renderRuntime, 'useSSR').mockReturnValue(false)\n jest\n .spyOn(renderRuntime, 'useRuntime')\n .mockReturnValue({ account: 'store' })\n\n const cookie = jest.requireMock('../utils/cookie') as {\n getCountryCode: () => string\n getFacetsData: (k: unknown) => unknown\n }\n\n jest.spyOn(cookie, 'getCountryCode').mockReturnValue('BR')\n jest\n .spyOn(cookie, 'getFacetsData')\n .mockImplementation((key: unknown) =>\n key === 'zip-code' ? '12345-678' : undefined\n )\n\n const reloadMock = jest.fn()\n\n Object.defineProperty(window, 'location', {\n configurable: true,\n value: { ...window.location, reload: reloadMock },\n })\n })\n\n it.each([\n [\n 'UPDATE_ZIPCODE + SELECT_DELIVERY_SHIPPING_OPTION triggers reload',\n [\n {\n type: 'UPDATE_ZIPCODE',\n args: { zipcode: '12345-678', reload: true },\n },\n { type: 'SELECT_DELIVERY_SHIPPING_OPTION' },\n ],\n ],\n [\n 'UPDATE_ZIPCODE + RESET_SHIPPING_OPTION triggers reload',\n [\n {\n type: 'UPDATE_ZIPCODE',\n args: { zipcode: '12345-678', reload: true },\n },\n { type: 'RESET_SHIPPING_OPTION' },\n ],\n ],\n ])('%s', async (_title, actions) => {\n const { getByTestId } = render(<ActionRunner actions={actions} />)\n\n fireEvent.click(getByTestId('btn'))\n\n await waitFor(() => {\n expect(getByTestId('btn')).toBeTruthy()\n })\n })\n\n it('UPDATE_PICKUP sets selected pickup via explicit action', async () => {\n const actions = [\n { type: 'UPDATE_ZIPCODE', args: { zipcode: '12345-678', reload: false } },\n {\n type: 'UPDATE_PICKUP',\n args: {\n pickup: {\n pickupPoint: {\n isActive: true,\n id: 'p1',\n friendlyName: 'Store 1',\n },\n },\n },\n },\n ]\n\n const { getByTestId } = render(<ActionRunner actions={actions} />)\n\n fireEvent.click(getByTestId('btn'))\n\n await waitFor(() => {\n expect(getByTestId('btn')).toBeTruthy()\n })\n })\n\n it('smoke: RESET_SHIPPING_OPTION executes without errors', async () => {\n function ResetComponent() {\n const { dispatch } = useShippingOption()\n\n return (\n <button\n data-testid=\"reset\"\n onClick={() => dispatch({ type: 'RESET_SHIPPING_OPTION' } as never)}\n >\n Reset\n </button>\n )\n }\n\n const { getByTestId } = render(<ResetComponent />)\n\n fireEvent.click(getByTestId('reset'))\n\n await waitFor(() => {\n expect(getByTestId('reset')).toBeTruthy()\n })\n })\n})\n\n```" } ]
code_shipping-option-components_5ed2d504
[ { "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 shipping-option-components/react/__tests__/LocationDetectorButton.test.tsx from the shipping-option-components VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\nimport { render, waitFor } from '@vtex/test-tools/react'\nimport * as reactIntl from 'react-intl'\n\nimport LocationDetectorButton from '../components/LocationDetectorButton'\n\nconst messages = {\n 'store/shipping-option-zipcode.LocationDetectorButton.title':\n 'Use my location',\n 'store/shipping-option-zipcode.LocationDetectorButtonLoading.description':\n 'Detecting location...',\n 'store/shipping-option-zipcode.LocationDetectorButtonError.description':\n 'Location detection failed',\n} as const\n\n// Mock geolocation\nconst mockGeolocation = {\n getCurrentPosition: jest.fn(),\n watchPosition: jest.fn(),\n clearWatch: jest.fn(),\n}\n\n// Mock fetch\nconst mockFetch = jest.fn()\n\n// Mock useRuntime\nconst mockUseRuntime = jest.fn()\n\n// Mock useCssHandles\nconst mockUseCssHandles = jest.fn()\n\n// Mock intl\nconst mockIntl = {\n formatMessage: ({ id }: { id: string }) =>\n messages[id as keyof typeof messages] || id,\n} as reactIntl.IntlShape\n\n// Mock modules\njest.mock('vtex.render-runtime', () => ({\n useRuntime: () => mockUseRuntime(),\n}))\n\njest.mock('vtex.css-handles', () => ({\n useCssHandles: () => mockUseCssHandles(),\n}))\n\njest.mock('../components/EmptyState', () => {\n const MockEmptyState = ({ description }: { description: string }) => (\n <div data-testid=\"empty-state\">{description}</div>\n )\n\n return MockEmptyState\n})\n\njest.mock('../components/PinIcon', () => {\n const MockPinIcon = ({ filled }: { filled: boolean }) => (\n <span\n data-testid=\"pin-icon\"\n data-filled={filled}\n role=\"img\"\n aria-label=\"pin icon\"\n />\n )\n\n return MockPinIcon\n})\n\ndescribe('LocationDetectorButton', () => {\n // Shared test data\n const mockCoordinates = { latitude: -23.5505, longitude: -46.6333 }\n const mockPostcode = '01310-100'\n\n // Helper functions\n const mockSuccessfulGeolocation = () => {\n mockGeolocation.getCurrentPosition.mockImplementation((success) => {\n success({ coords: mockCoordinates })\n })\n }\n\n const mockGeolocationError = (errorMessage = 'Geolocation denied') => {\n mockGeolocation.getCurrentPosition.mockImplementation((_, error) => {\n error(new Error(errorMessage))\n })\n }\n\n const mockSuccessfulFetch = (postcode = mockPostcode) => {\n mockFetch.mockResolvedValue({\n ok: true,\n json: () => Promise.resolve({ address: { postcode } }),\n })\n }\n\n const mockFailedFetch = (status = 500) => {\n mockFetch.mockResolvedValue({ ok: false, status })\n }\n\n // Helper functions that return render results for simpler usage\n const renderWithSuccessfulLocationDetection = () => {\n mockSuccessfulGeolocation()\n mockSuccessfulFetch()\n\n return render(<LocationDetectorButton />)\n }\n\n const renderWithGeolocationError = () => {\n mockGeolocationError()\n\n return render(<LocationDetectorButton />)\n }\n\n const renderWithAPIError = () => {\n mockSuccessfulGeolocation()\n mockFailedFetch()\n\n return render(<LocationDetectorButton />)\n }\n\n beforeEach(() => {\n jest.clearAllMocks()\n\n // Setup default mocks\n Object.defineProperty(global, 'navigator', {\n value: { geolocation: mockGeolocation },\n writable: true,\n })\n\n global.fetch = mockFetch\n\n mockUseRuntime.mockReturnValue({\n culture: { country: 'BRA' },\n route: { path: '/products', queryString: {} },\n })\n\n mockUseCssHandles.mockReturnValue({\n locationDetectorButton: 'locationDetectorButton',\n locationDetectorButtonContainer: 'locationDetectorButtonContainer',\n locationDetectorButtonIcon: 'locationDetectorButtonIcon',\n })\n\n jest.spyOn(reactIntl, 'useIntl').mockImplementation(() => mockIntl)\n\n // Mock btoa\n jest.spyOn(global, 'btoa').mockImplementation((str) => `encoded-${str}`)\n })\n\n afterEach(() => {\n jest.restoreAllMocks()\n })\n\n describe('Initial render conditions', () => {\n it('renders nothing when region_id already exists in queryString', () => {\n mockUseRuntime.mockReturnValue({\n culture: { country: 'BRA' },\n route: {\n path: '/products',\n queryString: { region_id: 'existing-region' },\n },\n })\n\n const { container } = render(<LocationDetectorButton />)\n\n expect(container.firstChild).toBeNull()\n })\n\n it('renders loading state initially when no regionId is set', () => {\n const { getByTestId, getByText } = render(<LocationDetectorButton />)\n\n expect(getByTestId('empty-state')).toBeInTheDocument()\n expect(getByText('Detecting location...')).toBeInTheDocument()\n })\n\n it('renders loading state when geolocation is not supported', () => {\n Object.defineProperty(global, 'navigator', {\n value: {},\n writable: true,\n })\n\n const { getByTestId } = render(<LocationDetectorButton />)\n\n expect(getByTestId('empty-state')).toBeInTheDocument()\n })\n })\n\n describe('Geolocation functionality', () => {\n it('calls geolocation API on mount when available', () => {\n render(<LocationDetectorButton />)\n\n expect(mockGeolocation.getCurrentPosition).toHaveBeenCalledWith(\n expect.any(Function),\n expect.any(Function)\n )\n })\n\n it('renders location button after successful geolocation and API call', async () => {\n const { getByText, getByTestId } = renderWithSuccessfulLocationDetection()\n\n await waitFor(() => {\n expect(getByText('Use my location')).toBeInTheDocument()\n expect(getByTestId('pin-icon')).toBeInTheDocument()\n })\n })\n\n it('handles geolocation error gracefully', async () => {\n const { getByTestId, getByText } = renderWithGeolocationError()\n\n await waitFor(() => {\n expect(getByTestId('empty-state')).toBeInTheDocument()\n expect(getByText('Location detection failed')).toBeInTheDocument()\n })\n })\n\n it('handles API error gracefully', async () => {\n const { getByTestId, getByText } = renderWithAPIError()\n\n await waitFor(() => {\n expect(getByTestId('empty-state')).toBeInTheDocument()\n expect(getByText('Location detection failed')).toBeInTheDocument()\n })\n })\n\n it('shows error state with icon when location detection fails', async () => {\n const { container } = renderWithGeolocationError()\n\n await waitFor(() => {\n const emptyState = container.querySelector(\n '[data-testid=\"empty-state\"]'\n )\n\n expect(emptyState).toBeInTheDocument()\n })\n })\n\n it('maintains error state after geolocation failure', async () => {\n const { getByText } = renderWithGeolocationError()\n\n await waitFor(() => {\n expect(getByText('Location detection failed')).toBeInTheDocument()\n })\n\n // Error state should persist since the component doesn't automatically retry\n expect(getByText('Location detection failed')).toBeInTheDocument()\n })\n })\n\n describe('Link generation and navigation', () => {\n // All tests in this group use successful location detection\n beforeEach(() => {\n mockSuccessfulGeolocation()\n mockSuccessfulFetch()\n })\n\n it('generates correct href with ? separator for empty queryString', async () => {\n mockUseRuntime.mockReturnValue({\n culture: { country: 'BRA' },\n route: { path: '/products', queryString: {} },\n })\n\n const { getByRole } = render(<LocationDetectorButton />)\n\n await waitFor(() => {\n const link = getByRole('link')\n\n expect(link).toHaveAttribute(\n 'href',\n '/products?region_id=encoded-vtex:BRA:01310100'\n )\n })\n })\n\n it('generates correct href with & separator for existing queryString', async () => {\n mockUseRuntime.mockReturnValue({\n culture: { country: 'BRA' },\n route: { path: '/products', queryString: { category: 'electronics' } },\n })\n\n const { getByRole } = render(<LocationDetectorButton />)\n\n await waitFor(() => {\n const link = getByRole('link')\n\n expect(link).toHaveAttribute(\n 'href',\n '/products&region_id=encoded-vtex:BRA:01310100'\n )\n })\n })\n\n it('handles postal codes with hyphens correctly', async () => {\n mockFetch.mockResolvedValue({\n ok: true,\n json: () =>\n Promise.resolve({\n address: { postcode: '01310-100' },\n }),\n })\n\n const { getByRole } = render(<LocationDetectorButton />)\n\n await waitFor(() => {\n const link = getByRole('link')\n\n // Should remove hyphens from postal code\n expect(link).toHaveAttribute(\n 'href',\n '/products?region_id=encoded-vtex:BRA:01310100'\n )\n })\n })\n\n it('handles alternative postal_code field from API', async () => {\n mockFetch.mockResolvedValue({\n ok: true,\n json: () =>\n Promise.resolve({\n address: { postal_code: '90210' },\n }),\n })\n\n const { getByRole } = render(<LocationDetectorButton />)\n\n await waitFor(() => {\n const link = getByRole('link')\n\n expect(link).toHaveAttribute(\n 'href',\n '/products?region_id=encoded-vtex:BRA:90210'\n )\n })\n })\n })\n\n describe('CSS handles and styling', () => {\n it('applies CSS handles correctly', async () => {\n const { container } = renderWithSuccessfulLocationDetection()\n\n // Check loading container handle\n expect(\n container.querySelector('.locationDetectorButtonContainer')\n ).toBeInTheDocument()\n\n // Check button and icon handles after successful load\n await waitFor(() => {\n expect(\n container.querySelector('.locationDetectorButton')\n ).toBeInTheDocument()\n expect(\n container.querySelector('.locationDetectorButtonIcon')\n ).toBeInTheDocument()\n })\n })\n })\n\n describe('Component behavior edge cases', () => {\n it('handles missing postcode in API response', async () => {\n mockSuccessfulGeolocation()\n mockFetch.mockResolvedValue({\n ok: true,\n json: () => Promise.resolve({ address: {} }), // No postcode\n })\n\n const { getByTestId } = render(<LocationDetectorButton />)\n\n await waitFor(() => {\n // Should continue showing loading state when no postcode (not an error)\n expect(getByTestId('empty-state')).toBeInTheDocument()\n })\n })\n })\n})\n\n```" } ]
code_shipping-option-components_07e85552
[ { "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 shipping-option-components/react/__tests__/Client.test.ts from the shipping-option-components VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { getCatalogCount } from '../client'\n\ndescribe('client.getCatalogCount', () => {\n beforeEach(() => {\n jest.clearAllMocks()\n })\n\n it('uses credentials: \"omit\" and does not attach cookies', async () => {\n const mockFetch = jest\n .fn()\n .mockResolvedValue({ json: () => Promise.resolve({}) })\n\n ;(global as any).fetch = mockFetch\n\n await getCatalogCount('12345-678', [0, 0])\n\n expect(mockFetch).toHaveBeenCalledTimes(1)\n // eslint-disable-next-line prefer-destructuring\n const [, options] = mockFetch.mock.calls[0]\n\n expect(options).toMatchObject({\n method: 'GET',\n credentials: 'omit',\n headers: { 'Content-Type': 'application/json' },\n })\n\n // Ensure no Cookie header is forwarded\n expect(options.headers).not.toHaveProperty('Cookie')\n })\n})\n\n```" } ]
code_shipping-option-components_099a2d2a
[ { "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 shipping-option-components/react/__tests__/ShippingOptionContext.test.tsx from the shipping-option-components VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\nimport { screen, render } from '@vtex/test-tools/react'\n\nimport * as useShippingOption from '../context/useShippingOption'\nimport * as ShippingOptionProviderCore from '../context/ShippingOptionProviderCore'\nimport { ShippingOptionProvider } from '../context/ShippingOptionContext'\n\njest.mock('vtex.order-items')\njest.mock('vtex.pixel-manager')\n\n// Note: console.errors are expected in these tests because we are testing error boundaries\n// React always logs errors to console even when they are caught by error boundaries\ndescribe('ShippingOptionContext should render its children even when', () => {\n it('useShippingOption throws an error', () => {\n const mock = jest\n .spyOn(useShippingOption, 'useShippingOption')\n .mockImplementation(() => {\n throw new Error('Test error in useShippingOption')\n })\n\n render(\n <ShippingOptionProvider>\n <span>Children message</span>\n </ShippingOptionProvider>\n )\n\n mock.mockRestore()\n\n expect(screen.queryByText('Children message')).toBeInTheDocument()\n })\n\n it('ShippingOptionContextCore throws an error', () => {\n const mock = jest\n .spyOn(ShippingOptionProviderCore, 'ShippingOptionProviderCore')\n .mockImplementation(() => {\n throw new Error('Test error in ShippingOptionProviderCore')\n })\n\n render(\n <ShippingOptionProvider>\n <span>Children message</span>\n </ShippingOptionProvider>\n )\n\n mock.mockRestore()\n\n expect(screen.queryByText('Children message')).toBeInTheDocument()\n })\n})\n\n```" } ]
code_shipping-option-components_20463e7f
[ { "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 shipping-option-components/react/hooks/useShippingOptions.ts from the shipping-option-components VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\n/* eslint-disable no-restricted-globals */\nimport { useCallback, useEffect, useState } from 'react'\nimport { useRuntime, useSSR } from 'vtex.render-runtime'\nimport { useIntl } from 'react-intl'\nimport { usePixel } from 'vtex.pixel-manager'\n\nimport { getCountryCode, getFacetsData, getOrderFormId } from '../utils/cookie'\nimport messages from '../messages'\nimport {\n getAddress,\n getCartProducts,\n getPickups,\n removeCartProductsById,\n updateOrderForm,\n updateSession,\n} from '../client'\nimport type { CartItem, CartProduct } from '../components/UnavailableItemsModal'\n\ndeclare let window: any\n\nconst useShippingOptions = () => {\n const [inputZipCode, setInputZipCode] = useState<string>()\n const [selectedZipCode, setSelectedZipCode] = useState<string | null>()\n const [isLoading, setIsLoading] = useState(true)\n const [isPageLoading, setIsPageLoading] = useState(true)\n const [countryCode, setCountryCode] = useState<string>()\n const [inputErrorMessage, setInputErrorMessage] = useState<string>()\n const [city, setCity] = useState<string>()\n const [pickups, setPickups] = useState<Pickup[]>([])\n const [selectedPickup, setSelectecPickup] = useState<Pickup>()\n const [geoCoordinates, setGeoCoordinates] = useState<number[]>()\n const [shippingOption, setShippingOption] = useState<\n 'delivery' | 'pickup-in-point'\n >()\n\n const [unavailableCartItems, setUnavailableCartItems] = useState<CartItem[]>(\n []\n )\n\n const isSSR = useSSR()\n const { account } = useRuntime()\n const intl = useIntl()\n const { push } = usePixel()\n\n const fetchPickups = useCallback(\n async (country: string, zipCode: string, coordinates: number[]) => {\n const responsePickups = await getPickups(country, zipCode, account)\n\n setPickups(responsePickups.items)\n\n if (responsePickups?.items?.length === 0) {\n setIsLoading(false)\n\n return\n }\n\n const pickupPointId = getFacetsData('pickupPoint')\n\n if (pickupPointId) {\n const pickup = responsePickups.items.find(\n (p: any) => p.pickupPoint.id === pickupPointId\n )\n\n setSelectecPickup(pickup)\n await updateSession(\n country,\n zipCode,\n coordinates,\n pickup,\n shippingOption\n )\n }\n\n setIsLoading(false)\n },\n [account, shippingOption]\n )\n\n useEffect(() => {\n if (isSSR) {\n return\n }\n\n const segmentZipCode = getFacetsData('zip-code')\n const segmentCountryCode = getCountryCode()\n const segmentShippingOption = getFacetsData('shipping')\n\n setSelectedZipCode(segmentZipCode ?? null)\n setInputZipCode(segmentZipCode)\n setCountryCode(segmentCountryCode)\n setShippingOption(segmentShippingOption as 'delivery' | 'pickup-in-point')\n\n if (segmentZipCode) {\n getAddress(segmentCountryCode, segmentZipCode, account).then((res) => {\n setCity(res.city)\n setGeoCoordinates(res.geoCoordinates)\n fetchPickups(segmentCountryCode, segmentZipCode, res.geoCoordinates)\n })\n } else {\n setIsLoading(false)\n }\n }, [account, isSSR, fetchPickups])\n\n const onError = (message: string) => {\n setInputErrorMessage(message)\n setIsLoading(false)\n\n setTimeout(() => {\n setInputErrorMessage(undefined)\n }, 3000)\n }\n\n const onSelectPickup = async (pickup: Pickup, shouldPersistFacet = true) => {\n setSelectecPickup(pickup)\n\n if (!countryCode || !selectedZipCode || !geoCoordinates) {\n return\n }\n\n await updateSession(\n countryCode,\n selectedZipCode,\n geoCoordinates,\n pickup,\n shouldPersistFacet ? 'pickup-in-point' : shippingOption\n )\n\n location.reload()\n }\n\n const handleIsLoading = () => {\n setIsLoading(true)\n setIsPageLoading(false)\n }\n\n const validateCartItems = async () => {\n const orderFormId = getOrderFormId()\n\n const products = await getCartProducts(orderFormId)\n\n // IMPORTANT: validate products here\n // Task: TIS-189\n const unavailableItems = products.map(\n (product: CartProduct, id: number) => ({\n cartItemIndex: id,\n product,\n })\n )\n\n setUnavailableCartItems(unavailableItems)\n\n return unavailableItems\n }\n\n const onSubmit = async (reload = true) => {\n if (!countryCode) {\n return false\n }\n\n if (!inputZipCode) {\n onError(intl.formatMessage(messages.postalCodeInputPlaceHolder))\n\n return false\n }\n\n setPickups([])\n setCity(undefined)\n\n handleIsLoading()\n\n const orderFormId = getOrderFormId()\n\n if (orderFormId) {\n await updateOrderForm(countryCode, inputZipCode, orderFormId)\n }\n\n const { geoCoordinates: coordinates } = await getAddress(\n countryCode,\n inputZipCode,\n account\n )\n\n if (coordinates.length === 0) {\n onError(intl.formatMessage(messages.postalCodeInputError))\n\n return false\n }\n\n const unavailableItems = await validateCartItems()\n\n if (unavailableItems.length > 0) {\n setIsLoading(false)\n\n return false\n }\n\n setGeoCoordinates(coordinates)\n\n setSelectedZipCode(inputZipCode)\n\n await updateSession(countryCode, inputZipCode, coordinates)\n\n await fetchPickups(countryCode, inputZipCode, coordinates)\n\n if (!reload) {\n setIsLoading(false)\n }\n\n if (reload) {\n location.reload()\n }\n\n return true\n }\n\n const removeUnavailableItems = async () => {\n const orderFormId = getOrderFormId()\n\n await removeCartProductsById(\n orderFormId,\n unavailableCartItems.map((item) => item.cartItemIndex)\n )\n\n onSubmit()\n }\n\n const onChange = (zipCode?: string) => {\n setInputZipCode(zipCode)\n }\n\n const addressLabel = city ? `${selectedZipCode}, ${city}` : selectedZipCode\n\n useEffect(() => {\n window.addressLabel = addressLabel\n push({\n id: 'shipping-option-addressLabel',\n label: addressLabel,\n })\n }, [addressLabel, push])\n\n const pickupPointLabel = selectedPickup\n ? selectedPickup.pickupPoint.friendlyName\n : ''\n\n useEffect(() => {\n window.pickupPointLabel = pickupPointLabel\n push({\n id: 'shipping-option-pickupPointLabel',\n label: pickupPointLabel,\n })\n }, [pickupPointLabel, push])\n\n const isFirstLoading = isPageLoading && isLoading\n\n return {\n zipCode: inputZipCode,\n selectedZipCode,\n isLoading,\n isFirstLoading,\n inputErrorMessage,\n onSubmit,\n onChange,\n addressLabel,\n city,\n pickups,\n selectedPickup,\n onSelectPickup,\n geoCoordinates,\n shippingOption,\n countryCode,\n unavailableCartItems,\n removeUnavailableItems,\n }\n}\n\nexport default useShippingOptions\n\n```" } ]
code_shipping-option-components_977d664a
[ { "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 shipping-option-components/react/components/UnavailableItemsModal/index.tsx from the shipping-option-components VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\n/* eslint-disable no-restricted-globals */\nimport React, { useState } from 'react'\nimport { Button } from 'vtex.styleguide'\nimport { useIntl } from 'react-intl'\n\nimport Modal from '../Modal'\nimport ProductItem from './ProductItem'\nimport messages from '../../messages'\n\nexport type CartProduct = { id: string; name: string; imageUrl: string }\n\nexport type CartItem = {\n cartItemIndex: number\n product: CartProduct\n}\n\ninterface Props {\n isOpen: boolean\n onClose: () => void\n onTryAgain: () => void\n onRemoveItems: () => void\n unavailableCartItems: CartItem[]\n unavailabilityMessage?: string\n}\n\nconst UnavailableItemsModal = ({\n isOpen,\n onClose,\n onTryAgain,\n onRemoveItems,\n unavailableCartItems,\n unavailabilityMessage,\n}: Props) => {\n const intl = useIntl()\n\n const [isLoading, setIsLoading] = useState(false)\n\n const handleRemoveItemsClick = async () => {\n setIsLoading(true)\n await onRemoveItems()\n\n onClose()\n }\n\n return (\n <Modal\n showArrowBack={false}\n isTopCloseButton={false}\n title={intl.formatMessage(messages.unavailableItemsModalTitle)}\n isOpen={isOpen}\n onClose={onClose}\n nonDismissible\n >\n <div className=\"flex-auto flex flex-column justify-between mt0\">\n <p className=\"mid-gray ma0\">{unavailabilityMessage}</p>\n <div className=\"mv7 overflow-auto\">\n {unavailableCartItems.map(({ product }) => (\n <ProductItem\n key={product.id}\n imageUrl={product.imageUrl}\n productName={product.name}\n />\n ))}\n </div>\n <div style={{ gap: '.75rem' }} className=\"flex flex-column\">\n <Button\n className=\"mb3\"\n isLoading={isLoading}\n onClick={handleRemoveItemsClick}\n >\n {intl.formatMessage(messages.unavailableItemsModalRemoveButton)}\n </Button>\n <Button\n isLoading={isLoading}\n variation=\"secondary\"\n onClick={onTryAgain}\n >\n {intl.formatMessage(messages.unavailableItemsModalRetryButton)}\n </Button>\n </div>\n </div>\n </Modal>\n )\n}\n\nexport default UnavailableItemsModal\n\n```" } ]
code_shipping-option-components_dc365659
[ { "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 shipping-option-components/react/components/UnavailableItemsModal/ProductItem.tsx from the shipping-option-components VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\n\ninterface Props {\n imageUrl: string\n productName: string\n}\n\nconst ProductItem = ({ imageUrl, productName }: Props) => {\n return (\n <div className=\"flex flex-row pa5 bg-base t-body c-on-base br3 b--muted-4 ba mb5\">\n <img\n className=\"br2\"\n style={{ width: '64px', height: '64px' }}\n src={imageUrl}\n alt={productName}\n />\n <p className=\"ml6\">{productName}</p>\n </div>\n )\n}\n\nexport default ProductItem\n\n```" } ]
code_shipping-option-components_70b38ce7
[ { "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 shipping-option-components/react/components/LocationModal/index.tsx from the shipping-option-components VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React, { useEffect, useState } from 'react'\nimport { useIntl } from 'react-intl'\n\nimport AddLocation from './AddLocation'\nimport Modal from '../Modal'\nimport messages from '../../messages'\nimport EmptyState from '../EmptyState'\nimport type { ZipCodeError } from '../../context/ShippingOptionContext'\nimport { PRODUCTS_NOT_FOUND_ERROR_CODE } from '../../constants'\n\nconst LOCATION_SELECTION = 'locationSelection'\nconst NO_PICKUP_STATE = 'noPickupState'\n\ntype Stages = 'locationSelection' | 'noPickupState'\n\ninterface Props {\n isOpen: boolean\n onClose: () => void\n onSubmit: (zipCode: string) => void\n isLoading?: boolean\n inputErrorMessage?: ZipCodeError\n selectedZipcode?: string\n nonDismissibleModal?: boolean\n showLocationDetectorButton?: boolean\n}\n\nconst LocationModal = ({\n isOpen,\n onClose,\n onSubmit,\n isLoading,\n inputErrorMessage,\n selectedZipcode,\n nonDismissibleModal,\n showLocationDetectorButton = false,\n}: Props) => {\n const [zipcode, setZipcode] = useState<string>('')\n const [stage, setStage] = useState<Stages>(LOCATION_SELECTION)\n const intl = useIntl()\n\n useEffect(() => setZipcode(selectedZipcode ?? ''), [selectedZipcode])\n\n useEffect(() => {\n if (inputErrorMessage?.code === PRODUCTS_NOT_FOUND_ERROR_CODE) {\n setStage(NO_PICKUP_STATE)\n }\n }, [inputErrorMessage])\n\n const stageContent: StageContent = {\n locationSelection: {\n title: intl.formatMessage(messages.locationModalTitle),\n content: (\n <AddLocation\n onSubmit={onSubmit}\n showLocationDetectorButton={showLocationDetectorButton}\n isLoading={isLoading}\n inputErrorMessage={inputErrorMessage?.message}\n onChange={(value: string) => setZipcode(value)}\n zipcode={zipcode}\n />\n ),\n },\n noPickupState: {\n title: '',\n content: (\n <EmptyState\n title={intl.formatMessage(messages.noPickupsStateTitle)}\n description={intl.formatMessage(messages.noPickupsStateDescription, {\n postalCode: ` ${zipcode}`,\n })}\n buttonLabel={intl.formatMessage(messages.noPickupsStateButtonLabel)}\n onClick={() => setStage(LOCATION_SELECTION)}\n variant=\"secondary\"\n />\n ),\n },\n }\n\n return (\n <Modal\n onArrowBack={() => {}}\n showArrowBack={false}\n isTopCloseButton\n title={stageContent[stage].title}\n isOpen={isOpen}\n onClose={onClose}\n nonDismissible={nonDismissibleModal}\n >\n {stageContent[stage].content}\n </Modal>\n )\n}\n\nexport default LocationModal\n\n```" } ]
code_shipping-option-components_0ffe9412
[ { "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 shipping-option-components/react/components/LocationModal/AddLocation.tsx from the shipping-option-components VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\nimport { Button } from 'vtex.styleguide'\nimport { useIntl } from 'react-intl'\n\nimport PostalCodeInput from '../PostalCodeInput'\nimport messages from '../../messages'\nimport PostalCodeHelpLink from '../PostalCodeHelpLink'\nimport LocationDetectorButton from '../LocationDetectorButton'\n\ninterface AddLocationProps {\n onSubmit: (zipcode: string) => void\n onChange: (zipCode: string) => void\n zipcode: string\n isLoading?: boolean\n inputErrorMessage?: string\n showLocationDetectorButton?: boolean\n}\n\nconst AddLocation = ({\n onSubmit,\n onChange,\n zipcode,\n isLoading,\n inputErrorMessage,\n showLocationDetectorButton,\n}: AddLocationProps) => {\n const intl = useIntl()\n\n return (\n <div className=\"flex-auto flex flex-column justify-between mt0\">\n <p className=\"mid-gray ma0\">\n {intl.formatMessage(messages.locationModalDescription)}\n </p>\n\n <div>\n <PostalCodeInput\n onChange={(value: string) => onChange(value)}\n zipcode={zipcode}\n onSubmit={onSubmit}\n errorMessage={inputErrorMessage}\n showClearButton={false}\n placeholder={intl.formatMessage(\n messages.popoverPostalCodeInputPlaceHolder\n )}\n />\n <div className=\"mt3\">\n <PostalCodeHelpLink />\n </div>\n </div>\n\n <Button isLoading={isLoading} onClick={() => onSubmit(zipcode)}>\n {intl.formatMessage(messages.popoverSubmitButtonLabel)}\n </Button>\n {showLocationDetectorButton && <LocationDetectorButton />}\n </div>\n )\n}\n\nexport default AddLocation\n\n```" } ]
code_shipping-option-components_b2b6610a
[ { "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 shipping-option-components/react/components/PickupSelection/index.tsx from the shipping-option-components VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React, { useEffect, useState } from 'react'\nimport { useIntl } from 'react-intl'\n\nimport PostalCodeInput from '../PostalCodeInput'\nimport messages from '../../messages'\nimport EmptyState from '../EmptyState'\nimport PickupList from './PickupList'\n\ninterface Props {\n onSubmit: (zipCode: string) => void\n inputErrorMessage?: string\n selectedZipcode?: string\n pickups: Pickup[]\n selectedPickup?: Pickup\n onSelectPickup: (pickup: Pickup, shouldPersistFacet?: boolean) => void\n onDeliverySelection?: () => void\n isLoading: boolean\n}\n\nconst PickupSelection = ({\n onSubmit,\n inputErrorMessage,\n selectedZipcode,\n pickups,\n selectedPickup,\n onSelectPickup,\n onDeliverySelection,\n isLoading,\n}: Props) => {\n const [zipcode, setZipcode] = useState<string>('')\n const intl = useIntl()\n\n useEffect(() => setZipcode(selectedZipcode ?? ''), [selectedZipcode])\n\n return (\n <div className=\"flex flex-column mt5 vh-100\">\n <div className=\"mb7\">\n <PostalCodeInput\n onChange={(value: string) => setZipcode(value)}\n zipcode={zipcode}\n onSubmit={onSubmit}\n errorMessage={inputErrorMessage}\n placeholder={intl.formatMessage(messages.postalCodeInputPlaceHolder)}\n />\n </div>\n {pickups.length === 0 && !isLoading ? (\n <EmptyState\n onClick={onDeliverySelection}\n buttonLabel={intl.formatMessage(messages.noStoresStateButton)}\n title={intl.formatMessage(messages.noStoresStateTitle)}\n description={intl.formatMessage(messages.noStoresStateDescription, {\n postalCode: ` ${zipcode}`,\n })}\n />\n ) : (\n <PickupList\n pickups={pickups}\n onSelectPickup={onSelectPickup}\n selectedPickup={selectedPickup}\n />\n )}\n </div>\n )\n}\n\nexport default PickupSelection\n\n```" } ]
code_shipping-option-components_68c0f1ce
[ { "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 shipping-option-components/react/components/PickupSelection/PickupItem.tsx from the shipping-option-components VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\nimport { useCssHandles } from 'vtex.css-handles'\n\nimport '../../styles.css'\n\ninterface Props {\n pickup: Pickup\n onClick: () => void\n selected: boolean\n}\n\nconst CSS_HANDLES = ['pickupItem', 'pickupItemSelected'] as const\n\nconst PickupItem = ({ pickup, onClick, selected }: Props) => {\n const {\n distance,\n pickupPoint: {\n friendlyName,\n address: { city, neighborhood, number, postalCode, street },\n },\n } = pickup\n\n const handle = useCssHandles(CSS_HANDLES)\n\n return (\n <button\n style={{\n padding: '1.25rem',\n backgroundColor: 'unset',\n marginBottom: '1.25rem',\n }}\n className={`${handle.pickupItem} ${\n selected ? `${handle.pickupItemSelected} bw1 b--action-primary` : ''\n } pointer relative hover-b--gray b--black-10 ba br2`}\n onClick={onClick}\n >\n <p className=\"f4 tl ma0 fw6 mb2\" style={{ maxWidth: '80%' }}>\n {friendlyName}\n </p>\n <p className=\"mid-gray f6 ma0 tl\">{`${number} ${street}`}</p>\n <p className=\"mid-gray f6 ma0 tl\">{`${neighborhood}, ${city}, ${postalCode}`}</p>\n <span className=\"mid-gray absolute top-1 right-1\">\n {distance.toFixed(1)} Km\n </span>\n </button>\n )\n}\n\nexport default PickupItem\n\n```" } ]
code_shipping-option-components_26c994f2
[ { "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 shipping-option-components/react/components/PickupSelection/PickupList.tsx from the shipping-option-components VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React, { useEffect, useState } from 'react'\nimport { useIntl } from 'react-intl'\nimport { Button } from 'vtex.styleguide'\nimport { useCssHandles } from 'vtex.css-handles'\n\nimport messages from '../../messages'\nimport PickupItem from './PickupItem'\n\nconst CSS_HANDLES = ['updateButtonContainer'] as const\n\ninterface Props {\n pickups: Pickup[]\n selectedPickup?: Pickup\n onSelectPickup: (pickup: Pickup, shouldPersistFacet?: boolean) => void\n}\n\nconst PickupList = ({ pickups, selectedPickup, onSelectPickup }: Props) => {\n const handle = useCssHandles(CSS_HANDLES)\n const intl = useIntl()\n const [highlightedPickup, setHighlightedPickup] = useState<Pickup>()\n\n useEffect(() => {\n if (selectedPickup) {\n setHighlightedPickup(selectedPickup)\n }\n }, [selectedPickup])\n\n const showUpdateButton =\n selectedPickup &&\n highlightedPickup &&\n highlightedPickup.pickupPoint.id !== selectedPickup.pickupPoint.id\n\n const handleClickItem = (pickup: Pickup) => {\n setHighlightedPickup(pickup)\n\n if (\n !selectedPickup ||\n selectedPickup.pickupPoint.id === pickup.pickupPoint.id\n ) {\n onSelectPickup(pickup)\n }\n }\n\n return (\n <>\n <div className=\"m-100 flex flex-column justify-center\">\n {pickups.map((currentPickup) => (\n <PickupItem\n key={currentPickup.pickupPoint.id}\n selected={\n !!highlightedPickup &&\n highlightedPickup.pickupPoint.id === currentPickup.pickupPoint.id\n }\n onClick={() => handleClickItem(currentPickup)}\n pickup={currentPickup}\n />\n ))}\n </div>\n {showUpdateButton && (\n <div\n style={{ bottom: '-30px' }}\n className={`sticky left-0 bottom-0 w-100 flex justify-center ${handle.updateButtonContainer}`}\n >\n <Button\n block\n onClick={() => {\n onSelectPickup(highlightedPickup as Pickup)\n }}\n >\n {intl.formatMessage(messages.updateButtonLabel)}\n </Button>\n </div>\n )}\n </>\n )\n}\n\nexport default PickupList\n\n```" } ]
code_shipping-option-components_5a61403f
[ { "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 shipping-option-components/react/components/ShippingSelectionModal/index.tsx from the shipping-option-components VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\n/* eslint-disable no-restricted-globals */\nimport React, { useState } from 'react'\nimport { useIntl } from 'react-intl'\n\nimport Modal from '../Modal'\nimport ShippingMethodStage from './ShippingMethodStage'\nimport PickupSelection from '../PickupSelection'\nimport messages from '../../messages'\n\ninterface Props {\n pickupProps: React.ComponentProps<typeof PickupSelection>\n isOpen: boolean\n onClose: () => void\n selectedShipping?: 'delivery' | 'pickup-in-point'\n nonDismissibleModal: boolean\n onDeliverySelection: () => void\n onPickupMethodSelection?: () => void\n}\n\ntype Stages = 'shippingSelection' | 'pickupSelection'\n\nconst ShippingSelectionModal = ({\n pickupProps,\n isOpen,\n onClose,\n selectedShipping,\n nonDismissibleModal,\n onDeliverySelection,\n onPickupMethodSelection,\n}: Props) => {\n const intl = useIntl()\n const {\n onSelectPickup,\n onSubmit,\n pickups,\n inputErrorMessage,\n selectedPickup,\n selectedZipcode,\n isLoading,\n } = pickupProps\n\n const [stage, setStage] = useState<Stages>('shippingSelection')\n\n const stageContent: StageContent = {\n shippingSelection: {\n title: intl.formatMessage(messages.shippingSelectionModalTitle),\n content: (\n <ShippingMethodStage\n selectedShipping={selectedShipping}\n onDeliverySelection={onDeliverySelection}\n onPickupSelection={() => {\n if (onPickupMethodSelection) {\n onPickupMethodSelection()\n }\n\n setStage('pickupSelection')\n }}\n />\n ),\n },\n pickupSelection: {\n title: intl.formatMessage(messages.pickupSelectionTitle),\n content: (\n <PickupSelection\n isLoading={isLoading}\n onSelectPickup={onSelectPickup}\n onSubmit={onSubmit}\n pickups={pickups}\n inputErrorMessage={inputErrorMessage}\n selectedPickup={selectedPickup}\n selectedZipcode={selectedZipcode}\n onDeliverySelection={onDeliverySelection}\n />\n ),\n },\n }\n\n return (\n <Modal\n onArrowBack={() => setStage('shippingSelection')}\n showArrowBack={stage !== 'shippingSelection'}\n isTopCloseButton={stage === 'shippingSelection'}\n title={stageContent[stage].title}\n isOpen={isOpen}\n onClose={onClose}\n nonDismissibleModal={nonDismissibleModal}\n >\n {stageContent[stage].content}\n </Modal>\n )\n}\n\nexport default ShippingSelectionModal\n\n```" } ]
code_shipping-option-components_0b57a370
[ { "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 shipping-option-components/react/components/ShippingSelectionModal/ShippingIcon.tsx from the shipping-option-components VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\n\ninterface Props {\n width?: number\n height?: number\n}\n\nconst ShippingIcon = ({ width = 32, height = 33 }: Props) => (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width={width}\n height={height}\n viewBox=\"0 0 32 33\"\n fill=\"none\"\n >\n <mask\n id=\"mask0_32_109\"\n maskUnits=\"userSpaceOnUse\"\n x=\"0\"\n y=\"0\"\n width=\"32\"\n height=\"33\"\n >\n <rect y=\"0.5\" width=\"32\" height=\"32\" fill=\"#D9D9D9\" />\n </mask>\n <g mask=\"url(#mask0_32_109)\">\n <path\n d=\"M15.1627 27.0657V16.9754L6.34233 11.8744V21.7344C6.34233 21.8026 6.35933 21.8666 6.39333 21.9264C6.42755 21.9864 6.47888 22.0377 6.54733 22.0804L15.1627 27.0657ZM16.838 27.0657L25.4533 22.0804C25.5218 22.0377 25.5731 21.9864 25.6073 21.9264C25.6413 21.8666 25.6583 21.8026 25.6583 21.7344V11.8607L16.838 16.9754V27.0657ZM14.9577 28.8734L5.70966 23.5394C5.38144 23.3536 5.12566 23.0989 4.94233 22.7754C4.75877 22.4516 4.66699 22.1039 4.66699 21.7324V11.2677C4.66699 10.8961 4.75877 10.5485 4.94233 10.2247C5.12566 9.90113 5.38144 9.64647 5.70966 9.46069L14.9577 4.12669C15.2859 3.94091 15.6334 3.84802 16.0003 3.84802C16.3672 3.84802 16.7148 3.94091 17.043 4.12669L26.291 9.46069C26.6192 9.64647 26.875 9.90113 27.0583 10.2247C27.2419 10.5485 27.3337 10.8961 27.3337 11.2677V21.7324C27.3337 22.1039 27.2419 22.4516 27.0583 22.7754C26.875 23.0989 26.6192 23.3536 26.291 23.5394L17.043 28.8734C16.7148 29.0591 16.3672 29.152 16.0003 29.152C15.6334 29.152 15.2859 29.0591 14.9577 28.8734ZM21.2047 12.5154L24.7073 10.4934L16.2053 5.57436C16.1371 5.53724 16.0688 5.51869 16.0003 5.51869C15.9319 5.51869 15.8635 5.53724 15.7953 5.57436L12.5123 7.46669L21.2047 12.5154ZM16.0003 15.5497L19.5243 13.4934L10.8037 8.45902L7.27966 10.4934L16.0003 15.5497Z\"\n fill=\"#505050\"\n />\n </g>\n </svg>\n)\n\nexport default ShippingIcon\n\n```" } ]
code_shipping-option-components_2aa50f95
[ { "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 shipping-option-components/react/components/ShippingSelectionModal/DeliveryModalButton.tsx from the shipping-option-components VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\nimport { useCssHandles } from 'vtex.css-handles'\nimport { Spinner } from 'vtex.styleguide'\nimport { useDevice } from 'vtex.device-detector'\n\nimport ShippingIcon from './ShippingIcon'\nimport PickupIcon from './PickupIcon'\nimport DeliveryIcon from './DeliveryIcon'\n\ninterface Props {\n onClick: () => void\n selectedShipping?: 'delivery' | 'pickup-in-point'\n selectedPickup?: Pickup\n loading: boolean\n}\n\nconst CSS_HANDLES = [\n 'deliveryModalButton',\n 'deliveryModalButtonLabel',\n 'deliveryModalButtonLabelLimited',\n]\n\nconst SHIPPING_ICONS = {\n 'pickup-in-point': <PickupIcon width={24} height={24} />,\n delivery: <DeliveryIcon width={24} height={22.5} />,\n}\n\nconst DeliveryModalButton = ({\n selectedShipping,\n onClick,\n selectedPickup,\n loading,\n}: Props) => {\n const handles = useCssHandles(CSS_HANDLES)\n const { isMobile } = useDevice()\n\n return (\n <button\n onClick={onClick}\n className={`flex flex-row items-center pa4 ${handles.deliveryModalButton}`}\n >\n {selectedShipping ? (\n SHIPPING_ICONS[selectedShipping]\n ) : (\n <span>\n <ShippingIcon width={32} height={32} />\n </span>\n )}\n {!isMobile && (\n <>\n {loading ? (\n <span className=\"ml3\">\n <Spinner size={14} />\n </span>\n ) : (\n <span\n className={`${handles.deliveryModalButtonLabel} ${\n selectedShipping === 'pickup-in-point'\n ? handles.deliveryModalButtonLabelLimited\n : ''\n } c-action-primary`}\n >\n {selectedShipping\n ? selectedShipping === 'delivery'\n ? 'Filtrando por entrega'\n : selectedPickup?.pickupPoint.friendlyName\n : 'Filtrar por envío'}\n </span>\n )}\n </>\n )}\n </button>\n )\n}\n\nexport default DeliveryModalButton\n\n```" } ]
code_shipping-option-components_b9e8074c
[ { "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 shipping-option-components/react/components/ShippingSelectionModal/DeliveryIcon.tsx from the shipping-option-components VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\n\ninterface Props {\n width?: number\n height?: number\n}\n\nconst DeliveryIcon = ({ width = 34, height = 32 }: Props) => (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width={width}\n height={height}\n viewBox=\"0 0 34 32\"\n fill=\"none\"\n >\n <path\n d=\"M8.27603 16H3.91309\"\n stroke=\"#3F3F40\"\n strokeWidth=\"2\"\n strokeMiterlimit=\"10\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n />\n <path\n d=\"M8.2767 23.5007H6.82239\"\n stroke=\"#3F3F40\"\n strokeWidth=\"2\"\n strokeMiterlimit=\"10\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n />\n <path\n d=\"M25.4797 25.0012H32C32.5523 25.0012 33 24.5535 33 24.0012V16.6103C33 16.236 32.791 15.893 32.4583 15.7215L27.1827 13.0007L25.9137 7.76493C25.805 7.31637 25.4034 7.00049 24.9418 7.00049H14.0939V25.0012H17.2512\"\n stroke=\"#3F3F40\"\n strokeWidth=\"2\"\n strokeMiterlimit=\"10\"\n />\n <path\n d=\"M1 8.5H8.27158\"\n stroke=\"#3F3F40\"\n strokeWidth=\"2\"\n strokeMiterlimit=\"10\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n />\n <path\n d=\"M1 0.999756H14.0888V6.99999\"\n stroke=\"#3F3F40\"\n strokeWidth=\"2\"\n strokeMiterlimit=\"10\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n />\n <path\n d=\"M21.3554 31.0001C23.765 31.0001 25.7183 28.9853 25.7183 26.4999C25.7183 24.0146 23.765 21.9998 21.3554 21.9998C18.9458 21.9998 16.9924 24.0146 16.9924 26.4999C16.9924 28.9853 18.9458 31.0001 21.3554 31.0001Z\"\n stroke=\"#3F3F40\"\n strokeWidth=\"2\"\n strokeMiterlimit=\"10\"\n strokeLinecap=\"square\"\n />\n </svg>\n)\n\nexport default DeliveryIcon\n\n```" } ]
code_shipping-option-components_6074fc08
[ { "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 shipping-option-components/react/components/ShippingSelectionModal/PickupIcon.tsx from the shipping-option-components VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\nimport { useCssHandles } from 'vtex.css-handles'\n\ninterface Props {\n width?: number\n height?: number\n}\n\nconst CSS_HANDLES = ['pickupIconPath', 'pickupIconSVG'] as const\n\nconst PickupIcon = ({ width = 34, height = 34 }: Props) => {\n const handles = useCssHandles(CSS_HANDLES)\n\n return (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width={width}\n height={height}\n viewBox=\"0 0 34 34\"\n fill=\"none\"\n className={handles.pickupIconSVG}\n >\n <path\n d=\"M27.6667 1H6.33333L1 10.6C1 13.5461 3.3872 15.9333 6.33333 15.9333C9.27947 15.9333 11.6667 13.5461 11.6667 10.6C11.6667 13.5461 14.0539 15.9333 17 15.9333C19.9461 15.9333 22.3333 13.5461 22.3333 10.6C22.3333 13.5461 24.7205 15.9333 27.6667 15.9333C30.6128 15.9333 33 13.5461 33 10.6L27.6667 1Z\"\n stroke=\"#3F3F40\"\n strokeWidth=\"2\"\n strokeMiterlimit=\"10\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className={handles.pickupIconPath}\n />\n <path\n d=\"M29 21V33H5V21\"\n stroke=\"#3F3F40\"\n strokeWidth=\"2\"\n strokeMiterlimit=\"10\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className={handles.pickupIconPath}\n />\n <path\n d=\"M13.7998 33.0001V24.4668H20.1998V33.0001\"\n stroke=\"#3F3F40\"\n strokeWidth=\"2\"\n strokeMiterlimit=\"10\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className={handles.pickupIconPath}\n />\n </svg>\n )\n}\n\nexport default PickupIcon\n\n```" } ]
code_shipping-option-components_1e664bdf
[ { "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 shipping-option-components/react/components/ShippingSelectionModal/ShippingSelectionOptionButton.tsx from the shipping-option-components VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\nimport { useCssHandles } from 'vtex.css-handles'\n\ninterface Props {\n onClick: () => void\n icon: React.ReactNode\n label: string\n isSelected: boolean\n}\n\nconst CSS_HANDLES = ['shippingOptionButton', 'shippingOptionButtonSelected']\n\nconst ShippingOptionButton = ({ icon, label, onClick, isSelected }: Props) => {\n const handles = useCssHandles(CSS_HANDLES)\n\n return (\n <button\n onClick={onClick}\n className={`br2 w-100 ${handles.shippingOptionButton} ${\n isSelected ? handles.shippingOptionButtonSelected : ''\n }`}\n >\n <div className=\"flex items-center\">\n {icon}\n <p className=\"f3 ml4 mt0 mb0 tc\">{label}</p>\n </div>\n </button>\n )\n}\n\nexport default ShippingOptionButton\n\n```" } ]
code_shipping-option-components_a03484ba
[ { "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 shipping-option-components/react/components/ShippingSelectionModal/ShippingMethodStage.tsx from the shipping-option-components VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\nimport { useCssHandles } from 'vtex.css-handles'\nimport { useIntl } from 'react-intl'\n\nimport ShippingSelectionOptionButton from './ShippingSelectionOptionButton'\nimport DeliveryIcon from './DeliveryIcon'\nimport PickupIcon from './PickupIcon'\nimport messages from '../../messages'\n\nconst CSS_HANDLES = ['shippingMethodModalOptions']\n\ninterface Props {\n onPickupSelection: () => void\n onDeliverySelection: () => void\n selectedShipping?: 'delivery' | 'pickup-in-point'\n}\n\nconst ShippingMethodStage = ({\n onDeliverySelection,\n onPickupSelection,\n selectedShipping,\n}: Props) => {\n const intl = useIntl()\n const handles = useCssHandles(CSS_HANDLES)\n\n return (\n <>\n <p className=\"mid-gray ma0\">\n {intl.formatMessage(messages.shippingSelectionModalDescription)}\n </p>\n <div\n className={`flex flex-column w-100 mt8 justify-around ${handles.shippingMethodModalOptions}`}\n >\n <ShippingSelectionOptionButton\n onClick={onDeliverySelection}\n icon={<DeliveryIcon />}\n label={intl.formatMessage(\n messages.shippingSelectionModalDeliveryButton\n )}\n isSelected={selectedShipping === 'delivery'}\n />\n <ShippingSelectionOptionButton\n onClick={onPickupSelection}\n icon={<PickupIcon />}\n label={intl.formatMessage(\n messages.shippingSelectionModalPickupButton\n )}\n isSelected={selectedShipping === 'pickup-in-point'}\n />\n </div>\n </>\n )\n}\n\nexport default ShippingMethodStage\n\n```" } ]
code_policies-example_8cbc3acf
[ { "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 policies-example/docs/README.md from the policies-example VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```markdown\n\n\n# Service Example\n\nA reference app implementing a VTEX IO service with HTTP route handlers.\n\n![Service Example Architecture](https://user-images.githubusercontent.com/18706156/77381360-72489680-6d5c-11ea-9da8-f4f03b6c5f4c.jpg)\n\nWe use [**KoaJS**](https://koajs.com/) as the web framework, so you might want to get into that\n\nWe also use the [**node-vtex-api**](https://github.com/vtex/node-vtex-api), a VTEX set of utilities for Node services. You can import this package using NPM from `@vtex/api` (already imported on this project)\n\n- Start from `node/index.ts` and follow the comments and imports :)\n\n## Recipes\n\n### Defining routes on _service.json_ \n```json\n{\n \"memory\": 256,\n \"ttl\": 10,\n \"timeout\": 2,\n \"minReplicas\": 2,\n \"maxReplicas\": 4,\n \"routes\": {\n \"status\": {\n \"path\": \"/_v/status/:code\",\n \"public\": true\n }\n }\n}\n```\n\nThe `service.json` file that sits on the root of the `node` folder holds informations about this service, like the maximum timeout and number of replicas, what might be discontinued on the future, but also **sets its routes**. \n\nKoa uses the [path-to-regexp](https://github.com/pillarjs/path-to-regexp) format for defining routes and, as seen on the example, we use the `:code` notation for declaring a **route param** named code, in this case. A HTTP request for `https://{{workspace}}--{{account}}.myvtex.com/_v/status/500` will match the route we've defined. \n\nFor cach _key_ on the `routes` object, there should be a **corresponding entry** on the exported Service object on `node/index.ts`, this will hook your code to a specific route.\n\n### Access Control\nYou can also provide a `public` option for each route. If `true`, that resource will be reachable for everyone on the internet. If `false`, VTEX credentials will be requested as well.\n\nAnother way of controlling access to specific routes is using **ReBACs (Resource-based access)**, that supports more robust configuration. You can read more [on this document](https://docs.google.com/document/d/1ZxNHMFIXfXz3BgTN9xyrHL3V5dYz14wivYgQjRBZ6J8/edit#heading=h.z7pad3qd2qw7) (VTEX only).\n\n#### Query String\nFor `?accepting=query-string`, you **don't need to declare anything**, as any query provided to the URL will already be available for you to use on the code as `ctx.query`, already parsed as an object, or `ctx.queryString`, taken directly from the URL as a string.\n\n#### Route Params\nRoute Params will be available for you to use on the code as `ctx.vtex.params`, already parsed as an object.\nFor a path like `/_v/status/:code`, if you receive the request `/_v/status/200`, `ctx.vtex.params` will return `{ code: '200' }`\n\n#### HTTP methods\nWhen you define a route on the `service.json`, your NodeJS handlers for that route will be triggered **on every HTTP method** (GET, POST, PUT...), so, if you need to handle them separately you need to implement a \"sub-router\". Fortunately, the _node-vtex-api_ provides a helper function `method`, exported from `@vtex/api`, to accomplish that behaviour. Instead of passing your handlers directly to the corresponding route on `index.ts`, you pass a `method` call passing **an object with the desired method as key and one handler as its corresponding value**. Check this example:\n```typescript\nimport { method } from '@vtex/api'\n...\n\nexport default new Service<Clients, State>({\n clients,\n routes: {\n status: method({\n GET: statusGetHandler,\n POST: statusPostHandler,\n }),\n },\n})\n```\n\n### Throwing errors\n\nWhen building a HTTP service, we should follow HTTP rules regarding data types, cache, authorization, and status code. Our example app sets a `ctx.status` value that will be used as a HTTP status code return value, but often we also want to give proper information about errors as well.\n\nThe **node-vtex-api** already exports a handful of **custom error classes** that can be used for that purpose, like the `NotFoundError`. You just need to throw them inside one of the the route handlers that the appropriate response will be sent to the server.\n\n```typescript\nimport { UserInputError } from '@vtex/api'\n\nexport async function validate(ctx: Context, next: () => Promise<any>) {\n const { code } = ctx.vtex.route.params\n if (isNaN(code) || code < 100 || code > 600) {\n throw new UserInputError('Code must be a number between 100 and 600')\n }\n...\n```\n\nYou can check all the available errors [here](https://github.com/vtex/node-vtex-api/tree/fd6139349de4e68825b1074f1959dd8d0c8f4d5b/src/errors), but some are not useful for just-HTTP services. Check the most useful ones:\n\n|Error Class | HTTP Code |\n|--|:--:|\n| `UserInputError` | 400 |\n| `AuthenticationError` | 401 |\n| `ForbiddenError` | 403 |\n| `NotFoundError` | 404 |\n\nYou can also **create your custom error**, just see how it's done above ;)\n\n### Reading a JSON body\n\nWhen writing POST or PUT handlers, for example, often you need to have access to the **request body** that comes as a JSON format, which is not provided directly by the handler function.\n\nFor this, you have to use the [co-body](https://www.npmjs.com/package/co-body) package that will parse the request into a readable JSON object, used as below: \n```typescript\nimport { json } from 'co-body'\nexport async function method(ctx: Context, next: () => Promise<any>) {\n const body = await json(ctx.req)\n```\n\n### Other example apps\n\nWe use Node services across all VTEX, and there are a lot inspiring examples. If you want to dive deeper on learning about this subject, don't miss those internal apps: [builder-hub](https://github.com/vtex/builder-hub) or [store-sitemap](https://github.com/vtex-apps/store-sitemap)\n\n\n## Testing\n\n`@vtex/test-tools` and `@types/jest` should be installed on `./node` package as `devDependencies`.\n\nRun `vtex test` and [Jest](https://jestjs.io/) will do its thing.\n\nCheck the `node/__tests__/simple.test.ts` test case and also [Jest's Documentation](https://jestjs.io/docs/en/getting-started).\n\n## Splunk Dashboard\n\nWe have an (for now, VTEX-only, internal) Splunk dashboard to show all metrics related to your app. You can find it [here](https://splunk7.vtex.com/en-US/app/vtex_colossus/node_app_metrics).\n\nAfter linking this app and making some requests, you can select `vtex.service-example` and see the metrics for your app. **Don't forget to check the box Development, as you are linking your app in a development workspace**.\n\nFor convenience, the link for the current version: https://splunk7.vtex.com/en-US/app/vtex_colossus/node_app_metrics?form.time.earliest=-30m%40m&form.time.latest=%40m&form.picked_context=false&form.picked_region=aws-us-east-*&form.picked_service=vtex.service-example\n\n```" } ]
code_policies-example_baf8114c
[ { "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 policies-example/node/service.json from the policies-example 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 \"testPolicieService\": {\n \"path\": \"/_v/test-policies-service-route\",\n \"public\": false,\n \"access\": \"authorized\",\n \"policies\": [\n {\n \"effect\": \"allow\",\n \"actions\": [\"get\"],\n \"principals\": [\"vrn:apps:*:*:*:app/vtex.policies-example-3@*\"]\n }\n ]\n }\n }\n}\n\n```" } ]
code_policies-example_c95f4ea1
[ { "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 policies-example/node/package.json from the policies-example VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"dependencies\": {\n \"@types/xmldom\": \"^0.1.31\",\n \"co-body\": \"^6.0.0\",\n \"ramda\": \"^0.25.0\",\n \"xmldom\": \"^0.6.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/ramda\": \"types/npm-ramda#dist\",\n \"@vtex/api\": \"6.45.11-beta\",\n \"@vtex/tsconfig\": \"^0.5.6\",\n \"typescript\": \"3.9.7\"\n },\n \"scripts\": {\n \"lint\": \"tsc --noEmit --pretty\"\n },\n \"version\": \"0.2.0\"\n}\n\n```" } ]
code_policies-example_8d1cdb6b
[ { "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 policies-example/node/index.ts from the policies-example VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport type { ClientsConfig, ServiceContext } from '@vtex/api'\nimport { method, Service } from '@vtex/api'\n\nimport { Clients } from './clients'\nimport { testPolicieServiceCode } from './middlewares/testPolicieServiceCode'\n\nconst TIMEOUT_MS = 800\n\nconst clients: ClientsConfig<Clients> = {\n implementation: Clients,\n options: {\n default: {\n retries: 2,\n timeout: TIMEOUT_MS,\n },\n },\n}\n\ndeclare global {\n type Context = ServiceContext<Clients>\n}\n\n// Export a service that defines route handlers and client options.\nexport default new Service({\n clients,\n routes: {\n // `status` is the route ID from service.json. It maps to an array of middlewares (or a single handler).\n testPolicieService: method({\n GET: [testPolicieServiceCode],\n }),\n },\n})\n\n```" } ]
code_policies-example_1453fea2
[ { "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 policies-example/node/clients/formula1.ts from the policies-example VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\n/* eslint-disable no-console */\nimport type { InstanceOptions, IOContext } from '@vtex/api'\nimport { ExternalClient } from '@vtex/api'\n\nexport class Formula1 extends ExternalClient {\n constructor(ctx: IOContext, options?: InstanceOptions) {\n super('http://ergast.com/api/f1/2020', ctx, {\n ...options,\n headers: {\n 'X-Vtex-Use-Https': 'false',\n },\n })\n }\n\n public async getDrivers() {\n const drivers = await this.http.get('/driverStandings.json')\n\n if (drivers.MRData.StandingsTable.StandingsLists[0].DriverStandings) {\n const driversInfos: DriversInfo[] = []\n\n drivers.MRData.StandingsTable.StandingsLists[0].DriverStandings.forEach(\n (element: any) => {\n driversInfos.push({\n name: element.Driver.givenName,\n lastName: element.Driver.familyName,\n points: parseFloat(element.points),\n })\n }\n )\n\n return driversInfos\n }\n\n return []\n }\n}\n\n```" } ]
code_policies-example_1582999f
[ { "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 policies-example/node/clients/index.ts from the policies-example VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { IOClients } from '@vtex/api'\n\nimport { Formula1 } from './formula1'\n\n// Extend the default IOClients implementation with our own custom clients.\nexport class Clients extends IOClients {\n public get f1() {\n return this.getOrSet('formula1', Formula1)\n }\n}\n\n```" } ]
code_policies-example_8e9ade0a
[ { "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 policies-example/node/typings/DrivesInfos.d.ts from the policies-example VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\ninterface DriversInfo {\n name: string\n lastName: string\n points: number\n [k: string]: unknown\n}\n\n```" } ]
code_policies-example_5def1f5e
[ { "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 policies-example/node/middlewares/testPolicieServiceCode.ts from the policies-example VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nexport async function testPolicieServiceCode(ctx: Context) {\n const {\n clients: { f1 },\n } = ctx\n\n const retorno = await f1.getDrivers()\n\n ctx.status = 200\n ctx.body = retorno\n}\n\n```" } ]
code_broadcaster-worker_fd1db037
[ { "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 broadcaster-worker/docs/README.md from the broadcaster-worker VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```markdown\n# Broadcaster Worker\n\nApp in VTEXIO designed to listen to broadcaster catalog changes \nand to notify other apps that want to know the changes.\n\n### How it works?\n\nThe broadcaster worker listens to the SKU change event in the events system. It receives the `id` of the SKU that has been indexed, then gets all SKU data and checks if there was any change in the data, it does that by hashing the catalog response and comparing it to the one saved in the database, if the SKU has changed it pushes a new event with the SKU data.\n\nIt does the same thing for the SKU's product, brand and categories data.\n```" } ]
code_broadcaster-worker_988ff562
[ { "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 broadcaster-worker/node/service.json from the broadcaster-worker VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"memory\": 128,\n \"ttl\": 10,\n \"timeout\": 2,\n \"minReplicas\": 2,\n \"maxReplicas\": 5,\n \"workers\": 1,\n \"events\": {\n \"broadcasterNotification\": {\n \"keys\": [\"broadcaster.notification\"]\n },\n \"indexRoutes\": {\n \"keys\": [\"broadcaster.indexRoutes\"]\n }\n },\n \"routes\": {\n \"indexRoutes\": {\n \"path\": \"/index-routes\",\n \"public\": false\n }\n }\n}\n\n```" } ]
code_broadcaster-worker_d61a7b91
[ { "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 broadcaster-worker/node/package.json from the broadcaster-worker VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"dependencies\": {\n \"ramda\": \"^0.25.0\"\n },\n \"devDependencies\": {\n \"@types/node\": \"12.x\",\n \"@types/ramda\": \"types/npm-ramda#dist\",\n \"@vtex/api\": \"6.42.1\",\n \"eslint\": \"^6.3.0\",\n \"eslint-config-vtex\": \"^11.0.0\",\n \"prettier\": \"^1.18.2\",\n \"typescript\": \"3.9.7\",\n \"vtex.broadcaster-worker\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.broadcaster-worker@0.3.1/public/_types/react\",\n \"vtex.catalog-api-proxy\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.catalog-api-proxy@0.7.2/public/_types/react\",\n \"vtex.catalog-graphql\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.catalog-graphql@1.70.3/public/@types/vtex.catalog-graphql\"\n },\n \"scripts\": {\n \"lint\": \"tsc --noEmit --pretty && eslint -c .eslintrc.json --fix './**/*.ts'\"\n },\n \"version\": \"0.5.2\"\n}\n\n```" } ]
code_broadcaster-worker_e116ddf7
[ { "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 broadcaster-worker/node/typings.ts from the broadcaster-worker VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { Category } from '@vtex/api/lib/clients/apps/catalogGraphQL/category'\nimport { RecorderState, EventContext, ServiceContext as ServiceCtx, ParamsContext } from '@vtex/api'\nimport { Clients } from './clients/index'\n\ndeclare global {\n type Context = EventContext<Clients, State>\n type ServiceContext = ServiceCtx<Clients, State, ParamsContext>\n\n interface State extends RecorderState, BroadcasterEvent, IndexRoutesEvent {\n nextPayload: IndexRoutesEvent\n }\n\n interface BroadcasterEvent {\n HasStockKeepingUnitModified: boolean\n IdSku: string\n indexBucket?: string\n }\n\n interface IndexRoutesEvent {\n indexBucket?: string\n from: number\n processedProducts: number\n productsWithoutSKU: number\n attempt?: number\n }\n\n interface IdentifiedCategory extends Category {\n parents: Pick<Category, 'name' | 'id'>[]\n }\n\n type ID = string\n type Float = number\n type Int = number\n}\n\n```" } ]
code_broadcaster-worker_2998332e
[ { "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 broadcaster-worker/node/constants.ts from the broadcaster-worker VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { appIdToAppAtMajor } from \"@vtex/api\"\n\nexport const USER_BUCKET = 'listener'\n\nexport const VTEX_APP_ID = process.env.VTEX_APP_ID!\n\nexport const VTEX_APP_AT_MAJOR = appIdToAppAtMajor(VTEX_APP_ID)\n```" } ]
code_broadcaster-worker_08861349
[ { "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 broadcaster-worker/node/index.ts from the broadcaster-worker VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { LRUCache, Service, Cached, ParamsContext } from '@vtex/api'\n\nimport { locale } from './middlewares/locale'\nimport { notify } from './middlewares/notify'\nimport { throttle } from './middlewares/throttle'\nimport { indexRoutes, indexAllRoutes } from './middlewares/indexRoutes'\nimport { Clients } from './clients'\nimport { validation } from './middlewares/validation'\nimport { nextEvent } from './middlewares/nextEvent'\nimport { errors } from './middlewares/errors'\nimport { settings } from './middlewares/settings'\nimport { filterStockEvents } from './middlewares/filterStock'\n\nconst TREE_SECONDS_MS = 3 * 1000\nconst CONCURRENCY = 10\n\nconst tenantCacheStorage = new LRUCache<string, Cached>({\n max: 3000\n})\n\nconst segmentCacheStorage = new LRUCache<string, Cached>({\n max: 3000\n})\n\nmetrics.trackCache('tenant', tenantCacheStorage)\nmetrics.trackCache('segment', segmentCacheStorage)\n\nexport default new Service<Clients, State, ParamsContext>({\n clients: {\n implementation: Clients,\n options: {\n default: {\n exponentialTimeoutCoefficient: 2,\n exponentialBackoffCoefficient: 2,\n initialBackoffDelay: 50,\n retries: 1,\n timeout: TREE_SECONDS_MS,\n concurrency: CONCURRENCY,\n },\n tenant: {\n memoryCache: tenantCacheStorage,\n timeout: TREE_SECONDS_MS\n },\n segment: {\n memoryCache: segmentCacheStorage,\n timeout: TREE_SECONDS_MS\n },\n events: {\n timeout: TREE_SECONDS_MS\n },\n vbase: {\n concurrency: 5,\n }\n },\n },\n events: {\n broadcasterNotification: [\n filterStockEvents, settings, errors, throttle, locale, notify,\n ],\n indexRoutes: [settings, errors, indexRoutes, nextEvent],\n },\n routes: {\n indexRoutes: [validation, indexAllRoutes],\n },\n})\n\n```" } ]
code_broadcaster-worker_8df7d35f
[ { "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 broadcaster-worker/node/clients/noCacheVBase.ts from the broadcaster-worker VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { IOContext, InstanceOptions, VBase } from \"@vtex/api\";\n\nexport class NoCacheVBase extends VBase {\n public constructor(context: IOContext, options?: InstanceOptions) {\n super(\n context,\n {\n ...(options ?? {}),\n headers: {\n ...(options?.headers ?? {}),\n 'Cache-Control': 'no-cache',\n }, \n }\n )\n }\n}\n```" } ]
code_broadcaster-worker_da98c4f3
[ { "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 broadcaster-worker/node/clients/index.ts from the broadcaster-worker VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { IOClients } from '@vtex/api'\nimport { Catalog } from './catalog'\nimport { NoCacheVBase } from './noCacheVBase'\n\nexport class Clients extends IOClients {\n public get catalog() {\n return this.getOrSet('catalog', Catalog)\n }\n\n public get noCacheVBase() {\n return this.getOrSet('noCacheVBase', NoCacheVBase)\n }\n}\n\n```" } ]
code_broadcaster-worker_eacf9c13
[ { "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 broadcaster-worker/node/clients/catalog.ts from the broadcaster-worker VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { IOContext, InstanceOptions, ExternalClient } from \"@vtex/api\";\n\ninterface GetProductsAndSkuIdsReponse {\n data: Record<string, number[]>\n range: {\n total: number\n from: number\n to: number\n }\n}\n\nexport class Catalog extends ExternalClient {\n public constructor(context: IOContext, options?: InstanceOptions) {\n super(\n `http://${context.account}.vtexcommercestable.com.br`,\n context,\n {\n ...(options ?? {}),\n headers: {\n ...(options?.headers ?? {}),\n 'VtexIdclientAutCookie': context.authToken,\n 'Content-Type': 'application/json',\n 'X-Vtex-Use-Https': 'true',\n }, \n }\n )\n }\n\n public getProductsAndSkuIds (from: number, to: number): Promise<GetProductsAndSkuIdsReponse>{\n return this.http.get('/api/catalog_system/pvt/products/GetProductAndSkuIds', {\n params: {\n _from: from,\n _to: to\n },\n headers: {\n }\n })\n }\n}\n```" } ]
code_broadcaster-worker_3499bcd4
[ { "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 broadcaster-worker/node/middlewares/validation.ts from the broadcaster-worker VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nconst VALIDATION_BUCKET = 'validation'\n\nconst oneHourFromNowMS = () => `${new Date(Date.now() + 1 * 60 * 60 * 1000)}`\n\nexport const valid = (nextIndexation?: string) => {\n const date = nextIndexation && new Date(nextIndexation)\n if (date && date.toString() !== 'Invalid Date' && date > new Date()) {\n return false \n }\n return true \n}\n\nexport async function validation(ctx: ServiceContext, next: () => Promise<void>) {\n const caller = ctx.headers['x-vtex-caller']\n if (caller.includes('@vtex.com.br')) {\n return next()\n }\n const {\n vtex: { account, workspace },\n clients: { vbase } \n } = ctx\n\n\n const fileName = `${account}-${workspace}`\n const nextIndexation = await vbase.getJSON<string>(VALIDATION_BUCKET, fileName, true)\n if (valid(nextIndexation)) {\n await next()\n await vbase.saveJSON<string>(VALIDATION_BUCKET, fileName, oneHourFromNowMS())\n ctx.status = 200\n return \n }\n\n ctx.status = 429\n ctx.body = `A Indexation has already been done in the last hour. Next indexation available after ${nextIndexation}.`\n}\n\n```" } ]
code_broadcaster-worker_bbad000a
[ { "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 broadcaster-worker/node/middlewares/filterStock.ts from the broadcaster-worker VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nexport async function filterStockEvents(ctx: Context, next: () => Promise<void>) {\n if (!ctx.body.HasStockKeepingUnitModified) {\n return\n }\n \n await next()\n}\n\n```" } ]
code_broadcaster-worker_e69a61d8
[ { "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 broadcaster-worker/node/middlewares/throttle.ts from the broadcaster-worker VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { sleep } from './../utils/event';\nimport { TooManyRequestsError } from '@vtex/api'\n\nconst MAX_REQUEST = 5\nlet COUNTER = 0\n\nexport async function throttle(\n _: Context,\n next: () => Promise<void>\n) {\n if (COUNTER > MAX_REQUEST) {\n const timeToSleep = Math.ceil(Math.random() * 100)\n await sleep(timeToSleep)\n throw new TooManyRequestsError()\n }\n\n try {\n COUNTER++\n await next()\n } finally {\n COUNTER--\n }\n}\n```" } ]
code_broadcaster-worker_9a615042
[ { "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 broadcaster-worker/node/middlewares/errors.ts from the broadcaster-worker 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 isTooManyRequestsError = (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(_: Context, next: () => Promise<void>) {\n try {\n await next()\n } catch (error) {\n if (isTooManyRequestsError(error)) {\n throw new TooManyRequestsError()\n }\n throw error\n }\n}\n\n```" } ]
code_broadcaster-worker_3eb7da7d
[ { "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 broadcaster-worker/node/middlewares/locale.ts from the broadcaster-worker VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nconst TEN_MINUTES_S = 10 * 60\n\nconst getTenant = async (clients: Context['clients']) => {\n const { segment, tenant } = clients\n const [ segmentData, tenantInfo ] = await Promise.all([\n segment.getSegmentByToken(null),\n tenant.info({\n forceMaxAge: TEN_MINUTES_S,\n nullIfNotFound: true,\n }).catch(_ => null),\n ])\n const cultureFromTenant = tenantInfo && tenantInfo.defaultLocale\n const cultureFromDefaultSegment = segmentData!.cultureInfo\n\n return {\n locale: cultureFromTenant || cultureFromDefaultSegment,\n }\n}\n\nexport async function locale(ctx: Context, next: () => Promise<any>) {\n\n /** \n * Insert tenant and locale values into the context so we call\n * all other services with the correct headers\n */\n if (!ctx.vtex.tenant || !ctx.vtex.locale) {\n const tenantInfo = await getTenant(ctx.clients) \n \n ctx.vtex.tenant = tenantInfo\n ctx.vtex.locale = tenantInfo.locale\n }\n \n await next()\n}\n\n```" } ]
code_broadcaster-worker_335ab69b
[ { "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 broadcaster-worker/node/middlewares/settings.ts from the broadcaster-worker VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { VTEX_APP_AT_MAJOR } from \"../constants\"\n\n\nexport interface Settings {\n disableIndexation: boolean \n}\n\nexport const DEFAULT_SETTINGS = {\n disableIndexation: false,\n}\n\nexport async function settings(ctx: Context, next: () => Promise<void>) {\n const {\n clients: { apps },\n vtex: { logger },\n } = ctx\n\n const { disableIndexation } = {\n ...DEFAULT_SETTINGS,\n ...(await apps.getAppSettings(VTEX_APP_AT_MAJOR) as Settings),\n }\n if (disableIndexation) {\n logger.debug({\n message: 'Indexing disabled',\n ...ctx.body,\n })\n return\n }\n\n await next()\n}\n\n```" } ]
code_broadcaster-worker_13ba35ab
[ { "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 broadcaster-worker/node/middlewares/notify.ts from the broadcaster-worker VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { IOClients, LINKED} from '@vtex/api'\nimport { isEmpty, isNil } from 'ramda'\n\nimport { USER_BUCKET } from '../constants'\nimport {\n objToHash,\n providerToVbaseFilename,\n Storage,\n toBrandProvider,\n toCategoryProvider,\n toProductProvider,\n toSkuProvider,\n} from '../utils/catalog'\nimport {\n brandChanged,\n categoryChanged,\n productChanged,\n skuChanged,\n} from './../utils/event'\n\nconst isStorage = (maybeStorage: {} | Storage | null): maybeStorage is Storage => {\n if (isNil(maybeStorage) || isEmpty(maybeStorage)) {\n return false\n }\n return true\n}\n\nconst replaceIfChanged = async <T>(\n data: T,\n fileName: string,\n bucket: string,\n { vbase }: IOClients\n) => {\n const hash = objToHash(data)\n\n const oldHash = await vbase\n .getJSON<Storage | null>(bucket, fileName, true)\n .then(maybeHash => isStorage(maybeHash) ? maybeHash.hash : null)\n \n if (oldHash !== hash) {\n await vbase.saveJSON<Storage>(bucket, fileName, { hash })\n return true\n }\n\n return false\n}\n\nconst getAllCategories = async (categoryId: string | undefined, ctx: Context): Promise<IdentifiedCategory[]> => {\n const { clients: { catalogGraphQL } } = ctx\n if (!categoryId) {\n return []\n }\n const categoryResponse = await catalogGraphQL.category(categoryId)\n if (!categoryResponse || !categoryResponse.category) {\n return []\n }\n const { category } = categoryResponse\n const categories = await getAllCategories(category.parentCategoryId, ctx)\n const identifiedCategory = {\n ...category,\n parents: categories.map(c => ({id: c.id, name: c.name}))\n }\n return [...categories, identifiedCategory]\n}\n\nexport async function notify(ctx: Context, next: () => Promise<any>) {\n const {\n clients: { catalogGraphQL, events },\n clients,\n body: { IdSku, indexBucket },\n vtex: { logger },\n } = ctx\n const bucket = indexBucket || USER_BUCKET\n const eventPromises = []\n const changedEntities: Record<string, number> = {}\n const logWholeProductAndSku = {sku: {}, product: {}}\n\n // Modification in SKU\n const skuResponse = await catalogGraphQL.sku(IdSku)\n if (!skuResponse || !skuResponse.sku) {\n return\n }\n const { sku } = skuResponse\n const filenameSku = providerToVbaseFilename(toSkuProvider(sku.id))\n let changed = await replaceIfChanged(sku, filenameSku, bucket, clients)\n if (changed) {\n logWholeProductAndSku.sku = sku\n eventPromises.push(events.sendEvent('', skuChanged, sku))\n changedEntities.sku = 1\n }\n\n // Modification in Product\n const productResponse = await catalogGraphQL.product(sku.productId)\n if (!productResponse || !productResponse.product) {\n return\n }\n const { product } = productResponse\n const filenameProduct = providerToVbaseFilename(\n toProductProvider(sku.productId)\n )\n changed = await replaceIfChanged(product, filenameProduct, bucket, clients)\n if (changed) {\n logWholeProductAndSku.product = product\n eventPromises.push(events.sendEvent('', productChanged, product))\n changedEntities.product = 1\n }\n\n // Modification in Brand\n const brandResponse = await catalogGraphQL.brand(product.brandId)\n if (!brandResponse || !brandResponse.brand) {\n return\n }\n const { brand } = brandResponse\n const filenameBrand = providerToVbaseFilename(\n toBrandProvider(product.brandId)\n )\n changed = await replaceIfChanged(brand, filenameBrand, bucket, clients)\n if (changed) {\n eventPromises.push(events.sendEvent('', brandChanged, brand))\n changedEntities.brand = 1\n } \n\n // Modification in Categories\n const categories = await getAllCategories(product.categoryId, ctx)\n const changedCategoriesIds: string[] = []\n for (const category of categories) {\n const filenameCategory = providerToVbaseFilename(\n toCategoryProvider(category.id)\n )\n changed = await replaceIfChanged(category, filenameCategory, bucket, clients)\n if (changed) {\n changedCategoriesIds.push(category.id)\n eventPromises.push(events.sendEvent('', categoryChanged, category))\n }\n }\n changedEntities.categories = changedCategoriesIds.length\n\n // Wait for all events to be sent\n await Promise.all(eventPromises)\n\n metrics.batch('changed-entities', undefined, changedEntities)\n\n if (!isEmpty(logWholeProductAndSku.sku) && !isEmpty(logWholeProductAndSku.product)) {\n logger.debug({\n 'sku': logWholeProductAndSku.sku,\n 'product': logWholeProductAndSku.product\n })\n }\n\n if (LINKED) {\n console.log('changedEntities', changedEntities, { sku: sku.id, brand: brand.id, product: product.id, categories: changedCategoriesIds})\n }\n\n await next()\n}\n\n```" } ]
code_broadcaster-worker_ef21eeb9
[ { "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 broadcaster-worker/node/middlewares/indexRoutes.ts from the broadcaster-worker VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { sleep } from '../utils/event'\n\nexport const BROACASTER_INDEX_ROUTES = 'broadcaster.indexRoutes'\nconst BROADCASTER_NOTIFICATION = 'broadcaster.notification'\nconst PAGE_LIMIT = 10\nconst BUCKET = 'indexRoutes'\nconst FILE = 'data.json'\n\nconst index = async (ctx: Context, next: () => Promise<void>) => {\n const { clients: { catalog, events, noCacheVBase }, vtex: { logger }, body } = ctx\n logger.info({ message: 'Event received', payload: ctx.body})\n const {\n indexBucket,\n from,\n processedProducts,\n productsWithoutSKU,\n }: IndexRoutesEvent = body\n\n const { data: dataFile, headers: {etag} } = await noCacheVBase.getRawJSON<IndexRoutesEvent>(BUCKET, FILE, true)\n if (dataFile?.indexBucket != indexBucket) {\n logger.debug({ \n message: 'Invalid Indexation', \n currentIndexBucket: dataFile?.indexBucket, \n from,\n receivedIndexBucket: indexBucket\n })\n return\n }\n\n if (from < (dataFile?.from ?? 0)) {\n logger.debug({\n message: 'Duplicated event',\n currentIndexBucket: dataFile?.indexBucket,\n from,\n receivedIndexBucket: indexBucket\n })\n return\n }\n\n const to = from + PAGE_LIMIT - 1\n const { data, range: { total } } = await catalog.getProductsAndSkuIds(from, to)\n let countProductsWithoutSKU = 0\n\n const productIds = Object.keys(data)\n const skuIds = productIds.reduce((acc, productId) => {\n const skus = data[productId]\n if (skus.length) {\n const skuId = skus[0]\n acc.push(skuId)\n } else {\n countProductsWithoutSKU++\n }\n return acc\n }, [] as number[])\n \n for (let idx in skuIds) {\n const skuId = skuIds[idx]\n await sleep(50)\n events.sendEvent('', BROADCASTER_NOTIFICATION, {\n HasStockKeepingUnitModified: true,\n IdSku: skuId,\n indexBucket,\n })\n }\n const payload: IndexRoutesEvent = {\n indexBucket,\n from: from + PAGE_LIMIT,\n processedProducts: processedProducts + skuIds.length,\n productsWithoutSKU: productsWithoutSKU + countProductsWithoutSKU,\n }\n ctx.state.nextPayload = payload\n if (payload.processedProducts >= total || payload.from >= total) {\n logger.info({ \n message: `Indexation complete`, \n processedProducts: payload.processedProducts, \n productsWithoutSKU: payload.productsWithoutSKU, \n total, \n indexBucket \n })\n await noCacheVBase.deleteFile(BUCKET, FILE)\n return\n } else {\n logger.info({\n message: 'Processed',\n processedProducts: payload.processedProducts,\n productsWithoutSKU: payload.productsWithoutSKU,\n totalProducts: total,\n from,\n indexBucket,\n })\n\n const shouldTriggerNext : boolean = await noCacheVBase.saveJSON(BUCKET, FILE, payload, undefined, etag)\n .then(_ => true)\n .catch(e => e?.response?.status != 412)\n\n if (shouldTriggerNext) await next()\n }\n}\n\nexport async function indexRoutes(ctx: Context, next: () => Promise<void>) {\n const { vtex: { logger } } = ctx\n try {\n await index(ctx, next)\n } catch (error) {\n logger.error({ message: 'Indexation error', error, payload: ctx.body})\n throw error\n }\n}\n\nexport async function indexAllRoutes(ctx: ServiceContext) {\n const { clients: { events, noCacheVBase } } = ctx\n const indexBucket = (Math.random() * 10000).toString()\n const data = { indexBucket, from: 0 }\n await noCacheVBase.saveJSON(BUCKET, FILE, data)\n\n const payload: IndexRoutesEvent = {\n indexBucket,\n from: 0,\n processedProducts: 0,\n productsWithoutSKU: 0,\n }\n events.sendEvent('', BROACASTER_INDEX_ROUTES, payload)\n ctx.status = 200\n}\n\n```" } ]
code_broadcaster-worker_508e0556
[ { "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 broadcaster-worker/node/middlewares/nextEvent.ts from the broadcaster-worker VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { BROACASTER_INDEX_ROUTES } from \"./indexRoutes\"\n\nexport async function nextEvent(ctx: Context) {\n const { vtex: { logger }, clients: { events }, state: { nextPayload } } = ctx\n events.sendEvent('', BROACASTER_INDEX_ROUTES, nextPayload)\n logger.info({ message: 'Event sent', nextPayload })\n}\n```" } ]
code_broadcaster-worker_74567dfe
[ { "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 broadcaster-worker/node/utils/event.ts from the broadcaster-worker VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nexport const eventName = (route: string) => `broadcaster.${route}`\n\nexport const skuChanged = eventName('sku')\nexport const productChanged = eventName('product')\nexport const brandChanged = eventName('brand')\nexport const categoryChanged = eventName('category')\n\nexport const sleep = (ms: number) => new Promise(resolve => setTimeout(resolve, ms))\n```" } ]
code_broadcaster-worker_27409bd7
[ { "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 broadcaster-worker/node/utils/catalog.ts from the broadcaster-worker VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport * as crypto from 'crypto'\n\nexport interface Storage {\n hash: string\n}\n\nexport const toSkuProvider = (id: string) => `SKU-id.${id}`\nexport const toProductProvider = (id: string) => `Product-id.${id}`\nexport const toBrandProvider = (id: string) => `Brand-id.${id}`\nexport const toCategoryProvider = (id: string) => `Category-id.${id}`\n\nexport const providerToVbaseFilename = (provider: string) => `${provider}.json`\n\nexport const objToHash = <T>(obj: T) =>\n crypto\n .createHash('md5')\n .update(JSON.stringify(obj))\n .digest('hex')\n\n```" } ]
code_datadog-log-forwarder_07740711
[ { "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 datadog-log-forwarder/node/service.json from the datadog-log-forwarder 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 \"routes\": {\n \"forward\": {\n \"path\": \"/_v/start\",\n \"public\": false\n }\n }\n}\n\n```" } ]
code_datadog-log-forwarder_a100ac02
[ { "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 datadog-log-forwarder/node/package.json from the datadog-log-forwarder 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 \"eventsource\": \"^1.0.7\"\n },\n \"devDependencies\": {\n \"@types/co-body\": \"^0.0.3\",\n \"@types/jest\": \"^24.0.18\",\n \"@types/node\": \"^12.0.0\",\n \"@types/ramda\": \"types/npm-ramda#dist\",\n \"@types/eventsource\": \"^1.0.7\",\n \"@vtex/api\": \"6.17.0\",\n \"@vtex/test-tools\": \"^1.0.0\",\n \"tslint\": \"^5.14.0\",\n \"tslint-config-vtex\": \"^2.1.0\",\n \"typescript\": \"3.8.3\"\n },\n \"scripts\": {\n \"lint\": \"tsc --noEmit --pretty && tslint -c tslint.json --fix './**/*.ts'\"\n },\n \"version\": \"0.0.6\"\n}\n\n```" } ]
code_datadog-log-forwarder_d77e42ba
[ { "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 datadog-log-forwarder/node/index.ts from the datadog-log-forwarder VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { ClientsConfig, LRUCache, ParamsContext, Recorder, Service, ServiceContext, method } from '@vtex/api'\n\nimport { Clients } from './clients'\nimport { validate } from './middlewares/validate'\nimport { settings } from './middlewares/settings'\nimport { forwarder } from './middlewares/forwarder'\n\nconst TIMEOUT_MS = 800\n\n// Create a LRU memory cache for the Status client.\n// The @vtex/api HttpClient respects Cache-Control headers and uses the provided cache.\nconst memoryCache = new LRUCache<string, any>({max: 5000})\nmetrics.trackCache('status', memoryCache)\n\n// This is the configuration for clients available in `ctx.clients`.\nconst clients: ClientsConfig<Clients> = {\n // We pass our custom implementation of the clients bag, containing the Status client.\n implementation: Clients,\n options: {\n // All IO Clients will be initialized with these options, unless otherwise specified.\n default: {\n retries: 2,\n timeout: TIMEOUT_MS,\n },\n // This key will be merged with the default options and add this cache to our Status client.\n status: {\n memoryCache,\n },\n },\n}\n\ndeclare global {\n // We declare a global Context type just to avoid re-writing ServiceContext<Clients, State> in every handler and resolver\n type Context = ServiceContext<Clients, State>\n\n // The shape of our State object found in `ctx.state`. This is used as state bag to communicate between middlewares.\n interface State {\n region: string,\n apiKey: string,\n recorder: Recorder,\n body: any\n }\n}\n\n// Export a service that defines route handlers and client options.\nexport default new Service<Clients, State, ParamsContext>({\n clients,\n routes: {\n // `status` is the route ID from service.json. It maps to an array of middlewares (or a single handler).\n forward: method({\n POST: [\n settings,\n validate,\n forwarder,\n ],\n }),\n },\n})\n\n```" } ]
code_datadog-log-forwarder_140bff0f
[ { "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 datadog-log-forwarder/node/clients/datadog.ts from the datadog-log-forwarder VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { ExternalClient, InstanceOptions, IOContext, RequestConfig } from '@vtex/api'\n\nexport function DatadogPartialFromRegion(region : string) {\n return class extends Datadog {\n constructor(context: IOContext, options?: InstanceOptions) {\n super(region, context, options)\n }\n }\n}\n\nexport class Datadog extends ExternalClient {\n constructor(region: string, context: IOContext, options?: InstanceOptions) {\n super(`https://http-intake.logs.datadoghq.${region}`, context, options)\n }\n\n public async postLog(log: any, conf?: RequestConfig): Promise<string> {\n return this.http.post(`/v1/input/`, log, conf)\n }\n}\n```" } ]
code_datadog-log-forwarder_96549481
[ { "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 datadog-log-forwarder/node/clients/index.ts from the datadog-log-forwarder VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { IOClients } from '@vtex/api'\n\nimport { DatadogPartialFromRegion } from './datadog'\n\n// Extend the default IOClients implementation with our own custom clients.\nexport class Clients extends IOClients {\n public get datadogcom() {\n return this.getOrSet('datadog', DatadogPartialFromRegion('com'))\n }\n\n public get datadogeu() {\n return this.getOrSet('datadog', DatadogPartialFromRegion('eu')) \n }\n}\n\n```" } ]
code_datadog-log-forwarder_071739bf
[ { "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 datadog-log-forwarder/node/middlewares/settings.ts from the datadog-log-forwarder VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nexport interface Settings {\n region: string,\n apikey: string\n}\n\nexport const APP_ID = process.env.VTEX_APP_ID!\n\nexport async function settings(ctx: Context, next: () => Promise<any>) {\n const {\n clients: {\n apps\n }\n } = ctx\n\n Object.assign(ctx.state, await apps.getAppSettings(APP_ID))\n\n await next()\n}\n```" } ]
code_datadog-log-forwarder_0b7dea40
[ { "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 datadog-log-forwarder/node/middlewares/validate.ts from the datadog-log-forwarder VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { UserInputError } from '@vtex/api'\n\nexport async function validate(ctx: Context, next: () => Promise<any>) {\n validateRegion(ctx.state.region) \n validateApiKey(ctx.state.apiKey)\n\n await next()\n}\n\nfunction validateRegion(region: string) : boolean {\n if (!region) {\n throw new UserInputError('Error parsing Apps config: region is not present')\n }\n \n return true\n}\n\nfunction validateApiKey(apiKey: string) : boolean {\n if (!apiKey) {\n throw new UserInputError('Error parsing Apps config: apiKey is not present')\n }\n\n return true\n}\n```" } ]
code_datadog-log-forwarder_fbb9a059
[ { "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 datadog-log-forwarder/node/middlewares/forwarder.ts from the datadog-log-forwarder VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { IOContext, AuthType, UserInputError, Logger } from '@vtex/api'\nimport { LogSource } from '../skidder/logsource'\nimport { Clients } from '../clients'\nimport { Datadog } from '../clients/datadog'\n\n/**\n * If isn't tolerable to be asleep while logs are generated,\n * this should be at least as great as the time Skidder would\n * take to restart this service\n */\nconst timeToLive = 60 * 1000\nconst timeBetweenBatchs = 10000\nconst maxSizeBatch = 500\n\nexport async function forwarder(ctx: Context, next: () => Promise<any>) {\n const {\n state: { region, apiKey },\n clients,\n vtex,\n } = ctx\n\n setImmediate(async () => {\n const datadogClient = datadogClientFromRegion(clients, region)\n startEventSource(vtex, apiKey, datadogClient)\n })\n\n ctx.status = 200\n ctx.set('Cache-Control', 'no-cache')\n\n await next() \n}\n\nfunction startEventSource(vtex: IOContext, apiKey: string, client: Datadog) {\n const { authToken, userAgent, logger } = vtex\n const es = new LogSource(vtex, {\n headers: {\n Authorization: `${AuthType.bearer} ${authToken}`,\n 'User-Agent': `${userAgent}#${Math.random()}`, // Remove Random\n }\n })\n\n es.onopen = () => {\n logger.info('connection started')\n }\n\n es.onerror = (err) => {\n logger.error(`Error reading logs: ${JSON.stringify(err, null, 2)}`)\n }\n\n const wd = new Watchdog(timeToLive, es.close);\n wd.start()\n\n const datadogHeaders = {\n headers: {\n 'Content-Type': 'application/json',\n 'DD-API-KEY': apiKey,\n }\n }\n\n const batcher = new DatadogBatcher(client, datadogHeaders, logger)\n\n es.addEventListener('message', async (msg: Event) => {\n wd.rearm()\n\n try {\n await batcher.batchMessage(JSON.parse((msg as MessageEvent).data))\n //console.log(res)\n } catch (error) {\n logger.error(`Error sending log: ${error}`)\n }\n })\n}\n\nfunction datadogClientFromRegion(clients: Clients, region: string): Datadog {\n switch (region) {\n case 'com':\n return clients.datadogcom\n case 'eu':\n return clients.datadogeu\n }\n throw new UserInputError(`Could not find a Datadog client for ${region} region`)\n}\n\nclass Watchdog {\n private timeoutHandler?: any\n constructor(private timeout: number, private onTimedOut: Function) { }\n\n public start() {\n this.timeoutHandler = setTimeout(() => this.onTimedOut, this.timeout);\n }\n\n public rearm() {\n clearTimeout(this.timeoutHandler)\n this.start()\n }\n}\n\nclass DatadogBatcher {\n private messages: any[]\n private watchdog: Watchdog\n\n constructor(private client: Datadog, private headers: any, private logger: Logger) {\n this.messages = []\n this.watchdog = new Watchdog(timeBetweenBatchs, () => this.sendBatch())\n this.watchdog.start()\n }\n\n async batchMessage(msg: any) {\n if (this.messages.push(msg) >= maxSizeBatch) {\n await this.sendBatch()\n }\n }\n\n async sendBatch() {\n this.watchdog.rearm()\n const total = this.messages.length\n\n if (total > 0) {\n const breakingPoint = Math.min(maxSizeBatch, total)\n const batch = this.messages.slice(0, breakingPoint)\n this.messages = this.messages.slice(breakingPoint)\n\n this.logger.info(`sending batch with ${batch.length}/${total} logs`)\n await this.client.postLog(batch, this.headers)\n }\n }\n\n async postLogs(logs: any[]): Promise<string | void> {\n try {\n return this.client.postLog(logs, this.headers)\n } catch (reason) {\n this.logger.error(reason)\n this.messages.concat(logs)\n }\n }\n}\n```" } ]
code_datadog-log-forwarder_1658094e
[ { "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 datadog-log-forwarder/node/skidder/logsource.ts from the datadog-log-forwarder VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { IOContext } from '@vtex/api'\nimport EventSource = require('eventsource')\n\nconst skidderMajor = 1\n\nexport class LogSource extends EventSource {\n constructor(vtex: IOContext, opts : EventSource.EventSourceInitDict) {\n const { account, workspace, logger } = vtex\n const url = `http://infra.io.vtex.com/skidder/v${skidderMajor}/${account}/${workspace}/logs/stream`\n logger.info(`connecting with ${url}`)\n super(url, opts)\n }\n}\n```" } ]
code_trustpilot_867885af
[ { "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 trustpilot/messages/pt.json from the trustpilot VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"admin/editor.trustpilot.base-url\": \"URL Base\",\n \"admin/editor.trustpilot.template-id\": \"ID do template\",\n \"admin/editor.trustpilot.business-unit-id\": \"ID da unidade de negócio\",\n \"admin/editor.trustpilot.widget\": \"Trustpilot - Widget Genérico\",\n \"admin/editor.trustpilot.theme\": \"Tema\",\n \"admin/editor.trustpilot.width\": \"Largura\",\n \"admin/editor.trustpilot.height\": \"Altura\",\n \"admin/editor.trustpilot.stars\": \"Estrelas\",\n \"admin/editor.trustpilot.tag\": \"Marcação\"\n}\n\n```" } ]
code_trustpilot_76340a62
[ { "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 trustpilot/messages/en.json from the trustpilot VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"admin/editor.trustpilot.base-url\": \"Base URL\",\n \"admin/editor.trustpilot.template-id\": \"Template ID\",\n \"admin/editor.trustpilot.business-unit-id\": \"Business Unit ID\",\n \"admin/editor.trustpilot.widget\": \"Trustpilot - Generic Widget\",\n \"admin/editor.trustpilot.theme\": \"Theme\",\n \"admin/editor.trustpilot.width\": \"Width\",\n \"admin/editor.trustpilot.height\": \"Height\",\n \"admin/editor.trustpilot.stars\": \"Stars\",\n \"admin/editor.trustpilot.tag\": \"Tag\"\n}\n\n```" } ]
code_trustpilot_80fbbe79
[ { "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 trustpilot/messages/context.json from the trustpilot VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"admin/editor.trustpilot.base-url\": \"Base URL\",\n \"admin/editor.trustpilot.template-id\": \"Template ID\",\n \"admin/editor.trustpilot.business-unit-id\": \"Business Unit ID\",\n \"admin/editor.trustpilot.widget\": \"Trustpilot - Generic Widget\",\n \"admin/editor.trustpilot.theme\": \"Theme\",\n \"admin/editor.trustpilot.width\": \"Width\",\n \"admin/editor.trustpilot.height\": \"Height\",\n \"admin/editor.trustpilot.stars\": \"Stars\",\n \"admin/editor.trustpilot.tag\": \"Tag\"\n}\n\n```" } ]
code_trustpilot_f30fc4cd
[ { "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 trustpilot/messages/es.json from the trustpilot VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"admin/editor.trustpilot.base-url\": \"URL base\",\n \"admin/editor.trustpilot.template-id\": \"Template ID\",\n \"admin/editor.trustpilot.business-unit-id\": \"ID de unidad de negocio\",\n \"admin/editor.trustpilot.widget\": \"Trustpilot - Widget genérico\",\n \"admin/editor.trustpilot.theme\": \"Tema\",\n \"admin/editor.trustpilot.width\": \"Ancho\",\n \"admin/editor.trustpilot.height\": \"Alto\",\n \"admin/editor.trustpilot.stars\": \"Estrellas\",\n \"admin/editor.trustpilot.tag\": \"Etiqueta\"\n}\n\n```" } ]
code_trustpilot_111b2b8c
[ { "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 trustpilot/docs/README.md from the trustpilot VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```markdown\n📢 Use this project, [contribute](https://github.com/vtex-apps/CHANGEME) to it or open issues to help evolve it using [Store Discussion](https://github.com/vtex-apps/store-discussion).\n\n# Trustpilot\n\n<!-- prettier-ignore-start -->\n<!-- markdownlint-disable -->\n<!-- ALL-CONTRIBUTORS-BADGE:START - Do not remove or modify this section -->\n[![All Contributors](https://img.shields.io/badge/all_contributors-0-orange.svg?style=flat-square)](#contributors-)\n<!-- ALL-CONTRIBUTORS-BADGE:END -->\n<!-- markdownlint-enable -->\n<!-- prettier-ignore-end -->\n\nThis is a Trustpilot first-party integration app. The [solution](https://www.trustpilot.com/) provides a review platform for your store.\n\n## Configuration\n\n1. [Install](https://vtex.io/docs/recipes/development/installing-an-app/) the `vtex.trustpilot` app in the VTEX account in which you are working.\n2. In your VTEX account's admin, open the **App** section and select the Trustpilot App box.\n3. Fill in your integration key, provided by Trustpilot, in the fields.\n4. Save your changes.\n\n### Using the Trustpilot's Widget component\n\nThe `trustpilot` app also enables Truspilot's widget component to be added to your store theme by adding the `trustpilot-micro-review-count` block in a template of your choosing.\n\n1. Using a [Developer workspace](https://vtex.io/docs/recipes/development/creating-a-development-workspace/), open your store's theme directory in your code editor and add the `shop-review-interfaces` app as a dependency in the `manifest.json` file:\n\n```diff\n \"dependencies\": {\n+ \"vtex.shop-review-interfaces\": \"0.x\"\n }\n```\n\n2. Add the `shop-review-badge` block, exported by the `shop-review-interfaces`, in a template and block of your choosing, such as the Footer.\n3. Save your changes and [link](https://vtex.io/docs/recipes/development/linking-an-app/) the store theme app.\n4. Once your changes linked, access the admin's Site Editor using the same Developer workspace (`{workspaceName}-{accountName}.myvtex.com/admin/cms/site-editor`) and look for the `Trustpilot - Generic Widget` block.\n5. When editing the block, add the widget's `template id` and `business unit id` value provided by the [Trustpilot's widget](https://widgets-trustboxinstructions.b2b.trustpilot.com/#/trustbox/eyJjb2RlSGVhZCI6IjwhLS0gVHJ1c3RCb3ggc2NyaXB0IC0tPlxuPHNjcmlwdCB0eXBlPVwidGV4dC9qYXZhc2NyaXB0XCIgc3JjPVwiLy93aWRnZXQudHJ1c3RwaWxvdC5jb20vYm9vdHN0cmFwL3Y1L3RwLndpZGdldC5ib290c3RyYXAubWluLmpzXCIgYXN5bmM%252BPC9zY3JpcHQ%252BXG48IS0tIEVuZCBUcnVzdEJveCBzY3JpcHQgLS0%252BIiwiY29kZUJvZHkiOiI8IS0tIFRydXN0Qm94IHdpZGdldCAtIE1pY3JvIFJldmlldyBDb3VudCAtLT5cbjxkaXYgY2xhc3M9XCJ0cnVzdHBpbG90LXdpZGdldFwiIGRhdGEtbG9jYWxlPVwiaXQtSVRcIiBkYXRhLXRlbXBsYXRlLWlkPVwiNTQxOWI2YThiMGQwNGEwNzY0NDZhOWFkXCIgZGF0YS1idXNpbmVzc3VuaXQtaWQ9XCI1ZTc0ZTJkYjYwMGQxYTAwMDFiZTE1ODlcIiBkYXRhLXN0eWxlLWhlaWdodD1cIjI0cHhcIiBkYXRhLXN0eWxlLXdpZHRoPVwiMTAwJVwiIGRhdGEtdGhlbWU9XCJsaWdodFwiPlxuICA8YSBocmVmPVwiaHR0cHM6Ly9pdC50cnVzdHBpbG90LmNvbS9yZXZpZXcvbWlyaWFkZS5jb21cIiB0YXJnZXQ9XCJfYmxhbmtcIiByZWw9XCJub29wZW5lclwiPlRydXN0cGlsb3Q8L2E%252BXG48L2Rpdj5cbjwhLS0gRW5kIFRydXN0Qm94IHdpZGdldCAtLT4iLCJ0cnVzdEJveE5hbWUiOiJNaWNybyBSZXZpZXcgQ291bnQiLCJsb2NhbGUiOiJpdC1JVCJ9).\n6. Save your changes.\n7. Access your store's website using the Developer workspace to check out the new component. If no more changes are desired, repeat the steps above in a [Production workspace](https://vtex.io/docs/recipes/development/creating-a-production-workspace/) and then [promote it to Master](https://vtex.io/docs/recipes/development/promoting-a-workspace-to-master).\n\n\n:information_source: _The integration key must be provided by Trustpilot._\n\nThe `trustpilot` app also enables Truspilot's widgets to be added to your store theme by inserting the `shop-review-badge` interface in your layout and then using the `trustpilot-widget` block in a template of your choosing.\n\n| Interface | Block | Description |\n| ------------------- | ------------------- | --------------------------------------- |\n| `shop-review-badge` | `trustpilot-widget` | Adds a Trustpilot widget in your store. |\n\n\n## Block without badge\n\nTo use widget without `shop-review-badge` to landing pages, for example, you can use `trustpilot-widget`. Therefore, you need to add the following in the manifest.json file.\n\n```diff\n \"peerDependencies\": {\n+ \"vtex.trustpilot\": \"2.x\"\n }\n```\n## `trustpilot-widget` as props\n\n```json\n{\n \"trustpilot-widget#home\":{\n \"title\":\"Widget TrustPilot\",\n \"props\":{\n \"width\":\"100%\",\n \"height\":\"240px\",\n \"theme\":\"light\",\n \"stars\":\"4,5\",\n \"tag\":\"cart\",\n \"businessUnitId\":\"597a23fwffdsfe05a793fe\",\n \"templateId\":\"5419b6a8b0d04a076446a9ad\"\n }\n }\n}\n```\n\n| Prop name | Type | Description | Default value |\n| :-------: | :------: | :---------------------------------------------------------: | :-----------: |\n| `width` | `string` | Change width of template | `undefined` |\n| `height` | `string` | Change height of template | `undefined` |\n| `theme` | `string` | Change theme of template `light` or `dark` | `undefined` |\n| `stars` | `string` | Change stars stock of template | `undefined` |\n| `tag` | `string` | Change tag of template. More info [here](https://support.trustpilot.com/hc/en-us/articles/203840856-Tag-your-service-reviews) | `undefined` |\n| `businessUnitId` | `string` | Set your business code | `undefined` |\n| `templateId` | `string` | Set your template ID | `5419b6a8b0d04a076446a9ad` |\n\n<!-- DOCS-IGNORE:start -->\n\n## Contributors ✨\n\nThanks goes to these wonderful people:\n\n<!-- ALL-CONTRIBUTORS-LIST:START - Do not remove or modify this section -->\n<!-- prettier-ignore-start -->\n<!-- markdownlint-disable -->\n<!-- markdownlint-enable -->\n<!-- prettier-ignore-end -->\n\n<!-- ALL-CONTRIBUTORS-LIST:END -->\n\nThis project follows the [all-contributors](https://github.com/all-contributors/all-contributors) specification. Contributions of any kind are welcome!\n\n<!-- DOCS-IGNORE:end -->\n\n```" } ]
code_trustpilot_c0a07370
[ { "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 trustpilot/react/index.tsx from the trustpilot VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport { PixelMessage, OrderPlacedTrackedData } from './typings/events'\nimport { createProductInvitation } from './modules/invitation'\n\nfunction isOrderPlacedTrackedEvent(\n e: PixelMessage\n): e is PixelMessage<OrderPlacedTrackedData> {\n return e.data.eventName === 'vtex:orderPlacedTracked'\n}\n\nexport function handleEvents(e: PixelMessage) {\n if (isOrderPlacedTrackedEvent(e)) {\n createProductInvitation(e.data)\n }\n}\n\nif (typeof window !== 'undefined') {\n window.addEventListener('message', handleEvents)\n}\n\n```" } ]
code_trustpilot_b89912d3
[ { "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 trustpilot/react/package.json from the trustpilot VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"scripts\": {\n \"test\": \"vtex-test-tools test\"\n },\n \"devDependencies\": {\n \"@apollo/react-testing\": \"^3.1.3\",\n \"@types/graphql\": \"^14.5.0\",\n \"@types/jest\": \"^24.9.0\",\n \"@types/node\": \"^13.1.8\",\n \"@types/ramda\": \"^0.26.5\",\n \"@types/react\": \"^16.9.19\",\n \"@types/react-intl\": \"^3.0.0\",\n \"@vtex/test-tools\": \"^3.0.1\",\n \"apollo-cache-inmemory\": \"^1.6.5\",\n \"apollo-client\": \"^2.6.8\",\n \"graphql\": \"^14.5.4\",\n \"react-intl\": \"^3.11.0\",\n \"typescript\": \"3.8.3\",\n \"vtex.css-handles\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.css-handles@0.4.2/public/@types/vtex.css-handles\",\n \"vtex.pixel-interfaces\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.pixel-interfaces@1.1.1/public/_types/react\",\n \"vtex.render-runtime\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.render-runtime@8.99.0/public/@types/vtex.render-runtime\"\n },\n \"version\": \"2.2.2\"\n}\n\n```" } ]
code_trustpilot_df63b106
[ { "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 trustpilot/react/Widget.tsx from the trustpilot VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React, { useRef, useEffect } from 'react'\nimport { useRuntime } from 'vtex.render-runtime'\n\ninterface Props {\n baseUrl?: string\n templateId: string\n businessUnitId: string\n theme: string\n width: string\n height: string\n stars: string\n tag?: string\n}\n\nconst Widget: StorefrontFunctionComponent<Props> = ({\n // 5419b6a8b0d04a076446a9ad = micro review count\n templateId = '5419b6a8b0d04a076446a9ad',\n businessUnitId,\n theme,\n width,\n height,\n stars,\n tag,\n baseUrl = 'https://www.trustpilot.com/review',\n}) => {\n const ref = useRef(null)\n const {\n culture: { locale },\n } = useRuntime()\n\n const storeDomain = window?.location?.hostname ?? ''\n const hasConfig = businessUnitId != null && templateId != null\n\n useEffect(() => {\n if (window.Trustpilot && ref.current && hasConfig) {\n window.Trustpilot.loadFromElement(ref.current, true)\n }\n }, [hasConfig])\n\n if (!hasConfig) {\n return null\n }\n\n return (\n <div\n ref={ref}\n data-locale={locale}\n data-template-id={templateId}\n data-businessunit-id={businessUnitId}\n data-theme={theme}\n data-style-width={width}\n data-style-height={height}\n data-stars={stars}\n data-tags={tag}\n >\n <a\n href={`${baseUrl}/${storeDomain}`}\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n >\n Trustpilot\n </a>\n </div>\n )\n}\n\nWidget.schema = {\n title: 'admin/editor.trustpilot.widget',\n type: 'object',\n properties: {\n baseUrl: {\n title: 'admin/editor.trustpilot.base-url',\n type: 'string',\n default: 'https://www.trustpilot.com/review',\n },\n templateId: {\n title: 'admin/editor.trustpilot.template-id',\n type: 'string',\n default: '5419b6a8b0d04a076446a9ad',\n },\n businessUnitId: {\n title: 'admin/editor.trustpilot.business-unit-id',\n type: 'string',\n },\n theme: {\n title: 'admin/editor.trustpilot.theme',\n type: 'string',\n },\n width: {\n title: 'admin/editor.trustpilot.width',\n type: 'string',\n },\n height: {\n title: 'admin/editor.trustpilot.height',\n type: 'string',\n },\n stars: {\n title: 'admin/editor.trustpilot.stars',\n type: 'string',\n },\n tag: {\n title: 'admin/editor.trustpilot.tag',\n type: 'string',\n },\n },\n}\n\nexport default Widget\n\n```" } ]
code_trustpilot_622b7e66
[ { "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 trustpilot/store/interfaces.json from the trustpilot VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"pixel.trustpilot\": {\n \"component\": \"index\"\n },\n \"shop-review-badge.trustpilot-widget\": {\n \"component\": \"Widget\"\n },\n \"trustpilot-widget\": {\n \"component\": \"Widget\"\n }\n}\n\n```" } ]
code_trustpilot_fd0d2f41
[ { "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 trustpilot/store/plugins.json from the trustpilot VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"pixels > pixel\": \"pixel.trustpilot\",\n \"shop-review-badge\": \"shop-review-badge.trustpilot-widget\"\n}\n\n```" } ]
code_trustpilot_0499056e
[ { "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 trustpilot/react/typings/storefront.d.ts from the trustpilot VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { FunctionComponent } from 'react'\n\ndeclare global {\n interface StorefrontFunctionComponent<P = {}> extends FunctionComponent<P> {\n getSchema?(props: P): object\n schema?: object\n }\n\n interface StorefrontComponent<P = {}, S = {}> extends Component<P, S> {\n getSchema?(props: P): object\n schema: object\n }\n}\n\n```" } ]
code_trustpilot_6561346e
[ { "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 trustpilot/react/typings/events.d.ts from the trustpilot VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\ntype PixelMessagePayload =\n | ProductViewData\n | ProductClickData\n | OrderPlacedData\n | OrderPlacedTrackedData\n | PageViewData\n | ProductImpressionData\n | AddToCartData\n | RemoveToCartData\n | CartChangedData\n | HomePageInfo\n | ProductPageInfoData\n | SearchPageInfoData\n | UserData\n | CartIdData\n\nexport interface PixelMessage<T = PixelMessagePayload> extends MessageEvent {\n data: T\n}\n\nexport interface EventData {\n event: string\n eventName: string\n currency: string\n}\n\nexport interface PageInfoData extends EventData {\n event: 'pageInfo'\n eventName: 'vtex:pageInfo'\n accountName: string\n pageTitle: string\n pageUrl: string\n}\n\nexport interface UserData extends PageInfoData {\n eventType: 'userData'\n eventName: 'vtex:userData'\n firstName?: string\n lastName?: string\n document?: string\n id?: string\n email?: string\n phone?: string\n isAuthenticated: boolean\n}\n\nexport interface CartIdData extends PageInfoData {\n eventType: 'cartId'\n eventName: 'vtex:cartId'\n cartId: string\n}\n\nexport interface HomePageInfo extends PageInfoData {\n eventType: 'homeView'\n}\n\nexport interface ProductPageInfoData extends PageInfoData {\n eventType: 'productPageInfo'\n}\n\nexport interface SearchPageInfoData extends PageInfoData {\n eventType:\n | 'internalSiteSearchView'\n | 'categoryView'\n | 'departmentView'\n | 'emptySearchView'\n category?: CategoryMetaData\n department?: DepartmentMetaData\n search?: SearchMetaData\n}\n\ninterface CategoryMetaData {\n id: string\n name: string\n}\n\ninterface DepartmentMetaData {\n id: string\n name: string\n}\n\ninterface SearchMetaData {\n term: string\n category: CategoryMetaData\n results: number\n}\n\nexport interface PageViewData extends EventData {\n event: 'pageView'\n eventName: 'vtex:pageView'\n pageTitle: string\n pageUrl: string\n referrer: string\n}\n\nexport interface AddToCartData extends EventData {\n event: 'addToCart'\n eventName: 'vtex:addToCart'\n items: CartItem[]\n}\n\nexport interface RemoveToCartData extends EventData {\n event: 'removeFromCart'\n eventName: 'vtex:removeFromCart'\n items: CartItem[]\n}\n\nexport interface CartChangedData extends EventData {\n event: 'cartChanged'\n eventName: 'vtex:cartChanged'\n items: CartItem[]\n}\n\nexport interface OrderPlacedData extends Order, EventData {\n event: 'orderPlaced'\n eventName: 'vtex:orderPlaced'\n}\n\nexport interface OrderPlacedTrackedData extends Order, EventData {\n event: 'orderPlacedTracked'\n eventName: 'vtex:orderPlacedTracked'\n}\n\nexport interface ProductViewData extends EventData {\n event: 'productView'\n eventName: 'vtex:productView'\n product: ProductDetail\n}\n\nexport interface ProductClickData extends EventData {\n event: 'productClick'\n eventName: 'vtex:productClick'\n product: ProductSummary\n}\n\nexport interface ProductImpressionData extends EventData {\n event: 'productImpression'\n eventName: 'vtex:productImpression'\n impressions: Impression[]\n product?: ProductSummary // deprecated, use impressions list!\n position?: number // deprecated, use impressions list!\n list: string\n}\n\ninterface CartItem {\n skuId: string\n variant: string\n price: number\n name: string\n quantity: number\n productRefId: string\n brand: string\n category: string\n detailUrl: string\n imageUrl: string\n}\n\nexport interface Order {\n currency: string\n accountName: string\n orderGroup: string\n salesChannel: string\n coupon: string\n visitorType: string\n visitorContactInfo: string[]\n visitorAddressState: string\n visitorAddressCountry: string\n visitorAddressPostalCode: string\n transactionId: string\n transactionDate: string\n transactionAffiliation: string\n transactionTotal: number\n transactionShipping: number\n transactionSubtotal: number\n transactionDiscounts: number\n transactionTax: number\n transactionCurrency: string\n transactionPaymentType: PaymentType[]\n transactionShippingMethod: ShippingMethod[]\n transactionLatestShippingEstimate: Date\n transactionProducts: ProductOrder[]\n transactionPayment: {\n id: string\n }\n}\n\nexport interface Impression {\n product: ProductSummary\n position: number\n}\n\nexport interface PaymentType {\n group: string\n paymentSystemName: string\n installments: number\n value: number\n}\n\nexport interface ShippingMethod {\n itemId: string\n selectedSla: string\n}\n\nexport interface ProductOrder {\n id: string\n name: string\n sku: string\n skuRefId: string\n skuName: string\n productRefId: string\n ean: string\n slug: string\n brand: string\n brandId: string\n seller: string\n sellerId: string\n category: string\n categoryId: string\n categoryTree: string[]\n categoryIdTree: string[]\n priceTags: PriceTag[]\n originalPrice: number\n price: number\n sellingPrice: number\n tax: number\n quantity: number\n components: any[]\n measurementUnit: string\n unitMultiplier: number\n}\n\nexport interface PriceTag {\n identifier: string\n isPercentual: boolean\n value: number\n}\n\ninterface Product {\n brand: string\n brandId: string\n categories: string[]\n productId: string\n productName: string\n productReference: string\n linkText: string\n items: Item[]\n}\n\nexport interface ProductSummary extends Product {\n sku: Item\n}\n\nexport interface ProductDetail extends Product {\n categoryId: string\n categoryTree: Array<{ id: string; name: string }>\n selectedSku: Item\n}\n\nexport interface Item {\n itemId: string\n name: string\n ean?: string // TODO: provide this info at productImpression\n referenceId: { Key: string; Value: string }\n seller?: Seller\n sellers: Seller[]\n}\n\nexport interface Seller {\n commertialOffer: CommertialOffer\n sellerId: string\n}\n\nexport interface CommertialOffer {\n Price: number\n ListPrice: number\n AvailableQuantity: number\n}\n\n```" } ]
code_trustpilot_b096613b
[ { "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 trustpilot/react/typings/global.d.ts from the trustpilot VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\ninterface Window {\n dataLayer: any[]\n Trustpilot: any\n tp: any\n}\n\n```" } ]
code_trustpilot_512fde7f
[ { "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 trustpilot/react/modules/invitation.ts from the trustpilot VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { OrderPlacedTrackedData } from '../typings/events'\n\nexport function createProductInvitation(eventData: OrderPlacedTrackedData) {\n const { visitorContactInfo, orderGroup, transactionProducts } = eventData\n\n const [email, name, lastname] = visitorContactInfo\n const products = transactionProducts.map(product => {\n return {\n sku: product.sku,\n productUrl: `${window.location.origin}/${product.slug}/p`,\n name: product.name,\n }\n })\n const skus = products.map(p => p.sku)\n\n const tpData = {\n recipientEmail: email,\n recipientName: `${name} ${lastname}`,\n referenceId: orderGroup,\n source: 'InvitationScript',\n productSkus: skus,\n products,\n }\n\n window.tp('createInvitation', tpData)\n}\n\n```" } ]
code_vtex-b2b-core_190c69dc
[ { "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 vtex-b2b-core/node/service.json from the vtex-b2b-core VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"memory\": 256,\n \"ttl\": 10,\n \"timeout\": 2,\n \"minReplicas\": 1,\n \"maxReplicas\": 1,\n \"workers\": 1,\n \"routes\": {\n \"status\": {\n \"path\": \"/_v/status/:code\",\n \"public\": true\n }\n }\n}\n\n```" } ]
code_vtex-b2b-core_01b60dea
[ { "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 vtex-b2b-core/node/package.json from the vtex-b2b-core 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/ramda\": \"types/npm-ramda#dist\",\n \"@vtex/api\": \"6.45.15\",\n \"@vtex/test-tools\": \"^1.0.0\",\n \"@vtex/tsconfig\": \"^0.5.6\",\n \"typescript\": \"3.9.7\",\n \"vtex.b2b-core\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.b2b-core@0.0.1/public/@types/vtex.b2b-core\"\n },\n \"resolutions\": {\n \"@types/testing-library__dom\": \"6.12.1\",\n \"@types/express\": \"4.16.0\",\n \"@types/express-serve-static-core\": \"4.16.0\"\n },\n \"scripts\": {\n \"lint\": \"tsc --noEmit --pretty\"\n },\n \"version\": \"1.0.0\"\n}\n\n```" } ]
code_vtex-b2b-core_786b8567
[ { "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 vtex-b2b-core/node/index.ts from the vtex-b2b-core VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport type { ClientsConfig, ServiceContext, RecorderState } from '@vtex/api'\nimport { LRUCache, method, Service } from '@vtex/api'\n\nimport { Clients } from './clients'\nimport { status } from './middlewares/status'\nimport { validate } from './middlewares/validate'\n\nconst TIMEOUT_MS = 800\n\nconst memoryCache = new LRUCache<string, any>({ max: 5000 })\n\nmetrics.trackCache('status', memoryCache)\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\ndeclare global {\n type Context = ServiceContext<Clients, State>\n\n interface State extends RecorderState {\n code: number\n }\n}\n\nexport default new Service({\n clients,\n routes: {\n status: method({\n GET: [validate, status],\n }),\n },\n})\n\n```" } ]
code_vtex-b2b-core_97a60675
[ { "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 vtex-b2b-core/public/metadata/messages/es-AR.json from the vtex-b2b-core VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"name\": \"B2B Core\",\n \"headline\": \"B2B Core\",\n \"overview\": \"B2B Core\",\n \"features\": [\"B2B Core\"],\n \"websiteURL\": \"https://vtex.com/\",\n \"support\": {\n \"url\": \"https://support.vtex.com/hc/requests\"\n }\n}\n\n```" } ]
code_vtex-b2b-core_29e470d0
[ { "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 vtex-b2b-core/public/metadata/messages/pt-BR.json from the vtex-b2b-core VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"name\": \"B2B Core\",\n \"headline\": \"B2B Core\",\n \"overview\": \"B2B Core\",\n \"features\": [\"B2B Core\"],\n \"websiteURL\": \"https://vtex.com/\",\n \"support\": {\n \"url\": \"https://support.vtex.com/hc/requests\"\n }\n}\n\n```" } ]
code_vtex-b2b-core_ec330c59
[ { "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 vtex-b2b-core/public/metadata/messages/en-US.json from the vtex-b2b-core VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"name\": \"B2B Core\",\n \"headline\": \"B2B Core\",\n \"overview\": \"B2B Core\",\n \"features\": [\"B2B Core\"],\n \"websiteURL\": \"https://vtex.com/\",\n \"support\": {\n \"url\": \"https://support.vtex.com/hc/requests\"\n }\n}\n\n```" } ]
code_vtex-b2b-core_c1253ce9
[ { "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 vtex-b2b-core/masterdata/buyerOrgMember/schema.json from the vtex-b2b-core VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"title\": \"buyerOrgMember\",\n \"properties\": {\n \"customerId\": {\n \"type\": \"string\",\n \"title\": \"CustomerId\"\n },\n \"name\": {\n \"type\": \"string\",\n \"title\": \"Name\"\n },\n \"email\": {\n \"type\": \"string\",\n \"title\": \"Email\"\n },\n \"role\": {\n \"type\": \"string\",\n \"title\": \"Role\"\n }\n },\n \"v-indexed\": [\"id\", \"customerId\"],\n \"v-cache\": false\n}\n\n```" } ]
code_vtex-b2b-core_16c538ad
[ { "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 vtex-b2b-core/masterdata/buyerOrgConfiguration/schema.json from the vtex-b2b-core VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"title\": \"buyerOrgConfiguration\",\n \"properties\": {\n \"sellers\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\"\n },\n \"title\": \"Sellers\"\n },\n \"accessControlList\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\"\n },\n \"title\": \"AccessControlList\"\n },\n \"tradePolicy\": {\n \"type\": \"string\",\n \"title\": \"TradePolicy\"\n },\n \"canEditAddress\": {\n \"type\": \"boolean\",\n \"title\": \"CanEditAddress\"\n }\n },\n \"v-indexed\": [\"id\"],\n \"v-cache\": false\n}\n\n```" } ]
code_vtex-b2b-core_a10f8fbb
[ { "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 vtex-b2b-core/node/clients/status.ts from the vtex-b2b-core VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport type { InstanceOptions, IOContext, IOResponse } from '@vtex/api'\nimport { ExternalClient } from '@vtex/api'\n\nexport default class Status extends ExternalClient {\n constructor(context: IOContext, options?: InstanceOptions) {\n super('http://httpstat.us', context, options)\n }\n\n public async getStatus(status: number): Promise<string> {\n return this.http.get(status.toString(), {\n metric: 'status-get',\n })\n }\n\n public async getStatusWithHeaders(\n status: number\n ): Promise<IOResponse<string>> {\n return this.http.getRaw(status.toString(), {\n metric: 'status-get-raw',\n })\n }\n\n public async getStatusAndForceMaxAge(\n status: number\n ): Promise<IOResponse<string>> {\n return this.http.get(status.toString(), {\n forceMaxAge: 5000,\n metric: 'status-get-forceMaxAge',\n })\n }\n}\n\n```" } ]
code_vtex-b2b-core_31566818
[ { "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 vtex-b2b-core/node/clients/index.ts from the vtex-b2b-core VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { IOClients } from '@vtex/api'\n\nimport Status from './status'\n\nexport class Clients extends IOClients {\n public get status() {\n return this.getOrSet('status', Status)\n }\n}\n\n```" } ]
code_vtex-b2b-core_da35a0f1
[ { "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 vtex-b2b-core/node/middlewares/status.ts from the vtex-b2b-core VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nexport async function status(ctx: Context, next: () => Promise<any>) {\n const {\n state: { code },\n clients: { status: statusClient },\n } = ctx\n\n console.info('Received code:', code)\n\n const statusResponse = await statusClient.getStatus(code)\n\n console.info('Status response:', statusResponse)\n\n const {\n headers,\n data,\n status: responseStatus,\n } = await statusClient.getStatusWithHeaders(code)\n\n console.info('Status headers', headers)\n console.info('Status data:', data)\n\n ctx.status = responseStatus\n ctx.body = data\n ctx.set('Cache-Control', headers['cache-control'])\n\n await next()\n}\n\n```" } ]
code_vtex-b2b-core_2dbe2576
[ { "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 vtex-b2b-core/node/middlewares/validate.ts from the vtex-b2b-core VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { UserInputError } from '@vtex/api'\n\nexport async function validate(ctx: Context, next: () => Promise<any>) {\n const {\n vtex: {\n route: { params },\n },\n } = ctx\n\n console.info('Received params:', params)\n\n const { code } = params\n\n if (!code) {\n throw new UserInputError('Code is required')\n }\n\n const codeNumber = parseInt(code as string, 10)\n\n ctx.state.code = codeNumber\n\n await next()\n}\n\n```" } ]
code_search-segment-graphql_9be7740d
[ { "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 search-segment-graphql/graphql/schema.graphql from the search-segment-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```graphql\ntype Query {\n searchSegment(\n userEmail: String\n isAuthenticated: Boolean\n selectedFacets: [SelectedFacetsInput]\n ): [SelectedFacets] @cacheControl(scope: PUBLIC, maxAge: SHORT)\n}\n\n```" } ]
code_search-segment-graphql_059ed166
[ { "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 search-segment-graphql/node/package.json from the search-segment-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"name\": \"search-graphql\",\n \"description\": \"Don't delete this file, it's necessary to generate the TypeScript types of the GraphQL\"\n}\n\n```" } ]
code_search-segment-graphql_7ffeeeb1
[ { "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 search-segment-graphql/graphql/types/SelectedFacets.graphql from the search-segment-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```graphql\ntype SelectedFacets {\n key: String\n value: String\n}\n\ninput SelectedFacetsInput {\n key: String\n value: String\n}\n\n```" } ]
code_flixmedia_0d6cd1f1
[ { "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 flixmedia/docs/README.md from the flixmedia VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```markdown\n📢 Use this project, [contribute](https://github.com/vtex-apps/flixmedia) to it or open issues to help evolve it using [Store Discussion](https://github.com/vtex-apps/store-discussion).\n\n# Flixmedia\n\n> 🚧 WARNING\n> \n> This app is no longer supported. Consider using the [Flixmedia](https://apps.vtex.com/acupula-flixmedia/p) app by ACCT as an alternative.\n\nFlixmedia first party integration app. The [solution](https://flixmedia.eu/) enhances your website content, capturing retail partners, engaging shoppers, and increasing sale rates.\n\n## Configuration\n\n### Step 1 - Installing the Flixmedia app\n\n#### Using VTEX App Store \n\n1. Access the Apps section in your account's admin page.\n2. Look for the Flixmedia app.\n3. Click on the `Install` button.\n\n#### Using VTEX IO Toolbelt\n\nIn your terminal, log into your VTEX account and [install](https://vtex.io/docs/recipes/development/installing-an-app/) the `vtex.flixmedia@0.x` app.\n\n> ℹ️ *You can confirm if the app has been properly installed by running `vtex ls`.*\n\n### Step 2 - Defining the app settings\n\n1. Access the Flixmedia app in your admin's Apps section.\n2. Fill out the fields according to your Flixmedia data.\n3. Save your changes.\n\n![flixmedia-gif](https://user-images.githubusercontent.com/52087100/101814695-41cca680-3afd-11eb-975e-5db39d825f98.gif)\n\n### Step 3 - Updating your store theme \n\n1. Add the Flixmedia app to your theme's dependencies in the `manifest.json` file:\n\n```diff\n dependencies: {\n+ \"vtex.flixmedia\": \"0.x\"\n }\n```\n\n2. Declare the `product-details.flixmedia` block in the `store.product`'s children list, as shown below:\n\n```json\n\"store.product\": {\n \"children\": [\n \"product-description.flixmedia\",\n ]\n}\n```\n\n3. [Deploy your changes](https://vtex.io/docs/recipes/store-management/making-your-theme-content-public/).\n\n## Customization\n\nNo CSS Handles are available yet for the app customization.\n\n## Contributors ✨\n\nThanks goes to these wonderful people:\n\n<!-- ALL-CONTRIBUTORS-LIST:START - Do not remove or modify this section -->\n<!-- prettier-ignore-start -->\n<!-- markdownlint-disable -->\n<!-- markdownlint-enable -->\n<!-- prettier-ignore-end -->\n<!-- ALL-CONTRIBUTORS-LIST:END -->\n\nThis project follows the [all-contributors](https://github.com/all-contributors/all-contributors) specification. Contributions of any kind are welcome!\n\n<!-- DOCS-IGNORE:end -->\n\n```" } ]
code_flixmedia_0a6af6bd
[ { "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 flixmedia/graphql/schema.graphql from the flixmedia VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```graphql\n# Default GraphQL Type. You can learn more about GraphQL here: http://graphql.org/learn/\n\n# Specifies the available queries.\n# The resolvers for this query are implemented in here: node/graphql/index.ts\n\ntype Query {\n publicAppSettings: Settings @cacheControl(scope: SEGMENT, maxAge: MEDIUM)\n}\n\ntype Settings {\n flixDistributor: String\n flixLanguage: String\n flixBrand: String\n flixButton: String\n flixInpage: String\n flixButtonImage: String\n flixPrice: String\n flixFallback: String\n}\n```" } ]
code_flixmedia_d1832686
[ { "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 flixmedia/node/package.json from the flixmedia VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"name\": \"node\",\n \"version\": \"0.1.9\",\n \"description\": \"\",\n \"main\": \"index.js\",\n \"dependencies\": {\n \"axios\": \"^0.18.0\"\n },\n \"devDependencies\": {\n \"@vtex/api\": \"^3.3.1\",\n \"eslint\": \"^5.16.0\",\n \"eslint-config-vtex\": \"^10.1.0\",\n \"prettier\": \"^1.18.2\",\n \"typescript\": \"3.5.2\"\n },\n \"scripts\": {\n \"test\": \"echo \\\"Error: no test specified\\\" && exit 1\"\n },\n \"author\": \"\",\n \"license\": \"ISC\"\n}\n\n```" } ]
code_flixmedia_4d3a1be8
[ { "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 flixmedia/node/index.ts from the flixmedia VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { Service, Context, IOClients } from '@vtex/api'\n\ndeclare var process: {\n env: {\n VTEX_APP_ID: string\n }\n}\n\nexport default new Service({\n graphql: {\n resolvers: {\n Query: {\n publicAppSettings: async function publicAppSettings(\n _: any,\n __: any,\n ctx: Context<IOClients>\n ) {\n const {\n clients: { apps },\n } = ctx\n const settings = await apps.getAppSettings(process.env.VTEX_APP_ID)\n return settings\n },\n },\n },\n },\n})\n```" } ]
code_flixmedia_4021c18c
[ { "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 flixmedia/react/package.json from the flixmedia VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"name\": \"reviews\",\n \"dependencies\": {\n \"apollo-client\": \"2.4.12\",\n \"graphql\": \"14.1.1\",\n \"prop-types\": \"15.6.2\",\n \"react\": \"16.3.2\",\n \"react-apollo\": \"2.4.1\"\n },\n \"devDependencies\": {\n \"@types/classnames\": \"^2.2.7\",\n \"@types/graphql\": \"^14.2.0\",\n \"@types/jest\": \"^24.0.11\",\n \"@types/node\": \"^11.13.0\",\n \"@types/prop-types\": \"^15.7.0\",\n \"@types/ramda\": \"^0.26.5\",\n \"@types/react\": \"^16.8.10\",\n \"@types/react-intl\": \"^2.3.17\",\n \"@vtex/test-tools\": \"^0.2.0\",\n \"apollo-client\": \"^2.5.1\",\n \"eslint\": \"^5.16.0\",\n \"eslint-config-vtex\": \"^10.1.0\",\n \"eslint-config-vtex-react\": \"^4.1.0\",\n \"prettier\": \"^1.18.2\",\n \"tslint-eslint-rules\": \"^5.4.0\",\n \"typescript\": \"3.5.2\"\n },\n \"version\": \"0.1.9\"\n}\n\n```" } ]