[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of freshchat/react/typings/global.d.ts from the freshchat VTEX app.

[Assistant]
Here's the implementation:

```typescript
interface Window extends Window {
  dataLayer: any[]
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of iframe/messages/pt.json from the iframe VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "editor.iframe.title": "Iframe",
  "editor.iframe.src.description": "Endereço de origem do iframe",
  "editor.iframe.src.title": "Src",
  "editor.iframe.height.title": "Altura",
  "editor.iframe.width.title": "Comprimento",
  "editor.iframe.id.title": "ID",
  "editor.iframe.className.title": "className",
  "editor.iframe.onLoad.title": "onLoad",
  "editor.dynamiciframe.id.title": "ID",
  "editor.dynamiciframe.className.title": "className",
  "editor.dynamiciframe.onLoad.title": "onLoad",
  "editor.iframe.title.title": "Title",
  "editor.iframe.allow.title": "Allow",
  "editor.dynamiciframe.title": "Dynamic Iframe",
  "editor.dynamiciframe.title.title": "Title",
  "editor.dynamiciframe.srcPrepend.description": "iframe source url pre-pended string",
  "editor.dynamiciframe.srcPrepend.title": "Prepend",
  "editor.dynamiciframe.srcAppend.description": "iframe source url appended string",
  "editor.dynamiciframe.srcAppend.title": "Append",
  "editor.dynamiciframe.height.title": "Height",
  "editor.dynamiciframe.width.title": "Width",
  "editor.dynamiciframe.allow.title": "Allow"
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of iframe/messages/en.json from the iframe VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "editor.iframe.title": "Iframe",
  "editor.iframe.src.description": "Source url of the iframe",
  "editor.iframe.src.title": "Src",
  "editor.iframe.height.title": "Height",
  "editor.iframe.width.title": "Width",
  "editor.iframe.title.title": "Title",
  "editor.iframe.allow.title": "Allow",
  "editor.iframe.id.title": "ID",
  "editor.iframe.className.title": "className",
  "editor.iframe.onLoad.title": "onLoad",
  "editor.dynamiciframe.id.title": "ID",
  "editor.dynamiciframe.className.title": "className",
  "editor.dynamiciframe.onLoad.title": "onLoad",
  "editor.dynamiciframe.title": "Dynamic Iframe",
  "editor.dynamiciframe.title.title": "Title",
  "editor.dynamiciframe.srcPrepend.description": "iframe source url pre-pended string",
  "editor.dynamiciframe.srcPrepend.title": "Prepend",
  "editor.dynamiciframe.srcAppend.description": "iframe source url appended string",
  "editor.dynamiciframe.srcAppend.title": "Append",
  "editor.dynamiciframe.height.title": "Height",
  "editor.dynamiciframe.width.title": "Width",
  "editor.dynamiciframe.allow.title": "Allow"
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of iframe/messages/context.json from the iframe VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "editor.iframe.title": "editor.iframe.title",
  "editor.iframe.src.description": "editor.iframe.src.description",
  "editor.iframe.src.title": "editor.iframe.src.title",
  "editor.iframe.height.title": "editor.iframe.height.title",
  "editor.iframe.width.title": "editor.iframe.width.title",
  "editor.iframe.title.title": "editor.iframe.title.title",
  "editor.iframe.allow.title": "editor.iframe.allow.title",
  "editor.iframe.id.title": "editor.iframe.id.title",
  "editor.iframe.className.title": "editor.iframe.className.title",
  "editor.iframe.onLoad.title": "editor.iframe.onLoad.title",
  "editor.dynamiciframe.title": "editor.dynamiciframe.title",
  "editor.dynamiciframe.title.title": "editor.dynamiciframe.title.title",
  "editor.dynamiciframe.srcPrepend.description": "editor.dynamiciframe.srcPrepend.description",
  "editor.dynamiciframe.srcPrepend.title": "editor.dynamiciframe.srcPrepend.title",
  "editor.dynamiciframe.srcAppend.description": "editor.dynamiciframe.srcAppend.description",
  "editor.dynamiciframe.srcAppend.title": "editor.dynamiciframe.srcAppend.title",
  "editor.dynamiciframe.height.title": "editor.dynamiciframe.height.title",
  "editor.dynamiciframe.width.title": "editor.dynamiciframe.width.title",
  "editor.dynamiciframe.allow.title": "editor.dynamiciframe.allow.title",
  "editor.dynamiciframe.id.title": "editor.dynamiciframe.id.title",
  "editor.dynamiciframe.className.title": "editor.dynamiciframe.className.title",
  "editor.dynamiciframe.onLoad.title": "editor.dynamiciframe.onLoad.title"
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of iframe/messages/es.json from the iframe VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "editor.iframe.title": "Iframe",
  "editor.iframe.src.description": "Dirección de origen del iframe",
  "editor.iframe.src.title": "Src",
  "editor.iframe.height.title": "Altura",
  "editor.iframe.width.title": "Longitud",
  "editor.iframe.id.title": "ID",
  "editor.iframe.className.title": "className",
  "editor.iframe.onLoad.title": "onLoad",
  "editor.dynamiciframe.id.title": "ID",
  "editor.dynamiciframe.className.title": "className",
  "editor.dynamiciframe.onLoad.title": "onLoad",
  "editor.iframe.title.title": "Title",
  "editor.iframe.allow.title": "Allow",
  "editor.dynamiciframe.title": "Dynamic Iframe",
  "editor.dynamiciframe.title.title": "Title",
  "editor.dynamiciframe.srcPrepend.description": "iframe source url pre-pended string",
  "editor.dynamiciframe.srcPrepend.title": "Prepend",
  "editor.dynamiciframe.srcAppend.description": "iframe source url appended string",
  "editor.dynamiciframe.srcAppend.title": "Append",
  "editor.dynamiciframe.height.title": "Height",
  "editor.dynamiciframe.width.title": "Width",
  "editor.dynamiciframe.allow.title": "Allow"
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of iframe/messages/ar.json from the iframe VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "editor.iframe.title": "اطار الموقع",
  "editor.iframe.src.description": "مصدر رابط محدد لأطار الموقع ",
  "editor.iframe.src.title": "المصدر",
  "editor.iframe.height.title": "الطول",
  "editor.iframe.width.title": "العرض",
  "editor.iframe.title.title": "العنوان",
  "editor.iframe.allow.title": "السماح",
  "editor.iframe.id.title": "ID",
  "editor.iframe.className.title": "className",
  "editor.iframe.onLoad.title": "onLoad",
  "editor.dynamiciframe.id.title": "ID",
  "editor.dynamiciframe.className.title": "className",
  "editor.dynamiciframe.onLoad.title": "onLoad",
  "editor.dynamiciframe.title": "اطار مواقع ديناميكي",
  "editor.dynamiciframe.title.title": "العنوان",
  "editor.dynamiciframe.srcPrepend.description": "مصدر رابط اطار الموقع من السلسة الساقة",
  "editor.dynamiciframe.srcPrepend.title": "سلسلة سابقة",
  "editor.dynamiciframe.srcAppend.description": " مصدر رابط اطار الموقع من السلسة الساقة ",
  "editor.dynamiciframe.srcAppend.title": "ارفق",
  "editor.dynamiciframe.height.title": "الطول",
  "editor.dynamiciframe.width.title": "العرض",
  "editor.dynamiciframe.allow.title": "السماح"
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of iframe/docs/README.md from the iframe VTEX app.

[Assistant]
Here's the implementation:

```markdown
📢 Use this project, [contribute](https://github.com/vtex-apps/iframe) to it or open issues to help evolve it using [Store Discussion](https://github.com/vtex-apps/store-discussion).

# Iframe

<!-- DOCS-IGNORE:start -->
<!-- ALL-CONTRIBUTORS-BADGE:START - Do not remove or modify this section -->

[![All Contributors](https://img.shields.io/badge/all_contributors-0-orange.svg?style=flat-square)](#contributors-)

<!-- ALL-CONTRIBUTORS-BADGE:END -->
<!-- DOCS-IGNORE:end -->

An app that makes it possible to render external iframes on a store.

![image](https://user-images.githubusercontent.com/18701182/67055752-abcb0500-f11f-11e9-8c24-50234214d474.png)

## Configuration - standard Iframe

1. Add the `vtex.iframe` to the theme's dependencies on the `manifest.json`

```json
"dependencies": {
 "vtex.iframe": "0.x"
}
```

2.  Add the interface `iframe` to any **custom page** (Iframes are not allowed outside custom pages).

```json
{
  "store.custom#about-us": {
    "blocks": ["flex-layout.row#about-us", "iframe"]
  },

  "iframe": {
    "props": {
      "src": ""
    }
  }
}
```

| Prop name | Type   | Description                             | Default value |
| --------- | ------ | --------------------------------------- | ------------- |
| `src`     | String | Source address the iframe should render | `null`        |
| `width`   | Number | Width attribute of the iframe           | `null`        |
| `height`  | Number | Height attribute of the iframe          | `null`        |
| `allow`   | String | allow attribute of the iframe           | `null`        |

## Configuration - dynamic Iframe

1. Add the `vtex.iframe` to the theme's dependencies on the `manifest.json`

```json
"dependencies": {
  "vtex.iframe": "0.x"
}
```

2. Add the dynamicIframe block and its properties to the blocks.json file

```json
{
  "store.custom#locationPage": {
    "children": ["iframe.dynamic-src"]
  },
  "iframe.dynamic-src": {
    "props": {
      "dynamicSrc": "https://www.test.com/exampleStaticPathName/{dynamicParam1}/{dynamicParam2}/exampleStaticPageName",
      "width": "1920",
      "height": "1000",
      "title": "exampleStaticPageName iframe wrapper for {account}",
      "allow": "geolocation"
    }
  }
}
```

3. register your new page in routes.json with appropriate parameters passed into the page url

```json
{
  "store.custom#locationPage": {
    "path": "/:param1/:param2/pagename"
  }
}
```

| Prop name    | Type   | Description                                                       | Default value |
| ------------ | ------ | ----------------------------------------------------------------- | ------------- |
| `dynamicSrc` | String | iframe src with dynamic parameters from page URL enclosed in '{}' | `null`        |
| `width`      | Number | Width attribute of the iframe                                     | `null`        |
| `height`     | Number | Height attribute of the iframe                                    | `null`        |
| `title`      | String | title attribute of the iframe                                     | `null`        |
| `allow`      | String | allow attribute of the iframe                                     | `null`        |
| `id`         | String | ID attribute of the iframe                                        | `null`        |
| `className`  | String | class attribute of the iframe                                     | `null`        |
| `onLoad`     | String | onLoad attribute of the iframe                                    | `null`        |
| `srcAccount` | Object | Object with account name and src                                  | `null`        |

### srcAccount

Using srcAccount

```json
  "iframe#logout": {
    "props": {
      "src": "//www.mywebsiteprod.com/logout",
      "srcAccount": {
        "mywebsiteprod": "//www.mywebsite.com/logout",
        "mywebsiteqa": "//qa.mywebsite.com/logout"
      },
      "onLoad": "setTimeout(() => {window.location.href='/'}, 5000)",
      "className": "iframeLogout",
      "id": "iframeLogout"
    }
  },
```

## Customization

There is a `.container` handle that wraps the iframe, it's also possible to use `blockClass`.

<!-- DOCS-IGNORE:start -->

## Contributors ✨

Thanks goes to these wonderful people ([emoji key](https://allcontributors.org/docs/en/emoji-key)):

<!-- ALL-CONTRIBUTORS-LIST:START - Do not remove or modify this section -->
<!-- prettier-ignore-start -->
<!-- markdownlint-disable -->
<!-- markdownlint-enable -->
<!-- prettier-ignore-end -->

<!-- ALL-CONTRIBUTORS-LIST:END -->

This project follows the [all-contributors](https://github.com/all-contributors/all-contributors) specification. Contributions of any kind welcome!

<!-- DOCS-IGNORE:end -->

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of iframe/react/package.json from the iframe VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "scripts": {
    "test": "vtex-test-tools test",
    "lint": "tsc --noEmit && eslint --ext ts,tsx ."
  },
  "dependencies": {
    "classnames": "^2.2.6",
    "ramda": "^0.26.1",
    "react": "^16.13.1",
    "react-dom": "^16.13.1",
    "react-intl": "^3.12.0"
  },
  "devDependencies": {
    "@apollo/react-testing": "^3.1.3",
    "@types/classnames": "^2.2.7",
    "@types/graphql": "^14.5.0",
    "@types/jest": "^25.1.4",
    "@types/node": "^13.9.8",
    "@types/prop-types": "^15.7.0",
    "@types/ramda": "^0.26.5",
    "@types/react": "^16.9.31",
    "@vtex/test-tools": "^3.1.0",
    "@vtex/tsconfig": "^0.4.4",
    "apollo-cache-inmemory": "^1.6.5",
    "apollo-client": "^2.6.8",
    "graphql": "^14.6.0",
    "typescript": "3.9.7",
    "vtex.css-handles": "http://vtex.vtexassets.com/_v/public/typings/v1/vtex.css-handles@0.4.4/public/@types/vtex.css-handles",
    "vtex.render-runtime": "http://vtex.vtexassets.com/_v/public/typings/v1/vtex.render-runtime@8.132.4/public/@types/vtex.render-runtime",
    "vtex.styleguide": "http://vtex.vtexassets.com/_v/public/typings/v1/vtex.styleguide@9.146.4/public/@types/vtex.styleguide"
  },
  "version": "0.8.0"
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of iframe/react/DynamicIframe.tsx from the iframe VTEX app.

[Assistant]
Here's the implementation:

```tsx
import React from 'react'
import { useRuntime } from 'vtex.render-runtime'

import Iframe from './Iframe'

interface Props {
  dynamicSrc: string
  width?: number
  height?: number
  title?: string
  allow?: string
  id?: string
  className?: string
  onLoad?: any
}

function DynamicIframe({
  dynamicSrc = '',
  width,
  height,
  title,
  allow,
  id,
  className,
  onLoad,
}: Props) {
  const {
    route: { params, queryString },
    query = {},
  } = useRuntime()

  const _dynamicParams: any = Object.keys(params).length ? params : queryString

  let allParamsExist = true

  const queryStringSearch = Object.keys(params).length
    ? Object.keys(query).reduce((acc, key) => {
        return `${acc || '?'}${key}=${query[key]}&`
      }, '')
    : ``

  const src = dynamicSrc.replace(/({[A-z0-9]*})/g, (match: string) => {
    const thisParam = match.replace(/{|}/g, '')
    if (!thisParam || !_dynamicParams[thisParam]) {
      allParamsExist = false
      console.error(
        `parameter ${thisParam} not found in runtime params: ${_dynamicParams}`
      )
      return ''
    }
    return _dynamicParams[thisParam]
  })

  if (allParamsExist !== true || !src) {
    return null
  }

  return (
    <Iframe
      title={title}
      src={src + queryStringSearch}
      width={width}
      height={height}
      allow={allow}
      id={id}
      className={className}
      onLoad={onLoad}
    />
  )
}

DynamicIframe.schema = {
  title: 'editor.dynamiciframe.title',
  type: 'object',
  properties: {
    dynamicSrc: {
      title: 'editor.dynamiciframe.dynamicSrc.title',
      description: 'editor.dynamiciframe.dynamicSrc.description',
      type: 'string',
      default: null,
    },
    width: {
      title: 'editor.dynamiciframe.width.title',
      type: 'number',
      default: null,
    },
    height: {
      title: 'editor.dynamiciframe.height.title',
      type: 'number',
      default: null,
    },
    title: {
      title: 'editor.dynamiciframe.title.title',
      type: 'string',
      default: null,
    },
    id: {
      title: 'editor.dynamiciframe.id.title',
      type: 'string',
      default: null,
    },
    className: {
      title: 'editor.dynamiciframe.className.title',
      type: 'string',
      default: null,
    },
    onLoad: {
      title: 'editor.dynamiciframe.onLoad.title',
      type: 'string',
      default: null,
    },
    allow: {
      title: 'editor.dynamiciframe.allow.title',
      type: 'string',
      default: null,
    },
  },
}

export default DynamicIframe

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of iframe/react/Iframe.tsx from the iframe VTEX app.

[Assistant]
Here's the implementation:

```tsx
/* eslint-disable no-console */
import React from 'react'
import { useCssHandles } from 'vtex.css-handles'
import { useRuntime } from 'vtex.render-runtime'

const CSS_HANDLES = ['container'] as const

interface Props {
  src?: string
  srcAccount?: any
  width?: number
  height?: number
  allow?: string
  title?: string
  id?: string
  className?: string
  onLoad?: any
}

function Iframe(props: Props) {
  const {
    src,
    srcAccount,
    width,
    height,
    title,
    allow,
    id,
    className,
    onLoad,
  } = props
  const handles = useCssHandles(CSS_HANDLES)
  const runtime = useRuntime()

  const handleIframeLoad = () => {
    if (!onLoad) return null
    // eslint-disable-next-line @typescript-eslint/no-implied-eval, no-new-func
    return Function('IframeHandler', `"use strict";(${onLoad});`)(onLoad)
  }

  const processSrc = () => srcAccount?.[runtime.account] ?? src

  console.log('processSrc =>', processSrc())

  return (
    <div className={`${handles.container} w-100 flex justify-center`}>
      <iframe
        title={title}
        src={processSrc()}
        width={width}
        height={height}
        allow={allow}
        id={id}
        className={className}
        onLoad={handleIframeLoad}
        frameBorder="0"
      />
    </div>
  )
}

Iframe.schema = {
  title: 'editor.iframe.title',
  type: 'object',
  properties: {
    src: {
      title: 'editor.iframe.src.title',
      description: 'editor.iframe.src.description',
      type: 'string',
      default: null,
    },
    srcAccount: {
      title: 'editor.iframe.srcAccount.title',
      description: 'editor.iframe.srcAccount.description',
      type: 'string',
      default: null,
    },
    width: {
      title: 'editor.iframe.width.title',
      type: 'number',
      default: null,
    },
    height: {
      title: 'editor.iframe.height.title',
      type: 'number',
      default: null,
    },
    title: {
      title: 'editor.iframe.title.title',
      type: 'string',
      default: null,
    },
    id: {
      title: 'editor.iframe.id.title',
      type: 'string',
      default: null,
    },
    className: {
      title: 'editor.iframe.className.title',
      type: 'string',
      default: null,
    },
    onLoad: {
      title: 'editor.iframe.onLoad.title',
      type: 'string',
      default: null,
    },
    allow: {
      title: 'editor.iframe.allow.title',
      type: 'string',
      default: null,
    },
  },
}

export default Iframe

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of iframe/store/interfaces.json from the iframe VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "iframe": {
    "component": "Iframe"
  },
  "iframe.dynamic-src":{
    "component": "DynamicIframe"
  }
}
```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of iframe/react/__tests__/index.test.tsx from the iframe VTEX app.

[Assistant]
Here's the implementation:

```tsx
import React from 'react'
import { render } from '@vtex/test-tools/react'
import { useRuntime } from 'vtex.render-runtime'

import DynamicIframe from '../DynamicIframe'

const mockedUseRuntime = useRuntime as jest.Mock

describe('DynamicIframe', () => {
  it('should render the right URL', () => {
    mockedUseRuntime.mockImplementation(() => {
      return {
        route: {
          params: {
            param1: 'foo',
            param2: 'bar',
          },
        },
      }
    })

    const { container } = render(
      <DynamicIframe dynamicSrc="https://{param1}.com/{param2}.aspx" />
    )

    const iframe = container.querySelector('iframe') as HTMLIFrameElement

    expect(iframe.src).toBe('https://foo.com/bar.aspx')
  })
})

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of kit-indexer/docs/README.md from the kit-indexer VTEX app.

[Assistant]
Here's the implementation:

```markdown
# Kit Indexer

App in VTEX that receives a notification when a SKU is changed, if the SKU changed is a KIT, the SKU is updated with the correct weight which is the sum of the weights of its components.

## How it works?

![diagram](images/indexer-diagram.png)

## How to install

⚠ First, make sure the broadcaster app is installed.
![my-apps](images/apps.png)

Run command: `vtex install vtex.kit-indexer`

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of kit-indexer/node/service.json from the kit-indexer VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "memory": 128,
  "ttl": 10,
  "timeout": 2,
  "minReplicas": 2,
  "maxReplicas": 10,
  "workers": 4,
  "events": {
    "skuChange": {
      "keys": ["broadcaster.notification"]
    }
  }
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of kit-indexer/node/package.json from the kit-indexer VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "dependencies": {
    "co-body": "^6.0.0"
  },
  "devDependencies": {
    "@types/co-body": "^0.0.3",
    "@types/node": "12.x",
    "@vtex/api": "6.45.12",
    "@vtex/tsconfig": "^0.5.6",
    "typescript": "3.9.7"
  },
  "scripts": {
    "lint": "tsc --noEmit --pretty && eslint -c .eslintrc.json --fix './**/*.ts'"
  },
  "version": "0.7.2"
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of kit-indexer/node/index.ts from the kit-indexer VTEX app.

[Assistant]
Here's the implementation:

```typescript
import type {
  ParamsContext,
  ServiceContext,
  RecorderState,
  ClientsConfig,
} from '@vtex/api'
import { Service } from '@vtex/api'

import { skuChange } from './events/skuChange'
import { Clients } from './clients'

const TIMEOUT_MS = 10000
const CONCURRENCY = 10

declare global {
  type Context = ServiceContext<Clients, State>

  interface State extends RecorderState {
    code: number
  }
}

const clients: ClientsConfig<Clients> = {
  // We pass our custom implementation of the clients bag, containing the Status client.
  implementation: Clients,
  options: {
    // All IO Clients will be initialized with these options, unless otherwise specified.
    default: {
      retries: 2,
      timeout: TIMEOUT_MS,
    },
    events: {
      exponentialTimeoutCoefficient: 2,
      exponentialBackoffCoefficient: 2,
      initialBackoffDelay: 50,
      retries: 1,
      timeout: TIMEOUT_MS,
      concurrency: CONCURRENCY,
    },
  },
}

export default new Service<Clients, State, ParamsContext>({
  clients,
  events: {
    skuChange,
  },
})

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of kit-indexer/node/clients/index.ts from the kit-indexer VTEX app.

[Assistant]
Here's the implementation:

```typescript
import { IOClients } from '@vtex/api'

import Catalog from './catalog'

// Extend the default IOClients implementation with our own custom clients.
export class Clients extends IOClients {
  public get catalog() {
    return this.getOrSet('catalog', Catalog)
  }
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of kit-indexer/node/clients/catalog.ts from the kit-indexer VTEX app.

[Assistant]
Here's the implementation:

```typescript
import type { InstanceOptions, IOContext } from '@vtex/api'
import { ExternalClient } from '@vtex/api'

interface UpdateBody {
  ProductId: number
  Name: string
  PackagedHeight: number
  PackagedLength: number
  PackagedWidth: number
  PackagedWeightKg: number
}

export default class Catalog extends ExternalClient {
  constructor(context: IOContext, options?: InstanceOptions) {
    super(`http://${context.account}.myvtex.com/api`, context, {
      ...options,
      headers: {
        ...options?.headers,
        VtexIdclientAutCookie:
          context.adminUserAuthToken ?? context.authToken ?? '',
        'X-Vtex-Use-Https': 'true',
      },
    })
  }

  public async getProduct(sku: string) {
    return this.http.get(
      `/catalog_system/pvt/sku/stockkeepingunitbyid/${sku}`,
      {
        metric: 'get-product-by-sku-id',
      }
    )
  }

  public async updateProduct(data: UpdateBody, skuId: string) {
    return this.http.put(`/catalog/pvt/stockkeepingunit/${skuId}`, data, {
      metric: 'update-product-by-sku-id',
    })
  }
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of kit-indexer/node/events/skuChange.ts from the kit-indexer VTEX app.

[Assistant]
Here's the implementation:

```typescript
import type { EventContext } from '@vtex/api'
import { LogLevel, NotFoundError, ResolverError } from '@vtex/api'

import type { Clients } from '../clients'

interface Item {
  Id: number
  Name: string
  unitPrice: number
  Amount: number
  EstimatedDateArrival: string
  Dimension: Dimension
  RefId: string
  EAN: string
  IsKitOptimized: boolean
}

interface Dimension {
  cubicweight: number
  height: number
  length: number
  weight: number
  width: number
}

export async function skuChange(ctx: EventContext<Clients>) {
  const {
    clients: { catalog: catalogClient },
  } = ctx

  const { IdSku, HasStockKeepingUnitModified } = ctx.body

  if (!HasStockKeepingUnitModified) return

  let product
  let totalWeight = 0

  try {
    // Add individual weights
    product = await catalogClient.getProduct(IdSku)

    if (product.IsKit) {
      const { KitItems } = product

      totalWeight = 0

      KitItems.forEach((element: Item) => {
        totalWeight += element.Dimension.weight
      })
    }
  } catch (error) {
    const erroMessage = `SKU ${IdSku} not found.`
    const splunkError = {
      error: erroMessage,
      detail: error,
    }

    ctx.vtex.logger.log(splunkError, LogLevel.Error)
    throw new NotFoundError(erroMessage)
  }

  if (product?.IsKit && totalWeight !== product.Dimension.weight) {
    // Update base product with the fixed weight
    try {
      await catalogClient.updateProduct(
        {
          ProductId: product.ProductId,
          Name: product.NameComplete,
          PackagedHeight: product.Dimension.height,
          PackagedLength: product.Dimension.length,
          PackagedWidth: product.Dimension.width,
          PackagedWeightKg: totalWeight,
        },
        IdSku
      )
    } catch (error) {
      const erroMessage = `SKU ${IdSku} cannot be updated.`
      const splunkError = {
        error: erroMessage,
        detail: error,
      }

      ctx.vtex.logger.log(splunkError, LogLevel.Error)
      throw new ResolverError(erroMessage)
    }
  }
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of avantlink/docs/README.md from the avantlink VTEX app.

[Assistant]
Here's the implementation:

```markdown
# Avantlink

> VTEX Avantlink first party app

## Setup

Open a terminal and type:

```
vtex install vtex.avantlink@1.x
```

Open your admin in the Apps section:

https://YOURSTORENAME.myvtex.com/admin/apps/

Click in Avantlink and fill your Site ID.

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of avantlink/react/package.json from the avantlink VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "devDependencies": {
    "@types/graphql": "^14.5.0",
    "@types/jest": "^24.0.18",
    "@types/node": "^12.7.11",
    "eslint": "5",
    "eslint-config-vtex-react": "^4.1.0",
    "prettier": "^1.18.2",
    "typescript": "3.5.2"
  }
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of avantlink/react/index.ts from the avantlink VTEX app.

[Assistant]
Here's the implementation:

```typescript
import { canUseDOM } from 'vtex.render-runtime'
import { PixelMessage, OrderPlacedData } from './typings/events'

let added = false
function handleMessages(e: PixelMessage) {
  switch (e.data.eventName) {
    case 'vtex:pageView': {
      const { pageUrl } = e.data
      const isOrderPlaced = pageUrl.indexOf('checkout/orderPlaced') !== -1
      if (!isOrderPlaced && added === false) {
        addTrackingLib()
      }
      break
    }
    case 'vtex:orderPlaced': {
      const order = e.data
      addMetrics(order)
      addTrackingLib()
      break
    }
    default:
      break
  }
}

function addTrackingLib() {
  added = true
  const avm = document.createElement('script')
  avm.type = 'text/javascript'
  avm.async = true
  avm.src =
    ('https:' == document.location.protocol ? 'https://' : 'http://') +
    'cdn.avmws.com/' +
    window.__avantlink_siteId +
    '/'
  const s = document.getElementsByTagName('script')[0]
  s.parentNode!.insertBefore(avm, s)
}

function addMetrics(order: OrderPlacedData) {
  window._AvantMetrics = window._AvantMetrics || []
  window._AvantMetrics.push([
    'order',
    {
      order_id: order.transactionId,
      amount: order.transactionSubtotal + order.transactionDiscounts, // (Sum because discounts are negative)
      state: order.visitorAddressState,
      country: order.visitorAddressCountry,
      tax: order.transactionTax,
      shipping: order.transactionShipping,
      currency: order.currency,
    },
  ])

  order.transactionProducts.forEach(product => {
    window._AvantMetrics.push([
      'item',
      {
        order_id: order.transactionId,
        parent_sku: product.id,
        variant_sku: product.sku,
        price: product.price,
        qty: product.quantity,
      },
    ])
  })
}

if (canUseDOM) {
  window.addEventListener('message', handleMessages)
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of avantlink/store/interfaces.json from the avantlink VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "pixel.avantlink": {
    "component": "index"
  }
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of avantlink/react/typings/events.d.ts from the avantlink VTEX app.

[Assistant]
Here's the implementation:

```typescript
export interface PixelMessage extends MessageEvent {
  data: OrderPlacedData | PageViewData
}

export interface EventData {
  event: string
  eventName: string
  currency: string
}

export interface PageViewData extends EventData {
  event: 'pageView'
  eventName: 'vtex:pageView'
  pageTitle: string
  pageUrl: string
  referrer: string
}

export interface OrderPlacedData extends Order, EventData {
  event: 'orderPlaced'
  eventName: 'vtex:orderPlaced'
}

export interface Order {
  currency: string
  accountName: string
  orderGroup: string
  salesChannel: string
  coupon: string
  visitorType: string
  visitorContactInfo: string[]
  visitorAddressState: string
  visitorAddressCountry: string
  visitorAddressPostalCode: string
  transactionId: string
  transactionDate: string
  transactionAffiliation: string
  transactionTotal: number
  transactionShipping: number
  transactionSubtotal: number
  transactionDiscounts: number
  transactionTax: number
  transactionCurrency: string
  transactionPaymentType: PaymentType[]
  transactionShippingMethod: ShippingMethod[]
  transactionProducts: ProductOrder[]
  transactionPayment: {
    id: string
  }
}

interface PaymentType {
  group: string
  paymentSystemName: string
  installments: number
  value: number
}

interface ShippingMethod {
  itemId: string
  selectedSla: string
}

interface ProductOrder {
  id: string
  name: string
  sku: string
  skuRefId: string
  skuName: string
  brand: string
  brandId: string
  seller: string
  sellerId: string
  category: string
  categoryId: string
  categoryTree: string[]
  categoryIdTree: string[]
  priceTags: PriceTag[]
  originalPrice: number
  price: number
  sellingPrice: number
  tax: number
  quantity: number
  components: any[]
  measurementUnit: string
  unitMultiplier: number
}

interface PriceTag {
  identifier: string
  isPercentual: boolean
  value: number
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of avantlink/react/typings/vtex.render-runtime.d.ts from the avantlink VTEX app.

[Assistant]
Here's the implementation:

```typescript
declare module 'vtex.render-runtime' {
  export const canUseDOM: boolean
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of avantlink/react/typings/global.d.ts from the avantlink VTEX app.

[Assistant]
Here's the implementation:

```typescript
interface Window extends Window {
  _AvantMetrics: AvantMetric[]
  __avantlink_siteId: string
}

type AvantMetric = ['order', OrderMetric] | ['item', ItemMetric]

interface OrderMetric {
  // should be replaced with the actual id/number that uniquely identifies this order.
  order_id: string
  // should be replaced with the dollar amount total for this order, not including tax or shipping and handling fees. Should be formatted as a decimal number without dollar sign or commas. It should be noted that the order amount must be above 0 for that sale to record as an affiliate sale.
  amount: number
  // should be replaced with the U.S. state associated with the order’s billing address; preferably the standard (e.g. U.S. Postal Service) 2-letter abbreviation for the state.
  state: string
  // should be replaced with the country associated with the order’s billing address; preferably the 2- or 3-letter ISO 3166 country code.
  country: string
  // Exclusive coupon code(s) can be supplied if one or more coupon codes were used for the order. This element isn't required, but it is encouraged. This data provides the capability of merchants to associate a coupon code to particular affiliates.
  ecc?: string
  // Custom affiliate commission can be supplied for solutions that require highly customized logic for computing the commission due for a particular order.
  ac?: string
  // Custom network commission can be supplied for solutions that require highly customized logic for computing the commission due for a particular order.
  nc?: string
  // Can be used to specify the dollar amount (in decimal format, no dollar sign, no commas) of tax charged for this order.
  tax?: number
  // Can be used to specify the dollar amount (in decimal format, no dollar sign, no commas) of shipping and handling fees charged for this order.
  shipping?: number
  // Can be used to specify the currency type to be used for this transaction, if different than the default; must be specified as a 3-letter ISO 4217 currency code
  currency?: string
  // Can be used to specify whether the customer is new or returning; must be “Y” or “N”. While this isn't a required element we recommend that this value be provided as it allows for merchants to give a bump to affiliates on sales from new customers, thus encouraging affiliates to market to new customers.
  new_customer?: 'Y' | 'N'
}

interface ItemMetric {
  // should be replaced with the actual id/number that uniquely identifies this order.
  order_id: string
  // should be replaced with the parent-level unique identifier (commonly called a SKU) for each item. This SKU should agree with any product SKUs provided in the product datafeed for your program.
  parent_sku: string
  // should be replaced with the variant-level (a.k.a. child-level) unique identifier for each item. This identifier is more specific (generally down to the size/color/style level) than the parent-level SKU mentioned above. If variant-level details are included in the product datafeed, then this value can/should agree with the individual variant-level identifiers.
  variant_sku: string
  // should be replaced with the per-item price (in decimal format, no dollar sign, no commas) for each item.
  price: number
  // should be replaced with the number representing how many of this particular item were ordered. If this product doesn't have an associated variant sku please leave this field blank, as if our system finds a blank variant_sku value the parent SKU will be used.
  qty: number
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of starter.node-service/src/routes.ts from the starter.node-service VTEX app.

[Assistant]
Here's the implementation:

```typescript
import Router from 'koa-router'

import CallVtexApiExampleController from './controllers/call-vtex-api-example.controller'
import HealthCheckController from './controllers/healthcheck.controller'
import IndexController from './controllers/index.controller'
import PrivateController from './controllers/private.controller'
import authorization from './middlewares/authorization.middleware'

const router = new Router()

router.get('/', IndexController.getIndex)

router.get('/private', authorization, PrivateController.getPrivate)

router.get('/category/1', CallVtexApiExampleController.getProductCategory)

router.get('/healthcheck', HealthCheckController.getHealthCheck)

export default router

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of starter.node-service/src/index.ts from the starter.node-service VTEX app.

[Assistant]
Here's the implementation:

```typescript
import dotenv from 'dotenv'

// dotenv config must be loaded before anything else
dotenv.config({ path: './src/.env' })

// eslint-disable-next-line import/first
import { app, server } from './server'

export { app, server }

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of starter.node-service/src/server.ts from the starter.node-service VTEX app.

[Assistant]
Here's the implementation:

```typescript
import type { ClientsConfig } from '@vtex/api'
import { TracerSingleton } from '@vtex/api/lib/service/tracing/TracerSingleton'
import Koa from 'koa'

// import graphqlHTTP from 'koa-graphql'

// import { GraphqlSchema } from './graphql/graphql.schema'
// import { graphQlResolvers } from './graphql/resolvers/graphql.resolvers'
import { Clients } from './clients'
import { defaultMiddlewares } from './middlewares'
import { defaultClientOptions } from './middlewares/default-configuration.constants'
import router from './routes'

const app = new Koa()
const port = process.env.PORT ?? 8080

const clients: ClientsConfig<Clients> = {
  implementation: Clients,
  options: {
    ...defaultClientOptions,

    // You can add specific options for each client here
    catalog: {
      timeout: 1000,
    },
  },
}

const middlewares = defaultMiddlewares(clients)

middlewares.forEach((middleware) => app.use(middleware))

app.use(router.routes())

// router.all(
//   '/graphql',
//   graphqlHTTP({
//     schema: GraphqlSchema,
//     rootValue: graphQlResolvers,
//     graphiql: !configuration.isProd(),
//   })
// )

// app.use(router.routes()).use(router.allowedMethods())

const server = app.listen(port, () => {
  console.log(`App listening on the port ${port}`)
})

declare module 'opentracing' {
  interface Tracer {
    close(): void
  }
}

server.on('close', () => {
  const tracer = TracerSingleton.getTracer()

  tracer.close()
})

export { app, server }

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of starter.node-service/src/clients/index.ts from the starter.node-service VTEX app.

[Assistant]
Here's the implementation:

```typescript
import { IOClients } from '@vtex/api'
import { Catalog } from '@vtex/clients'

// Extend the default IOClients implementation with addional clients
export class Clients extends IOClients {
  public get catalog() {
    return this.getOrSet('catalog', Catalog)
  }
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of starter.node-service/src/middlewares/authorization.middleware.ts from the starter.node-service VTEX app.

[Assistant]
Here's the implementation:

```typescript
import { StatusCodes } from 'http-status-codes'
import type { Next, Context } from 'koa'
import axios from 'axios'

const authorizationMiddleware = async (ctx: Context, next: Next) => {
  // TODO migrate middleware to npm lib
  const CREDENTIALS_VALIDATION_ENDPOINT = '/auth/users/validate'

  const headers = {
    'x-vtex-api-appkey': process.env.VTEX_APP_KEY ?? '',
    'x-vtex-api-apptoken': process.env.VTEX_APP_TOKEN ?? '',
  }

  const data = createDataFromRequesterCredentials(ctx)

  if (!data) {
    ctx.throw(StatusCodes.UNAUTHORIZED)
  }

  const request = await axios.post(CREDENTIALS_VALIDATION_ENDPOINT, data, {
    headers,
    baseURL: process.env.APPS_FRAMEWORK_API_HOST,
    responseType: 'json',
  })

  if (request.status !== StatusCodes.OK) {
    ctx.throw(StatusCodes.FORBIDDEN)
  }

  await next()
}

function createDataFromRequesterCredentials(
  ctx: Context
): ValidateCredentialsPayload {
  let data: ValidateCredentialsPayload = {}

  if (ctx.headers.authorization) {
    data = {
      authToken: ctx.headers.authorization,
    }
  } else if (ctx.headers.vtexidclientautcookie) {
    data = {
      authToken: ctx.headers.vtexidclientautcookie as string,
    }
  } else if (ctx.cookies.get('VtexIdclientAutCookie')) {
    data = {
      authToken: ctx.cookies.get('VtexIdclientAutCookie') as string,
    }
  } else if (ctx.headers.vtexAppKey && ctx.headers.vtexAppToken) {
    data = {
      vtexAppKey: ctx.headers.vtexAppKey as string,
      vtexAppToken: ctx.headers.vtexAppToken as string,
    }
  }

  return data
}

export interface ValidateCredentialsPayload {
  authToken?: string
  vtexAppKey?: string
  vtexAppToken?: string
}

export default authorizationMiddleware

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of starter.node-service/src/middlewares/route-type.middleware.ts from the starter.node-service VTEX app.

[Assistant]
Here's the implementation:

```typescript
import koaCompose from 'koa-compose'
import type { Context, Middleware, Next } from 'koa'

export type RouteType = 'system' | 'app'

const SYSTEM_ROUTES = ['/healthcheck']

const getRouteType = (ctx: Context): RouteType => {
  if (SYSTEM_ROUTES.includes(ctx.request.path)) {
    return 'system'
  }

  return 'app'
}

export type MiddlewaresByRouteType<T extends Context> = Record<
  RouteType,
  Array<Middleware<unknown, T, unknown>>
>

export const addExecuteMiddlewaresForRouteType = <T extends Context>(
  middlewaresByRouteType: MiddlewaresByRouteType<T>
) => {
  return async function executeMiddlwaresForRouteType(ctx: T, next: Next) {
    const routeType = getRouteType(ctx)
    const middlewares = middlewaresByRouteType[routeType]
    const middleware = koaCompose(middlewares)

    await middleware(ctx, next)
  }
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of starter.node-service/src/middlewares/fetch-app-token.middleware.ts from the starter.node-service VTEX app.

[Assistant]
Here's the implementation:

```typescript
import type { Context, Next } from 'koa'
import axios from 'axios'
import { ACCOUNT_HEADER, CREDENTIAL_HEADER } from '@vtex/api'

export const fetchAppTokenMiddleware = async (ctx: Context, next: Next) => {
  const headers = {
    'x-vtex-api-appkey': process.env.VTEX_APP_KEY ?? '',
    'x-vtex-api-apptoken': process.env.VTEX_APP_TOKEN ?? '',
  }

  const accountName = ctx.headers[ACCOUNT_HEADER] as string

  try {
    const request = await axios.get(`auth/accounts/${accountName}/jwt`, {
      headers,
      baseURL: process.env.APPS_FRAMEWORK_API_HOST,
      responseType: 'json',
    })

    // set request header for future middlewares
    ctx.header[CREDENTIAL_HEADER] = request.data.jwt
  } catch (e) {
    console.error(e)
  }

  await next()
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of starter.node-service/src/middlewares/app-routes.middleware.ts from the starter.node-service VTEX app.

[Assistant]
Here's the implementation:

```typescript
/* eslint-disable max-params */
import type { ClientsConfig, IOClients } from '@vtex/api'
import { authTokens } from '@vtex/api/lib/service/worker/runtime/http/middlewares/authTokens'
import { cancellationToken } from '@vtex/api/lib/service/worker/runtime/http/middlewares/cancellationToken'
import { clients } from '@vtex/api/lib/service/worker/runtime/http/middlewares/clients'
import { perMinuteRateLimiter } from '@vtex/api/lib/service/worker/runtime/http/middlewares/rateLimit'
import { trackIncomingRequestStats } from '@vtex/api/lib/service/worker/runtime/http/middlewares/requestStats'
import { removeSetCookie } from '@vtex/api/lib/service/worker/runtime/http/middlewares/setCookie'
// import { timings } from '@vtex/api/lib/service/worker/runtime/http/middlewares/timings'
import { vary } from '@vtex/api/lib/service/worker/runtime/http/middlewares/vary'
import { traceUserLandRemainingPipelineMiddleware } from '@vtex/api/lib/service/tracing/tracingMiddlewares'
import koaCompose from 'koa-compose'

import { nameSpanOperationMiddleware } from './tracing.middleware'
import { createContextMiddleware } from './context.middleware'
import { globalLimiter } from './default-configuration.constants'
import { fetchAppTokenMiddleware } from './fetch-app-token.middleware'
import { validateExpectedHeaders } from './validate-expected-headers.middleware'

export const createAppRoutesMiddleware = <T extends IOClients>(
  clientsConfig: ClientsConfig<T>
) => {
  const { implementation, options } = clientsConfig

  const middlewares = [
    validateExpectedHeaders,
    fetchAppTokenMiddleware,
    nameSpanOperationMiddleware(),
    createContextMiddleware(),
    cancellationToken,
    trackIncomingRequestStats,
    vary,
    authTokens,
    // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
    clients(implementation!, options),
    // TODO understand what is service settings
    // ...(serviceRoute.settingsType === 'workspace' ||
    // serviceRoute.settingsType === 'userAndWorkspace'
    //   ? [getServiceSettings()]
    //   : []),
    removeSetCookie,
    // TODO timings requires the compose function to set timings in the context
    // timings,
    // TODO if param is undefined, concurrentRateLimiter is noop
    // concurrentRateLimiter(serviceRoute?.rateLimitPerReplica?.concurrent),
    perMinuteRateLimiter(undefined, globalLimiter),
    traceUserLandRemainingPipelineMiddleware(),
  ]

  return koaCompose(middlewares)
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of starter.node-service/src/middlewares/context.middleware.ts from the starter.node-service VTEX app.

[Assistant]
Here's the implementation:

```typescript
import type {
  ParamsContext,
  RecorderState,
  ServiceContext,
  IOClients,
} from '@vtex/api'
import { prepareHandlerCtx } from '@vtex/api/lib/service/worker/runtime/utils/context'

import { getRouteId } from '../utils/context.utils'

export const createContextMiddleware = () => {
  return async function pvtContext<
    T extends IOClients,
    U extends RecorderState,
    V extends ParamsContext
  >(ctx: ServiceContext<T, U, V>, next: () => Promise<void>) {
    const {
      params,
      request: { header },
    } = ctx

    const routeId = getRouteId(ctx)

    ctx.vtex = {
      // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
      ...prepareHandlerCtx(header, ctx.tracing!),
      // TODO ...(smartcache && { recorder: ctx.state.recorder }),
      route: {
        id: routeId,
        params,
        type: 'private',
      },
    }
    await next()
  }
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of starter.node-service/src/middlewares/tracing.middleware.ts from the starter.node-service VTEX app.

[Assistant]
Here's the implementation:

```typescript
import type { ServiceContext } from '@vtex/api'

import { getRouteId } from '../utils/context.utils'

export const nameSpanOperationMiddleware = () => {
  return function nameSpanOperation(
    ctx: ServiceContext,
    next: () => Promise<void>
  ) {
    const operationType = 'app-route-handler'

    const operationName = getRouteId(ctx)

    ctx.tracing?.currentSpan.setOperationName(
      `${operationType}:${operationName}`
    )

    return next()
  }
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of starter.node-service/src/middlewares/default-configuration.constants.ts from the starter.node-service VTEX app.

[Assistant]
Here's the implementation:

```typescript
import { createTokenBucket } from '@vtex/api/lib/service/worker/runtime/utils/tokenBucket'
import type { ClientsConfig, InstanceOptions } from '@vtex/api'
import { IOClients } from '@vtex/api'

export const globalLimiter = createTokenBucket()

export const defaultClientOptions: Record<string, InstanceOptions> = {
  messages: {
    concurrency: 10,
    retries: 2,
    timeout: 1000,
  },
  messagesGraphQL: {
    concurrency: 10,
    retries: 2,
    timeout: 1000,
  },
}

export const defaultClients: ClientsConfig = {
  implementation: IOClients,
  options: defaultClientOptions,
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of starter.node-service/src/middlewares/index.ts from the starter.node-service VTEX app.

[Assistant]
Here's the implementation:

```typescript
import type { ClientsConfig, ServiceContext } from '@vtex/api'
import { TracerSingleton } from '@vtex/api/lib/service/tracing/TracerSingleton'
import { addTracingMiddleware } from '@vtex/api/lib/service/tracing/tracingMiddlewares'
import bodyParser from 'koa-bodyparser'
import cors from '@koa/cors'
import helmet from 'koa-helmet'
import json from 'koa-json'
import logger from 'koa-logger'

import configuration from '../utils/configuration.utils'
import { defaultClients } from './default-configuration.constants'
import { createAppRoutesMiddleware } from './app-routes.middleware'
// eslint-disable-next-line @typescript-eslint/consistent-type-imports
import {
  addExecuteMiddlewaresForRouteType,
  MiddlewaresByRouteType,
} from './route-type.middleware'

export const defaultMiddlewares = (clients: ClientsConfig = defaultClients) => {
  const tracer = TracerSingleton.getTracer()

  const middlewaresForRouteType: MiddlewaresByRouteType<ServiceContext> = {
    app: [createAppRoutesMiddleware(clients)],
    system: [],
  }

  const middlewares = [
    helmet({
      // CSP is disabled in development to allow access to GraphiQL UI
      contentSecurityPolicy: configuration.isProd(),
    }),
    cors(),
    json(),
    bodyParser(),
    addTracingMiddleware(tracer),
    addExecuteMiddlewaresForRouteType(middlewaresForRouteType),
  ]

  if (!configuration.isProd()) {
    middlewares.push(logger())
  }

  return middlewares
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of starter.node-service/src/middlewares/validate-expected-headers.middleware.ts from the starter.node-service VTEX app.

[Assistant]
Here's the implementation:

```typescript
import type { Context, Next } from 'koa'
import { ACCOUNT_HEADER } from '@vtex/api'

export const validateExpectedHeaders = async (ctx: Context, next: Next) => {
  if (!ctx.header[ACCOUNT_HEADER]) {
    ctx.throw(400, `Missing ${ACCOUNT_HEADER} header`)
  }

  await next()
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of starter.node-service/src/utils/configuration.utils.ts from the starter.node-service VTEX app.

[Assistant]
Here's the implementation:

```typescript
import { ENVIRONMENT } from './configuration.constants'

export default class ConfigurationUtils {
  public static isProd(): boolean {
    return !(
      process.env.NODE_ENV === ENVIRONMENT.development ||
      process.env.NODE_ENV === ENVIRONMENT.test
    )
  }
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of starter.node-service/src/utils/context.utils.ts from the starter.node-service VTEX app.

[Assistant]
Here's the implementation:

```typescript
import type { Context } from 'koa'

export const getRouteId = (ctx: Context): string => {
  return `${ctx.method}-${ctx.path}`
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of starter.node-service/src/utils/configuration.constants.ts from the starter.node-service VTEX app.

[Assistant]
Here's the implementation:

```typescript
export const ENVIRONMENT = {
  development: 'development',
  production: 'production',
  test: 'test',
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of starter.node-service/src/__tests__/e2e.test.ts from the starter.node-service VTEX app.

[Assistant]
Here's the implementation:

```typescript
import request from 'supertest'
import { StatusCodes } from 'http-status-codes'
import axios from 'axios'
import type { Catalog, Category } from '@vtex/clients'

import { app, server } from '../index'

jest.mock('axios')
const mockedAxios = axios as jest.Mocked<typeof axios>

jest.mock('@vtex/clients', () => {
  const originalModule = jest.requireActual('@vtex/clients')

  return {
    __esModule: true,
    ...originalModule,
    Catalog: jest.fn(
      (): Partial<Catalog> => ({
        getCategoryById: jest.fn((categoryId: string) => {
          return Promise.resolve({
            Id: categoryId,
          } as Category)
        }),
      })
    ),
  }
})

describe('Index Route', () => {
  beforeEach(() => {
    mockedAxios.get.mockResolvedValue({ status: 200, data: { jwt: 'token' } })
  })
  it('returns status code 200', async () => {
    const response = await request(app.callback())
      .get('/')
      .set('x-vtex-account', 'account')

    expect(response.status).toBe(StatusCodes.OK)
  })
})

describe('Call VTEX API Route', () => {
  beforeEach(() => {
    mockedAxios.get.mockResolvedValue({ status: 200, data: { jwt: 'token' } })
  })
  it('returns status code 200', async () => {
    const response = await request(app.callback())
      .get('/category/1')
      .set('x-vtex-account', 'account')

    expect(response.status).toBe(StatusCodes.OK)
    expect(response.body.Id).toBe('1')
  })
})

// TODO - Add tests once graphql is implemented
// eslint-disable-next-line jest/no-disabled-tests
describe.skip('GraphQL queries', () => {
  beforeEach(() => {
    mockedAxios.get.mockResolvedValue({ status: 200, data: { jwt: 'token' } })
  })
  it('returns Hello World data', async () => {
    const response = await request(app.callback())
      .post('/graphql')
      .set('Content-Type', 'application/json')
      .set('x-vtex-account', 'account')
      .send({ query: '{ hello }' })

    expect(response.status).toBe(StatusCodes.OK)
    expect(response.body.data.hello).toBe('Hello world!')
  })
})

describe('HealthCheck Route', () => {
  beforeEach(() => {
    mockedAxios.get.mockResolvedValue({ status: 200, data: { jwt: 'token' } })
  })
  it('returns status code 200', async () => {
    const response = await request(app.callback())
      .get('/healthcheck')
      .set('x-vtex-account', 'account')

    expect(response.status).toBe(StatusCodes.OK)
  })
})

describe('Private Route', () => {
  beforeEach(() => {
    mockedAxios.get.mockResolvedValue({ status: 200, data: { jwt: 'token' } })
  })

  it('returns status code 200 when external validation of credential passes', async () => {
    mockedAxios.post.mockResolvedValue({ status: 200 })
    const response = await request(app.callback())
      .get('/private')
      .set('x-vtex-account', 'account')

    expect(response.status).toBe(StatusCodes.OK)
    expect(response.text).toBe(
      'This is a private route. It requires valid credentials in order to access it'
    )
  })

  it('returns status code 403 when external validation of credential fails', async () => {
    mockedAxios.post.mockResolvedValue({ status: 400 })

    const response = await request(app.callback())
      .get('/private')
      .set('x-vtex-account', 'account')

    expect(response.status).toBe(StatusCodes.FORBIDDEN)
  })
})

afterAll(() => {
  server.close()
})

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of starter.node-service/src/graphql/graphql.schema.ts from the starter.node-service VTEX app.

[Assistant]
Here's the implementation:

```typescript
import { buildSchema } from 'graphql'

export const GraphqlSchema = buildSchema(`
  type Query {
    hello: String
  }
`)

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of starter.node-service/src/controllers/healthcheck.controller.ts from the starter.node-service VTEX app.

[Assistant]
Here's the implementation:

```typescript
import type { BaseContext } from 'koa'
import { StatusCodes } from 'http-status-codes'

export default class HealthCheckController {
  public static async getHealthCheck(ctx: BaseContext) {
    ctx.status = StatusCodes.OK
  }
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of starter.node-service/src/controllers/call-vtex-api-example.controller.ts from the starter.node-service VTEX app.

[Assistant]
Here's the implementation:

```typescript
import type { Context } from 'koa'
import { StatusCodes } from 'http-status-codes'

import type { Clients } from '../clients'

export default class CallVtexApiExampleController {
  public static async getProductCategory(ctx: Context) {
    const { catalog } = <Clients>ctx.clients

    const category = await catalog.getCategoryById('1')

    ctx.status = StatusCodes.OK
    ctx.body = category
  }
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of starter.node-service/src/controllers/index.controller.ts from the starter.node-service VTEX app.

[Assistant]
Here's the implementation:

```typescript
import type { Context } from 'koa'
import { StatusCodes } from 'http-status-codes'

export default class IndexController {
  public static async getIndex(ctx: Context) {
    ctx.status = StatusCodes.OK
  }
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of starter.node-service/src/controllers/private.controller.ts from the starter.node-service VTEX app.

[Assistant]
Here's the implementation:

```typescript
import type { BaseContext } from 'koa'
import { StatusCodes } from 'http-status-codes'

export default class PrivateController {
  public static async getPrivate(ctx: BaseContext) {
    ctx.status = StatusCodes.OK
    ctx.body =
      'This is a private route. It requires valid credentials in order to access it'
  }
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of starter.node-service/src/__tests__/middlewares/route-type.middleware.test.ts from the starter.node-service VTEX app.

[Assistant]
Here's the implementation:

```typescript
import type { ServiceContext } from '@vtex/api'
import type { Context, Next } from 'koa'
import compose from 'koa-compose'

import type { MiddlewaresByRouteType } from '../../middlewares/route-type.middleware'
import { addExecuteMiddlewaresForRouteType } from '../../middlewares/route-type.middleware'

jest.mock('koa-compose')
const mockedCompose = compose as jest.MockedFunction<typeof compose>

describe('Route type resolver middlewarew', () => {
  const runTest = async (
    routePath: string,
    middlewaresByRouteType: MiddlewaresByRouteType<Context>
  ) => {
    mockedCompose.mockReturnValue((_ctx: unknown, _next?: Next) =>
      Promise.resolve()
    )

    const middleware = addExecuteMiddlewaresForRouteType(middlewaresByRouteType)

    expect(middleware).toBeDefined()

    const ctx = {
      request: {
        method: 'GET',
        path: routePath,
      },
    } as ServiceContext

    const next = jest.fn()

    await middleware(ctx, next)
  }

  it('should add middlewares for an app route type', async () => {
    const middlewaresByRouteType: MiddlewaresByRouteType<Context> = {
      app: [(_ctx: Context, _next: Next) => Promise.resolve()],
      system: [],
    }

    await runTest('/', middlewaresByRouteType)

    expect(mockedCompose).toBeCalledWith(middlewaresByRouteType.app)
  })

  it('should add middlewares for an system route type', async () => {
    const middlewaresByRouteType: MiddlewaresByRouteType<Context> = {
      app: [],
      system: [(_ctx: Context, _next: Next) => Promise.resolve()],
    }

    await runTest('/healthcheck', middlewaresByRouteType)

    expect(mockedCompose).toBeCalledWith(middlewaresByRouteType.system)
  })
})

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of starter.node-service/src/__tests__/middlewares/tracing.middleware.test.ts from the starter.node-service VTEX app.

[Assistant]
Here's the implementation:

```typescript
import { Span } from '@vtex/api'
import type { ServiceContext } from '@vtex/api'

import { nameSpanOperationMiddleware } from '../../middlewares/tracing.middleware'

describe('Tracing middleware', () => {
  it('should set tracing context operation name', async () => {
    const middleware = nameSpanOperationMiddleware()

    const span = new Span()

    const ctx = {
      method: 'GET',
      path: '/the-path',
      tracing: {
        currentSpan: span,
      },
    } as ServiceContext

    const next = jest.fn()

    const spanSpyInstance = jest.spyOn(span, 'setOperationName')

    await middleware(ctx, next)

    expect(spanSpyInstance).toHaveBeenCalledTimes(1)
    expect(spanSpyInstance).toHaveBeenLastCalledWith(
      'app-route-handler:GET-/the-path'
    )

    spanSpyInstance.mockRestore()
  })
})

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of starter.node-service/src/__tests__/middlewares/app-route.middleware.test.ts from the starter.node-service VTEX app.

[Assistant]
Here's the implementation:

```typescript
import { IOClients } from '@vtex/api'

import { createAppRoutesMiddleware } from '../../middlewares/app-routes.middleware'
import { defaultClientOptions } from '../../middlewares/default-configuration.constants'

describe('App Route specific middlewares', () => {
  it('should return a composed middlware for app route', () => {
    expect(
      createAppRoutesMiddleware({
        implementation: IOClients,
        options: defaultClientOptions,
      })
    ).toBeDefined()
  })
})

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of starter.node-service/src/__tests__/middlewares/authorization-middleware.test.ts from the starter.node-service VTEX app.

[Assistant]
Here's the implementation:

```typescript
import type { AxiosRequestConfig } from 'axios'
import axios from 'axios'
import type { Context } from 'koa'

import type { ValidateCredentialsPayload } from '../../middlewares/authorization.middleware'
import authorization from '../../middlewares/authorization.middleware'

jest.mock('axios')
const mockedAxios = axios as jest.Mocked<typeof axios>

describe('Authorization Middleware', () => {
  const thisAppKey = 'thisAppKey'
  const thisAppToken = 'thisAppToken'

  afterEach(() => {
    jest.resetAllMocks()
  })

  it('throw 403', async () => {
    const ctx: Partial<Context> = {
      status: undefined,
      headers: { authorization: undefined },
      throw: jest.fn() as any,
      cookies: { get: jest.fn() } as any,
    }

    mockedAxios.post.mockResolvedValue({ status: 400 })

    await authorization(ctx as Context, jest.fn())
    expect(ctx.throw).toBeCalledWith(403)
  })

  it('forward jwt token from auth header to post body', async () => {
    process.env.VTEX_APP_KEY = thisAppKey
    process.env.VTEX_APP_TOKEN = thisAppToken
    const authorizationToken = 'token'

    const ctx: Partial<Context> = {
      status: undefined,
      headers: { authorization: authorizationToken },
    }

    const { mock } = mockedAxios.post

    mockedAxios.post.mockResolvedValue({ status: 200 })

    await authorization(ctx as Context, jest.fn())

    const data = mock.calls[0][1] as ValidateCredentialsPayload
    const { headers } = mock.calls[0][2] as AxiosRequestConfig

    expect(data).toStrictEqual({ authToken: authorizationToken })
    expect(headers).toStrictEqual({
      'x-vtex-api-appkey': thisAppKey,
      'x-vtex-api-apptoken': thisAppToken,
    })
  })

  it('forwards appkey/apptoken from headers to post body', async () => {
    process.env.VTEX_APP_KEY = thisAppKey
    process.env.VTEX_APP_TOKEN = thisAppToken
    const thirdPartyAppKey = 'thirdPartyAppKey'
    const thirdPartyAppToken = 'thirdPartyAppToken'

    const ctx: Partial<Context> = {
      status: undefined,
      headers: {
        vtexAppKey: thirdPartyAppKey,
        vtexAppToken: thirdPartyAppToken,
      },
      cookies: { get: jest.fn() } as any,
    }

    const { mock } = mockedAxios.post

    mockedAxios.post.mockResolvedValue({ status: 200 })

    await authorization(ctx as Context, jest.fn())

    const data = mock.calls[0][1] as ValidateCredentialsPayload
    const { headers } = mock.calls[0][2] as AxiosRequestConfig

    expect(data).toStrictEqual({
      vtexAppKey: thirdPartyAppKey,
      vtexAppToken: thirdPartyAppToken,
    })
    expect(headers).toStrictEqual({
      'x-vtex-api-appkey': thisAppKey,
      'x-vtex-api-apptoken': thisAppToken,
    })
  })
})

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of starter.node-service/src/__tests__/middlewares/fetch-app-token-middleware.test.ts from the starter.node-service VTEX app.

[Assistant]
Here's the implementation:

```typescript
import type { AxiosRequestConfig } from 'axios'
import axios from 'axios'
import type { Context } from 'koa'

import { fetchAppTokenMiddleware } from '../../middlewares/fetch-app-token.middleware'

jest.mock('axios')
const mockedAxios = axios as jest.Mocked<typeof axios>

describe('Fetch App Token Middleware', () => {
  const thisAppKey = 'thisAppKey'
  const thisAppToken = 'thisAppToken'

  afterEach(() => {
    jest.resetAllMocks()
  })

  it('should set headers and fetch JWT token', async () => {
    process.env.VTEX_APP_KEY = thisAppKey
    process.env.VTEX_APP_TOKEN = thisAppToken
    const authorizationToken = 'JWT-Bearer-Token'
    const accountName = 'storecomponents'

    const ctx: Partial<Context> = {
      status: undefined,
      headers: {
        authorization: authorizationToken,
        'x-vtex-account': accountName,
      },
      header: {},
    }

    const { mock } = mockedAxios.get

    mockedAxios.get.mockResolvedValue({
      status: 200,
      data: { jwt: authorizationToken },
    })

    await fetchAppTokenMiddleware(ctx as Context, jest.fn())

    const { headers } = mock.calls[0][1] as AxiosRequestConfig

    expect(mock.calls[0][0]).toBe(`auth/accounts/${accountName}/jwt`)
    expect(headers).toStrictEqual({
      'x-vtex-api-appkey': thisAppKey,
      'x-vtex-api-apptoken': thisAppToken,
    })
    expect(ctx.header?.['x-vtex-credential']).toBe(authorizationToken)
  })
})

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of starter.node-service/src/__tests__/middlewares/context.middleware.test.ts from the starter.node-service VTEX app.

[Assistant]
Here's the implementation:

```typescript
import type { ServiceContext } from '@vtex/api'
import type { Request } from 'koa'

import { createContextMiddleware } from '../../middlewares/context.middleware'

declare module 'http' {
  interface IncomingHttpHeaders {
    'x-vtex-account'?: string
    'x-vtex-credential'?: string
  }
}

jest.mock('@vtex/api/lib/tracing/UserLandTracer')

describe('Context middleware', () => {
  // eslint-disable-next-line jest/no-focused-tests
  it('should create a valid context middleware', async () => {
    const contextMiddleware = createContextMiddleware()
    const ctx = {
      tracing: {},
      request: {
        header: {
          'x-vtex-account': 'account',
          'x-vtex-credential': 'credential',
        },
      } as Request,
    } as ServiceContext

    const next = jest.fn()

    await contextMiddleware(ctx, next)

    expect(next).toBeCalled()

    const vtexContext = ctx.vtex

    expect(vtexContext).toBeDefined()
    expect(vtexContext.account).toBe('account')
    expect(vtexContext.authToken).toBe('credential')
  })
})

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of starter.node-service/src/__tests__/utils/context.utils.test.ts from the starter.node-service VTEX app.

[Assistant]
Here's the implementation:

```typescript
import type { Context } from 'koa'

import { getRouteId } from '../../utils/context.utils'

describe('Context utils', () => {
  it('should get route id with method and path', () => {
    expect(
      getRouteId({
        method: 'GET',
        path: '/route',
      } as Context)
    ).toBe('GET-/route')
  })
})

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of starter.node-service/src/graphql/resolvers/graphql.resolvers.ts from the starter.node-service VTEX app.

[Assistant]
Here's the implementation:

```typescript
export const graphQlResolvers = {
  hello: () => 'Hello world!',
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of amp-header/react/package.json from the amp-header VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "private": true,
  "dependencies": {
    "react": "^16.8.6",
    "react-amphtml": "^4.0.1",
    "react-dom": "^16.8.6"
  },
  "devDependencies": {
    "@types/node": "^12.7.0",
    "@types/react": "^16.9.2",
    "@types/react-dom": "^16.8.5",
    "@vtex/tsconfig": "^0.1.1"
  }
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of amp-header/react/Header.tsx from the amp-header VTEX app.

[Assistant]
Here's the implementation:

```tsx
import React from 'react'
import { IconSearch } from 'vtex.store-icons'
import { ExtensionPoint } from 'vtex.render-runtime'

const Header = () => {
  return (
    <React.Fragment>
      <header className="ph5 w-100 flex center justify-center pb4 pv2 bb bw1 b--muted-4">
        <div className="flex-wrap flex w-100 justify-between items-center">
          <ExtensionPoint id="category-menu" />
          <a className="pl3" href="/">
            store theme
          </a>
          <div className="ml-auto">
            <IconSearch />
          </div>
          <input
            className="w-100 ma0 border-box bw1 br2  b--solid outline-0 c-on-base bg-base b--muted-4 hover-b--muted-3 f5 pv4 ph6 pr8"
            type="text"
            placeholder="Buscar"
          />
        </div>
      </header>
    </React.Fragment>
  )
}

export default Header

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of amp-header/store/blocks.json from the amp-header VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "amp-header": {
    "blocks": [
      "category-menu"
    ]
  }
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of amp-header/store/interfaces.json from the amp-header VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "amp-header": {
    "component": "Header",
    "allowed": [
      "category-menu"
    ]
  }
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of amp-header/react/typings/vtex.store-icons.d.ts from the amp-header VTEX app.

[Assistant]
Here's the implementation:

```typescript
import React from 'react'

declare module 'vtex.store-icons' {
  export const IconHome: React.ComponentType<{}>

  export const IconSearch: React.ComponentType<{}>
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of mycheckout-checkout-service/test/app.e2e-spec.ts from the mycheckout-checkout-service VTEX app.

[Assistant]
Here's the implementation:

```typescript
import { Test, TestingModule } from '@nestjs/testing';
import { INestApplication } from '@nestjs/common';
import * as request from 'supertest';
import { AppModule } from 'src/app.module';

describe('AppController (e2e)', () => {
  let app: INestApplication;

  beforeEach(async () => {
    const moduleFixture: TestingModule = await Test.createTestingModule({
      imports: [AppModule],
    }).compile();

    app = moduleFixture.createNestApplication();
    await app.init();
  });

  it('/ (GET)', () => {
    return request(app.getHttpServer())
      .get('/get-all')
      .expect(200)
      .expect('[]');
  });
});

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of mycheckout-checkout-service/test/jest-e2e.json from the mycheckout-checkout-service VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "moduleFileExtensions": ["js", "json", "ts"],
  "rootDir": ".",
  "testEnvironment": "node",
  "testRegex": ".e2e-spec.ts$",
  "transform": {
    "^.+\\.(t|j)s$": "ts-jest"
  }
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of mycheckout-checkout-service/src/main.ts from the mycheckout-checkout-service VTEX app.

[Assistant]
Here's the implementation:

```typescript
import { NestFactory } from '@nestjs/core';
import { useContainer } from 'class-validator';
import * as bodyParser from 'body-parser';
import { AppModule } from './app.module';
import { ValidationPipe } from './shared/validation/validation.pipe';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.setGlobalPrefix(`api/checkout`);

  app.useGlobalPipes(
    new ValidationPipe({
      transform: true,
      transformOptions: {
        enableImplicitConversion: true,
      },
    }),
  );
  app.use(bodyParser.json({ limit: '50mb' }));
  app.use(bodyParser.urlencoded({ limit: '50mb', extended: true }));
  //for service in validator constraint
  useContainer(app.select(AppModule), { fallbackOnErrors: true });

  await app.listen(8080);
}
bootstrap();

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of mycheckout-checkout-service/src/app.module.ts from the mycheckout-checkout-service VTEX app.

[Assistant]
Here's the implementation:

```typescript
import i18nConfig from 'src/config/i18n';
import { Module } from '@nestjs/common';
import { I18nModule } from 'nestjs-i18n';
import { APP_FILTER, APP_INTERCEPTOR } from '@nestjs/core';
import { ConfigModule } from '@nestjs/config';
import { HealthController } from './app/health/health.controller';
import { AccountsModule } from './app/accounts/accounts.module';
import { UsersModule } from './app/users/users.module';
import { MastersModule } from './app/masters/masters.module';
import { OrdersModule } from './app/orders/orders.module';
import { VtexModule } from './app/vtex/vtex.module';
import { PaymentProvidersModule } from './app/payment-providers/payment-providers.module';
import { CommonModule } from './app/common/common.module';
import { ChannelsModule } from './app/channels/channels.module';
import { OmsModule } from './app/oms/oms.module';
import configuration from './config/configuration';
import { AllResponsesInterceptor } from './shared/responses/all-responses.interceptor';
import { AllExceptionsFilter } from './shared/responses/all-exceptions.filter';
import { ExistsRule } from './shared/validation/rules/exists.rule';
import dynamodbConfig from './config/dynamodb';
import { CustomDynamooseModule } from './shared/utils/dynamoose-module';

export const environment = process.env.NODE_ENV
  ? process.env.NODE_ENV
  : 'development';

export const isContainer = process.env.CONTAINER == 'docker';

@Module({
  imports: [
    /*General Modules*/
    CustomDynamooseModule.forRootAsync(dynamodbConfig()),
    ConfigModule.forRoot({
      ...(isContainer
        ? {
            envFilePath: ['/config/.env'],
            load: [configuration],
          }
        : {
            envFilePath: ['.env.local'],
          }),
      isGlobal: true,
    }),
    I18nModule.forRoot(i18nConfig()),
    /*Internal Modules*/
    OrdersModule,
    VtexModule,
    AccountsModule,
    UsersModule,
    MastersModule,
    PaymentProvidersModule,
    CommonModule,
    ChannelsModule,
    OmsModule,
  ],
  providers: [
    {
      provide: APP_INTERCEPTOR,
      useClass: AllResponsesInterceptor,
    },
    {
      provide: APP_FILTER,
      useClass: AllExceptionsFilter,
    },
    ExistsRule,
  ],
  controllers: [HealthController],
})
export class AppModule {}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of mycheckout-checkout-service/src/config/i18n.ts from the mycheckout-checkout-service VTEX app.

[Assistant]
Here's the implementation:

```typescript
import { I18nJsonParser } from 'nestjs-i18n';
import { join } from 'path';

export default () => ({
  fallbackLanguage: 'en',
  parser: I18nJsonParser,
  parserOptions: {
    path: join(__dirname, '../assets/lang/'),
    watch: true,
  },
});

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of mycheckout-checkout-service/src/config/dynamodb.ts from the mycheckout-checkout-service VTEX app.

[Assistant]
Here's the implementation:

```typescript
import { ConfigModule, ConfigService } from '@nestjs/config';
import {
  DynamooseModuleAsyncOptions,
  DynamooseModuleOptions,
} from 'nestjs-dynamoose';

export default (): DynamooseModuleAsyncOptions => ({
  imports: [ConfigModule],
  useFactory: async (
    config: ConfigService,
  ): Promise<DynamooseModuleOptions> => {
    const region = config.get<string>('DB_REGION', 'localhost');
    return {
      aws: {
        accessKeyId: config.get<string>('AWS_ACCESS_KEY_ID', 'ios2p9'),
        secretAccessKey: config.get<string>('AWS_SECRET_ACCESS_KEY', 'qj4ch9'),
        region: region,
      },
      model: { prefix: `${config.get<string>('DB', 'checkout')}.` },
      local: region == 'localhost',
    };
  },
  inject: [ConfigService],
});

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of mycheckout-checkout-service/src/config/configuration.ts from the mycheckout-checkout-service VTEX app.

[Assistant]
Here's the implementation:

```typescript
export default () => {
  if (!process.env.AWS_SECRET_ACCESS_KEY) {
    throw new Error('AWS_SECRET_ACCESS_KEY must be defined.');
  }
  if (!process.env.AWS_ACCESS_KEY_ID) {
    throw new Error('AWS_ACCESS_KEY_ID must be defined.');
  }
  if (!process.env.PAYMENTEZ_API_KEY) {
    throw new Error('PAYMENTEZ_API_KEY must be defined');
  }
  if (!process.env.PAYMENTEZ_API_TOKEN) {
    throw new Error('PAYMENTEZ_API_TOKEN must be defined');
  }
  if (!process.env.INFOBIP_APP_KEY) {
    throw new Error('INFOBIP_APP_KEY must be defined');
  }
  if (!process.env.MERCADOPAGO_ACCESS_TOKEN) {
    throw new Error('MERCADOPAGO_ACCESS_TOKEN must be defined');
  }
  if (!process.env.TWILIO_AUTH_TOKEN) {
    throw new Error('TWILIO_AUTH_TOKEN must be defined');
  }
  if (!process.env.JWT_TOKEN) {
    throw new Error('JWT_TOKEN must be defined');
  }
  if (!process.env.MAILER_VTEX_APP_KEY) {
    throw new Error('MAILER_VTEX_APP_KEY must be defined');
  }
  if (!process.env.MAILER_VTEX_APP_TOKEN) {
    throw new Error('MAILER_VTEX_APP_TOKEN must be defined');
  }
  if (!process.env.AWS_STYLES_BUCKET) {
    throw new Error('AWS_STYLES_BUCKET must be defined');
  }
  if (!process.env.AWS_STYLES_CF_DISTRIBUTION_ID) {
    throw new Error('AWS_STYLES_CF_DISTRIBUTION_ID must be defined');
  }
  return {
    AWS_SECRET_ACCESS_KEY: process.env.AWS_SECRET_ACCESS_KEY,
    AWS_ACCESS_KEY_ID: process.env.AWS_ACCESS_KEY_ID,
    PAYMENTEZ_API_KEY: process.env.PAYMENTEZ_API_KEY,
    PAYMENTEZ_API_TOKEN: process.env.PAYMENTEZ_API_TOKEN,
    INFOBIP_APP_KEY: process.env.INFOBIP_APP_KEY,
    MERCADOPAGO_ACCESS_TOKEN: process.env.MERCADOPAGO_ACCESS_TOKEN,
    TWILIO_AUTH_TOKEN: process.env.TWILIO_AUTH_TOKEN,
    JWT_TOKEN: process.env.JWT_TOKEN,
    MAILER_VTEX_APP_KEY: process.env.MAILER_VTEX_APP_KEY,
    MAILER_VTEX_APP_TOKEN: process.env.MAILER_VTEX_APP_TOKEN,
    AWS_STYLES_BUCKET: process.env.AWS_STYLES_BUCKET,
    AWS_STYLES_CF_DISTRIBUTION_ID: process.env.AWS_STYLES_CF_DISTRIBUTION_ID
  };
};

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of mycheckout-checkout-service/src/typings/OrderContext.d.ts from the mycheckout-checkout-service VTEX app.

[Assistant]
Here's the implementation:

```typescript
import { AccountDoc } from '../app/accounts/schemas/account.schema';
import { CustomDataDto } from '../app/orders/dtos/customData.dto';
import { ItemDto } from '../app/orders/dtos/item.dto';
import { LogisticInfoDto } from '../app/orders/dtos/logisticInfo.dto';
import { MarketingDataDto } from '../app/orders/dtos/marketingData.dto';
import { ProcessTransactionDto } from '../app/orders/dtos/processTransaction.dto';
import { OrderDoc } from '../app/orders/schemas/order.schema';
import { AddressDoc } from '../app/users/addresses/schemas/address.schema';
import { ProfileDoc } from '../app/users/profiles/schemas/profile.schema';
import { TransactionQueue } from './vtex/order';
import { ExternalAddressDto } from 'src/app/orders/dtos/externalAddress.dto';

interface OrderContext {
  profile?: ProfileDoc;
  addresses?: AddressDoc[];
  account?: AccountDoc;
  payment?: PaymentData;
  order?: OrderDoc;
  vtex?: Vtex;
  orderInfo?: OrderInfo;
  dataDto?: DataDTO;
  queueMessage?: Partial<TransactionQueue>;
  processTransactionDto?: ProcessTransactionDto;
  transaction?: Transaction;
  totalizers?: Totalizers;
  headers?: any;
}

interface Totalizers {
  totals?: number;
  shippingTotal?: number;
  subTotal?: number;
}

interface Transaction {
  transactionId: string;
  aliasCC?: string;
  aliasCVV?: string;
  cardContent?: unknown;
  internalCardContent?: unknown;
  gatewayCallbackResponse?: unknown;
  token?: string;
}

interface Vtex {
  simulation: CheckoutOrderForm;
  totals: number;
  shippingTotal: number;
  order?: any;
  checkoutCookie?: string;
  items: Item[];
  gifts?: Item[];
}

export interface Item {
  id: string;
  quantity: number;
  seller: string;
  priceTags: any[];
  offerings: any[];
  price: number;
  isGift: boolean;
}

interface DataDTO {
  channel: string;
  oms: string;
  profile: {
    email: string;
    habeasData?: boolean;
  };
  shipping: {
    addressId?: string;
    externalAddress?: ExternalAddressDto;
    logisticsInfo: LogisticInfoDto[];
  };
  account: {
    accountName: string;
    storePreferences: {
      countryCode: string;
      currencyCode: string;
      salesChannel: string;
    };
  };
  payment: {
    cardId?: string;
    token?: string;
    franchise?: string;
    number?: string;
    gateway: string;
    paymentMethod: string;
    paymentSystem?: string;
    additionalData?: unknown;
    cvv?: string;
    bin?: string;
    holderName?: string;
    holderDocument?: string;
    expirationDate?: string;
    cardNumber?: string;
  };
  items: ItemDto[];
  customData?: CustomDataDto;
  gifts?: ItemDto[];
  offerings?: Offering[];
  marketingData?: MarketingDataDto;
  authToken?: string;
}

interface OrderInfo {
  id: string;
  items?: any;
  logisticInfo?: any;
  total?: number;
  totalShipping?: number;
  orderId: string;
}

interface PaymentData {
  token?: string;
  franchise?: string;
  number?: string;
  gateway: string;
  additionalData?: unknown;
  bin?: string;
  cvv?: string;
  holderName?: string;
  holderDocument?: string;
  expirationDate?: string;
  cardNumber?: string;
  paymentSystem?: string;
  paymentMethod?: string;
}

interface Offering {
  id: string;
  parentItemId: string;
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of mycheckout-checkout-service/src/base/base-options.interface.ts from the mycheckout-checkout-service VTEX app.

[Assistant]
Here's the implementation:

```typescript
export interface IDecorators<K> {
  decorators?: { use: any; in: K[] }[];
}

export interface IPartialEntity<T> {
  partialEntity?: Partial<T>;
}

export interface BaseOptionsA<K, T> extends IDecorators<K>, IPartialEntity<T> {
  omit?: K[];
}

export interface BaseOptionsB<K, T> extends IDecorators<K>, IPartialEntity<T> {
  pick?: K[];
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of mycheckout-checkout-service/src/base/base-controller.interface.ts from the mycheckout-checkout-service VTEX app.

[Assistant]
Here's the implementation:

```typescript
import { PaginationDto } from './paginator/dto/pagination.dto';
import { PaginationResponse } from './paginator';
import { GeneralResponse } from '../shared/responses/general-response';

export interface IBaseController<T> {
  get(query: any): Promise<T>;
  getAll(paginationDto?: PaginationDto): Promise<PaginationResponse<T>>;
  create(data: T): Promise<T>;
  update(query: any, data: Partial<T>): Promise<GeneralResponse>;
  delete(query: any): Promise<GeneralResponse>;
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of mycheckout-checkout-service/src/base/base-service.interface.ts from the mycheckout-checkout-service VTEX app.

[Assistant]
Here's the implementation:

```typescript
import { PaginationDto } from './paginator/dto/pagination.dto';
import { PaginationResponse } from './paginator';
import { GeneralResponse } from '../shared/responses/general-response';

export interface IBaseService<T> {
  get(query: string): Promise<T>;
  getAll(paginationDto?: PaginationDto): Promise<PaginationResponse<T>>;
  getAllByQuery(query: string): Promise<any>;
  create(data: T): Promise<T>;
  update(query: string, data: Partial<T>, user?: any): Promise<GeneralResponse>;
  delete(query: string, user?: any): Promise<GeneralResponse>;
}

```