id
stringlengths
12
53
messages
listlengths
3
3
code_b2b-supplier_3259fe26
[ { "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 b2b-supplier/messages/sv.json from the b2b-supplier VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"store/b2b-approved-message.message\": \"Din organisation är inte godkänd att göra beställningar i denna butik just nu. Om det har varit så här ett tag och du anser att detta är ett misstag, vänligen kontakta oss.\",\n \"store/b2b-auth.signup\": \"Skapa konto\",\n \"store/b2b-supplier.creating-buyer-org\": \"Skapar köparorganisation i leverantör\"\n}\n\n```" } ]
code_b2b-supplier_96c65868
[ { "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 b2b-supplier/messages/es.json from the b2b-supplier VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"store/b2b-approved-message.message\": \"Tu organización no está aprobada para realizar pedidos en esta tienda en este momento. Si ha sido así por un tiempo y crees que es un error, ponte en contacto con nosotros.\",\n \"store/b2b-auth.signup\": \"Regístrate\",\n \"store/b2b-supplier.creating-buyer-org\": \"Creando una organización de compradores en el proveedor\"\n}\n```" } ]
code_b2b-supplier_f97df852
[ { "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 b2b-supplier/messages/ar.json from the b2b-supplier VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"store/b2b-approved-message.message\": \"لم تتم الموافقة على مؤسستك لوضع الطلبات على هذا المتجر الآن. إذا كانت مثل هذه لفترة من الوقت وتعتقد أن هذا خطأ، يرجى الاتصال بنا.\",\n \"store/b2b-auth.signup\": \"التسجيل\",\n \"store/b2b-supplier.creating-buyer-org\": \"إنشاء منظمة للمشترين في المورد\"\n}\n\n```" } ]
code_b2b-supplier_63ad180a
[ { "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 b2b-supplier/messages/es-MX.json from the b2b-supplier VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"store/b2b-approved-message.message\": \"Tu organización no está aprobada para realizar pedidos en esta tienda en este momento. Si ha sido así por un tiempo y crees que es un error, ponte en contacto con nosotros.\",\n \"store/b2b-auth.signup\": \"Regístrate\",\n \"store/b2b-supplier.creating-buyer-org\": \"Creando una organización de compradores en el proveedor\"\n}\n\n```" } ]
code_b2b-supplier_57593861
[ { "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 b2b-supplier/docs/README.md from the b2b-supplier VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```markdown\n📢 Use this project, [contribute](https://github.com/{OrganizationName}/{AppName}) to it or open issues to help evolve it using [Store Discussion](https://github.com/vtex-apps/store-discussion).\n\n# B2B Supplier\n\n<!-- DOCS-IGNORE:start -->\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<!-- DOCS-IGNORE:end -->\n\nThe **B2B Supplier** app allows you, as a supplier, to enable customers to sign up and log in as Buyer Organizations in your store. It enables components related to authentication and authorization of users and Buyer Organizations.\n\n## Installation\n\nTo install the **B2B Supplier** app, you must follow the steps below.\n\n1. Run the following command on your CLI:\n\n ```\n vtex install vtex.b2b-supplier\n ```\n\n\n2. Add the app as a dependency in your theme’s `manifest.json` file, as follows:\n\n ```json\n \"dependencies\": {\n \"vtex.b2b-supplier\": \"0.x\"\n }\n ```\n\n\n3. Declare the following blocks in a given theme template or inside another block from the theme.\n\n| Block name | Description |\n| ----------- | ----------- | \n| `b2b-supplier.sign-up-button` | Renders a `Sign up` button that leads users to the form where they can sign up as a Buyer Organization. |\n| `b2b-supplier.approved-status` | Renders an alert informing the Buyer Organization user of their approval status in your store. |\n\nAfter the installation, it will be possible for buyers to Sign up as a Buyer Organization in your store or for you to create and manage Buyer Organizations via API.\n\n>⚠️ Remember that every time a new Buyer Organization signs up, it is necessary for the supplier to approve their access on Master Data.\n\n\n## Customization\n\nIn order to apply CSS customizations in this and other blocks, follow the instructions given in the recipe on [Using CSS Handles for store customization](https://developers.vtex.com/vtex-developer-docs/docs/vtex-io-documentation-using-css-handles-for-store-customization).\n\n\n| CSS Handles |\n| ----------- | \n| `container` | \n| `button` | \n| `label` |\n\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<!-- 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_b2b-supplier_9fbff110
[ { "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 b2b-supplier/node/service.json from the b2b-supplier VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"memory\": 256,\n \"ttl\": 60,\n \"timeout\": 120,\n \"minReplicas\": 2,\n \"maxReplicas\": 5,\n \"routes\": {\n \"keep-alive\": {\n \"path\": \"/_v/vtex.b2b-supplier/keep-alive\",\n \"public\": true,\n \"policies\": [\n {\n \"effect\": \"allow\",\n \"actions\": [\"get\"]\n }\n ]\n }\n }\n}\n```" } ]
code_b2b-supplier_b9388a88
[ { "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 b2b-supplier/node/package.json from the b2b-supplier VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"license\": \"MIT\",\n \"devDependencies\": {\n \"@types/axios\": \"^0.14.0\",\n \"@types/jsonwebtoken\": \"^8.5.4\",\n \"vtex.css-handles\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.css-handles@0.4.4/public/@types/vtex.css-handles\",\n \"vtex.styleguide\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.styleguide@9.145.0/public/@types/vtex.styleguide\"\n },\n \"dependencies\": {\n \"@vtex/api\": \"6.45.4\",\n \"jsonwebtoken\": \"^8.5.1\"\n },\n \"version\": \"2.3.0\"\n}\n\n```" } ]
code_b2b-supplier_3aa54043
[ { "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 b2b-supplier/node/index.ts from the b2b-supplier VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport type { ServiceContext } from '@vtex/api'\nimport { LRUCache, method, Service } from '@vtex/api'\n\nimport { resolvers } from './resolvers'\n\nconst memoryCache = new LRUCache<string, never>({ max: 5000 })\n\nmetrics.trackCache('status', memoryCache)\n\ndeclare global {\n type Context = ServiceContext\n}\n\nconst keepAlive = async (ctx: Context) => {\n ctx.set('Cache-Control', 'no-cache')\n ctx.status = 200\n}\n\n// Export a service that defines route handlers and client options.\nexport default new Service({\n routes: {\n 'keep-alive': method({ GET: keepAlive }),\n },\n graphql: {\n resolvers,\n },\n})\n\n```" } ]
code_b2b-supplier_26829e72
[ { "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 b2b-supplier/react/ApprovedStatus.test.tsx from the b2b-supplier VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\nimport { render } from '@vtex/test-tools/react'\n\nimport ApprovedStatus from './ApprovedStatus'\n\ntest('should render', () => {\n const { queryByTestId } = render(<ApprovedStatus />)\n\n expect(queryByTestId('message-container')).toBeInTheDocument()\n})\n\n```" } ]
code_b2b-supplier_bc1e42e6
[ { "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 b2b-supplier/react/SignUpButton.tsx from the b2b-supplier VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\nimport { Button } from 'vtex.styleguide'\nimport { FormattedMessage } from 'react-intl'\nimport { useCssHandles } from 'vtex.css-handles'\nimport { useQuery } from 'react-apollo'\nimport { useRuntime } from 'vtex.render-runtime'\n\nimport SignUpButtonQuery from './graphql/SignUpButtonQuery.graphql'\nimport { isLoggedIn, useSession } from './session'\n\nconst SIGN_UP_URL = 'https://join.vtex.com/buyer'\nconst SIGN_UP_ROUTE = '/signup'\n\nconst useSignUpStart = (handleRedirectSignup: () => void) => {\n const { route } = useRuntime()\n\n React.useEffect(() => {\n if (route.canonicalPath === SIGN_UP_ROUTE) handleRedirectSignup()\n }, [route.canonicalPath, handleRedirectSignup])\n}\n\nconst SignUpButton = () => {\n const { data } = useQuery(SignUpButtonQuery, { ssr: false })\n\n const handles = useCssHandles(['container', 'button', 'label'])\n\n const session = useSession()\n\n const handleRedirectSignup = React.useCallback(() => {\n if (!data?.supplierMeta) return\n\n const qs = new URLSearchParams({ supplier: data?.supplierMeta })\n\n window.location.href = `${SIGN_UP_URL}?${qs}`\n }, [data?.supplierMeta])\n\n useSignUpStart(handleRedirectSignup)\n\n if (isLoggedIn(session)) return null\n\n return (\n <div className={`${handles.container ?? ''} flex items-center`}>\n <Button\n variation=\"tertiary\"\n size=\"regular\"\n data-testid=\"signup-button\"\n onClick={handleRedirectSignup}\n className={handles.button}\n >\n <span className={`${handles.label ?? ''} f6 gray`}>\n <FormattedMessage id=\"store/b2b-auth.signup\" />\n </span>\n </Button>\n </div>\n )\n}\n\nexport default SignUpButton\n\n```" } ]
code_b2b-supplier_eff6ed67
[ { "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 b2b-supplier/react/SignUpButton.test.tsx from the b2b-supplier VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\nimport { render } from '@vtex/test-tools/react'\n\nimport SignUpButton from './SignUpButton'\n\ntest('Should render', () => {\n const { queryByTestId } = render(<SignUpButton />)\n\n expect(queryByTestId('signup-button')).toBeInTheDocument()\n})\n\n```" } ]
code_b2b-supplier_7e78137d
[ { "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 b2b-supplier/react/ApprovedStatus.tsx from the b2b-supplier VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\nimport { Alert } from 'vtex.styleguide'\nimport { FormattedMessage } from 'react-intl'\n\nimport { isApproved, isLoggedIn, useSession } from './session'\n\nconst ApprovedStatus = () => {\n const [show, setShow] = React.useState(true)\n const session = useSession()\n\n if (!show) return null\n\n if (!isLoggedIn(session)) return null\n\n if (isApproved(session)) return null\n\n return (\n <div className=\"relative\">\n <div className=\"mw8 tc absolute center top-0 left-0 right-0 z-1\">\n <Alert\n type=\"warning\"\n onClose={() => setShow(false)}\n data-testid=\"message-container\"\n >\n <FormattedMessage id=\"store/b2b-approved-message.message\" />\n </Alert>\n </div>\n </div>\n )\n}\n\nexport default ApprovedStatus\n\n```" } ]
code_b2b-supplier_cbc97e5a
[ { "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 b2b-supplier/react/session.ts from the b2b-supplier VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport type {\n Session,\n SessionPromise,\n SessionResponse,\n} from 'vtex.render-runtime'\nimport React from 'react'\n\nconst NOT_APPROVED_TRADE_POLICY = '5'\n\ndeclare global {\n interface Window {\n __RENDER_8_SESSION__?: {\n sessionPromise?: Promise<SessionPromise>\n }\n }\n}\n\nexport function getSession() {\n return window?.__RENDER_8_SESSION__?.sessionPromise ?? null\n}\n\nexport const useSession = () => {\n const [session, setSession] = React.useState<SessionResponse>()\n\n React.useEffect(() => {\n ;(async () => {\n const sessionPromise = getSession()\n\n if (!sessionPromise) return\n\n const { response } = await sessionPromise\n\n setSession(response)\n })()\n }, [])\n\n return session\n}\n\nexport const isLoggedIn = (session: SessionResponse | undefined): boolean =>\n !!(session as Session)?.namespaces?.profile?.email\n\nexport const isApproved = (session: SessionResponse | undefined): boolean => {\n const tradePolicy = (session as Session)?.namespaces?.store?.channel?.value\n\n if (!tradePolicy) return false\n\n return tradePolicy !== NOT_APPROVED_TRADE_POLICY\n}\n\n```" } ]
code_b2b-supplier_869b2b7a
[ { "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 b2b-supplier/react/package.json from the b2b-supplier VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"name\": \"b2b-supplier\",\n \"version\": \"2.3.0\",\n \"scripts\": {\n \"test\": \"vtex-test-tools test\"\n },\n \"dependencies\": {\n \"apollo-client\": \"^2.6.8\",\n \"react\": \"^16.12.0\",\n \"react-apollo\": \"^3.1.3\",\n \"react-dom\": \"^16.12.0\",\n \"react-intl\": \"^3.12.0\"\n },\n \"devDependencies\": {\n \"@apollo/react-testing\": \"^3.1.3\",\n \"@types/jest\": \"^25.1.4\",\n \"@types/node\": \"^13.9.8\",\n \"@types/react\": \"^16.9.31\",\n \"@vtex/test-tools\": \"^3.3.2\",\n \"@vtex/tsconfig\": \"^0.4.4\",\n \"apollo-cache-inmemory\": \"^1.6.5\",\n \"graphql\": \"^14.6.0\",\n \"typescript\": \"3.9.7\",\n \"vtex.css-handles\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.css-handles@0.4.4/public/@types/vtex.css-handles\",\n \"vtex.render-runtime\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.render-runtime@8.132.3/public/@types/vtex.render-runtime\",\n \"vtex.styleguide\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.styleguide@9.145.0/public/@types/vtex.styleguide\"\n }\n}\n\n```" } ]
code_b2b-supplier_d4968b09
[ { "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 b2b-supplier/react/styles.global.css from the b2b-supplier VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```css\n@keyframes spin {\n from {transform:rotate(0deg);}\n to {transform:rotate(360deg);}\n}\n\n.rotating {\n animation: spin 1s linear infinite\n}\n\n```" } ]
code_b2b-supplier_d7dc9454
[ { "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 b2b-supplier/store/interfaces.json from the b2b-supplier VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"b2b-supplier\": {\n \"component\": \"SignUpButton\"\n },\n \"b2b-supplier.approved-status\": {\n \"component\": \"ApprovedStatus\"\n },\n \"b2b-supplier.signup-button\": {\n \"component\": \"SignUpButton\"\n }\n}\n\n```" } ]
code_b2b-supplier_eefbab3d
[ { "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 b2b-supplier/node/typings/profileSystem.d.ts from the b2b-supplier VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\ninterface Address {\n id: string\n userId: string\n receiverName?: string\n complement?: string\n neighborhood?: string\n country?: string\n state?: string\n number?: string\n street?: string\n postalCode?: string\n city?: string\n reference?: string\n addressName?: string\n addressType?: string\n geoCoordinates?: string\n}\n\nexport interface Profile {\n firstName?: string\n lastName?: string\n profilePicture?: string\n email: string\n document?: string\n userId?: string\n birthDate?: string\n gender?: string\n homePhone?: string\n businessPhone?: string\n isCorporate?: boolean\n corporateName?: string\n corporateDocument?: string\n stateRegistration?: string\n approved?: boolean\n addresses?: Address[]\n tradeName?: string\n payments?: PaymentProfile[]\n customFields?: ProfileCustomField[]\n}\n\n```" } ]
code_b2b-supplier_fe21ec34
[ { "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 b2b-supplier/node/utils/getRequestConfig.ts from the b2b-supplier VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport type { IOContext, RequestTracingConfig } from '@vtex/api'\n\ntype Args = {\n context: IOContext\n authMethod: AuthMethod\n metric: string\n tracingConfig?: RequestTracingConfig\n}\n\nexport type AuthMethod = 'AUTH_TOKEN' | 'STORE_TOKEN' | 'ADMIN_TOKEN'\n\nexport const createTracing = (\n metric: string,\n tracingConfig?: RequestTracingConfig\n) => ({\n requestSpanNameSuffix: metric,\n ...tracingConfig?.tracing,\n})\n\nexport const getAuthToken = (ctx: IOContext, method: AuthMethod) => {\n switch (method) {\n case 'STORE_TOKEN':\n return ctx.storeUserAuthToken\n\n case 'ADMIN_TOKEN':\n return ctx.adminUserAuthToken\n\n case 'AUTH_TOKEN':\n return ctx.authToken\n\n default:\n return null\n }\n}\n\nexport const getRequestConfig = ({\n context,\n authMethod,\n metric,\n tracingConfig,\n}: Args) => {\n const token = getAuthToken(context, authMethod)\n const headers: Headers = token\n ? {\n VtexIdclientAutCookie: token,\n }\n : {}\n\n return {\n headers,\n metric,\n tracing: createTracing(metric, tracingConfig),\n }\n}\n\nexport interface Headers {\n [key: string]: string\n}\n\n```" } ]
code_b2b-supplier_f62dd04a
[ { "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 b2b-supplier/node/utils/statusCodeUtils.ts from the b2b-supplier VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport type { AxiosError } from 'axios'\nimport { AuthenticationError, ForbiddenError, UserInputError } from '@vtex/api'\n\nexport function isNotSuccessCode(statusCode: number) {\n return statusCode < 200 || statusCode > 299\n}\n\nexport const statusToError = (e: AxiosError) => {\n console.log(e.response?.data)\n if (!e.response) throw e\n\n const { response } = e as AxiosError\n\n if (!response?.status) throw e\n\n const { status } = response\n\n if (status === 401) throw new AuthenticationError(e)\n\n if (status === 403) throw new ForbiddenError(e)\n\n if (status === 400) throw new UserInputError(e)\n\n throw e\n}\n\n```" } ]
code_b2b-supplier_8a285268
[ { "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 b2b-supplier/node/utils/wrapTryCatch.ts from the b2b-supplier VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nexport default async function wrapTryCatch<T>(promise: Promise<T>) {\n try {\n const response = await promise\n\n return {\n response,\n error: null,\n }\n } catch (error) {\n return {\n response: null,\n error,\n }\n }\n}\n\n```" } ]
code_b2b-supplier_8444d35b
[ { "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 b2b-supplier/node/resolvers/supplierMeta.ts from the b2b-supplier VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport jwt from 'jsonwebtoken'\n\nconst SECRET = process.env.SECRET ?? 'b2b-s3cr3t'\n\nconst supplierMeta = (_: unknown, __: unknown, ctx: Context) => {\n const {\n vtex: { account },\n header: { referer },\n } = ctx\n\n return jwt.sign({ returnUrl: referer, account }, SECRET)\n}\n\nexport default supplierMeta\n\n```" } ]
code_b2b-supplier_ec66fc3a
[ { "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 b2b-supplier/node/resolvers/index.ts from the b2b-supplier VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport supplierMeta from './supplierMeta'\n\nexport const resolvers = {\n Query: {\n supplierMeta,\n },\n}\n\n```" } ]
code_b2b-supplier_e9d6f8ed
[ { "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 b2b-supplier/react/assests/PinkDots.tsx from the b2b-supplier VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\n\nconst PinkDots = () => {\n return (\n <div className=\"flex items-center rotating\">\n <span\n id=\"pinkDot1\"\n className=\"br-100 dib bg-rebel-pink\"\n style={{\n height: '0.5rem',\n width: '0.5rem',\n minWidth: '0.5rem',\n }}\n />\n <span\n id=\"pinkDot2\"\n className=\"br-100 dib bg-rebel-pink ml3\"\n style={{\n height: '0.5rem',\n width: '0.5rem',\n minWidth: '0.5rem',\n }}\n />\n </div>\n )\n}\n\nexport default PinkDots\n\n```" } ]
code_b2b-supplier_aeca5f3f
[ { "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 b2b-supplier/react/assests/VtexLogoFull.tsx from the b2b-supplier VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\n\nconst VtexLogoFull = () => {\n return (\n <svg\n height=\"100%\"\n viewBox=\"0 0 88 32\"\n fill=\"none\"\n xmlns=\"http://www.w3.org/2000/svg\"\n >\n <path\n fillRule=\"evenodd\"\n clipRule=\"evenodd\"\n d=\"M6.63761 0H34.4236C36.5224 0 37.8656 2.24785 36.8812 4.11234L22.9541 30.4738C21.8783 32.5116 18.9741 32.5079 17.9021 30.4678L14.856 24.6673L12.4281 29.2646C12.1069 29.8746 11.4769 30.2561 10.7906 30.2561C10.1044 30.2561 9.47437 29.8746 9.1532 29.2646L0.213403 12.2451C-0.0889814 11.6675 -0.0688659 10.9728 0.26643 10.4139C0.601726 9.85495 1.20332 9.51321 1.85233 9.51301H6.89095L4.11161 4.2192C3.10344 2.3039 4.48308 0 6.63761 0ZM15.938 22.6309L21.9432 11.2616C22.1409 10.8875 22.1291 10.4366 21.9122 10.0735C21.6952 9.71042 21.3049 9.4883 20.8838 9.48828H8.89792C8.46599 9.48957 8.06621 9.71805 7.84401 10.0906C7.6218 10.4632 7.60956 10.9255 7.81174 11.3094L13.759 22.6309C13.9729 23.0365 14.392 23.2901 14.8485 23.2901C15.305 23.2901 15.7241 23.0365 15.938 22.6309Z\"\n fill=\"#F71963\"\n />\n <path\n d=\"M63.9797 12.2306H60.9403V22.7083C60.9399 22.9071 60.7798 23.0681 60.5822 23.0685H58.2382C58.0406 23.0681 57.8806 22.9071 57.8801 22.7083V12.2306H54.8229C54.7299 12.2344 54.6393 12.2002 54.5719 12.1357C54.5044 12.0712 54.4658 11.982 54.4648 11.8883V10.035C54.4658 9.94142 54.5044 9.85217 54.5719 9.78767C54.6393 9.72317 54.7299 9.68894 54.8229 9.69279H63.9789C64.1765 9.68347 64.3445 9.83638 64.3549 10.035V11.8891C64.3441 12.0871 64.1767 12.2395 63.9797 12.2306Z\"\n fill=\"#F71963\"\n />\n <path\n d=\"M73.7343 22.9918C73.108 23.0815 72.0545 23.2257 70.1221 23.2257C67.8138 23.2257 65.7744 22.6316 65.7744 19.3562V13.3779C65.7744 10.1025 67.8324 9.52637 70.1399 9.52637C72.0716 9.52637 73.108 9.67059 73.7343 9.76027C73.9846 9.79614 74.0924 9.88656 74.0924 10.1205V11.7966C74.092 11.9954 73.9319 12.1564 73.7343 12.1568H69.9616C69.1206 12.1568 68.8168 12.4445 68.8168 13.3809V15.0189H73.5916C73.7892 15.0194 73.9493 15.1804 73.9497 15.3791V17.0889C73.9493 17.2877 73.7892 17.4487 73.5916 17.4491H68.8168V19.357C68.8168 20.2926 69.1206 20.581 69.9616 20.581H73.7343C73.9319 20.5814 74.092 20.7425 74.0924 20.9412V22.6152C74.0924 22.8476 73.9846 22.9559 73.7343 22.9918Z\"\n fill=\"#F71963\"\n />\n <path\n d=\"M87.2343 23.0662H84.3896C84.1571 23.0662 84.0494 22.9914 83.9245 22.7964L81.458 18.8574L79.2232 22.7097C79.0977 22.9257 78.9728 23.0699 78.7774 23.0699H76.1296C75.9506 23.0699 75.8614 22.9615 75.8614 22.836C75.8649 22.7919 75.877 22.749 75.8971 22.7097L79.773 16.2083L75.857 10.0349C75.8371 10.002 75.8249 9.96491 75.8213 9.92655C75.8346 9.78923 75.9525 9.68643 76.0895 9.69265H78.9699C79.1667 9.69265 79.3101 9.87275 79.4156 10.0349L81.7046 13.6705L83.9201 10.0349C84.0092 9.87275 84.1705 9.69265 84.3658 9.69265H87.0137C87.1507 9.68643 87.2686 9.78923 87.2819 9.92655C87.2783 9.96491 87.2661 10.002 87.2462 10.0349L83.3495 16.2464L87.4134 22.7097C87.4451 22.7646 87.4634 22.8264 87.4669 22.8898C87.4676 22.9944 87.3777 23.0662 87.2343 23.0662Z\"\n fill=\"#F71963\"\n />\n <path\n d=\"M50.1743 9.72587C50.0425 9.72622 49.9294 9.82005 49.9039 9.95006L47.3065 19.6193C47.2709 19.8173 47.2174 19.889 47.0562 19.889C46.895 19.889 46.8415 19.8143 46.8058 19.6193L44.2055 9.94782C44.18 9.81781 44.0668 9.72398 43.9351 9.72363H41.3786C41.2944 9.72372 41.2148 9.76243 41.1625 9.82878C41.1101 9.89513 41.0907 9.98187 41.1097 10.0644C41.1097 10.0644 44.282 21.1534 44.317 21.2626C44.7404 22.5838 45.7679 23.2152 47.0755 23.2152C48.3207 23.2152 49.4076 22.5539 49.8325 21.2663C49.8831 21.1168 52.9848 10.0637 52.9848 10.0637C53.0036 9.98123 52.984 9.89471 52.9317 9.82855C52.8794 9.76239 52.7999 9.72377 52.7159 9.72363L50.1743 9.72587Z\"\n fill=\"#F71963\"\n />\n <path\n fillRule=\"evenodd\"\n clipRule=\"evenodd\"\n d=\"M6.63761 0H34.4236C36.5224 0 37.8656 2.24785 36.8812 4.11234L22.9541 30.4738C21.8783 32.5116 18.9741 32.5079 17.9021 30.4678L14.856 24.6673L12.4281 29.2646C12.1069 29.8746 11.4769 30.2561 10.7906 30.2561C10.1044 30.2561 9.47437 29.8746 9.1532 29.2646L0.213403 12.2451C-0.0889814 11.6675 -0.0688659 10.9728 0.26643 10.4139C0.601726 9.85495 1.20332 9.51321 1.85233 9.51301H6.89095L4.11161 4.2192C3.10344 2.3039 4.48308 0 6.63761 0ZM15.938 22.6309L21.9432 11.2616C22.1409 10.8875 22.1291 10.4366 21.9122 10.0735C21.6952 9.71042 21.3049 9.4883 20.8838 9.48828H8.89792C8.46599 9.48957 8.06621 9.71805 7.84401 10.0906C7.6218 10.4632 7.60956 10.9255 7.81174 11.3094L13.759 22.6309C13.9729 23.0365 14.392 23.2901 14.8485 23.2901C15.305 23.2901 15.7241 23.0365 15.938 22.6309Z\"\n fill=\"#F71963\"\n />\n </svg>\n )\n}\n\nexport default VtexLogoFull\n\n```" } ]
code_b2b-supplier_7747c504
[ { "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 b2b-supplier/react/typings/vtex.render-runtime.d.ts from the b2b-supplier VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\n/* Typings for `render-runtime` */\ndeclare module 'vtex.render-runtime' {\n import type { ComponentType, ReactElement, ReactType } from 'react'\n\n export interface NavigationOptions {\n page: string\n params?: unknown\n }\n\n export interface RenderContextProps {\n runtime: {\n navigate: (options: NavigationOptions) => void\n }\n }\n\n interface ExtensionPointProps {\n id: string\n\n [key: string]: any\n }\n\n interface ChildBlock<BlockProps> {\n props: BlockProps\n }\n\n export const ExtensionPoint: ComponentType<ExtensionPointProps>\n export const useChildBlock: <BlockProps>({\n id,\n }: {\n id: string\n }) => ChildBlock<BlockProps> | null\n export const Helmet: ReactElement\n export const Link: ReactType\n export const NoSSR: ReactElement\n export const RenderContextConsumer: unknown\n export const TreePathContextConsumer: unknown\n export const useTreePath: unknown\n export const useRuntime: any\n export const canUseDOM: boolean\n export const withRuntimeContext: <\n TOriginalProps extends Record<string, unknown>\n >(\n Component: ComponentType<TOriginalProps & RenderContextProps>\n ) => ComponentType<TOriginalProps>\n\n export const withSession: <TOriginalProps extends {}>(\n Component: ComponentType<TOriginalProps & RenderContextProps>\n ) => ComponentType<TOriginalProps>\n\n interface KeyValue {\n value: string\n }\n\n interface Session {\n id: string\n namespaces: {\n store: {\n channel: KeyValue\n }\n profile: {\n isAuthenticated: KeyValue\n email: string\n }\n }\n }\n\n interface SessionUnauthorized {\n type: 'Unauthorized'\n message: string\n }\n\n interface SessionForbidden {\n type: 'Forbidden'\n message: string\n }\n\n type SessionResponse = Session | SessionUnauthorized | SessionForbidden\n\n export interface RenderSession {\n sessionPromise: Promise<SessionPromise>\n }\n\n export interface SessionPromise {\n response: Session | SessionUnauthorized | SessionForbidden\n }\n}\n\n```" } ]
code_b2b-supplier_007605ee
[ { "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 b2b-supplier/react/typings/gql.d.ts from the b2b-supplier VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\ndeclare module '*.gql' {\n import { DocumentNode } from 'graphql'\n\n const Schema: DocumentNode\n\n export default Schema\n}\n\ndeclare module '*.graphql' {\n import { DocumentNode } from 'graphql'\n\n const schema: DocumentNode\n\n export default Schema\n}\n\n```" } ]
code_b2b-supplier_b310e210
[ { "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 b2b-supplier/react/typings/css.d.ts from the b2b-supplier VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\ndeclare module '*.css' {\n type Styles = {\n [selector: string]: string\n }\n\n const styles: Styles\n\n export default styles\n}\n\n```" } ]
code_barcode-generator_9e6ef7d7
[ { "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 barcode-generator/docs/README.md from the barcode-generator VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```markdown\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## 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 information about this service, like the maximum timeout and number of replicas, 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 in the example, we use the `:code` notation for declaring a route param named `code`. An HTTP request for `https://{{workspace}}--{{account}}.myvtex.com/_v/status/500` will match the route we've defined. \n\nFor each _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 to 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)**, which supports a 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\n\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 behavior. 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. \n\nCheck 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 an HTTP service, we should follow HTTP rules regarding data types, cache, authorization, and status codes. Our example app sets a `ctx.status` value that will be used as an HTTP status code return value, but often, we also want to give proper information about errors.\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 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, you often need to have access to the **request body** that comes in 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## 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```" } ]
code_barcode-generator_4987a134
[ { "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 barcode-generator/node/service.json from the barcode-generator 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 \"status\": {\n \"path\": \"/_v/status/:code\",\n \"public\": true\n }\n }\n}\n\n```" } ]
code_barcode-generator_9b5400ad
[ { "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 barcode-generator/node/package.json from the barcode-generator 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 },\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\": \"0.2.26\"\n}\n\n```" } ]
code_barcode-generator_e9641fc0
[ { "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 barcode-generator/node/index.ts from the barcode-generator 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\n// Create a LRU memory cache for the Status client.\n// The 'max' parameter sets the size of the cache.\n// The @vtex/api HttpClient respects Cache-Control headers and uses the provided cache.\n// Note that the response from the API being called must include an 'etag' header\n// or a 'cache-control' header with a 'max-age' value. If neither exist, the response will not be cached.\n// To force responses to be cached, consider adding the `forceMaxAge` option to your client methods.\nconst memoryCache = new LRUCache<string, any>({ max: 5000 })\n\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 extends RecorderState {\n code: number\n }\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 status: method({\n GET: [validate, status],\n }),\n },\n})\n\n```" } ]
code_barcode-generator_60dc4938
[ { "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 barcode-generator/node/clients/status.ts from the barcode-generator 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 // when using an LRUCache, this will force the response to be cached\n forceMaxAge: 5000,\n metric: 'status-get-forceMaxAge',\n })\n }\n}\n\n```" } ]
code_barcode-generator_e9f81c81
[ { "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 barcode-generator/node/clients/index.ts from the barcode-generator VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { IOClients } from '@vtex/api'\n\nimport Status from './status'\n\n// Extend the default IOClients implementation with our own custom clients.\nexport class Clients extends IOClients {\n public get status() {\n return this.getOrSet('status', Status)\n }\n}\n\n```" } ]
code_barcode-generator_15c5eeba
[ { "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 barcode-generator/node/middlewares/status.ts from the barcode-generator 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_barcode-generator_4e326363
[ { "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 barcode-generator/node/middlewares/validate.ts from the barcode-generator 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') // Wrapper for a Bad Request (400) HTTP Error. Check others in https://github.com/vtex/node-vtex-api/blob/fd6139349de4e68825b1074f1959dd8d0c8f4d5b/src/errors/index.ts\n }\n\n const codeNumber = parseInt(code as string, 10)\n\n ctx.state.code = codeNumber\n\n await next()\n}\n\n```" } ]
code_barcode-generator_420d9748
[ { "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 barcode-generator/node/__tests__/simple.test.ts from the barcode-generator VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\n// You can import your files here for testing them\n//\n// More info: https://github.com/sapegin/jest-cheat-sheet\n\ndescribe('simpleTest', () => {\n it('one test case', async () => {\n expect(0.2 + 0.1).not.toBe(0.3)\n })\n})\n\n```" } ]
code_order-sms-notification_d27427a9
[ { "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 order-sms-notification/docs/README.md from the order-sms-notification VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```markdown\n# Order SMS Notification\n\n### how to install in an account\n\n - first install vtex.sms-provider in version 0.x (any version higher than 0.5.0 since we fixed a bug in 0.5.1)\n\n - then configure a trigger in MasterData v2 in the `order` data entity. (tldr; make a schema with name `order-sms-notification` in `order` entity SUBSTITUTING {{accountName}} in action uri with the proper account name) ex.:\n ```\n{\n \"properties\": {\n \"orderId\": {\n \"type\": \"string\",\n \"title\": \"Order Id\"\n },\n \"status\": {\n \"type\": \"string\",\n \"title\": \"Status\"\n }\n },\n \"required\": [\n \"orderId\",\n \"status\"\n ],\n \"v-indexed\": [\n \"orderId\",\n \"status\"\n ],\n \"v-default-fields\": [\n \"id\",\n \"orderId\",\n \"status\",\n \"_self\"\n ],\n \"v-triggers\": [\n {\n \"name\": \"send-sms\",\n \"condition\": \"status=ready-for-handling\",\n \"active\": true,\n \"action\": {\n \"type\": \"http\",\n \"uri\": \"https://{{accountName}}.myvtex.com/_v/order-sms-notification\",\n \"method\": \"POST\",\n \"headers\": {\n \"content-type\": \"application/json\"\n },\n \"body\": {\n \"orderId\": \"{!orderId}\",\n \"accountName\": \"{!accountName}\"\n }\n }\n }\n ]\n}\n ```\n\n```" } ]
code_order-sms-notification_10ed0110
[ { "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 order-sms-notification/masterdata/masterdata.json from the order-sms-notification VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n[\n {\n \"entity\": \"ORDER_FISCAL_CODE\",\n \"type\": \"schemas\",\n \"values\": [\n {\n \"id\": \"ORDER_FISCAL_CODE_SCHEMA\",\n \"hooks\": [\n {\n \"name\": \"send-request\",\n \"condition\": \"updatedIn is null\",\n \"active\": true,\n \"action\": {\n \"type\": \"http\",\n \"uri\":\n \"https://api.vtex.com/instore/functions/vtex.instore-functions-save-fiscal-note-v0/run\",\n \"headers\": {\n \"content-type\": \"application/json\"\n },\n \"method\": \"POST\",\n \"body\": {\n \"orderId\": \"{!id}\",\n \"type\": \"Output\",\n \"accountName\": \"{!accountName}\"\n }\n }\n }\n ]\n }\n ]\n },\n {\n \"entity\": \"CANCEL_ORDER_FISCAL_CODE\",\n \"type\": \"schemas\",\n \"values\": [\n {\n \"id\": \"CANCEL_ORDER_FISCAL_CODE_SCHEMA\",\n \"hooks\": [\n {\n \"name\": \"send-request\",\n \"condition\": \"updatedIn is null\",\n \"active\": true,\n \"action\": {\n \"type\": \"http\",\n \"uri\":\n \"https://api.vtex.com/instore/functions/vtex.instore-functions-save-fiscal-note-v0/run\",\n \"headers\": {\n \"content-type\": \"application/json\"\n },\n \"method\": \"POST\",\n \"body\": {\n \"orderId\": \"{!id}\",\n \"type\": \"Input\",\n \"accountName\": \"{!accountName}\"\n }\n }\n }\n ]\n }\n ]\n },\n {\n \"entity\": \"vtable\",\n \"type\": \"documents\",\n \"schemas\": [\"app\"],\n \"values\": [\n {\n \"id\": \"stores\",\n \"name\": \"stores\",\n \"title\": \"Admin das lojas\",\n \"tables\": [\n {\n \"id\": \"main\",\n \"label\": \"Complete\",\n \"title\": \"Stores\",\n \"entity\": \"stores\",\n \"model\": \"v1\",\n \"saveOnChange\": true,\n \"fields\": {\n \"id\": {\n \"width\": 200,\n \"label\": \"Id do Documento\"\n },\n \"name\": {\n \"width\": 200,\n \"label\": \"Nome\"\n },\n \"country\": {\n \"width\": 200,\n \"label\": \"País\"\n },\n \"address\": {\n \"width\": 400,\n \"label\": \"Endereço\"\n },\n \"number\": {\n \"width\": 100,\n \"label\": \"Número\"\n },\n \"complement\": {\n \"width\": 200,\n \"label\": \"Complemento\"\n },\n \"neighborhood\": {\n \"width\": 200,\n \"label\": \"Bairro\"\n },\n \"city\": {\n \"width\": 200,\n \"label\": \"Cidade\"\n },\n \"state\": {\n \"width\": 200,\n \"label\": \"Estado\"\n },\n \"postalCode\": {\n \"width\": 200,\n \"label\": \"CEP\"\n },\n \"latitude\": {\n \"width\": 50,\n \"label\": \"Latitude\"\n },\n \"longitude\": {\n \"width\": 50,\n \"label\": \"Longitude\"\n },\n \"tradePolicy\": {\n \"width\": 200,\n \"label\": \"Política comercial\"\n },\n \"ecommerceSellerId\": {\n \"width\": 50,\n \"label\": \"ecommerceSellerId\"\n },\n \"storeSellerId\": {\n \"width\": 50,\n \"label\": \"storeSellerId\"\n }\n },\n \"list\": [\n \"id\",\n \"name\",\n \"country\",\n \"tradePolicy\",\n \"postalCode\",\n \"city\",\n \"state\",\n \"address\",\n \"number\",\n \"complement\",\n \"neighborhood\"\n ],\n \"editor\": {\n \"settings\": {\n \"sections\": [\n {\n \"name\": \"Principal\",\n \"fields\": [\n \"id\",\n \"name\",\n \"country\",\n \"postalCode\",\n \"city\",\n \"state\",\n \"address\",\n \"number\",\n \"complement\",\n \"neighborhood\"\n ]\n },\n {\n \"name\": \"Informações técnicas\",\n \"fields\": [\n \"tradePolicy\",\n \"ecommerceSellerId\",\n \"latitude\",\n \"longitude\",\n \"storeSellerId\"\n ]\n }\n ]\n }\n }\n }\n ]\n },\n {\n \"id\": \"vendors\",\n \"name\": \"vendors\",\n \"title\": \"Admin dos vendedores\",\n \"tables\": [\n {\n \"id\": \"main\",\n \"label\": \"Complete\",\n \"title\": \"Vendors\",\n \"entity\": \"vendors\",\n \"model\": \"v1\",\n \"saveOnChange\": true,\n \"fields\": {\n \"id\": {\n \"width\": 200,\n \"label\": \"Id do Documento\"\n },\n \"user\": {\n \"width\": 200,\n \"label\": \"Email\"\n },\n \"name\": {\n \"width\": 200,\n \"label\": \"Nome\"\n },\n \"store\": {\n \"width\": 300,\n \"relatedApp\": \"stores\",\n \"relatedTable\": \"main\",\n \"label\": \"Loja\"\n }\n },\n \"list\": [\"id\", \"user\", \"name\", \"store\"],\n \"editor\": {\n \"settings\": {\n \"sections\": [\n {\n \"name\": \"Cadastro do vendedor\",\n \"fields\": [\"id\", \"user\", \"name\", \"store\"]\n }\n ]\n }\n }\n }\n ]\n }\n ]\n }\n]\n```" } ]
code_order-sms-notification_f8e38352
[ { "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 order-sms-notification/node/log-helper.ts from the order-sms-notification VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nlet currentAccountName = 'account-name-not-set'\nlet currentFunctionName = 'function-name-not-set'\n\nexport function configLog(accountName, functionName) {\n currentAccountName = accountName\n currentFunctionName = functionName\n}\n\nexport function sendLog(message) {\n console.log(`[${currentAccountName}] [${currentFunctionName}] ${message}`)\n}\n\n```" } ]
code_order-sms-notification_b497ea4b
[ { "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 order-sms-notification/node/service.json from the order-sms-notification VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"stack\": \"nodejs\",\n \"memory\": 64,\n \"runtimeArgs\": [\n \"--optimize_for_size\",\n \"--max_old_space_size=48\"\n ],\n \"routes\": {\n \"sms\": {\n \"path\": \"/_v/order-sms-notification\",\n \"public\": true\n }\n }\n}\n\n```" } ]
code_order-sms-notification_04267e23
[ { "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 order-sms-notification/node/order-fetcher.ts from the order-sms-notification VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport fetchHelper from './fetch-helper'\nimport { sendLog } from './log-helper'\n\nconst CORRECT_STATE = 'ready-for-handling'\nconst FUTURE_STATE_CHANGE = 'start-handling'\nconst FUTURE_STATE = 'invoiced'\n\nconst getCheckoutEndpoint = accountName =>\n `http://${accountName}.vtexcommercestable.com.br/api/checkout`\n\nconst getOMSEndpoint = accountName =>\n `http://${accountName}.vtexcommercestable.com.br/api/oms`\n\nconst getMDEndpoint = (accountName, acronym) =>\n `http://api.vtex.com/${accountName}/dataentities/${acronym}/documents`\n\n\nexport function getFeed(accountName, maxLot, authToken) {\n const omsEndpoint = getOMSEndpoint(accountName)\n const feedUrl = `${omsEndpoint}/pvt/feed/orders/status?maxLot=${maxLot}`\n return fetchHelper(feedUrl, {\n headers: {\n 'X-Vtex-Proxy-To': `https://${accountName}.vtexcommercestable.com.br`,\n Authorization: authToken,\n }\n })\n}\n\nexport function getOrderForm(accountName, orderFormId) {\n const checkoutEndpoint = getCheckoutEndpoint(accountName)\n const checkoutUrl = `${checkoutEndpoint}/pub/orderForm/${orderFormId}`\n return fetchHelper(checkoutUrl)\n}\n\nexport function getOrder(accountName, orderId, authToken) {\n const omsEndpoint = getOMSEndpoint(accountName)\n const omsUrl = `${omsEndpoint}/pvt/orders/${orderId}`\n return fetchHelper(omsUrl, {\n headers: {\n 'X-Vtex-Proxy-To': `https://${accountName}.vtexcommercestable.com.br`,\n 'Proxy-Authorization': authToken,\n 'VtexIdclientAutCookie': authToken,\n }\n })\n}\n\nexport function addCart(accountName, orderFormId, itemsPayload) {\n const checkoutEndpoint = getCheckoutEndpoint(accountName)\n const checkoutUrl = `${checkoutEndpoint}/pub/orderForm/${orderFormId}/items`\n return fetchHelper(checkoutUrl, {\n method: 'POST',\n body: JSON.stringify(itemsPayload),\n headers: {\n 'X-Vtex-Proxy-To': `https://${accountName}.vtexcommercestable.com.br`,\n }\n })\n}\n\nfunction leftPad(value) {\n value = parseInt(value, 10)\n if (value < 10) {\n return `0${value}`\n }\n return value.toString()\n}\n\nfunction formatInternationalDate(date) {\n const year = date.getFullYear()\n const day = leftPad(date.getDate())\n const month = leftPad(date.getMonth() + 1)\n return `${year}-${month}-${day}`\n}\n\nexport function invoiceOrder({\n accountName,\n orderId,\n invoiceType,\n invoiceNumber,\n invoiceValue,\n invoiceUrl,\n items,\n headers\n}) {\n const omsEndpoint = getOMSEndpoint(accountName)\n return fetchHelper(`${omsEndpoint}/pvt/orders/${orderId}/invoice`, {\n method: 'POST',\n headers,\n body: JSON.stringify({\n invoiceNumber,\n invoiceValue,\n invoiceUrl,\n issuanceDate: formatInternationalDate(new Date()),\n trackingNumber: null,\n trackingUrl: null,\n type: invoiceType,\n items: items\n }),\n retries: 3\n })\n}\n\nfunction getXmlTagValue(xml, tagName) {\n const begin = xml.indexOf(`<${tagName}>`) + `<${tagName}>`.length\n const end = xml.indexOf(`</${tagName}>`, begin)\n return xml.substring(begin, end)\n}\n\nfunction getXmlTagPropertyValue(xml, tagName, property) {\n let begin = xml.indexOf(`<${tagName}`) + `<${tagName}`.length\n begin = xml.indexOf(`${property}=\"`, begin) + `${property}=\"`.length\n const end = xml.indexOf(`\"`, begin)\n return xml.substring(begin, end)\n}\n\nfunction getInvoiceNumber(xml) {\n if (!xml) {\n return null\n }\n return (\n getXmlTagPropertyValue(xml, 'infNFe', 'Id') ||\n getXmlTagPropertyValue(xml, 'infCFe', 'Id')\n )\n}\n\nfunction getCancelInvoiceNumber(xml) {\n if (!xml) {\n return null\n }\n return (\n getXmlTagValue(xml, 'chNFe') || getXmlTagPropertyValue(xml, 'infCFe', 'Id')\n )\n}\n\nfunction getInvoiceUrl(accountName, orderId, acronym) {\n return `${getMDEndpoint(accountName, acronym)}/${orderId}`\n}\n\nfunction rejectWithError(\n errorMessage,\n shouldRetry = false,\n extraErrorInfo = {}\n) {\n sendLog(errorMessage)\n return Promise.reject({\n message: errorMessage,\n shouldRetry,\n ...extraErrorInfo\n })\n}\n\nexport function updateFiscalNote(\n accountName,\n order,\n authToken,\n cfeXml,\n type = 'Output'\n) {\n const { orderId } = order\n\n const invoiceNumber =\n type === 'Input' ? getCancelInvoiceNumber(cfeXml) : getInvoiceNumber(cfeXml)\n\n if (!invoiceNumber) {\n return rejectWithError(\n `Error finding invoiceNumber (${invoiceNumber}) on xml ${cfeXml}`\n )\n }\n\n const mdEntity =\n type === 'Input' ? 'CANCEL_ORDER_FISCAL_CODE' : 'ORDER_FISCAL_CODE'\n\n if (order.packageAttachment && order.packageAttachment.packages) {\n let alreadyHasInvoiceNumber = false\n\n order.packageAttachment.packages.forEach(orderPackage => {\n alreadyHasInvoiceNumber =\n alreadyHasInvoiceNumber ||\n (orderPackage.type === type &&\n orderPackage.invoiceNumber === invoiceNumber)\n })\n\n if (alreadyHasInvoiceNumber) {\n return rejectWithError(\n `The fiscal note with number ${invoiceNumber} and type ${\n type\n } already exists on order ${orderId}`,\n false, // should not retry\n { alreadyHasInvoiceNumber }\n )\n }\n }\n\n const headers = {\n 'Proxy-Authorization': authToken,\n 'VtexIdclientAutCookie': authToken,\n 'X-Vtex-Proxy-To': `https://${accountName}.vtexcommercestable.com.br`,\n }\n\n return invoiceOrder({\n accountName,\n orderId,\n invoiceType: type,\n invoiceNumber,\n invoiceValue: order.value,\n invoiceUrl: getInvoiceUrl(accountName, orderId, mdEntity),\n items: order.items,\n headers\n }).catch(e => {\n e.shouldRetry = true\n return Promise.reject(e)\n })\n}\n\nexport function updateCancelFiscalNote(accountName, order, cfeXml, authToken) {\n return updateFiscalNote(accountName, order, cfeXml, authToken, 'Input')\n}\n\nexport function changeOrderStatus(\n accountName,\n order,\n authToken,\n correctState = CORRECT_STATE,\n futureStateChange = FUTURE_STATE_CHANGE,\n futureState = FUTURE_STATE\n) {\n const { orderId } = order\n if (order.status === futureState) {\n sendLog(`Order ${orderId} is already with status ${futureState}`)\n return Promise.resolve({ success: true })\n }\n if (order.status !== correctState) {\n return rejectWithError(\n `Order ${order.orderId} with incorrect status ${\n order.status\n } instead of ${correctState}`,\n true\n )\n }\n const omsEndpoint = getOMSEndpoint(accountName)\n const omsUrl = `${omsEndpoint}/pvt/orders/${orderId}/changestate/${\n futureStateChange\n }`\n const headers = {\n 'Proxy-Authorization': authToken,\n 'VtexIdclientAutCookie': authToken,\n 'X-Vtex-Proxy-To': `https://${accountName}.vtexcommercestable.com.br`,\n }\n return fetchHelper(omsUrl, {\n method: 'POST',\n headers,\n retries: 3\n }).catch(e => {\n e.shouldRetry = true\n return Promise.reject(e)\n })\n}\n\n```" } ]
code_order-sms-notification_b63a89d4
[ { "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 order-sms-notification/node/typings.d.ts from the order-sms-notification VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\ndeclare module 'colossus' {\n import {Context as KoaContext} from 'koa'\n \n export interface IOContext {\n account: string\n workspace: string\n authToken: string\n params: {\n [param: string]: string\n }\n region: string\n route: string\n }\n \n export interface ColossusContext extends KoaContext {\n vtex: IOContext\n }\n}\n```" } ]
code_order-sms-notification_39747a28
[ { "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 order-sms-notification/node/package.json from the order-sms-notification VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"name\": \"vtex.order-sms-notification\",\n \"version\": null,\n \"dependencies\": {\n \"@vtex/api\": \"^2.4.0\",\n \"axios\": \"^0.18.0\",\n \"co-body\": \"^6.0.0\",\n \"node-fetch\": \"^2.1.1\",\n \"splunk-events\": \"^1.2.3\"\n },\n \"devDependencies\": {\n \"@types/koa\": \"^2.0.39\",\n \"@types/node\": \"^7.0.8\",\n \"tslint\": \"^5.8.0\",\n \"tslint-config-vtex\": \"^2.0.0\",\n \"typescript\": \"^2.4.2\"\n },\n \"scripts\": {\n \"lint\": \"tsc --noEmit && tslint -c tslint.json './**/*.ts'\"\n }\n}\n\n```" } ]
code_order-sms-notification_c7739b8a
[ { "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 order-sms-notification/node/fetch-helper.ts from the order-sms-notification VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport fetch from 'node-fetch'\nimport { sendLog } from './log-helper'\n\nconst DEFAULT_TIMEOUT = 10000\n\ntype fetchOptions = {\n headers?: object\n body?: any\n timeout?: number\n retries?: number\n method?: string\n}\n\nconst DEFAULT_OPTIONS: fetchOptions = {\n headers: {},\n timeout: null,\n retries: null\n}\n\nclass CustomRequestError extends Error {\n type = 'custom-request-error'\n response = null\n}\n\nfunction fetchWithRetries(url, options, retries) {\n return fetch(url, options)\n .then(response => {\n sendLog(\n `url finished: ${url} ${response.statusText ||\n response.status.toString()} options: ${JSON.stringify(options)}`\n )\n if (response.status >= 400 && response.status < 600) {\n const statusText = response.statusText || response.status.toString()\n const error = new CustomRequestError(`Request Error ${statusText}`)\n error.response = response.json()\n return Promise.reject(error)\n }\n\n const responseCopy = response.clone()\n return responseCopy.json().catch(() => response.text())\n })\n .catch(error => {\n sendLog(`Error on request: ${url}, ${error.type} - ${error.message}`)\n if (error.type === 'request-timeout' && retries > 0) {\n sendLog(`WARNING: Retrying request to ${url} (retry number ${retries})`)\n return fetchWithRetries(url, options, retries - 1)\n }\n if (error.response) {\n return error.response.then(errorData => {\n return Promise.reject({\n ...errorData,\n error\n })\n })\n }\n return Promise.reject(error)\n })\n}\n\nfunction fetchHelper(url, options = DEFAULT_OPTIONS) {\n const fetchOptions = {\n ...options,\n headers: {\n Accept: 'application/json',\n 'Content-Type': 'application/json',\n ...options.headers\n },\n timeout: options.timeout || DEFAULT_TIMEOUT\n }\n const retries = options.retries || 1\n return fetchWithRetries(url, fetchOptions, retries)\n}\n\nexport default fetchHelper\n\n```" } ]
code_order-sms-notification_9189e481
[ { "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 order-sms-notification/node/index.ts from the order-sms-notification VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { Apps } from '@vtex/api'\nimport axios from 'axios'\nimport { json } from 'co-body'\nimport { ColossusContext } from 'colossus'\nimport SplunkEvents from 'splunk-events'\n\nimport { configLog, sendLog } from './log-helper'\nimport { getOrder } from './order-fetcher'\n\nconst FUNCTION_NAME = 'seller_newOrderSMSNotification'\nconst SPLUNK_ENDPOINT = 'splunk-heavyforwarder-public.vtex.com'\nconst splunkEvents = new SplunkEvents()\n\nfunction logEvent(level, type, workflow, event) {\n console.log(`\\n\\n [SPLUNK] - Sending log, level: ${level}, type: ${type}, workflow: ${workflow}, event: ${event.toString()}\\n \\n`)\n try {\n splunkEvents.logEvent(\n level,\n type,\n workflow,\n '-',\n event\n )\n } catch (e) {\n console.log(`\\n\\n [SPLUNK] - Error sending log: ${e.toString()} \\n\\n`)\n }\n}\n\nasync function getMobileNumberFromSettings({ vtex }) {\n const filter = 'vtex.order-sms-notification'\n const apps = new Apps(vtex)\n let phone = ''\n await apps.getAppSettings(filter).then((r) => {\n phone = r.mobilePhone\n return phone\n })\n return phone\n}\n\nfunction postMessageCenterSMS(accountName, ctx, mobileNumber, selectedDeliveryChannel, orderId, openTextField, authToken) {\n logEvent('Important', 'Info', 'post-message-center-sms', {\n account: accountName,\n accountName,\n mobileNumber,\n orderId,\n sourceType: 'KPI',\n step: 'start'\n })\n const payload = getMessageCenterPayload(mobileNumber, selectedDeliveryChannel, orderId, openTextField)\n const url = `http://sms-provider.vtex.aws-us-east-1.vtex.io/${accountName}/${ctx.vtex.workspace}/_v/0/sms`\n console.log('\\n\\n [SMS PROVIDER] - Starting Request to SMS provider API \\n \\n')\n\n return axios({\n data: payload,\n headers: {\n 'Authorization': authToken,\n 'Proxy-Authorization': authToken,\n },\n method: 'post',\n responseType: 'stream',\n url,\n }).then((response) => {\n console.log(`\\n\\n [SMS PROVIDER] - Success calling api. Status: ${response.status} \\n \\n`)\n logEvent('Important', 'Info', 'post-message-center-sms', {\n account: accountName,\n message: 'Success calling sms provider (message center)',\n mobileNumber,\n payloadMessage: payload.messagetext,\n responseStatus: response.status,\n sourceType: 'LOG'\n })\n return response\n }).catch((error) => {\n console.log(`\\n\\n [SMS PROVIDER] - Error calling api. Status: ${error} \\n \\n`)\n logEvent('Critical', 'Error', 'post-message-center-sms', {\n account: accountName,\n error: error.toString(),\n message: 'Error calling sms provider (message center)',\n mobileNumber,\n payloadMessage: payload.messagetext,\n responseStatus: 503,\n sourceType: 'LOG'\n })\n return {\n data: {\n error,\n message: 'Erro na hora de chamar o sms provider (message center)',\n },\n status: 503,\n }\n })\n}\n\nfunction getMessageCenterPayload(mobileNumber, selectedDeliveryChannel, orderId, openTextField) {\n let text = ''\n if (openTextField != null) {\n text = `Novo pedido para sua loja do tipo ${selectedDeliveryChannel}! Pedido - ${orderId} - O vendedor desse cliente: ${openTextField}`\n } else {\n text = `Novo pedido para sua loja do tipo ${selectedDeliveryChannel}! Pedido - ${orderId}`\n }\n return {\n destination: mobileNumber,\n messagetext: text,\n }\n \n}\n\nasync function sendSMS(accountName: string, authToken: string, ctx: ColossusContext) {\n configLog(accountName, FUNCTION_NAME)\n sendLog(\n `Initiating SMS notification for accountName ${accountName}`,\n )\n console.log('\\n\\n [ORDER SMS] - Parsing body... \\n \\n')\n let body\n logEvent('Important', 'Info', 'parse-request-body', {\n account: accountName,\n sourceType: 'KPI',\n step: 'start'\n })\n try {\n body = await json(ctx.req)\n } catch (e) {\n logEvent('Critical', 'Error', 'parse-request-body', {\n account: accountName,\n error: e,\n sourceType: 'LOG',\n })\n return {\n data: {\n error: e.toString(),\n message: 'Error parsing request body',\n },\n status: 500\n }\n }\n console.log(`\\n\\n [ORDER SMS] - Body parsed: \\n workspace: ${ctx.vtex.workspace}\\n body: ${JSON.stringify(body)} \\n orderId: ${body.orderId} \\n accountName: ${body.accountName} \\n \\n`)\n logEvent('Important', 'Info', 'parse-request-body', {\n account: accountName,\n bodyAccountName: body.accountName,\n bodyOrderId: body.orderId,\n sourceType: 'KPI',\n step: 'end'\n })\n\n\n let mobileNumber\n console.log(`\\n\\n [SETTINGS] - getting mobile phone from app settings \\n \\n`)\n logEvent('Important', 'Info', 'get-settings', {\n account: accountName,\n bodyAccountName: body.accountName,\n bodyOrderId: body.orderId,\n sourceType: 'KPI',\n step: 'start'\n })\n try {\n mobileNumber = await getMobileNumberFromSettings(ctx)\n } catch (e) {\n console.log(`\\n\\n [SETTINGS] - Error getting number from settings: \\n Error: ${'' + e} \\n \\n`)\n logEvent('Critical', 'Error', 'get-settings', {\n account: accountName,\n error: e.toString(),\n message: 'Error getting mobile number from app settings (VBASE)... perhaps it is not configured in my-apps settings in myvtex admin...',\n responseStatus: 503,\n sourceType: 'LOG',\n })\n return {\n data: {\n error: e,\n message: 'Error getting mobile number from app settings (vbase)',\n },\n status: 503\n }\n }\n \n if(!mobileNumber) {\n console.log(`\\n\\n [SETTINGS] - Exiting function, no mobile number in app settings. \\n \\n`)\n logEvent('Critical', 'Error', 'get-settings', {\n account: accountName,\n message: 'Mobile number is empty in app settings...',\n responseStatus: 500,\n sourceType: 'LOG',\n })\n return {\n data: {\n error: 'Config error',\n message: 'No mobile number found in app settings...'\n },\n status: 500,\n }\n }\n console.log(`\\n\\n [SETTINGS] - got this mobile number: ${mobileNumber} \\n \\n`)\n logEvent('Important', 'Info', 'get-settings', {\n account: accountName,\n bodyAccountName: body.accountName,\n bodyOrderId: body.orderId,\n mobileNumber,\n sourceType: 'KPI',\n step: 'end'\n })\n \n console.log(`\\n\\n [OMS] - getting order data \\n \\n`)\n logEvent('Important', 'Info', 'get-order-data', {\n account: accountName,\n bodyAccountName: body.accountName,\n bodyOrderId: body.orderId,\n mobileNumber,\n sourceType: 'KPI',\n step: 'start'\n })\n let orderData\n try {\n orderData = await getOrder(body.accountName, body.orderId, authToken)\n } catch (e) {\n logEvent('Critical', 'Error', 'get-order-data', {\n account: accountName,\n error: e.toString(),\n message: 'Error getting order data...',\n mobileNumber,\n responseStatus: 500,\n sourceType: 'LOG',\n })\n return {\n data: {\n error: e.error,\n message: 'Exiting function, error getting order data...'\n },\n status: 503\n }\n }\n console.log(`\\n\\n [OMS] - GOT THIS: ${orderData} \\n \\n`)\n\n if(!orderData) {\n console.log(`\\n\\n [OMS] - Exiting function, order data is empty... \\n \\n`)\n logEvent('Critical', 'Error', 'get-order-data', {\n account: accountName,\n bodyAccountName: body.accountName,\n bodyOrderId: body.orderId,\n message: 'Exiting function, order data is empty...',\n mobileNumber,\n sourceType: 'KPI',\n step: 'end'\n })\n return {\n data: {\n message: 'Exiting function, order data is empty...'\n },\n status: 500\n }\n }\n\n logEvent('Important', 'Info', 'get-order-data', {\n account: accountName,\n bodyAccountName: body.accountName,\n bodyOrderId: body.orderId,\n mobileNumber,\n sourceType: 'KPI',\n step: 'end'\n })\n\n logEvent('Important', 'Info', 'check-order-instore', {\n account: accountName,\n bodyAccountName: body.accountName,\n bodyOrderId: body.orderId,\n mobileNumber,\n sourceType: 'KPI',\n step: 'start'\n })\n\n // valida se é pedido do instore, nesse caso sair da funcao -- ainda precisa fazer o loop dentro do customApps\n if(orderData.customData != null && (orderData.customData.customApps[0].fields['cart-type'] === 'INSTORE' || orderData.customData[0].fields[0]['cart-type'] === 'INSTORE_DELIVERY')){\n console.log(`\\n\\n [MASTER DATA] - Exiting function, order is NOT inStore... \\n \\n`)\n logEvent('Important', 'Info', 'check-order-instore', {\n account: accountName,\n bodyAccountName: body.accountName,\n bodyOrderId: body.orderId,\n message: 'Exiting function, order is inStore so message was not sent...',\n mobileNumber,\n responseStatus: 204,\n sourceType: 'KPI',\n step: 'end'\n })\n return {\n data: {\n message: 'Exiting function, order is NOT inStore so message was not sent...'\n },\n status: 204 // returns 2xx so masterdata doesn't retry, since it's pointless\n }\n }\n console.log(`\\n\\n [MASTER DATA] - order ${orderData.orderId} is inStore:\\n SLA: ${orderData.shippingData.logisticsInfo[0].deliveryChannel} \\n Custom data: ${orderData.customData} \\n \\n`)\n\n console.log(`\\n\\n [MASTER DATA] - parsing order data... \\n \\n`)\n const deliveryChannel = orderData.shippingData ? orderData.shippingData.logisticsInfo[0].deliveryChannel : null\n const openTextField = orderData.openTextField ? orderData.openTextField.value : null\n console.log(`\\n\\n [MASTER DATA] -> pedido - ${orderData.orderId} - tipo de entrega: ${deliveryChannel} - observação: ${openTextField} \\n \\n`)\n console.log(`\\n\\n [MESSAGE CENTER] - calling function postMessageCenterSMS... \\n \\n`)\n logEvent('Important', 'Info', 'check-order-instore', {\n account: accountName,\n bodyAccountName: body.accountName,\n bodyOrderId: body.orderId,\n message: 'Order is NOT instore so SMS was sent',\n mobileNumber,\n sourceType: 'KPI',\n step: 'end'\n })\n const response = await postMessageCenterSMS(body.accountName, ctx, mobileNumber, deliveryChannel, orderData.orderId, openTextField, authToken)\n console.log(`\\n\\n [MESSAGE CENTER] - FINISHED CALLING MESSAGE CENTER, RETURNING THIS RESPONSE: \\n ctx.response.status: ${response.status} \\n ctx.response.body:\\n`)\n logEvent('Important', 'Info', 'post-message-center-sms', {\n account: accountName,\n bodyAccountName: body.accountName,\n mobileNumber,\n orderId: body.orderId,\n responseStatus: response.status,\n sourceType: 'KPI',\n step: 'end'\n })\n console.log(response.data)\n console.log('\\n')\n return response\n}\n\nexport default {\n routes: {\n sms: async (ctx: ColossusContext) => {\n // fetcher to log events to splunk depends on colossus context\n function splunkCustomFetcher(context) {\n const headers = context.headers || {}\n return axios({\n ...context,\n headers: {\n ...headers,\n 'Proxy-Authorization': ctx.vtex.authToken,\n 'X-Vtex-Proxy-To': `https://${SPLUNK_ENDPOINT}:8088`,\n }\n })\n }\n console.log('\\n\\n [ORDER SMS] - Just received a request! Configuring splunk to start... \\n \\n')\n splunkEvents.config({\n debug: true,\n endpoint: `http://${SPLUNK_ENDPOINT}`,\n request: splunkCustomFetcher,\n token: '473bad07-24e0-4c46-964e-d6f059ec8789',\n })\n console.log('\\n\\n [ORDER SMS] - Splunk configured, let\\'s start \\n \\n')\n let { vtex: { account, authToken } } = ctx\n authToken = ctx.vtex.authToken\n ctx.set('Cache-Control', 'no-cache')\n logEvent('Important', 'Info', 'request-received', {\n account,\n sourceType: 'KPI',\n })\n const res = await sendSMS(account, authToken, ctx)\n logEvent('Important', 'Info', 'request-responded', {\n account,\n reponseError: res.data.message || 'There was no error in response data...',\n reponseMessage: res.data.message || 'There was no message in response data...',\n responseStatus: res.status || 'There was no status in reponse data...',\n sourceType: 'KPI',\n })\n ctx.response.status = res.status\n ctx.response.body = res.data\n }\n },\n}\n\n\n\n\n```" } ]
code_sponsored-banners_a04d8458
[ { "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 sponsored-banners/messages/sl.json from the sponsored-banners VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"store/sponsored-banner\": \"Sponzorirana pasica\",\n \"admin/editor.ad-unit\": \"Dimenzije\",\n \"admin/editor.show-banner\": \"Prikaži pasico\"\n}\n```" } ]
code_sponsored-banners_c1958227
[ { "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 sponsored-banners/messages/hu.json from the sponsored-banners VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"store/sponsored-banner\": \"Szponzorált szalaghirdetés\",\n \"admin/editor.ad-unit\": \"Méretek\",\n \"admin/editor.show-banner\": \"Szalaghirdetés megjelenítése\"\n}\n```" } ]
code_sponsored-banners_ad6871d3
[ { "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 sponsored-banners/messages/nl.json from the sponsored-banners VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"store/sponsored-banner\": \"Gesponsorde banner\",\n \"admin/editor.ad-unit\": \"Afmetingen\",\n \"admin/editor.show-banner\": \"Banner weergeven\"\n}\n```" } ]
code_sponsored-banners_977f0165
[ { "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 sponsored-banners/messages/ja.json from the sponsored-banners VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"store/sponsored-banner\": \"スポンサー付きバナー\",\n \"admin/editor.ad-unit\": \"寸法\",\n \"admin/editor.show-banner\": \"バナーを表示\"\n}\n```" } ]
code_sponsored-banners_b143d093
[ { "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 sponsored-banners/messages/de.json from the sponsored-banners VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"store/sponsored-banner\": \"Gesponsertes Banner\",\n \"admin/editor.ad-unit\": \"Abmessungen\",\n \"admin/editor.show-banner\": \"Banner anzeigen\"\n}\n```" } ]
code_sponsored-banners_4f9f9492
[ { "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 sponsored-banners/messages/ru.json from the sponsored-banners VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"store/sponsored-banner\": \"Рекламный баннер\",\n \"admin/editor.ad-unit\": \"Размеры\",\n \"admin/editor.show-banner\": \"Показать баннер\"\n}\n```" } ]
code_sponsored-banners_b6cbd563
[ { "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 sponsored-banners/messages/pl.json from the sponsored-banners VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"store/sponsored-banner\": \"Baner sponsorowany\",\n \"admin/editor.ad-unit\": \"Wymiary\",\n \"admin/editor.show-banner\": \"Pokaż baner\"\n}\n```" } ]
code_sponsored-banners_6b24dfb6
[ { "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 sponsored-banners/messages/uk.json from the sponsored-banners VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"store/sponsored-banner\": \"Рекламний банер\",\n \"admin/editor.ad-unit\": \"Розміри\",\n \"admin/editor.show-banner\": \"Показати банер\"\n}\n```" } ]
code_sponsored-banners_b70c4387
[ { "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 sponsored-banners/messages/fi.json from the sponsored-banners VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"store/sponsored-banner\": \"Sponsoroitu banneri\",\n \"admin/editor.ad-unit\": \"Mitat\",\n \"admin/editor.show-banner\": \"Näytä banneri\"\n}\n```" } ]
code_sponsored-banners_13b3ddb4
[ { "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 sponsored-banners/messages/sk.json from the sponsored-banners VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"store/sponsored-banner\": \"Sponzorovaný banner\",\n \"admin/editor.ad-unit\": \"Rozmery\",\n \"admin/editor.show-banner\": \"Zobraziť banner\"\n}\n```" } ]
code_sponsored-banners_baaa2187
[ { "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 sponsored-banners/messages/pt.json from the sponsored-banners VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"store/sponsored-banner\": \"Banner patrocinado\",\n \"admin/editor.ad-unit\": \"Dimensões\",\n \"admin/editor.show-banner\": \"Exibir banner\"\n}\n```" } ]
code_sponsored-banners_c4ca2426
[ { "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 sponsored-banners/messages/en.json from the sponsored-banners VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"store/sponsored-banner\": \"Sponsored banner\",\n \"admin/editor.ad-unit\": \"Dimensions\",\n \"admin/editor.show-banner\": \"Show banner\"\n}\n\n```" } ]
code_sponsored-banners_23c1cc5e
[ { "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 sponsored-banners/messages/it.json from the sponsored-banners VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"store/sponsored-banner\": \"Banner sponsorizzato\",\n \"admin/editor.ad-unit\": \"Dimensioni\",\n \"admin/editor.show-banner\": \"Mostra banner\"\n}\n```" } ]
code_sponsored-banners_81b36cdf
[ { "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 sponsored-banners/messages/fr.json from the sponsored-banners VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"store/sponsored-banner\": \"Bannière sponsorisée\",\n \"admin/editor.ad-unit\": \"Dimensions\",\n \"admin/editor.show-banner\": \"Afficher la bannière\"\n}\n```" } ]
code_sponsored-banners_7f796856
[ { "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 sponsored-banners/messages/el.json from the sponsored-banners VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"store/sponsored-banner\": \"Χορηγούμενο μπάνερ\",\n \"admin/editor.ad-unit\": \"Διαστάσεις\",\n \"admin/editor.show-banner\": \"Εμφάνιση μπάνερ\"\n}\n```" } ]
code_sponsored-banners_64b026ca
[ { "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 sponsored-banners/messages/bg.json from the sponsored-banners VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"store/sponsored-banner\": \"Спонсориран банер\",\n \"admin/editor.ad-unit\": \"Размери\",\n \"admin/editor.show-banner\": \"Показване на банер\"\n}\n```" } ]
code_sponsored-banners_79a531fe
[ { "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 sponsored-banners/messages/ro.json from the sponsored-banners VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"store/sponsored-banner\": \"Banner sponsorizat\",\n \"admin/editor.ad-unit\": \"Dimensiuni\",\n \"admin/editor.show-banner\": \"Afișare banner\"\n}\n```" } ]
code_sponsored-banners_33a5388f
[ { "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 sponsored-banners/messages/ca.json from the sponsored-banners VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"store/sponsored-banner\": \"Bàner patrocinat\",\n \"admin/editor.ad-unit\": \"Dimensions\",\n \"admin/editor.show-banner\": \"Mostra el bàner\"\n}\n```" } ]
code_sponsored-banners_b887dbd2
[ { "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 sponsored-banners/messages/ko.json from the sponsored-banners VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"store/sponsored-banner\": \"스폰서 배너\",\n \"admin/editor.ad-unit\": \"치수\",\n \"admin/editor.show-banner\": \"배너 표시\"\n}\n```" } ]
code_sponsored-banners_ea20395c
[ { "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 sponsored-banners/messages/cs.json from the sponsored-banners VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"store/sponsored-banner\": \"Sponzorovaný banner\",\n \"admin/editor.ad-unit\": \"Rozměry\",\n \"admin/editor.show-banner\": \"Zobrazit banner\"\n}\n```" } ]
code_sponsored-banners_b9e5e50b
[ { "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 sponsored-banners/messages/id.json from the sponsored-banners VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"store/sponsored-banner\": \"Spanduk bersponsor\",\n \"admin/editor.ad-unit\": \"Dimensi\",\n \"admin/editor.show-banner\": \"Tampilkan spanduk\"\n}\n```" } ]
code_sponsored-banners_4776dbe1
[ { "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 sponsored-banners/messages/no.json from the sponsored-banners VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"store/sponsored-banner\": \"Sponset banner\",\n \"admin/editor.ad-unit\": \"Dimensjoner\",\n \"admin/editor.show-banner\": \"Vis banner\"\n}\n```" } ]
code_sponsored-banners_8641e4cb
[ { "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 sponsored-banners/messages/da.json from the sponsored-banners VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"store/sponsored-banner\": \"Sponsoreret banner\",\n \"admin/editor.ad-unit\": \"Dimensioner\",\n \"admin/editor.show-banner\": \"Vis banner\"\n}\n```" } ]
code_sponsored-banners_e76fca3e
[ { "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 sponsored-banners/messages/th.json from the sponsored-banners VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"store/sponsored-banner\": \"แบนเนอร์ที่สนับสนุน\",\n \"admin/editor.ad-unit\": \"ขนาด\",\n \"admin/editor.show-banner\": \"แสดงแบนเนอร์\"\n}\n```" } ]
code_sponsored-banners_fb72ae92
[ { "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 sponsored-banners/messages/sv.json from the sponsored-banners VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"store/sponsored-banner\": \"Sponsrad banner\",\n \"admin/editor.ad-unit\": \"Mått\",\n \"admin/editor.show-banner\": \"Visa banner\"\n}\n```" } ]
code_sponsored-banners_5493f73a
[ { "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 sponsored-banners/messages/es.json from the sponsored-banners VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"store/sponsored-banner\": \"Banner patrocinado\",\n \"admin/editor.ad-unit\": \"Dimensiones\",\n \"admin/editor.show-banner\": \"Mostrar banner\"\n}\n\n```" } ]
code_sponsored-banners_c865c244
[ { "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 sponsored-banners/messages/ar.json from the sponsored-banners VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"store/sponsored-banner\": \"لافتة دعائية\",\n \"admin/editor.ad-unit\": \"الأبعاد\",\n \"admin/editor.show-banner\": \"عرض اللافتة\"\n}\n```" } ]
code_sponsored-banners_8a2500dc
[ { "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 sponsored-banners/docs/README.md from the sponsored-banners VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```markdown\n📢 Use this project, [contribute](https://github.com/{OrganizationName}/{AppName}) to it or open issues to help evolve it using [Store Discussion](https://github.com/vtex-apps/store-discussion).\n\n# Sponsored Banners\n\n<!-- DOCS-IGNORE:start -->\n<!-- ALL-CONTRIBUTORS-BADGE:START - Do not remove or modify this section -->\n\n[![All Contributors](https://img.shields.io/badge/all_contributors-0-orange.svg?style=flat-square)](#contributors-)\n\n<!-- ALL-CONTRIBUTORS-BADGE:END -->\n<!-- DOCS-IGNORE:end -->\n\nVTEX Sponsored Banners is responsible for implementing the necessary frontend apps to properly render the sponsored banner.\n\nThis component will request the sponsored banners available for publisher that's implementing it and render it on screen. This component already add the Analytics data.\n\n![alt text](banner-example.png)\n\n## Configuration\n\n### Step 1: Adding the Sponsored Products app to your theme's dependency\n\nIn your theme's `manifest.json`, add the Sponsored Banners app as a dependency:\n\n```json\n \"dependencies\": {\n \"vtex.sponsored-banners\": \"0.x\"\n }\n```\n\nNow, you are able to use all the blocks exported by the `sponsored-banners` app. Check out the full list below:\n\n#### `sponsored-banners` blocks\n\n| Block name | Description |\n| ------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| `sponsored-banners` | Renders the Banner on Screen. You can customize its CSS however fits best your store. Already contains analytics data to observe impression and click metrics to assess the performance of the campaigns |\n\n### Step 2: Using the Sponsored Banners blocks\n\n#### The sponsored banner\n\nThis is fairly straightforward: simply call it as a child block on your Home. For example:\n\n```diff\n\"disposition-layout#home\": {\n \"children\": [\n \"flex-layout.row#component-options-home\",\n \"flex-layout.row#component-benefits-home\",\n+ \"sponsored-banners\",\n \"flex-layout.row#home-tab-layout-shelf-01\",\n \"flex-layout.row#component-shelfbanner-home-02\",\n ]\n},\n```\n\n## Blocks\n\n### `sponsored-banners`\n\n| Prop name | Type | Description | Default value |\n| --------- | -------- | ------------------ | ---------------------------- |\n| `adUnit` | `string` | Banner dimensions. | `billboard` or `970 x 250px` |\n\n## Customization\n\nIn order to apply CSS customizations in this and other blocks, follow the instructions given in the recipe on [Using CSS Handles for store customization](https://vtex.io/docs/recipes/style/using-css-handles-for-store-customization).\n\n| CSS Handles |\n| --------------- |\n| `bannerWrapper` |\n| `bannerImage` |\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---\n\nCheck out some documentation models that are already live:\n\n- [Breadcrumb](https://github.com/vtex-apps/breadcrumb)\n- [Image](https://vtex.io/docs/components/general/vtex.store-components/image)\n- [Condition Layout](https://vtex.io/docs/components/all/vtex.condition-layout@1.1.6/)\n- [Add To Cart Button](https://vtex.io/docs/components/content-blocks/vtex.add-to-cart-button@0.9.0/)\n- [Store Form](https://vtex.io/docs/components/all/vtex.store-form@0.3.4/)\n\n```" } ]
code_sponsored-banners_094c31d2
[ { "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 sponsored-banners/react/SponsoredBanner.tsx from the sponsored-banners VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport { SponsoredBanner } from './components/SponsoredBanner'\n\nexport default SponsoredBanner\n\n```" } ]
code_sponsored-banners_d1596d77
[ { "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 sponsored-banners/react/messages.ts from the sponsored-banners VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { defineMessages } from 'react-intl'\n\nconst messages = defineMessages({\n sponsoredBanner: { id: 'store/sponsored-banner' },\n editorAdUnit: { id: 'admin/editor.ad-unit' },\n showBanner: { id: 'admin/editor.show-banner' },\n})\n\nexport default messages\n\n```" } ]
code_sponsored-banners_eb0fe5ba
[ { "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 sponsored-banners/react/babel.config.js from the sponsored-banners VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```javascript\nmodule.exports = {\n presets: [\n '@babel/preset-env',\n ['@babel/preset-react', { runtime: 'automatic' }],\n '@babel/preset-typescript',\n ],\n}\n\n```" } ]
code_sponsored-banners_f315dd91
[ { "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 sponsored-banners/react/package.json from the sponsored-banners VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"name\": \"sponsored-banners\",\n \"version\": \"0.0.6\",\n \"scripts\": {\n \"test\": \"vtex-test-tools test\"\n },\n \"jest\": {\n \"testEnvironment\": \"jsdom\"\n },\n \"dependencies\": {\n \"apollo-client\": \"^2.6.8\",\n \"react\": \"^16.12.0\",\n \"react-apollo\": \"^3.1.3\",\n \"react-dom\": \"^16.12.0\",\n \"react-intl\": \"^3.12.0\",\n \"vtex.styleguide\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.styleguide@9.146.9/public/@types/vtex.styleguide\",\n \"vtex.adserver-graphql\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.adserver-graphql@0.3.1/public/@types/vtex.adserver-graphql\"\n },\n \"devDependencies\": {\n \"@apollo/react-testing\": \"^3.1.3\",\n \"@babel/core\": \"^7.23.0\",\n \"@babel/preset-env\": \"^7.22.20\",\n \"@babel/preset-react\": \"^7.22.15\",\n \"@babel/preset-typescript\": \"^7.23.0\",\n \"@types/node\": \"^13.9.8\",\n \"@types/react\": \"^16.9.31\",\n \"@vtex/test-tools\": \"^3.3.2\",\n \"@vtex/tsconfig\": \"^0.4.4\",\n \"apollo-cache-inmemory\": \"^1.6.5\",\n \"babel-jest\": \"^29.7.0\",\n \"graphql\": \"^14.6.0\",\n \"jest\": \"^26.0.0\",\n \"jest-environment-jsdom\": \"^26.0.0\",\n \"ts-jest\": \"^29.1.1\",\n \"typescript\": \"3.9.7\"\n },\n \"resolutions\": {\n \"@types/jest\": \"26.0.15\"\n }\n}\n\n```" } ]
code_sponsored-banners_9127411b
[ { "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 sponsored-banners/store/interfaces.json from the sponsored-banners VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"sponsored-banners\": {\n \"component\": \"SponsoredBanner\"\n }\n}\n```" } ]
code_sponsored-banners_a80131ea
[ { "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 sponsored-banners/react/typings/vtex.css-handles.d.ts from the sponsored-banners VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\ndeclare module 'vtex.css-handles' {\n export const useCssHandles\n}\n\n```" } ]
code_sponsored-banners_6c450b30
[ { "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 sponsored-banners/react/typings/gql.d.ts from the sponsored-banners VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\ndeclare module '*.gql' {\n import { DocumentNode } from 'graphql'\n\n const Schema: DocumentNode\n\n export default Schema\n}\n\ndeclare module '*.graphql' {\n import { DocumentNode } from 'graphql'\n\n const schema: DocumentNode\n\n export default schema\n}\n\n```" } ]
code_sponsored-banners_1ff8d462
[ { "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 sponsored-banners/react/typings/vtex.device-detector.d.ts from the sponsored-banners VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\ndeclare module 'vtex.device-detector' {\n export const useDevice\n}\n\n```" } ]
code_sponsored-banners_b709ac46
[ { "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 sponsored-banners/react/typings/css.d.ts from the sponsored-banners VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\ndeclare module '*.css' {\n type Styles = {\n [selector: string]: string\n }\n\n const styles: Styles\n\n export default styles\n}\n\n```" } ]
code_sponsored-banners_a5473d82
[ { "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 sponsored-banners/react/typings/vtex.styleguide.d.ts from the sponsored-banners VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\ndeclare module 'vtex.styleguide' {\n export const Spinner\n}\n\n```" } ]
code_sponsored-banners_028aa57d
[ { "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 sponsored-banners/react/utils/getDataProperties.ts from the sponsored-banners VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport type { DataProperties, SponsoredBanner } from '../interfaces'\n\nexport function getDataProperties(banner: SponsoredBanner): DataProperties {\n const { adResponseId, advertisement } = banner\n const { bannerImageId } = advertisement\n\n return {\n 'data-van-aid': bannerImageId,\n 'data-van-banner-imageid': bannerImageId,\n 'data-van-res-id': adResponseId,\n }\n}\n\n```" } ]
code_sponsored-banners_6a685119
[ { "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 sponsored-banners/react/query/sponsoredBanners.gql from the sponsored-banners VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```graphql\nquery sponsoredBanners(\n $sponsoredCount: Int\n $placement: Placement\n $adUnit: AdUnit\n $channel: Channel\n $anonymousId: String\n) {\n sponsoredBanners(\n sponsoredCount: $sponsoredCount\n placement: $placement\n adUnit: $adUnit\n channel: $channel\n anonymousId: $anonymousId\n ) @context(provider: \"vtex.adserver-graphql\") {\n adResponseId\n advertisement {\n bannerImageId\n imageUrl\n targetUrl\n width\n height\n }\n }\n}\n\n```" } ]
code_sponsored-banners_28494f60
[ { "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 sponsored-banners/react/query/index.ts from the sponsored-banners VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport QuerySponsoredBanners from './sponsoredBanners.gql'\n\nexport default QuerySponsoredBanners\n\n```" } ]
code_sponsored-banners_1a001a69
[ { "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 sponsored-banners/react/interfaces/adsAnalytics.ts from the sponsored-banners VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nexport type DataProperties = {\n 'data-van-aid': string\n 'data-van-banner-imageid': string\n 'data-van-res-id': string\n}\n\n```" } ]
code_sponsored-banners_3401f33d
[ { "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 sponsored-banners/react/interfaces/index.ts from the sponsored-banners VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nexport * from './sponsoredBannersData'\nexport * from './sponsoredBannersProps'\nexport * from './adsAnalytics'\n\n```" } ]
code_sponsored-banners_e6417503
[ { "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 sponsored-banners/react/interfaces/sponsoredBannersData.ts from the sponsored-banners VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\ninterface Advertisement {\n bannerImageId: string\n imageUrl: string\n targetUrl: string\n width: number\n height: number\n}\n\nexport interface SponsoredBanner {\n adResponseId: string\n advertisement: Advertisement\n}\n\nexport interface SponsoredBannersData {\n sponsoredBanners: SponsoredBanner[]\n}\n\n```" } ]
code_sponsored-banners_421fa247
[ { "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 sponsored-banners/react/interfaces/sponsoredBannersProps.ts from the sponsored-banners VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\ntype AdUnit = 'billboard'\n\ntype Placement = 'homepage'\n\ntype Channel = 'website' | 'android' | 'ios' | 'msite' | 'whatsapp'\n\nexport interface SponsoredBannersProps {\n adUnit: AdUnit\n placement?: Placement\n channel?: Channel\n showBanner?: boolean\n}\n\n```" } ]
code_sponsored-banners_9f77c77b
[ { "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 sponsored-banners/react/utils/__test__/getDataProperties.test.tsx from the sponsored-banners VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport { getDataProperties } from '../getDataProperties'\n\ndescribe('getDataProperties', () => {\n const response = getDataProperties({\n adResponseId: '123',\n advertisement: {\n bannerImageId: '1',\n imageUrl: 'www.image.com.br',\n targetUrl: 'www.target.com.br',\n width: 970,\n height: 250,\n },\n })\n\n it('should return the correct data properties', () => {\n expect(response).toEqual({\n 'data-van-aid': '1',\n 'data-van-banner-imageid': '1',\n 'data-van-res-id': '123',\n })\n })\n})\n\n```" } ]
code_sponsored-banners_a460e47f
[ { "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 sponsored-banners/react/components/SponsoredBanner/SponsoredBanner.tsx from the sponsored-banners 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'\n\nimport { useSponsoredBanner } from './useSponsoredBanner'\nimport { getDataProperties } from '../../utils'\nimport type { SponsoredBannersProps } from '../../interfaces'\n\nconst CSS_HANDLES = ['bannerWrapper', 'bannerImage'] as const\n\nexport const SponsoredBanner = (props: SponsoredBannersProps) => {\n const handles = useCssHandles(CSS_HANDLES)\n const { sponsoredBanners, error, loading, styleProps, imageAlt } =\n useSponsoredBanner(props)\n\n if (\n !props.showBanner ||\n !!error ||\n !sponsoredBanners ||\n sponsoredBanners.length === 0\n ) {\n return null\n }\n\n const banner = sponsoredBanners[0]\n const dataProperties = getDataProperties(banner)\n\n return (\n <div\n {...dataProperties}\n data-testid=\"banner\"\n className={`${handles.bannerWrapper} flex justify-center items-center`}\n style={{\n maxWidth: banner.advertisement.width,\n height: 'auto',\n aspectRatio: `${styleProps.ratio}`,\n margin: '0 auto',\n }}\n >\n {loading ? (\n <Spinner size={styleProps.spinnerSize} />\n ) : (\n <a\n href={banner.advertisement.targetUrl}\n style={{\n padding: 0,\n border: 'none',\n background: 'none',\n cursor: 'pointer',\n }}\n >\n <img\n className={handles.bannerImage}\n src={banner.advertisement.imageUrl}\n alt={imageAlt}\n style={{\n width: banner.advertisement.width,\n height: 'auto',\n aspectRatio: `${styleProps.ratio}`,\n }}\n />\n </a>\n )}\n </div>\n )\n}\n\nSponsoredBanner.defaultProps = {\n adUnit: 'billboard',\n showBanner: true,\n}\n\nSponsoredBanner.schema = {\n title: 'store/sponsored-banner',\n type: 'object',\n properties: {\n adUnit: {\n type: 'string',\n title: 'admin/editor.ad-unit',\n default: 'billboard',\n enum: ['billboard'],\n enumNames: ['970px x 250px'],\n },\n showBanner: {\n type: 'boolean',\n title: 'admin/editor.show-banner',\n default: true,\n },\n },\n}\n\n```" } ]
code_sponsored-banners_a3397a59
[ { "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 sponsored-banners/react/components/SponsoredBanner/useSponsoredBanner.ts from the sponsored-banners VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { useQuery } from 'react-apollo'\nimport { useIntl } from 'react-intl'\nimport { useDevice } from 'vtex.device-detector'\n\nimport sponsoredBannersQuery from '../../query'\nimport messages from '../../messages'\nimport type {\n SponsoredBannersData,\n SponsoredBannersProps,\n} from '../../interfaces'\n\nconst SPONSORED_COUNT = 1\n\nexport function useSponsoredBanner({\n adUnit,\n placement = 'homepage',\n channel = 'website',\n}: SponsoredBannersProps) {\n const { formatMessage } = useIntl()\n const { device } = useDevice()\n const isDesktop = device === 'desktop'\n\n const { data, loading, error } = useQuery<SponsoredBannersData>(\n sponsoredBannersQuery,\n {\n variables: {\n sponsoredCount: SPONSORED_COUNT,\n placement,\n adUnit,\n channel,\n },\n }\n )\n\n const imageAlt = formatMessage(messages.sponsoredBanner)\n\n const styleProps = {\n spinnerSize: isDesktop ? 40 : 20,\n ratio:\n data && data.sponsoredBanners.length > 0\n ? data.sponsoredBanners[0].advertisement.width /\n data.sponsoredBanners[0].advertisement.height\n : 0,\n }\n\n return {\n sponsoredBanners: data?.sponsoredBanners ?? [],\n loading,\n error,\n styleProps,\n imageAlt,\n }\n}\n\n```" } ]
code_sponsored-banners_a15e80f7
[ { "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 sponsored-banners/react/components/SponsoredBanner/__test__/useSponsoredBanner.test.ts from the sponsored-banners VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { useQuery } from 'react-apollo'\nimport { renderHook } from '@vtex/test-tools/react'\nimport { useDevice } from 'vtex.device-detector'\n\nimport { mockData, mockProps } from './mocks'\nimport { useSponsoredBanner } from '../useSponsoredBanner'\n\njest.mock('react-apollo', () => ({\n useQuery: jest.fn(),\n}))\n\njest.mock('react-intl', () => ({\n defineMessages: jest.fn().mockImplementation(() => ({\n sponsoredBanner: 'sponsoredBanner',\n })),\n useIntl: jest.fn().mockReturnValue({\n formatMessage: jest.fn().mockImplementation((text) => text),\n }),\n}))\n\njest.mock('vtex.device-detector', () => ({\n useDevice: jest.fn(),\n}))\n\njest.mock('../../../query', () => ({\n sponsoredBannersQuery: jest.fn(),\n}))\n\ndescribe('useSponsoredBanner hook', () => {\n describe('when it has data without error', () => {\n beforeEach(() => {\n ;(useQuery as jest.Mock).mockReturnValue({\n data: mockData,\n loading: false,\n error: null,\n })\n ;(useDevice as jest.Mock).mockReturnValue({ device: 'desktop' })\n })\n\n it('should return correct values', () => {\n const { result } = renderHook(() => useSponsoredBanner(mockProps))\n\n expect(result.current.loading).toBe(false)\n expect(result.current.error).toBeNull()\n expect(result.current.imageAlt).toBe('sponsoredBanner')\n\n expect(result.current.styleProps).toEqual({\n spinnerSize: 40,\n ratio: 3.88,\n })\n\n expect(result.current.sponsoredBanners).toEqual([\n {\n adResponseId: '123',\n advertisement: {\n bannerImageId: '1',\n imageUrl: 'www.image.com.br',\n targetUrl: 'www.target.com.br',\n width: 970,\n height: 250,\n },\n },\n ])\n })\n\n it('should return correct values for mobile', () => {\n ;(useDevice as jest.Mock).mockReturnValueOnce({ device: 'mobile' })\n\n const { result } = renderHook(() => useSponsoredBanner(mockProps))\n\n expect(result.current.styleProps).toEqual({\n spinnerSize: 20,\n ratio: 3.88,\n })\n })\n })\n\n describe('when it has error', () => {\n beforeEach(() => {\n ;(useQuery as jest.Mock).mockReturnValue({\n data: null,\n loading: false,\n error: 'error',\n })\n })\n\n it('should return correct values', () => {\n const { result } = renderHook(() => useSponsoredBanner(mockProps))\n\n expect(result.current.loading).toBe(false)\n expect(result.current.error).toBe('error')\n expect(result.current.imageAlt).toBe('sponsoredBanner')\n\n expect(result.current.styleProps).toEqual({\n spinnerSize: 40,\n ratio: 0,\n })\n\n expect(result.current.sponsoredBanners).toEqual([])\n })\n })\n\n describe('when it has no data', () => {\n beforeEach(() => {\n ;(useQuery as jest.Mock).mockReturnValue({\n data: null,\n loading: false,\n error: null,\n })\n })\n\n it('should return correct values', () => {\n const { result } = renderHook(() => useSponsoredBanner(mockProps))\n\n expect(result.current.loading).toBe(false)\n expect(result.current.error).toBeNull()\n expect(result.current.imageAlt).toBe('sponsoredBanner')\n\n expect(result.current.styleProps).toEqual({\n spinnerSize: 40,\n ratio: 0,\n })\n\n expect(result.current.sponsoredBanners).toEqual([])\n })\n })\n\n describe('when it has no data in the array', () => {\n beforeEach(() => {\n ;(useQuery as jest.Mock).mockReturnValue({\n data: { sponsoredBanners: [] },\n loading: false,\n error: null,\n })\n })\n\n it('should return correct values', () => {\n const { result } = renderHook(() => useSponsoredBanner(mockProps))\n\n expect(result.current.loading).toBe(false)\n expect(result.current.error).toBeNull()\n expect(result.current.imageAlt).toBe('sponsoredBanner')\n\n expect(result.current.styleProps).toEqual({\n spinnerSize: 40,\n ratio: 0,\n })\n\n expect(result.current.sponsoredBanners).toEqual([])\n })\n })\n\n describe('when loading is true and it has no data', () => {\n beforeEach(() => {\n ;(useQuery as jest.Mock).mockReturnValue({\n data: null,\n loading: true,\n error: null,\n })\n })\n\n it('should return correct values', () => {\n const { result } = renderHook(() => useSponsoredBanner(mockProps))\n\n expect(result.current.loading).toBe(true)\n expect(result.current.error).toBeNull()\n expect(result.current.imageAlt).toBe('sponsoredBanner')\n\n expect(result.current.styleProps).toEqual({\n spinnerSize: 40,\n ratio: 0,\n })\n\n expect(result.current.sponsoredBanners).toEqual([])\n })\n })\n\n describe('when loading is true and it has ]] data', () => {\n beforeEach(() => {\n ;(useQuery as jest.Mock).mockReturnValue({\n data: mockData,\n loading: true,\n error: null,\n })\n })\n\n it('should return correct values', () => {\n const { result } = renderHook(() => useSponsoredBanner(mockProps))\n\n expect(result.current.loading).toBe(true)\n expect(result.current.error).toBeNull()\n expect(result.current.imageAlt).toBe('sponsoredBanner')\n\n expect(result.current.styleProps).toEqual({\n spinnerSize: 40,\n ratio: 3.88,\n })\n\n expect(result.current.sponsoredBanners).toEqual([\n {\n adResponseId: '123',\n advertisement: {\n bannerImageId: '1',\n imageUrl: 'www.image.com.br',\n targetUrl: 'www.target.com.br',\n width: 970,\n height: 250,\n },\n },\n ])\n })\n })\n})\n\n```" } ]
code_sponsored-banners_e59fd47c
[ { "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 sponsored-banners/react/components/SponsoredBanner/__test__/SponsoredBanner.test.tsx from the sponsored-banners VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport '@testing-library/jest-dom'\nimport React from 'react'\nimport { render } from '@vtex/test-tools/react'\n\nimport { SponsoredBanner } from '../SponsoredBanner'\nimport { useSponsoredBanner } from '../useSponsoredBanner'\nimport { mockData } from './mocks'\n\njest.mock('../useSponsoredBanner', () => ({\n useSponsoredBanner: jest.fn(),\n}))\n\ndescribe('SponsoredBanner component', () => {\n describe('when there are banners available', () => {\n beforeEach(() => {\n ;(useSponsoredBanner as jest.Mock).mockReturnValue({\n sponsoredBanners: mockData.sponsoredBanners,\n imageAlt: 'Alt da imagem',\n loading: false,\n error: null,\n styleProps: {\n spinnerSize: 40,\n ratio: 3,\n },\n })\n })\n\n it('renders the sponsored banners image', () => {\n const { getByAltText, getByTestId } = render(<SponsoredBanner />)\n const banner = getByTestId('banner')\n const image = getByAltText('Alt da imagem')\n\n expect(banner).toBeInTheDocument()\n expect(image).toBeInTheDocument()\n expect(image).toHaveAttribute('src', 'www.image.com.br')\n })\n\n it('render href correctly', () => {\n const { getByAltText } = render(<SponsoredBanner />)\n const image = getByAltText('Alt da imagem')\n\n expect(image.parentElement).toHaveAttribute('href', 'www.target.com.br')\n })\n\n it('render width and ratio correctly correctly', () => {\n const { getByTestId, getByAltText } = render(<SponsoredBanner />)\n\n const banner = getByTestId('banner')\n const image = getByAltText('Alt da imagem')\n\n expect(banner.style.maxWidth).toBe('970px')\n expect(banner.style.aspectRatio).toBe('3')\n expect(image.style.width).toBe('970px')\n expect(image.style.aspectRatio).toBe('3')\n })\n\n it('render data analytics correctly', () => {\n const { getByTestId } = render(<SponsoredBanner />)\n const banner = getByTestId('banner')\n\n expect(banner).toHaveAttribute('data-van-aid', '1')\n expect(banner).toHaveAttribute('data-van-banner-imageid', '1')\n expect(banner).toHaveAttribute('data-van-res-id', '123')\n })\n })\n\n describe('when loading is true', () => {\n beforeEach(() => {\n ;(useSponsoredBanner as jest.Mock).mockReturnValue({\n sponsoredBanners: mockData.sponsoredBanners,\n imageAlt: 'Alt da imagem',\n loading: true,\n error: null,\n styleProps: {\n spinnerSize: 40,\n ratio: 3,\n },\n })\n })\n\n it('render the banner, but does not render the image', () => {\n const { queryByAltText, queryByTestId } = render(<SponsoredBanner />)\n const banner = queryByTestId('banner')\n const image = queryByAltText('Alt da imagem')\n\n expect(banner).toBeTruthy()\n expect(image).toBeNull()\n })\n })\n\n describe('when showBanner prop is false', () => {\n beforeEach(() => {\n ;(useSponsoredBanner as jest.Mock).mockReturnValue({\n sponsoredBanners: mockData.sponsoredBanners,\n imageAlt: 'Alt da imagem',\n loading: false,\n error: null,\n styleProps: {\n spinnerSize: 40,\n ratio: 3,\n },\n })\n })\n\n it('does not render the banner', () => {\n const { queryByAltText, queryByTestId } = render(\n <SponsoredBanner showBanner={false} />\n )\n\n const banner = queryByTestId('banner')\n const image = queryByAltText('Alt da imagem')\n\n expect(banner).toBeNull()\n expect(image).toBeNull()\n })\n })\n\n describe('when it has any error', () => {\n beforeEach(() => {\n ;(useSponsoredBanner as jest.Mock).mockReturnValue({\n sponsoredBanners: mockData.sponsoredBanners,\n imageAlt: 'Alt da imagem',\n loading: false,\n error: true,\n styleProps: {\n spinnerSize: 40,\n ratio: 3,\n },\n })\n })\n\n it('does not render the banner', () => {\n const { queryByAltText, queryByTestId } = render(<SponsoredBanner />)\n const banner = queryByTestId('banner')\n const image = queryByAltText('Alt da imagem')\n\n expect(banner).toBeNull()\n expect(image).toBeNull()\n })\n })\n\n describe('when sponsored banners is null', () => {\n beforeEach(() => {\n ;(useSponsoredBanner as jest.Mock).mockReturnValue({\n sponsoredBanners: null,\n imageAlt: 'Alt da imagem',\n loading: false,\n error: null,\n styleProps: {\n spinnerSize: 40,\n ratio: 3,\n },\n })\n })\n\n it('does not render the banner', () => {\n const { queryByAltText, queryByTestId } = render(<SponsoredBanner />)\n const banner = queryByTestId('banner')\n const image = queryByAltText('Alt da imagem')\n\n expect(banner).toBeNull()\n expect(image).toBeNull()\n })\n })\n\n describe('when sponsored banner is empty array', () => {\n beforeEach(() => {\n ;(useSponsoredBanner as jest.Mock).mockReturnValue({\n sponsoredBanners: [],\n imageAlt: 'Alt da imagem',\n loading: false,\n error: null,\n styleProps: {\n spinnerSize: 40,\n ratio: 3,\n },\n })\n })\n\n it('does not render the banner', () => {\n const { queryByAltText, queryByTestId } = render(<SponsoredBanner />)\n const banner = queryByTestId('banner')\n const image = queryByAltText('Alt da imagem')\n\n expect(banner).toBeNull()\n expect(image).toBeNull()\n })\n })\n})\n\n```" } ]
code_sponsored-banners_9ae94944
[ { "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 sponsored-banners/react/components/SponsoredBanner/__test__/mocks/index.ts from the sponsored-banners VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport type {\n SponsoredBannersData,\n SponsoredBannersProps,\n} from '../../../../interfaces'\n\nexport const mockData: SponsoredBannersData = {\n sponsoredBanners: [\n {\n adResponseId: '123',\n advertisement: {\n bannerImageId: '1',\n imageUrl: 'www.image.com.br',\n targetUrl: 'www.target.com.br',\n width: 970,\n height: 250,\n },\n },\n ],\n}\n\nexport const mockProps: SponsoredBannersProps = {\n adUnit: 'billboard',\n placement: 'homepage',\n channel: 'android',\n}\n\n```" } ]
code_render-runtime_18562bf2
[ { "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 render-runtime/docs/README.md from the render-runtime VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```markdown\n# Render Runtime\n\nThe Render Runtime app is responsible for handling runtime execution of React apps in the VTEX IO Platform. Additionally, it exports:\n\n- Helpful variables, such as [`canUseDOM`](#canusedom).\n- Hooks, such as [`useRuntime`](#useruntime).\n- React components, such as [`Block` (alias `ExtensionPoint`)](#block-alias-extensionpoint), [`Helmet`](#helmet), [`Link`](#link), [`NoSSR`](#nossr) and [`withRuntimeContext`](#withruntimecontext-high-order-component).\n\n> ℹ️ **Tip:** Run vtex setup --typings to add vtex.render-runtime types in your app. This way, IDEs will be able to provide autocomplete for variables and methods.\n\nCheck the following sections for more information on the objects exported by the Render Runtime app.\n\n# Variables\n\n## canUseDOM\n\nA *boolean* value that indicates whether the code is running in a browser environment (`true`) or in a Node/SSR environment (`false`). \n\n> ℹ️ Notice that the `canUseDOM` variable is especially useful in cases the components use DOM related data _(e.g: `document` or `window`)_.\n\nTake the following usage example:\n\n```tsx\nimport React from 'react'\nimport { canUseDOM } from 'vtex.render-runtime'\n\nfunction MyComponent() {\n const data = canUseDOM\n ? window.localStorage.getItem('foo')\n : ''\n\n return <div>Hello</div>\n}\n\nexport default MyComponent\n```\n\n# Hooks\n\n## useRuntime\n\nThe `useRuntime` React hook is useful when creating components since it provides runtime contextual variables and methods.\n\nFor an example on its usage, check the following snippet:\n\n```tsx\nimport React from 'react'\nimport { useRuntime } from 'vtex.render-runtime'\n\nfunction MyComponent() {\n const runtime = useRuntime()\n\n return <div>Hello</div>\n}\n```\n\nInside the `runtime` object you can have access to the following variables:\n\n| Name | Type | Description |\n|:--------------|:-------|:-------------------------|\n|[`account`](#account) |string |The VTEX account name, (e.g., `storecomponents`). |\n|[`binding`](#binding) |object |An object containing the `id` and `canonicalBaseAddress` of the store binding. |\n|[`culture`](#culture) |object |An object containing culture, currency and locale information. |\n|[`deviceInfo`](#deviceinfo) |object |An object specifying the user device type (`phone`, `desktop`, `tablet`, or `unknown`). *This data varies when the user resizes the window.*|\n|[`getSettings`](#getsettings) |function|A function that, when called, returns the public `settings` of an app.|\n|[`hints`](#hints) |object | An object which specifies the user device type (`phone`, `desktop`, `tablet`, or `unknown`) based on the information provided by the CDN. *Different from `deviceInfo` this data is static.*|\n|[`history`](#history)|object |A `history` object reexported from the `history` package. For further information, check [this link.](https://github.com/ReactTraining/history/tree/v4/docs)|\n|[`navigate`](#navigate)|function|A function used in the client-side to define the navigation behaviour. |\n|[`page`](#page)|string |The current `page` id (e.g., `store.home`).|\n|[`pages`](#pages)|object |Object containing all `pages`. The keys are the pages ids (e.g., `store.home`).|\n|[`route`](#route)|object |Object containing data related to the current route, such as `id`, `path`, `blockId` and others.|\n|[`production`](#production)|boolean |Points if the app is in a production workspace (`true`) or not (`false`). |\n|[`query`](#query)|object |The URL query string values in a key-value format (e.g., `{ \"foo\": \"bar\" }`).|\n|[`renderMajor`](#rendermajor)|number |The major version of the Render Runtime app.|\n|[`rootPath`](#rootpath)|string |The store root path (e.g., `/ar`). If not specified, its value is `undefined`.|\n|[`setQuery`](#setquery)|function|A function that can be called to set query string params.|\n|[`workspace`](#workspace)|string |The current workspace name (e.g., `master`).|\n\n### Usage examples\n\nCheck the following section for usage examples on how to use the internal `runtime` variables.\n\n#### `account`\n\n```tsx\nimport React from 'react'\nimport { useRuntime } from 'vtex.render-runtime'\n\nfunction MyComponent() {\n const { account } = useRuntime()\n\n return <div>Welcome to {account}</div>\n}\n\nexport default MyComponent\n```\n\n#### `binding`\n\n```tsx\nimport React from 'react'\nimport { useRuntime } from 'vtex.render-runtime'\n\nfunction MyComponent() {\n const { binding } = useRuntime()\n\n return <div>Canonical address is \"{binding.canonicalBaseAddress}\"</div>\n}\n\nexport default MyComponent\n```\n\n*Type:*\n\n```tsx\ninterface BindingInfo {\n id: string\n canonicalBaseAddress: string\n}\n```\n\n*Example value:*\n\n```json\n{\n \"id\": \"aacb06b3-a8fa-4bab-b5bd-2d654d20dcd8\",\n \"canonicalBaseAddress\": \"storetheme.vtex.com/\"\n}\n```\n\n#### `culture`\n\n\n```tsx\nimport React from 'react'\nimport { useRuntime } from 'vtex.render-runtime'\n\nfunction MyComponent() {\n const { culture } = useRuntime()\n\n return <div>Current active locale is: \"{culture.locale}\"</div>\n}\n\nexport default MyComponent\n```\n\n*Type:*\n\n```tsx\ninterface Culture {\n availableLocales: string[]\n country: string\n currency: string\n language: string\n locale: string\n customCurrencyDecimalDigits: number | null\n customCurrencySymbol: string | null\n}\n```\n\n*Example value:*\n\n```json\n{\n \"availableLocales\": [],\n \"country\": \"USA\",\n \"currency\": \"USD\",\n \"language\": \"en\",\n \"locale\": \"en-US\",\n \"customCurrencyDecimalDigits\": null,\n \"customCurrencySymbol\": \"$\"\n}\n```\n\n#### `deviceInfo`\n\n```tsx\nimport React from 'react'\nimport { useRuntime } from 'vtex.render-runtime'\n\nfunction MyComponent() {\n const { deviceInfo } = useRuntime()\n\n return <div>This page is being rendered on a \"{deviceInfo.type}\"</div>\n}\n\nexport default MyComponent\n```\n\n*Type:*\n```tsx\ninterface DeviceInfo {\n isMobile: boolean\n type: 'phone' | 'tablet' | 'desktop' | 'unknown'\n}\n```\n\n*Example value:*\n```json\n{\n \"isMobile\": false,\n \"type\": \"desktop\"\n}\n```\n\n#### `getSettings`\n\n```tsx\nimport React from 'react'\nimport { useRuntime } from 'vtex.render-runtime'\n\nfunction MyComponent() {\n const { getSettings } = useRuntime()\n const settings = getSettings('vtex.store')\n\n return <div>This is the store's name: \"{settings.storeName}\"</div>\n}\n\nexport default MyComponent\n```\n\n#### `hints`\n\n```tsx\nimport React from 'react'\nimport { useRuntime } from 'vtex.render-runtime'\n\nfunction MyComponent() {\n const { hints } = useRuntime()\n\n if (!hints.desktop) {\n return <div>This is not a desktop</div>\n }\n\n return <div>This is a desktop</div>\n}\n\nexport default MyComponent\n```\n\n*Type:*\n\n```tsx\ninterface Hints {\n desktop: boolean\n mobile: boolean\n tablet: boolean\n phone: boolean\n unknown: boolean\n}\n```\n\n*Example value:*\n\n```json\n{\n \"desktop\": true,\n \"mobile\": false,\n \"tablet\": false,\n \"phone\": false,\n \"unknown\": false,\n}\n```\n\n#### `history`\n\n```tsx\nimport React from 'react'\nimport { useRuntime } from 'vtex.render-runtime'\n\nfunction MyComponent() {\n const { history } = useRuntime()\n\n const handleClick = () => {\n history.goBack()\n }\n\n return <button onClick={handleClick}>Back</button>\n}\n\nexport default MyComponent\n```\n\n#### `navigate`\n\n```tsx\nimport React from 'react'\nimport { useRuntime } from 'vtex.render-runtime'\n\nfunction MyComponent() {\n const { navigate } = useRuntime()\n\n const handleClick = () => {\n navigate({\n to: '/other-page'\n })\n }\n\n return <button onClick={handleClick}>Go</button>\n}\n\nexport default MyComponent\n```\n\n*Function param:*\n\n```tsx\ninterface NavigateOptions {\n fallbackToWindowLocation?: boolean\n hash?: string\n page?: string\n params?: any\n query?: any\n replace?: boolean\n rootPath?: string\n scrollOptions?: false | {\n baseElementId: string,\n behavior: 'auto' | 'smooth'\n left: number\n top: number\n }\n skipSetPath?: boolean\n to?: string\n}\n```\n\n#### `page`\n\n```tsx\nimport React from 'react'\nimport { useRuntime } from 'vtex.render-runtime'\n\nfunction MyComponent() {\n const { page } = useRuntime()\n\n return <div>This is the current page id: \"{page}\"</div>\n}\n\nexport default MyComponent\n```\n\n#### `pages`\n\n```tsx\nimport React from 'react'\nimport { useRuntime } from 'vtex.render-runtime'\n\nfunction MyComponent() {\n const { pages, page } = useRuntime()\n\n return <div>This is the current page declarer: \"{pages[page].declarer}\"</div>\n}\n\nexport default MyComponent\n```\n\n*Example value:*\n\n```json\n{\n \"allowConditions\": true,\n \"context\": null,\n \"declarer\": \"vtex.store@2.x\",\n \"path\": \"/\",\n \"routeId\": \"store.home\",\n \"blockId\": \"vtex.store-theme@4.x:store.home\",\n \"map\": []\n}\n\n```\n\n#### `route`\n\n```tsx\nimport React from 'react'\nimport { useRuntime } from 'vtex.render-runtime'\n\nfunction MyComponent() {\n const { route } = useRuntime()\n\n return <div>This is the current route full path: \"{route.path}\"</div>\n}\n\nexport default MyComponent\n```\n\n*Example value:*\n\n```json\n{\n \"domain\": \"store\",\n \"id\": \"store.home\",\n \"pageContext\": {\n \"id\": \"store.home\",\n \"type\": \"route\"\n },\n \"params\": {},\n \"path\": \"/\",\n \"pathId\": \"/\",\n \"queryString\": {},\n \"breakpointStyles\": [\n {\n \"path\": \"/_v/public/vtex.styles-graphql/v1/style/vtex.store-theme@4.3.0$style.common.min.css\",\n \"mediaQuery\": \"\",\n \"type\": \"common\"\n },\n {\n \"path\": \"/_v/public/vtex.styles-graphql/v1/style/vtex.store-theme@4.3.0$style.small.min.css\",\n \"mediaQuery\": \"screen and (min-width: 20em)\",\n \"type\": \"small\"\n },\n {\n \"path\": \"/_v/public/vtex.styles-graphql/v1/style/vtex.store-theme@4.3.0$style.notsmall.min.css\",\n \"mediaQuery\": \"screen and (min-width: 40em)\",\n \"type\": \"notsmall\"\n },\n {\n \"path\": \"/_v/public/vtex.styles-graphql/v1/style/vtex.store-theme@4.3.0$style.large.min.css\",\n \"mediaQuery\": \"screen and (min-width: 64em)\",\n \"type\": \"large\"\n },\n {\n \"path\": \"/_v/public/vtex.styles-graphql/v1/style/vtex.store-theme@4.3.0$style.xlarge.min.css\",\n \"mediaQuery\": \"screen and (min-width: 80em)\",\n \"type\": \"xlarge\"\n }\n ],\n \"fonts\": \"/_v/public/vtex.styles-graphql/v1/fonts/7ead87572b7446c1ca01c45f5065665fc8cfd256\",\n \"overrides\": [\n \"/_v/public/vtex.styles-graphql/v1/overrides/vtex.product-list@0.28.2$overrides.css\",\n \"/_v/public/vtex.styles-graphql/v1/overrides/vtex.minicart@2.56.0$overrides.css\",\n \"/_v/public/vtex.styles-graphql/v1/overrides/vtex.store-theme@4.3.0$overrides.css\"\n ],\n \"rootName\": \"store.home\",\n \"ssr\": true,\n \"styleMeta\": {\n \"fontsHash\": \"7ead87572b7446c1ca01c45f5065665fc8cfd256\",\n \"overridesIds\": [\n {\n \"id\": \"vtex.product-list@0.28.2$overrides.css\"\n },\n {\n \"id\": \"vtex.minicart@2.56.0$overrides.css\"\n },\n {\n \"id\": \"vtex.store-theme@4.3.0$overrides.css\"\n }\n ],\n \"themeId\": \"vtex.store-theme@4.3.0$style.min.css\"\n },\n \"blockId\": \"vtex.store-theme@4.x:store.home\",\n \"canonicalPath\": \"/\",\n \"metaTags\": null,\n \"routeId\": \"store.home\",\n \"title\": null,\n \"varyContentById\": false\n}\n```\n\n#### `production`\n\n```tsx\nimport React from 'react'\nimport { useRuntime } from 'vtex.render-runtime'\n\nfunction MyComponent() {\n const { production } = useRuntime()\n\n if (!production) {\n return <div>This is not a production workspace</div>\n }\n\n return <div>This is a production workspace</div>\n}\n\nexport default MyComponent\n```\n\n#### `query`\n\n```tsx\nimport React from 'react'\nimport { useRuntime } from 'vtex.render-runtime'\n\nfunction MyComponent() {\n const { query } = useRuntime()\n\n return <div>The current query strings are {JSON.stringify(query)}</div>\n}\n\nexport default MyComponent\n```\n\n#### `renderMajor`\n\n```tsx\nimport React from 'react'\nimport { useRuntime } from 'vtex.render-runtime'\n\nfunction MyComponent() {\n const { renderMajor } = useRuntime()\n\n return <div>This page is rendered using vtex.render-runtime@{renderMajor}.x</div>\n}\n\nexport default MyComponent\n```\n\n#### `rootPath`\n\n```tsx\nimport React from 'react'\nimport { useRuntime } from 'vtex.render-runtime'\n\nfunction MyComponent() {\n const { rootPath } = useRuntime()\n\n if (!rootPath) {\n return <div>The store doesn't have a rootPath set</div>\n }\n\n return <div>The store rootPath is \"{rootPath}\"</div>\n}\n\nexport default MyComponent\n```\n\n#### `setQuery`\n\n```tsx\nimport React from 'react'\nimport { useRuntime } from 'vtex.render-runtime'\n\nfunction MyComponent() {\n const { setQuery } = useRuntime()\n\n const handleClick = () => {\n setQuery({ foo: 'bar' })\n }\n\n return <button>Set</button>\n}\n\nexport default MyComponent\n```\n\n#### `workspace`\n\n```tsx\nimport React from 'react'\nimport { useRuntime } from 'vtex.render-runtime'\n\nfunction MyComponent() {\n const { workspace } = useRuntime()\n\n return <div>This is the {workspace} workspace</div>\n}\n\nexport default MyComponent\n```\n\n# Components\n\n## Block (alias ExtensionPoint)\n\n`Block` is a React component used to create Store Framework blocks. \n\nFor implementation details, take the following example. \n\n> ℹ️ *Notice that the `Block` component will always expect a specific block `id`.*\n\n```tsx\nimport React from 'react'\nimport { Block } from 'vtex.render-runtime'\n// or\n// import { ExtensionPoint } from 'vtex.render-runtime'\n\nfunction MyComponent() {\n return (\n <div>\n Foobar\n <Block id=\"my-other-block\" />\n {/* or <ExtensionPoint id=\"my-other-block\" /> */}\n </div>\n )\n}\n\nexport default MyComponent\n```\n\n## Helmet\n\n`Helmet` is a component used to add HTML tags inside the `<head>` tag of a page. Take the following example:\n\n> ℹ️ `Helmet` is a reexport of [the `Helmet` component from the `react-helmet` library](https://github.com/nfl/react-helmet/tree/release/5.2.0).\n\n```tsx\nimport React from 'react'\nimport { Helmet } from 'vtex.render-runtime'\n\nfunction MyComponent() {\n return (\n <>\n <Helmet>\n <meta property=\"og:type\" content=\"article\" />\n </Helmet>\n </>\n )\n}\n\nexport default MyComponent\n```\n\n## Link\n\nThe `Link` React component is responsible for rendering an `a` HTML element that, when clicked, navigates the user to the provided route.\n\n> ℹ️ Notice that the `Link` component has a similar API to the `navigate` method from the [`useRuntime`](#useruntime) hook.\n\n| Name | Type | Description | Default |\n| :------------- |:-------------| :-----|:-----|\n| `page` | `string` | The name of the page that the user will be redirected to. Maps to a `blocks.json` block (e.g., `'store.product'`)||\n| `to` | `string` |The URL of the page that the user will be redirected to (e.g., `/shirt/p?skuId=1`). Notice that `to` is an **alternative** to `page` and it contains the whole URL instead of the page name. | |\n| `params` | `object` | The `param` values of the page path in a key-value format (e.g, `{slug: 'shirt'}`). Params that starts with `__` are not considered on path transformations, and can be generaly be used as an alternative to query params | `{}`|\n| `query` | `string` | The representation of the query params that are appended to the page path (e.g., `skuId=231`.) | `''` |\n| `onClick` | `function` | A callback that is fired when the user clicks on a component (e.g., `() => alert('Salut')`) | |\n| `replace` | `boolean` | The boolean value used to indicate if it should call (`true`) the replace function to navigate or not (`false`) | |\n\nOther props you pass will be forwarded to the `a` component and can be used for customization.\n\nTake the following usage examples:\n\n```tsx\nimport React from 'react'\nimport { Link } from 'vtex.render-runtime'\n\nfunction MyComponent() {\n return <Link to=\"/otherpage\" classname=\"c-on-base\">Hello</Link>\n}\n\nexport default MyComponent\n```\n\n```tsx\nimport React from 'react'\nimport { Link } from 'vtex.render-runtime'\n\nfunction MyComponent() {\n const params = {\n slug: PRODUCT_SLUG, // Considered on path transformations (/{slug}/p)\n __listName: 'List of products' // Ignored on path transformations\n __yourProductPageParam: YOUR_PARAM // Ignored on path transformations\n }\n\n return <Link to=\"/productpage\" params={params}>Hello</Link>\n}\n\nexport default MyComponent\n```\n\n## NoSSR\n\n> ⚠️ We always recommend using the [`canUseDOM`](#canusedom) variable when possible.\n\n`NoSSR` is a React component that avoids rendering its children during Server-Side Rendering (SSR).\n\n> ℹ️ Notice that the `NoSSR` component is especially useful in cases the components use DOM related data _(e.g: `document` or `window`)_.\n\nTake the following usage example:\n\n```tsx\nimport React from 'react'\nimport { NoSSR } from 'vtex.render-runtime'\n\nimport DomRelatedComponent from './DomRelatedComponent'\n\nfunction MyComponent() {\n return (\n <NoSSR onSSR={<div>Loading...</div>}>\n <DomRelatedComponent/>\n </NoSSR>\n )\n}\n```\n\n## withRuntimeContext (High Order Component)\n\n`withRuntimeContext` is a React High Order Component (HOC) that allows class components to access the runtime context.\n\n> ℹ️ When using function components, you can use [`useRuntimeContext`](#useruntimecontext) hook instead.\n\nTake the following usage example:\n\n```tsx\nimport React from 'react'\nimport { withRuntimeContext, RenderContext } from 'vtex.render-runtime'\n\nclass MyComponent extends React.Component<{ runtime: RenderContext }>{\n render({ runtime }) {\n return <div>This is the current page id: \"{runtime.page}\"</div>\n }\n}\n\nconst MyComponentWithRuntime = withRuntimeContext(MyComponent)\n```\n\nNotice that, when in SSR mode, you can optionally provide the `onSSR` prop together with a component to render instead.\n\n```" } ]
code_render-runtime_86b1a781
[ { "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 render-runtime/react/index.tsx from the render-runtime VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\n/* global module */\nimport './o11y/instrument'\nimport 'core-js/es6/symbol'\nimport 'core-js/fn/symbol/iterator'\nimport { canUseDOM } from 'exenv'\nimport * as runtimeGlobals from './core/main'\n\nimport { polyfillIntl } from './start/intl'\nimport { addAMPProxy } from './start/amp'\nimport { patchLibs } from './start/patchLibs'\nimport { registerRuntimeGlobals } from './start/register'\nimport { loadRuntimeJSONs } from './start/runtime'\nimport { hydrateUncriticalStyles } from './start/styles'\n\nfunction performanceMark(...args: Parameters<typeof window.performance.mark>) {\n if (\n typeof window === 'undefined' ||\n !(typeof window?.performance?.mark === 'function')\n ) {\n return\n }\n window.performance.mark(...args)\n}\n\nconst uncriticalStylesPromise = hydrateUncriticalStyles()\nperformanceMark('uncritical-styles-start')\nuncriticalStylesPromise.then(() => {\n performanceMark('uncritical-styles-end')\n})\n\nperformanceMark('intl-polyfill-start')\nconst intlPolyfillPromise = polyfillIntl()\nintlPolyfillPromise.then(() => {\n performanceMark('intl-polyfill-end')\n})\n\nregisterRuntimeGlobals(runtimeGlobals)\naddAMPProxy(window.__RUNTIME__)\npatchLibs()\n\nexport const renderReadyPromise: Promise<any> = canUseDOM\n ? (function () {\n const contentLoadedPromise = new Promise((resolve) => {\n window.addEventListener('DOMContentLoaded', resolve)\n if (window.__DOM_READY__) {\n resolve()\n }\n })\n\n contentLoadedPromise.then(() => {\n performanceMark('content-loaded-promise-resolved')\n })\n\n const scriptsLoadedPromise = new Promise((resolve) => {\n if (typeof window.__ASYNC_SCRIPTS_READY__ === 'undefined') {\n return resolve()\n }\n\n window.addEventListener('asyncScriptsReady', resolve)\n if (window.__ASYNC_SCRIPTS_READY__) {\n resolve()\n }\n })\n\n return Promise.all([\n contentLoadedPromise,\n intlPolyfillPromise,\n scriptsLoadedPromise,\n uncriticalStylesPromise,\n ])\n })()\n : Promise.resolve()\n\nfunction start() {\n global.__RUNTIME__ = window.__RUNTIME__\n if (window.__RUNTIME__.start && !window.__ERROR__) {\n if (canUseDOM) {\n renderReadyPromise.then(() => {\n setTimeout(() => {\n performanceMark('render-start')\n window.__RENDER_8_RUNTIME__.start()\n performanceMark('render-end')\n window?.performance?.measure?.(\n '[VTEX IO] Rendering/Hydration',\n 'render-start',\n 'render-end'\n )\n }, 1)\n })\n } else {\n window.__RENDER_8_RUNTIME__.start()\n }\n }\n}\n\nif (module.hot) {\n module.hot.accept('./core/main', () => {\n // eslint-disable-next-line @typescript-eslint/no-var-requires\n const hotGlobals = require('./core/main')\n window.__RENDER_8_RUNTIME__.ExtensionContainer =\n hotGlobals.ExtensionContainer\n window.__RENDER_8_RUNTIME__.ExtensionPoint = hotGlobals.ExtensionPoint\n window.__RENDER_8_RUNTIME__.LayoutContainer = hotGlobals.LayoutContainer\n window.__RENDER_8_RUNTIME__.Link = hotGlobals.Link\n window.__RENDER_8_RUNTIME__.Loading = hotGlobals.Loading\n window.__RENDER_8_RUNTIME__.buildCacheLocator = hotGlobals.buildCacheLocator\n runtimeGlobals.start()\n })\n}\n\nif (!canUseDOM) {\n start()\n} else {\n loadRuntimeJSONs().then(() => start())\n}\n\nexport * from './core/main'\n\n```" } ]
code_render-runtime_7b452f15
[ { "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 render-runtime/react/intl-polyfill.ts from the render-runtime VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { path } from 'ramda'\nimport { canUseDOM } from 'exenv'\n\nimport { PluralRules } from '@formatjs/intl-pluralrules'\nimport RelativeTimeFormat from '@formatjs/intl-relativetimeformat'\n\nlet myPromise = null\n\nif (typeof window.Intl.PluralRules === 'undefined' || !canUseDOM) {\n Object.defineProperty(Intl, 'PluralRules', {\n value: PluralRules,\n writable: true,\n enumerable: false,\n configurable: true,\n })\n}\n\nif (!('RelativeTimeFormat' in Intl) || !canUseDOM) {\n Object.defineProperty(Intl, 'RelativeTimeFormat', {\n value: RelativeTimeFormat,\n writable: true,\n enumerable: false,\n configurable: true,\n })\n}\n\nconst locale = path<string>(['__RUNTIME__', 'culture', 'locale'], window)\nconst [lang] = locale ? locale.split('-') : ['']\n\nmyPromise = new Promise((resolve) => {\n const hasPolyfilledPlural =\n window.Intl.PluralRules.polyfilled && canUseDOM && lang\n const hasPolyfilledRelative =\n window.Intl.RelativeTimeFormat.polyfilled && canUseDOM && lang\n\n const pluralPromise = hasPolyfilledPlural\n ? import('@formatjs/intl-pluralrules/dist/locale-data/' + lang)\n : Promise.resolve()\n const relativeTimePromise = hasPolyfilledRelative\n ? import('@formatjs/intl-relativetimeformat/dist/locale-data/' + lang)\n : Promise.resolve()\n Promise.all([pluralPromise, relativeTimePromise]).then(resolve)\n})\n\nexport default myPromise\n\n```" } ]
code_render-runtime_99b9f2c3
[ { "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 render-runtime/react/LayoutContainer.tsx from the render-runtime VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\n// @ts-nocheck\nimport { LayoutContainer } from 'vtex.render-runtime'\n\nexport default LayoutContainer\n\n```" } ]