[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 admin-pages/react/components/admin/store/PWAForm/components/withPWAMutations.tsx from the admin-pages VTEX app.

[Assistant]
Here's the implementation:

```tsx
import React from 'react'
import { Mutation, MutationFn, MutationResult } from 'react-apollo'

import UpdateManifest from '../mutations/UpdateManifest.graphql'
import UpdateManifestIcon from '../mutations/UpdateManifestIcon.graphql'
import UpdatePWASettings from '../mutations/UpdatePWASettings.graphql'

import { PWASettings } from './withPWASettings'

export interface ManifestMutationData {
  start_url: string
  theme_color: string
  background_color: string
  display: string
  orientation: string
}

interface UpdateManifestData {
  manifest: ManifestMutationData
}

interface UpdateManifestVariables {
  manifest: ManifestMutationData
}

class UpdateManifestMutation extends Mutation<
  UpdateManifestData,
  UpdateManifestVariables
> {}

interface UpdateManifestIconVariables {
  icon: File
  iOS: boolean
}

class UpdateManifestIconMutation extends Mutation<
  UpdateManifestData,
  UpdateManifestIconVariables
> {}

interface UpdatePWASettingsData {
  settings: PWASettings
}

class UpdatePWASettingsMutation extends Mutation<
  PWASettings,
  UpdatePWASettingsData
> {}

export interface PWAMutationProps {
  updateManifest: {
    mutate: MutationFn<UpdateManifestData, UpdateManifestVariables>
  } & MutationResult<UpdateManifestData>
  updateManifestIcon: {
    mutate: MutationFn<UpdateManifestData, UpdateManifestIconVariables>
  } & MutationResult<UpdateManifestData>
  updatePWASettings: {
    mutate: MutationFn<PWASettings, UpdatePWASettingsData>
  } & MutationResult<PWASettings>
}

const withPWAMutations = <T extends {}>(
  WrappedComponent: React.ComponentType<T & PWAMutationProps>
) => {
  const ComponentWithPWAMutations = (props: T) => (
    <UpdateManifestMutation mutation={UpdateManifest}>
      {(updateManifestMutate, updateManifestRest) => (
        <UpdateManifestIconMutation mutation={UpdateManifestIcon}>
          {(updateManifestIconMutate, updateManifestIconRest) => (
            <UpdatePWASettingsMutation mutation={UpdatePWASettings}>
              {(updatePWASettingsMutate, updatePWASettingsRest) => (
                <WrappedComponent
                  {...props}
                  updateManifest={{
                    mutate: updateManifestMutate,
                    ...updateManifestRest,
                  }}
                  updateManifestIcon={{
                    mutate: updateManifestIconMutate,
                    ...updateManifestIconRest,
                  }}
                  updatePWASettings={{
                    mutate: updatePWASettingsMutate,
                    ...updatePWASettingsRest,
                  }}
                />
              )}
            </UpdatePWASettingsMutation>
          )}
        </UpdateManifestIconMutation>
      )}
    </UpdateManifestMutation>
  )

  return ComponentWithPWAMutations
}

export default withPWAMutations

```


[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 admin-pages/react/components/MediaGalleryWidget/icons/IconImage.tsx from the admin-pages VTEX app.

[Assistant]
Here's the implementation:

```tsx
import React from 'react'

interface Props {
  color?: string
}

const IconImage: React.FC<Props> = ({ color = 'currentColor' }) => (
  <svg
    width="23"
    height="20"
    viewBox="0 0 23 20"
    fill="none"
    xmlns="http://www.w3.org/2000/svg"
  >
    <path
      fill-rule="evenodd"
      clip-rule="evenodd"
      d="M3.50146 1.75C2.81068 1.75 2.25146 2.30921 2.25146 3V17C2.25146 17.5802 2.64596 18.0676 3.18156 18.2088L7.29428 13.2729C7.90488 12.5399 8.98838 12.4313 9.73207 13.0263L11.5996 14.5209C11.7085 14.6077 11.866 14.5897 11.952 14.4823L15.288 10.3123C15.8917 9.55808 16.9937 9.43542 17.7482 10.0394L20.7455 12.4371V3C20.7455 2.30921 20.1863 1.75 19.4955 1.75H3.50146ZM22.2455 13.9319V3C22.2455 1.48079 21.0147 0.25 19.4955 0.25H3.50146C1.98225 0.25 0.751465 1.48079 0.751465 3V17C0.751465 18.5192 1.98225 19.75 3.50146 19.75H19.4955C21.0134 19.75 22.2455 18.5195 22.2455 17V14.0689C22.2496 14.0232 22.2496 13.9774 22.2455 13.9319ZM20.7455 14.358L16.8111 11.2106C16.7037 11.1247 16.5455 11.1418 16.4592 11.2495L13.1232 15.4195C12.5193 16.174 11.4186 16.296 10.6635 15.693L8.79503 14.1976C8.68873 14.1127 8.5342 14.1281 8.44683 14.2329L5.09967 18.25H19.4955C20.1855 18.25 20.7455 17.6905 20.7455 17V14.358ZM8.38242 6.11612C7.89427 5.62796 7.10281 5.62796 6.61465 6.11612C6.1265 6.60427 6.1265 7.39573 6.61465 7.88389C7.10281 8.37204 7.89427 8.37204 8.38242 7.88389C8.87058 7.39573 8.87058 6.60427 8.38242 6.11612ZM9.44222 5.0546C8.36821 3.98151 6.62765 3.9818 5.55399 5.05546C4.48005 6.1294 4.48005 7.8706 5.55399 8.94455C6.62794 10.0185 8.36914 10.0185 9.44308 8.94455C10.517 7.8706 10.517 6.1294 9.44308 5.05546L9.44222 5.0546Z"
      fill={color}
    />
  </svg>
)

export default IconImage

```


[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 admin-pages/react/components/HighlightOverlay/OverlayMask/index.tsx from the admin-pages VTEX app.

[Assistant]
Here's the implementation:

```tsx
import React from 'react'
import { CSSTransition } from 'react-transition-group'
import styles from './OverlayMask.css'

interface Props {
  isActive: boolean
  style?: React.CSSProperties
}

const classNames = {
  enter: styles['overlay-mask-enter'],
  enterActive: styles['overlay-mask-enter-active'],
  enterDone: styles['overlay-mask-enter-done'],
  exit: styles['overlay-mask-exit'],
  exitActive: styles['overlay-mask-exit-active'],
  exitDone: styles['overlay-mask-exit-done'],
}

const timeout = {
  enter: 300,
  exit: 150,
}

export default function OverlayMask({ style, isActive }: Props) {
  const overlayMaskStyle: React.CSSProperties = isActive
    ? {}
    : { pointerEvents: 'none' }

  return (
    <CSSTransition
      mountOnEnter
      in={isActive}
      timeout={timeout}
      classNames={classNames}
    >
      <div
        className="absolute bg-base h-100 w-100"
        style={{ ...overlayMaskStyle, ...style }}
      />
    </CSSTransition>
  )
}

```


[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 admin-pages/react/components/HighlightOverlay/OverlayMask/OverlayMask.css from the admin-pages VTEX app.

[Assistant]
Here's the implementation:

```css
.overlay-mask-enter {
  opacity: 0;
}

.overlay-mask-enter-active {
  opacity: 0.8;
  transition: opacity 300ms cubic-bezier(0.19, 1, 0.22, 1);
}

.overlay-mask-enter-done {
  opacity: 0.8;
}

.overlay-mask-exit {
  opacity: 0.8;
}

.overlay-mask-exit-active {
  opacity: 0;
  transition: opacity 150ms cubic-bezier(0.215, 0.61, 0.355, 1);
}

.overlay-mask-exit-done {
  opacity: 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 admin-pages/react/components/HighlightOverlay/hooks/usePortal.ts from the admin-pages VTEX app.

[Assistant]
Here's the implementation:

```typescript
import { useEffect, useRef } from 'react'
import { ObserverReturnType } from './useResizeObserver'

export default function usePortal({
  subscribeToResize,
  unsubscribeToResize,
}: ObserverReturnType) {
  const portalContainerRef = useRef<HTMLDivElement>(
    document.createElement<'div'>('div')
  )

  useEffect(() => {
    const portalContainer = portalContainerRef.current
    portalContainer.setAttribute('class', 'absolute z-9999')
    const portalRoot = document.querySelector<HTMLDivElement>(
      '.render-provider'
    )

    const rootComputedStyle = (portalRoot &&
      window.getComputedStyle(portalRoot)) || { height: 0, width: 0 }

    portalContainer.setAttribute(
      'style',
      `width: ${rootComputedStyle.width}; height: ${rootComputedStyle.height}; pointer-events: none;`
    )

    if (portalRoot) {
      portalRoot.prepend(portalContainer)
    }

    function resizeCallback() {
      if (portalRoot) {
        const rootComputedStyle = window.getComputedStyle(portalRoot)
        portalContainer.setAttribute(
          'style',
          `width: ${rootComputedStyle.width}; height: ${rootComputedStyle.height}; pointer-events: none;`
        )
      }
    }

    subscribeToResize(resizeCallback)

    function resizeOnLoad() {
      const rootComputedStyle = (portalRoot &&
        window.getComputedStyle(portalRoot)) || { height: 0, width: 0 }

      portalContainer.setAttribute(
        'style',
        `width: ${rootComputedStyle.width}; height: ${rootComputedStyle.height}; pointer-events: none;`
      )
    }

    window.addEventListener('load', resizeOnLoad)

    return () => {
      unsubscribeToResize(resizeCallback)

      if (portalRoot) {
        portalRoot.removeChild(portalContainer)
      }
      window.removeEventListener('load', resizeOnLoad)
    }
  }, [subscribeToResize, unsubscribeToResize])

  return portalContainerRef.current
}

```


[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 admin-pages/react/components/HighlightOverlay/hooks/useHighlightOnHover.ts from the admin-pages VTEX app.

[Assistant]
Here's the implementation:

```typescript
import { useCallback, useEffect, useRef } from 'react'
import { State } from '../typings'

const HIGHLIGHT_REMOVAL_TIMEOUT_MS = 300

export default function useHighlightOnHover({
  editMode,
  editExtensionPoint,
  highlightHandler,
  highlightTreePath,
  sidebarBlocksMap,
}: State) {
  const highlightRemovalTimeout = useRef<number | undefined>()
  const handleMouseOverHighlight = useCallback<EventListener>(
    e => {
      if (!e.currentTarget || !(e.currentTarget instanceof HTMLElement)) {
        return
      }

      const treePath = e.currentTarget.getAttribute('data-extension-point')
      const isEditable =
        treePath &&
        sidebarBlocksMap[treePath] &&
        sidebarBlocksMap[treePath].isEditable

      if (isEditable) {
        highlightHandler(treePath)
      }

      clearTimeout(highlightRemovalTimeout.current)
      e.stopPropagation()
    },
    [highlightHandler, sidebarBlocksMap]
  )

  const handleMouseLeaveHighlight = useCallback<EventListener>(() => {
    if (highlightRemovalTimeout.current) {
      clearTimeout(highlightRemovalTimeout.current)
    }

    highlightRemovalTimeout.current = window.setTimeout(() => {
      highlightHandler(null)
    }, HIGHLIGHT_REMOVAL_TIMEOUT_MS)
  }, [highlightHandler])

  const handleClickHighlight = useCallback<EventListener>(
    e => {
      if (!e.currentTarget) {
        return
      }

      e.preventDefault()
      e.stopPropagation()
      editExtensionPoint(highlightTreePath)
      highlightHandler(null)
    },
    [editExtensionPoint, highlightHandler, highlightTreePath]
  )

  useEffect(() => {
    const elements = Array.from(
      document.querySelectorAll(`[data-extension-point]`)
    )
    if (editMode) {
      elements.forEach((e: Element) => {
        const element = e as HTMLElement

        if (editMode) {
          element.addEventListener('mouseover', handleMouseOverHighlight)
          element.addEventListener('mouseleave', handleMouseLeaveHighlight)
          element.addEventListener('click', handleClickHighlight)
          element.style.cursor = 'pointer'
        }
      })
    }

    return () => {
      if (editMode) {
        elements.forEach((e: Element) => {
          const element = e as HTMLElement
          element.removeEventListener('mouseover', handleMouseOverHighlight)
          element.removeEventListener('mouseleave', handleMouseLeaveHighlight)
          element.removeEventListener('click', handleClickHighlight)
          element.style.cursor = 'default'
        })
      }
    }
  }, [
    handleMouseOverHighlight,
    editMode,
    handleMouseLeaveHighlight,
    handleClickHighlight,
  ])
}

```


[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 admin-pages/react/components/HighlightOverlay/hooks/useResizeObserver.ts from the admin-pages VTEX app.

[Assistant]
Here's the implementation:

```typescript
import { useEffect, useCallback, useRef } from 'react'
import observeResize from 'simple-element-resize-detector'
import { isArray } from 'util'

type ResizeFn = (el: Element) => void

export default function useResizeObserver() {
  const callbacksRef = useRef<Set<ResizeFn>>(new Set())

  const subscribeToResize = useCallback((callbacks: ResizeFn | ResizeFn[]) => {
    const fns = isArray(callbacks) ? callbacks : [callbacks]
    fns.forEach(fn => {
      callbacksRef.current.add(fn)
    })
  }, [])

  const unsubscribeToResize = useCallback(
    (callbacks: ResizeFn | ResizeFn[]) => {
      const fns = isArray(callbacks) ? callbacks : [callbacks]
      fns.forEach(fn => {
        callbacksRef.current.delete(fn)
      })
    },
    []
  )

  useEffect(() => {
    const root = document.querySelector<HTMLBodyElement>('body')

    if (root) {
      const currentStyle = root.getAttribute('style') || ''
      const newStyle = currentStyle + 'position: relative;'
      root.setAttribute('style', newStyle)
    }

    const resizeDetector =
      root &&
      observeResize(root, element => {
        callbacksRef.current.forEach(fn => {
          fn(element)
        })
      })

    return () => {
      if (resizeDetector && resizeDetector.parentNode) {
        resizeDetector.parentNode.removeChild(resizeDetector)
      }

      if (root) {
        const currentStyle = root.getAttribute('style') || ''
        const newStyle = currentStyle.replace('position: relative;', '')

        if (!newStyle) {
          root.removeAttribute('style')
        } else {
          root.setAttribute('style', newStyle)
        }
      }
    }
  }, [])

  return { subscribeToResize, unsubscribeToResize }
}

export type ObserverReturnType = ReturnType<typeof useResizeObserver>

```


[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 admin-pages/react/components/HighlightOverlay/hooks/useHighlightedElementInfo.ts from the admin-pages VTEX app.

[Assistant]
Here's the implementation:

```typescript
import { useMemo } from 'react'
import { State } from '../typings'

function isElementInHorizontalAxis(el: Element) {
  const rect = el.getBoundingClientRect()

  return (
    rect.left >= 0 &&
    rect.right <= (window.innerWidth || document.documentElement.clientWidth)
  )
}

function getElementInfo(
  highlightTreePath: string,
  sidebarBlocksMap: State['sidebarBlocksMap']
) {
  const elements = document.querySelectorAll(
    `[data-extension-point="${highlightTreePath}"]`
  )

  const provider = document.querySelector<HTMLDivElement>('.render-provider')
  const elementsArray: Element[] = Array.prototype.slice.call(elements)

  const viewportMiddle =
    (window.innerWidth || document.documentElement.clientWidth) / 2

  const visibleElementsClosestToMiddle = elementsArray
    .filter(currElement => {
      const currRect = currElement.getBoundingClientRect()

      return (
        currRect.width > 0 &&
        currRect.height > 0 &&
        isElementInHorizontalAxis(currElement)
      )
    })
    .sort((elemA, elemB) => {
      const rectA = elemA.getBoundingClientRect()
      const rectB = elemB.getBoundingClientRect()
      const middleA = rectA.left || 0 + rectA.width
      const middleB = rectB.left || 0 + rectB.width

      const differenceA =
        viewportMiddle - middleA < 0
          ? middleA - viewportMiddle
          : viewportMiddle - middleA
      const differenceB =
        viewportMiddle - middleB < 0
          ? middleB - viewportMiddle
          : viewportMiddle - middleB

      if (differenceA < differenceB) {
        return -1
      } else if (differenceA > differenceB) {
        return 1
      }
      return 0
    })

  const visibleElement = visibleElementsClosestToMiddle[0]

  const isEditable =
    sidebarBlocksMap[highlightTreePath] &&
    sidebarBlocksMap[highlightTreePath].isEditable

  const hasValidElement = !(
    !highlightTreePath ||
    elements.length === 0 ||
    !visibleElement ||
    !isEditable ||
    !provider
  )

  return { visibleElement, hasValidElement }
}

export default function useHighlightedElementInfo(
  highlightTreePath: State['highlightTreePath'],
  sidebarBlocksMap: State['sidebarBlocksMap'],
  elementHeight: State['elementHeight']
) {
  return useMemo<Partial<ReturnType<typeof getElementInfo>>>(() => {
    return (
      (highlightTreePath &&
        getElementInfo(highlightTreePath, sidebarBlocksMap)) ||
      {}
    )
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [highlightTreePath, sidebarBlocksMap, elementHeight])
}

```


[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 admin-pages/react/components/HighlightOverlay/hooks/useAutoScroll.ts from the admin-pages VTEX app.

[Assistant]
Here's the implementation:

```typescript
import debounce from 'lodash/debounce'
import { useEffect } from 'react'
import { State } from '../typings'

interface UseAutoScrollArgs {
  highlightTreePath: State['highlightTreePath']
  editMode: State['editMode']
  visibleElement?: Element
}

function isElementInViewport(el: Element) {
  const rect = el.getBoundingClientRect()

  return (
    rect.top >= 0 &&
    rect.left >= 0 &&
    rect.bottom <=
      (window.innerHeight || document.documentElement.clientHeight) &&
    rect.right <= (window.innerWidth || document.documentElement.clientWidth)
  )
}

const scrollToElement = debounce((element: Element) => {
  if (!isElementInViewport(element)) {
    element.scrollIntoView({
      behavior: 'smooth',
      block: 'center',
      inline: 'center',
    })
  }
}, 75)

export default function useAutoScroll({
  highlightTreePath,
  editMode,
  visibleElement,
}: UseAutoScrollArgs) {
  useEffect(() => {
    if (visibleElement && !editMode) {
      scrollToElement(visibleElement)
    }
  }, [visibleElement, editMode])

  useEffect(() => {
    if (highlightTreePath === null) {
      scrollToElement.cancel()
    }
  }, [highlightTreePath])
}

```


[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 admin-pages/react/components/HighlightOverlay/hooks/useStyles/utils.ts from the admin-pages VTEX app.

[Assistant]
Here's the implementation:

```typescript
import { CSSProperties } from 'react'

import { GetStyles } from './typings'

let defaultHighlightRect = { x: 0, y: 0, width: 0, height: 0 }

const INITIAL_HIGHLIGHT_RECT = {
  height: 0,
  width: 0,
  x: 0,
  y: 0,
}

const BLUE = '#134CD8'

function getHighlightRect(visibleElement?: Element) {
  const provider = document.querySelector<HTMLDivElement>('.render-provider')

  const iframeBody = document.querySelector('body')

  const paddingFromIframeBody = iframeBody
    ? {
        left: parseInt(
          window.getComputedStyle(iframeBody, null).paddingLeft || '0',
          10
        ),
        right: parseInt(
          window.getComputedStyle(iframeBody, null).paddingRight || '0',
          10
        ),
      }
    : {
        left: 0,
        right: 0,
      }

  const providerRect = (provider &&
    (provider.getBoundingClientRect() as DOMRect)) || { x: 0, y: 0 }

  const rect = visibleElement
    ? (visibleElement.getBoundingClientRect() as DOMRect)
    : INITIAL_HIGHLIGHT_RECT

  // Add offset from render provider main div
  rect.y += -providerRect.y
  rect.x +=
    -providerRect.x +
    (paddingFromIframeBody.left + paddingFromIframeBody.right) / 2

  defaultHighlightRect = rect

  return rect
}

export const getStyles: GetStyles = ({
  hasValidElement,
  highlightTreePath,
  visibleElement,
}) => {
  const highlight =
    highlightTreePath && hasValidElement && getHighlightRect(visibleElement)

  const { x: left, y: top, width, height } = highlight || defaultHighlightRect

  const isBlockWidthSmaller = width < 98 * 1.25
  const isBlockHeightSmaller = height < 26

  const highlightDimensions = {
    height: !isBlockHeightSmaller && top - 4 < 0 ? height : height + 8,
    left:
      !isBlockWidthSmaller && width >= document.body.scrollWidth
        ? left
        : left - 4,
    top: !isBlockHeightSmaller && top - 4 < 0 ? top : top - 4,
    width:
      !isBlockWidthSmaller && width >= document.body.scrollWidth
        ? document.body.scrollWidth
        : width + 8,
  }

  const highlightWidthRatio =
    highlightDimensions.width / document.body.scrollWidth

  const highlightStyle: CSSProperties = {
    ...highlightDimensions,
    boxShadow: `rgb(0, 0, 0) 0px ${60 * highlightWidthRatio}px ${66 *
      highlightWidthRatio}px -${78 * highlightWidthRatio}px`,
    pointerEvents: 'none',
    zIndex: 9999,
  }

  const startX = `${highlightDimensions.left}px`
  const endX = `${highlightDimensions.left + highlightDimensions.width}px`

  const startY = `${highlightDimensions.top}px`
  const endY = `${highlightDimensions.top + highlightDimensions.height}px`

  const maskStyle = {
    clipPath:
      `polygon(0% 0%, 0% 100%, ${startX} 100%, ${startX} ${startY}, ${endX} ${startY}, ` +
      `${endX} ${endY}, ${startX} ${endY}, ${startX} 100%, 100% 100%, 100% 0%)`,
  }

  const labelStyle = {
    backgroundColor: BLUE,
    width: 90,
    height: 20,
    transform: `${
      isBlockHeightSmaller || isBlockWidthSmaller ? 'translate(4px, -24px)' : ''
    }`,
  }

  return { highlightStyle, labelStyle, maskStyle }
}

```


[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 admin-pages/react/components/HighlightOverlay/hooks/useStyles/typings.d.ts from the admin-pages VTEX app.

[Assistant]
Here's the implementation:

```typescript
import { CSSProperties } from 'react'

import { ObserverReturnType } from '../useResizeObserver'
import { State } from '../../typings'

interface GetStylesParams {
  hasValidElement?: boolean
  highlightTreePath: State['highlightTreePath']
  visibleElement?: Element
}

export type GetStyles = (
  params: GetStylesParams
) => {
  highlightStyle: CSSProperties
  labelStyle: CSSProperties
  maskStyle: CSSProperties
}

interface UseStylesParams extends GetStylesParams, ObserverReturnType {
  isOverlayMaskActive: boolean
  setState: React.Dispatch<React.SetStateAction<State>>
}

export type UseStyles = (params: UseStylesParams) => void

```


[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 admin-pages/react/components/HighlightOverlay/hooks/useStyles/index.ts from the admin-pages VTEX app.

[Assistant]
Here's the implementation:

```typescript
import { useCallback, useEffect } from 'react'

import { UseStyles } from './typings'
import { getStyles } from './utils'

/*
 * The "data-extension-point" attribute is re-added to the element every
 * time it's edited. By observing it, we can consistently check if the
 * block's automatic height has changed and adapt the HighlightOverlay's
 * height accordingly.
 */

const useStyles: UseStyles = ({
  hasValidElement,
  highlightTreePath,
  isOverlayMaskActive,
  setState,
  subscribeToResize,
  unsubscribeToResize,
  visibleElement,
}) => {
  const updateStyles = useCallback(
    (clientHeight?) => {
      const elementHeight: HTMLElement['clientHeight'] = clientHeight

      const styles = getStyles({
        hasValidElement,
        highlightTreePath,
        visibleElement,
      })

      setState(state => ({
        ...state,
        ...styles,
        elementHeight: elementHeight || state.elementHeight,
      }))
    },
    [hasValidElement, highlightTreePath, setState, visibleElement]
  )

  useEffect(() => {
    function resizeCallback(element: Element) {
      updateStyles(element.clientHeight)
    }

    subscribeToResize(resizeCallback)
    updateStyles()

    return () => {
      unsubscribeToResize(resizeCallback)
    }
  }, [
    isOverlayMaskActive,
    subscribeToResize,
    unsubscribeToResize,
    updateStyles,
    visibleElement,
  ])
}

export default useStyles

```


[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 similar-products-variants/docs/README.md from the similar-products-variants VTEX app.

[Assistant]
Here's the implementation:

```markdown
# Similar Products Variants

The Similar Products Variants app returns similar products related to an SKU so users can select other colors or types of the same product.

![similar-in-action](https://user-images.githubusercontent.com/67270558/147780521-db76029b-c1fa-4627-a8bb-fa7485355424.png)

## Before you start
1. Set up similar products in your store’s **Products and SKU.** Access your store’s Admin and go to **Products > Catalog > Products and SKU**.
2. In **Products and SKU**, in the column **SKU**, click on the desired SKU.
3. In the field **Similar (Alternative Products)**, type the product name you desire

![similar-field](https://user-images.githubusercontent.com/67270558/147780337-ccc0d622-535e-47ce-9ede-d86f1d571546.gif)

4. Then, In **Products and SKU**, in the column **SKU**, click on the one you have added in the last step.
5. Go to the `Images` tab, and on the field `Label`, type a name to identify the image displayed in the thumbnail through the `imageLabel` prop of the `Similar Products` Variants app.

Now, follow the [app’s configuration below](#configuration) to show the similar products you have set up.

## Configuration

1. Using [VTEX IO CLI](https://developers.vtex.com/vtex-developer-docs/docs/vtex-io-documentation-vtex-io-cli-installation-and-command-reference), install the app by running the following:

```bash
vtex install vtex.similar-products-variants
```
2. Add the `vtex.similar-products-variants` app to your theme's dependencies in the `manifest.json`

```json
"dependencies": {
    "vtex.similar-products-variants": “0.x”
}
```

3. Add the `similar-products-variants` block to the product template you desire, such as `store.product`, to display a similar product list.

```json
...
  "flex-layout.col#right-col": {
    "props": {
      "preventVerticalStretch": true,
      "rowGap": 0
    },
    "children": [
      "flex-layout.row#product-name",
      "product-rating-summary",
      "flex-layout.row#list-price-savings",
      "flex-layout.row#selling-price",
      "product-installments",
      "product-separator",
      "product-identifier.product",
      "sku-selector",
    + "similar-products-variants",
      "product-quantity",
      "link-seller",
      "product-availability",
      "product-assembly-options",
      "product-gifts",
      "flex-layout.row#buy-button",
      "availability-subscriber",
      "shipping-simulator",
      "share#default"
    ]
  },
  "similar-products-variants": {
      "props": {
          "imageLabel": "swatch"
      }
  },
...
```

| Prop name  | Type | Description                                                                                | Default value |
|--------------|--------|------------------------------------| ------------- |
| `imageLabel` | String | The identifier of the image thumbnail displayed for each variant.  The identifier is set in the Admin’s Catalog. If the label does not exist or is not defined, the first image is used. | `null`  |

## Customization

To apply CSS customizations in this and other blocks, follow the instructions given in the recipe on [Using CSS Handles for store customization](https://vtex.io/docs/recipes/style/using-css-handles-for-store-customization).

| CSS Handles            |
| -----------            |
| `variants`             |
| `title`                |
| `var-wrap`             |
| `img_wrap`             |
| `img_wrap--is-active`  |
| `img`                  |

```


[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 similar-products-variants/react/Index.tsx from the similar-products-variants VTEX app.

[Assistant]
Here's the implementation:

```tsx
import React from 'react'
import type { ProductTypes } from 'vtex.product-context'
import { useProduct } from 'vtex.product-context'
import { useQuery } from 'react-apollo'
import { useCssHandles } from 'vtex.css-handles'
import { useRuntime } from 'vtex.render-runtime'
import { useIntl } from 'react-intl'
import { Link } from 'vtex.render-runtime'

import productRecommendationsQuery from './queries/productRecommendations.gql'

interface SimilarProductsVariantsProps {
  productQuery: {
    product: {
      productId: string
    }
  },
  imageLabel: string
}

const CSS_HANDLES = [
  'variants',
  'title',
  'var-wrap',
  'img_wrap',
  'img',
] as const

function SimilarProductsVariants({
  productQuery,
  imageLabel
}: SimilarProductsVariantsProps) {
  const handles = useCssHandles(CSS_HANDLES)
  const intl = useIntl()
  const productContext = useProduct()
  const { route } = useRuntime()
  const productId =
    productQuery?.product?.productId ?? productContext?.product?.productId

  const { data, loading, error } = useQuery(productRecommendationsQuery, {
    variables: {
      identifier: { field: 'id', value: productId },
      type: `similars`,
    },
    skip: !productId,
  })

  if (loading || error) return null

  const { productRecommendations } = data

  const { products } = {
    products: productRecommendations || [],
  }

  const unique = [
    ...new Set<string>(
      products.map((item: ProductTypes.Product) => item.productId)
    ),
  ]

  const items: ProductTypes.Product[] = []

  unique.forEach(id => {
    const item = products.find(
      (element: ProductTypes.Product) => element.productId === id
    )

    if (item) items.push(item)
  })

  if( items.length == 0 ){
    return <></>
  }

  return (
    <div className={`${handles.variants}`}>
      <p className={`${handles.title}`}>{intl.formatMessage({ id: "store/title.label" })}</p>
      <div className={handles['var-wrap']}>
        {items.map((element: ProductTypes.Product) => {
          const imageIndex = imageLabel === undefined
            ? 0
            : element.items[0].images.findIndex(image => image.imageLabel === imageLabel) === -1
              ? 0
              : element.items[0].images.findIndex(image => image.imageLabel === imageLabel)

          const srcImage = element.items[0].images[imageIndex].imageUrl
          return (
            <Link
              key={element.productId}
              className={`${handles.img_wrap}${route?.params?.slug === element.linkText ? '--is-active' : ''}`}
              {...{
              page: 'store.product',
              params: {
              slug: element?.linkText,
              id: element?.productId,
              },
            }}>
                <img
                  src={srcImage}
                  alt={element.productName}
                  height="50px"
                  className={`${handles.img} mr3 ${route?.params?.slug === element.linkText ? 'o-50' : ''
                    }`
                  }
                />
            </Link>
          )
        })}
      </div>
    </div>
  )
}

SimilarProductsVariants.schema = {
  title: 'SimilarProducts Variants',
  description: 'SimilarProducts Variants',
  type: 'object',
  properties: {},
}

export default SimilarProductsVariants

```


[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 similar-products-variants/react/package.json from the similar-products-variants VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "scripts": {
    "test": "vtex-test-tools test",
    "lint": "tsc --noEmit && eslint --ext ts,tsx ."
  },
  "dependencies": {
    "apollo-client": "^2.6.8",
    "react": "^16.12.0",
    "react-apollo": "^3.1.3",
    "react-dom": "^16.12.0",
    "react-intl": "^5.21.2"
  },
  "devDependencies": {
    "@apollo/react-testing": "^3.1.3",
    "@types/jest": "^25.1.4",
    "@types/node": "^13.9.8",
    "@types/react": "^16.9.31",
    "@vtex/test-tools": "^3.3.2",
    "@vtex/tsconfig": "^0.4.4",
    "apollo-cache-inmemory": "^1.6.5",
    "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.order-items": "http://vtex.vtexassets.com/_v/public/typings/v1/vtex.order-items@0.13.1/public/@types/vtex.order-items",
    "vtex.order-manager": "http://vtex.vtexassets.com/_v/public/typings/v1/vtex.order-manager@0.11.1/public/@types/vtex.order-manager",
    "vtex.product-context": "http://vtex.vtexassets.com/_v/public/typings/v1/vtex.product-context@0.10.0/public/@types/vtex.product-context",
    "vtex.render-runtime": "http://vtex.vtexassets.com/_v/public/typings/v1/vtex.render-runtime@8.132.3/public/@types/vtex.render-runtime",
    "vtex.search-graphql": "http://vtex.vtexassets.com/_v/public/typings/v1/vtex.search-graphql@0.47.2/public/@types/vtex.search-graphql",
    "vtex.similar-products-variants": "https://roo--paragonsports.myvtex.com/_v/private/typings/linked/v1/vtex.similar-products-variants@0.0.7+build1637602189/public/@types/vtex.similar-products-variants",
    "vtex.store-resources": "http://vtex.vtexassets.com/_v/public/typings/v1/vtex.store-resources@0.85.0/public/@types/vtex.store-resources",
    "vtex.styleguide": "http://vtex.vtexassets.com/_v/public/typings/v1/vtex.styleguide@9.145.2/public/@types/vtex.styleguide"
  },
  "version": "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 similar-products-variants/store/interfaces.json from the similar-products-variants VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "similar-products-variants": {
    "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 similar-products-variants/react/typings/gql.d.ts from the similar-products-variants VTEX app.

[Assistant]
Here's the implementation:

```typescript
declare module '*.gql' {
  import type { DocumentNode } from 'graphql'

  const Schema: DocumentNode

  export default Schema
}

declare module '*.graphql' {
  import type { DocumentNode } from 'graphql'

  const schema: DocumentNode

  export default Schema
}

```


[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 similar-products-variants/react/typings/css.d.ts from the similar-products-variants VTEX app.

[Assistant]
Here's the implementation:

```typescript
declare module '*.css' {
  const css: any
  export default css
}

```


[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 similar-products-variants/react/queries/productRecommendations.gql from the similar-products-variants VTEX app.

[Assistant]
Here's the implementation:

```graphql
query ProductRecommendations(
  $identifier: ProductUniqueIdentifier
  $type: CrossSelingInputEnum
) {
  productRecommendations(identifier: $identifier, type: $type)
    @context(provider: "vtex.search-graphql") {
    productId
    linkText
    specificationGroups {
      name
      originalName
      specifications {
        name
        originalName
        values
      }
    }
    items {
      images {
        imageLabel
        imageUrl
      }
      variations {
        name
        values
      }
    }
  }
}
```


[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 speedsize/docs/README.md from the speedsize VTEX app.

[Assistant]
Here's the implementation:

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

# APP NAME

<!-- 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 -->

Under the app's name, you should explain the topic, giving a **brief description** of the **app's functionality** (what is it for?) in a store.

Next, you can **add media** (either an image of a GIF) if possible, so that users can better understand how the app works in practice.

![Media Placeholder](https://user-images.githubusercontent.com/52087100/71204177-42ca4f80-227e-11ea-89e6-e92e65370c69.png)

## Configuration

It is possible to install in your store either by using App Store or the VTEX IO Toolbelt.

### Using VTEX App Store

1. Access the **Apps** section in your account's admin page and look for the Icommkt box;
2. Then, click on the **Install** button;
3. You'll see a warning message about needing to enter the necessary configurations. Scroll down and type in your **NAME OF A SETTINGS FIELD** in the `NAME OF THE APP` field.
4. Click on **Save**.

### Using VTEX IO Toolbelt

1. [Install](https://vtex.io/docs/recipes/development/installing-an-app/) the `vtex.icommkt@0.x` app. You can confirm that the app has now been installed by running `vtex ls` again.
2. Access the **Apps** section in your account's admin page and look for the NAME OF THE APP box. Once you find it, click on the box.
3. Fill in the `NAME OF THE APP` field with your **NAME OF THE SETTINGS FIELD**.
4. Click on **Save**.

<!-- Remember to also **showcase any necessary disclaimer** related to the app in this section, such as the different behavior it may display during its configuration. -->

## Modus Operandi *(not mandatory)*

There are scenarios in which an app can behave differently in a store, according to its configuration. It's crucial then to go through these **behavioral changes** in this section, allowing users to fully understand the **practical application** of the app in their store.

If you feel compelled to give further details, such as the app's **relationship with others**, don't hesitate to use this section.

<!-- 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 are 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 speedsize/service-workers/header.js from the speedsize VTEX app.

[Assistant]
Here's the implementation:

```javascript
function fetchSpeedSizeSW() {
  // eslint-disable-next-line no-console
  console.log('[SpeedSize SW] Fetch of SpeedSizeSW')
  const today = new Date()
  // eslint-disable-next-line no-undef
  importScripts("https://di6367dava8ow.cloudfront.net"+"/"+"8310be04-0308-4646-a73c-13c37508ae99"+"/"+today.getDate()+"-"+ (today.getMonth() + 1) +"-"+today.getFullYear()+"/sw.js");
}

export default fetchSpeedSizeSW

```


[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 speedsize/react/index.tsx from the speedsize VTEX app.

[Assistant]
Here's the implementation:

```tsx
import { canUseDOM } from 'vtex.render-runtime'

import type { PixelMessage } from './typings/events'

export function handleEvents(e: PixelMessage) {
  switch (e.data.eventName) {
    case 'vtex:pageView': {
      break
    }

    default: {
      break
    }
  }
}

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

```


[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 speedsize/react/package.json from the speedsize VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "scripts": {
    "test": "vtex-test-tools test"
  },
  "devDependencies": {
    "@apollo/react-testing": "^3.1.3",
    "@types/graphql": "^14.5.0",
    "@types/jest": "^25.1.5",
    "@types/node": "^13.11.0",
    "@types/react": "^16.9.31",
    "@types/react-intl": "^3.0.0",
    "@vtex/test-tools": "^3.1.0",
    "apollo-cache-inmemory": "^1.6.5",
    "apollo-client": "^2.6.8",
    "graphql": "^14.5.4",
    "react-intl": "^3.11.0",
    "typescript": "3.9.7",
    "vtex.pixel-interfaces": "http://vtex.vtexassets.com/_v/public/typings/v1/vtex.pixel-interfaces@1.1.1/public/_types/react",
    "vtex.render-runtime": "http://vtex.vtexassets.com/_v/public/typings/v1/vtex.render-runtime@8.124.3/public/@types/vtex.render-runtime"
  }
}

```


[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 speedsize/store/interfaces.json from the speedsize VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "pixel.speedsize": {
    "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 speedsize/public/metadata/messages/es-AR.json from the speedsize VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "name": "",
  "headline": "",
  "overview": "",
  "features": [],
  "additionalInformation": "",
  "websiteURL": "https://vtex.com/",
  "support": {
    "url": "https://support.vtex.com/hc/requests"
  }
}

```


[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 speedsize/public/metadata/messages/pt-BR.json from the speedsize VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "name": "",
  "headline": "",
  "overview": "",
  "features": [],
  "additionalInformation": "",
  "websiteURL": "https://vtex.com/",
  "support": {
    "url": "https://support.vtex.com/hc/requests"
  }
}

```


[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 speedsize/public/metadata/messages/en-US.json from the speedsize VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "name": "",
  "headline": "",
  "overview": "",
  "features": [],
  "additionalInformation": "",
  "websiteURL": "https://vtex.com/",
  "support": {
    "url": "https://support.vtex.com/hc/requests"
  }
}

```


[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 speedsize/react/typings/events.d.ts from the speedsize VTEX app.

[Assistant]
Here's the implementation:

```typescript
export interface PixelMessage extends MessageEvent {
  data:
    | ProductViewData
    | ProductClickData
    | OrderPlacedData
    | OrderPlacedTrackedData
    | PageViewData
    | ProductImpressionData
    | AddToCartData
    | RemoveToCartData
    | CartChangedData
    | HomePageInfo
    | ProductPageInfoData
    | SearchPageInfoData
    | UserData
    | CartIdData
    | PromoViewData
    | PromotionClickData
    | NewsletterSubscriptionData
}

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

export interface PageInfoData extends EventData {
  event: 'pageInfo'
  eventName: 'vtex:pageInfo'
  accountName: string
  pageTitle: string
  pageUrl: string
}

export interface UserData extends PageInfoData {
  eventType: 'userData'
  eventName: 'vtex:userData'
  firstName?: string
  lastName?: string
  document?: string
  id?: string
  email?: string
  phone?: string
  isAuthenticated: boolean
}

export interface CartIdData extends PageInfoData {
  eventType: 'cartId'
  eventName: 'vtex:cartId'
  cartId: string
}

export interface HomePageInfo extends PageInfoData {
  eventType: 'homeView'
}

export interface ProductPageInfoData extends PageInfoData {
  eventType: 'productPageInfo'
}

export interface SearchPageInfoData extends PageInfoData {
  eventType:
    | 'internalSiteSearchView'
    | 'categoryView'
    | 'departmentView'
    | 'emptySearchView'
  category?: CategoryMetaData
  department?: DepartmentMetaData
  search?: SearchMetaData
}

interface CategoryMetaData {
  id: string
  name: string
}

interface DepartmentMetaData {
  id: string
  name: string
}

interface SearchMetaData {
  term: string
  category: CategoryMetaData
  results: number
}

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

export interface AddToCartData extends EventData {
  event: 'addToCart'
  eventName: 'vtex:addToCart'
  items: CartItem[]
}

export interface RemoveToCartData extends EventData {
  event: 'removeFromCart'
  eventName: 'vtex:removeFromCart'
  items: CartItem[]
}

export interface CartChangedData extends EventData {
  event: 'cartChanged'
  eventName: 'vtex:cartChanged'
  items: CartItem[]
}

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

export interface OrderPlacedTrackedData extends Order, EventData {
  event: 'orderPlacedTracked'
  eventName: 'vtex:orderPlacedTracked'
}

export interface ProductViewData extends EventData {
  event: 'productView'
  eventName: 'vtex:productView'
  product: Product
}

export interface ProductClickData extends EventData {
  event: 'productClick'
  eventName: 'vtex:productClick'
  product: ProductSummary
  list?: string
}

export interface ProductImpressionData extends EventData {
  event: 'productImpression'
  eventName: 'vtex:productImpression'
  impressions: Impression[]
  product?: ProductSummary // deprecated, use impressions list!
  position?: number // deprecated, use impressions list!
  list: string
}

export interface CartData extends EventData {
  event: 'cart'
  eventName: 'vtex:cart'
  orderForm: OrderForm
}

export interface PromoViewData extends EventData {
  event: 'promoView'
  eventName: 'vtex:promoView'
  promotions: Promotion[]
}

export interface PromotionClickData extends EventData {
  event: 'promotionClick'
  eventName: 'vtex:promotionClick'
  promotions: Promotion[]
}

export interface NewsletterSubscriptionData extends EventData {
  event: 'newsletterSubscription'
  eventName: 'vtex:newsletterSubscription'
  name: string
  email: string
  phone: string
}

interface Promotion {
  id?: string
  name?: string
  creative?: string
  position?: string
}

interface CartItem {
  brand: string
  ean: string
  category: string
  detailUrl: string
  imageUrl: string
  name: string
  price: number
  productId: string
  productRefId: string
  quantity: number
  seller: string
  sellerName: string
  skuId: string
  variant: string
}

export interface OrderForm {
  id: string
  items: CartItem[]
}

export interface Order {
  accountName: string
  corporateName: string
  coupon: string
  currency: string
  openTextField: string
  orderGroup: string
  salesChannel: string
  visitorAddressCity: string
  visitorAddressComplement: string
  visitorAddressCountry: string
  visitorAddressNeighborhood: string
  visitorAddressNumber: string
  visitorAddressPostalCode: string
  visitorAddressState: string
  visitorAddressStreet: string
  visitorContactInfo: string[]
  visitorContactPhone: string
  visitorType: string
  transactionId: string
  transactionDate: string
  transactionAffiliation: string
  transactionTotal: number
  transactionShipping: number
  transactionSubtotal: number
  transactionDiscounts: number
  transactionTax: number
  transactionCurrency: string
  transactionPaymentType: PaymentType[]
  transactionShippingMethod: ShippingMethod[]
  transactionLatestShippingEstimate: Date
  transactionProducts: ProductOrder[]
  transactionPayment: {
    id: string
  }
}

export interface Impression {
  product: ProductSummary
  position: number
}

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

export interface ShippingMethod {
  itemId: string
  selectedSla: string
}

export interface ProductOrder {
  id: string
  name: string
  sku: string
  skuRefId: string
  skuName: string
  productRefId: string
  ean: string
  slug: 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
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  components: any[]
  measurementUnit: string
  unitMultiplier: number
}

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

export interface Product {
  brand: string
  brandId: string
  categories: string[]
  categoryId: string
  categoryTree: Array<{ id: string; name: string }>
  detailUrl: string
  items: Item[]
  linkText: string
  productId: string
  productName: string
  productReference: string
  selectedSku: Item
}

export interface Item {
  itemId: string
  name: string
  ean: string
  referenceId: { Key: string; Value: string }
  imageUrl: string
  sellers: Seller[]
}

export interface ProductSummary {
  brand: string
  brandId: string
  categories: string[]
  items: ItemSummary[]
  linkText: string
  productId: string
  productName: string
  productReference: string
  sku: ItemSummary
}

interface ItemSummary {
  itemId: string
  ean: string
  name: string
  referenceId: { Key: string; Value: string }
  seller: Seller
  sellers: Seller[]
}

export interface Seller {
  commertialOffer: CommertialOffer
  sellerId: string
  sellerName: string
}

export interface CommertialOffer {
  Price: number
  ListPrice: number
  AvailableQuantity: 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 speedsize/react/typings/global.d.ts from the speedsize VTEX app.

[Assistant]
Here's the implementation:

```typescript
interface Window extends Window {
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  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 giftcard-protocol-example/docs/README.md from the giftcard-protocol-example VTEX app.

[Assistant]
Here's the implementation:

```markdown

# Gift Card Protocol Example

A reference app implementing a VTEX IO Gift Card integration service. This app is an example to be followed in order to develop a gift card service integration with VTEX.

## Testing the app
At first, once you link this application, it's important to know that so as to test it in a store to place an order, for example, it's necessary to register the external provider on the account. By doing that, Gift Card Hub will know how to compose the routes which it's going to send the requests to. This step can be found in the [GraphQL section](#graphql-queries-and-mutations).

Having the app linked, it will have the routes mentioned before exposed. At first, you can test all your routes on Postman, to make sure that they work as you expect it to. After doing that, you can trigger the communication between the Gift Card Hub and your application by simulating a purchase on a store. You'll have to configure your provider on an account so you can use it on your simulation.

> **NOTE**: Some endpoints are only used when the order status changes, such as settlement and cancellation, which means that you need to have permission to use the admin panel to change orders' status.

## Clients
In this example, there are a few clients implemented for you to use.
- `GiftCardHub`: used to connect to the Gift Card Hub to configure or delete a provider on an account;
- `GiftCardProvider`: used to connect to the provider's external API, where it must have methods implemented to handle all the request that the Gift Card Hub might make;
- `VtexCommerce`: basic external client that can be used as the class that can be inherited to develop other clients that connectes to VTEX API.

## Routes
Gift Card Hub expects the provider's API to be able to handle some endpoints that are related to gift card, transactions, cancellations, settlements, etc. In this example, all the routes are defined on the `service.json` and have their handlers implemented.
> The base URL that is used is defined when configuring the provider on an account.

## Parsers
As a way to simplify the logic behind the handlers that are implemented in this example, all the code logic that can be necessary to parse the payloads to a specific format is expected to be implemented inside `parsers` directory. This is necessary because both the external provider API and VTEX API expect specific payload formats. Inside the folder, there are two files, `providerToVtex.ts` and `vtexToProvider.ts`.

### VTEX to Provider
In this file, you can define parsers to convert request body formats to the formar that the provider's API expects. In this example, there are some functions implemented, feel free to use them to help developing the integration.

### Provider to VTEX
It's not always that the provider's API have response or request bodies that are aligned with the format that VTEX expects. In this file, you can define parsers to convert them.

## GraphQL queries and mutations

### Getting list of providers configured on an account
There is a GraphQL query that can be used on GraphiQL to check the providers that are configured on the account you're running this application.

To do that, you can use the route that is available to GraphiQL when linking this app and write a query similar to the following one:

```graphql
query {
  getGiftCardProviders{
    serviceUrl
    oauthProvider
    preAuthEnabled
    cancelEnabled
  }
}
```

After doing that, you will receive a response similar to this one:
```json
{
  "data": {
    "getGiftCardProviders": [
      {
        "serviceUrl": "http://api.vtex.com/appliancetheme",
        "oauthProvider": "vtex",
        "preAuthEnabled": true,
        "cancelEnabled": true
      },
      {
        "serviceUrl": "https://fabiana--appliancetheme.myvtex.com/my-provider",
        "oauthProvider": "vtex",
        "preAuthEnabled": true,
        "cancelEnabled": true
      }
    ]
  }
}
```

> **Note**: There will always be a VTEX Gift Card provider configured on any account, because this is the native provider offered by VTEX.

### Using GraphiQL to configure the gift card provider on an account

In this example app, there are also two mutations configured, which are related to adding or deleting a provider from an account.

- Setting a provider
  ```graphql
  mutation ($id: String, $giftCardProvInput: GiftCardProviderInput) {
    setGiftCardProvider (id: $id, giftCardProvInput: $giftCardProvInput){
      serviceUrl
      oauthProvider
      preAuthEnabled
      cancelEnabled
    }
  }
  ```

  Query variables:
  ```json
  {
    "id": "FabianaTest2",
    "giftCardProvInput": {
      "serviceUrl": "https://fabiana--appliancetheme.myvtex.com/my-provider",
      "oauthProvider": "vtex",
      "preAuthEnabled": true,
      "cancelEnabled": true
    }
  }
  ```

- Deleting a provider
  ```graphql
  mutation ($id: String) {
    deleteGiftCardProvider (id: $id){
      serviceUrl
      oauthProvider
      preAuthEnabled
      cancelEnabled
    }
  }
  ```

  Query variables:
  ```json
  {
    "id": "FabianaTest2",
  }
  ```

```


[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 giftcard-protocol-example/graphql/schema.graphql from the giftcard-protocol-example VTEX app.

[Assistant]
Here's the implementation:

```graphql
type Query {
  getGiftCardProviders: [GiftCardProvider]
}

type Mutation {
  setGiftCardProvider(
    id: String
    giftCardProvInput: GiftCardProviderInput
  ): GiftCardProviderResponse
  deleteGiftCardProvider(id: String): GiftCardProviderResponse
}

type GiftCardProvider {
  serviceUrl: String
  oauthProvider: String
  preAuthEnabled: Boolean
  cancelEnabled: Boolean
}

input GiftCardProviderInput {
  serviceUrl: String
  oauthProvider: String
  preAuthEnabled: Boolean
  cancelEnabled: Boolean
}

type GiftCardProviderResponse {
  serviceUrl: String
  oauthProvider: String
  preAuthEnabled: Boolean
  cancelEnabled: Boolean
  id: String
  caption: String
  _self: Self
}

input SelfInput {
  href: String
}

type Self {
  href: 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 giftcard-protocol-example/node/service.json from the giftcard-protocol-example VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "stack": "nodejs",
  "memory": 512,
  "ttl": 43200,
  "timeout": 300,
  "routes": {
    "list": {
      "path": "/my-provider/giftcards/_search",
      "public": true
    },
    "create": {
      "path": "/my-provider/giftcards",
      "public": true
    },
    "get": {
      "path": "/my-provider/giftcards/:id/",
      "public": true
    },
    "transactions": {
      "path": "/my-provider/giftcards/:giftCardId/transactions",
      "public": true
    },
    "getTransaction": {
      "path": "/my-provider/giftcards/:giftCardId/transactions/:id/",
      "public": true
    },
    "authorization": {
      "path": "/my-provider/giftcards/:giftCardId/transactions/:id/authorization",
      "public": true
    },
    "cancellation": {
      "path": "/my-provider/giftcards/:giftCardId/transactions/:id/cancellations",
      "public": true
    },
    "settlement": {
      "path": "/my-provider/giftcards/:giftCardId/transactions/:id/settlements",
      "public": 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 giftcard-protocol-example/node/package.json from the giftcard-protocol-example VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "dependencies": {
    "co-body": "^6.0.0"
  },
  "devDependencies": {
    "@types/co-body": "^0.0.3",
    "@types/jest": "^24.0.18",
    "@types/node": "^12.0.0",
    "@vtex/api": "6.36.2",
    "@vtex/test-tools": "^1.0.0",
    "tslint": "^5.14.0",
    "tslint-config-vtex": "^2.1.0",
    "typescript": "3.8.3"
  },
  "resolutions": {
    "**/**/acorn": "^6.4.1",
    "**/**/minimist": "^0.2.1",
    "**/**/kind-of": "^6.0.3",
    "**/**/handlebars": "^4.3.0",
    "**/**/js-yaml": "^3.13.1"
  },
  "scripts": {
    "lint": "tsc --noEmit --pretty && tslint -c tslint.json --fix './**/*.ts'"
  },
  "version": "1.0.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 giftcard-protocol-example/node/index.ts from the giftcard-protocol-example VTEX app.

[Assistant]
Here's the implementation:

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

import { Clients } from './clients/index'
import {
  createCancellation,
  listAllCancellations,
} from './handlers/cancellations'
import { getOrCreateGiftCard, listGiftCards } from './handlers/giftcards'
import { createSettlement, listAllSettlements } from './handlers/settlements'
import {
  createTransaction,
  getTransactionAuthorization,
  getTransactionById,
  listTransactions,
} from './handlers/transactions'
import { deleteGiftCardProvider } from './resolvers/deleteGiftCardProvider'
import { getGiftCardProviders } from './resolvers/getProviders'
import { setGiftCardProvider } from './resolvers/setGiftCardProvider'
import { validateCredentials } from './handlers/credentials'

const TIMEOUT_MS = 800

// This is the configuration for clients available in `ctx.clients`.
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,
    },
  },
}

declare global {
  // We declare a global Context type just to avoid re-writing ServiceContext<Clients, State> in every handler and resolver
  type Context = ServiceContext<Clients>
}

// It's possible to check the implementation of each handler in the handlers folder
export default new Service<Clients, RecorderState, ParamsContext>({
  clients,
  graphql: {
    resolvers: {
      Mutation: {
        deleteGiftCardProvider,
        setGiftCardProvider,
      },
      Query: {
        getGiftCardProviders,
      },
    },
  },
  routes: {
    authorization: method({
      GET: [validateCredentials, getTransactionAuthorization],
    }),
    cancellation: method({
      GET: [validateCredentials, listAllCancellations],
      POST: [validateCredentials, createCancellation],
    }),
    create: method({
      POST: [validateCredentials, getOrCreateGiftCard],
    }),
    get: method({
      GET: [validateCredentials, getOrCreateGiftCard],
    }),
    getTransaction: method({
      GET: [validateCredentials, getTransactionById],
    }),
    list: method({
      POST: [validateCredentials, listGiftCards],
    }),
    settlement: method({
      GET: [validateCredentials, listAllSettlements],
      POST: [validateCredentials, createSettlement],
    }),
    transactions: method({
      GET: [validateCredentials, listTransactions],
      POST: [validateCredentials, createTransaction],
    }),
  },
})

```


[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 giftcard-protocol-example/node/clients/vtexCommerce.ts from the giftcard-protocol-example VTEX app.

[Assistant]
Here's the implementation:

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

export default class VtexCommerce extends ExternalClient {
  constructor(ctx: IOContext, baseRoute: string, options?: InstanceOptions) {
    super(`http://api.vtex.com/api/${baseRoute}`, ctx, {
      ...options,
      headers: {
        VtexIdclientAutCookie: ctx.authToken,
        ...options?.headers,
      },
      params: {
        an: ctx.account,
        ...options?.params,
      },
    })
  }
}

```


[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 giftcard-protocol-example/node/clients/giftCardHub.ts from the giftcard-protocol-example VTEX app.

[Assistant]
Here's the implementation:

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

import { createTracing } from '../utils/tracing'
import VtexCommerce from './vtexCommerce'

export class GiftCardHub extends VtexCommerce {
  constructor(ctx: IOContext, options?: InstanceOptions) {
    super(ctx, 'giftcardproviders', {
      ...options,
      headers: {
        ...(ctx.adminUserAuthToken
          ? {
              VtexIdclientAutCookie: ctx.adminUserAuthToken,
            }
          : {}),
      },
    })
  }

  public getProviders(userToken: string, tracingConfig?: RequestTracingConfig) {
    const metric = 'giftcardprovider-getProviders'

    return this.http.get<GiftCardProvider[]>('', {
      headers: {
        VtexIdclientAutCookie: userToken,
      },
      metric,
      tracing: createTracing(metric, tracingConfig),
    })
  }

  // eslint-disable-next-line max-params
  public createOrUpdateGiftCardProvider(
    id: string,
    body: GiftCardProvider,
    userToken: string,
    tracingConfig?: RequestTracingConfig
  ) {
    const metric = 'giftcardprovider-createOrUpdate'
    return this.http.put<GiftCardProviderResponse>(id, body, {
      headers: {
        VtexIdclientAutCookie: userToken,
      },
      metric,
      tracing: createTracing(metric, tracingConfig),
    })
  }

  public deleteGiftCardById(
    id: string,
    userToken: string,
    tracingConfig?: RequestTracingConfig
  ) {
    const metric = 'giftcardprovider-Delete'
    return this.http.delete<any>(id, {
      headers: {
        VtexIdclientAutCookie: userToken,
      },
      metric,
      tracing: createTracing(metric, tracingConfig),
    })
  }
}

interface GiftCardProvider {
  serviceUrl: string
  oauthProvider: string
  preAuthEnabled: boolean
  cancelEnabled: boolean
}

interface GiftCardProviderResponse extends GiftCardProvider {
  id: string
  caption: string
  _self: {
    href: 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 giftcard-protocol-example/node/clients/index.ts from the giftcard-protocol-example VTEX app.

[Assistant]
Here's the implementation:

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

import { GiftCardHub } from './giftCardHub'
import { GiftCardProvider } from './giftCardProvider'

export class Clients extends IOClients {
  public get giftCardHub() {
    return this.getOrSet('giftCardHub', GiftCardHub)
  }

  public get giftCardProvider() {
    return this.getOrSet('giftCardProvider', GiftCardProvider)
  }
}

```


[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 giftcard-protocol-example/node/clients/giftCardProvider.ts from the giftcard-protocol-example VTEX app.

[Assistant]
Here's the implementation:

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

export class GiftCardProvider extends ExternalClient {
  constructor(ctx: IOContext, options?: InstanceOptions) {
    // The first argument is the base URl of your provider API endpoint
    super('baseURL', ctx, options)
  }

  public getGiftCardById(_: string) {
    /*
      This is the method that will be used to connect to the provider API
      and get a specific gift card by its id.
      For instance, it's returning a mocked object that it's already in the format
      that VTEX expects.
      It receives a string, which is the id. For now, it returns a mocked gift card,
      but it's here where the connection with the external API will happen.
    */

    return {
      balance: 100000,
      caption: 'gift card by id',
      emissionDate: '2020-07-05T14:48:00.000Z',
      expiringDate: '2030-10-10T14:48:00.000Z',
      id: 'xpto1',
      provider: 'FabianaTest',
      transaction: {
        href: 'appliancetheme/giftcardproviders/FabianaTest',
      },
    }
  }

  public getListOfGiftCards(_: GiftCardListRequest) {
    /*
      This is the method that will be used to connect to the provider API
      and get a list of available gift cards.
      For instance, it's returning a mocked object that it's already in the format
      that VTEX expects.
      It receives a well defined body, which is the format that the hub uses. For now,
      it's returning a mocked list that contains only one gift card that is already
      in the format that the Hub expects.
    */

    return [
      {
        balance: 100000,
        caption: 'gift card by id',
        emissionDate: '2020-07-05T14:48:00.000Z',
        expiringDate: '2030-10-10T14:48:00.000Z',
        id: 'xpto1',
        provider: 'FabianaTest',
        transaction: {
          href: 'appliancetheme/giftcardproviders/FabianaTest',
        },
      },
    ]
  }

  public createGiftCard(body: GiftCardRequest) {
    /*
      This is the method that will be used to connect to the provider API
      and create a gift card. It needs to create the gift card and return a body
      response in the format that VTEX expects.
    */
    return body
  }

  public createTransaction(_: string, __: TransactionRequest) {
    /*
      This is the method that will be used to connect to the provider API
      and create a gift card. It needs to create the gift card and return a body
      response in the format that VTEX expects.
    */
    return {
      cardId: 'xpto1',
      id: '01010101',
      _self: {
        href: 'appliancetheme/giftcardproviders/FabianaTest',
      },
    }
  }

  public listTransactions(_: string) {
    /*
      This is the method that will be used to connect to the provider API
      and create a gift card. It needs to create the gift card and return a body
      response in the format that VTEX expects.
    */
    return []
  }

  public getTransactionById(_: string, __: string) {
    /*
      Method that handlers the case of getting a transaction by its id.
      The parameter is the id.
    */
    return {}
  }

  public getTransactionAuthorization(_: string, __: string) {
    /*
      Method that handlers the case of getting a transaction authorization by its id.
      The parameters are the transaction id and the gift card id.
    */
    return {}
  }

  public createCancellation(
    _: string,
    __: string,
    ___: CreateCancellationBody
  ) {
    /*
      Method that handlers the case of creating a transaction cancellation.
    */
    return {}
  }

  public listAllCancellations(_: string, __: string) {
    /*
      Method that handlers the case of getting a transaction authorization by its id.
      The parameter is the id.
    */
    return {}
  }

  public createSettlement(_: string, __: string, ___: CreateSettlementBody) {
    /*
      Method that handlers the case of creating a transaction settlement.
    */
    return {}
  }

  public listAllSettlements(_: string, __: string) {
    /*
      Method that handlers the case of getting a transaction authorization by its id.
      The parameter is the id.
    */
    return {}
  }
}

```


[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 giftcard-protocol-example/node/parsers/vtexToProvider.ts from the giftcard-protocol-example VTEX app.

[Assistant]
Here's the implementation:

```typescript
export const parseGiftCardToProvider = (giftCardRequest: GiftCardRequest) => {
  // Parse here the checkout request to the expected format
  return giftCardRequest
}

export const parseTransactionToProvider = (
  transactionRequest: TransactionRequest
) => {
  // Parse here the checkout request to the expected format
  return transactionRequest
}

```


[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 giftcard-protocol-example/node/parsers/providerToVtex.ts from the giftcard-protocol-example VTEX app.

[Assistant]
Here's the implementation:

```typescript
export const parseGiftCardToVtex = (
  providerResponse: unknown // replace unknown with the typing of your provider
): GiftCardResponse => {
  // Parse here your response to the expected format
  return providerResponse as GiftCardResponse
}

export const parseTransactionToVtex = (
  providerResponse: unknown // replace unknown with the typing of your provider
): TransactionResponse => {
  // Parse here your response to the expected format
  return providerResponse as TransactionResponse
}

```


[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 giftcard-protocol-example/node/typings/orderForm.d.ts from the giftcard-protocol-example VTEX app.

[Assistant]
Here's the implementation:

```typescript
interface OrderFormConfiguration {
  paymentConfiguration: PaymentConfiguration
  taxConfiguration: TaxConfiguration | null
  minimumQuantityAccumulatedForItems: number
  decimalDigitsPrecision: number
  minimumValueAccumulated: number
  apps: App[]
  allowMultipleDeliveries: boolean
  allowManualPrice: boolean
  maxNumberOfWhiteLabelSellers: number
  maskFirstPurchaseData: boolean
  recaptchaValidation: boolean
}

interface PaymentConfiguration {
  requiresAuthenticationForPreAuthorizedPaymentOption: boolean
  allowInstallmentsMerge: boolean
  blockPaymentSession: boolean
  paymentSystemToCheckFirstInstallment: boolean
}

interface TaxConfiguration {
  allowExecutionAfterErrors: boolean
  authorizationHeader: string
  integratedAuthentication: boolean
  url: string | null
}

interface App {
  fields: string[]
  id: string
  major: 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 giftcard-protocol-example/node/typings/transaction.d.ts from the giftcard-protocol-example VTEX app.

[Assistant]
Here's the implementation:

```typescript
interface TransactionRequest {
  operation: string
  value: number
  descrption: string
  redemptionToken: string
  redemptionCode: string
  requestId: string
  orderInfo: OrderInfo
  paymentRelatedSellerInfo: PaymentRelatedSellerInfo
}

interface TransactionResponse {
  cardId: string
  id: string
  _self: {
    href: string
  }
}

interface Transaction {
  value: number
  description: string
  redemptionCode: string
  date: string
  requestId: string
  orderInfo: OrderInfo
  settlement: {
    _href: string
  }
  cancellation: {
    _href: string
  }
  authorization: {
    _href: string
  }
  operation: string
}

interface PaymentRelatedSellerInfo {
  seller: string
  sellerOrderId: string
  sellerOrderId: string
  sellerSequence: string
  value: number
}

interface OrderInfo {
  orderId: string
  sequence: string
  cart: Cart
  clientProfile: Client
  shipping: string
}

interface AuthorizationInfo {
  oid: string
  value: number
  date: string
}

interface CancellationInfo {
  oid: string
  value: number
  date: string
}

interface SettlementInfo {
  oid: string
  value: number
  date: 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 giftcard-protocol-example/node/typings/cancellation.d.ts from the giftcard-protocol-example VTEX app.

[Assistant]
Here's the implementation:

```typescript
interface CreateCancellationBody {
  value: Float32Array
  requestId: 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 giftcard-protocol-example/node/typings/settlement.d.ts from the giftcard-protocol-example VTEX app.

[Assistant]
Here's the implementation:

```typescript
interface CreateSettlementBody {
  value: Float32Array
  requestId: 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 giftcard-protocol-example/node/typings/giftCard.d.ts from the giftcard-protocol-example VTEX app.

[Assistant]
Here's the implementation:

```typescript
interface GiftCardListResponse {
  id: string
  provider: string
  balance: number
  totalBalance?: number
  relationName?: string
  caption?: string
  groupName: string
  _self: {
    href: string
  }
}

interface GiftCardResponse {
  id: string
  redemptionToken?: string
  balance: number
  relationname?: string
  emissionDate: string
  expiringDate: string
  caption?: string
  provider: string
  discount?: boolean
  groupName?: string
  transaction: {
    _href: string
  }
}

interface GiftCardRequest {
  relationName: string
  expiringDate: string
  caption: string
  redemptionCode: string
  profileId: string
  multipleRedemptions?: boolean
  restrictedToOwner?: boolean
  multipleCredits?: boolean
}

interface GiftCardListRequest {
  client: Client
  cart: Cart
}

interface Client {
  id: string
  email: string
  document: string
}

interface Cart {
  grandTotal: number
  relationName: string | null
  redemptionCode: string
  discount: number
  shipping: number
  taxes: number
  items: Item[]
  itemsTotal: number
}

interface Item {
  productId: string
  id: string
  refId: string
  name: string | null
  price: number
  quantity: 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 giftcard-protocol-example/node/utils/tracing.ts from the giftcard-protocol-example VTEX app.

[Assistant]
Here's the implementation:

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

export const createTracing = (
  metric: string,
  tracingConfig?: RequestTracingConfig
) => ({
  requestSpanNameSuffix: metric,
  ...tracingConfig?.tracing,
})

```


[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 giftcard-protocol-example/node/resolvers/setGiftCardProvider.ts from the giftcard-protocol-example VTEX app.

[Assistant]
Here's the implementation:

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

export async function setGiftCardProvider(
  _: unknown,
  { id, giftCardProvInput }: SetInput,
  ctx: Context
) {
  /*
    This resolver is responsible for configuring a gift card
    provider on an account by using GraphQL
  */

  const {
    clients: { giftCardHub },
    vtex: { adminUserAuthToken: userToken },
  } = ctx

  if (!userToken) {
    throw new AuthenticationError('No authorization provided')
  }

  return giftCardHub.createOrUpdateGiftCardProvider(
    id,
    giftCardProvInput,
    userToken
  )
}

interface SetInput {
  id: string
  giftCardProvInput: GiftCardProvider
}

interface GiftCardProvider {
  serviceUrl: string
  oauthProvider: string
  preAuthEnabled: boolean
  cancelEnabled: 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 giftcard-protocol-example/node/resolvers/deleteGiftCardProvider.ts from the giftcard-protocol-example VTEX app.

[Assistant]
Here's the implementation:

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

export async function deleteGiftCardProvider(
  _: unknown,
  { id }: DeleteInput,
  ctx: Context
) {
  /*
    This resolver is responsible for deleting a gift card provider
    on an account by using GraphQL
  */

  const {
    clients: { giftCardHub },
    vtex: { adminUserAuthToken: userToken },
  } = ctx

  if (!userToken) {
    throw new AuthenticationError('No authorization provided')
  }

  return giftCardHub.deleteGiftCardById(id, userToken)
}

interface DeleteInput {
  id: 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 giftcard-protocol-example/node/resolvers/getProviders.ts from the giftcard-protocol-example VTEX app.

[Assistant]
Here's the implementation:

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

export async function getGiftCardProviders(
  _: unknown,
  __: unknown,
  ctx: Context
) {
  const {
    clients: { giftCardHub },
    vtex: { adminUserAuthToken: userToken },
  } = ctx

  if (!userToken) {
    throw new AuthenticationError('No authorization provided')
  }

  return giftCardHub.getProviders(userToken)
}

```


[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 giftcard-protocol-example/node/handlers/cancellations.ts from the giftcard-protocol-example VTEX app.

[Assistant]
Here's the implementation:

```typescript
import { json } from 'co-body'

export async function listAllCancellations(ctx: Context) {
  const {
    clients: { giftCardProvider },
    vtex: {
      route: {
        params: { giftCardId, id },
      },
    },
  } = ctx

  ctx.status = 200
  ctx.body = giftCardProvider.listAllCancellations(
    id as string,
    giftCardId as string
  )
}

export async function createCancellation(ctx: Context) {
  const body: CreateCancellationBody = await json(ctx.req)

  const {
    clients: { giftCardProvider },
    vtex: {
      route: {
        params: { giftCardId, id },
      },
    },
  } = ctx

  ctx.status = 200
  ctx.body = giftCardProvider.createCancellation(
    id as string,
    giftCardId as string,
    body
  )
}

```


[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 giftcard-protocol-example/node/handlers/giftcards.ts from the giftcard-protocol-example VTEX app.

[Assistant]
Here's the implementation:

```typescript
import { json } from 'co-body'

export async function getOrCreateGiftCard(ctx: Context) {
  const {
    clients: { giftCardProvider },
    vtex: {
      route: {
        params: { id },
      },
    },
  } = ctx

  if (id) {
    ctx.body = giftCardProvider.getGiftCardById(id as string)
  } else {
    const body = await json(ctx.req)
    ctx.body = giftCardProvider.createGiftCard(body)
  }

  ctx.status = 200
  ctx.set('Cache-Control', 'no-cache,no-store')
}

export async function listGiftCards(ctx: Context) {
  const body = await json(ctx.req)

  const {
    clients: { giftCardProvider },
  } = ctx

  ctx.status = 200
  ctx.set('Cache-Control', 'no-cache,no-store')
  ctx.body = giftCardProvider.getListOfGiftCards(body)
}

```


[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 giftcard-protocol-example/node/handlers/transactions.ts from the giftcard-protocol-example VTEX app.

[Assistant]
Here's the implementation:

```typescript
import { json } from 'co-body'

export async function listTransactions(ctx: Context) {
  const {
    clients: { giftCardProvider },
    vtex: {
      route: {
        params: { giftCardId },
      },
    },
  } = ctx

  ctx.status = 200
  ctx.body = giftCardProvider.listTransactions(giftCardId as string)
}

export async function createTransaction(ctx: Context) {
  const body = await json(ctx.req)

  const {
    clients: { giftCardProvider },
    vtex: {
      route: {
        params: { giftCardId },
      },
    },
  } = ctx

  ctx.status = 200
  ctx.body = giftCardProvider.createTransaction(giftCardId as string, body)
}

export async function getTransactionById(ctx: Context) {
  const {
    clients: { giftCardProvider },
    vtex: {
      route: {
        params: { giftCardId, id },
      },
    },
  } = ctx

  ctx.status = 200
  ctx.body = giftCardProvider.getTransactionById(
    id as string,
    giftCardId as string
  )
}

export async function getTransactionAuthorization(ctx: Context) {
  const {
    clients: { giftCardProvider },
    vtex: {
      route: {
        params: { giftCardId, id },
      },
    },
  } = ctx

  ctx.status = 200
  ctx.body = giftCardProvider.getTransactionAuthorization(
    id as string,
    giftCardId as 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 giftcard-protocol-example/node/handlers/credentials.ts from the giftcard-protocol-example VTEX app.

[Assistant]
Here's the implementation:

```typescript
export async function validateCredentials(ctx: Context, next: () => Promise<any>) {
  if (!ctx.headers['x-provider-api-appkey'] || !ctx.headers['x-provider-api-apptoken']) {
    ctx.status = 401
    ctx.body = {
      message: 'Unauthorized request',
      status: 401
    }
    return
  }

  let appSettings: Record<string, unknown>;

  try {
  const appId = process.env.VTEX_APP_ID || ctx.vtex

    appSettings = await ctx.clients.apps.getAppSettings(appId)

    if (!appSettings) {
      ctx.status = 400;
      ctx.body = {
        message: 'Empty app settings giftcard protocol configuration',
        status: 400
      }
      return
    }
  } catch (error) {
    ctx.status = 500;
    ctx.body = {
      message: 'error loading app settings',
      status: 500
    }
    return
  }

  const { giftCardHubAppKey, giftCardHubAppToken } = appSettings

  if (ctx.headers['x-provider-api-appkey'] !== giftCardHubAppKey ||
    ctx.headers['x-provider-api-apptoken'] !== giftCardHubAppToken
  ) {
    ctx.status = 403
    ctx.body = {
      message: 'Forbidden request',
      status: 403
    }
    return
  }

  return 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 giftcard-protocol-example/node/handlers/settlements.ts from the giftcard-protocol-example VTEX app.

[Assistant]
Here's the implementation:

```typescript
import { json } from 'co-body'

export async function listAllSettlements(ctx: Context) {
  const {
    clients: { giftCardProvider },
    vtex: {
      route: {
        params: { giftCardId, id },
      },
    },
  } = ctx

  ctx.status = 200
  ctx.body = giftCardProvider.listAllSettlements(
    id as string,
    giftCardId as string
  )
}

export async function createSettlement(ctx: Context) {
  const body: CreateSettlementBody = await json(ctx.req)

  const {
    clients: { giftCardProvider },
    vtex: {
      route: {
        params: { giftCardId, id },
      },
    },
  } = ctx

  ctx.status = 200
  ctx.body = giftCardProvider.createSettlement(
    id as string,
    giftCardId as string,
    body
  )
}

```


[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 search-page-context/docs/README.md from the search-page-context VTEX app.

[Assistant]
Here's the implementation:

```markdown
# VTEX Search Page Context app

This app is the search page context, contains three contexts.

1 - `SearchPageContext`: pass down variables set by user in blocks (SearchPageContext). This way, the children in flex search-result can access it.

2 - `SearchPageStateContext`: holds variable state in search page, like if the search is loading, what mobile layout is selected, etc. (SearchPageStateContext)

3 - `SearchPageDispatchContext`: holds the dispatch function for the search page state context.

## Usage

```jsx
import {
  useSearchPageState,
  useSearchPage,
  useSearchPageStateDispatch,
} from 'vtex.search-page-context/SearchPageContext'

...

const { pagination, searchQuery } = useSearchPage()
const { isFetchingMore } = useSearchPageState()
const dispatch = useSearchPageStateDispatch()
```

```


[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 search-page-context/react/package.json from the search-page-context VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "devDependencies": {
    "@types/node": "^11.13.4",
    "@types/react": "^16.8.13",
    "typescript": "3.9.7"
  },
  "dependencies": {
    "react": "^16.8.3",
    "react-dom": "^16.8.3"
  },
  "version": "0.2.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 search-page-context/react/SearchPageContext.ts from the search-page-context VTEX app.

[Assistant]
Here's the implementation:

```typescript
import { createContext, useContext, useReducer } from 'react'
import type { MaybeResponsiveInput } from 'vtex.responsive-values'

const SearchPageContext = createContext({})

const useSearchPage = () => useContext(SearchPageContext)

const SearchPageStateContext = createContext({} as State)

const useSearchPageState = () => useContext(SearchPageStateContext)

const SearchPageStateDispatch = createContext((_: ReducerActions) => {})

const useSearchPageStateDispatch = () => useContext(SearchPageStateDispatch)

interface LayoutOption {
  name: string
  component: string
  itemsPerRow: MaybeResponsiveInput<number>
}

interface State {
  mobileLayout?: string
  showContentLoader?: boolean
  isFetchingMore?: boolean
  galleryLayouts?: LayoutOption[]
  selectedGalleryLayout?: string
  /** For accessibility purposes */
  focusedGalleryLayout?: string
}

interface InitialArgs {
  mobileLayout: string
  showContentLoader: boolean
  selectedGalleryLayout?: string
}

type ReducerActions =
  | { type: 'SWITCH_LAYOUT'; args: { mobileLayout: string } }
  | { type: 'HIDE_CONTENT_LOADER' }
  | { type: 'SET_FETCHING_MORE'; args: { isFetchingMore: boolean } }
  | { type: 'SET_GALLERY_LAYOUTS'; args: { galleryLayouts: LayoutOption[] } }
  | {
      type: 'SWITCH_GALLERY_LAYOUT'
      args: { selectedGalleryLayout: string; focus?: boolean }
    }
  | { type: 'SET_FOCUS_GALLERY_LAYOUT'; args: { focusedGalleryLayout: string } }

function reducer(state: State, action: ReducerActions): State {
  switch (action.type) {
    case 'SWITCH_LAYOUT': {
      const { mobileLayout } = action.args

      return { ...state, mobileLayout }
    }

    case 'HIDE_CONTENT_LOADER': {
      return { ...state, showContentLoader: false }
    }

    case 'SET_FETCHING_MORE': {
      const { isFetchingMore } = action.args

      return { ...state, isFetchingMore }
    }

    case 'SET_GALLERY_LAYOUTS': {
      const { galleryLayouts } = action.args

      return { ...state, galleryLayouts }
    }

    case 'SWITCH_GALLERY_LAYOUT': {
      const { selectedGalleryLayout, focus = true } = action.args

      const newState = {
        ...state,
        selectedGalleryLayout,
      }

      if (focus) {
        newState.focusedGalleryLayout = selectedGalleryLayout
      }

      return newState
    }

    case 'SET_FOCUS_GALLERY_LAYOUT': {
      const { focusedGalleryLayout } = action.args

      return { ...state, focusedGalleryLayout }
    }

    default:
      return state
  }
}

const useSearchPageStateReducer = (initialState: InitialArgs) => {
  return useReducer(reducer, {
    mobileLayout: initialState.mobileLayout,
    showContentLoader: initialState.showContentLoader,
    selectedGalleryLayout: initialState.selectedGalleryLayout,
    isFetchingMore: false,
  })
}

export default {
  SearchPageContext,
  useSearchPage,
  SearchPageStateContext,
  useSearchPageState,
  SearchPageStateDispatch,
  useSearchPageStateDispatch,
  useSearchPageStateReducer,
}

```


[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 search-page-context/react/typings/vtex.responsive-values.d.ts from the search-page-context VTEX app.

[Assistant]
Here's the implementation:

```typescript
declare module 'vtex.responsive-values' {
  const useResponsiveValues: (input: any) => any
  const useResponsiveValue: <T>(input: MaybeResponsiveInput<T>) => T

  // eslint-disable-next-line no-restricted-syntax
  enum InputDevices {
    Mobile = 'mobile',
    Phone = 'phone',
    Tablet = 'tablet',
    Desktop = 'desktop',
  }

  // eslint-disable-next-line no-restricted-syntax
  enum InputDevices {
    MOBILE = 'mobile',
    PHONE = 'phone',
    TABLET = 'tablet',
    DESKTOP = 'desktop',
  }

  // eslint-disable-next-line no-restricted-syntax
  enum InputDevices {
    mobile = 'mobile',
    phone = 'phone',
    tablet = 'tablet',
    desktop = 'desktop',
  }

  // eslint-disable-next-line no-restricted-syntax
  enum OutputDevices {
    phone = 'phone',
    tablet = 'tablet',
    desktop = 'desktop',
  }

  type ResponsiveInput<T> = { [P in keyof typeof InputDevices]?: T }
  export type MaybeResponsiveInput<T> = T | ResponsiveInput<T>

  type ResponsiveOutput<T> = { [P in keyof typeof OutputDevices]: T }
}

```


[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 collections/graphql/schema.graphql from the collections VTEX app.

[Assistant]
Here's the implementation:

```graphql
type Query {
  collections(
    searchKey: String
    page: Int
    pageSize: Int
  ): CollectionsList

  collection(
    id: Int
    page: Int
    pageSize: Int
  ): Collection

  collectionContains(
    collectionId: Int
    skus: [SkuContainsInput]
  ): ContainsResult

  categoriesAutocomplete(
    name: String
  ): [Category]

  brandsAutocomplete(
    name: String
  ): [Brand]

  getBrands(
    ids: [Int]
  ): [Brand]

  getCategories(
    ids: [Int]
  ): [Category]

  getProductsBySku(
    ids: [Int]
    from: Int = 0
    to: Int = 9
  ): ProductResult

  getProducts(
    query: String = "",
    category: String = "",
    specificationFilters: [String],
    priceRange: String = "",
    collection: String = "",
    salesChannel: String = "",
    orderBy: String = "OrderByPriceDESC",
    from: Int = 0,
    to: Int = 9
  ): ProductResult
}

type Mutation {
  createCollection(
    name: String
    searchable: Boolean
    highlight: Boolean
    dateFrom: String
    dateTo: String
    groups: [GroupInput]
  ) : Int

  updateGroup(
    collectionId: Int
    name: String
    type: String
    preSale: Boolean
    release: Boolean
    brands: [Int]
    categories: [Int]
    skus: [Int]
  ) : 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 collections/node/package.json from the collections VTEX app.

[Assistant]
Here's the implementation:

```json
{
  "name": "vtex.collections",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "dependencies": {
    "axios": "^0.17.1",
    "cookie": "^0.3.1",
    "debug": "^3.1.0",
    "follow-redirects": "^1.4.0",
    "is-buffer": "^1.1.6",
    "lodash": "^4.17.4",
    "ms": "^2.0.0"
  },
  "devDependencies": {
    "@types/koa": "^2.0.44",
    "@types/node": "^9.4.7",
    "tslint": "^5.9.1",
    "tslint-config-vtex": "^2.0.0"
  },
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC"
}

```