id
stringlengths 12
53
| messages
listlengths 3
3
|
|---|---|
code_render-runtime_b512488e
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of render-runtime/react/ExtensionContainer.tsx from the render-runtime VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\n// @ts-nocheck\nimport { ExtensionContainer } from 'vtex.render-runtime'\n\nexport default ExtensionContainer\n\n```"
}
] |
code_render-runtime_cc7c036e
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of render-runtime/react/AMP.tsx from the render-runtime VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\nimport 'react-amphtml'\nimport 'react-amphtml/helpers'\n\nimport {\n AmpScriptsManager,\n AmpScripts,\n headerBoilerplate,\n} from 'react-amphtml/setup'\nimport { RenderRuntime } from './typings/runtime'\n\nexport const setupAMP = (\n root: JSX.Element,\n renderFn: any,\n runtime: RenderRuntime\n) => {\n const scripts = new AmpScripts()\n\n const ampRoot = (\n <AmpScriptsManager ampScripts={scripts}>{root}</AmpScriptsManager>\n )\n\n return {\n ampRoot,\n getExtraRenderedData: () => {\n const ampScripts = renderFn(scripts.getScriptElements())\n const ampHeadBoilerplate = runtime.route.canonicalPath\n ? renderFn(headerBoilerplate(runtime.route.canonicalPath))\n : ''\n\n return { ampScripts, ampHeadBoilerplate }\n },\n }\n}\n\n```"
}
] |
code_render-runtime_15abe8bb
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of render-runtime/react/package.json from the render-runtime VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"license\": \"UNLICENSED\",\n \"scripts\": {\n \"lint\": \"tsc --noEmit --pretty && eslint --fix --ext ts,tsx .\",\n \"test\": \"vtex-test-tools test\"\n },\n \"dependencies\": {\n \"@formatjs/intl-pluralrules\": \"^1.3.9\",\n \"@formatjs/intl-relativetimeformat\": \"^4.5.1\",\n \"@sentry/react\": \"^7.116.0\",\n \"@vtex/blocks-inspector\": \"^0.0.8\",\n \"apollo-cache-inmemory\": \"^1.6.3\",\n \"apollo-client\": \"^2.6.4\",\n \"apollo-link-error\": \"^1.1.11\",\n \"apollo-link-http\": \"^1.5.15\",\n \"apollo-link-persisted-queries\": \"^0.2.2\",\n \"apollo-upload-client\": \"^8.1.0\",\n \"apollo-utilities\": \"^1.0.16\",\n \"classnames\": \"^2.2.5\",\n \"core-js\": \"^2.5.7\",\n \"debounce\": \"^1.2.0\",\n \"eventemitter3\": \"^3.0.0\",\n \"eventsource-polyfill\": \"^0.9.6\",\n \"exenv\": \"^1.2.2\",\n \"graphql\": \"^0.13.2\",\n \"hoist-non-react-statics\": \"^2.5.0\",\n \"js-base64\": \"^2.4.9\",\n \"myvtex-sse\": \"^1.2.0\",\n \"prop-types\": \"^15.7.2\",\n \"query-string\": \"^5.1.1\",\n \"ramda\": \"^0.26.1\",\n \"react-amphtml\": \"^4.0.2\",\n \"react-apollo\": \"^3.1.2\",\n \"react-helmet\": \"^5.2.0\",\n \"react-json-view\": \"^1.19.1\",\n \"route-parser\": \"^0.0.5\",\n \"use-media\": \"^1.4.0\"\n },\n \"devDependencies\": {\n \"@apollo/react-testing\": \"3.1.2\",\n \"@types/apollo-upload-client\": \"^8.1.0\",\n \"@types/debounce\": \"^1.0.0\",\n \"@types/eventemitter3\": \"^2.0.2\",\n \"@types/graphql\": \"^0.13.3\",\n \"@types/history\": \"^4.7.2\",\n \"@types/intl\": \"^1.2.0\",\n \"@types/jest\": \"^24.0.0\",\n \"@types/js-base64\": \"^2.3.1\",\n \"@types/node\": \"^12.12.3\",\n \"@types/p-queue\": \"^3.2.1\",\n \"@types/prop-types\": \"^15.7.3\",\n \"@types/qs\": \"^6.5.1\",\n \"@types/query-string\": \"^5.1.0\",\n \"@types/ramda\": \"^0.26.36\",\n \"@types/react\": \"^16.9.35\",\n \"@types/react-content-loader\": \"^3.1.4\",\n \"@types/react-dom\": \"^16.8.0\",\n \"@types/react-helmet\": \"^5.0.5\",\n \"@types/react-hot-loader\": \"^4.1.0\",\n \"@types/route-parser\": \"^0.1.1\",\n \"@vtex/test-tools\": \"^3.0.0\",\n \"babel-core\": \"^6.26.3\",\n \"babel-jest\": \"^24.1.0\",\n \"babel-preset-env\": \"^1.7.0\",\n \"babel-preset-react-app\": \"^7.0.1\",\n \"eslint\": \"^5.16.0\",\n \"eslint-config-vtex-react\": \"^5.0.1\",\n \"eventsource-polyfill\": \"^0.9.6\",\n \"history\": \"^4.7.2\",\n \"husky\": \"^1.1.4\",\n \"jest\": \"^24.1.0\",\n \"jest-dom\": \"^3.1.1\",\n \"jest-transform-graphql\": \"^2.1.0\",\n \"lint-staged\": \"^8.0.4\",\n \"prettier\": \"^2.0.0\",\n \"react\": \"^16.8.6\",\n \"react-dom\": \"^16.8.6\",\n \"react-hot-loader\": \"^4.3.12\",\n \"react-intl\": \"^3.9.1\",\n \"react-no-ssr\": \"^1.1.0\",\n \"regenerator-runtime\": \"^0.13.1\",\n \"ts-jest\": \"^24.0.1\",\n \"typescript\": \"3.9.7\"\n },\n \"husky\": {\n \"hooks\": {\n \"pre-commit\": \"lint-staged\"\n }\n },\n \"lint-staged\": {\n \"*.{js,css,json,md}\": [\n \"prettier --write\",\n \"git add\"\n ],\n \"*.{ts,tsx}\": [\n \"eslint --fix\",\n \"git add\"\n ]\n },\n \"version\": \"8.136.1\"\n}\n\n```"
}
] |
code_render-runtime_a481388e
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of render-runtime/react/error.tsx from the render-runtime VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\n/* global module */\nimport React, { Component } from 'react'\nimport { captureException } from '@sentry/react'\n\nrequire('myvtex-sse')\n\nconst ERROR_PAGE_COMPONENT = 'ErrorPage'\n\nimport { renderReadyPromise } from '.'\nimport { isAdmin } from './utils/isAdmin'\nimport { CustomAdminTags } from './o11y/types'\nimport { extractExtra } from './o11y/extractExtra'\nimport ErrorDisplay from './components/ErrorPage/ErrorPage'\n\n/**\n * The ErrorPage component is rendered when there is an error on the Render Framework server-side lifecycle.\n *\n * Errors that occur on the client-side are caught by the ErrorBoundary component (see react/components/ErrorBoundary.tsx).\n *\n * @warning\n * Updates to this component must be followed by changes to Render Server, specifically the node/middlewares/error.ts file.\n *\n * This is required to ensure that the error page rendered during errors on the server-side lifecycle is always up-to-date, as\n * depending on the error, the Render Server may not be able to fetch the latest version of the ErrorPage component from the\n * Render Runtime, thus falling back to a hardcoded version that must be always up to date.\n *\n * Use this PR as a reference on how to update the Render Server accordingly: https://github.com/vtex/render-server/pull/800.\n */\nclass ErrorPage extends Component {\n public componentDidMount() {\n if (!isAdmin()) return\n\n const tags: CustomAdminTags = {\n admin_render_runtime_page: ERROR_PAGE_COMPONENT,\n }\n\n try {\n const error = window?.__ERROR__\n const requestId = window?.__REQUEST_ID__\n const defaultError =\n 'Render Runtime renderered an error page and there is no error or request id available'\n\n if (error) {\n captureException(error, { tags: { ...tags, ...extractExtra(error) } })\n } else if (requestId) {\n captureException(requestId, { tags })\n } else {\n captureException(defaultError, { tags })\n }\n } catch (e) {\n captureException(e, { tags })\n }\n }\n\n public render() {\n if (window.__ERROR__) console.error(window.__ERROR__)\n\n return <ErrorDisplay errorCode={window.__REQUEST_ID__} />\n }\n}\n\nif (window.__ERROR__) {\n // compatibility\n window.__RENDER_8_COMPONENTS__ =\n window.__RENDER_8_COMPONENTS__ || global.__RENDER_8_COMPONENTS__\n window.__RENDER_8_HOT__ = window.__RENDER_8_HOT__ || global.__RENDER_8_HOT__\n global.__RUNTIME__ = window.__RUNTIME__\n window.__RENDER_8_COMPONENTS__[ERROR_PAGE_COMPONENT] = ErrorPage as any\n\n const start = () => {\n global.__RUNTIME__.extensions = global.__RUNTIME__.extensions || {}\n global.__RUNTIME__.pages = global.__RUNTIME__.pages || {}\n global.__RUNTIME__.components = global.__RUNTIME__.components || {}\n global.__RUNTIME__.disableSSR = true\n global.__RUNTIME__.extensions.error = {\n component: ERROR_PAGE_COMPONENT,\n props: {},\n }\n\n window.__RENDER_8_RUNTIME__.render('error', global.__RUNTIME__)\n }\n\n renderReadyPromise.then(start)\n\n if (module.hot) {\n module.hot.accept('./core/main', () => {\n // eslint-disable-next-line @typescript-eslint/no-var-requires\n const hotGlobals = require('./core/main')\n window.__RENDER_8_RUNTIME__.ExtensionContainer =\n hotGlobals.ExtensionContainer\n window.__RENDER_8_RUNTIME__.ExtensionPoint = hotGlobals.ExtensionPoint\n window.__RENDER_8_RUNTIME__.LayoutContainer = hotGlobals.LayoutContainer\n window.__RENDER_8_RUNTIME__.Link = hotGlobals.Link\n window.__RENDER_8_RUNTIME__.Loading = hotGlobals.Loading\n window.__RENDER_8_RUNTIME__.buildCacheLocator =\n hotGlobals.buildCacheLocator\n start()\n })\n } else {\n const CLOSED = 2\n let eventSource: any\n const initSSE = () => {\n const hasNoSSE = !eventSource || eventSource.readyState === CLOSED\n if (!document.hidden && hasNoSSE) {\n eventSource = window.myvtexSSE(\n global.__RUNTIME__.account,\n global.__RUNTIME__.workspace,\n 'vtex.builder-hub:*:build.status',\n { verbose: true },\n (event: any) => {\n if (event.body && event.body.code === 'success') {\n window.location.reload()\n }\n }\n )\n }\n }\n initSSE()\n document.addEventListener('visibilitychange', initSSE)\n }\n}\n\n```"
}
] |
code_render-runtime_98ab0363
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of render-runtime/react/LegacyExtensionContainer.tsx from the render-runtime VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\n// @ts-nocheck\nimport { LegacyExtensionContainer } from 'vtex.render-runtime'\n\nexport default LegacyExtensionContainer\n\n```"
}
] |
code_render-runtime_330f1723
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of render-runtime/react/error.css from the render-runtime VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```css\n\n.imgHeight {\n height: 80px;\n}\n\n.errorStack {\n margin: 20px auto;\n max-width: 980px;\n word-wrap: 'break-word';\n}\n\n.errorDetails {\n font-family: 'courier, code';\n max-width: 980px;\n margin: 20px auto;\n word-wrap: 'break-word';\n}\n\n.stringValue {\n word-wrap: 'break-all';\n}\n\n@media only screen and (min-width: 40em) {\n .imgHeight {\n height: 225px;\n }\n}\n\n```"
}
] |
code_render-runtime_c45dbe41
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of render-runtime/react/externals.json from the render-runtime VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"commons\": {\n \"dev\": [\n {\n \"clientOnly\": true,\n \"path\": \"npm:vtex-render-session@1.9.2/dist/index.js\"\n },\n {\n \"path\": \"npm:bluebird@3.5.1/js/browser/bluebird.js\",\n \"serverOnly\": true\n },\n {\n \"path\": \"npm:regenerator-runtime@0.11.1/runtime.js\"\n },\n {\n \"global\": \"PropTypes\",\n \"import\": \"prop-types\",\n \"path\": \"npm:prop-types@15.7.2/prop-types.js\"\n },\n {\n \"global\": \"React\",\n \"import\": \"react\",\n \"path\": \"npm:react@16.9.0/umd/react.development.js\",\n \"alternative\": {\n \"enableConcurrentMode\": \"npm:react@0.0.0-experimental-94c0244ba/umd/react.development.js\"\n }\n },\n {\n \"global\": \"ReactDOM\",\n \"import\": \"react-dom\",\n \"path\": \"npm:react-dom@16.9.0/umd/react-dom.development.js\",\n \"alternative\": {\n \"enableConcurrentMode\": \"npm:react-dom@0.0.0-experimental-94c0244ba/umd/react-dom.development.js\"\n }\n },\n {\n \"global\": \"ReactDOMServer\",\n \"import\": \"react-dom/server\",\n \"path\": \"npm:react-dom@16.9.0/umd/react-dom-server.browser.development.js\",\n \"alternative\": {\n \"enableConcurrentMode\": \"npm:react-dom@0.0.0-experimental-94c0244ba/umd/react-dom-server.browser.development.js\"\n }\n },\n {\n \"global\": \"ReactIntl\",\n \"import\": \"react-intl\",\n \"path\": \"npm:react-intl@3.9.1/dist/react-intl.js\"\n },\n {\n \"global\": \"History\",\n \"import\": \"history\",\n \"path\": \"npm:history@4.7.2/umd/history.js\"\n },\n {\n \"global\": \"R\",\n \"import\": \"ramda\",\n \"path\": \"npm:ramda@0.26.1/dist/ramda.js\"\n },\n {\n \"path\": \"npm:intl@1.2.5/dist/Intl.js\",\n \"serverOnly\": true\n },\n {\n \"clientOnly\": true,\n \"path\": \"npm:lazysizes@5.3.2/plugins/unveilhooks/ls.unveilhooks.min.js\"\n },\n {\n \"clientOnly\": true,\n \"path\": \"npm:lazysizes@5.3.2/lazysizes.min.js\"\n },\n {\n \"clientOnly\": true,\n \"path\": \"npm:fg-loadcss@2.1.0/dist/cssrelpreload.min.js\"\n },\n {\n \"cssRelPreload\": true,\n \"path\": \"npm:animate.css@3.7.0/animate.css\"\n },\n {\n \"path\": \"npm:vtex-tachyons@3.1.0/tachyons.css\"\n },\n {\n \"path\": \"runtime:AMP\",\n \"serverOnly\": true\n },\n {\n \"path\": \"runtime:intl-polyfill\",\n \"serverOnly\": true\n }\n ],\n \"prod\": [\n {\n \"clientOnly\": true,\n \"path\": \"npm:vtex-render-session@1.9.2/dist/index.min.js\"\n },\n {\n \"path\": \"npm:bluebird@3.5.1/js/browser/bluebird.min.js\",\n \"serverOnly\": true\n },\n {\n \"path\": \"npm:regenerator-runtime@0.11.1/runtime.js\"\n },\n {\n \"global\": \"PropTypes\",\n \"import\": \"prop-types\",\n \"path\": \"npm:prop-types@15.7.2/prop-types.min.js\"\n },\n {\n \"global\": \"React\",\n \"import\": \"react\",\n \"path\": \"npm:react@16.9.0/umd/react.production.min.js\",\n \"alternative\": {\n \"enableConcurrentMode\": \"npm:react@0.0.0-experimental-94c0244ba/umd/react.production.min.js\"\n }\n },\n {\n \"global\": \"ReactDOM\",\n \"import\": \"react-dom\",\n \"path\": \"npm:react-dom@16.9.0/umd/react-dom.production.min.js\",\n \"alternative\": {\n \"enableConcurrentMode\": \"npm:react-dom@0.0.0-experimental-94c0244ba/umd/react-dom.production.min.js\"\n }\n },\n {\n \"global\": \"ReactDOMServer\",\n \"import\": \"react-dom/server\",\n \"path\": \"npm:react-dom@16.9.0/umd/react-dom-server.browser.production.min.js\",\n \"alternative\": {\n \"enableConcurrentMode\": \"npm:react-dom@0.0.0-experimental-94c0244ba/umd/react-dom-server.browser.production.min.js\"\n }\n },\n {\n \"global\": \"ReactIntl\",\n \"import\": \"react-intl\",\n \"path\": \"npm:react-intl@3.9.1/dist/react-intl.min.js\"\n },\n {\n \"global\": \"History\",\n \"import\": \"history\",\n \"path\": \"npm:history@4.7.2/umd/history.min.js\"\n },\n {\n \"global\": \"R\",\n \"import\": \"ramda\",\n \"path\": \"npm:ramda@0.26.1/dist/ramda.min.js\"\n },\n {\n \"path\": \"npm:intl@1.2.5/dist/Intl.min.js\",\n \"serverOnly\": true\n },\n {\n \"clientOnly\": true,\n \"path\": \"npm:lazysizes@5.3.2/plugins/unveilhooks/ls.unveilhooks.min.js\"\n },\n {\n \"clientOnly\": true,\n \"path\": \"npm:lazysizes@5.3.2/lazysizes.min.js\"\n },\n {\n \"clientOnly\": true,\n \"path\": \"npm:fg-loadcss@2.1.0/dist/cssrelpreload.min.js\"\n },\n {\n \"cssRelPreload\": true,\n \"path\": \"npm:animate.css@3.7.0/animate.min.css\"\n },\n {\n \"path\": \"npm:vtex-tachyons@3.1.0/tachyons.min.css\"\n },\n {\n \"path\": \"runtime:AMP\",\n \"serverOnly\": true\n },\n {\n \"path\": \"runtime:intl-polyfill\",\n \"serverOnly\": true\n }\n ]\n },\n \"vtex\": {},\n \"gocommerce\": {}\n}\n\n```"
}
] |
code_render-runtime_1eff6d91
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of render-runtime/react/core/main.tsx from the render-runtime VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport 'apollo-cache-inmemory'\nimport 'apollo-client'\nimport 'apollo-link-http'\nimport 'apollo-link-persisted-queries'\nimport 'apollo-upload-client'\nimport 'apollo-utilities'\nimport 'classnames'\nimport 'graphql'\nimport EventEmitter from 'eventemitter3'\nimport { createBrowserHistory as createHistory } from 'history'\nimport queryString from 'query-string'\nimport React, { ReactElement } from 'react'\nimport { getDataFromTree } from 'react-apollo'\nimport {\n hydrate as hydrateDOM,\n render as renderDOM,\n unstable_createRoot,\n} from 'react-dom'\nimport Helmet from '../components/Helmet'\nimport NoSSR, { useSSR } from '../components/NoSSR'\nimport { isEmpty } from 'ramda'\nimport Loading from '../components/Loading'\nimport {\n MaybeLazyImage,\n LazyImages,\n useLazyImagesContext,\n} from '../components/LazyImages'\nimport { LoadingContextProvider } from '../components/LoadingContext'\n\nimport ChildBlock from '../components/ChildBlock'\nimport useChildBlock from '../components/useChildBlock'\nimport ExtensionContainer from '../components/ExtensionPoint/ExtensionContainer'\nimport ExtensionPoint from '../components/ExtensionPoint'\nimport Block from '../components/Block'\nimport LayoutContainer from '../components/LayoutContainer'\nimport LegacyExtensionContainer from '../components/ExtensionPoint/LegacyExtensionContainer'\nimport Link from '../components/Link'\nimport RenderContext from '../components/RenderContext'\n/** Important: Builder-Hub will only export types of functions imported from individual files.\n * So `useRuntime` should be imported from `../components/useRuntime`\n * and `withRuntimeContext` from `../components/withRuntimeContext` rather than being imported\n * along with the other functions from `RenderContext` */\nimport useRuntime from '../components/useRuntime'\nimport withRuntimeContext from '../components/withRuntimeContext'\nimport canUseDOM from '../components/canUseDOM'\nimport RenderProvider from '../components/RenderProvider'\nimport { getVTEXImgHost } from '../utils/assets'\nimport PageCacheControl from '../utils/cacheControl'\nimport {\n getState,\n createApolloClient,\n ApolloClientFunctions,\n} from '../utils/client'\nimport { buildCacheLocator } from '../utils/client'\nimport { getMarkups, getOrCreateContainer } from '../utils/dom'\nimport { registerEmitter } from '../utils/events'\nimport { getBaseURI } from '../utils/host'\nimport registerComponent from '../utils/registerComponent'\nimport { withSession } from '../utils/session'\nimport { TreePathContext, useTreePath } from '../utils/treePath'\nimport {\n isStyleWritable,\n optimizeSrcForVtexImg,\n optimizeStyleForVtexImg,\n} from '../utils/vteximg'\nimport withHMR from '../utils/withHMR'\nimport { generateExtensions } from '../utils/blocks'\nimport { promised } from '../utils/promise'\nimport {\n RenderedSuccess,\n NamedServerRendered,\n Rendered,\n ServerRendered,\n} from '../typings/global'\nimport { RenderRuntime, Extensions } from '../typings/runtime'\n// We need to keep this import so the types of this modules are kept in the final bundle by the Builder Hub.\nimport '../typings/runtime'\n\nlet emitter: EventEmitter | null = null\nconst cssClasses = new Set<string>()\n\nconst renderExtension = (\n extensionName: string,\n destination: HTMLElement,\n props = {}\n) => {\n if (emitter) {\n emitter.emit('renderExtensionLoader.addOrUpdateExtension', {\n destination,\n extensionName,\n props,\n })\n } else {\n throw new Error(`ExtensionPortal can't be rendered before RenderProvider`)\n }\n}\n\nfunction renderToStringWithData(\n component: ReactElement<any>,\n renderFn: (root: ReactElement) => string,\n skipQuery = false\n): Promise<ServerRendered> {\n const getDataFn = (): Promise<string | void> => {\n if (skipQuery) return Promise.resolve()\n return getDataFromTree(component)\n }\n\n const startGetDataFromTree = window.hrtime()\n return getDataFn().then(() => {\n const endGetDataFromTree = window.hrtime(startGetDataFromTree)\n\n const startRenderToString = window.hrtime()\n const markup = renderFn(component)\n const endRenderToString = window.hrtime(startRenderToString)\n return {\n markup,\n renderTimeMetric: {\n getDataFromTree: endGetDataFromTree,\n renderToString: endRenderToString,\n },\n }\n })\n}\n\nconst clientRender = (\n root: JSX.Element,\n elem: Element,\n hydrate: boolean,\n concurrent?: boolean\n): Promise<void> => {\n return promised((resolve) => {\n if (concurrent) {\n unstable_createRoot(elem, { hydrate }).render(root)\n resolve()\n } else if (hydrate) {\n hydrateDOM(root, elem, resolve)\n } else {\n renderDOM(root, elem, resolve)\n }\n })\n}\n\nconst createRootElement = (\n name: string,\n runtime: RenderRuntime,\n sessionPromise: Promise<void>,\n apollo: ApolloClientFunctions\n) => {\n const { customRouting, pages, extensions } = runtime\n const isPage =\n !!pages[name] && !!pages[name].path && !!extensions[name]?.component\n const history = canUseDOM && isPage && !customRouting ? createHistory() : null\n\n return (\n <RenderProvider\n apollo={apollo}\n history={history}\n root={name}\n runtime={runtime}\n sessionPromise={sessionPromise}\n >\n {!isPage ? <ExtensionPoint id={name} /> : null}\n </RenderProvider>\n )\n}\n\nconst prepareRootElement = (\n name: string,\n runtime: RenderRuntime,\n baseURI: string,\n cacheControl: PageCacheControl | undefined\n) => {\n const sessionPromise = canUseDOM\n ? window.__RENDER_8_SESSION__.sessionPromise\n : Promise.resolve()\n\n return createApolloClient(\n runtime,\n baseURI,\n sessionPromise,\n cacheControl\n ).then((apollo) =>\n apollo\n .hydrate(runtime.queryData)\n .then(() => createRootElement(name, runtime, sessionPromise, apollo))\n )\n}\n\n// Either renders the root component to a DOM element or returns a {name, markup} promise.\nconst render = async (\n name: string,\n runtime: RenderRuntime,\n element?: HTMLElement\n): Rendered => {\n const { concurrentMode, disableSSR, disableSSQ, page } = runtime\n\n const cacheControl = canUseDOM ? undefined : new PageCacheControl()\n const baseURI = getBaseURI(runtime)\n emitter = registerEmitter(runtime, baseURI)\n\n if (canUseDOM) {\n const { container, created } = element\n ? { container: element, created: false }\n : getOrCreateContainer()\n const shouldHydrate = !(disableSSR || created)\n return promised<void>((resolve) => {\n prepareRootElement(name, runtime, baseURI, cacheControl)\n .then((root) =>\n clientRender(root, container, shouldHydrate, concurrentMode)\n )\n .then(resolve)\n })\n }\n\n // eslint-disable-next-line @typescript-eslint/no-var-requires\n const { renderToStaticMarkup, renderToString } = require('react-dom/server')\n\n const commonRenderResult = {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n maxAge: cacheControl!.maxAge,\n page,\n }\n\n if (runtime.amp) {\n return Promise.all([\n prepareRootElement(name, runtime, baseURI, cacheControl),\n import(\n /* webpackMode: \"weak\" */\n '../AMP'\n ),\n ]).then(([root, { setupAMP }]) => {\n const { ampRoot, getExtraRenderedData } = setupAMP(\n root,\n renderToStaticMarkup,\n runtime\n )\n return renderToStringWithData(\n ampRoot,\n renderToStaticMarkup,\n disableSSQ\n ).then(({ markup, renderTimeMetric }) => ({\n ...commonRenderResult,\n markups: getMarkups(name, markup),\n renderTimeMetric,\n ...getExtraRenderedData(),\n }))\n })\n }\n\n return prepareRootElement(name, runtime, baseURI, cacheControl).then((root) =>\n renderToStringWithData(root, renderToString, disableSSQ).then(\n ({ markup, renderTimeMetric }) => ({\n ...commonRenderResult,\n markups: getMarkups(name, markup),\n renderTimeMetric,\n })\n )\n )\n}\n\nfunction validateRootComponent(rootName: string, extensions: Extensions) {\n if (!extensions[rootName]) {\n throw new Error(`Missing extension point for page ${rootName}`)\n }\n\n if (!extensions[rootName]?.component) {\n throw new Error(`Missing component for extension point ${rootName}`)\n }\n}\n\nfunction setLazyCookie(setCookie: string) {\n if (setCookie) {\n document.cookie = setCookie\n }\n}\n\nfunction start() {\n try {\n if (\n window.__RUNTIME__.blocksTree &&\n !isEmpty(window.__RUNTIME__.blocksTree)\n ) {\n window.__RUNTIME__.hasNewExtensions = true\n window.__RUNTIME__.extensions = generateExtensions(\n window.__RUNTIME__.blocksTree,\n // eslint-disable-next-line\n window.__RUNTIME__.blocks!,\n // eslint-disable-next-line\n window.__RUNTIME__.contentMap!,\n window.__RUNTIME__.pages[window.__RUNTIME__.page]\n )\n }\n\n if (canUseDOM) {\n const browserQuery = window.location.search\n ? queryString.parse(window.location.search)\n : {}\n const serverQuery = window.__RUNTIME__.serverQuery ?? {}\n window.__RUNTIME__.query = { ...serverQuery, ...browserQuery }\n }\n\n const runtime: RenderRuntime = window.__RUNTIME__\n runtime.isJanusProxied =\n canUseDOM && window.location.pathname.startsWith('/api/io/')\n const rootName = runtime.page\n validateRootComponent(rootName, runtime.extensions)\n\n const ReactCreateElement = React.createElement\n const vtexImgHost = getVTEXImgHost(runtime.account)\n React.createElement = function patchedCreateElement(type: any, props: any) {\n if (\n !canUseDOM &&\n typeof type === 'string' &&\n type[0].toLowerCase() === type[0] &&\n props &&\n props.className\n ) {\n const classnames: string[] = props.className.trim().split(/\\s+/)\n classnames.forEach((classname) => cssClasses.add(classname))\n }\n\n if (type === 'a' && props) {\n if (props.target && !props.href) {\n props.target = undefined\n }\n // Follow Google's security recommendations concerning target blank\n // https://developers.google.com/web/tools/lighthouse/audits/noopener\n const rel = props.rel ? props.rel.split(' ') : []\n if (\n props.target === '_blank' &&\n !(rel.indexOf('noopener') !== -1 || rel.indexOf('noreferrer') !== -1)\n ) {\n props.rel = rel.concat('noopener').join(' ')\n }\n }\n\n if (type === 'img') {\n props.src = optimizeSrcForVtexImg(vtexImgHost, props.src)\n if (\n typeof props.src === 'string' &&\n props.src.startsWith(vtexImgHost)\n ) {\n props.crossOrigin = props.crossOrigin || 'anonymous'\n }\n return ReactCreateElement.apply(React, [\n MaybeLazyImage,\n {\n createElement: ReactCreateElement,\n imageProps: props,\n },\n ])\n }\n\n if (props && props.style && isStyleWritable(props)) {\n props.style = optimizeStyleForVtexImg(vtexImgHost, props.style)\n }\n // This rule was introduced in a eslint-config update.\n // Should be fixed in a future PR\n //eslint-disable-next-line prefer-rest-params\n return ReactCreateElement.apply(React, arguments)\n }\n\n const maybeRenderPromise = render(rootName, runtime)\n if (!canUseDOM) {\n // Expose render promise to global context.\n window.rendered = (maybeRenderPromise as Promise<\n NamedServerRendered\n >).then(({ markups, maxAge, page, renderTimeMetric, ...rendered }) => ({\n cssClasses: Array.from(cssClasses).sort(),\n extensions: markups.reduce<RenderedSuccess['extensions']>(\n (acc, { name, markup }) => ((acc[name] = markup), acc),\n {}\n ),\n head: Helmet.rewind(),\n maxAge,\n renderMetrics: { [page]: renderTimeMetric },\n state: getState(runtime),\n ...rendered,\n }))\n } else {\n setLazyCookie(runtime.workspaceCookie)\n maybeRenderPromise\n .then(() => {\n ;(window as any).__HAS_HYDRATED__ = true\n })\n .catch((error) => {\n console.error('Error during hydration', error)\n })\n }\n } catch (error) {\n console.error('Unexpected error rendering:', error)\n if (!canUseDOM) {\n window.rendered = { error }\n }\n }\n}\n\nconst RenderContextConsumer = RenderContext.Consumer\nconst TreePathContextConsumer = TreePathContext.Consumer\n\nexport {\n ExtensionContainer,\n /** Block is the preferred nomenclature now, ExtensionPoint is kept for\n * backwards compatibility\n */\n Block,\n ExtensionPoint,\n LayoutContainer,\n LegacyExtensionContainer,\n Helmet,\n Link,\n NoSSR,\n useSSR,\n RenderContextConsumer,\n TreePathContextConsumer,\n LazyImages as ExperimentalLazyImages,\n useLazyImagesContext as useExperimentalLazyImagesContext,\n canUseDOM,\n render,\n start,\n withHMR,\n registerComponent,\n withRuntimeContext,\n ChildBlock,\n useChildBlock,\n useRuntime,\n useTreePath,\n withSession,\n Loading,\n LoadingContextProvider,\n buildCacheLocator,\n renderExtension,\n // These unstable APIs should be deprecated shortly\n ChildBlock as Unstable__ChildBlock,\n useChildBlock as useChildBlock__unstable,\n}\n\n```"
}
] |
code_render-runtime_787fe73a
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of render-runtime/react/typings/render.d.ts from the render-runtime VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\ndeclare module 'vtex.render-runtime' {\n let runtimeExports: RuntimeExports\n export = runtimeExports\n}\n\n```"
}
] |
code_render-runtime_c06fa8ec
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of render-runtime/react/typings/exenv.d.ts from the render-runtime VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\ndeclare module 'exenv' {\n const canUseDOM: boolean\n}\n\n```"
}
] |
code_render-runtime_e712040b
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of render-runtime/react/typings/runtime.ts from the render-runtime VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { IntrospectionResultData } from 'apollo-cache-inmemory'\nimport EventEmitter from 'eventemitter3'\nimport { Device, DeviceInfo } from '../utils/withDevice'\n\nexport interface RenderRuntime {\n amp: boolean\n account: string\n accountId: string\n appsEtag: string\n binding?: BindingInfo\n blocks?: Blocks\n blocksTree?: BlockContentTree\n channelPrivacy?: 'private' | 'public'\n contentMap?: ContentMap\n customRouting?: boolean\n emitter: EventEmitter\n exposeBindingAddress?: boolean\n workspace: string\n disableSSR: boolean\n disableSSQ: boolean\n hints: RenderHints\n introspectionResult: IntrospectionResultData\n inspect: boolean\n page: string\n route: Route\n version: string\n culture: Culture\n pages: Pages\n extensions: Extensions\n platform: string\n concurrentMode: boolean\n loadedDevices: Device[]\n deviceInfo: DeviceInfo\n preview: boolean\n production: boolean\n publicEndpoint: string\n messages: Record<string, string>\n components: Components\n renderMajor: number\n query?: Record<string, string>\n serverQuery?: Record<string, string>\n start: boolean\n runtimeMeta: {\n version: string\n config?: any\n }\n settings: {\n [app: string]: any\n }\n cacheHints: CacheHintsMap\n segmentToken: string\n defaultExtensions: Extensions\n rootPath?: string\n workspaceCookie: string\n hasNewExtensions: boolean\n queryData?: Array<{\n query: string\n variables: any\n data: string\n }>\n uncriticalStyleRefs?: StyleRefs\n isJanusProxied?: boolean\n}\n\nexport interface Route {\n domain: string\n blockId: string\n canonicalPath?: string\n id: string\n metaTags?: RouteMetaTags\n pageContext: PageDataContext\n params: Record<string, any>\n queryString?: Record<string, any>\n path: string\n title?: string\n}\n\ninterface RouteMetaTags {\n description?: string\n keywords?: string[]\n}\n\ninterface PageDataContext {\n type: string\n id: string\n}\n\ninterface ContentMap {\n [contentId: string]: Record<string, any>\n}\n\ninterface RenderHints {\n desktop: boolean\n mobile: boolean\n tablet: boolean\n phone: boolean\n unknown: boolean\n}\n\ninterface Culture {\n country: string\n availableLocales: string[]\n currency: string\n customCurrencyDecimalDigits: number | null\n customCurrencySymbol: string | null\n language: string\n locale: string\n}\n\nexport interface Pages {\n [name: string]: Page\n}\n\nexport interface Page {\n allowConditions: boolean\n canonical?: string\n cname?: string\n path: string\n auth?: boolean\n params?: any\n theme?: string\n disableExternals?: string[]\n declarer?: string | null\n name?: string\n title?: string\n conditional?: boolean\n map?: string[]\n routeId: string\n blockId: string\n}\n\nexport interface BindingInfo {\n id: string\n canonicalBaseAddress: string\n}\n\ntype BlockContentTree = Record<string, TreeEntry>\ntype Blocks = Record<string, BlockEntry>\n\ntype RenderStrategy = 'client' | 'lazy' | 'server'\ntype HydrationType = 'always' | 'on-view'\n\ninterface BlockEntry {\n after?: BlockInsertion[]\n around?: BlockInsertion[]\n before?: BlockInsertion[]\n blockId: string\n blocks?: BlockInsertion[]\n component: string\n composition?: Composition\n hasContentSchema: boolean\n props?: Record<string, any>\n context?: {\n component: string\n props?: Record<string, any>\n }\n implements: string[]\n originalBlockId?: string\n preview?: Preview\n render: RenderStrategy\n hydration?: HydrationType\n track?: string[]\n title?: string\n}\n\ninterface TreeEntry {\n blockIdMap: Record<string, string>\n contentIdMap: Record<string, string>\n}\n\nexport interface BlockInsertion {\n extensionPointId: string\n blockId: string\n /**\n * This property was replaced by blockRole,\n * but it cannot be removed since that would be a breaking-change\n * in builder-hub. Prefer using blockRole since it can tell you more\n * about the BlockInsertion.\n */\n children?: boolean\n blockRole?: 'block' | 'children' | 'slot'\n}\n\nexport interface Extension {\n after?: string[]\n around?: string[]\n before?: string[]\n blockId?: string\n blocks?: BlockInsertion[]\n context?: {\n component: string\n props?: any\n }\n component: string\n track?: string[]\n props?: any\n content?: Record<string, any>\n render?: RenderStrategy\n preview?: Preview\n hydration?: HydrationType\n composition?: Composition\n hasContentSchema?: boolean\n contentIds?: string[]\n}\n\nexport interface Extensions {\n [name: string]: Extension\n}\n\nenum Composition {\n blocks = 'blocks',\n children = 'children',\n}\n\ninterface Preview {\n type: string\n width: PreviewDimension\n height: PreviewDimension\n fullWidth?: boolean\n options?: any\n}\n\nexport interface PreviewDimension {\n desktop: PreviewDimensionValue\n mobile: PreviewDimensionValue\n}\n\ninterface PreviewDimensionValue {\n fromProp?: string\n defaultValue?: number\n}\n\ninterface StyleRefs {\n base: StyleRef[]\n overrides: StyleRef[]\n}\n\nexport interface StyleRef {\n path: string\n id?: string\n class?: string\n crossorigin?: boolean\n preload?: boolean\n media?: string\n}\n\nexport interface CacheHints {\n scope?: string\n maxAge?: string\n version?: number\n provider?: string\n sender?: string\n}\n\ninterface CacheHintsMap {\n [hash: string]: CacheHints\n}\n\nexport interface Components {\n [entrypoint: string]: ComponentEntry\n}\n\ninterface ComponentEntry {\n assets: string[]\n dependencies: string[]\n}\n\n// We need to keep this so this file is kept in type generation\nexport default {}\n\n```"
}
] |
code_render-runtime_5196c6cf
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of render-runtime/react/typings/global.d.ts from the render-runtime VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { ApolloClient } from 'apollo-client'\nimport { NormalizedCacheObject } from 'apollo-cache-inmemory'\nimport { EventEmitter } from 'eventemitter3'\nimport { Component } from 'react'\nimport ExtensionContainer from '../ExtensionContainer'\nimport ExtensionPoint from '../components/ExtensionPoint/index'\nimport Link from '../components/Link'\nimport { History, Location } from 'history'\nimport { HelmetData } from 'react-helmet'\nimport { TreePathProps } from '../utils/treePath'\n\nimport type { RenderContext } from '../components/RenderContext'\n\ninterface RenderMetric {\n getDataFromTree?: [number, number]\n renderToString: [number, number]\n}\n\ninterface ServerRendered {\n markup: string\n renderTimeMetric: RenderMetric\n}\n\ninterface NamedMarkup {\n markup: string\n name: string\n}\n\ninterface NamedServerRendered {\n markups: NamedMarkup[]\n maxAge: number\n page: string\n renderTimeMetric: RenderMetric\n ampScripts?: string[]\n}\n\ntype ClientRendered = Element\n\ninterface LogEvent {\n name: string\n data?: any\n}\n\ninterface NavigationRoute {\n path: string\n params: Record<string, any>\n id: string\n}\n\ninterface SetQueryOptions {\n merge?: boolean\n replace?: boolean\n scrollOptions?: RenderScrollOptions\n}\n\ninterface RelativeScrollToOptions extends ScrollToOptions {\n baseElementId?: string\n}\n\ntype RenderScrollOptions = RelativeScrollToOptions | false\n\ninterface RenderHistoryLocation extends Location {\n state?: {\n navigationRoute: NavigationRoute\n renderRouting?: true\n scrollOptions?: RenderScrollOptions\n fetchPage?: boolean\n preventRemount?: boolean\n }\n}\n\ninterface RenderedSuccess {\n state: any\n head: HelmetData\n maxAge: number\n extensions: {\n [id: string]: string\n }\n renderMetrics: {\n [name: string]: RenderMetric\n }\n}\n\ninterface RenderedFailure {\n error: any\n}\n\ntype ConfigurationDevice = 'any' | 'desktop' | 'mobile'\n\ninterface PageContextOptions {\n scope?: string\n device?: string\n conditions?: string[]\n template?: string\n}\n\nexport type ApolloClientType = ApolloClient<NormalizedCacheObject>\n\ninterface FetchRoutesInput extends PageContextOptions {\n apolloClient: ApolloClientType\n locale: string\n page: string\n paramsJSON?: string\n path?: string\n production: boolean\n renderMajor: number\n}\n\ninterface FetchDefaultPages {\n apolloClient: ApolloClientType\n locale: string\n pages: Pages\n routeIds: string[]\n renderMajor: number\n}\n\ninterface FetchNavigationDataInput {\n apolloClient: ApolloClientType\n production: boolean\n locale: string\n routeId: string\n declarer?: string | null\n paramsJSON?: string\n path?: string\n renderMajor: number\n skipCache: boolean\n query?: string\n}\n\ninterface RenderComponent<P = {}, S = {}> {\n getCustomMessages?: (locale: string) => any\n WrappedComponent?: RenderComponent\n new (): Component<P, S>\n}\n\ninterface ComponentsRegistry {\n [component: string]: RenderComponent<any, any>\n}\n\ninterface HotEmitterRegistry {\n [appId: string]: EventEmitter\n}\n\ninterface GraphQLResult<T extends string, U> {\n data: Record<T, U>\n errors?: any\n}\n\ninterface DefaultPagesQueryResult {\n data: DefaultPagesQueryResultData\n errors?: any\n}\n\ninterface DefaultPagesQueryResultData {\n defaultPages: DefaultPagesQueryResponse\n}\n\ninterface MatchingPage {\n blockId: string\n canonicalPath?: string\n metaTags?: RouteMetaTags\n pageContext: PageDataContext\n title?: string\n routeId: string\n}\n\ntype Rendered = Promise<void | ClientRendered | NamedServerRendered>\n\ninterface MatchingServerPage {\n blockId: string\n canonicalPath?: string\n metaTags?: RouteMetaTags\n pageContext: PageDataContext\n title?: string\n routeId: string\n params: Record<string, string>\n queryString?: Record<string, any>\n id: string\n path: string\n domain: string\n}\n\ninterface ServerPageResponse {\n appsEtag: RenderRuntime['appsEtag']\n blocks: RenderRuntime['blocks']\n blocksTree: RenderRuntime['blocksTree']\n cacheHints: RenderRuntime['cacheHints']\n contentMap: RenderRuntime['contentMap']\n components: RenderRuntime['components']\n extensions: RenderRuntime['extensions']\n messages: RenderRuntime['messages']\n pages: RenderRuntime['pages']\n route: MatchingServerPage\n settings: RenderRuntime['settings']\n queryData: RenderRuntime['queryData']\n page: string\n}\n\ninterface PageQueryResponse {\n blocksJSON: string\n blocksTreeJSON: string\n contentMapJSON: string\n componentsJSON: string\n extensionsJSON: string\n messages: KeyedString[]\n pagesJSON: string\n appsSettingsJSON: string\n appsEtag: string\n cacheHintsJSON: string\n page: MatchingPage\n}\n\ninterface DefaultPagesQueryResponse {\n componentsJSON: string\n extensionsJSON: string\n messages: KeyedString[]\n}\n\ninterface KeyedString {\n key: string\n message: string\n}\n\ninterface ParsedServerPageResponse extends ServerPageResponse {\n matchingPage: MatchingServerPage\n}\n\ninterface ParsedPageQueryResponse {\n blocks: RenderRuntime['blocks']\n blocksTree: RenderRuntime['blocksTree']\n contentMap: RenderRuntime['contentMap']\n components: RenderRuntime['components']\n extensions: RenderRuntime['extensions']\n messages: RenderRuntime['messages']\n pages: RenderRuntime['pages']\n appsEtag: RenderRuntime['appsEtag']\n settings: RenderRuntime['settings']\n cacheHints: RenderRuntime['cacheHints']\n matchingPage: MatchingPage\n}\n\ninterface ParsedDefaultPagesQueryResponse {\n components: RenderRuntime['components']\n}\n\ntype Rendered = Promise<ClientRendered | NamedServerRendered>\n\ninterface AssetEntry {\n name: string\n path: string\n app: string\n}\n\ninterface RuntimeExports {\n ExtensionContainer: ExtensionContainer\n ExtensionPoint: ExtensionPoint\n Link: Link\n NoSSR: any\n LayoutContainer: any\n LegacyExtensionContainer: any\n Loading: any\n Helmet: any\n canUseDOM: boolean\n withHMR: any\n withRuntimeContext: any\n withSession: any\n RenderContextConsumer: React.Consumer<RenderContext>\n TreePathContextConsumer: React.Consumer<TreePathProps>\n buildCacheLocator: any\n useRuntime(): RenderContext\n start(): void\n render(name: string, runtime: RenderRuntime, element?: HTMLElement): Rendered\n}\n\ninterface RenderSession {\n patchSession: (data: any) => Promise<void>\n sessionPromise: Promise<void>\n}\n\ndeclare global {\n interface Window extends Window {\n __APP_ID__: string\n __ERROR__: any\n __hasPortals__: boolean\n __hostname__: string\n __pathname__: string\n __provideRuntime: (\n runtime: RenderContext | null,\n messages: Record<string, string>,\n shouldUpdateRuntime: boolean,\n setMessages: (messages: RenderRuntime['messages']) => void\n ) => Promise<void>\n __RENDER_8_COMPONENTS__: ComponentsRegistry\n __RENDER_8_HOT__: HotEmitterRegistry\n __RENDER_8_RUNTIME__: RuntimeExports\n __RENDER_8_SESSION__: RenderSession\n __REQUEST_ID__: string\n __RUNTIME__: RenderRuntime\n __RUNTIME_EXTENSIONS__: RenderRuntime['extensions']\n __RUNTIME_QUERYDATA__: RenderRuntime['queryData']\n __STATE__: NormalizedCacheObject\n __DOM_READY__?: boolean\n __ASYNC_SCRIPTS_READY__?: boolean\n __CRITICAL__UNCRITICAL_APPLIED__: Promise<void> | undefined\n __CRITICAL__RAISE_UNCRITICAL_EVENT__: () => void | null\n browserHistory: History\n flags: Record<string, boolean>\n hrtime: NodeJS.Process['hrtime']\n Intl: any\n IntlPolyfill: any\n myvtexSSE: any\n ReactAMPHTML: any\n ReactAMPHTMLHelpers: any\n ReactIntlLocaleData: any\n ReactIntl: any\n IntlPluralRules: any\n IntlRelativeTimeFormat: any\n rendered: Promise<RenderedSuccess> | RenderedFailure\n requestIdleCallback: (callback: (...args) => any | void) => number\n ReactApollo: any\n }\n\n namespace NodeJS {\n interface Global extends Window {\n myvtexSSE: any\n }\n }\n\n interface NodeModule {\n hot: any\n }\n}\n\ninterface PrefetchRouteData {\n extensions: RenderRuntime['extensions']\n components: RenderRuntime['components']\n messages: RenderRuntime['messages']\n}\n\ninterface ContentResponse {\n contentMapJSON: string\n extensionsContent: {\n contentJSON: string\n contentIds: string[]\n treePath: string\n }[]\n contentMessages: RenderRuntime['messages']\n}\n\n```"
}
] |
code_render-runtime_3f8dc0e4
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of render-runtime/react/typings/node.d.ts from the render-runtime VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\ninterface Module {\n hot: any\n}\n\ndeclare const module: Module\n\ndeclare module '*.graphql' {\n import { DocumentNode } from 'graphql'\n\n const value: DocumentNode\n export default value\n}\n\ndeclare module '*.png' {\n let url: string\n export = url\n}\n\ndeclare module '*.css' {\n const content: any\n export default content\n}\n\ndeclare const vtex: any\n\n```"
}
] |
code_render-runtime_015023c1
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of render-runtime/react/queries/navigationPage.graphql from the render-runtime VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```graphql\nquery NavigationPage (\n $routeId: String,\n $declarer: String,\n $params: String,\n $path: String,\n $query: String,\n $renderMajor: Int,\n) {\n navigationPage(\n routeId: $routeId,\n declarer: $declarer,\n params: $params,\n path: $path,\n query: $query,\n renderMajor: $renderMajor\n ) {\n appsEtag\n appsSettingsJSON\n blocksJSON\n blocksTreeJSON\n contentMapJSON\n cacheHintsJSON\n componentsJSON\n extensionsJSON\n messages {\n key\n message\n }\n page {\n blockId\n canonicalPath\n metaTags {\n description\n keywords\n }\n pageContext {\n id\n type\n }\n title\n routeId\n }\n pagesJSON\n }\n}\n\n```"
}
] |
code_render-runtime_ec1a4e9e
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of render-runtime/react/queries/routeData.graphql from the render-runtime VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```graphql\nquery RouteData($routeId: String, $declarer: String, $query: String, $device: UserDevice, $renderMajor: Int) {\n prefetchBlocks(input:{ routeId:$routeId, renderMajor:$renderMajor, declarer: $declarer, query: $query, device: $device}) {\n extensionsJSON\n componentsJSON\n messages {\n key\n message\n }\n }\n}\n\n```"
}
] |
code_render-runtime_84dddf96
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of render-runtime/react/queries/routePreviews.graphql from the render-runtime VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```graphql\nquery RoutePreviews($routes: [PreviewRouteInput], $renderMajor: Int) {\n defaultPages: routePreviews (\n routes: $routes,\n renderMajor: $renderMajor,\n ) {\n componentsJSON\n }\n}\n\n```"
}
] |
code_render-runtime_4d11ed24
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of render-runtime/react/queries/ListContent.graphql from the render-runtime VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```graphql\nquery ListContent(\n $bindingId: String\n $blockId: String\n $pageContext: PageContextInput\n $template: String\n $treePath: String\n) {\n listContent(\n bindingId: $bindingId\n blockId: $blockId\n pageContext: $pageContext\n template: $template\n treePath: $treePath\n ) {\n contentJSON\n }\n}\n\n```"
}
] |
code_render-runtime_104a1328
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of render-runtime/react/start/styles.ts from the render-runtime VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { canUseDOM } from 'exenv'\n\nexport const hydrateUncriticalStyles = async () => {\n if (\n canUseDOM &&\n typeof window.__CRITICAL__RAISE_UNCRITICAL_EVENT__ === 'function'\n ) {\n window.__CRITICAL__RAISE_UNCRITICAL_EVENT__()\n return window.__CRITICAL__UNCRITICAL_APPLIED__\n }\n}\n\n```"
}
] |
code_render-runtime_298b1bcc
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of render-runtime/react/start/runtime.ts from the render-runtime VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { promised } from '../utils/promise'\n\nconst getValue = (element: HTMLTemplateElement) => {\n if (typeof element.content === 'undefined') {\n return element.textContent as string\n }\n\n // Using textContent instead of innerHTML because it's faster\n let value = ''\n const childNodes = element.content.childNodes\n for (let i = 0; i < childNodes.length; i++) {\n const node = childNodes[i]\n value += node.textContent\n }\n return value\n}\n\nconst writeVarToWindow = (template: HTMLTemplateElement, value: string) => {\n const { varname, field } = template.dataset\n const windowAsAny = window as any\n if (!varname) {\n console.error('Missing data-varname:', template)\n return\n }\n\n if (!field) {\n windowAsAny[varname] = JSON.parse(value)\n return\n }\n\n if (!windowAsAny[varname]) {\n console.error(`Global var ${varname} not found to set ${field}`)\n }\n\n windowAsAny[varname][field] = JSON.parse(value)\n}\n\nexport const loadRuntimeJSONs = (): Promise<void | void[]> => {\n const templates = window?.document?.querySelectorAll<HTMLTemplateElement>(\n 'template[data-type=\"json\"]'\n )\n if (!templates || templates.length === 0) {\n return Promise.resolve()\n }\n\n const promises = Array.from(templates).map((template) =>\n promised<string>((resolve) => {\n const value = getValue(template)\n resolve(value)\n }).then((value) =>\n promised<void>((resolve) => {\n writeVarToWindow(template, value)\n resolve()\n })\n )\n )\n\n return Promise.all(promises)\n}\n\n```"
}
] |
code_render-runtime_4539e49b
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of render-runtime/react/start/amp.ts from the render-runtime VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { canUseDOM } from 'exenv'\nimport { RenderRuntime } from '../typings/runtime'\n\nexport const addAMPProxy = (runtime: RenderRuntime) => {\n if (!runtime.amp) {\n window.ReactAMPHTML = window.ReactAMPHTMLHelpers =\n typeof Proxy !== 'undefined'\n ? new Proxy(\n {},\n {\n get: (_, key) => {\n if (key === '__esModule' || key === 'constructor') {\n return\n }\n const message = canUseDOM\n ? 'You can not render AMP components on client-side'\n : 'You must check runtime.amp to render AMP components'\n\n throw new Error(message)\n },\n }\n )\n : {} // IE11 users will not have a clear error in this case\n }\n}\n\n```"
}
] |
code_render-runtime_0f046dd9
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of render-runtime/react/start/register.ts from the render-runtime VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nexport const registerRuntimeGlobals = (runtimeGlobals: any) => {\n window.__RENDER_8_RUNTIME__ = { ...runtimeGlobals }\n\n // compatibility\n window.__RENDER_8_COMPONENTS__ =\n window.__RENDER_8_COMPONENTS__ || global.__RENDER_8_COMPONENTS__\n window.__RENDER_8_HOT__ = window.__RENDER_8_HOT__ || global.__RENDER_8_HOT__\n}\n\n```"
}
] |
code_render-runtime_a00438a0
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of render-runtime/react/start/patchLibs.ts from the render-runtime VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { createCustomReactApollo } from '../utils/reactApollo'\nimport { createReactIntl } from '../utils/reactIntl'\n\nexport const patchLibs = () => {\n if (window.ReactApollo) {\n window.ReactApollo = createCustomReactApollo()\n }\n\n if (window.ReactIntl) {\n window.ReactIntl = createReactIntl()\n }\n}\n\n```"
}
] |
code_render-runtime_324e3578
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of render-runtime/react/start/intl.ts from the render-runtime VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { canUseDOM } from 'exenv'\nimport { prop } from 'ramda'\n\nexport const polyfillIntl = () => {\n if (window.IntlPolyfill) {\n window.IntlPolyfill.__disableRegExpRestore()\n if (!window.Intl) {\n window.Intl = window.IntlPolyfill\n }\n }\n\n if (\n window.Intl &&\n canUseDOM &&\n (!window.Intl.PluralRules || !window.Intl.RelativeTimeFormat)\n ) {\n return import('../intl-polyfill').then(prop('default'))\n }\n\n return Promise.resolve()\n}\n\n```"
}
] |
code_render-runtime_3174f850
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of render-runtime/react/utils/routes.ts from the render-runtime VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { stringify } from 'query-string'\nimport { isEmpty } from 'ramda'\n\nimport navigationPageQuery from '../queries/navigationPage.graphql'\nimport routePreviews from '../queries/routePreviews.graphql'\nimport routeDataQuery from '../queries/routeData.graphql'\nimport { generateExtensions } from './blocks'\nimport { fetchWithRetry } from './fetch'\nimport { parseMessages } from './messages'\nimport { isEnabled } from './flags'\nimport { DeviceInfo } from './withDevice'\nimport {\n ApolloClientType,\n PageQueryResponse,\n FetchNavigationDataInput,\n ParsedPageQueryResponse,\n GraphQLResult,\n FetchDefaultPages,\n DefaultPagesQueryResponse,\n ParsedDefaultPagesQueryResponse,\n DefaultPagesQueryResult,\n KeyedString,\n PrefetchRouteData,\n ContentResponse,\n ServerPageResponse,\n ParsedServerPageResponse,\n} from '../typings/global'\nimport { RenderRuntime, Pages } from '../typings/runtime'\n\nconst parsePageQueryResponse = (\n page: PageQueryResponse\n): ParsedPageQueryResponse => {\n const {\n appsEtag,\n appsSettingsJSON,\n blocksJSON,\n blocksTreeJSON,\n contentMapJSON,\n cacheHintsJSON,\n componentsJSON,\n extensionsJSON,\n messages,\n pagesJSON,\n page: {\n blockId,\n canonicalPath,\n metaTags,\n pageContext: { id, type },\n routeId,\n title,\n },\n } = page\n\n const [\n blocks,\n blocksTree,\n contentMap,\n cacheHints,\n components,\n pages,\n settings,\n ] = [\n blocksJSON,\n blocksTreeJSON,\n contentMapJSON,\n cacheHintsJSON,\n componentsJSON,\n pagesJSON,\n appsSettingsJSON,\n ].map((json) => JSON.parse(json))\n\n const extensions = isEmpty(blocksTree)\n ? JSON.parse(extensionsJSON)\n : generateExtensions(blocksTree, blocks, contentMap, pages[routeId])\n\n return {\n appsEtag,\n cacheHints,\n blocks,\n blocksTree,\n contentMap,\n components,\n extensions,\n matchingPage: {\n blockId,\n canonicalPath,\n metaTags,\n pageContext: { id, type },\n routeId,\n title,\n },\n messages: parseMessages(messages),\n pages,\n settings,\n }\n}\n\nconst parseDefaultPagesQueryResponse = (\n defaultPages: DefaultPagesQueryResponse\n): ParsedDefaultPagesQueryResponse => {\n const { componentsJSON } = defaultPages\n const components = JSON.parse(componentsJSON)\n return {\n components,\n }\n}\n\nfunction prependIOProxy(path: string) {\n if (!path) {\n return '/api/io'\n }\n\n const joiner = path.startsWith('/') ? '' : '/'\n\n return `/api/io${joiner}${path}`\n}\n\nconst runtimeFields = [\n 'appsEtag',\n 'blocks',\n 'blocksTree',\n 'components',\n 'contentMap',\n 'extensions',\n 'messages',\n 'page',\n 'pages',\n 'query',\n 'queryData',\n 'route',\n 'runtimeMeta',\n 'settings',\n].join(',')\n\nfunction getRelativeURLWithQuery({\n path,\n query,\n}: {\n path: string\n query: Record<string, any>\n}) {\n // we don't need to have the rootPath here because only\n // the relative path matters\n const baseUrl = window.location.origin\n const urlObj = new URL(path, baseUrl)\n\n urlObj.search = ''\n\n Object.entries(query).forEach(([key, value]) => {\n if (typeof value === 'undefined') {\n return\n }\n urlObj.searchParams.set(key, value)\n })\n\n return urlObj.href.slice(baseUrl.length)\n}\n\nexport const fetchServerPage = async ({\n fetcher,\n path: rawPath,\n query: rawQuery,\n workspace,\n deviceInfo,\n isJanusProxied,\n}: {\n path: string\n query?: Record<string, string>\n fetcher: GlobalFetch['fetch']\n workspace?: string\n deviceInfo?: DeviceInfo\n isJanusProxied?: boolean\n}): Promise<ParsedServerPageResponse> => {\n const path = isJanusProxied ? prependIOProxy(rawPath) : rawPath\n const url = getRelativeURLWithQuery({\n path,\n query: {\n ...rawQuery,\n ...(workspace ? { workspace } : {}),\n __pickRuntime: runtimeFields,\n ...(deviceInfo && {\n __device: deviceInfo.type,\n }),\n },\n })\n const page: ServerPageResponse = await fetchWithRetry(\n url,\n {\n credentials: 'same-origin',\n headers: {\n accept: 'application/json',\n },\n },\n fetcher\n ).then(({ response }) => response.json())\n const {\n blocksTree,\n blocks,\n contentMap,\n extensions: pageExtensions,\n pages,\n route,\n route: { routeId },\n queryData,\n } = page\n if (routeId === 'redirect') {\n window.location.href = isJanusProxied\n ? prependIOProxy(route.path)\n : route.path\n }\n\n const queryString = stringify(rawQuery || {})\n const routePath = `${path}${queryString ? '?' + queryString : queryString}`\n\n const extensions =\n !isEmpty(blocksTree) && blocksTree && blocks && contentMap\n ? generateExtensions(blocksTree, blocks, contentMap, pages[routeId])\n : pageExtensions\n\n return {\n ...page,\n extensions,\n matchingPage: {\n ...route,\n path: routePath,\n },\n queryData,\n }\n}\n\ninterface PrefetchPageResponse {\n page: string\n queryData: RenderRuntime['queryData']\n contentResponse: ContentResponse | null\n route: RenderRuntime['route']\n}\n\nconst prefetchCounters = {\n pages: 0,\n render: 0,\n}\n\nconst promiseWithCounterWrapper = <T = any>(\n promise: Promise<T>,\n counterName: 'pages' | 'render'\n) => {\n return promise\n .then((data) => {\n prefetchCounters[counterName] = 0\n return data\n })\n .catch((error) => {\n prefetchCounters[counterName]++\n throw error\n })\n}\n\nexport const isPrefetchEnabled = (\n storeSettings: Record<string, any> | null | undefined\n) => Boolean(isEnabled('PREFETCH') && storeSettings?.enablePrefetch)\n\nexport const isPrefetchActive = (\n storeSettings: Record<string, any> | null | undefined\n) =>\n prefetchCounters.pages < 4 &&\n prefetchCounters.render < 4 &&\n isPrefetchEnabled(storeSettings)\n\nexport const getPrefetchForPath = async ({\n fetcher,\n path,\n query: rawQuery,\n workspace,\n}: {\n path: string\n query?: Record<string, string>\n fetcher: GlobalFetch['fetch']\n workspace?: string\n}): Promise<PrefetchPageResponse | null> => {\n const url = getRelativeURLWithQuery({\n path,\n query: {\n ...rawQuery,\n ...(workspace ? { workspace } : {}),\n __pickRuntime: 'page,queryData,contentResponse,route',\n },\n })\n\n const pageResponsePromise = fetchWithRetry(\n url,\n {\n credentials: 'same-origin',\n headers: {\n accept: 'application/json',\n },\n },\n fetcher,\n 0\n ).then(({ response }) => response.json())\n const pageResponse: PrefetchPageResponse | null = await promiseWithCounterWrapper(\n pageResponsePromise,\n 'render'\n ).catch(() => null)\n\n return pageResponse\n}\n\nconst parseFecthRouteData = (data: PrefetchBlocks): PrefetchRouteData => {\n return {\n extensions: JSON.parse(data.extensionsJSON),\n components: JSON.parse(data.componentsJSON),\n messages: parseMessages(data.messages),\n }\n}\n\nconst getDeviceFromHint = (hints: RenderRuntime['hints']) => {\n if (hints.desktop) {\n return 'desktop'\n }\n if (hints.phone) {\n return 'phone'\n }\n if (hints.tablet) {\n return 'tablet'\n }\n return 'unknown'\n}\n\ninterface FetchRouteDataArgs {\n apolloClient: ApolloClientType\n routeId: string\n declarer: string | null\n query?: string\n hints: RenderRuntime['hints']\n renderMajor: number\n}\n\ninterface PrefetchBlocksQueryVars {\n routeId: string\n declarer: string | null\n query?: string\n device: 'desktop' | 'phone' | 'tablet' | 'unknown'\n renderMajor: number\n}\n\ninterface PrefetchBlocksQueryResult {\n prefetchBlocks: PrefetchBlocks\n}\n\ninterface PrefetchBlocks {\n extensionsJSON: string\n componentsJSON: string\n messages: KeyedString[]\n}\n\nexport const fetchRouteData = ({\n apolloClient,\n routeId,\n declarer,\n query,\n hints,\n renderMajor,\n}: FetchRouteDataArgs) => {\n const promise = apolloClient\n .query<PrefetchBlocksQueryResult, PrefetchBlocksQueryVars>({\n fetchPolicy: 'no-cache',\n query: routeDataQuery,\n variables: {\n declarer,\n query,\n routeId,\n device: getDeviceFromHint(hints),\n renderMajor,\n },\n })\n .then(({ data: { prefetchBlocks }, errors }) =>\n errors ? Promise.reject(errors) : parseFecthRouteData(prefetchBlocks)\n )\n return promiseWithCounterWrapper(promise, 'pages')\n}\n\nexport const fetchNavigationPage = ({\n apolloClient,\n routeId,\n declarer,\n production,\n paramsJSON,\n renderMajor,\n skipCache,\n query,\n}: FetchNavigationDataInput) =>\n apolloClient\n .query<{ navigationPage: PageQueryResponse }>({\n fetchPolicy: production && !skipCache ? 'cache-first' : 'network-only',\n query: navigationPageQuery,\n variables: {\n declarer,\n params: paramsJSON,\n production,\n query,\n renderMajor,\n routeId,\n },\n })\n .then<ParsedPageQueryResponse>(\n ({\n data: { navigationPage: pageData },\n errors,\n }: GraphQLResult<'navigationPage', PageQueryResponse>) =>\n errors ? Promise.reject(errors) : parsePageQueryResponse(pageData)\n )\n\nconst getRoutesParam = (routeIds: string[], pages: Pages) => {\n return routeIds\n .filter((routeId) => routeId in pages)\n .map((routeId) => {\n const page = pages[routeId]\n return {\n declarer: page.declarer,\n routeId,\n }\n })\n}\n\nexport const fetchDefaultPages = ({\n apolloClient,\n pages,\n routeIds,\n renderMajor,\n}: FetchDefaultPages) => {\n return apolloClient\n .query<{ defaultPages: DefaultPagesQueryResponse }>({\n query: routePreviews,\n variables: { renderMajor, routes: getRoutesParam(routeIds, pages) },\n })\n .then<ParsedDefaultPagesQueryResponse>(\n ({ data: { defaultPages }, errors }: DefaultPagesQueryResult) => {\n return errors\n ? Promise.reject(errors)\n : parseDefaultPagesQueryResponse(defaultPages)\n }\n )\n}\n\n```"
}
] |
code_render-runtime_3f960e0e
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of render-runtime/react/utils/apolloCache.ts from the render-runtime VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { parse } from 'graphql'\nimport { promised } from './promise'\nimport { canUseDOM } from 'exenv'\nimport { ApolloClientType } from '../typings/global'\n\nexport interface QueryData {\n data: string\n query: string\n variables: Record<string, any>\n}\n\nexport const createHydrationFn = (\n client: ApolloClientType,\n warningMessage = \"Error writing query from render-server in Apollo's cache\"\n) => {\n return async (queryData: QueryData[] | undefined) => {\n if (!queryData || queryData.length === 0) {\n return\n }\n\n const hydrationFn = canUseDOM ? hydrateApolloCacheAsync : hydrateApolloCache\n await hydrationFn(queryData, client, warningMessage)\n }\n}\n\nconst hydrateApolloCache = (\n queryData: QueryData[],\n client: ApolloClientType,\n warningMessage?: string\n) => {\n return queryData.map(({ data, query, variables }) => {\n try {\n client.writeQuery({\n query: parse(query),\n data: JSON.parse(data),\n variables,\n })\n } catch (error) {\n if (warningMessage) {\n console.warn(warningMessage, error)\n }\n }\n })\n}\n\nconst hydrateApolloCacheAsync = (\n queryData: QueryData[],\n client: ApolloClientType,\n warningMessage?: string\n) => {\n return Promise.all(\n queryData.map(({ data, query, variables }) => {\n return promised<void>((resolve) => {\n try {\n client.writeQuery({\n query: parse(query),\n data: JSON.parse(data),\n variables,\n })\n } catch (error) {\n if (warningMessage) {\n console.warn(warningMessage, error)\n }\n }\n resolve()\n })\n })\n )\n}\n\n```"
}
] |
code_render-runtime_1559e685
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of render-runtime/react/utils/registerComponent.tsx from the render-runtime VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport { path } from 'ramda'\nimport { ComponentType } from 'react'\n\nimport maybeWrapWithHMR from './withHMR'\n\nconst loadedComponents: Record<string, { implementer: any }> = {}\n\nexport const isComponentType = (Arg: any): Arg is ComponentType => {\n const isFunction = typeof Arg === 'function'\n\n /** If Arg is a function, assumes an UpperCamelCase naming convention\n * for components, and lowerCamelCase for functions.\n * (See https://reactjs.org/docs/jsx-in-depth.html#user-defined-components-must-be-capitalized)\n * If the function name is unable to be determined, defaults\n * to true (i.e. assumes the function is probably a component)\n *\n * This is needed so that functions exported on IO (e.g. HOC) don't\n * get treated as components, so they can be callable.\n */\n if (isFunction) {\n const name: string | undefined = path(\n ['prototype', 'constructor', 'name'],\n Arg\n )\n if (!name) {\n return true\n }\n\n const firstChar = name.charAt(0)\n\n if (!firstChar || firstChar === '') {\n return true\n }\n\n const isFirstCharUpperCase = firstChar.toUpperCase() === firstChar\n\n return isFirstCharUpperCase\n }\n\n return !!(Arg && Arg.prototype && Arg.prototype.render)\n}\n\nconst idToAppAtMajor = (appId: string) => {\n const [name, version] = appId.split('@')\n const [major] = version.split('.')\n return `${name}@${major}.x`\n}\n\nexport const getLoadedComponent = (componentLocator: string) => {\n return (\n loadedComponents[componentLocator] &&\n loadedComponents[componentLocator].implementer\n )\n}\n\nexport default (\n module: Module,\n InitialImplementer: any,\n app: string,\n name: string,\n lazy = false\n) => {\n const componentLocators = [`${app}/${name}`, `${idToAppAtMajor(app)}/${name}`]\n\n if (module.hot || !lazy) {\n const implementer = lazy ? InitialImplementer() : InitialImplementer\n const wrappedComponent = maybeWrapWithHMR(module, implementer)\n componentLocators.forEach((locator) => {\n window.__RENDER_8_COMPONENTS__[locator] = wrappedComponent\n loadedComponents[locator] = { implementer: wrappedComponent }\n })\n\n return wrappedComponent\n }\n\n componentLocators.forEach((locator) => {\n Object.defineProperty(window.__RENDER_8_COMPONENTS__, locator, {\n get: () => {\n if (loadedComponents[locator]) {\n return loadedComponents[locator].implementer\n }\n\n const implementer = InitialImplementer()\n componentLocators.forEach((eachLocator) => {\n loadedComponents[eachLocator] = { implementer }\n })\n\n return implementer\n },\n })\n })\n\n return InitialImplementer\n}\n\n```"
}
] |
code_render-runtime_8ee8bfe2
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of render-runtime/react/utils/blocks.ts from the render-runtime VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { RenderRuntime, Extension, Page, Extensions } from '../typings/runtime'\n\ninterface ExtensionResult {\n treePath: string\n extension: Extension\n}\n\nexport const withStar = (treePath: string) => {\n const parts = treePath.split('/')\n parts[0] = '*'\n return parts.join('/')\n}\n\nconst createExtensions = (\n blockTreePath: string,\n extensionPath: string,\n bindingPath: string,\n outerNested: boolean,\n blocksTree: NonNullable<RenderRuntime['blocksTree']>,\n blocksMap: NonNullable<RenderRuntime['blocks']>,\n contentMap: NonNullable<RenderRuntime['contentMap']>\n): ExtensionResult[] => {\n const result: ExtensionResult[] = []\n if (!blocksTree[blockTreePath]) {\n return result\n }\n\n const { blockIdMap, contentIdMap } = blocksTree[blockTreePath]\n const mappedBlockId =\n blockIdMap[extensionPath] ||\n blockIdMap[withStar(extensionPath)] ||\n blockIdMap['*']\n const block = blocksMap[mappedBlockId]\n const { blockId, after = [], around = [], before = [], blocks = [] } = block\n const blockContentMapId =\n contentIdMap[bindingPath] || contentIdMap[withStar(bindingPath)] || blockId\n const blockContentId = `${blockContentMapId}+${blockId}`\n\n const maybeContent = contentMap[blockContentId] ||\n contentMap[blockContentMapId] || { content: {}, contentIds: [] }\n const content = maybeContent.content || maybeContent\n const contentIds = maybeContent.contentIds || []\n\n const self = [\n {\n treePath: extensionPath,\n extension: {\n after: after.map((insertion) => insertion.extensionPointId),\n around: around.map((insertion) => insertion.extensionPointId),\n before: before.map((insertion) => insertion.extensionPointId),\n blockId: block.originalBlockId || blockId,\n blocks: blocks,\n component: block.component,\n composition: block.composition,\n content,\n contentIds,\n context: block.context,\n hasContentSchema: block.hasContentSchema,\n preview: block.preview,\n props: block.props,\n render: block.render,\n title: block.title,\n track: block.track,\n },\n },\n ]\n\n const [afterExtensions, aroundExtensions, beforeExtensions] = [\n after,\n around,\n before,\n ].map((outer) => {\n return outer.reduce((acc, { extensionPointId }) => {\n const outerExtensionPath = `${extensionPath}/${extensionPointId}`\n const outerResults = createExtensions(\n extensionPointId,\n outerExtensionPath,\n bindingPath,\n true,\n blocksTree,\n blocksMap,\n contentMap\n )\n acc.push(...outerResults)\n return acc\n }, [] as ExtensionResult[])\n })\n\n const innerExtensions = blocks.reduce((acc, { extensionPointId }) => {\n const innerBlockTreePath = `${blockTreePath}/${extensionPointId}`\n const innerExtensionPath = `${extensionPath}/${extensionPointId}`\n const innerBindingPath = outerNested\n ? bindingPath\n : `${bindingPath}/${extensionPointId}`\n const innerResults = createExtensions(\n innerBlockTreePath,\n innerExtensionPath,\n innerBindingPath,\n outerNested,\n blocksTree,\n blocksMap,\n contentMap\n )\n acc.push(...innerResults)\n return acc\n }, [] as ExtensionResult[])\n\n return result.concat(\n self,\n afterExtensions,\n aroundExtensions,\n beforeExtensions,\n innerExtensions\n )\n}\n\nexport const generateExtensions = (\n blocksTree: NonNullable<RenderRuntime['blocksTree']>,\n blocks: NonNullable<RenderRuntime['blocks']>,\n contentMap: NonNullable<RenderRuntime['contentMap']>,\n page: Page\n): Extensions => {\n const extensions: Extensions = {}\n const routeId = page.routeId\n const routeResult = createExtensions(\n routeId,\n routeId,\n routeId,\n false,\n blocksTree,\n blocks,\n contentMap\n )\n routeResult.forEach((eachResult) => {\n extensions[eachResult.treePath] = eachResult.extension\n })\n\n return extensions\n}\n\n```"
}
] |
code_render-runtime_1186d081
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of render-runtime/react/utils/isAdmin.ts from the render-runtime VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { canUseDOM } from 'exenv'\n\n/**\n * This function checks if anything is running in the Admin environment,\n * without relying on Render's own features.\n */\nexport function isAdmin() {\n if (!canUseDOM) {\n return false\n }\n\n const { host = '' } = window.location\n\n const isMyvtexDomain = host.includes('myvtex.com')\n\n if (!isMyvtexDomain) {\n return false\n }\n\n const adminPathnames = [\n '/admin',\n '/_v/segment/admin-login/v1/login', // Let's consider the Admin Login page as an Admin App even though it's technically not.\n ]\n\n const { pathname = '' } = window.location\n\n return adminPathnames.some((path) => pathname.startsWith(path))\n}\n\n```"
}
] |
code_render-runtime_c46f27ac
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of render-runtime/react/utils/components.ts from the render-runtime VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { uniqWith } from 'ramda'\nimport { hasComponentImplementation, fetchAssets } from './assets'\nimport { AssetEntry } from '../typings/global'\nimport { RenderRuntime, Extensions, BlockInsertion } from '../typings/runtime'\n\nconst FILE_PATH_REX = /([^/]+?)(?:$|\\?)/ // https://regex101.com/r/joJ2p7/1\nconst FILE_EXT_REX = /(\\.min)?(\\.js|\\.css)/ // https://regex101.com/r/8vmjes/1\n\nconst uniqAsset = uniqWith<AssetEntry, AssetEntry>((a, b) => a.path === b.path)\n\nconst getAppAndVersion = (locator: string) => {\n const [appAtVersion] = locator.split('/')\n const [app, version] = appAtVersion.split('@')\n return { app, version }\n}\n\nexport const isConflictingLoadedComponents = (\n navigatedComponents: RenderRuntime['components'],\n loadedComponents: RenderRuntime['components']\n) => {\n const loadedVersionsByApp = Object.keys(loadedComponents).reduce(\n (acc, locator) => {\n const { app, version } = getAppAndVersion(locator)\n const [major] = version.split('.')\n if (!acc[app]) {\n acc[app] = { [major]: version }\n } else {\n acc[app][major] = version\n }\n return acc\n },\n {} as Record<string, Record<string, string>>\n )\n\n return Object.keys(navigatedComponents).some((locator) => {\n const { app, version } = getAppAndVersion(locator)\n const [major] = version.split('.')\n const loadedVersion = loadedVersionsByApp[app]?.[major]\n\n return loadedVersion && loadedVersion !== version\n })\n}\n\nexport const fetchComponents = async (\n components: RenderRuntime['components'],\n runtime: RenderRuntime,\n extensions?: Extensions\n) => {\n // In order for only fetching `components`, we create corresponding extensions\n // for them if they weren't passed\n if (!extensions) {\n const componentsNames = Object.keys(components)\n extensions = componentsNames.reduce((acc, component) => {\n acc[component] = { component }\n return acc\n }, {} as RenderRuntime['extensions'])\n }\n const componentsToDownload = Object.values(extensions).reduce<string[]>(\n (acc, extension) => {\n if (!extension) {\n return acc\n }\n if (extension.render === 'lazy') {\n return acc\n }\n if (!hasComponentImplementation(extension.component)) {\n acc.push(extension.component)\n }\n const context = extension?.context?.component\n if (context && !hasComponentImplementation(context)) {\n acc.push(context)\n }\n return acc\n },\n []\n )\n\n if (componentsToDownload.length === 0) {\n return\n }\n\n const allAssets = traverseListOfComponents(components, componentsToDownload)\n await fetchAssets(runtime, allAssets)\n}\n\nexport const traverseListOfComponents = (\n componentsData: RenderRuntime['components'] | Record<string, string[]>,\n componentsToTraverse: string[]\n) => {\n const allAssets = componentsToTraverse.reduce((acc, component) => {\n const assets = traverseComponent(componentsData, component, false)\n acc.push(...assets)\n return acc\n }, [] as AssetEntry[])\n\n return uniqAsset(allAssets)\n}\n\nexport const traverseComponent = (\n components: RenderRuntime['components'] | Record<string, string[]>,\n component: string,\n isRoot = true\n): AssetEntry[] => {\n const entry = components[component]\n const [app] = component.split('/')\n if (Array.isArray(entry)) {\n return entry.map((asset) => {\n return { path: asset, app, name: assetName(asset) }\n })\n }\n const { dependencies, assets } = entry\n const assetsForDeps = dependencies.reduce(\n (acc, dependency) => {\n const depAssets = traverseComponent(components, dependency, false)\n return depAssets.concat(acc)\n },\n assets.map((asset) => {\n return { path: asset, app, name: assetName(asset) }\n })\n )\n\n if (isRoot) {\n return uniqAsset(assetsForDeps)\n }\n return assetsForDeps\n}\n\nexport const traverseExtension = (\n extensions: Extensions,\n components: RenderRuntime['components'],\n extensionId: string,\n isRoot: boolean\n): AssetEntry[] => {\n const extension = extensions[extensionId]\n if (!extension) {\n return []\n }\n const children: string[] =\n extension.blocks?.map(\n (block: BlockInsertion) => `${extensionId}/${block.extensionPointId}`\n ) ?? []\n\n const component = extension.component\n\n const componentAssets = traverseComponent(components, component, isRoot)\n const childrenAssets = children\n .map((child: string) =>\n traverseExtension(extensions, components, child, false)\n )\n .reduce((acc, cur) => {\n acc.push(...cur)\n return acc\n }, [])\n\n return componentAssets.concat(childrenAssets)\n}\n\nconst assetName = (asset: string) => {\n const baseNameMatch = FILE_PATH_REX.exec(asset)\n const baseName =\n baseNameMatch && baseNameMatch.length > 0 ? baseNameMatch[1] : ''\n const assetName = baseName.replace(FILE_EXT_REX, '')\n return assetName\n}\n\n```"
}
] |
code_render-runtime_86637ce7
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of render-runtime/react/utils/treePath.tsx from the render-runtime VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport hoistNonReactStatics from 'hoist-non-react-statics'\nimport React, { ComponentType, useContext, FC, useMemo } from 'react'\nimport { Extensions } from '../typings/runtime'\n\nconst relative = (parent: string, id: string) => id.replace(`${parent}/`, '')\n\nexport const escapeRegex = (s: string) =>\n s.replace(/[-/\\\\^$*+?.()|[\\]{}]/g, '\\\\$&')\n\nexport const isDirectChild = (id: string, parent: string) => {\n return (\n id !== parent &&\n new RegExp(`^${escapeRegex(parent)}/[a-zA-Z0-9-_#]+$`).test(id)\n )\n}\n\nconst parseId = (id: string) => {\n const matches = /^(.*?)(\\d+)?$/.exec(id)\n\n if (matches === null) {\n return []\n }\n\n const [, text, numericText] = matches\n const numbericValue = numericText ? parseInt(numericText, 10) : 0\n return [text, numbericValue]\n}\n\nexport const getDirectChildren = (extensions: Extensions, treePath: string) => {\n return Object.entries(extensions)\n .filter(\n ([id, extension]) => extension?.component && isDirectChild(id, treePath)\n )\n .map(([id]) => relative(treePath, id))\n .sort((idA, idB) => {\n const [textA, numberA] = parseId(idA)\n const [textB, numberB] = parseId(idB)\n const [valueA, valueB] =\n textA === textB ? [numberA, numberB] : [textA, textB]\n\n return valueA < valueB ? -1 : 1\n })\n}\n\nexport const TreePathContext = React.createContext<TreePathProps>({\n treePath: '',\n})\nTreePathContext.displayName = 'TreePathContext'\n\nexport const TreePathContextProvider: FC<TreePathProps> = ({\n treePath,\n children,\n}) => {\n const value = useMemo(() => ({ treePath }), [treePath])\n return (\n <TreePathContext.Provider value={value}>\n {children}\n </TreePathContext.Provider>\n )\n}\nTreePathContextProvider.displayName = 'TreePathContextProvider'\n\nexport const useTreePath = () => {\n return useContext(TreePathContext)\n}\n\nexport interface TreePathProps {\n treePath: string\n}\n\nexport function withTreePath<TOriginalProps>(\n Component: ComponentType<TOriginalProps & TreePathProps>\n): ComponentType<TOriginalProps> {\n const WithTreePath = (props: TOriginalProps) => {\n const { treePath } = useTreePath()\n return <Component {...props} treePath={treePath} />\n }\n\n WithTreePath.displayName = `TreePath(${\n Component.displayName || Component.name || 'Component'\n })`\n WithTreePath.WrappedComponent = Component\n\n return hoistNonReactStatics<TOriginalProps, TreePathProps>(\n WithTreePath,\n Component\n )\n}\n\n```"
}
] |
code_render-runtime_14ddf6ca
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of render-runtime/react/utils/messages.ts from the render-runtime VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { pluck, zipObj } from 'ramda'\nimport { KeyedString } from '../typings/global'\n\nexport const parseMessages = (messages: KeyedString[] | null) => {\n return messages && zipObj(pluck('key', messages), pluck('message', messages))\n}\n\n```"
}
] |
code_render-runtime_f6155348
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of render-runtime/react/utils/slots.tsx from the render-runtime VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React, { FC, useMemo } from 'react'\n\nimport { getChildExtensions } from '../components/ExtensionPoint/index'\nimport ComponentLoader from '../components/ExtensionPoint/ComponentLoader'\nimport { useRuntime } from '../components/RenderContext'\nimport { Extension } from '../typings/runtime'\n\ninterface GenerateSlotArgs {\n treePath: string\n slotName: string\n slotValue: string\n hydration: Extension['hydration']\n}\n\nexport function generateSlot({\n treePath,\n slotName,\n slotValue,\n hydration,\n}: GenerateSlotArgs) {\n const newTreePath = `${treePath}/${slotValue}`\n\n const SlotComponent: FC<any> = (props) => {\n const runtime = useRuntime()\n const extension = runtime.extensions[newTreePath]\n\n const slotChildren = getChildExtensions(runtime, newTreePath)\n const componentProps = extension?.props ?? {}\n const extensionContent = extension?.content ?? {}\n\n const componentLoaderPropsWithContent = useMemo(\n () => ({\n // Props received by the slot being used directly as a component\n ...props,\n // Props received by the block referenced by slotValue in a user's theme\n ...componentProps,\n // Content saved in the CMS for this treePath\n ...extensionContent,\n }),\n [componentProps, extensionContent, props]\n )\n\n /**\n * The ComponentLoader component below will handle both recursive calls to generateSlots\n * (slots could contain slots another slots in its props) and partial hydration support.\n */\n return (\n <ComponentLoader\n component={extension?.component ?? null}\n props={componentLoaderPropsWithContent}\n treePath={newTreePath}\n runtime={runtime}\n hydration={hydration}\n >\n {Array.isArray(slotChildren) &&\n slotChildren.length === 0 &&\n componentLoaderPropsWithContent.children\n ? componentLoaderPropsWithContent.children\n : slotChildren}\n </ComponentLoader>\n )\n }\n\n SlotComponent.displayName = `${slotName}Slot`\n\n return SlotComponent\n}\n\n```"
}
] |
code_render-runtime_ee61ebeb
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of render-runtime/react/utils/assets.ts from the render-runtime VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport queryString from 'query-string'\nimport { getLoadedComponent } from './registerComponent'\nimport { isEnabled } from './flags'\nimport { AssetEntry, RenderComponent } from '../typings/global'\nimport { RenderRuntime, StyleRef, Extensions } from '../typings/runtime'\n\nconst imageHost = isEnabled('VTEX_ASSETS_URL')\n ? 'vtexassets.com'\n : 'vteximg.com.br'\n\nfunction getExtension(path: string) {\n const adjPath = path.split('?')[0]\n const result = /\\.\\w+$/.exec(adjPath)\n return result ? result[0] : ''\n}\n\nconst isRelative = (path: string) => {\n return path && path[0] === '/' && path[1] !== '/'\n}\n\nexport const getVTEXImgHost = (account: string) => {\n return `https://${account}.${imageHost}`\n}\n\nconst getAbsoluteURL = (\n account: string,\n url: string,\n production: boolean,\n rootPath: string\n) => {\n if (!isRelative(url)) {\n return url\n }\n\n return production ? `${getVTEXImgHost(account)}${url}` : rootPath + url\n}\n\nclass ServerSideAssetLoadingError extends Error {\n public constructor() {\n super('Loading assets on server side rendering is not supported')\n }\n}\n\nfunction isAbsolute(path: string) {\n return path && !path.startsWith('/')\n}\n\nexport function addScriptToPage(src: string): Promise<void> {\n return new Promise((resolve, reject) => {\n if (!document || !document.head) {\n throw new ServerSideAssetLoadingError()\n }\n const script = document.createElement('script')\n script.type = 'text/javascript'\n script.onload = () => resolve()\n script.onerror = () => reject()\n script.async = false\n script.src = src\n if (isAbsolute(src)) {\n script.crossOrigin = 'anonymous'\n }\n document.body.appendChild(script)\n })\n}\n\nfunction addStyleToPage(href: string) {\n if (!document || !document.head) {\n throw new ServerSideAssetLoadingError()\n }\n const link = document.createElement('link')\n link.href = href\n link.type = 'text/css'\n link.rel = 'stylesheet'\n if (isAbsolute(href)) {\n link.crossOrigin = 'anonymous'\n }\n const overrideLink =\n document.getElementById('styles_bundled') ||\n document.getElementById('override_link_0')\n\n if (overrideLink) {\n document.head.insertBefore(link, overrideLink)\n } else {\n document.head.appendChild(link)\n }\n}\n\nconst updateHref = (linkElement: HTMLLinkElement) => {\n const href = linkElement && linkElement.getAttribute('href')\n\n if (href) {\n const now = Date.now()\n const idPrefix = 'hot_reload_css'\n const modifiedHref = href.replace(\n /build(\\d)+/,\n `build${Math.round(now / 1000)}`\n )\n const newCssElement = document.createElement('link')\n const nextElementSibling = linkElement.nextElementSibling\n newCssElement.rel = 'stylesheet'\n newCssElement.type = 'text/css'\n newCssElement.href = modifiedHref\n newCssElement.id = idPrefix + now\n newCssElement.onload = function onLoadCb() {\n requestAnimationFrame(() => {\n if (\n nextElementSibling &&\n linkElement.parentNode &&\n nextElementSibling.id.indexOf(idPrefix) > -1\n ) {\n linkElement.parentNode.removeChild(nextElementSibling)\n }\n\n linkElement.disabled = true\n })\n }\n\n if (linkElement.parentNode) {\n linkElement.parentNode.insertBefore(newCssElement, nextElementSibling)\n }\n }\n}\n\nexport const hotReloadOverrides = () => {\n const linkElements: HTMLLinkElement[] = Array.from(\n document.querySelectorAll('.override_link')\n )\n linkElements.forEach(updateHref)\n}\n\nexport const hotReloadTachyons = () => {\n const linkElements: HTMLLinkElement[] = Array.from(\n document.querySelectorAll('.style_link')\n )\n linkElements.forEach(updateHref)\n}\n\nfunction prefetchStyle(href: string) {\n if (!document || !document.head) {\n throw new ServerSideAssetLoadingError()\n }\n const link = document.createElement('link')\n link.href = href\n link.as = 'style'\n link.rel = 'prefetch'\n if (isAbsolute(href)) {\n link.crossOrigin = 'anonymous'\n }\n document.head.appendChild(link)\n}\n\nfunction prefetchScript(href: string) {\n if (!document || !document.head) {\n throw new ServerSideAssetLoadingError()\n }\n const link = document.createElement('link')\n link.href = href\n link.as = 'script'\n link.rel = 'prefetch'\n if (isAbsolute(href)) {\n link.crossOrigin = 'anonymous'\n }\n document.head.appendChild(link)\n}\n\nfunction getExistingScriptSrcs() {\n const paths: string[] = []\n for (let i = 0; i < document.scripts.length; i++) {\n const script = document.scripts.item(i)\n if (script !== null) {\n paths.push(script.src)\n }\n }\n return paths\n}\n\nfunction getExistingStyleHrefs() {\n return Array.from(\n document.head.querySelectorAll('link[type=\"text/css\"],style')\n ).reduce<string[]>((hrefs, styleSheet) => {\n const href =\n (styleSheet as HTMLLinkElement).href ||\n styleSheet.getAttribute('data-href')\n\n if (href) {\n hrefs.push(href)\n }\n return hrefs\n }, [])\n}\n\nfunction getExistingPrefetchScriptLinks() {\n return getExistingPrefetchLinks('script')\n}\nfunction getExistingPrefetchStyleLinks() {\n return getExistingPrefetchLinks('style')\n}\n\nfunction getExistingPrefetchLinks(prefetchType: string[] | string) {\n const paths: string[] = []\n const links = document.getElementsByTagName('link')\n for (let i = 0; i < links.length; i++) {\n const item = links.item(i)\n if (item && item.rel === 'prefetch' && prefetchType.includes(item.as)) {\n paths.push(item.href)\n }\n }\n return paths\n}\n\nfunction assetOnList(path: string, assets: string[]) {\n return assets.some((asset) => asset.indexOf(path) !== -1)\n}\n\nfunction isScript(path: string) {\n return getExtension(path) === '.js'\n}\n\nexport function shouldAddScriptToPage(\n path: string,\n scripts: string[] = getExistingScriptSrcs()\n) {\n return isScript(path) && !assetOnList(path, scripts)\n}\n\nexport function getLoadedImplementation<P = {}, S = {}>(component: string) {\n return getLoadedComponent(component) as RenderComponent<P, S>\n}\n\nexport function getImplementation<P = {}, S = {}>(\n component: string | undefined\n) {\n if (!component) return null\n return window.__RENDER_8_COMPONENTS__[component] as RenderComponent<P, S>\n}\n\nexport function hasComponentImplementation(component: string) {\n return window.__RENDER_8_COMPONENTS__.hasOwnProperty(component)\n}\n\nexport function getExtensionImplementation<P = {}, S = {}>(\n extensions: Extensions,\n name: string\n) {\n const extension = extensions[name]\n return extension && extension.component\n ? getImplementation<P, S>(extension.component)\n : null\n}\n\nexport function fetchUncriticalStyles(\n refs: StyleRef[]\n): Promise<Array<UncriticalStyle>> {\n return Promise.all(\n refs.map(\n (ref) =>\n new Promise<UncriticalStyle>((resolve) => {\n const { path, id, class: className, media = '' } = ref\n fetch(path)\n .then(async (response) => {\n const body = await response.text()\n resolve({ href: path, id, className, media, body })\n })\n .catch((error) => {\n console.error(`Error loading uncritical style.`, error)\n resolve({ href: path, id, className, media, body: '' })\n })\n })\n )\n )\n}\n\nexport async function fetchAssets(\n runtime: RenderRuntime,\n assets: AssetEntry[]\n) {\n const existingScripts = getExistingScriptSrcs()\n const existingStyles = getExistingStyleHrefs()\n\n const styles = getAssetsToAdd(runtime, assets, '.css', existingStyles)\n styles.forEach(addStyleToPage)\n\n const scripts = getAssetsToAdd(runtime, assets, '.js', existingScripts)\n if (scripts.length === 0) {\n return\n }\n\n await Promise.all(scripts.map(addScriptToPage))\n}\n\nexport function prefetchAssets(runtime: RenderRuntime, assets: AssetEntry[]) {\n const existingScripts = getExistingScriptSrcs()\n const existingStyles = getExistingStyleHrefs()\n const existingScriptsPrefetches = getExistingPrefetchScriptLinks()\n const existingStylesPrefetches = getExistingPrefetchStyleLinks()\n\n const scripts = getAssetsToAdd(runtime, assets, '.js', [\n ...existingScripts,\n ...existingScriptsPrefetches,\n ])\n const styles = getAssetsToAdd(runtime, assets, '.css', [\n ...existingStyles,\n ...existingStylesPrefetches,\n ])\n scripts.forEach(prefetchScript)\n styles.forEach(prefetchStyle)\n}\n\nfunction getAssetsToAdd(\n runtime: RenderRuntime,\n assets: AssetEntry[],\n assetExtension: string,\n existingAssets: string[]\n) {\n const { account, production, rootPath = '' } = runtime\n\n const existingBundledAssetsByApp = groupAssetsByApp(\n existingAssets,\n assetExtension\n )\n\n return Array.from(\n assets.reduce((acc, asset) => {\n if (\n shouldAddAssetToPage(\n asset,\n assetExtension,\n existingBundledAssetsByApp,\n existingAssets\n )\n ) {\n const absoluteAsset = getAbsoluteURL(\n account,\n asset.path,\n production,\n rootPath\n )\n acc.add(absoluteAsset)\n }\n return acc\n }, new Set<string>())\n )\n}\n\nfunction shouldAddAssetToPage(\n asset: AssetEntry,\n assetExtension: string,\n existingBundledAssetsByApp: Record<string, string[]>,\n existingAssets: string[]\n) {\n return (\n hasExtension(asset.path, assetExtension) &&\n !hasBundledAsset(asset.app, asset.name, existingBundledAssetsByApp) &&\n !assetOnList(asset.path, existingAssets)\n )\n}\n\nfunction hasExtension(path: string, fileExtension: string) {\n return getExtension(path) === fileExtension\n}\n\nfunction parseFilesQueryString(\n filesQueryString: string,\n assetExtension: string\n) {\n const [appOrType, ...assets] = filesQueryString.split(',')\n if (assetExtension === '.js') {\n return { app: appOrType, assets }\n }\n\n if (appOrType.indexOf('react~') === 0) {\n const [, app] = appOrType.split('~')\n return { app, assets }\n }\n\n return {}\n}\n\nfunction groupAssetsByApp(\n assets: string[],\n assetExtension: string\n): Record<string, string[]> {\n return assets.reduce((acc: Record<string, string[]>, asset) => {\n if (!asset) {\n return acc\n }\n\n const { query: parsedQuery } = queryString.parseUrl(asset)\n if (!parsedQuery || !parsedQuery.files) {\n return acc\n }\n\n const queryFiles: string[] = Array.isArray(parsedQuery.files)\n ? parsedQuery.files\n : [parsedQuery.files]\n queryFiles.forEach((files: string) => {\n if (!files) {\n return\n }\n\n const { app, assets } = parseFilesQueryString(files, assetExtension)\n if (!app || !assets || assets.length === 0) {\n return\n }\n\n if (!acc[app]) {\n acc[app] = assets\n } else {\n acc[app].push(...assets)\n }\n })\n return acc\n }, {})\n}\n\nfunction hasBundledAsset(\n app: string,\n asset: string,\n assetsByApp: Record<string, string[]>\n) {\n return !!assetsByApp[app] && assetsByApp[app].indexOf(asset) !== -1\n}\n\nexport type UncriticalStyle = {\n href: string\n media: string\n className?: string\n id?: string\n body: string\n} | null\n\n```"
}
] |
code_render-runtime_a9979afd
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of render-runtime/react/utils/session.tsx from the render-runtime VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport hoistNonReactStatics from 'hoist-non-react-statics'\nimport React, { ComponentType } from 'react'\n\nimport Session from '../components/Session'\n\ninterface Options {\n renderWhileLoading?: boolean\n}\n\nexport const withSession = ({ renderWhileLoading }: Options = {}) => {\n return function <TOriginalProps>(\n Component: ComponentType<TOriginalProps>\n ): ComponentType<TOriginalProps> {\n class WithSession extends React.Component<TOriginalProps> {\n public static get displayName(): string {\n return `WithSession(${\n Component.displayName || Component.name || 'Component'\n })`\n }\n\n public static get WrappedComponent() {\n return Component\n }\n\n public render() {\n return (\n <Session renderWhileLoading={renderWhileLoading}>\n <Component {...this.props} />\n </Session>\n )\n }\n }\n\n return hoistNonReactStatics<TOriginalProps, {}>(WithSession, Component)\n }\n}\n\n```"
}
] |
code_render-runtime_aab78a57
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of render-runtime/react/utils/pages.ts from the render-runtime VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { canUseDOM } from 'exenv'\nimport { History, LocationDescriptorObject } from 'history'\nimport queryString from 'query-string'\nimport { difference, is, isEmpty, keys, startsWith } from 'ramda'\nimport RouteParser from 'route-parser'\n\nimport { isEnabled } from './flags'\nimport {\n NavigationRoute,\n RelativeScrollToOptions,\n RenderScrollOptions,\n} from '../typings/global'\nimport { Pages } from '../typings/runtime'\n\nconst EMPTY_OBJECT = (Object.freeze && Object.freeze({})) || {}\n\nconst removeTrailingParenthesis = (path: string) =>\n path.endsWith('(') ? path.substr(0, path.length - 1) : path\n\nexport function getComparablePrecedence(path: string): string {\n return path\n .split('/')\n .reduce((acc, pathSegment) => {\n if (pathSegment.startsWith('*')) {\n acc.push(3)\n } else if (pathSegment.startsWith(':')) {\n acc.push(2)\n } else if (pathSegment) {\n acc.push(1)\n }\n\n return acc\n }, [] as number[])\n .join()\n}\n\nfunction isHost(hostname: string) {\n return (\n hostname === (canUseDOM ? window.location.hostname : window.__hostname__)\n )\n}\n\nfunction trimEndingSlash(token: string) {\n return token.replace(/\\/$/, '') || '/'\n}\n\nfunction createLocationDescriptor(\n navigationRoute: NavigationRoute,\n {\n hash,\n query,\n scrollOptions,\n fetchPage,\n preventRemount,\n skipSetPath,\n }: Partial<NavigateOptions>\n): LocationDescriptorObject {\n return {\n state: {\n fetchPage,\n navigationRoute,\n preventRemount,\n renderRouting: true,\n scrollOptions,\n },\n ...(skipSetPath ? {} : { pathname: navigationRoute.path }),\n ...(query && { search: query }),\n ...(hash && { hash }),\n }\n}\n\nfunction adjustTemplate(template: string) {\n // make last splat capture optional\n return trimEndingSlash(template).replace(/(\\/\\*\\w+)$/, '($1)')\n}\n\nfunction adjustPath(path: string) {\n const [pathname] = path.split('#')\n return trimEndingSlash(pathname)\n}\n\nfunction getValidTemplate(page: string, pages: Pages) {\n const pageDescriptor = pages[page]\n\n if (!pageDescriptor) {\n console.error(`Page ${page} was not found`)\n return null\n }\n\n const { path: template, canonical } = pageDescriptor\n if (!template) {\n console.error(`Page ${page} has no path`)\n return null\n }\n\n return adjustTemplate(canonical || template)\n}\n\nexport function pathFromPageName(page: string, pages: Pages, params: any) {\n const validTemplate = getValidTemplate(page, pages)\n if (!validTemplate) {\n return null\n }\n const path = new RouteParser(validTemplate).reverse(params)\n const filters = params\n ? params.rest || (params.terms && `/${params.terms}`) || ''\n : ''\n return path ? `${path}${filters}` : null\n}\n\nexport function queryStringToMap(query: string): Record<string, any> {\n if (!query) {\n return {}\n }\n return queryString.parse(query)\n}\n\nexport function mapToQueryString(query: Record<string, any> = {}): string {\n return queryString.stringify(query, { encode: false })\n}\n\nexport function getPageParams(path: string, routePath: string) {\n const pagePathWithRest =\n routePath && /\\*\\w+$/.test(routePath)\n ? routePath\n : routePath.replace(/\\/?$/, '*_rest')\n return (routePath && getParams(pagePathWithRest, path)) || EMPTY_OBJECT\n}\n\nfunction getParams(template: string, target: string) {\n const properTemplate = adjustTemplate(template)\n const properTarget = adjustPath(target)\n return new RouteParser(properTemplate).match(properTarget)\n}\n\nfunction getPagePath(name: string, pages: Pages) {\n const { path: pagePath, cname } = pages[name]\n return cname && isHost(cname) ? '/' : pagePath\n}\n\nfunction checkValidParams(id: string, pages: Pages, path: string, params: any) {\n const template = getValidTemplate(id, pages) || ''\n const validParams = getParams(template, path) as Record<string, any>\n const invalidParams = difference(keys(params), keys(validParams))\n\n if (!isEmpty(invalidParams)) {\n console.warn(\n `The following params are invalid: ${invalidParams.join(', ')}`\n )\n }\n}\n\nfunction getRouteFromPageName(\n id: string,\n pages: Pages,\n params: any\n): NavigationRoute | null {\n const pathParams = Object.keys(params)\n .filter((key) => !key.startsWith('__'))\n .reduce((acc, key) => {\n acc[key] = params[key]\n return acc\n }, {} as any)\n\n const path = pathFromPageName(id, pages, pathParams) || ''\n checkValidParams(id, pages, path, pathParams)\n\n return path ? { id, path, params } : null\n}\n\nfunction getCanonicalPath(\n canonicalPathTemplate: string,\n params: Record<string, string>\n): string | false {\n const properPathTemplate = adjustTemplate(canonicalPathTemplate)\n const canonicalPath = new RouteParser(properPathTemplate).reverse(params)\n if (canonicalPath) {\n return canonicalPath\n }\n\n console.warn(\n `Canonical path template '${canonicalPathTemplate}' could not be created with params: ${params}`\n )\n return false\n}\n\nexport function getRouteFromPath(\n path: string,\n pages: Pages\n): NavigationRoute | null {\n const routeMatch = routeMatchFromPath(path, pages)\n if (!routeMatch) {\n return null\n }\n\n const params = getPageParams(path, routeMatch.path)\n const navigationPath = routeMatch.canonical\n ? getCanonicalPath(routeMatch.canonical, params) || path\n : path\n\n return {\n id: routeMatch.id,\n params,\n path: navigationPath,\n }\n}\n\nexport function getRouteFromPathOld(\n path: string,\n pages: Pages,\n query?: string,\n hash?: string\n): NavigationRoute | null {\n const queryMap = query ? queryStringToMap(hash ? query + hash : query) : {}\n const routeMatch = routeIdFromPathAndQueryOld(path, queryMap, pages)\n if (!routeMatch) {\n return null\n }\n\n const params = getPageParams(path, routeMatch.path)\n const navigationPath = routeMatch.canonical\n ? getCanonicalPath(routeMatch.canonical, params) || path\n : path\n\n return {\n id: routeMatch.id,\n params,\n path: navigationPath,\n }\n}\n\nconst mergePersistingQueries = (currentQuery: string, query: string) => {\n const KEYS = ['disableUserLand', '__bindingAddress', '__siteEditor']\n const current = queryStringToMap(currentQuery)\n const next = queryStringToMap(query)\n const has = (value?: string) => !!value || value === null\n const persisting = KEYS.reduce<Record<string, any>>((cur, key) => {\n if (has(current[key]) && current[key] !== 'false') {\n cur[key] = current[key]\n }\n return cur\n }, {})\n return mapToQueryString({ ...persisting, ...next })\n}\n\nexport const formatPathParameters = (params: Record<string, string>) => {\n const obj: Record<string, string> = {}\n for (const key in params) {\n obj[key] = decodeURI(params[key])\n }\n\n return obj\n}\n\nexport function getNavigationRouteToNavigate(\n pages: Pages,\n options: NavigateOptions,\n showLogs = false\n) {\n const {\n page,\n params,\n query: inputQuery,\n to: inputTo = '',\n rootPath,\n modifiers,\n modifiersOptions,\n } = options\n\n if (!page && !inputTo) {\n showLogs &&\n console.error(\n `Invalid navigation options. You should use 'page' or 'to' parameters`\n )\n return null\n }\n\n if (inputTo && inputQuery) {\n showLogs &&\n console.warn(\n `You shouldn't pass 'query' in a separate prop when using 'to'`\n )\n }\n\n // If the prop `to` is something like `to=\"#header\"`\n // just change the hash using location, avoid doing a history navigation\n if (inputTo.indexOf('#') === 0 && inputTo.indexOf('?') === -1) {\n return { hash: inputTo }\n }\n\n const [to, extractedQuery] = (is(String, inputTo) ? inputTo : '').split('?')\n const [realQuery, hash] = (is(String, extractedQuery)\n ? extractedQuery\n : ''\n ).split('#')\n const realHash = is(String, hash) ? `#${hash}` : ''\n let query = inputQuery || realQuery\n\n const decodedParams = formatPathParameters(params)\n\n let navigationRoute: any = {}\n\n if (isEnabled('RENDER_NAVIGATION')) {\n const fallbackPage = { path: to, params: {}, id: '' }\n const routeFromPage =\n page && getRouteFromPageName(page, pages, decodedParams)\n const routeFromPath = getRouteFromPath(to, pages)\n navigationRoute = routeFromPage || routeFromPath || fallbackPage\n } else {\n navigationRoute = page\n ? getRouteFromPageName(page, pages, decodedParams)\n : getRouteFromPathOld(to, pages, query, realHash)\n }\n\n if (!navigationRoute) {\n showLogs &&\n console.warn(\n `Unable to find route for ${\n page ? `page '${page}' and the passed parameters` : `path '${to}'`\n }`\n )\n return null\n }\n\n navigationRoute.path = navigationRootPath(navigationRoute.path, rootPath)\n if (modifiers) {\n for (const modifier of modifiers) {\n const { path, query: fixedQuery } = modifier({\n path: navigationRoute.path,\n query,\n options: modifiersOptions,\n })\n navigationRoute.path = path || navigationRoute.path\n query = fixedQuery || query\n }\n }\n navigationRoute.realHash = realHash\n navigationRoute.query = query\n return navigationRoute\n}\n\nexport function navigate(\n history: History | null,\n pages: Pages,\n options: NavigateOptions\n) {\n const {\n scrollOptions,\n fallbackToWindowLocation = true,\n replace,\n fetchPage = true,\n preventRemount,\n skipSetPath = false,\n } = options\n\n const navigationRoute = getNavigationRouteToNavigate(pages, options, true)\n if (navigationRoute.hash) {\n window.location.hash = navigationRoute.hash\n return true\n }\n\n if (navigationRoute == null) {\n return false\n }\n\n if (history) {\n const nextQuery = mergePersistingQueries(\n history.location.search,\n navigationRoute.query\n )\n const location = createLocationDescriptor(navigationRoute, {\n fetchPage,\n preventRemount,\n query: nextQuery,\n scrollOptions,\n hash: navigationRoute.realHash,\n skipSetPath,\n })\n const method = replace ? 'replace' : 'push'\n window.setTimeout(() => history[method](location), 0)\n return true\n }\n\n if (fallbackToWindowLocation) {\n window.location.href = `${navigationRoute.path}${navigationRoute.query}`\n return true\n }\n\n return false\n}\n\nfunction navigationRootPath(path: string, rootPath?: string) {\n // Prefix any non-absolute paths (e.g. http:// or https://) with runtime.rootPath\n if (\n rootPath &&\n !path.startsWith('http') &&\n !path.startsWith(`${rootPath}/`)\n ) {\n return rootPath + path\n }\n\n return path\n}\n\nexport function goBack(history: History | null) {\n if (history) {\n window.setTimeout(() => history.goBack(), 0)\n return true\n }\n\n console.warn('Unable to go to previous page')\n return false\n}\n\nexport function scrollTo(options: RelativeScrollToOptions) {\n const { baseElementId = null } = options || {}\n const scrollAnchor =\n baseElementId && document.querySelector(`#${baseElementId}`)\n\n if (!scrollAnchor) {\n return polyfillScrollTo(options)\n }\n\n const { top, left } = scrollAnchor.getBoundingClientRect()\n polyfillScrollTo({\n left: left + window.scrollX + (options.left || 0),\n top: top + window.scrollY + (options.top || 0),\n })\n}\n\nfunction polyfillScrollTo(options: ScrollToOptions) {\n try {\n window.scrollTo(options)\n } catch (e) {\n const x = options.left == null ? window.scrollX : options.left\n const y = options.top == null ? window.scrollY : options.top\n window.scrollTo(x, y)\n }\n}\n\nfunction routeMatchForMappedURL(\n mappedSegments: string[],\n routes: Pages\n): RouteMatch | null {\n let id: string | undefined\n let score: number\n let highScore: number = Number.NEGATIVE_INFINITY\n\n for (const name in routes) {\n const { map = [], path: routePath } = routes[name]\n if (!routePath || map.length === 0 || !startsWith(map, mappedSegments)) {\n continue\n }\n\n score = map.length\n if (highScore > score) {\n continue\n }\n\n highScore = score\n id = name\n }\n\n if (!id) {\n return null\n }\n\n const { path } = routes[id]\n const pathSegments = path.split('/')\n const slicedPathSegments = pathSegments.slice(0, highScore + 1)\n const newPath = slicedPathSegments.join('/')\n\n return {\n id,\n path: removeTrailingParenthesis(newPath),\n }\n}\n\nfunction routeMatchFromPath(path: string, routes: Pages): RouteMatch | null {\n let id: string | undefined\n let pathPrecedence: string\n let chosenPathPrecedence: string | null = null\n\n for (const name in routes) {\n const pagePath = getPagePath(name, routes)\n if (!pagePath) {\n continue\n }\n\n const matches = !!getParams(pagePath, path)\n if (!matches) {\n continue\n }\n\n pathPrecedence = getComparablePrecedence(pagePath)\n if (\n chosenPathPrecedence !== null &&\n chosenPathPrecedence < pathPrecedence\n ) {\n continue\n }\n\n chosenPathPrecedence = pathPrecedence\n id = name\n }\n\n if (!id) {\n return null\n }\n\n return {\n canonical: routes[id].canonical,\n id,\n path: getPagePath(id, routes),\n }\n}\n\nfunction routeIdFromPathAndQueryOld(\n path: string,\n query: Record<string, string>,\n routes: Pages\n) {\n const mappedSegments = query.map ? query.map.split(',') : []\n let routeMatch: RouteMatch | null = null\n\n // Don't use map segments to match a route when Render\n // navigation is enabled\n if (mappedSegments.length > 0 && !isEnabled('RENDER_NAVIGATION')) {\n routeMatch = routeMatchForMappedURL(mappedSegments, routes)\n }\n\n if (!routeMatch) {\n routeMatch = routeMatchFromPath(path, routes)\n }\n\n return routeMatch\n}\n\ninterface RouteMatch {\n canonical?: string\n id: string\n path: string\n}\n\nexport interface NavigateOptions {\n hash?: string\n page?: string\n params?: any\n query?: any\n to?: string\n scrollOptions?: RenderScrollOptions\n fallbackToWindowLocation?: boolean\n replace?: boolean\n fetchPage?: boolean\n preventRemount?: boolean\n rootPath?: string\n modifiers?: Set<NavigationRouteModifier>\n modifiersOptions?: Record<string, any>\n skipSetPath?: boolean\n}\n\nexport interface NavigationRouteChange {\n path: string\n query?: string\n options?: Record<string, NavigationRouteChange>\n}\n\nexport type NavigationRouteModifier = (\n navigationRoute: NavigationRouteChange\n) => NavigationRouteChange\n\n```"
}
] |
code_render-runtime_40aa1c53
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of render-runtime/react/utils/location.ts from the render-runtime VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport queryString from 'query-string'\nimport { pickBy } from 'ramda'\n\nexport const appendLocationSearch = (\n search: string,\n params: Record<string, string>\n) => {\n if (!search) {\n return `?${queryString.stringify(params, { encode: false })}`\n }\n\n const included = queryString.parse(search)\n const filteredParams = pickBy(\n (_, paramName) => !(paramName in included),\n params\n ) as Record<string, string>\n const additionalSearch = queryString.stringify(filteredParams, {\n encode: false,\n })\n if (!additionalSearch) {\n return search\n }\n\n return `${search}&${additionalSearch}`\n}\n\n```"
}
] |
code_render-runtime_15d3f612
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of render-runtime/react/utils/cookie.ts from the render-runtime VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { canUseDOM } from 'exenv'\n\nconst ONE_YEAR_S = 60 * 60 * 24 * 365\n\nexport const setCookie = (\n key: string,\n value: string,\n path = '/',\n maxAge: number = ONE_YEAR_S\n) => {\n if (!canUseDOM) {\n return\n }\n\n window.document.cookie = `${key}=${value};path=${path};max-age=${maxAge}`\n}\n\n```"
}
] |
code_render-runtime_c2bdf681
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of render-runtime/react/utils/reactApollo.tsx from the render-runtime VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React, { PureComponent } from 'react'\nimport { Query, Mutation } from 'react-apollo'\nimport { compose } from 'ramda'\n\nconst noop = () => {}\n\nclass RenderRuntimeQuery extends PureComponent<{\n children: (result: any) => JSX.Element | null\n}> {\n public render() {\n const { children, ...rest } = this.props\n\n return (\n <Query {...(rest as any)}>\n {(result: any) => {\n if (result.networkStatus === 1 && result.data === undefined) {\n result.data = {} as any\n result.refetch = noop as any\n }\n return children(result)\n }}\n </Query>\n )\n }\n}\n\nclass RenderRuntimeMutation extends PureComponent<{\n children: (mutateFunction: any, result: any) => JSX.Element | null\n}> {\n public render() {\n const { children, ...rest } = this.props\n\n return (\n <Mutation {...(rest as any)}>\n {(mutateFunction: any, result: any) => {\n return children(mutateFunction, result)\n }}\n </Mutation>\n )\n }\n}\n\nexport const createCustomReactApollo = () => {\n // eslint-disable-next-line no-unused-vars\n const { Query, Mutation, ...rest } = window.ReactApollo\n return {\n ...rest,\n Query: RenderRuntimeQuery,\n Mutation: RenderRuntimeMutation,\n compose,\n }\n}\n\n```"
}
] |
code_render-runtime_ceae8295
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of render-runtime/react/utils/vteximg.ts from the render-runtime VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { isEnabled } from './flags'\n\nconst SECURE_PROTOCOL = 'https://'\nconst PROTOCOL_RELATIVE_PREFIX = '//'\nconst ARQUIVOS_RELATIVE_PREFIX = '/arquivos'\nconst ASSETS_RELATIVE_PREFIX = '/assets'\nconst FILE_MANAGER_PATH_REGEX = /url\\(\"?(.*\\/)assets\\/vtex\\.file-manager-graphql/\n\nconst toVtexAssets = (url: string) =>\n isEnabled('VTEX_ASSETS_URL')\n ? url.replace('vteximg.com.br', 'vtexassets.com')\n : url\n\nexport function optimizeSrcForVtexImg(vtexImgHost: string, src?: any) {\n try {\n if (src && src.indexOf(PROTOCOL_RELATIVE_PREFIX) === 0) {\n return toVtexAssets(\n src.replace(PROTOCOL_RELATIVE_PREFIX, SECURE_PROTOCOL)\n )\n }\n\n if (\n src &&\n (src.indexOf(ARQUIVOS_RELATIVE_PREFIX) === 0 ||\n src.indexOf(ASSETS_RELATIVE_PREFIX) === 0)\n ) {\n return vtexImgHost + src\n }\n\n return toVtexAssets(src)\n } catch (e) {\n console.warn('Failed to optimize image source.')\n return src\n }\n}\n\nexport function optimizeStyleForVtexImg(vtexImgHost: string, style?: any) {\n try {\n if (style && style.backgroundImage) {\n const match = FILE_MANAGER_PATH_REGEX.exec(style.backgroundImage)\n if (match && match[1]) {\n style.backgroundImage = style.backgroundImage.replace(\n match[1],\n vtexImgHost + '/'\n )\n }\n }\n\n return style\n } catch (e) {\n console.warn('Failed to optimize style.')\n return style\n }\n}\n\nexport function isStyleWritable(props: any): boolean {\n const propertyDescriptor = Object.getOwnPropertyDescriptor(props, 'style')\n return (propertyDescriptor && propertyDescriptor.writable) || false\n}\n\n```"
}
] |
code_render-runtime_f555a25d
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of render-runtime/react/utils/pages.test.ts from the render-runtime VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { formatPathParameters, getComparablePrecedence } from './pages'\nimport RouteParser from 'route-parser'\n\ndescribe('#formatPathParameters', () => {\n it('should remove any encoding', () => {\n const params = [\n {\n term: 'a%2520b%2520c',\n },\n {\n term: 'a%20b%20c',\n },\n ]\n\n const results = params.map((param) => formatPathParameters(param))\n\n expect(results).toEqual([{ term: 'a%20b%20c' }, { term: 'a b c' }])\n })\n})\n\ndescribe('#routeParser', () => {\n it('should not add double enconding', () => {\n const params = [\n {\n term: 'a',\n },\n {\n term: 'b',\n },\n {\n term: 'a%20b%20c',\n },\n ]\n\n const validTemplate = ['/:term', '/:term', '/:term']\n\n const results = params.map((param, index) =>\n new RouteParser(validTemplate[index]).reverse(param)\n )\n\n expect(results).toEqual(['/a', '/b', '/a%20b%20c'])\n })\n})\n\ndescribe('#getPrecedence', () => {\n it('should set precedence as expected', () => {\n const routes = [\n '/a/b/c',\n '/a/:b/c',\n '/:a/b/c',\n '/a/b/:c',\n '/a/:b/:c',\n '/:a/b/:c',\n '/a/b/*c',\n '/a/:b/*c',\n '/:a/b/*c',\n '/a/*b',\n '/:a/*b',\n '/*a',\n ]\n\n const result = routes.sort((a, b) =>\n getComparablePrecedence(b) > getComparablePrecedence(a) ? -1 : 1\n )\n\n expect(result).toEqual([\n '/a/b/c',\n '/a/b/:c',\n '/a/b/*c',\n '/a/:b/c',\n '/a/:b/:c',\n '/a/:b/*c',\n '/a/*b',\n '/:a/b/c',\n '/:a/b/:c',\n '/:a/b/*c',\n '/:a/*b',\n '/*a',\n ])\n })\n})\n\n```"
}
] |
code_render-runtime_28a88740
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of render-runtime/react/utils/events.ts from the render-runtime VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport EventEmitter from 'eventemitter3'\nimport { canUseDOM } from 'exenv'\nimport { RenderRuntime } from '../typings/runtime'\n\ninterface IOEvent {\n key: string\n body: {\n code: string\n type: string\n hash: string\n locales: any\n subject: string\n updated: string[]\n }\n}\n\ninterface EventEmitterSource extends Array<EventEmitter> {\n eventSource?: EventSource\n}\n\ninterface EmittersRegistry {\n [key: string]: EventEmitterSource\n}\n\nconst CONNECTION_CLOSED = 2\n\nconst emittersByWorkspace: EmittersRegistry = {}\n\nconst initSSE = (\n account: string,\n workspace: string,\n baseURI: string,\n isProductionWorkspace: boolean\n) => {\n if (isProductionWorkspace) {\n return undefined\n }\n\n require('eventsource-polyfill')\n // eslint-disable-next-line @typescript-eslint/no-var-requires\n const myvtexSSE = require('myvtex-sse')\n const path = `vtex.builder-hub:*:react2,pages0,build.status,pages1,styles?workspace=${workspace}`\n const linkInterruptedPath = `colossus:*:link_interrupted?workspace=${workspace}`\n const source: EventSource = myvtexSSE(account, workspace, path, {\n verbose: false,\n host: baseURI,\n })\n const linkInterruptedSource: EventSource = myvtexSSE(\n account,\n workspace,\n linkInterruptedPath,\n {\n verbose: false,\n host: baseURI,\n }\n )\n\n const handler = ({ data }: MessageEvent) => {\n const event = JSON.parse(data) as IOEvent\n const {\n key,\n body: { code, type, hash, locales, subject, updated },\n } = event\n\n if (key === 'build.status') {\n switch (code) {\n case 'start':\n console.log(`[build] Build started. app=${subject}`)\n emittersByWorkspace[`${account}/${workspace}`].forEach((e) =>\n e.emit('build.status', code)\n )\n break\n case 'success':\n console.log(`[build] Build success. app=${subject}`)\n emittersByWorkspace[`${account}/${workspace}`].forEach((e) =>\n e.emit('build.status', code)\n )\n break\n case 'fail':\n console.log(`[build] Build failed. app=${subject}`)\n emittersByWorkspace[`${account}/${workspace}`].forEach((e) =>\n e.emit('build.status', code)\n )\n break\n }\n return\n }\n\n if (key === 'link_interrupted') {\n console.log(`[colossus] Link interrupted.`)\n emittersByWorkspace[`${account}/${workspace}`].forEach((e) =>\n e.emit('link_interrupted', code)\n )\n }\n\n switch (type) {\n case 'hmr':\n console.log(`[react2] Received update. app=${subject} hash=${hash}`)\n if (window.__RENDER_8_HOT__[subject]) {\n window.__RENDER_8_HOT__[subject].emit('webpackHotUpdate', hash)\n }\n break\n case 'reload':\n console.log(`[react2] Received reload. app=${subject}`)\n emittersByWorkspace[`${account}/${workspace}`].forEach((e) =>\n e.emit('build.status', 'reload')\n )\n location.reload(true)\n break\n case 'locales':\n console.log(\n `[react2] Received locale update. appId=${subject} locales=${locales}`\n )\n emittersByWorkspace[`${account}/${workspace}`].forEach((e) =>\n e.emit('localesUpdated', locales)\n )\n break\n case 'changed':\n console.log('[pages0] Extensions changed.')\n emittersByWorkspace[`${account}/${workspace}`].forEach((e) =>\n e.emit('extensionsUpdated')\n )\n break\n case 'blocks':\n console.log('[pages1] Blocks changed.')\n emittersByWorkspace[`${account}/${workspace}`].forEach((e) =>\n e.emit('blocksUpdated')\n )\n break\n case 'styles':\n console.log('[styles] Styles changed.')\n if (updated.some((filePath) => /style\\.json/gi.test(filePath))) {\n emittersByWorkspace[`${account}/${workspace}`].forEach((e) =>\n e.emit('styleTachyonsUpdate')\n )\n }\n if (updated.some((filePath) => /overrides\\.css/gi.test(filePath))) {\n emittersByWorkspace[`${account}/${workspace}`].forEach((e) =>\n e.emit('styleOverrides')\n )\n }\n\n break\n }\n }\n\n source.onmessage = handler\n linkInterruptedSource.onmessage = handler\n source.onopen = () =>\n console.log('[render] Connected to event server successfully')\n source.onerror = () =>\n console.log('[render] Connection to event server failed')\n linkInterruptedSource.onopen = () =>\n console.log('[colossus] Connected to event server successfully')\n linkInterruptedSource.onerror = () =>\n console.log('[colossus] Connection to event server failed')\n\n return source\n}\n\nexport const registerEmitter = (runtime: RenderRuntime, baseURI: string) => {\n if (!canUseDOM) {\n return null\n }\n\n const { account, production, workspace } = runtime\n\n // Share SSE connections for same account and workspace\n if (!emittersByWorkspace[`${account}/${workspace}`]) {\n emittersByWorkspace[`${account}/${workspace}`] = []\n emittersByWorkspace[`${account}/${workspace}`].eventSource = initSSE(\n account,\n workspace,\n baseURI,\n production\n )\n\n if (!production) {\n document.addEventListener('visibilitychange', () => {\n const es = emittersByWorkspace[`${account}/${workspace}`].eventSource\n // Ensure SSE server connection\n if (!document.hidden && es && es.readyState === CONNECTION_CLOSED) {\n emittersByWorkspace[`${account}/${workspace}`].eventSource = initSSE(\n account,\n workspace,\n baseURI,\n production\n )\n }\n })\n }\n }\n\n if (!runtime.emitter) {\n runtime.emitter = new EventEmitter()\n emittersByWorkspace[`${account}/${workspace}`].push(runtime.emitter)\n }\n\n return runtime.emitter\n}\n\n```"
}
] |
code_render-runtime_e5d3badb
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of render-runtime/react/utils/flags.ts from the render-runtime VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nconst flags = {\n RENDER_NAVIGATION: true,\n VTEX_ASSETS_URL: true,\n PREFETCH: false,\n}\n\nwindow.flags = flags\n\nexport const isEnabled = (flag: keyof typeof flags) => window.flags[flag]\n\n```"
}
] |
code_render-runtime_82aa8baf
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of render-runtime/react/utils/host.ts from the render-runtime VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { canUseDOM } from 'exenv'\n\nimport { RenderRuntime } from '../typings/runtime'\n\nfunction isRenderServedPage() {\n const generatorMetaTag = document.querySelector(`meta[name='generator']`)\n const generator = generatorMetaTag && generatorMetaTag.getAttribute('content')\n return generator && generator.startsWith('vtex.render-server')\n}\n\nexport function getBaseURI(runtime: RenderRuntime) {\n const {\n account,\n workspace,\n publicEndpoint,\n isJanusProxied,\n rootPath = '',\n } = runtime\n\n if (!canUseDOM) {\n return `${workspace}--${account}.${publicEndpoint}`\n }\n\n const {\n location: { hostname },\n } = window\n\n if (isJanusProxied) {\n return `${hostname}/api/io`\n }\n\n return hostname.endsWith(`.${publicEndpoint}`) || isRenderServedPage()\n ? hostname + rootPath\n : `${hostname}/api/io`\n}\n\n```"
}
] |
code_render-runtime_e11be5d1
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of render-runtime/react/utils/treePath.test.tsx from the render-runtime VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport { escapeRegex, isDirectChild } from './treePath'\n\ndescribe('#escapeRegex', () => {\n const specialRegexCharacters = [\n '[',\n ']',\n '\\\\',\n '^',\n '$',\n '.',\n '|',\n '?',\n '*',\n '+',\n '(',\n ')',\n ]\n\n it(`should prefix regex special characters: [ '${specialRegexCharacters.join(\n `', '`\n )}' ] with \\\\`, () => {\n specialRegexCharacters.forEach((specialRegexCharacter) => {\n expect(escapeRegex(specialRegexCharacter)).toEqual(\n `\\\\${specialRegexCharacter}`\n )\n })\n })\n\n it('should return own string if there are no special characters', () => {\n expect('testString').toBe('testString')\n })\n})\n\ndescribe('#isDirectChild', () => {\n it('should return true for one level of nesting', () => {\n expect(isDirectChild('store/home/shelf', 'store/home')).toBe(true)\n })\n\n it('should allow \"_\" on names', () => {\n expect(isDirectChild('store/home/shelf_0', 'store/home')).toBe(true)\n })\n\n it('should allow regex special characters on names', () => {\n expect(\n isDirectChild('store/home/$before_0/shelf_0', 'store/home/$before_0')\n ).toBe(true)\n })\n\n it('should return false for 2 levels nesting', () => {\n expect(isDirectChild('store/home/shelf/image', 'store/home')).toBe(false)\n })\n})\n\n```"
}
] |
code_render-runtime_49475516
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of render-runtime/react/utils/withDevice.tsx from the render-runtime VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React, { FC, ComponentType } from 'react'\nimport { useSSR } from '../components/NoSSR'\nimport { useMediaLayout } from 'use-media'\nimport { RenderRuntime } from '../typings/runtime'\n\nexport interface Props {\n runtime: RenderRuntime\n}\n\nexport interface WithDeviceProps {\n deviceInfo: DeviceInfo\n}\n\nexport enum Device {\n phone = 'phone',\n tablet = 'tablet',\n desktop = 'desktop',\n unknown = 'unknown',\n}\n\nexport interface DeviceInfo {\n type: Device\n isMobile: boolean\n}\n\nconst useDevice = (hints: RenderRuntime['hints']) => {\n const isSSR = useSSR()\n\n /** These screensizes are hardcoded, based on the default\n * Tachyons breakpoints. They should probably be the ones\n * configured via the style.json file, if available. */\n\n const isScreenMedium = useMediaLayout({ minWidth: '40rem' })\n const isScreenLarge = useMediaLayout({ minWidth: '64.1rem' })\n\n const serverDevice = {\n type: hints.phone\n ? Device.phone\n : hints.tablet\n ? Device.tablet\n : Device.desktop,\n isMobile: hints.mobile,\n }\n\n const clientDevice = {\n type: isScreenLarge\n ? Device.desktop\n : isScreenMedium\n ? Device.tablet\n : Device.phone,\n isMobile: !isScreenLarge,\n }\n\n return isSSR ? serverDevice : clientDevice\n}\n\nexport const withDevice = <P extends Props>(\n Component: ComponentType<P & WithDeviceProps>\n): FC<P> => {\n const MemoizedWithDevice = React.memo(\n ({ type, isMobile, ...props }: DeviceInfo & Props) => (\n <Component deviceInfo={{ type, isMobile }} {...(props as P)} />\n )\n )\n\n MemoizedWithDevice.displayName = 'MemoizedWithDevice'\n\n const WithDevice = ({ ...props }: P) => {\n const hints = props.runtime.hints\n const deviceInfo = useDevice(hints)\n\n return (\n <MemoizedWithDevice\n type={deviceInfo.type}\n isMobile={deviceInfo.isMobile}\n {...props}\n />\n )\n }\n\n return WithDevice\n}\n\n```"
}
] |
code_render-runtime_c5281bdd
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of render-runtime/react/utils/withHMR.tsx from the render-runtime VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport hoistNonReactStatics from 'hoist-non-react-statics'\nimport PropTypes from 'prop-types'\nimport React, { Component, ComponentType } from 'react'\n\nimport { withEmitter } from '../components/RenderContext'\nimport { isComponentType } from './registerComponent'\nimport { withTreePath } from './treePath'\n\nexport default (module: Module, InitialImplementer: any) => {\n if (!isComponentType(InitialImplementer) || !module.hot) {\n return InitialImplementer\n }\n\n /**\n * We should move this registering code to registerComponent.tsx. We currently\n * can not do this since old apps are still using this function to register\n * thenselves with the old withHMR function\n */\n const instances: HMRComponent[] = []\n const registerInstance = (instance: HMRComponent) => {\n instances.push(instance)\n }\n\n const unregisterInstance = (instance: HMRComponent) => {\n const index = instances.findIndex((registered) => registered === instance)\n if (index !== -1) {\n instances.splice(index, 1)\n }\n }\n\n class HMRComponent extends Component<any, { lastUpdate?: number }> {\n public static propTypes = {\n __clearError: PropTypes.func,\n __errorInstance: PropTypes.node,\n }\n\n public static get displayName(): string {\n return (\n HMRComponent.Implementer.displayName ||\n HMRComponent.Implementer.name ||\n 'Component'\n )\n }\n\n public static hotReload = (NewImplementer: ComponentType) => {\n HMRComponent.Implementer = NewImplementer\n hoistNonReactStatics(HMRComponent, NewImplementer)\n instances.forEach((instance) => instance.updateComponent())\n }\n\n private static Implementer = InitialImplementer as ComponentType\n\n public updateComponent = () => {\n const { __emitter, treePath, __clearError, __errorInstance } = this.props\n __emitter.emit('build.status', 'hmr:success')\n\n if (__clearError && __errorInstance) {\n __clearError()\n } else {\n this.setState({ lastUpdate: Date.now() })\n }\n\n console.log(\n `[render] Component updated via HMR. treePath=${treePath} updated=${HMRComponent.displayName}`\n )\n }\n\n public componentDidMount() {\n registerInstance(this)\n }\n\n public componentWillUnmount() {\n unregisterInstance(this)\n }\n\n public render() {\n // eslint-disable-next-line\n const { __emitter, __clearError, __errorInstance, treePath, ...props } = this.props\n return (\n this.props.__errorInstance || <HMRComponent.Implementer {...props} />\n )\n }\n }\n\n return hoistNonReactStatics(\n withEmitter(withTreePath(HMRComponent)),\n InitialImplementer\n )\n}\n\n```"
}
] |
code_render-runtime_000bb4ff
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of render-runtime/react/utils/graphQLErrorsStore.ts from the render-runtime VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { GraphQLError } from 'graphql'\n\nexport interface ExtendedGraphQLError extends GraphQLError {\n operationId: string\n extensions: {\n code: string\n exception: {\n stacktrace: string\n name?: string\n }\n }\n}\n\nexport function isExtendedGraphQLError(\n error: GraphQLError\n): error is ExtendedGraphQLError {\n return 'operationId' in error\n}\n\nconst ignoredErrorTypes = [\n 'UserInputError',\n 'AuthenticationError',\n 'ForbiddenError',\n]\n\nclass GraphQLErrorsStore {\n private operationIds: string[] = []\n\n public addOperationIds(errors: readonly GraphQLError[]) {\n const operationIds = errors.reduce<string[]>((acc, error) => {\n if (\n isExtendedGraphQLError(error) &&\n !ignoredErrorTypes.includes(\n (error.extensions.exception && error.extensions.exception.name) || ''\n )\n ) {\n return acc.concat(error.operationId)\n }\n return acc\n }, [])\n this.operationIds = this.operationIds.concat(operationIds)\n }\n\n public getOperationIds() {\n const operationIds = this.operationIds.slice()\n this.operationIds = []\n return operationIds\n }\n}\n\nconst Store = new GraphQLErrorsStore()\n\nexport default Store\n\n```"
}
] |
code_render-runtime_15fa4683
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of render-runtime/react/utils/cacheControl.ts from the render-runtime VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nconst MINIMUM_MAX_AGE_S = 5\nconst DEFAULT_MAX_AGE_S = 10 * 60\nconst STATIC_PAGE_MAX_AGE_S = 7 * 24 * 60 * 60\n\nconst parseCacheControl = (cacheControl: string) => {\n const cacheDirectives = cacheControl.split(',').map((d) => d.trim())\n const maxAgeDirective = cacheDirectives.find((d) => d.startsWith('max-age'))\n const maxAgeStr = maxAgeDirective ? maxAgeDirective.split('=')[1] : null\n const maxAge = maxAgeStr ? parseInt(maxAgeStr, 10) : 0\n\n return {\n maxAge,\n noCache: cacheDirectives.includes('no-cache'),\n noStore: cacheDirectives.includes('no-store'),\n }\n}\n\nconst getMaxAge = (response: Response) => {\n const cacheControlHeader = response.headers.get('cache-control')\n if (!cacheControlHeader) {\n return DEFAULT_MAX_AGE_S\n }\n\n const { noCache, noStore, maxAge } = parseCacheControl(cacheControlHeader)\n if (noCache || noStore) {\n return MINIMUM_MAX_AGE_S\n }\n\n return Math.max(MINIMUM_MAX_AGE_S, maxAge)\n}\n\nexport default class PageCacheControl {\n private maxAges: number[] = []\n\n public get maxAge(): number {\n return this.maxAges.length > 0\n ? Math.min(...this.maxAges)\n : STATIC_PAGE_MAX_AGE_S\n }\n\n public evaluate(innerResponse: Response) {\n const responseMaxAge = getMaxAge(innerResponse)\n this.maxAges.push(responseMaxAge)\n }\n}\n\n```"
}
] |
code_render-runtime_5efc88cf
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of render-runtime/react/utils/reactIntl.tsx from the render-runtime VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport PropTypes from 'prop-types'\nimport { FormattedRelativeTime, injectIntl } from 'react-intl'\nimport React, { FC } from 'react'\nimport hoistNonReactStatics from 'hoist-non-react-statics'\n\nfunction getDisplayName(Component: React.ComponentType<any>) {\n return Component.displayName || Component.name || 'Component'\n}\n\n// We do our best to maintain compatibility with the prvious API but this is not perfect\nconst getCorrectUnit = (timeDiff: number) => {\n const years = timeDiff / (millisecondsInDay * 365)\n if (isUnitValid(years)) {\n return {\n value: Math.round(years),\n unit: 'year',\n }\n }\n const months = timeDiff / (millisecondsInDay * 30)\n if (isUnitValid(months)) {\n return {\n value: Math.round(months),\n unit: 'month',\n }\n }\n\n const days = timeDiff / millisecondsInDay\n if (isUnitValid(days)) {\n return {\n value: Math.round(days),\n unit: 'day',\n }\n }\n const hours = timeDiff / millisecondsInHour\n if (isUnitValid(hours)) {\n return {\n value: Math.round(hours),\n unit: 'hour',\n }\n }\n const minutes = (timeDiff / 60) * 1000\n if (isUnitValid(minutes)) {\n return {\n value: Math.round(minutes),\n unit: 'minute',\n }\n }\n return {\n value: Math.round(timeDiff / 1000),\n unit: 'second',\n }\n}\n\nconst FormattedRelative: FC<any> = (props) => {\n console.warn(\n 'FormattedRelative was removed in react-intl@3.x, you are using an approximation. Plase start using FormattedRelativeTime.'\n )\n const { value } = props\n let timeDiff\n if (value instanceof Date) {\n timeDiff = value.getTime() - Date.now()\n }\n if (typeof value === 'string') {\n timeDiff = new Date(value).getTime() - Date.now()\n }\n if (!timeDiff) {\n return null\n }\n const { value: newValue, unit } = getCorrectUnit(timeDiff)\n return <FormattedRelativeTime value={newValue} unit={unit as any} />\n}\n\nconst addLocaleData = () => {\n console.warn(\n 'addLocaleData was removed in react-intl@3.x and is not needed anymore. Please read: https://github.com/formatjs/react-intl/blob/master/docs/Upgrade-Guide.md#formattedrelativetime'\n )\n}\n\nconst millisecondsInHour = 60 * 60 * 1000\nconst millisecondsInDay = 24 * millisecondsInHour\n\nconst isUnitValid = (value: number) => Math.abs(value) >= 1\n\nconst renderFormatRelative = (intl: any) => (value: any) => {\n console.warn(\n 'formatRelative was removed in react-intl@3.x, please start using formatRelativeTime.'\n )\n let timeDiff\n if (value instanceof Date) {\n timeDiff = value.getTime() - Date.now()\n }\n if (typeof value === 'string') {\n timeDiff = new Date(value).getTime() - Date.now()\n }\n if (!timeDiff) {\n return null\n }\n\n const { value: newValue, unit } = getCorrectUnit(timeDiff)\n\n return intl.formatRelativeTime(newValue, unit)\n}\n\nconst renderRuntimeInjectIntl: FC<any> = (\n WrappedComponent: any,\n options?: any\n) => {\n const intlPropName = (options && options.intlPropName) || 'intl'\n const forwardRef = (options && options.forwardRef) || false\n const WithRenderRuntimeIntl = injectIntl((props) => {\n const intlObj = props[intlPropName] as any\n if (intlObj) {\n intlObj.formatRelative = renderFormatRelative(intlObj)\n }\n return (\n <WrappedComponent\n {...props}\n ref={forwardRef ? props.forwardedRef : null}\n />\n )\n }, options)\n\n WithRenderRuntimeIntl.displayName = `renderRuntimeInjectIntl(${getDisplayName(\n WrappedComponent\n )}`\n WithRenderRuntimeIntl.WrappedComponent = WrappedComponent\n\n if (forwardRef) {\n return hoistNonReactStatics(\n // eslint-disable-next-line react/display-name\n React.forwardRef((props, ref) => (\n <WithRenderRuntimeIntl {...(props as any)} forwardedRef={ref} />\n )),\n WrappedComponent\n ) as any\n }\n return hoistNonReactStatics(WithRenderRuntimeIntl, WrappedComponent) as any\n}\n\nexport const createReactIntl = () => {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n const { injectIntl, ...rest } = window.ReactIntl\n if (!window.ReactIntlLocaleData) {\n window.ReactIntlLocaleData = {}\n }\n\n return {\n ...rest,\n injectIntl: renderRuntimeInjectIntl,\n intlShape: PropTypes.any,\n FormattedRelative,\n addLocaleData,\n }\n}\n\n```"
}
] |
code_render-runtime_d47cac10
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of render-runtime/react/utils/promise.ts from the render-runtime VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { canUseDOM } from 'exenv'\n\ntype Resolver<T> = T extends void\n ? (resolve: () => void) => void\n : (resolve: (value: T) => void) => void\n\nexport const promised = <T = void>(resolver: Resolver<T>) => {\n return new Promise<T>((resolve) => {\n if (!canUseDOM) {\n resolver(resolve)\n } else {\n setTimeout(() => resolver(resolve), 1)\n }\n })\n}\n\n```"
}
] |
code_render-runtime_44dda59a
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of render-runtime/react/utils/fetch.ts from the render-runtime VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nconst delay = (ms: number): Promise<void> => {\n return new Promise((resolve) => setTimeout(resolve, ms))\n}\n\nconst RETRY_STATUSES = [\n 0,\n 408,\n 425,\n 429,\n 500,\n 501,\n 502,\n 503,\n 504,\n 505,\n 506,\n 507,\n 508,\n 510,\n 511,\n]\n\nconst canRetry = (status: number) => RETRY_STATUSES.includes(status)\n\nconst ok = (status: number) => 200 <= status && status < 300\nconst isNotFound = (status: number) => status === 404\n\nexport const fetchWithRetry = (\n url: string,\n init: RequestInit,\n fetcher: GlobalFetch['fetch'],\n maxRetries = 3\n) => {\n let status = 500\n const callFetch = (\n attempt = 0\n ): Promise<{ response: Response; error: any }> =>\n fetcher(url, init)\n .then((response) => {\n status = response.status\n return ok(status) || isNotFound(status)\n ? { response, error: null }\n : response\n .json()\n .then((error) => ({ response, error }))\n .catch(() => ({\n response,\n error: { message: 'Unable to parse JSON' },\n }))\n })\n .then(({ response, error }) => {\n if (error) {\n throw new Error(error.message || 'Unknown error')\n }\n return { response, error: null }\n })\n .catch((error) => {\n console.error(error)\n\n if (attempt >= maxRetries || !canRetry(status)) {\n throw error\n }\n\n const ms = 2 ** attempt * 500\n return delay(ms).then(() => callFetch(++attempt))\n })\n\n return callFetch()\n}\n\n```"
}
] |
code_render-runtime_62da05bb
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of render-runtime/react/utils/dom.tsx from the render-runtime VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport { canUseDOM } from 'exenv'\nimport React, { Fragment, ReactElement, ReactPortal } from 'react'\nimport { createPortal as reactCreatePortal } from 'react-dom'\nimport { NamedMarkup } from '../typings/global'\n\nconst portalPattern = /START_SERVER_PORTAL_([^!]+)!((\\n|.)+)END_SERVER_PORTAL_\\1!/g\n\n// Map `placeholder/with/slashes` to `render-placeholder-with-slashes`.\nconst hyphenate = (name: string) => name.replace(/[^\\w]/g, '-')\n\nconst portalWrapperId = (name: string) => `render-portal-ssr-${hyphenate(name)}`\n\nexport const RENDER_CONTAINER_CLASS = 'render-container'\n\nexport const ROUTE_CLASS_PREFIX = 'render-route-'\n\nexport const routeClass = (name: string) =>\n `${ROUTE_CLASS_PREFIX}${hyphenate(name)}`\n\nconst renderContainer = (name: string, markup: string) =>\n `<div class=\"${RENDER_CONTAINER_CLASS} ${routeClass(name)}\">${markup}</div>`\n\nconst portalWrapper = (name: string, markup: string) =>\n `<span id=\"${portalWrapperId(name)}\">${markup}</span>`\n\nexport const createPortal = (\n children: ReactElement<any>,\n name: string,\n hydrate: boolean\n) => {\n window.__hasPortals__ = true\n\n if (!hydrate) {\n return canUseDOM ? null : (\n <Fragment>\n {`START_SERVER_PORTAL_${name}!`}\n {children}\n {`END_SERVER_PORTAL_${name}!`}\n </Fragment>\n )\n }\n\n const ssrPortalContainer = document.getElementById(portalWrapperId(name))\n if (ssrPortalContainer) {\n ssrPortalContainer.remove()\n }\n\n const container = document.getElementsByClassName(routeClass(name))[0]\n if (!container) {\n console.warn(`Missing React Portal container div.${routeClass(name)}`)\n return null\n }\n\n return reactCreatePortal(children, container) as ReactPortal\n}\n\nexport const getMarkups = (\n pageName: string,\n pageMarkup: string\n): NamedMarkup[] => {\n const markups: NamedMarkup[] = []\n\n let matches = window.__hasPortals__ && portalPattern.exec(pageMarkup)\n let strippedMarkup = pageMarkup\n while (matches) {\n const [matched, name, markup] = matches\n strippedMarkup = strippedMarkup.replace(matched, '')\n markups.push({\n markup: renderContainer(name, portalWrapper(name, markup)),\n name,\n })\n matches = portalPattern.exec(pageMarkup)\n }\n\n markups.unshift({\n markup: renderContainer(pageName, strippedMarkup),\n name: pageName,\n })\n\n return markups\n}\n\nconst checkIsSiteEditorIframe = () => {\n try {\n return (\n canUseDOM &&\n window.top !== window.self &&\n window.top.__provideRuntime &&\n !!window.top.__provideRuntime &&\n window.__RUNTIME__.route.domain === 'store'\n )\n } catch {\n return false\n }\n}\n\nexport const isSiteEditorIframe = checkIsSiteEditorIframe()\n\nexport const getOrCreateContainer = () => {\n if (!canUseDOM) {\n throw new Error('Should not try to get container on server side')\n }\n\n const existingContainer = document.getElementsByClassName(\n RENDER_CONTAINER_CLASS\n )[0]\n\n if (existingContainer) {\n return { container: existingContainer, created: false }\n }\n\n const containerDiv = document.createElement('div')\n containerDiv.className = `render-container ${routeClass(name)}`\n containerDiv.style.display = 'none'\n document.body.appendChild(containerDiv)\n return { container: containerDiv, created: true }\n}\n\n```"
}
] |
code_render-runtime_77d38436
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of render-runtime/react/components/LoadingBar.css from the render-runtime VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```css\n@keyframes loading-bar-animation {\n 0% {\n transform: scale(0, 1);\n }\n 10% {\n transform: scale(0.5, 1);\n }\n 20% {\n transform: scale(0.75, 1);\n }\n 100% {\n transform: scale(0.95, 1);\n }\n}\n\n.loadingBarAnimation {\n transform-origin: 0 0;\n animation: loading-bar-animation 6s ease-out;\n transform: scale(0.95, 1);\n}\n\n```"
}
] |
code_render-runtime_cf1cb1e3
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of render-runtime/react/components/ChildBlock.tsx from the render-runtime VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\nimport useChildBlock, { Block, ChildBlockType } from './useChildBlock'\n\ninterface ChildBlockProps extends ChildBlockType {\n children(block: Block | null): React.ReactNode\n}\n\nfunction ChildBlock({ id, children }: ChildBlockProps) {\n const block = useChildBlock({ id })\n\n return children(block)\n}\n\nexport default ChildBlock\n\n```"
}
] |
code_render-runtime_a22b858d
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of render-runtime/react/components/Link.tsx from the render-runtime VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React, {\n MouseEvent,\n useCallback,\n useMemo,\n AnchorHTMLAttributes,\n} from 'react'\nimport { NavigateOptions, pathFromPageName } from '../utils/pages'\nimport { useRuntime } from './RenderContext'\nimport { useIsPrefetchActive } from '../hooks/prefetch'\nimport PrefetchLink from './Prefetch/PrefetchLink'\n\nconst isLeftClickEvent = (event: MouseEvent<HTMLAnchorElement>) =>\n event.button === 0\n\nconst isModifiedEvent = (event: MouseEvent<HTMLAnchorElement>) =>\n !!(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey)\n\nconst absoluteRegex = /^https?:\\/\\/|^\\/\\//i\nconst telephoneRegex = /^tel:/i\nconst mailToRegex = /^mailto:/i\n\nconst isAbsoluteUrl = (url: string) => absoluteRegex.test(url)\nconst isTelephoneUrl = (url: string) => telephoneRegex.test(url)\nconst isMailToUrl = (url: string) => mailToRegex.test(url)\n\ninterface Props\n extends NavigateOptions,\n Omit<AnchorHTMLAttributes<HTMLAnchorElement>, 'href'> {\n onClick?: (event: React.MouseEvent) => void\n className?: string\n target?: string\n waitToPrefetch?: number\n}\n\nconst appendWorkspaceToURL = (\n url: string | undefined,\n workspace: string | undefined\n) => {\n if (\n url == null ||\n !workspace ||\n workspace === '' ||\n String(url).indexOf('workspace=') > -1\n ) {\n return url\n }\n\n const separator = String(url).includes('?') ? '&' : '?'\n return url + separator + 'workspace=' + workspace\n}\n\nconst Link: React.FunctionComponent<Props> = ({\n page,\n onClick = () => {},\n params,\n to,\n scrollOptions,\n query,\n children,\n modifiers,\n replace,\n modifiersOptions,\n target,\n waitToPrefetch,\n ...linkProps\n}) => {\n const {\n pages,\n navigate,\n rootPath = '',\n route: { domain },\n query: queryFromRuntime,\n getSettings,\n } = useRuntime()\n\n // If workspace is set via querystring, keep it\n const workspace = queryFromRuntime?.workspace\n\n const storeSettings = getSettings('vtex.store')\n\n const isPrefetchActive = useIsPrefetchActive()\n\n const options = useMemo(\n () => ({\n fallbackToWindowLocation: false,\n page,\n params,\n query: workspace ? appendWorkspaceToURL(query ?? '', workspace) : query,\n rootPath,\n scrollOptions,\n to: appendWorkspaceToURL(to, workspace),\n modifiers,\n replace,\n modifiersOptions,\n }),\n [\n page,\n params,\n query,\n workspace,\n rootPath,\n scrollOptions,\n to,\n modifiers,\n replace,\n modifiersOptions,\n ]\n )\n\n const handleClick = useCallback(\n (event: MouseEvent<HTMLAnchorElement>) => {\n if (\n isModifiedEvent(event) ||\n !isLeftClickEvent(event) ||\n (to && (isAbsoluteUrl(to) || isTelephoneUrl(to) || isMailToUrl(to))) ||\n storeSettings?.useDefaultBrowserNavigation\n ) {\n return\n }\n\n onClick(event)\n\n // If you pass a target different from \"_self\" the component\n // will behave just like a normal anchor element\n if ((target === '_self' || !target) && navigate(options)) {\n event.preventDefault()\n }\n },\n [\n to,\n storeSettings?.useDefaultBrowserNavigation,\n onClick,\n target,\n navigate,\n options,\n ]\n )\n\n const getHref = () => {\n if (to) {\n // Prefix any non-absolute paths (e.g. http:// or https://) and non-special links (e.g. mailto: or tel:)\n // with runtime.rootPath\n if (\n rootPath &&\n !to.startsWith('http') &&\n !to.startsWith(rootPath) &&\n !isTelephoneUrl(to) &&\n !isMailToUrl(to)\n ) {\n return rootPath + to\n }\n return to\n }\n if (page) {\n const path = pathFromPageName(page, pages, params)\n const qs = query ? `?${query}` : ''\n if (path) {\n return appendWorkspaceToURL(rootPath + path + qs, workspace)\n }\n }\n return '#'\n }\n\n const href = appendWorkspaceToURL(getHref(), workspace) ?? ''\n\n // Href inside admin iframe should omit the `/app/` path\n const hrefWithoutIframePrefix =\n domain && domain === 'admin' && href.startsWith('/admin/app/')\n ? href.replace('/admin/app/', '/admin/')\n : href\n\n const linkElementProps = {\n target,\n href: hrefWithoutIframePrefix,\n ...linkProps,\n onClick: handleClick,\n }\n\n if (isPrefetchActive) {\n return (\n <PrefetchLink\n waitToPrefetch={waitToPrefetch}\n page={page}\n options={options}\n {...linkElementProps}\n >\n {children}\n </PrefetchLink>\n )\n }\n\n return <a {...linkElementProps}>{children}</a>\n}\n\nexport default Link\n\n```"
}
] |
code_render-runtime_33cbc20c
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of render-runtime/react/components/ExtensionPoint.tsx from the render-runtime VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport ExtensionPoint from './ExtensionPoint/index'\n\n// We need this indirection so its types are exported\nexport default ExtensionPoint\n\n```"
}
] |
code_render-runtime_eb3f3a1d
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of render-runtime/react/components/MaybeContext.test.tsx from the render-runtime VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\nimport { cleanup, render } from '@vtex/test-tools/react'\nimport 'jest-dom/extend-expect'\nimport MaybeContext from './MaybeContext'\nimport { Extension } from '../typings/runtime'\n\nafterEach(cleanup)\n\nconst TEST_STRING = 'This is category '\n\nbeforeAll(() => {\n window.__RENDER_8_COMPONENTS__ = {\n product: function MockProduct(props: any) {\n return (\n <div>\n <h1>{props.title}</h1>\n <p>{TEST_STRING + props.categoryId}!</p>\n </div>\n )\n } as any,\n }\n})\n\ntest(`it should pass props defined in extensions[path]context.props to the underlying component`, () => {\n const PAGE = 'store.product'\n const mockContextProps = { categoryId: 1, title: 'Product!' }\n const mockExtensions: Record<string, Partial<Extension>> = {\n [PAGE]: {\n context: {\n props: mockContextProps,\n component: 'product',\n },\n },\n }\n\n const mockRuntime: any = { extensions: mockExtensions }\n\n const { getByText } = render(\n <MaybeContext nestedPage={PAGE} runtime={mockRuntime} />\n )\n expect(getByText(new RegExp(mockContextProps.title, 'i'))).toBeInTheDocument()\n expect(\n getByText(new RegExp(TEST_STRING + mockContextProps.categoryId, 'i'))\n ).toBeInTheDocument()\n})\n\nafterAll(() => {\n delete window.__RENDER_8_COMPONENTS__\n})\n\n```"
}
] |
code_render-runtime_af4bd51f
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of render-runtime/react/components/LayoutContainer.tsx from the render-runtime VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React, { FunctionComponent } from 'react'\nimport { useTreePath } from '../utils/treePath'\nimport ExtensionPoint from './ExtensionPoint'\nimport { useRuntime } from './RenderContext'\nimport { LoadingWrapper } from './LoadingContext'\nimport { LazyImages } from './LazyImages'\nimport FoldableContainer from './FoldableContainer'\nimport { isSiteEditorIframe } from '../utils/dom'\nimport { Route } from '../typings/runtime'\n\ntype Element = string | ElementArray\ntype ElementArray = Element[]\n\ninterface LayoutContainerProps {\n aboveTheFold?: number\n elements: Element\n}\n\ninterface ContainerProps {\n aboveTheFold?: number\n elements: Element\n isRow: boolean\n isMobile?: boolean\n preview?: boolean\n route?: Route\n}\n\nconst Container: FunctionComponent<ContainerProps> = ({\n aboveTheFold,\n elements,\n isRow,\n isMobile,\n preview,\n children,\n route,\n ...props\n}) => {\n const className = `flex flex-grow-1 w-100 ${\n isRow ? 'flex-row' : 'flex-column'\n }`\n\n if (typeof elements === 'string') {\n if (elements === '__children__') {\n return <>{children}</>\n }\n\n const elementIdRegex = /#(.*)/\n const elementId = elements.match(elementIdRegex)\n const containerClass = !elements.includes('fold')\n ? `vtex-render__container-id-${elementId ? elementId[1] : elements}`\n : ''\n return (\n <div className={isRow ? containerClass : className}>\n <ExtensionPoint id={elements} {...props} />\n </div>\n )\n }\n\n let foldIndex = elements.indexOf('__fold__')\n if (foldIndex === -1) {\n foldIndex = elements.indexOf(`__fold__.${isMobile ? 'mobile' : 'desktop'}`)\n }\n\n const hasFold = foldIndex > -1\n\n const lazyImagesFoldPosition = elements.indexOf(\n '__fold__.experimentalLazyImages'\n )\n const hasLazyImagesFold = lazyImagesFoldPosition > -1\n\n // TODO: Seems to be legacy and unused, might be removed in the future\n let elementsToRender = elements.length\n if (preview && aboveTheFold != null) {\n elementsToRender = aboveTheFold\n }\n\n const wrappedElements: JSX.Element[] = elements\n .slice(0, elementsToRender)\n .map((element: Element, i: number) => {\n let container = (\n <Container\n key={element.toString()}\n elements={element}\n isMobile={isMobile}\n isRow={!isRow}\n {...props}\n >\n {children}\n </Container>\n )\n\n if (hasLazyImagesFold && i > lazyImagesFoldPosition) {\n container = (\n <LazyImages key={element.toString()}>{container}</LazyImages>\n )\n }\n\n return container\n })\n\n if (!hasFold || isSiteEditorIframe || route?.path?.includes('__siteEditor')) {\n return <div className={className}>{wrappedElements}</div>\n }\n\n return (\n <div className={className}>\n <FoldableContainer foldIndex={foldIndex}>\n {wrappedElements}\n </FoldableContainer>\n </div>\n )\n}\n\nconst LayoutContainer: React.FunctionComponent<LayoutContainerProps> = (\n props\n) => {\n const { extensions, preview, hints, route } = useRuntime()\n const { treePath } = useTreePath()\n\n const extension = extensions[treePath]\n\n const elements =\n extension?.blocks?.map?.((insertion) => insertion.extensionPointId) ?? []\n const containerProps = { ...props, elements }\n\n const container = (\n <Container\n {...containerProps}\n preview={preview}\n isRow={false}\n isMobile={hints.mobile}\n route={route}\n />\n )\n\n const isRootTreePath = treePath.indexOf('/') === -1\n\n if (extension?.preview && isRootTreePath) {\n /** TODO: LoadingWrapper is in the end a makeshift Suspense.\n * Should probably be replaced in the future. */\n return <LoadingWrapper>{container}</LoadingWrapper>\n }\n\n return container\n}\n\nexport default LayoutContainer\n\n```"
}
] |
code_render-runtime_f172e5fb
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of render-runtime/react/components/canUseDOM.ts from the render-runtime VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { canUseDOM } from 'exenv'\n\nexport default canUseDOM\n\n```"
}
] |
code_render-runtime_d195204e
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of render-runtime/react/components/Session.tsx from the render-runtime VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React, { FunctionComponent, Fragment, useEffect, useState } from 'react'\nimport Loading from './Loading'\nimport { useRuntime } from './RenderContext'\n\ninterface Props {\n renderWhileLoading?: boolean\n}\n\nconst Session: FunctionComponent<Props> = ({\n renderWhileLoading,\n children,\n}) => {\n const [ensured, setEnsured] = useState(false)\n const [error, setError] = useState(null)\n const { ensureSession } = useRuntime()\n\n useEffect(() => {\n let isCurrent = true\n if (ensured || error) {\n return\n }\n\n ensureSession()\n .then(() => {\n if (isCurrent) {\n setEnsured(true)\n }\n })\n .catch((err: any) => {\n if (isCurrent) {\n setError(err)\n }\n })\n\n return () => {\n isCurrent = false\n }\n }, [ensureSession, ensured, error])\n\n if (ensured || renderWhileLoading) {\n return <Fragment>{children}</Fragment>\n }\n\n if (error) {\n return (\n <div className=\"bg-washed-red pa6 f5 serious-black br3 pre\">\n <span>Error initializing session</span>\n <pre>\n <code className=\"f6\">{error}</code>\n </pre>\n </div>\n )\n }\n\n return <Loading />\n}\n\nexport default Session\n\n```"
}
] |
code_render-runtime_f2299f4f
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of render-runtime/react/components/FoldableContainer.tsx from the render-runtime VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React, { FunctionComponent } from 'react'\nimport LazyRender from './LazyRender'\n\ninterface Props {\n foldIndex?: number\n}\nconst FoldableContainer: FunctionComponent<Props> = ({\n children,\n foldIndex,\n}) => {\n if (foldIndex == null || foldIndex === -1) {\n return <>{children}</>\n }\n const childrenArray = React.Children.toArray(children)\n const aboveTheFold = childrenArray.slice(0, foldIndex)\n const belowTheFold = childrenArray.slice(foldIndex).map((element, i) => {\n return <LazyRender key={i}>{element}</LazyRender>\n })\n\n return (\n <>\n {aboveTheFold}\n {belowTheFold}\n </>\n )\n}\n\nexport default FoldableContainer\n\n```"
}
] |
code_render-runtime_9dfa8ca1
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of render-runtime/react/components/LoadingBar.tsx from the render-runtime VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\nimport styles from './LoadingBar.css'\n\nconst LoadingBar = () => (\n <div\n className={`${styles.loadingBarAnimation} fixed top-0 left-0 right-0 z-max bg-action-primary`}\n style={{ height: 4 }}\n >\n <div\n style={{\n background:\n 'linear-gradient(90deg, rgba(255, 255, 255, 0.1) 80%, rgba(255, 255, 255, 0.5) 90%, rgba(255, 255, 255, 0.8))',\n width: '100%',\n height: '100%',\n }}\n />\n </div>\n)\n\nexport default LoadingBar\n\n```"
}
] |
code_render-runtime_ca596f50
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of render-runtime/react/components/RenderProvider.tsx from the render-runtime VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport debounce from 'debounce'\nimport { canUseDOM } from 'exenv'\nimport { equals, merge, mergeWith, difference } from 'ramda'\nimport { History, UnregisterCallback, LocationListener } from 'history'\nimport PropTypes from 'prop-types'\nimport React, { Component, Fragment, ReactElement, Suspense } from 'react'\nimport { ApolloProvider } from 'react-apollo'\nimport { Helmet } from 'react-helmet'\nimport { IntlProvider } from 'react-intl'\n\nimport {\n fetchAssets,\n getLoadedImplementation,\n hasComponentImplementation,\n hotReloadOverrides,\n hotReloadTachyons,\n prefetchAssets,\n} from '../utils/assets'\nimport {\n traverseComponent,\n traverseListOfComponents,\n fetchComponents,\n isConflictingLoadedComponents,\n} from '../utils/components'\nimport { setCookie } from '../utils/cookie'\nimport {\n isSiteEditorIframe,\n RENDER_CONTAINER_CLASS,\n ROUTE_CLASS_PREFIX,\n routeClass,\n} from '../utils/dom'\nimport { isEnabled } from '../utils/flags'\nimport { appendLocationSearch } from '../utils/location'\nimport {\n goBack as pageGoBack,\n mapToQueryString,\n navigate as pageNavigate,\n NavigateOptions,\n NavigationRouteChange,\n NavigationRouteModifier,\n queryStringToMap,\n scrollTo as pageScrollTo,\n} from '../utils/pages'\nimport {\n fetchDefaultPages,\n fetchNavigationPage,\n fetchServerPage,\n} from '../utils/routes'\nimport { TreePathContextProvider } from '../utils/treePath'\nimport BuildStatus from './BuildStatus'\nimport ExtensionManager from './ExtensionPoint/ExtensionManager'\nimport ExtensionPoint from './ExtensionPoint'\nimport { RenderContextProvider } from './RenderContext'\nimport type { RenderContext } from './RenderContext'\nimport RenderPage from './RenderPage'\nimport {\n getPrefetechedData,\n PrefetchContextProvider,\n} from './Prefetch/PrefetchContext'\nimport { withDevice, WithDeviceProps, DeviceInfo } from '../utils/withDevice'\nimport { ApolloClientFunctions } from '../utils/client'\nimport {\n ConfigurationDevice,\n ApolloClientType,\n RenderHistoryLocation,\n SetQueryOptions,\n RenderScrollOptions,\n ParsedServerPageResponse,\n ParsedPageQueryResponse,\n PageContextOptions,\n} from '../typings/global'\nimport { RenderRuntime, Components, Extension } from '../typings/runtime'\nimport { getMessages as getErrorPageMessages } from './ErrorPage/messages'\n\n// TODO: Export components separately on @vtex/blocks-inspector, so this import can be simplified\nconst InspectorPopover = React.lazy(\n () =>\n new Promise<{ default: any }>((resolve) => {\n import('@vtex/blocks-inspector').then((BlocksInspector) => {\n resolve({ default: BlocksInspector.default.InspectorPopover })\n })\n })\n)\n\ninterface Props {\n children: ReactElement<any> | null\n history: History | null\n root: string\n runtime: RenderRuntime\n sessionPromise: Promise<void>\n apollo: ApolloClientFunctions\n}\n\nexport interface RenderProviderState {\n appsEtag: RenderRuntime['appsEtag']\n cacheHints: RenderRuntime['cacheHints']\n components: RenderRuntime['components']\n culture: RenderRuntime['culture']\n defaultExtensions: RenderRuntime['defaultExtensions']\n device: ConfigurationDevice\n deviceInfo: RenderRuntime['deviceInfo']\n extensions: RenderRuntime['extensions']\n inspect: RenderRuntime['inspect']\n messages: RenderRuntime['messages']\n page: RenderRuntime['page']\n pages: RenderRuntime['pages']\n preview: RenderRuntime['preview']\n production: RenderRuntime['production']\n query: RenderRuntime['query']\n settings: RenderRuntime['settings']\n route: RenderRuntime['route']\n loadedDevices: RenderRuntime['loadedDevices']\n loadedPages: Set<string>\n blocksTree?: RenderRuntime['blocksTree']\n blocks?: RenderRuntime['blocks']\n contentMap?: RenderRuntime['contentMap']\n}\n\nconst SEND_INFO_DEBOUNCE_MS = 100\nconst DISABLE_PREFETCH_PAGES = '__disablePrefetchPages'\n\nconst noop = () => {}\n\nconst areOptionsDifferent = (a: NavigateOptions, b: NavigateOptions) => {\n return (\n a.page !== b.page ||\n a.query !== b.query ||\n a.to !== b.to ||\n a.rootPath !== b.rootPath ||\n !equals(a.params, b.params)\n )\n}\n\nconst prependRootPath = (path: string, rootPath?: string) => {\n if (!rootPath) {\n return path\n }\n\n const maybeSlash = path.startsWith('/') ? '' : '/'\n return `${rootPath}${maybeSlash}${path}`\n}\n\ninterface NavigationState {\n isNavigating: boolean\n lastOptions?: NavigateOptions\n}\n\nexport class RenderProvider extends Component<\n Props & WithDeviceProps,\n RenderProviderState\n> {\n navigationState: NavigationState = { isNavigating: false }\n public static childContextTypes = {\n account: PropTypes.string,\n addMessages: PropTypes.func,\n amp: PropTypes.bool,\n binding: PropTypes.object,\n blocks: PropTypes.object,\n blocksTree: PropTypes.object,\n contentMap: PropTypes.object,\n components: PropTypes.object,\n culture: PropTypes.object,\n defaultExtensions: PropTypes.object,\n // TODO: the prop \"device\" might be legacy. Figure out if it's still being used.\n device: PropTypes.string,\n // named \"deviceInfo\" to avoid conflicts with the possibly legacy \"device\".\n deviceInfo: PropTypes.shape({\n type: PropTypes.oneOf(['desktop', 'tablet', 'phone', 'unknown']),\n isMobile: PropTypes.bool,\n }),\n isMobile: PropTypes.bool,\n emitter: PropTypes.object,\n ensureSession: PropTypes.func,\n extensions: PropTypes.object,\n fetchComponent: PropTypes.func,\n fetchComponents: PropTypes.func,\n getSettings: PropTypes.func,\n goBack: PropTypes.func,\n hints: PropTypes.object,\n history: PropTypes.object,\n inspect: PropTypes.bool,\n messages: PropTypes.object,\n navigate: PropTypes.func,\n onPageChanged: PropTypes.func,\n page: PropTypes.string,\n pages: PropTypes.object,\n patchSession: PropTypes.func,\n platform: PropTypes.string,\n prefetchDefaultPages: PropTypes.func,\n addNavigationRouteModifier: PropTypes.func,\n prefetchPage: PropTypes.func,\n preview: PropTypes.bool,\n production: PropTypes.bool,\n publicEndpoint: PropTypes.string,\n query: PropTypes.object,\n renderMajor: PropTypes.number,\n rootPath: PropTypes.string,\n route: PropTypes.object,\n setDevice: PropTypes.func,\n setQuery: PropTypes.func,\n updateComponentAssets: PropTypes.func,\n updateExtension: PropTypes.func,\n updateRuntime: PropTypes.func,\n workspace: PropTypes.string,\n navigationRouteModifiers: PropTypes.object,\n }\n\n public static propTypes = {\n children: PropTypes.element,\n history: PropTypes.object,\n root: PropTypes.string,\n runtime: PropTypes.object,\n }\n\n public sendInfoFromIframe = debounce(\n (params?: { shouldUpdateRuntime?: boolean }) => {\n if (!isSiteEditorIframe) {\n return undefined\n }\n\n return window.top.__provideRuntime(\n this.getChildContext(),\n this.state.messages,\n (params && params.shouldUpdateRuntime) || false,\n // Deprecated\n this.updateMessages\n )\n },\n SEND_INFO_DEBOUNCE_MS\n )\n\n private rendered!: boolean\n private sessionPromise: Promise<void>\n private unlisten!: UnregisterCallback | undefined\n private apolloClient: ApolloClientType\n private hydrateApollo: ApolloClientFunctions['hydrate']\n private prefetchRoutes: Set<string>\n public navigationRouteModifiers: Set<NavigationRouteModifier>\n private navigationModifierOptions: Record<string, NavigationRouteChange>\n private fetcher: GlobalFetch['fetch']\n\n public constructor(props: Props & WithDeviceProps) {\n super(props)\n const {\n appsEtag,\n binding,\n blocks,\n blocksTree,\n cacheHints,\n contentMap,\n culture,\n messages,\n components,\n exposeBindingAddress,\n extensions,\n isJanusProxied,\n pages,\n page,\n query,\n production,\n rootPath = '',\n route,\n settings,\n loadedDevices,\n } = props.runtime\n const { apollo, history, deviceInfo, sessionPromise } = props\n const ignoreCanonicalReplacement = isJanusProxied || (query && query.map)\n this.fetcher = fetch\n\n if (binding && canUseDOM) {\n setCookie('vtex_binding_address', binding.canonicalBaseAddress)\n }\n\n if (history) {\n const renderLocation: RenderHistoryLocation = {\n ...history.location,\n search:\n exposeBindingAddress && binding\n ? appendLocationSearch(history.location.search, {\n __bindingAddress: binding.canonicalBaseAddress,\n })\n : history.location.search,\n pathname:\n ignoreCanonicalReplacement || !route.canonicalPath\n ? history.location.pathname\n : rootPath + route.canonicalPath,\n state: {\n navigationRoute: {\n id: route.id,\n params: route.params,\n path: history.location.pathname,\n },\n renderRouting: true,\n },\n }\n // TODO: use something with better performance than equals\n if (!equals(history.location as RenderHistoryLocation, renderLocation)) {\n history.replace(renderLocation)\n }\n // backwards compatibility\n window.browserHistory = global.browserHistory = history\n }\n\n // todo: reload window if client-side created a segment different from server-side\n this.sessionPromise = sessionPromise\n this.apolloClient = apollo.getClient(this)\n this.hydrateApollo = apollo.hydrate\n\n this.state = {\n appsEtag,\n blocks,\n blocksTree,\n cacheHints,\n contentMap,\n components,\n culture,\n defaultExtensions: {},\n device: 'any',\n loadedDevices: loadedDevices ?? [props.deviceInfo.type],\n deviceInfo,\n extensions,\n loadedPages: new Set([page]),\n messages,\n page,\n pages,\n preview: false,\n production,\n query,\n route,\n settings: settings || {},\n inspect: false,\n }\n\n this.prefetchRoutes = new Set<string>()\n this.navigationRouteModifiers = new Set()\n this.navigationModifierOptions = {}\n }\n\n public componentDidMount() {\n this.rendered = true\n const { history, runtime } = this.props\n const { production, emitter, publicEndpoint } = runtime\n\n this.unlisten = history?.listen(this.onPageChanged as LocationListener)\n emitter.addListener('localesChanged', this.onLocaleSelected)\n\n if (!production) {\n emitter.addListener('extensionsUpdated', this.updateRuntime)\n emitter.addListener('blocksUpdated', this.updateRuntime)\n emitter.addListener('styleOverrides', hotReloadOverrides)\n emitter.addListener('styleTachyonsUpdate', hotReloadTachyons)\n }\n\n this.sendInfoFromIframe()\n this.prefetchPages()\n\n if (\n publicEndpoint === 'myvtex.com' &&\n !production &&\n '__inspect' in (this.state.query || {})\n ) {\n this.setState({ inspect: true })\n }\n }\n\n public UNSAFE_componentWillReceiveProps(nextProps: Props) {\n const updatedProps = difference(\n Object.entries(nextProps),\n Object.entries(this.props)\n ).map(([propName]) => propName)\n\n /** Update all extensions if runtime has changed. */\n const hasUpdatedRuntime = updatedProps.includes('runtime')\n\n if (this.rendered && hasUpdatedRuntime) {\n const {\n runtime: { extensions },\n } = nextProps\n this.setState({ extensions })\n }\n }\n\n public componentWillUnmount() {\n const { runtime } = this.props\n const { production, emitter } = runtime\n if (this.unlisten) {\n this.unlisten()\n }\n emitter.removeListener('localesChanged', this.onLocaleSelected)\n\n if (!production) {\n emitter.removeListener('extensionsUpdated', this.updateRuntime)\n emitter.removeListener('blocksUpdated', this.updateRuntime)\n emitter.removeListener('styleOverrides', hotReloadOverrides)\n emitter.removeListener('styleTachyonsUpdate', hotReloadTachyons)\n }\n }\n\n public getChildContext(): RenderContext {\n const { history, runtime } = this.props\n const {\n components,\n contentMap,\n extensions,\n inspect,\n messages,\n page,\n pages,\n preview,\n culture,\n device,\n deviceInfo,\n route,\n query,\n defaultExtensions,\n } = this.state\n\n const {\n account,\n amp,\n binding,\n emitter,\n hints,\n platform,\n production,\n publicEndpoint,\n renderMajor,\n rootPath,\n workspace,\n } = runtime\n\n return {\n account,\n addMessages: this.addMessages,\n amp,\n binding,\n components,\n contentMap,\n culture,\n defaultExtensions,\n device,\n deviceInfo,\n emitter,\n ensureSession: this.ensureSession,\n extensions,\n fetchComponent: this.fetchComponent,\n fetchComponents: this.fetchComponents,\n getSettings: this.getSettings,\n goBack: this.goBack,\n hints,\n history,\n inspect,\n messages,\n navigate: this.navigate,\n onPageChanged: this.onPageChanged,\n page,\n pages,\n patchSession: this.patchSession,\n platform,\n prefetchDefaultPages: this.prefetchDefaultPages,\n addNavigationRouteModifier: this.addNavigationRouteModifier,\n navigationRouteModifiers: this.navigationRouteModifiers,\n prefetchPage: this.prefetchPage,\n preview,\n production,\n publicEndpoint,\n query,\n renderMajor,\n rootPath,\n route,\n setDevice: this.handleSetDevice,\n setQuery: this.setQuery,\n updateComponentAssets: this.updateComponentAssets,\n updateExtension: this.updateExtension,\n updateRuntime: this.updateRuntime,\n workspace,\n }\n }\n\n public getSettings = (app: string) => {\n const { settings } = this.state\n return settings[app]\n }\n\n public ensureSession = () => {\n return this.sessionPromise\n }\n\n public patchSession = (data?: any) => {\n return this.sessionPromise.then(() =>\n canUseDOM ? window.__RENDER_8_SESSION__.patchSession(data) : undefined\n )\n }\n\n public getCustomMessages = (locale: string) => {\n const { components } = this.state\n const componentsArray = Object.keys(components)\n\n const customMessages = componentsArray\n .map(getLoadedImplementation)\n .filter(\n (component) =>\n component &&\n (component.getCustomMessages || component.WrappedComponent)\n )\n .map((component) => {\n const getCustomMessages =\n component.getCustomMessages ||\n (component.WrappedComponent &&\n component.WrappedComponent.getCustomMessages) ||\n noop\n return getCustomMessages(locale)\n })\n .reduce((acc, strings) => ({ ...acc, ...strings }), {})\n\n return customMessages\n }\n\n public goBack = () => {\n const { history } = this.props\n return pageGoBack(history)\n }\n\n public setQuery = (\n query: Record<string, any> = {},\n {\n merge = true,\n replace = false,\n scrollOptions = false,\n }: SetQueryOptions = {}\n ): boolean => {\n const {\n history,\n runtime: { rootPath },\n } = this.props\n const {\n pages,\n page,\n route: { params },\n } = this.state\n if (!history) {\n return false\n }\n const {\n location: { search },\n } = history\n\n const current = queryStringToMap(search)\n const nextQuery = mapToQueryString(merge ? { ...current, ...query } : query)\n\n return pageNavigate(history, pages, {\n fetchPage: false,\n skipSetPath: true,\n page,\n params,\n query: nextQuery,\n replace,\n scrollOptions,\n rootPath,\n modifiers: this.navigationRouteModifiers,\n })\n }\n\n public navigate = (options: NavigateOptions) => {\n const {\n history,\n runtime: { rootPath },\n } = this.props\n const { pages } = this.state\n options.rootPath = rootPath\n options.modifiers = this.navigationRouteModifiers\n\n this.navigationModifierOptions = {\n ...this.navigationModifierOptions,\n ...options.modifiersOptions,\n }\n options.modifiersOptions = this.navigationModifierOptions\n\n if (this.navigationState.isNavigating) {\n const lastOptions = this.navigationState.lastOptions!\n if (!areOptionsDifferent(lastOptions, options)) {\n return false\n }\n }\n\n this.navigationState = {\n isNavigating: true,\n lastOptions: options,\n }\n\n return pageNavigate(history, pages, options)\n }\n\n private updateDeviceBlocks = async (deviceInfo: DeviceInfo) => {\n const {\n runtime: { isJanusProxied, rootPath },\n } = this.props\n\n const {\n route: { path },\n } = this.state\n\n const query = queryStringToMap(location.search) as RenderRuntime['query']\n\n const { components, extensions, messages } = await fetchServerPage({\n fetcher: this.fetcher,\n path: prependRootPath(path, rootPath),\n query,\n deviceInfo,\n isJanusProxied,\n })\n\n await this.fetchComponents(components, extensions)\n\n this.setState((state) => ({\n extensions: { ...state.extensions, ...extensions },\n components: { ...state.components, ...components },\n messages: { ...state.messages, ...messages },\n }))\n }\n\n public addNavigationRouteModifier = (modifier: NavigationRouteModifier) => {\n this.navigationRouteModifiers.add(modifier)\n }\n\n public replaceRouteClass = (route: string) => {\n try {\n const containers = document.getElementsByClassName(RENDER_CONTAINER_CLASS)\n const currentRouteClass = containers[0].className\n .split(' ')\n .find((c) => c.startsWith(ROUTE_CLASS_PREFIX))\n const newRouteClass = routeClass(route)\n\n Array.prototype.forEach.call(containers, (e: Element) => {\n if (currentRouteClass) {\n e.classList.remove(currentRouteClass)\n }\n e.classList.add(newRouteClass)\n })\n } catch (e) {\n console.error('Failed to set route class', routeClass(route))\n }\n }\n\n public scrollTo = (scrollOptions?: RenderScrollOptions) => {\n try {\n if (scrollOptions === false) {\n return\n }\n\n const options = scrollOptions || { top: 0, left: 0 }\n window.setTimeout(() => pageScrollTo(options), 0)\n } catch (e) {\n console.warn('Failed to scroll after page navigation.')\n }\n }\n\n private mergeRouteParams<T extends { params: any }>(\n matchingPage: T,\n transientRoute: { params: any }\n ): T {\n return {\n ...matchingPage,\n params: {\n ...transientRoute.params,\n ...matchingPage.params,\n },\n }\n }\n\n public afterPageChanged = (\n route: string,\n scrollOptions?: RenderScrollOptions\n ) => {\n this.navigationState = { isNavigating: false }\n this.replaceRouteClass(route)\n this.scrollTo(scrollOptions)\n this.sendInfoFromIframe()\n }\n\n public onPageChanged = (location: RenderHistoryLocation) => {\n const {\n runtime: { renderMajor, query: queryFromRuntime, isJanusProxied },\n history,\n } = this.props\n\n const {\n culture: { locale },\n pages: pagesState,\n production,\n route,\n loadedPages,\n deviceInfo,\n } = this.state\n const { state } = location\n\n // In case of other router's navigation, or when preventRemount is true, do nothing\n if (!state || !state.renderRouting || state.preventRemount) {\n return\n }\n\n const { navigationRoute, fetchPage } = state\n const { id: maybePage, params } = navigationRoute\n const transientRoute = { ...route, ...navigationRoute }\n\n // We always have to navigate to a page. If none was found, we\n // navigate to the current page with preview\n const allowConditions =\n pagesState[maybePage] && pagesState[maybePage].allowConditions\n const declarer = pagesState[maybePage] && pagesState[maybePage].declarer\n const shouldSkipFetchNavigationData =\n (!allowConditions && loadedPages.has(maybePage)) || fetchPage === false\n const query = queryStringToMap(location.search) as RenderRuntime['query']\n const page = maybePage || route.id\n\n if (shouldSkipFetchNavigationData) {\n return this.setState(\n {\n page,\n query,\n route: transientRoute,\n },\n () => this.afterPageChanged(page, state.scrollOptions)\n )\n }\n\n const paramsJSON = JSON.stringify(params)\n const apolloClient = this.apolloClient\n const routeId = page\n\n const {\n prefetchedPathData,\n routeData,\n destinationRouteId,\n } = getPrefetechedData(navigationRoute.path)\n\n if (prefetchedPathData && routeData && destinationRouteId) {\n const routeId = destinationRouteId\n const matchingPage = prefetchedPathData.matchingPage\n const contentResponse = prefetchedPathData.contentResponse\n let extensions = routeData.extensions\n let messages = routeData.messages\n if (contentResponse) {\n //create a fresh copy of extensions to not change the one in memory\n extensions = JSON.parse(JSON.stringify(routeData.extensions))\n messages = { ...messages, ...contentResponse.contentMessages }\n for (const {\n treePath,\n contentJSON,\n contentIds,\n } of contentResponse.extensionsContent || []) {\n if (contentJSON !== '{}') {\n extensions[treePath]!.content = contentJSON\n ? JSON.parse(contentJSON)\n : undefined\n }\n extensions[treePath]!.contentIds = contentIds\n }\n }\n\n this.hydrateApollo(prefetchedPathData.queryData).then(() => {\n this.setState(\n (state) => ({\n ...state,\n components: { ...state.components, ...routeData.components },\n extensions: { ...state.extensions, ...extensions },\n loadedPages: loadedPages.add(routeId),\n messages: { ...state.messages, ...messages },\n page: routeId,\n preview: false,\n query,\n route: this.mergeRouteParams(matchingPage, transientRoute),\n }),\n () => {\n this.navigationState = { isNavigating: false }\n this.replaceRouteClass(routeId)\n this.sendInfoFromIframe()\n this.scrollTo(state.scrollOptions)\n }\n )\n })\n\n return Promise.resolve()\n }\n\n // Sets the preloading state, which currently displays\n // a loading bar at the top of the page\n this.setState({\n preview: true,\n })\n\n // If workspace is set via querystring, keep it during navigation\n const workspaceFromQuery = queryFromRuntime?.workspace\n\n const navigationPromise = isEnabled('RENDER_NAVIGATION')\n ? fetchServerPage({\n fetcher: this.fetcher,\n path: navigationRoute.path,\n query,\n workspace: workspaceFromQuery,\n deviceInfo,\n isJanusProxied,\n }).then(\n async ({\n appsEtag,\n components,\n extensions,\n matchingPage,\n messages,\n pages,\n settings,\n queryData,\n }: ParsedServerPageResponse) => {\n if (\n isConflictingLoadedComponents(components, this.state.components)\n ) {\n this.scrollTo({ top: 0, left: 0 })\n window.location.reload()\n return new Promise(() => {})\n }\n\n await Promise.all([\n this.hydrateApollo(queryData),\n this.fetchComponents(components, extensions),\n ])\n\n this.setState(\n (state) => ({\n ...state,\n appsEtag,\n components: { ...state.components, ...components },\n extensions: { ...state.extensions, ...extensions },\n loadedDevices: [deviceInfo.type],\n loadedPages: loadedPages.add(matchingPage.routeId),\n messages: { ...state.messages, ...messages },\n page: matchingPage.routeId,\n pages,\n preview: false,\n query,\n route: this.mergeRouteParams(matchingPage, transientRoute),\n settings,\n }),\n () => {\n const scrollOptions =\n history?.action === 'POP' ? false : state.scrollOptions\n\n this.navigationState = { isNavigating: false }\n this.replaceRouteClass(matchingPage.routeId)\n this.sendInfoFromIframe()\n this.scrollTo(scrollOptions)\n }\n )\n }\n )\n : fetchNavigationPage({\n apolloClient,\n declarer,\n locale,\n paramsJSON,\n production,\n query: JSON.stringify(query),\n renderMajor,\n routeId,\n skipCache: false,\n }).then(\n async ({\n appsEtag,\n cacheHints,\n components,\n extensions,\n matchingPage,\n messages,\n pages,\n settings,\n }: ParsedPageQueryResponse) => {\n const updatedRoute = { ...transientRoute, ...matchingPage }\n await this.fetchComponents(components, extensions)\n\n this.setState(\n {\n appsEtag,\n cacheHints: mergeWith(merge, this.state.cacheHints, cacheHints),\n components: { ...this.state.components, ...components },\n extensions: { ...this.state.extensions, ...extensions },\n loadedPages: loadedPages.add(page),\n messages: { ...this.state.messages, ...messages },\n page,\n pages,\n preview: false,\n query,\n route: this.mergeRouteParams(updatedRoute, transientRoute),\n settings,\n },\n () => {\n this.navigationState = { isNavigating: false }\n this.replaceRouteClass(page)\n this.sendInfoFromIframe()\n this.scrollTo(state.scrollOptions)\n }\n )\n }\n )\n navigationPromise.finally(() => {\n if (this.navigationState.isNavigating) {\n this.navigationState = { isNavigating: false }\n }\n })\n return navigationPromise\n }\n\n public prefetchPage = (pageName: string) => {\n const { extensions } = this.state\n const component = extensions[pageName]?.component\n if (component) {\n const { runtime } = this.props\n const { components } = this.state\n const componentsAssetsMap = traverseComponent(components, component)\n return prefetchAssets(runtime, componentsAssetsMap)\n }\n }\n\n public prefetchDefaultPages = async (routeIds: string[]) => {\n const {\n runtime: { query },\n } = this.props\n\n const disablePrefetch =\n query &&\n DISABLE_PREFETCH_PAGES in query &&\n query[DISABLE_PREFETCH_PAGES] !== 'false'\n if (!disablePrefetch) {\n if (this.rendered) {\n console.warn(\n \"prefetchDefaultPages should only be called before RenderProvider's render.\"\n )\n return\n }\n routeIds.forEach((routeId) => this.prefetchRoutes.add(routeId))\n }\n }\n\n public updateComponentAssets = (availableComponents: Components) => {\n this.setState({\n components: {\n ...this.state.components,\n ...availableComponents,\n },\n })\n }\n\n public fetchComponents = async (\n components: RenderRuntime['components'],\n extensions?: RenderRuntime['extensions']\n ) => {\n const { runtime } = this.props\n await fetchComponents(components, runtime, extensions)\n this.sendInfoFromIframe({ shouldUpdateRuntime: true })\n }\n\n public fetchComponent: RenderContext['fetchComponent'] = (component) => {\n if (!canUseDOM) {\n throw new Error('Cannot fetch components during server side rendering.')\n }\n\n const { runtime } = this.props\n const { components } = this.state\n\n const hasImplementation = !!hasComponentImplementation(component)\n\n if (hasImplementation) {\n return Promise.resolve()\n }\n\n const componentsAssetsMap = traverseComponent(components, component)\n\n const assetsPromise = fetchAssets(runtime, componentsAssetsMap)\n\n assetsPromise.then(() => {\n this.sendInfoFromIframe({ shouldUpdateRuntime: true })\n })\n\n return assetsPromise\n }\n\n public onLocaleSelected = (\n locale: string,\n domain?: string,\n callback?: (locale: string) => unknown\n ) => {\n if (locale !== this.state.culture.locale) {\n const sessionData = { public: {} }\n\n if (domain && domain === 'admin') {\n sessionData.public = {\n admin_cultureInfo: {\n value: locale,\n },\n }\n } else {\n sessionData.public = {\n cultureInfo: {\n value: locale,\n },\n }\n }\n\n return this.patchSession(sessionData)\n .then(() => {\n if (callback) return callback(locale)\n\n return window.location.reload()\n })\n .catch((e) => {\n console.log('Failed to fetch new locale file.')\n console.error(e)\n })\n }\n\n return undefined\n }\n\n public updateRuntime = async (options?: PageContextOptions) => {\n const {\n runtime: { renderMajor, query: queryFromRuntime, isJanusProxied },\n } = this.props\n const {\n page,\n pages: pagesState,\n production,\n culture: { locale },\n route,\n query,\n deviceInfo,\n } = this.state\n const declarer = pagesState[page] && pagesState[page].declarer\n const { pathname } = window.location\n const paramsJSON = JSON.stringify(route.params || {})\n\n // If workspace is set via querystring, keep it during navigation\n const workspaceFromQuery = queryFromRuntime?.workspace\n\n const {\n appsEtag,\n cacheHints,\n components,\n extensions,\n messages,\n pages,\n settings,\n } = isEnabled('RENDER_NAVIGATION')\n ? await fetchServerPage({\n path: route.path,\n query,\n fetcher: this.fetcher,\n workspace: workspaceFromQuery,\n deviceInfo,\n isJanusProxied,\n })\n : await fetchNavigationPage({\n apolloClient: this.apolloClient,\n declarer,\n locale,\n paramsJSON,\n path: pathname,\n production,\n query: '',\n renderMajor,\n routeId: page,\n skipCache: true,\n ...options,\n })\n\n await this.fetchComponents(components, extensions)\n\n await new Promise<void>((resolve) => {\n this.setState(\n (state) => ({\n appsEtag,\n cacheHints: isEnabled('RENDER_NAVIGATION')\n ? state.cacheHints\n : cacheHints,\n components,\n extensions: {\n ...state.extensions,\n ...extensions,\n },\n messages: {\n ...state.messages,\n ...messages,\n },\n page,\n pages,\n route,\n settings,\n }),\n resolve\n )\n })\n\n await this.sendInfoFromIframe()\n }\n\n public updateExtension = async (name: string, extension: Extension) => {\n const { extensions } = this.state\n\n await new Promise<void>((resolve) => {\n this.setState(\n {\n extensions: {\n ...extensions,\n [name]: extension,\n },\n },\n resolve\n )\n })\n\n if (name !== 'store/__overlay') {\n await this.sendInfoFromIframe()\n }\n }\n\n public handleSetDevice = (device: ConfigurationDevice) => {\n this.setState({ device })\n }\n\n public addMessages = async (newMessages: RenderRuntime['messages']) => {\n await new Promise<void>((resolve) => {\n this.setState(\n (state) => ({\n ...state,\n messages: {\n ...state.messages,\n ...newMessages,\n },\n }),\n resolve\n )\n })\n\n await this.sendInfoFromIframe()\n }\n\n private updateDevice = debounce(\n async (deviceInfo: DeviceInfo) => {\n if (!deviceInfo) {\n return\n }\n if (!this.state.loadedDevices.includes(deviceInfo.type)) {\n /** If resizing from a smaller to a larger device, keeps the current\n * blocks while the new ones are being loaded.\n * If resizing from a larger to a smaller one, can't do this because\n * the larger blocks would overflow the window and look bad.\n */\n const deviceOrder = ['desktop', 'tablet', 'phone']\n const prevDeviceType = this.state.deviceInfo.type\n const keepCurrentDevice =\n deviceOrder.indexOf(deviceInfo.type) <\n deviceOrder.indexOf(prevDeviceType)\n if (!keepCurrentDevice) {\n this.setState({ deviceInfo })\n }\n\n this.setState((state) => ({\n preview: true,\n loadedDevices: [...state.loadedDevices, deviceInfo.type],\n }))\n\n await this.updateDeviceBlocks(deviceInfo)\n }\n this.setState({\n deviceInfo,\n preview: false,\n })\n },\n 200, // debounce timeout\n false // means \"don't call this function immediately, wait for the debounce timeout\"\n )\n\n public componentDidUpdate() {\n if (!equals(this.state.deviceInfo, this.props.deviceInfo)) {\n this.updateDevice(this.props.deviceInfo)\n }\n }\n\n public render() {\n const { children } = this.props\n const {\n culture: { locale },\n messages,\n pages,\n page,\n query,\n production,\n inspect,\n } = this.state\n\n const customMessages = this.getCustomMessages(locale)\n const errorMessages = getErrorPageMessages(locale)\n const mergedMessages = {\n ...errorMessages,\n ...messages,\n ...customMessages,\n }\n\n const component = children ? (\n React.cloneElement(children as ReactElement<any>, { query })\n ) : (\n <div className=\"render-provider\">\n <Helmet title={pages[page] && pages[page].title} />\n <RenderPage page={page} query={query} />\n </div>\n )\n\n const context = this.getChildContext()\n\n return (\n <RenderContextProvider runtime={context}>\n <TreePathContextProvider treePath=\"\">\n <ApolloProvider client={this.apolloClient}>\n <IntlProvider\n locale={locale}\n messages={mergedMessages}\n textComponent={Fragment}\n >\n <PrefetchContextProvider history={this.props.history}>\n <Fragment>\n <ExtensionManager runtime={this.props.runtime} />\n {!production && !isSiteEditorIframe && <BuildStatus />}\n {component}\n {isSiteEditorIframe ? (\n <ExtensionPoint id=\"store/__overlay\" />\n ) : null}\n {inspect && (\n <Suspense fallback={null}>\n <InspectorPopover />\n </Suspense>\n )}\n </Fragment>\n </PrefetchContextProvider>\n </IntlProvider>\n </ApolloProvider>\n </TreePathContextProvider>\n </RenderContextProvider>\n )\n }\n\n // Deprecated\n private updateMessages = (newMessages: RenderProviderState['messages']) => {\n this.setState(\n (prevState) => ({\n ...prevState,\n messages: { ...prevState.messages, ...newMessages },\n }),\n () => {\n this.sendInfoFromIframe()\n }\n )\n }\n\n private prefetchPages = () => {\n if (this.prefetchRoutes.size > 0) {\n setTimeout(this.execPrefetchPages, 6 * 1000)\n }\n }\n\n private execPrefetchPages = async () => {\n const {\n runtime,\n runtime: { renderMajor },\n } = this.props\n\n const {\n pages,\n culture: { locale },\n } = this.state\n\n const { components: defaultComponents } = await fetchDefaultPages({\n apolloClient: this.apolloClient,\n locale,\n pages,\n renderMajor,\n routeIds: Array.from(this.prefetchRoutes),\n })\n\n const allAssets = traverseListOfComponents(\n defaultComponents,\n Object.keys(defaultComponents)\n )\n\n await prefetchAssets(runtime, allAssets)\n }\n}\n\nexport default withDevice<Props>(RenderProvider)\n\n```"
}
] |
code_render-runtime_2e461591
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of render-runtime/react/components/RenderContext.tsx from the render-runtime VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport hoistNonReactStatics from 'hoist-non-react-statics'\nimport React, { ComponentType, useContext } from 'react'\nimport { History } from 'history'\nimport {\n ConfigurationDevice,\n RenderHistoryLocation,\n SetQueryOptions,\n PageContextOptions,\n} from '../typings/global'\nimport { RenderRuntime, Components, Extension } from '../typings/runtime'\nimport { NavigationRouteModifier, NavigateOptions } from '../utils/pages'\n\nexport interface RenderContext\n extends Pick<\n RenderRuntime,\n | 'account'\n | 'amp'\n | 'binding'\n | 'components'\n | 'contentMap'\n | 'culture'\n | 'defaultExtensions'\n | 'deviceInfo'\n | 'emitter'\n | 'extensions'\n | 'hints'\n | 'inspect'\n | 'messages'\n | 'page'\n | 'pages'\n | 'platform'\n | 'preview'\n | 'production'\n | 'publicEndpoint'\n | 'query'\n | 'renderMajor'\n | 'rootPath'\n | 'route'\n | 'workspace'\n > {\n addMessages: (newMessages: RenderRuntime['messages']) => Promise<void>\n addNavigationRouteModifier: (modifier: NavigationRouteModifier) => void\n ensureSession: () => Promise<void>\n fetchComponent: (component: string) => Promise<unknown>\n fetchComponents: (\n components: RenderRuntime['components'],\n extensions?: RenderRuntime['extensions']\n ) => Promise<void>\n getSettings: (app: string) => any\n goBack: () => void\n device: string\n history: History | null\n navigate: (options: NavigateOptions) => boolean\n onPageChanged: (location: RenderHistoryLocation) => void\n patchSession: (data?: any) => Promise<void>\n prefetchDefaultPages: (routeIds: string[]) => Promise<void>\n prefetchPage: (name: string) => void\n setDevice: (device: ConfigurationDevice) => void\n setQuery: (query?: Record<string, any>, options?: SetQueryOptions) => boolean\n updateComponentAssets: (availableComponents: Components) => void\n updateExtension: (name: string, extension: Extension) => Promise<void>\n updateRuntime: (options?: PageContextOptions) => Promise<void>\n navigationRouteModifiers: Set<NavigationRouteModifier>\n}\n\nexport interface RenderContextProps {\n runtime: RenderContext\n}\n\nexport interface EmitterProps {\n __emitter: RenderContext['emitter']\n}\n\nexport const RenderContext = React.createContext<RenderContext>({} as any)\nRenderContext.displayName = 'RenderContext'\n\nexport const RenderContextProvider: React.FC<RenderContextProps> = ({\n children,\n runtime,\n}) => (\n <RenderContext.Provider value={runtime}>{children}</RenderContext.Provider>\n)\nRenderContextProvider.displayName = 'RenderContextProvider'\n\nexport const useRuntime = (): RenderContext => {\n return useContext(RenderContext)\n}\n\nexport const withRuntimeContext = <TOriginalProps extends {} = {}>(\n Component: ComponentType<TOriginalProps & RenderContextProps>\n): ComponentType<TOriginalProps> => {\n const WithRuntimeContext = (props: TOriginalProps) => {\n const runtime = useRuntime()\n return <Component {...props} runtime={runtime} />\n }\n WithRuntimeContext.displayName = `withRuntimeContext(${\n Component.displayName || Component.name || 'Component'\n })`\n WithRuntimeContext.WrappedComponent = Component\n return hoistNonReactStatics<TOriginalProps, RenderContextProps>(\n WithRuntimeContext,\n Component\n )\n}\n\nexport const withEmitter = <TOriginalProps extends {} = {}>(\n Component: ComponentType<TOriginalProps & EmitterProps>\n): ComponentType<TOriginalProps> => {\n const WithEmitter = (props: TOriginalProps) => {\n const { emitter } = useRuntime()\n return <Component {...props} __emitter={emitter} />\n }\n WithEmitter.displayName = `withEmitter(${\n Component.displayName || Component.name || 'Component'\n })`\n WithEmitter.WrappedComponent = Component\n return hoistNonReactStatics<TOriginalProps, EmitterProps>(\n WithEmitter,\n Component\n )\n}\n\nexport default RenderContext\n\n```"
}
] |
code_render-runtime_cc77374d
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of render-runtime/react/components/LazyRender.tsx from the render-runtime VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React, { FunctionComponent, useRef, useState } from 'react'\nimport { useOnView } from '../hooks/viewDetection'\n\ninterface Props {\n height?: number\n offset?: number\n debug?: boolean\n}\n\nconst LazyRender: FunctionComponent<Props> = ({\n children,\n height = 400,\n offset = 300,\n}) => {\n const ref = useRef(null)\n const [hasBeenViewed, setHasBeenViewed] = useState(false)\n\n useOnView({\n ref,\n onView: () => {\n setHasBeenViewed(true)\n },\n once: true,\n initializeOnInteraction: true,\n })\n\n if (hasBeenViewed) {\n return <>{children}</>\n }\n\n return (\n <div\n style={{\n position: 'relative',\n width: '100%',\n height,\n }}\n className=\"vtex-render__lazy-container\"\n >\n <div\n ref={ref}\n style={{\n position: 'relative',\n width: '100%',\n top: -offset,\n height: '100%',\n paddingBottom: offset * 2,\n boxSizing: 'content-box',\n }}\n />\n </div>\n )\n}\n\nexport default LazyRender\n\n```"
}
] |
code_render-runtime_05aca69c
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of render-runtime/react/components/Helmet.tsx from the render-runtime VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport { Helmet } from 'react-helmet'\n\n// We need this indirection so its types are exported\nexport default Helmet\n\n```"
}
] |
code_render-runtime_df83c01f
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of render-runtime/react/components/useRuntime.ts from the render-runtime VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { useRuntime } from './RenderContext'\nimport type { RenderContext } from './RenderContext'\n\ntype PublicRuntime = Pick<\n RenderContext,\n | 'account'\n | 'binding'\n | 'culture'\n | 'deviceInfo'\n | 'getSettings'\n | 'hints'\n | 'history'\n | 'navigate'\n | 'page'\n | 'pages'\n | 'route'\n | 'production'\n | 'query'\n | 'renderMajor'\n | 'rootPath'\n | 'setQuery'\n | 'workspace'\n>\n\nconst usePublicRuntime = useRuntime as () => PublicRuntime\n\nexport default usePublicRuntime\n\n```"
}
] |
code_render-runtime_c6a8077a
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of render-runtime/react/components/Block.tsx from the render-runtime VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport ExtensionPoint from './ExtensionPoint/index'\n\n// We need this indirection so its types are exported\nexport default ExtensionPoint\n\n```"
}
] |
code_render-runtime_09e51299
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of render-runtime/react/components/useChildBlock.tsx from the render-runtime VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport { useExtension } from '../hooks/extension'\n\nexport interface ChildBlockType {\n id: string\n}\n\nexport interface Block {\n props: Record<string, any>\n}\n\nfunction useChildBlock(childBlock: ChildBlockType): Block | null {\n if (typeof childBlock === 'string') {\n throw new Error(\n `You are passing a string as a parameter to useChildBlock (\"${childBlock}\"). You should pass an object like {id: \"${childBlock}\"}.`\n )\n }\n\n const { id } = childBlock\n\n if (!id) {\n throw new Error('The id you are sending to useChildBlock is empty')\n }\n\n const extension = useExtension({ children: id })\n\n // We are explicitly not exposing the private API here\n return extension ? { props: extension.props } : null\n}\n\nexport default useChildBlock\n\n```"
}
] |
code_render-runtime_36e15bcd
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of render-runtime/react/components/RenderPage.tsx from the render-runtime VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React, { FC } from 'react'\nimport ExtensionPoint from './ExtensionPoint'\nimport MaybeContext from './MaybeContext'\nimport { useRuntime } from './RenderContext'\n\ninterface Props {\n page: string\n query?: Record<string, string>\n}\n\nconst RenderPage: FC<Props> = (props) => {\n const runtime = useRuntime()\n const { page, query } = props\n const {\n route: { params },\n } = runtime\n\n return (\n <MaybeContext\n nestedPage={page}\n query={query}\n params={params}\n runtime={runtime}\n >\n <ExtensionPoint id={page} query={query} params={params} {...props} />\n </MaybeContext>\n )\n}\n\nexport default RenderPage\n\n```"
}
] |
code_render-runtime_433752a6
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of render-runtime/react/components/LazyImages.tsx from the render-runtime VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React, { useContext, FC } from 'react'\nimport styles from './LazyImages.css'\nimport { Helmet } from 'react-helmet'\n\ninterface LazyImagesContext {\n lazyLoad: boolean\n /** \"native\" uses the attribute \"loading=lazy\", which is good but only works\n * on Chrome. lazysizes is a JS plugin already provided by render-runtime,\n * with broader support, but the behaviour might be a little worse at times */\n method: 'native' | 'lazysizes'\n}\n\nconst LazyImagesContext = React.createContext<LazyImagesContext>({\n lazyLoad: false,\n method: 'lazysizes',\n})\n\ninterface LazyImagesProps {\n lazyLoad?: boolean\n experimentalMethod?: LazyImagesContext['method']\n}\n\nconst LazyImages: FC<LazyImagesProps> = ({\n children,\n lazyLoad = true,\n experimentalMethod = 'lazysizes',\n}) => {\n return (\n <LazyImagesContext.Provider\n value={{ lazyLoad, method: experimentalMethod }}\n >\n {children}\n </LazyImagesContext.Provider>\n )\n}\n\nconst useLazyImagesContext = () => {\n const value = useContext(LazyImagesContext)\n\n return value\n}\n\ninterface MaybeLazyImageProps {\n createElement: typeof React.createElement\n imageProps: Record<string, any>\n}\n\nconst MaybeLazyImage: FC<MaybeLazyImageProps> = ({\n createElement = React.createElement,\n imageProps,\n}) => {\n const { lazyLoad, method } = useLazyImagesContext()\n\n if (lazyLoad) {\n let newImageProps = imageProps\n\n switch (method) {\n case 'native':\n newImageProps = {\n ...imageProps,\n loading: 'lazy',\n }\n break\n case 'lazysizes':\n /** adds `lazyload` class to enable lazysizes, and moves the image URI\n * from src to data-src. `styles.lazyload` is used to hide the \"broken image\"\n * symbol while the image hasn't been loaded */\n newImageProps = {\n ...imageProps,\n // explicity key because we need react to re-render the whole img element\n // in case the src changes (i.e: product-summary + sku)\n key: imageProps.src,\n className: `lazyload ${imageProps.className ?? ''} ${\n styles.lazyload\n }`,\n src: undefined,\n 'data-src': imageProps.src,\n loading: 'lazy',\n }\n break\n }\n return createElement.apply(React, ['img', newImageProps])\n }\n\n const isPreloaded = String(imageProps['data-vtex-preload']) === 'true'\n\n // If it's preloaded, render the image along with a Helmet that adds preload\n if (isPreloaded) {\n return (\n <>\n <Helmet\n link={[\n {\n rel: 'preload',\n as: 'image',\n href: imageProps.src,\n crossOrigin: imageProps.crossOrigin,\n },\n ]}\n />\n {createElement.apply(React, ['img', imageProps])}\n </>\n )\n }\n\n // Otherwise, just render the image\n return createElement.apply(React, ['img', imageProps])\n}\n\nexport { LazyImages, MaybeLazyImage, useLazyImagesContext }\n\n```"
}
] |
code_render-runtime_e0c1ff8a
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of render-runtime/react/components/Loading.tsx from the render-runtime VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\n\nimport Preview from './Preview'\n\nimport { useExtension } from '../hooks/extension'\n\nconst Loading = () => {\n const extension = useExtension()\n\n if (!extension) {\n return null\n }\n\n const { preview } = extension\n\n if (!preview) {\n return null\n }\n\n return <Preview extension={extension} />\n}\n\nexport default Loading\n\n```"
}
] |
code_render-runtime_7e4e737a
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of render-runtime/react/components/TrackEventsWrapper.tsx from the render-runtime VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport { forEach } from 'ramda'\nimport { PureComponent } from 'react'\nimport ReactDOM from 'react-dom'\n\ninterface Props {\n events?: string[]\n id?: string\n}\n\nconst sendEvent = (id: string, event: string) => {\n window.postMessage(\n {\n pageComponentInteraction: {\n blockId: id,\n interactionType: event,\n namespace: 'renderRuntime',\n },\n },\n '*'\n )\n}\n\nclass TrackEventsWrapper extends PureComponent<Props> {\n public eventsHandler: Record<string, () => void> = {}\n\n public componentDidMount() {\n const { id, events } = this.props\n if (events && events.length && id) {\n // eslint-disable-next-line react/no-find-dom-node\n const element = ReactDOM.findDOMNode(this)\n if (element && element.addEventListener) {\n forEach((event) => {\n this.eventsHandler[event] = () => sendEvent(id, event)\n element.addEventListener(event, this.eventsHandler[event])\n }, events)\n }\n }\n }\n\n public componentWillUnmount() {\n const { id, events } = this.props\n if (events && events.length && id) {\n // eslint-disable-next-line react/no-find-dom-node\n const element = ReactDOM.findDOMNode(this)\n if (element && element.addEventListener) {\n forEach(\n (event) =>\n element.removeEventListener(event, this.eventsHandler[event]),\n events\n )\n }\n }\n }\n\n public render() {\n const { children } = this.props\n return children\n }\n}\n\nexport default TrackEventsWrapper\n\n```"
}
] |
code_render-runtime_f0089e44
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of render-runtime/react/components/MaybeContext.tsx from the render-runtime VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React, { useMemo, Fragment, FC } from 'react'\nimport ComponentLoader from '../components/ExtensionPoint/ComponentLoader'\nimport { RenderContextProps } from './RenderContext'\nimport { ExtensionPoint } from '../core/main'\n\ninterface Props extends RenderContextProps {\n nestedPage: string\n params?: Record<string, any>\n query?: Record<string, string>\n}\n\nconst useContextComponent = ({\n nestedPage,\n query,\n params,\n runtime,\n}: Props & RenderContextProps) => {\n const { extensions } = runtime\n\n const { context, before, after, props: pageProps } =\n extensions[nestedPage] ?? {}\n\n const pageContextProps = pageProps && pageProps.context\n\n /** Allows rendering header/footer if the Context component is loading,\n * by exposing them to ExtensionPointComponent via props.\n * TODO:This is a bit of a hack. The header/footer should probably be decoupled\n * from the context, but doing so introduces bugs on some stores. */\n const beforeElements =\n before &&\n before.map((beforeId) => (\n <ExtensionPoint id={beforeId} key={beforeId} treePath={nestedPage} />\n ))\n\n const afterElements =\n after &&\n after.map((afterId) => (\n <ExtensionPoint id={afterId} key={afterId} treePath={nestedPage} />\n ))\n\n const contextProps = useMemo(() => {\n if (!context) {\n return undefined\n }\n return {\n ...pageContextProps,\n beforeElements,\n afterElements,\n nextTreePath: nestedPage,\n params,\n query,\n ...context.props,\n }\n }, [\n context,\n pageContextProps,\n beforeElements,\n afterElements,\n nestedPage,\n params,\n query,\n ])\n const contextComponent = context ? context.component : undefined\n return [contextProps, contextComponent]\n}\n\nconst MaybeContext: FC<Props> = ({\n children,\n nestedPage,\n query,\n params,\n runtime,\n}) => {\n const [contextProps, contextComponent] = useContextComponent({\n nestedPage,\n query,\n params,\n runtime,\n })\n\n return contextComponent ? (\n <ComponentLoader\n component={contextComponent}\n props={contextProps}\n runtime={runtime}\n treePath={nestedPage}\n hydration=\"always\"\n >\n {children}\n </ComponentLoader>\n ) : (\n <Fragment>{children}</Fragment>\n )\n}\n\nexport default MaybeContext\n\n```"
}
] |
code_render-runtime_70edc75d
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of render-runtime/react/components/NoSSR.tsx from the render-runtime VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React, {\n useState,\n useEffect,\n useLayoutEffect,\n FunctionComponent,\n} from 'react'\n\nconst useEnhancedEffect =\n typeof window !== 'undefined' ? useLayoutEffect : useEffect\n\nconst useSSR = () => {\n const [isCSRAvailable, setCSR] = useState(false)\n\n useEnhancedEffect(() => {\n setCSR(true)\n }, [])\n\n return !isCSRAvailable\n}\n\ninterface Props {\n onSSR?: React.ReactNode\n}\n\nconst NoSSR: FunctionComponent<Props> = ({ children, onSSR }) => {\n const isSSR = useSSR()\n\n return <>{isSSR ? onSSR : children}</>\n}\n\nexport default NoSSR\n\nexport { useSSR }\n\n```"
}
] |
code_render-runtime_7fd4ed44
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of render-runtime/react/components/BuildStatus.tsx from the render-runtime VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React, { Component } from 'react'\nimport { RenderContextProps, withRuntimeContext } from './RenderContext'\n\ninterface State {\n animateOut: boolean\n status: string | null\n anchor: 'left' | 'right'\n interrupted: boolean | null\n}\n\nclass BuildStatus extends Component<RenderContextProps, State> {\n private animateOutHandle!: number\n private hideHandle!: number\n\n public constructor(props: RenderContextProps) {\n super(props)\n\n this.state = {\n animateOut: false,\n status: null,\n interrupted: null,\n anchor: 'left',\n }\n }\n\n public clearTimeouts = () => {\n clearTimeout(this.animateOutHandle)\n clearTimeout(this.hideHandle)\n }\n\n public hideWithDelay = (delayMillis: number) => {\n this.animateOutHandle = window.setTimeout(\n () => this.setState({ animateOut: true }),\n delayMillis\n )\n this.hideHandle = window.setTimeout(\n () =>\n this.setState({ status: null, interrupted: null, animateOut: false }),\n delayMillis + 300\n )\n }\n\n private handleMouseOver = () => {\n this.setState((state) => ({\n anchor: state.anchor === 'left' ? 'right' : 'left',\n }))\n }\n\n public updateStatus = (status: string) => {\n // After we started a reload, the UI shouldn't move.\n if (this.state.status === 'reload') {\n return\n }\n\n this.setState({ status, animateOut: false })\n this.clearTimeouts()\n\n if (status === 'success' || status === 'hmr:success') {\n const delay = status === 'success' ? 2000 : 0\n this.hideWithDelay(delay)\n }\n }\n\n public updateInterrupted = () => {\n this.clearTimeouts()\n this.setState({ interrupted: true, animateOut: false })\n const delay = 2000\n this.hideWithDelay(delay)\n }\n\n public subscribeToStatus = () => {\n const { emitter } = this.props.runtime\n emitter.addListener('build.status', this.updateStatus)\n }\n\n public unsubscribeToStatus = () => {\n const { emitter } = this.props.runtime\n emitter.removeListener('build.status', this.updateStatus)\n }\n\n public subscribeToLinkInterrupted = () => {\n const { emitter } = this.props.runtime\n emitter.addListener('link_interrupted', this.updateInterrupted)\n }\n\n public unsubscribeToLinkInterrupted = () => {\n const { emitter } = this.props.runtime\n emitter.removeListener('link_interrupted', this.updateInterrupted)\n }\n\n public componentDidMount() {\n this.subscribeToStatus()\n this.subscribeToLinkInterrupted()\n }\n\n public componentWillUnmount() {\n this.unsubscribeToStatus()\n this.unsubscribeToLinkInterrupted()\n this.clearTimeouts()\n }\n\n private renderLoading = () => (\n <svg\n width=\"26px\"\n height=\"26px\"\n viewBox=\"0 0 100 100\"\n preserveAspectRatio=\"xMidYMid\"\n >\n <style>{`\n @keyframes build-status-rotate {\n 0% {\n transform: rotate(0);\n }\n 100% {\n transform: rotate(360deg);\n }\n }\n\n .build-status-rotate {\n transform-origin: 50px 50px;\n animation: build-status-rotate 0.7s infinite linear;\n }\n\n `}</style>\n <g>\n <circle\n cx=\"50\"\n opacity=\"0.4\"\n cy=\"50\"\n fill=\"none\"\n stroke=\"#F71963\"\n r=\"40\"\n strokeWidth=\"14\"\n />\n <circle\n cx=\"50\"\n cy=\"50\"\n fill=\"none\"\n stroke=\"#F71963\"\n r=\"40\"\n strokeDasharray=\"60 900\"\n strokeWidth=\"12\"\n strokeLinecap=\"round\"\n className=\"build-status-rotate\"\n />\n </g>\n </svg>\n )\n\n public render() {\n const { status, animateOut, anchor, interrupted } = this.state\n\n if (status === null && interrupted === null) {\n return null\n }\n\n const className = `build-status ${status} z-max fixed animated pa3 bg-near-white br3 rebel-pink flex items-center shadow-4 ${\n animateOut ? 'fadeOut' : 'fadeIn'\n }`\n\n const message = interrupted\n ? 'Link interrupted'\n : status === 'fail'\n ? 'Oops! Build failed. Check your terminal for more information'\n : status === 'reload'\n ? 'Performing full reload'\n : null\n\n return (\n // eslint-disable-next-line jsx-a11y/mouse-events-have-key-events\n <div\n aria-hidden\n className={className}\n style={{\n top: '12px',\n [anchor]: '12px',\n animationDuration: '0.2s',\n opacity: 0.8,\n }}\n onMouseOver={this.handleMouseOver}\n >\n {message ? <p className=\"ma2\">{message}</p> : this.renderLoading()}\n </div>\n )\n }\n}\n\nexport default withRuntimeContext<{}>(BuildStatus)\n\n```"
}
] |
code_render-runtime_37487bea
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of render-runtime/react/components/withRuntimeContext.tsx from the render-runtime VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport { withRuntimeContext } from './RenderContext'\n\nexport default withRuntimeContext\n\n```"
}
] |
code_render-runtime_186b02e0
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of render-runtime/react/components/ErrorBoundary.tsx from the render-runtime VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React, { ErrorInfo, FunctionComponent } from 'react'\nimport ErrorDisplay from './ExtensionPoint/ErrorDisplay'\nimport { useRuntime } from './RenderContext'\nimport type { RenderContext } from './RenderContext'\nimport { isAdmin } from '../utils/isAdmin'\nimport { captureException } from '@sentry/react'\nimport { CustomAdminTags } from '../o11y/types'\nimport ErrorPage from './ErrorPage/ErrorPage'\n\ninterface Props {\n runtime: RenderContext\n}\n\nclass ErrorBoundary extends React.Component<Props> {\n public state = {\n error: undefined,\n errorInfo: undefined,\n }\n\n public componentDidCatch(error: Error, errorInfo: ErrorInfo) {\n this.setState({\n error,\n errorInfo,\n })\n\n if (!isAdmin()) return\n\n const tags: CustomAdminTags = {\n admin_render_runtime_page: 'ErrorBoundary',\n }\n\n captureException(this.state, { tags })\n }\n\n public render() {\n const { production } = this.props.runtime\n\n const { error, errorInfo } = this.state\n if (error) {\n if (!production) {\n return <ErrorDisplay error={error} errorInfo={errorInfo} />\n }\n\n if (isAdmin()) {\n return <ErrorPage />\n }\n\n return null\n }\n\n return this.props.children\n }\n}\n\nconst ErrorBoundaryWithContext: FunctionComponent = ({ children }) => {\n const runtime = useRuntime()\n\n return <ErrorBoundary runtime={runtime}>{children}</ErrorBoundary>\n}\n\nexport default ErrorBoundaryWithContext\n\nexport const withErrorBoundary = <P extends object>(\n Component: React.ComponentType<P>\n) => {\n const WithErrorBoundary = (props: P) => {\n const runtime = useRuntime()\n\n return (\n <ErrorBoundary runtime={runtime}>\n <Component {...props} />\n </ErrorBoundary>\n )\n }\n\n const displayName = Component.displayName || Component.name\n\n if (displayName) {\n WithErrorBoundary.displayName = `withErrorBoundary(${displayName})`\n }\n\n return WithErrorBoundary\n}\n\n```"
}
] |
code_render-runtime_81e3a825
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of render-runtime/react/components/LoadingContext.tsx from the render-runtime VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React, {\n useContext,\n useCallback,\n useMemo,\n useRef,\n ComponentType,\n FunctionComponent,\n useEffect,\n} from 'react'\nimport { canUseDOM } from 'exenv'\n\nimport GenericPreview from './Preview/GenericPreview'\n\ninterface LoadingContext {\n setLoading: (treePath: string, isLoading: boolean) => void\n isParentLoading?: boolean\n}\n\nconst LoadingContext = React.createContext<LoadingContext>({\n setLoading: () => {},\n isParentLoading: false,\n})\n\nLoadingContext.displayName = 'LoadingContext'\n\nconst LoadingContextProvider = LoadingContext.Provider\n\ninterface LoadingState {\n components: { [key: string]: boolean }\n}\n\nconst displayContent = (\n contentRef: React.RefObject<HTMLElement>,\n loaderRef: React.RefObject<HTMLElement>\n) => {\n if (contentRef.current) {\n contentRef.current.style.position = ''\n contentRef.current.style.width = ''\n contentRef.current.style.opacity = ''\n }\n if (loaderRef.current) {\n loaderRef.current.style.display = 'none'\n }\n}\n\nconst displayLoader = (\n contentRef: React.RefObject<HTMLElement>,\n loaderRef: React.RefObject<HTMLElement>\n) => {\n if (contentRef.current) {\n contentRef.current.style.position = 'absolute'\n contentRef.current.style.width = '100%'\n contentRef.current.style.opacity = '0'\n }\n if (loaderRef.current) {\n loaderRef.current.style.display = ''\n }\n}\n\n/** TODO: LoadingWrapper is in the end a makeshift Suspense.\n * Should probably be replaced in the future. */\nconst LoadingWrapper: FunctionComponent = ({ children }) => {\n /* Uses Ref instead of state to prevent rerenders */\n const state = useRef<LoadingState>({ components: {} })\n\n /* A parent component can include a LoadingContext to tell its\n * children that it is loading data. */\n const { isParentLoading } = useContext(LoadingContext)\n\n const contentContainer = useRef<HTMLDivElement>(null)\n const loaderContainer = useRef<HTMLDivElement>(null)\n\n const loadingTimeout = useRef<number | null>(null)\n const loadingComplete = useRef(false)\n\n const updateLoading = useCallback(() => {\n const areComponentsLoading = Object.values(state.current.components).some(\n Boolean\n )\n\n const isLoading = isParentLoading || areComponentsLoading\n\n if (!isLoading) {\n displayContent(contentContainer, loaderContainer)\n loadingComplete.current = true\n } else {\n if (!loadingComplete.current && loadingTimeout.current !== null) {\n window.clearTimeout(loadingTimeout.current)\n loadingTimeout.current = null\n }\n\n if (isParentLoading && loadingComplete.current) {\n loadingComplete.current = false\n displayLoader(contentContainer, loaderContainer)\n }\n }\n }, [isParentLoading])\n\n const setLoading = useCallback(\n (treePath, loading) => {\n if (loadingComplete.current) {\n return\n }\n\n state.current.components[treePath] = loading\n\n updateLoading()\n },\n [updateLoading]\n )\n\n useEffect(() => {\n updateLoading()\n }, [isParentLoading, updateLoading])\n\n const value = useMemo(\n () => ({\n setLoading,\n }),\n [setLoading]\n )\n\n const isSSR = !canUseDOM\n\n const returnValue = useMemo(\n () => (\n /** Renders both the content and the loader, and hides them via changing the\n * style via their refs. This is done for two reasons:\n * 1: to make the content execute its code while it is loading, because the\n * content can in turn require more components to be loaded, thus keeping\n * the loading state for longer.\n * 2: To prevent re-rendering when the loading state changes, which seemed\n * to cause some bugs. */\n <LoadingContextProvider value={value}>\n <div\n // Content container\n ref={contentContainer}\n suppressHydrationWarning\n style={{\n opacity: isSSR ? 1 : 0,\n position: isSSR ? 'unset' : 'absolute',\n width: isSSR ? 'unset' : '100%',\n }}\n >\n {children}\n </div>\n <div\n // Loader container\n ref={loaderContainer}\n suppressHydrationWarning\n style={{ display: isSSR ? 'none' : 'unset' }}\n >\n {/** TODO: Use a better preview in the future */}\n <GenericPreview />\n </div>\n </LoadingContextProvider>\n ),\n [children, isSSR, value]\n )\n\n return returnValue\n}\n\nconst useLoadingContext = () => {\n return useContext(LoadingContext)\n}\n\nconst withLoading = <T extends {}>(Component: ComponentType<T>) => {\n const EnhancedComponent: FunctionComponent<T> = (props) => {\n const isSSR = !canUseDOM\n const { setLoading } = useLoadingContext()\n\n if (isSSR) {\n return <Component {...props} setLoading={() => {}} />\n }\n\n return <Component {...props} setLoading={setLoading} />\n }\n\n EnhancedComponent.displayName = `WithLoading(${\n Component.displayName || Component.name || 'Component'\n })`\n\n return EnhancedComponent\n}\n\nexport {\n LoadingWrapper,\n useLoadingContext,\n withLoading,\n LoadingContextProvider,\n}\n\n```"
}
] |
code_render-runtime_2665ad06
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of render-runtime/react/o11y/ctx.ts from the render-runtime VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { AdminTags } from './types'\n\ninterface RuntimeInfo {\n account: string | null\n workspace: string | null\n route: { path: string | null; blockId: string | null }\n culture: { locale: string | null }\n production: boolean | null\n loadedDevices: Array<string | null>\n}\n\n/**\n * Infer the runtime information from the window.location object.\n */\nexport function inferRuntimeInfo(): Partial<RuntimeInfo> {\n const { host = '' } = window.location\n let account = ''\n let workspace = ''\n\n if (!host.includes('--')) {\n account = host.split('.')[0]\n workspace = 'master'\n } else {\n workspace = host.split('--')[0]\n account = host.split('--')[1].split('.')[0]\n }\n\n const { pathname } = window.location\n\n const locale =\n navigator?.language ?? Intl.DateTimeFormat().resolvedOptions().locale\n\n return {\n account,\n workspace,\n route: { path: pathname, blockId: null },\n culture: { locale },\n }\n}\n\n/**\n * Gets the Runtime information from the global __RUNTIME__ object\n * injected by Render Server, if available, otherwise infer the runtime\n * information from the window.location.\n */\nexport function getRuntimeInfo(): RuntimeInfo & { runtimeAvailable: boolean } {\n const runtime = window?.__RUNTIME__ ?? inferRuntimeInfo()\n\n const {\n account = null,\n workspace = null,\n culture: { locale } = { locale: null },\n route: { path, blockId } = { path: null, blockId: null },\n loadedDevices = null,\n production = null,\n } = runtime\n\n return {\n account,\n workspace,\n culture: { locale },\n route: { path, blockId },\n loadedDevices,\n production,\n runtimeAvailable: !!window?.__RUNTIME__,\n }\n}\n\n/**\n * Retrieves VTEX IO context and adapt it to format expected\n * by Sentry for the Admin.\n */\nexport function getIOContext(): AdminTags {\n const runtime = window?.__RUNTIME__ ?? inferRuntimeInfo()\n\n const {\n account = null,\n workspace = null,\n culture: { locale } = { locale: null },\n route: { path, blockId } = { path: null, blockId: null },\n loadedDevices = null,\n production = null,\n } = runtime\n\n return {\n admin_account: account,\n admin_workspace: workspace,\n admin_locale: locale,\n admin_path: path,\n admin_app_block: blockId, // ex. \"vtex.admin-home@3.x:admin.app.home\"\n admin_device: Array.isArray(loadedDevices)\n ? loadedDevices[0]\n : loadedDevices,\n admin_production: production,\n admin_runtime_available: !!window?.__RUNTIME__,\n }\n}\n\n```"
}
] |
code_render-runtime_dc18191c
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of render-runtime/react/o11y/extractExtra.ts from the render-runtime VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\n/**\n * This method extracts keys from objects iteratively\n * and adpat them to the format required by Sentry to log\n * events from the Admin by following our conventions.\n *\n * Sentry doesn't log all the keys from an object\n * when an error is captured, so we need to extract\n * the keys and values from the error object and\n * adapt them to the format required by Sentry ourselves\n * in order to make them indexable and searchable.\n *\n * This helps us aggregate and filter errors in Sentry by\n * dynamically generating keys.\n */\nexport function extractExtra(err: any) {\n try {\n const extra: any = {}\n\n return iterate(err, extra, 0, new Set())\n } catch (error) {\n return {}\n }\n}\n\n/**\n * This function is recursive and will iterate over the\n * object's keys and values to extract them and adapt\n * them to the format required by Sentry.\n */\nfunction iterate(\n err: any,\n extra: any,\n iterationNumber: number,\n seen: Set<any>\n) {\n if (typeof err === 'object') {\n // We don't want to rely on the browser's ability\n // to handle memory leaks when dealing with circular\n // references, so we need to keep track of the keys\n // we've already seen to avoid infinite loops.\n if (seen.has(err)) {\n throw new Error('Circular reference detected')\n }\n seen.add(err)\n\n for (const key in err) {\n if (typeof err[key] === 'object') {\n const updatedExtra = iterate(err[key], extra, iterationNumber + 1, seen)\n extra = { ...extra, ...updatedExtra }\n } else {\n if (typeof err[key] !== 'function') {\n const value = err[key]\n const tagKey = `admin_extra_${standardizeKey(key)}${iterationNumber}`\n\n if (tagKey.length >= 32) {\n // Skip. Sentry doesn't allow keys longer than 32 characters.\n // The keys that matter the most are shortened on the standardizeKey function.\n continue\n }\n\n // Split values that are too long into as many parts as necessary to fit\n // Sentry's limit of 200 characters per value\n if (value.length >= 200) {\n const chunks = []\n for (let chunk = 0; chunk < value.length; chunk += 199) {\n chunks.push(value.substr(chunk, 199))\n }\n\n for (let chunk = 0; chunk < chunks.length; chunk++) {\n extra[`${tagKey}_` + chunk] = chunks[chunk]\n }\n } else {\n extra[tagKey] = value\n }\n }\n }\n\n seen.delete(err)\n }\n } else {\n return err\n }\n\n return extra\n}\n\n/**\n * This function standardizes the keys extracted from the error object\n * to the format required by Sentry (snake_case, lowercase, short).\n */\nfunction standardizeKey(str: string) {\n return str\n .replace(/-/g, '_')\n .toLowerCase()\n .trim()\n .replace('graphql', 'gql')\n .replace('message', 'msg')\n .replace('request', 'req')\n .replace('response', 'res')\n .replace('isaxioserror', 'axios')\n}\n\n```"
}
] |
code_render-runtime_89c6c436
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of render-runtime/react/o11y/instrument.ts from the render-runtime VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport * as Sentry from '@sentry/react'\nimport { isAdmin } from '../utils/isAdmin'\nimport { getIOContext } from './ctx'\n\nif (isAdmin()) {\n Sentry.init({\n dsn:\n 'https://2fac72ea180d48ae9bf1dbb3104b4000@o191317.ingest.us.sentry.io/1292015',\n integrations: [Sentry.replayIntegration()],\n\n // Set tracesSampleRate to 0.1 to capture 10%\n // of transactions for tracing.\n tracesSampleRate: 0.1,\n\n // Set `tracePropagationTargets` to control for which URLs trace propagation should be enabled\n tracePropagationTargets: [\n /^\\//,\n /^(https?:\\/\\/)?([a-z0-9]+[.])*myvtex\\.com/,\n ],\n\n // Capture Replay for 0% of all sessions,\n // plus for 50% of sessions with an error\n replaysSessionSampleRate: 0,\n replaysOnErrorSampleRate: 0.5,\n\n beforeSend: (event) => {\n const ctx = getIOContext()\n\n // Must check with false, otherwise default null's\n // value leads to data mistakenly not sent to Sentry,\n // which can occur if somehow we can't infer whether\n // the apps are running under a production or development\n // environment.\n if (ctx.admin_production === false) {\n const params = new URL(document?.location?.toString())?.searchParams\n const shouldLog = params.get('forceLogs')\n\n if (shouldLog === 'true') {\n return makeEventWithCtx(event, ctx)\n }\n\n return null\n }\n\n return makeEventWithCtx(event, ctx)\n },\n })\n}\n\nfunction makeEventWithCtx(event: any, ctx: any) {\n const eventWithCtx = {\n ...event,\n tags: {\n ...event?.tags,\n ...ctx,\n },\n }\n\n return eventWithCtx\n}\n\n```"
}
] |
code_render-runtime_de262b38
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of render-runtime/react/o11y/extractExtra.test.ts from the render-runtime VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { extractExtra } from './extractExtra'\n\ndescribe('extractExtra', () => {\n test('should return an empty object when err is an empty object', () => {\n const err = {}\n const result = extractExtra(err)\n expect(result).toEqual({})\n })\n\n test('should extract simple key-value pairs', () => {\n const err = { a: 'value1', b: 'value2' }\n const result = extractExtra(err)\n expect(result).toEqual({\n admin_extra_a0: 'value1',\n admin_extra_b0: 'value2',\n })\n })\n\n test('should extract nested objects', () => {\n const err = {\n a: 'value1',\n nested: {\n b: 'value2',\n deeper: {\n c: 'value3',\n },\n },\n }\n const result = extractExtra(err)\n expect(result).toEqual({\n admin_extra_a0: 'value1',\n admin_extra_b1: 'value2',\n admin_extra_c2: 'value3',\n })\n })\n\n test('should ignore functions', () => {\n const err = {\n a: 'value1',\n func: () => {},\n }\n const result = extractExtra(err)\n expect(result).toEqual({\n admin_extra_a0: 'value1',\n })\n })\n\n test('high fidelity example #1', () => {\n const err = {\n details: {\n graphQLErrors: '[Array]',\n message: 'messages',\n name: 'Error',\n stack:\n 'Error: messages\\n at throwOnGraphQLErrors (/usr/local/app/node_modules/@vtex/api/lib/HttpClient/GraphQLClient.js:10:15)\\n at /usr/local/app/node_modules/@vtex/api/lib/HttpClient/GraphQLClient.js:23:15\\n at runMicrotasks (<anonymous>)\\n at processTicksAndRejections (node:internal/process/task_queues:96:5)\\n at MessagesGraphQL.translateWithDependencies (/usr/local/app/node_modules/@vtex/api/lib/clients/apps/MessagesGraphQL.js:66:26)\\n at dataloader_1.default.batch (/usr/local/app/node_modules/@vtex/api/lib/service/worker/runtime/graphql/schema/messagesLoaderV2.js:68:15)',\n },\n stack:\n 'Error: messages\\n at throwOnGraphQLErrors (/usr/local/app/node_modules/@vtex/api/lib/HttpClient/GraphQLClient.js:10:15)\\n at /usr/local/app/node_modules/@vtex/api/lib/HttpClient/GraphQLClient.js:23:15\\n at runMicrotasks (<anonymous>)\\n at processTicksAndRejections (node:internal/process/task_queues:96:5)\\n at MessagesGraphQL.translateWithDependencies (/usr/local/app/node_modules/@vtex/api/lib/clients/apps/MessagesGraphQL.js:66:26)\\n at dataloader_1.default.batch (/usr/local/app/node_modules/@vtex/api/lib/service/worker/runtime/graphql/schema/messagesLoaderV2.js:68:15)',\n }\n\n const result = extractExtra(err)\n expect(result).toEqual({\n admin_extra_gqlerrors1: '[Array]',\n admin_extra_msg1: 'messages',\n admin_extra_name1: 'Error',\n admin_extra_stack0_0:\n 'Error: messages\\n at throwOnGraphQLErrors (/usr/local/app/node_modules/@vtex/api/lib/HttpClient/GraphQLClient.js:10:15)\\n at /usr/local/app/node_modules/@vtex/api/lib/HttpClient/GraphQLClient.js:',\n admin_extra_stack0_1:\n '23:15\\n at runMicrotasks (<anonymous>)\\n at processTicksAndRejections (node:internal/process/task_queues:96:5)\\n at MessagesGraphQL.translateWithDependencies (/usr/local/app/node_modules/@vtex/',\n admin_extra_stack0_2:\n 'api/lib/clients/apps/MessagesGraphQL.js:66:26)\\n at dataloader_1.default.batch (/usr/local/app/node_modules/@vtex/api/lib/service/worker/runtime/graphql/schema/messagesLoaderV2.js:68:15)',\n admin_extra_stack1_0:\n 'Error: messages\\n at throwOnGraphQLErrors (/usr/local/app/node_modules/@vtex/api/lib/HttpClient/GraphQLClient.js:10:15)\\n at /usr/local/app/node_modules/@vtex/api/lib/HttpClient/GraphQLClient.js:',\n admin_extra_stack1_1:\n '23:15\\n at runMicrotasks (<anonymous>)\\n at processTicksAndRejections (node:internal/process/task_queues:96:5)\\n at MessagesGraphQL.translateWithDependencies (/usr/local/app/node_modules/@vtex/',\n admin_extra_stack1_2:\n 'api/lib/clients/apps/MessagesGraphQL.js:66:26)\\n at dataloader_1.default.batch (/usr/local/app/node_modules/@vtex/api/lib/service/worker/runtime/graphql/schema/messagesLoaderV2.js:68:15)',\n })\n })\n\n test('high fidelity example #2', () => {\n const err = {\n details: {\n code: 'ECONNABORTED',\n config: '[Object]',\n isAxiosError: true,\n message: 'timeout of 4000ms exceeded',\n name: 'Error',\n request: '[Object]',\n stack:\n 'Error: timeout of 4000ms exceeded\\n at createError (/usr/local/app/node_modules/axios/lib/core/createError.js:16:15)\\n at ClientRequest.handleRequestTimeout (/usr/local/app/node_modules/axios/lib/adapters/http.js:280:16)\\n at Object.onceWrapper (node:events:627:28)\\n at ClientRequest.emit (node:events:513:28)\\n at Socket.emitRequestTimeout (node:_http_client:839:9)\\n at Object.onceWrapper (node:events:627:28)\\n at Socket.emit (node:events:525:35)\\n at Socket._onTimeout (node:net:550:8)\\n at listOnTimeout (node:internal/timers:559:17)\\n at processTimers (node:internal/timers:502:7)',\n },\n stack:\n 'Error: timeout of 4000ms exceeded\\n at createError (/usr/local/app/node_modules/axios/lib/core/createError.js:16:15)\\n at ClientRequest.handleRequestTimeout (/usr/local/app/node_modules/axios/lib/adapters/http.js:280:16)\\n at Object.onceWrapper (node:events:627:28)\\n at ClientRequest.emit (node:events:513:28)\\n at Socket.emitRequestTimeout (node:_http_client:839:9)\\n at Object.onceWrapper (node:events:627:28)\\n at Socket.emit (node:events:525:35)\\n at Socket._onTimeout (node:net:550:8)\\n at listOnTimeout (node:internal/timers:559:17)\\n at processTimers (node:internal/timers:502:7)',\n }\n const result = extractExtra(err)\n expect(result).toEqual({\n admin_extra_code1: 'ECONNABORTED',\n admin_extra_axios1: true,\n admin_extra_msg1: 'timeout of 4000ms exceeded',\n admin_extra_name1: 'Error',\n admin_extra_req1: '[Object]',\n admin_extra_config1: '[Object]',\n admin_extra_stack0_0:\n 'Error: timeout of 4000ms exceeded\\n at createError (/usr/local/app/node_modules/axios/lib/core/createError.js:16:15)\\n at ClientRequest.handleRequestTimeout (/usr/local/app/node_modules/axios/lib',\n admin_extra_stack0_1:\n '/adapters/http.js:280:16)\\n at Object.onceWrapper (node:events:627:28)\\n at ClientRequest.emit (node:events:513:28)\\n at Socket.emitRequestTimeout (node:_http_client:839:9)\\n at Object.onceWr',\n admin_extra_stack0_2:\n 'apper (node:events:627:28)\\n at Socket.emit (node:events:525:35)\\n at Socket._onTimeout (node:net:550:8)\\n at listOnTimeout (node:internal/timers:559:17)\\n at processTimers (node:internal/tim',\n admin_extra_stack0_3: 'ers:502:7)',\n admin_extra_stack1_0:\n 'Error: timeout of 4000ms exceeded\\n at createError (/usr/local/app/node_modules/axios/lib/core/createError.js:16:15)\\n at ClientRequest.handleRequestTimeout (/usr/local/app/node_modules/axios/lib',\n admin_extra_stack1_1:\n '/adapters/http.js:280:16)\\n at Object.onceWrapper (node:events:627:28)\\n at ClientRequest.emit (node:events:513:28)\\n at Socket.emitRequestTimeout (node:_http_client:839:9)\\n at Object.onceWr',\n admin_extra_stack1_2:\n 'apper (node:events:627:28)\\n at Socket.emit (node:events:525:35)\\n at Socket._onTimeout (node:net:550:8)\\n at listOnTimeout (node:internal/timers:559:17)\\n at processTimers (node:internal/tim',\n admin_extra_stack1_3: 'ers:502:7)',\n })\n })\n\n test('high fidelity example #3', () => {\n const err = {\n details: {\n code: 'E_HTTP_500',\n config: '[Object]',\n isAxiosError: true,\n message: 'Request failed with status code 500',\n name: 'Error',\n request: '[Object]',\n response: '[Object]',\n stack:\n 'Error: Request failed with status code 500\\n at createError (/usr/local/app/node_modules/axios/lib/core/createError.js:16:15)\\n at settle (/usr/local/app/node_modules/axios/lib/core/settle.js:17:12)\\n at IncomingMessage.handleStreamEnd (/usr/local/app/node_modules/axios/lib/adapters/http.js:260:11)\\n at IncomingMessage.emit (node:events:525:35)\\n at endReadableNT (node:internal/streams/readable:1358:12)\\n at processTicksAndRejections (node:internal/process/task_queues:83:21)',\n },\n stack:\n 'Error: Request failed with status code 500\\n at createError (/usr/local/app/node_modules/axios/lib/core/createError.js:16:15)\\n at settle (/usr/local/app/node_modules/axios/lib/core/settle.js:17:12)\\n at IncomingMessage.handleStreamEnd (/usr/local/app/node_modules/axios/lib/adapters/http.js:260:11)\\n at IncomingMessage.emit (node:events:525:35)\\n at endReadableNT (node:internal/streams/readable:1358:12)\\n at processTicksAndRejections (node:internal/process/task_queues:83:21)',\n }\n\n const result = extractExtra(err)\n expect(result).toEqual({\n admin_extra_code1: 'E_HTTP_500',\n admin_extra_axios1: true,\n admin_extra_msg1: 'Request failed with status code 500',\n admin_extra_name1: 'Error',\n admin_extra_req1: '[Object]',\n admin_extra_res1: '[Object]',\n admin_extra_config1: '[Object]',\n admin_extra_stack0_0:\n 'Error: Request failed with status code 500\\n at createError (/usr/local/app/node_modules/axios/lib/core/createError.js:16:15)\\n at settle (/usr/local/app/node_modules/axios/lib/core/settle.js:17:',\n admin_extra_stack0_1:\n '12)\\n at IncomingMessage.handleStreamEnd (/usr/local/app/node_modules/axios/lib/adapters/http.js:260:11)\\n at IncomingMessage.emit (node:events:525:35)\\n at endReadableNT (node:internal/streams',\n admin_extra_stack0_2:\n '/readable:1358:12)\\n at processTicksAndRejections (node:internal/process/task_queues:83:21)',\n\n admin_extra_stack1_0:\n 'Error: Request failed with status code 500\\n at createError (/usr/local/app/node_modules/axios/lib/core/createError.js:16:15)\\n at settle (/usr/local/app/node_modules/axios/lib/core/settle.js:17:',\n admin_extra_stack1_1:\n '12)\\n at IncomingMessage.handleStreamEnd (/usr/local/app/node_modules/axios/lib/adapters/http.js:260:11)\\n at IncomingMessage.emit (node:events:525:35)\\n at endReadableNT (node:internal/streams',\n admin_extra_stack1_2:\n '/readable:1358:12)\\n at processTicksAndRejections (node:internal/process/task_queues:83:21)',\n })\n })\n\n test('should return the original input when it is not an object (string)', () => {\n const err = 'error'\n const result = extractExtra(err)\n expect(result).toEqual(err)\n })\n\n test('should return the original input when it is not an object (boolean)', () => {\n const err = false\n const result = extractExtra(err)\n expect(result).toEqual(err)\n })\n\n test('should return the original input when it is not an object (undefined)', () => {\n const result = extractExtra(undefined)\n expect(result).toEqual(undefined)\n })\n\n test('circular references given as input returns an empty object', () => {\n class Validator {\n model: any\n\n constructor(model: any) {\n this.model = model\n }\n }\n\n class Model {\n _attributes: any\n validator: any\n\n constructor() {\n this._attributes = {}\n this.validator = new Validator(this)\n }\n }\n\n const model = new Model()\n\n const result = extractExtra(model)\n expect(result).toEqual({})\n })\n\n test('should not grab 32+ character key-value pairs', () => {\n const err = {\n superlongkeythathasmorethanthirtytwocharacters: 'value1',\n b: 'value2',\n nested: {\n c: 'value3',\n anothersuperlongkeythathasmorethanthirtytwocharacters: 'value4',\n },\n }\n const result = extractExtra(err)\n expect(result).toEqual({\n admin_extra_b0: 'value2',\n admin_extra_c1: 'value3',\n })\n })\n})\n\n```"
}
] |
code_render-runtime_39e32012
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of render-runtime/react/o11y/types.ts from the render-runtime VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\n/**\n * Custom Admin tags logged by the Sentry SDK.\n */\nexport type CustomAdminTags = Record<string, any> & {\n /**\n * The Render Runtime page component that rendered an error.\n */\n admin_render_runtime_page: 'ErrorPage' | 'ErrorBoundary'\n}\n\n/**\n * Default Admin tags logged by the Sentry SDK.\n */\nexport interface AdminTags {\n /**\n * Account running the app.\n */\n admin_account: string\n /**\n * Workspace running the app.\n */\n admin_workspace: string\n /**\n * Locale running the app.\n */\n admin_locale: string\n /**\n * Path of the app.\n */\n admin_path: string\n /**\n * Block ID of the app.\n *\n * @example\n * \"vtex.admin-home@3.x:admin.app.home\"\n */\n admin_app_block: string\n /**\n * Device running the app.\n *\n * @example\n * [\"desktop\", \"tablet\"]\n */\n admin_device: string\n /**\n * Whether the app is running in production.\n * The values from this variable logged to\n * Sentry are always true OR null; never false.\n */\n admin_production: boolean\n /**\n * Whether the runtime information from the\n * global __RUNTIME__ object is available or not.\n */\n admin_runtime_available: boolean\n}\n\n```"
}
] |
code_render-runtime_6aa7335f
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of render-runtime/react/__tests__/LRUCache.test.ts from the render-runtime VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport LRU from '../components/Prefetch/LRUCache'\n\nconst sleep = (time: number) =>\n new Promise((resolve) => setTimeout(resolve, time))\n\ntest('get and set works', () => {\n const lru = new LRU({ max: 1 })\n const a = 1\n lru.set('a', a)\n expect(lru.get('a')).toBe(a)\n})\n\ntest('max options works', () => {\n const lru = new LRU({ max: 2 })\n const a = 1\n const b = 2\n lru.set('a', a)\n lru.set('b', b)\n expect(lru.get('a')).toBe(a)\n const c = 3\n lru.set('c', c)\n expect(lru.get('a')).toBe(a)\n expect(lru.get('c')).toBe(c)\n expect(lru.get('b')).toBe(undefined)\n})\n\ntest('maxSize options works', () => {\n const lru = new LRU({ maxSize: 2 })\n const a = 1\n const b = 2\n lru.set('a', a)\n lru.set('b', b)\n expect(lru.get('a')).toBe(a)\n const c = 3\n lru.set('c', c)\n expect(lru.get('a')).toBe(a)\n expect(lru.get('c')).toBe(c)\n expect(lru.get('b')).toBe(undefined)\n})\n\ntest('will remove the key in tail', () => {\n const lru = new LRU({ max: 3 })\n const a = 1\n const b = 2\n const c = 3\n const d = 4\n lru.set('a', a)\n lru.set('b', b)\n lru.set('c', c)\n lru.get('a')\n lru.get('b')\n lru.get('a')\n lru.get('c')\n lru.get('a')\n // cache is now a - c - b, b in tail\n\n lru.set('d', d)\n\n expect(lru.get('a')).toBe(a)\n expect(lru.get('c')).toBe(c)\n expect(lru.get('d')).toBe(d)\n expect(lru.get('b')).toBe(undefined)\n})\n\ntest('dispose function is called when key is removed', () => {\n const dispose = jest.fn()\n const lru = new LRU({ max: 2, disposeFn: dispose })\n const a = 1\n const b = 2\n lru.set('a', a)\n lru.set('b', b)\n expect(lru.get('a')).toBe(a)\n const c = 3\n lru.set('c', c)\n\n expect(dispose).toBeCalledTimes(1)\n expect(dispose).toBeCalledWith('b')\n dispose.mockClear()\n lru.get('c')\n lru.get('c')\n lru.set('d', 4)\n expect(dispose).toBeCalledTimes(1)\n expect(dispose).toBeCalledWith('a')\n})\n\ntest('max age parameter works', async () => {\n const dispose = jest.fn()\n const lru = new LRU({ max: 3, maxAge: 500, disposeFn: dispose })\n const a = 1\n const b = 2\n const c = 3\n lru.set('a', a)\n lru.set('b', b)\n\n await sleep(200)\n expect(lru.get('a')).toBe(a)\n expect(lru.get('b')).toBe(b)\n lru.set('c', c)\n\n await sleep(400)\n expect(lru.get('a')).toBe(undefined)\n expect(lru.get('b')).toBe(undefined)\n expect(lru.get('c')).toBe(c)\n\n expect(dispose).toBeCalledTimes(2)\n expect(dispose).toHaveBeenNthCalledWith(1, 'a')\n expect(dispose).toHaveBeenNthCalledWith(2, 'b')\n})\n\n```"
}
] |
code_render-runtime_de21e0d4
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of render-runtime/react/__tests__/PQueue.test.ts from the render-runtime VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport PQueue from '../components/Prefetch/PQueue'\n\nconst sleep = (time: number) =>\n new Promise((resolve) => setTimeout(resolve, time))\n\nbeforeEach(() => {\n jest.resetAllMocks()\n})\nit('should start all promises', async () => {\n const mockFn = jest.fn()\n const myPromiseFn = () =>\n new Promise(async (resolve) => {\n await sleep(100)\n mockFn()\n resolve()\n })\n\n const queue = new PQueue({})\n queue.add(myPromiseFn)\n queue.add(myPromiseFn)\n queue.add(myPromiseFn)\n\n await sleep(500)\n expect(mockFn).toBeCalledTimes(3)\n})\n\nit('should respect the maximum concurrency', async () => {\n const mockFn = jest.fn()\n const myPromiseFn = () =>\n new Promise(async (resolve) => {\n await sleep(500)\n mockFn()\n resolve()\n })\n\n const queue = new PQueue({ concurrency: 2 })\n queue.add(myPromiseFn)\n queue.add(myPromiseFn)\n queue.add(myPromiseFn)\n queue.add(myPromiseFn)\n queue.add(myPromiseFn)\n\n await sleep(700)\n expect(mockFn).toBeCalledTimes(2)\n\n await sleep(400)\n expect(mockFn).toBeCalledTimes(4)\n})\n\nit('should add with priority', async () => {\n const counters = [0, 0, 0, 0, 0]\n const myPromiseFn = (count: number) =>\n new Promise(async (resolve) => {\n await sleep(300)\n counters[count]++\n resolve()\n })\n\n const queue = new PQueue({ concurrency: 2, autoStart: false })\n queue.add(() => myPromiseFn(0))\n queue.add(() => myPromiseFn(1), { priority: 1 })\n queue.add(() => myPromiseFn(2), { priority: 2 })\n queue.add(() => myPromiseFn(3), { priority: 3 })\n\n queue.start()\n await sleep(100)\n\n queue.add(() => myPromiseFn(4), { priority: 4 })\n queue.add(() => myPromiseFn(3), { priority: 3 })\n queue.add(() => myPromiseFn(0), { priority: 0 })\n await sleep(250)\n\n // Should have resolved the two promises with high priorities\n expect(counters).toStrictEqual([0, 0, 1, 1, 0])\n await sleep(300)\n // Should have resolved the two promises with higher priorities at the moment (4 and 3)\n expect(counters).toStrictEqual([0, 0, 1, 2, 1])\n\n await sleep(600)\n // All of them should have resolved\n expect(counters).toStrictEqual([2, 1, 1, 2, 1])\n})\n\nit('should respect autoStart false argument', async () => {\n const mockFn = jest.fn()\n const mockPriorityFn = jest.fn()\n const myPromiseFn = () =>\n new Promise(async (resolve) => {\n await sleep(100)\n mockFn()\n resolve()\n })\n\n const myPromisePriorityFn = () =>\n new Promise(async (resolve) => {\n await sleep(100)\n mockPriorityFn()\n resolve()\n })\n\n const queue = new PQueue({ autoStart: false })\n\n queue.add(myPromiseFn)\n queue.add(myPromiseFn)\n queue.add(myPromisePriorityFn, { priority: 1 })\n queue.add(myPromiseFn)\n queue.add(myPromiseFn)\n await sleep(200)\n expect(mockFn).toBeCalledTimes(0)\n expect(mockPriorityFn).toBeCalledTimes(0)\n\n queue.start()\n await sleep(800)\n expect(mockFn).toBeCalledTimes(4)\n expect(mockPriorityFn).toBeCalledTimes(1)\n})\n\nit('pause method should freeze queue', async () => {\n const mockFn = jest.fn()\n const myPromiseFn = () =>\n new Promise(async (resolve) => {\n await sleep(200)\n mockFn()\n resolve()\n })\n\n const queue = new PQueue({})\n\n queue.add(myPromiseFn)\n queue.add(myPromiseFn)\n\n queue.pause()\n\n queue.add(myPromiseFn)\n queue.add(myPromiseFn)\n\n await sleep(300)\n expect(mockFn).toBeCalledTimes(2)\n\n queue.start()\n await sleep(300)\n expect(mockFn).toBeCalledTimes(4)\n})\n\nit('clear method should empty the queue', async () => {\n const mockBeforeFn = jest.fn()\n const mockAfterFn = jest.fn()\n const myPromiseBeforeFn = () =>\n new Promise(async (resolve) => {\n await sleep(200)\n mockBeforeFn()\n resolve()\n })\n\n const myPromiseAfterFn = () =>\n new Promise(async (resolve) => {\n await sleep(200)\n mockAfterFn()\n resolve()\n })\n\n const queue = new PQueue({ autoStart: false })\n\n queue.add(myPromiseBeforeFn)\n queue.add(myPromiseBeforeFn)\n\n queue.clear()\n\n queue.add(myPromiseAfterFn)\n queue.add(myPromiseAfterFn)\n queue.start()\n\n await sleep(300)\n expect(mockBeforeFn).toBeCalledTimes(0)\n expect(mockAfterFn).toBeCalledTimes(2)\n})\n\n```"
}
] |
code_render-runtime_eed7ce9a
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of render-runtime/react/__tests__/RenderProvider.test.tsx from the render-runtime VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React, { useEffect } from 'react'\nimport RenderProvider from '../components/RenderProvider'\nimport { useRuntime } from '../components/RenderContext'\nimport { render, wait } from '@vtex/test-tools/react'\n\nconst renderFakeProvider = ({ children }: { children: JSX.Element }) => {\n window.fetch = () => Promise.resolve({} as Response)\n window.__RENDER_8_SESSION__ = {\n sessionPromise: Promise.resolve(),\n patchSession: () => Promise.resolve(),\n }\n\n const props = {\n runtime: {\n account: 'vtex',\n amp: false,\n emitter: {\n addListener: () => {},\n removeListener: () => {},\n },\n production: false,\n route: {\n canonicalPath: '',\n },\n culture: {\n locale: 'en-US',\n },\n components: {},\n blocks: {},\n pages: {\n page: {\n path: 'page/:id',\n },\n },\n hints: {\n mobile: false,\n desktop: true,\n tablet: false,\n phone: false,\n unknown: false,\n },\n },\n history: {\n location: {\n search: '',\n pathname: '',\n },\n replace: () => {},\n push: () => {},\n listen: () => {},\n },\n }\n return render(<RenderProvider {...(props as any)}>{children}</RenderProvider>)\n}\n\nit('if child component calls navigate, should return true', async () => {\n let navigateResult = false\n const Child = () => {\n const { navigate } = useRuntime()\n useEffect(() => {\n navigateResult = navigate({ to: 'product' })\n }, [navigate])\n return <div>children</div>\n }\n renderFakeProvider({ children: <Child /> })\n await wait()\n expect(navigateResult).toBe(true)\n})\n\nit('Calling navigates one after another with same payload, will make second one return false', async () => {\n let navigateResultFirst = undefined\n let navigateResultSecond = undefined\n const Child = () => {\n const { navigate } = useRuntime()\n useEffect(() => {\n navigateResultFirst = navigate({ to: 'product' })\n navigateResultSecond = navigate({ to: 'product' })\n }, [navigate])\n return <div>children</div>\n }\n renderFakeProvider({ children: <Child /> })\n await wait()\n expect(navigateResultFirst).toBe(true)\n expect(navigateResultSecond).toBe(false)\n})\n\nit('Calling navigates one after another with different payload, will make second one return true also', async () => {\n let navigateResultFirst = undefined\n let navigateResultSecond = undefined\n const Child = () => {\n const { navigate } = useRuntime()\n useEffect(() => {\n navigateResultFirst = navigate({ to: 'product' })\n navigateResultSecond = navigate({ to: 'other-product' })\n }, [navigate])\n return <div>children</div>\n }\n renderFakeProvider({ children: <Child /> })\n await wait()\n expect(navigateResultFirst).toBe(true)\n expect(navigateResultSecond).toBe(true)\n})\n\nconst input: [any, any, any][] = [\n [\n { to: 'product', params: { id: 'a' } },\n { to: 'product', params: { id: 'a' } },\n false,\n ],\n [\n { to: 'product', params: { id: 'a' } },\n { to: 'product2', params: { id: 'a' } },\n true,\n ],\n [\n { to: 'product', params: { id: 'a' } },\n { to: 'product', params: { id: 'a', rest: 'b' } },\n true,\n ],\n [\n { page: 'page', params: { id: 'a' } },\n { page: 'page', params: { id: 'a' } },\n false,\n ],\n [\n { page: 'page', params: { id: 'a' } },\n { page: 'page', params: { id: 'b' } },\n true,\n ],\n]\n\nit.each(input)(\n 'test if navigation is properly exiting early based on different repeated input',\n async (arg1: any, arg2: any, expected: boolean) => {\n let navigateResultFirst = undefined\n let navigateResultSecond = undefined\n const Child = () => {\n const { navigate } = useRuntime()\n useEffect(() => {\n navigateResultFirst = navigate(arg1)\n navigateResultSecond = navigate(arg2)\n }, [navigate])\n return <div>children</div>\n }\n renderFakeProvider({ children: <Child /> })\n await wait()\n expect(navigateResultFirst).toBe(true)\n expect(navigateResultSecond).toBe(expected)\n }\n)\n\n```"
}
] |
code_render-runtime_69066b9d
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of render-runtime/react/hooks/viewDetection.tsx from the render-runtime VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport { useEffect, useRef, MutableRefObject } from 'react'\n\ninterface IntersectionEvent {\n entry: IntersectionObserverEntry\n unobserve: () => void\n}\n\ninterface HookOptions {\n ref: MutableRefObject<HTMLElement | null>\n onView?: (event: IntersectionEvent) => any\n threshold?: number\n once?: boolean\n bailOut?: boolean\n initializeOnInteraction?: boolean\n}\n\n/** Hook for detecting when an element is inside the viewport.\n * Differs from react-intersection-observer (https://www.npmjs.com/package/react-intersection-observer)\n * in that this hook doesn't use setState, using a callback approach instead, to improve\n * performance by preventing re-rendering.\n */\nconst useOnView = ({\n ref,\n onView,\n threshold = 0,\n once = false,\n bailOut = false,\n initializeOnInteraction = false,\n}: HookOptions) => {\n const isObserving = useRef(false)\n const didIntersect = useRef(false)\n\n useEffect(() => {\n const initializeObserver = () => {\n const element = ref.current\n\n if (\n bailOut ||\n isObserving.current ||\n !element ||\n !onView ||\n (once && didIntersect.current)\n ) {\n return () => {}\n }\n\n isObserving.current = true\n\n const unobserve = () => {\n if (isObserving.current) {\n observer.unobserve(element)\n isObserving.current = false\n }\n }\n\n const observer = new IntersectionObserver(([entry]) => {\n if (!entry.isIntersecting) {\n return\n }\n\n if (entry.intersectionRatio < threshold) {\n return\n }\n\n if (once) {\n unobserve()\n }\n\n didIntersect.current = true\n onView({ entry, unobserve })\n })\n\n observer.observe(element)\n\n return unobserve\n }\n\n if (initializeOnInteraction) {\n const cleanUpEvents = () => {\n window?.document?.removeEventListener('scroll', handleInteraction)\n window?.document?.removeEventListener('mouseover', handleInteraction)\n }\n\n let unobserve = () => {\n cleanUpEvents()\n }\n\n const handleInteraction = () => {\n cleanUpEvents()\n unobserve = initializeObserver()\n }\n\n window?.document?.addEventListener('scroll', handleInteraction)\n window?.document?.addEventListener('mouseover', handleInteraction)\n\n /** Triggers interaction event if the user has scrolled the\n * page before JS being initialized */\n if (window?.scrollY > 0) {\n handleInteraction()\n }\n\n return unobserve\n }\n\n return initializeObserver()\n }, [bailOut, initializeOnInteraction, onView, once, ref, threshold])\n}\n\nexport { useOnView }\n\n```"
}
] |
code_render-runtime_f6cc14f0
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of render-runtime/react/hooks/prefetch.ts from the render-runtime VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport {\n PrefetchState,\n usePrefetch,\n getCacheForPage,\n} from '../components/Prefetch/PrefetchContext'\nimport {\n queryStringToMap,\n NavigateOptions,\n getNavigationRouteToNavigate,\n} from '../utils/pages'\nimport {\n getPrefetchForPath,\n fetchRouteData,\n isPrefetchActive,\n} from '../utils/routes'\nimport { fetchComponents } from '../utils/components'\nimport { useRuntime } from '../components/RenderContext'\nimport { useApolloClient } from 'react-apollo'\nimport { useRef, useEffect, useCallback, MutableRefObject } from 'react'\nimport { useOnView } from './viewDetection'\nimport { ApolloClientType } from '../typings/global'\nimport { RenderRuntime } from '../typings/runtime'\n\ninterface PrefetchRequestsArgs {\n canonicalBaseAddress?: string\n client: ApolloClientType\n navigationRoute: any\n page?: string\n pages: RenderRuntime['pages']\n prefetchState: PrefetchState\n hints: RenderRuntime['hints']\n renderMajor: RenderRuntime['renderMajor']\n validCache: {\n pathValid: boolean\n routeValid: boolean\n }\n storeSettings: Record<string, any>\n}\n\nconst getPageToNavigate = (\n path: string,\n query: string,\n canonicalBaseAddress?: string\n) => {\n return getPrefetchForPath({\n path: path,\n fetcher: fetch,\n query: {\n ...queryStringToMap(query),\n ...(canonicalBaseAddress && { __bindingAddress: canonicalBaseAddress }),\n },\n })\n}\n\ninterface MaybeUpdatePathArgs {\n canonicalBaseAddress?: string\n prefetchState: PrefetchState\n navigationRoute: any\n validCache: {\n pathValid: boolean\n routeValid: boolean\n }\n page?: string\n}\n\nconst maybeUpdatePathCache = async ({\n canonicalBaseAddress,\n prefetchState,\n navigationRoute,\n validCache,\n page,\n}: MaybeUpdatePathArgs) => {\n const { pathsState } = prefetchState\n if (validCache.pathValid) {\n return pathsState[navigationRoute.path].page as string\n }\n\n const navigationData = await getPageToNavigate(\n navigationRoute.path,\n navigationRoute.query,\n canonicalBaseAddress\n )\n\n const navigationPage = page ?? navigationData?.page\n pathsState[navigationRoute.path] = { fetching: false, page: navigationPage }\n if (navigationData == null || navigationPage == null) {\n return null\n }\n\n const cacheObj = {\n routeId: navigationPage,\n matchingPage: navigationData.route,\n contentResponse: navigationData.contentResponse,\n queryData: navigationData.queryData,\n }\n\n const cache = getCacheForPage(navigationPage)\n\n cache.set(navigationRoute.path, cacheObj)\n return navigationPage\n}\n\nconst prefetchRequests = async ({\n canonicalBaseAddress,\n client,\n navigationRoute,\n page,\n pages,\n prefetchState,\n hints,\n renderMajor,\n validCache,\n storeSettings,\n}: PrefetchRequestsArgs) => {\n const { pathsState, routesCache, routePromise } = prefetchState\n if (!isPrefetchActive(storeSettings)) {\n return\n }\n\n const navigationPage = await maybeUpdatePathCache({\n canonicalBaseAddress,\n prefetchState,\n navigationRoute,\n validCache,\n page,\n })\n\n pathsState[navigationRoute.path] = { fetching: false, page: navigationPage }\n if (navigationPage == null) {\n return\n }\n\n const declarer = pages[navigationPage]?.declarer\n if (typeof declarer === 'undefined') {\n // Should not happen, but lets be safe\n return\n }\n\n let routeDataCache = routesCache.get(navigationPage)\n const routePromiseValue = routePromise[navigationPage]\n\n if (!routeDataCache && !routePromiseValue) {\n const newState = {\n promisePending: true,\n promise: fetchRouteData({\n apolloClient: client,\n routeId: navigationPage,\n declarer,\n hints,\n renderMajor,\n }),\n }\n newState.promise\n .then((data) => {\n routesCache.set(navigationPage, data)\n })\n .finally(() => {\n newState.promisePending = false\n newState.promise = null as any\n routePromise[navigationPage] = null\n })\n\n routePromise[navigationPage] = newState\n }\n const globalRouteDataState = routePromise[navigationPage]\n if (globalRouteDataState?.promisePending) {\n await globalRouteDataState.promise\n routeDataCache = routesCache.get(navigationPage)\n }\n\n if (!routeDataCache) {\n return\n }\n\n await fetchComponents(\n routeDataCache.components,\n window.__RUNTIME__,\n routeDataCache.extensions\n )\n}\n\ninterface UsePrefetchArgs {\n ref: MutableRefObject<HTMLElement | null>\n page?: string\n href: string\n options: NavigateOptions\n waitToPrefetch?: number\n}\n\n// Returns an object that for a given path, tells us if the routes or path cache has valid data for the given input.\n// We do this to know when to hit the server. Will return false (as invalid data) if cached data has expired its max age.\nconst getCacheValidData = (path: string, prefecthState: PrefetchState) => {\n const { pathsState, routesCache } = prefecthState\n const page = pathsState[path]?.page\n\n if (!page) {\n return {\n pathValid: false,\n routeValid: false,\n }\n }\n\n const cache = getCacheForPage(page)\n const validData = cache.has(path)\n const validRoutesData = routesCache.has(page)\n return {\n pathValid: validData,\n routeValid: validRoutesData,\n }\n}\n\nconst getPriorityForPage = (page: string | undefined) =>\n page === 'store.product' ? 1 : 0\n\nexport const useIsPrefetchActive = () => {\n const { getSettings } = useRuntime()\n const storeSettings = getSettings('vtex.store')\n return isPrefetchActive(storeSettings)\n}\n\nexport const usePrefetchAttempt = ({\n ref,\n page,\n href,\n options,\n waitToPrefetch,\n}: UsePrefetchArgs) => {\n const runtime = useRuntime()\n const prefetchState = usePrefetch()\n const client = useApolloClient() as ApolloClientType\n const hasTried = useRef(false)\n const canPrefetch = useRef(!waitToPrefetch || waitToPrefetch === 0)\n\n useEffect(() => {\n if (!canPrefetch.current) {\n setTimeout(() => {\n canPrefetch.current = true\n }, waitToPrefetch)\n }\n }, [canPrefetch, waitToPrefetch])\n\n const {\n pages,\n navigationRouteModifiers,\n hints,\n query,\n renderMajor,\n getSettings,\n } = runtime\n\n const canonicalBaseAddress = query?.__bindingAddress\n const storeSettings = getSettings('vtex.store')\n\n const attemptPrefetch = useCallback(() => {\n if (\n hasTried.current ||\n !isPrefetchActive(storeSettings) ||\n !canPrefetch.current\n ) {\n return\n }\n\n const { pathsState, queue } = prefetchState\n if (href && href[0] !== '/') {\n // Should only work on relative paths\n return\n }\n\n options.modifiers = navigationRouteModifiers\n const navigationRoute = getNavigationRouteToNavigate(pages, options)\n navigationRoute.original = options.to\n\n if (pathsState[navigationRoute.path]?.fetching) {\n // already fetching, no need to go any further\n hasTried.current = true\n return\n }\n\n const validCache = getCacheValidData(navigationRoute.path, prefetchState)\n\n if (validCache.pathValid && validCache.routeValid) {\n // cache all valid, no need to fetch anything\n hasTried.current = true\n return\n }\n\n if (!validCache.pathValid) {\n pathsState[navigationRoute.path] = { fetching: true }\n }\n\n const priority = getPriorityForPage(page)\n hasTried.current = true\n\n queue.add(\n async () =>\n prefetchRequests({\n canonicalBaseAddress,\n client,\n navigationRoute,\n page,\n pages,\n prefetchState,\n hints,\n renderMajor,\n validCache,\n storeSettings,\n }),\n { priority }\n )\n }, [\n canonicalBaseAddress,\n client,\n hints,\n href,\n navigationRouteModifiers,\n options,\n page,\n pages,\n prefetchState,\n renderMajor,\n storeSettings,\n ])\n\n useOnView({\n ref,\n onView: ({ unobserve }) => {\n /** Uses a setTimeout to prevent creating huge tasks,\n * if prefetchs accumulate.\n * Google \"Total Blocking Time\" for more info.\n */\n setTimeout(() => {\n if (!canPrefetch.current) {\n /** If canPrefetch is false, might be able to retry\n * later, so doesn't \"unobserve\" yet, just return */\n return\n }\n\n attemptPrefetch()\n unobserve()\n }, 1)\n },\n bailOut: !hints.mobile,\n initializeOnInteraction: true,\n threshold: 0.75,\n })\n\n const executePrefetch = useCallback(() => {\n if (hints.desktop) {\n attemptPrefetch()\n }\n }, [attemptPrefetch, hints.desktop])\n\n return executePrefetch\n}\n\n```"
}
] |
code_render-runtime_14bcd205
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of render-runtime/react/hooks/hydration.tsx from the render-runtime VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport { useState } from 'react'\n\n/** Gets HTML content from elements rendered on the server, before being\n * hydrated on the client (and whether they have been SSRendered at all). */\nexport const useDehydratedContent = (hydrationId: string) => {\n /** On both cases below, the use of useState is to guarantee that only the values\n * that it has been initialized with are being considered, to guarantee that it's\n * only taking into account the HTML that's coming from the server, instead of\n * eventual elements that might be inserted later.\n */\n const [dehydratedElement] = useState(() =>\n window?.document?.querySelector?.(`[data-hydration-id=\"${hydrationId}\"]`)\n )\n\n const [hasDehydratedContent] = useState(\n !!dehydratedElement && dehydratedElement.childElementCount > 0\n )\n\n return {\n hasRenderedOnServer: !!dehydratedElement,\n hasDehydratedContent,\n dehydratedElement,\n }\n}\n\n```"
}
] |
code_render-runtime_a08ffff8
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of render-runtime/react/hooks/extension.tsx from the render-runtime VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport { ReactElement } from 'react'\n\nimport { useRuntime } from '../components/RenderContext'\nimport { useTreePath } from '../utils/treePath'\nimport { Extension } from '../typings/runtime'\n\nfunction mountTreePath(base: string, children: string[]) {\n return [base, ...children].filter((id) => !!id).join('/')\n}\n\ninterface Options {\n children?: string[] | string\n}\n\nconst useExtension = ({ children }: Options = {}): Extension | null => {\n const { extensions } = useRuntime()\n\n const { treePath: baseTreePath } = useTreePath()\n\n const treePath = children\n ? mountTreePath(\n baseTreePath,\n Array.isArray(children) ? children : [children]\n )\n : baseTreePath\n\n const extension = treePath && extensions[treePath]\n\n return extension || null\n}\n\ninterface ExtensionContext {\n extension?: Extension | null\n}\n\ninterface Props {\n children({ extension }: ExtensionContext): ReactElement<any> | null\n}\n\nconst ExtensionConsumer = ({ children }: Props) => {\n const extension = useExtension()\n\n return children({ extension })\n}\n\nexport { useExtension, ExtensionConsumer }\n\n```"
}
] |
code_render-runtime_bb441ff6
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of render-runtime/react/typings/react-dom/experimental.d.ts from the render-runtime VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport ReactDOM from 'react-dom'\n\n// stripped from: https://github.com/DefinitelyTyped/DefinitelyTyped/blob/7ec01838c4ba1066b3c456492473dcaa44ddf5cd/types/react-dom/experimental.d.ts\ndeclare module 'react-dom' {\n export as namespace ReactDOM\n\n interface HydrationOptions {\n onHydrated?(suspenseInstance: Comment): void\n onDeleted?(suspenseInstance: Comment): void\n }\n\n interface RootOptions {\n hydrate?: boolean\n hydrationOptions?: HydrationOptions\n }\n\n interface Root {\n render(children: React.ReactChild | React.ReactNodeArray): void\n unmount(callback?: () => void): void\n }\n\n function unstable_createRoot(\n container: Element | Document | DocumentFragment | Comment,\n options?: RootOptions\n ): Root\n}\n\n```"
}
] |
code_render-runtime_8990684a
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of render-runtime/react/typings/@formatjs/intl-pluralrules.d.ts from the render-runtime VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\ndeclare module '@formatjs/intl-pluralrules' {\n export const PluralRules: any\n}\n\n```"
}
] |
code_render-runtime_4c3dae97
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of render-runtime/react/utils/client/generateHash.ts from the render-runtime VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport {\n ArgumentNode,\n BREAK,\n DocumentNode,\n StringValueNode,\n visit,\n} from 'graphql'\n\ninterface HashedDocumentNode extends DocumentNode {\n documentId: string\n}\n\nconst isHashedDocumentNode = (arg: any): arg is HashedDocumentNode => {\n return arg && arg.documentId\n}\n\nexport const generateHash = (query: HashedDocumentNode | DocumentNode) => {\n if (isHashedDocumentNode(query)) {\n return query.documentId\n }\n\n const asset = { hash: '' }\n visit(query, {\n Argument(node: ArgumentNode) {\n if (node.name.value === 'hash') {\n asset.hash = (node.value as StringValueNode).value\n return BREAK\n }\n },\n })\n return asset.hash\n}\n\n```"
}
] |
code_render-runtime_15b63832
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of render-runtime/react/utils/client/index.ts from the render-runtime VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport {\n InMemoryCache,\n IntrospectionFragmentMatcher,\n IntrospectionResultData,\n} from 'apollo-cache-inmemory'\nimport { ApolloClient } from 'apollo-client'\nimport { ApolloLink } from 'apollo-link'\nimport { onError } from 'apollo-link-error'\nimport { createHttpLink } from 'apollo-link-http'\nimport { createPersistedQueryLink } from 'apollo-link-persisted-queries'\nimport { createUploadLink } from 'apollo-upload-client'\nimport { canUseDOM } from 'exenv'\n\nimport PageCacheControl from '../cacheControl'\nimport graphQLErrorsStore from '../graphQLErrorsStore'\nimport { generateHash } from './generateHash'\nimport { toBase64Link } from './links/base64Link'\nimport { cachingLink } from './links/cachingLink'\nimport { ensureSessionLink } from './links/ensureSessionLink'\nimport { createIOFetchLink } from './links/ioFetchLink'\nimport { omitTypenameLink } from './links/omitVariableTypenameLink'\nimport { createUriSwitchLink } from './links/uriSwitchLink'\nimport { versionSplitterLink } from './links/versionSplitterLink'\nimport { createRuntimeContextLink } from './links/runtimeContextLink'\nimport { createHydrationFn, QueryData } from '../apolloCache'\nimport { RenderProvider } from '../../components/RenderProvider'\nimport { promised } from '../promise'\nimport { ApolloClientType } from '../../typings/global'\nimport { RenderRuntime } from '../../typings/runtime'\n\ninterface ApolloClientsRegistry {\n [key: string]: ApolloClientType\n}\n\nexport interface ApolloClientFunctions {\n getClient: (instance: RenderProvider) => ApolloClientType\n hydrate: (queryData: QueryData[] | undefined) => Promise<void>\n}\n\nconst buildCacheId = (\n vendor: string | undefined,\n app: string | undefined,\n major: string | undefined,\n type: string,\n cacheId: string\n) =>\n app && major\n ? `${vendor}.${app}@${major}.x:${type}:${cacheId}`\n : `${type}:${cacheId}`\n\nconst dataIdFromObject = (value: any) => {\n const { cacheId, __typename } = value || ({} as any)\n if (value && __typename && cacheId) {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n const [vendor, app, major, ...type] = __typename.split('_')\n const typename = type.join('_') || __typename\n return buildCacheId(vendor, app, major, typename, cacheId)\n }\n return null\n}\n\nexport const buildCacheLocator = (\n app: string,\n type: string,\n cacheId: string\n) => {\n const [vendor, appAndMajor] = app.replace(/-/g, '').split('.')\n const [appName, major] = appAndMajor && appAndMajor.split('@')\n return buildCacheId(vendor, appName, major, type, cacheId)\n}\n\nconst clientsByWorkspace: ApolloClientsRegistry = {}\n\nexport const getState = (runtime: RenderRuntime) => {\n const { account, workspace } = runtime\n const apolloClient = clientsByWorkspace[`${account}/${workspace}`]\n return apolloClient ? apolloClient.cache.extract() : {}\n}\n\nconst getOrCreateClient = (\n runtime: RenderRuntime,\n baseURI: string,\n runtimeContextLink: ApolloLink,\n sessionPromise: Promise<any>,\n fetcher: GlobalFetch['fetch'],\n cacheControl?: PageCacheControl\n) => {\n const {\n account,\n workspace,\n introspectionResult,\n }: {\n account: string\n workspace: string\n introspectionResult: IntrospectionResultData\n } = runtime\n\n if (!clientsByWorkspace[`${account}/${workspace}`]) {\n const cache = new InMemoryCache({\n addTypename: true,\n dataIdFromObject,\n fragmentMatcher: new IntrospectionFragmentMatcher({\n introspectionQueryResultData: introspectionResult,\n }),\n })\n\n const httpLink = ApolloLink.from([\n toBase64Link,\n createHttpLink({\n credentials: 'include',\n useGETForQueries: false,\n fetch: fetcher,\n }),\n ])\n\n const uploadLink = createUploadLink({\n credentials: 'include',\n })\n\n const fetcherLink = createIOFetchLink(httpLink, uploadLink)\n\n const persistedQueryLink = createPersistedQueryLink({\n disable: () => false,\n generateHash,\n useGETForHashedQueries: true,\n })\n\n const uriSwitchLink = createUriSwitchLink(baseURI, runtime)\n\n const cacheLink = cacheControl ? [cachingLink(cacheControl)] : []\n\n const errorLink = onError(({ graphQLErrors }) => {\n if (graphQLErrors) {\n graphQLErrorsStore.addOperationIds(graphQLErrors)\n }\n })\n\n const link = ApolloLink.from([\n errorLink,\n omitTypenameLink,\n versionSplitterLink,\n runtimeContextLink,\n persistedQueryLink,\n uriSwitchLink,\n ensureSessionLink(sessionPromise),\n ...cacheLink,\n fetcherLink, //this is a final link\n ])\n\n clientsByWorkspace[`${account}/${workspace}`] = new ApolloClient({\n cache: canUseDOM ? cache.restore(window.__STATE__) : cache,\n link,\n resolvers: {},\n ssrMode: !canUseDOM,\n /** TODO: The empty typedefs below fixes an issue with Apollo Devtools.\n * Should look into why it is needed in the first place.\n * https://github.com/apollographql/apollo-client-devtools/issues/238\n */\n typeDefs: [],\n })\n }\n\n return clientsByWorkspace[`${account}/${workspace}`]\n}\n\nexport const createApolloClient = (\n runtime: RenderRuntime,\n baseURI: string,\n sessionPromise: Promise<void>,\n cacheControl?: PageCacheControl\n): Promise<ApolloClientFunctions> => {\n return promised((resolve) => {\n const {\n setRenderProviderInstance,\n link: runtimeContextLink,\n } = createRuntimeContextLink(runtime)\n\n const client = getOrCreateClient(\n runtime,\n baseURI,\n runtimeContextLink,\n sessionPromise,\n fetch,\n cacheControl\n )\n\n resolve({\n getClient: (instance: RenderProvider) => {\n setRenderProviderInstance(instance)\n return client\n },\n hydrate: createHydrationFn(client),\n })\n })\n}\n\n```"
}
] |
code_render-runtime_79166ad0
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of render-runtime/react/utils/client/links/base64Link.ts from the render-runtime VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { ApolloLink, NextLink, Operation } from 'apollo-link'\nimport { Base64 } from 'js-base64'\n\nexport const toBase64Link = new ApolloLink(\n (operation: Operation, forward?: NextLink) => {\n const { extensions, variables } = operation\n if (variables && Object.keys(variables).length > 0) {\n operation.variables = {}\n operation.extensions = {\n ...extensions,\n variables: Base64.encode(JSON.stringify(variables)),\n }\n }\n return forward ? forward(operation) : null\n }\n)\n\n```"
}
] |
code_render-runtime_520ef1d2
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of render-runtime/react/utils/client/links/uriSwitchLink.ts from the render-runtime VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { ApolloLink, NextLink, Operation } from 'apollo-link'\nimport { canUseDOM } from 'exenv'\nimport {\n ASTNode,\n DirectiveNode,\n OperationDefinitionNode,\n StringValueNode,\n visit,\n} from 'graphql'\n\nimport { generateHash } from '../generateHash'\nimport { appendLocationSearch } from '../../location'\nimport { RenderRuntime, CacheHints } from '../../../typings/runtime'\n\ninterface Assets {\n operationType: string\n queryScope?: string\n}\n\nconst assetsFromQuery = (query: ASTNode) => {\n const assets: Assets = { operationType: 'mutation' }\n visit(query, {\n Directive(node: DirectiveNode) {\n if (node.name.value === 'context') {\n const scopeArg =\n node.arguments &&\n node.arguments.find((argNode) => argNode.name.value === 'scope')\n if (scopeArg) {\n assets.queryScope = (scopeArg.value as StringValueNode).value\n }\n }\n },\n OperationDefinition(node: OperationDefinitionNode) {\n assets.operationType = node.operation\n },\n })\n return assets\n}\n\nexport interface OperationContext {\n fetchOptions: any\n runtime: Pick<\n RenderRuntime,\n | 'appsEtag'\n | 'cacheHints'\n | 'components'\n | 'culture'\n | 'extensions'\n | 'messages'\n | 'pages'\n >\n}\n\nconst extractHints = (query: ASTNode, meta: CacheHints) => {\n const { operationType, queryScope } = assetsFromQuery(query)\n\n let hints\n if (operationType?.toLowerCase() === 'query') {\n hints = meta ? meta : { scope: queryScope }\n } else {\n hints = { ...meta, scope: 'private' }\n }\n\n const {\n maxAge = 'long',\n scope = 'private',\n version = 1,\n provider,\n sender,\n } = hints\n return {\n maxAge: maxAge.toLowerCase(),\n operationType,\n scope: scope.toLowerCase(),\n version,\n provider,\n sender,\n }\n}\n\nexport const createUriSwitchLink = (\n baseURI: string,\n initialRuntime: RenderRuntime\n) =>\n new ApolloLink((operation: Operation, forward?: NextLink) => {\n operation.setContext((oldContext: OperationContext) => {\n const {\n fetchOptions = {},\n // Fetches from context for not fetching a stale version of runtime\n runtime: {\n appsEtag,\n cacheHints,\n culture: { locale },\n },\n } = oldContext\n const { extensions } = operation\n const {\n binding,\n workspace,\n route: { domain },\n production,\n } = initialRuntime\n const hash = generateHash(operation.query)\n\n if (!production && !hash) {\n throw new Error(\n 'Could not generate hash from query. Are you using graphql-tag ? Split your graphql queries in .graphql files and import them instead'\n )\n }\n\n const includeQuery = (oldContext as any).http?.includeQuery || !hash\n const { maxAge, scope, version, provider, sender } = extractHints(\n operation.query,\n cacheHints[hash]\n )\n\n const requiresAuthorization =\n initialRuntime.settings?.[`vtex.${domain}`]?.requiresAuthorization\n\n const isPrivateChannel = initialRuntime.channelPrivacy === 'private'\n\n const customScope =\n requiresAuthorization || isPrivateChannel ? 'private' : scope\n const oldMethod = includeQuery ? 'POST' : fetchOptions.method || 'POST'\n const protocol = canUseDOM ? 'https:' : 'http:'\n const method =\n customScope?.toLowerCase() === 'private' ? 'POST' : oldMethod\n extensions.persistedQuery = {\n ...extensions.persistedQuery,\n sender,\n provider,\n }\n\n let query = `?workspace=${workspace}&maxAge=${maxAge}&appsEtag=${appsEtag}&domain=${domain}&locale=${locale}`\n if (binding && binding.id) {\n query = appendLocationSearch(query, { __bindingId: binding.id })\n }\n\n return {\n ...oldContext,\n http: {\n ...(oldContext as any).http,\n includeQuery,\n },\n scope: customScope,\n fetchOptions: { ...fetchOptions, method },\n uri: `${protocol}//${baseURI}/_v/${customScope}/graphql/v${version}${query}`,\n }\n })\n return forward ? forward(operation) : null\n })\n\n```"
}
] |
code_render-runtime_26fe7045
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of render-runtime/react/utils/client/links/omitVariableTypenameLink.ts from the render-runtime VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { ApolloLink, NextLink, Operation } from 'apollo-link'\nimport { canUseDOM } from 'exenv'\n\nconst deepCopyFiles = (src: any, dst: any) =>\n src &&\n typeof src === 'object' &&\n Object.keys(src).forEach((key) => {\n if (\n src[key] instanceof File ||\n src[key] instanceof Blob ||\n src[key] instanceof FileList\n ) {\n dst[key] = src[key]\n } else {\n deepCopyFiles(src[key], dst[key])\n }\n })\n\nconst omitTypename = (key: string, value: any) =>\n key === '__typename' ? undefined : value\n\nexport const omitTypenameLink = new ApolloLink(\n (operation: Operation, forward?: NextLink) => {\n const { variables } = operation\n if (variables && canUseDOM) {\n operation.variables = JSON.parse(\n JSON.stringify(operation.variables),\n omitTypename\n )\n deepCopyFiles(variables, operation.variables)\n }\n return forward ? forward(operation) : null\n }\n)\n\n```"
}
] |
code_render-runtime_2b51aef1
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of render-runtime/react/utils/client/links/cachingLink.ts from the render-runtime VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { ApolloLink, NextLink, Operation } from 'apollo-link'\nimport PageCacheControl from '../../cacheControl'\n\nexport const cachingLink = (cacheControl: PageCacheControl) => {\n return new ApolloLink((operation: Operation, forward?: NextLink) => {\n if (forward) {\n return forward(operation).map((data) => {\n const { response } = operation.getContext()\n cacheControl.evaluate(response)\n return data\n })\n }\n return null\n })\n}\n\n```"
}
] |
code_render-runtime_2b287db7
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of render-runtime/react/utils/client/links/ioFetchLink.ts from the render-runtime VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { ApolloLink, NextLink, Operation } from 'apollo-link'\nimport { canUseDOM } from 'exenv'\n\nconst isUploadable = (v: any) =>\n v instanceof File || v instanceof Blob || v instanceof FileList\n\nconst usesUpload = (value: any): boolean => {\n if (isUploadable(value)) {\n return true\n }\n\n // If it isn't an object we can't recurse anymore\n if (Object(value) !== value) {\n return false\n }\n\n return Object.values(value).some((v) => usesUpload(v))\n}\n\nconst useHttpLink = (operation: Operation) => {\n const { variables } = operation\n\n // No file upload is allowed during SSR\n if (!canUseDOM) {\n return true\n }\n\n const doUseHttpLink = !usesUpload(variables)\n return doUseHttpLink\n}\n\nconst passthrough = (operation: Operation, forward?: NextLink) =>\n forward ? forward(operation) : null\n\nexport const createIOFetchLink = (\n httpLink: ApolloLink,\n uploadLink: ApolloLink\n) => new ApolloLink(passthrough).split(useHttpLink, httpLink, uploadLink)\n\n```"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.