id
stringlengths 12
53
| messages
listlengths 3
3
|
|---|---|
code_example-payment-authorization-app_a75ae6aa
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of example-payment-authorization-app/docs/README.md from the example-payment-authorization-app VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```markdown\n# Payment app\n\nThe *Payment* app adds a verification step to the checkout process, responsible for allowing or forbidding an order placement.\n\nTo implement this feature in your store, you'll need to develop your own *Payment app*, but don't worry! This repository provides the necessary structure for that, and the following step by step will guide you.\n\n## Step by step\n\n> ℹ️ Please, keep in mind that in this step by step you'll be using the [VTEX IO](https://developers.vtex.com/vtex-developer-docs/docs/what-is-vtex-io) development platform.\n\n### Step 1: Setting up the basic development environment\n\n1. Using the terminal, [install the VTEX IO CLI](https://vtex.io/docs/recipes/development/vtex-io-cli-installation-and-command-reference/) (Command Line Interface) known as **Toolbelt** .\n2. Using the terminal and the Toolbelt, log in to your VTEX account by running the following command:\n\n```shell\nvtex login {account}\n```\n\n> ⚠️ Remember to replace the values between the curly brackets according to your scenario\n\nOnce you run this command, a window will open in your browser asking for your credentials.\n\n3. Once you provide your credentials, run the following command in the terminal to create a [Development workspace](https://vtex.io/docs/recipes/development/creating-a-development-workspace/) and to start developing your *Payment* app.\n\n```shell\nvtex use {examplename}\n```\n\n> ⚠️ Replace `{examplename}` with a name of your choosing. This name will be given to the workspace in which you will develop.\n\n> ℹ️ If you're used to working with GitHub, think of workspaces as branches.\n\n### Step 2: Editing the Payment app\n\n1. Using your terminal, clone the *Payment* app boilerplate repository to your local files by running:\n\n```shell\ngit clone https://github.com/vtex-apps/example-payment-authorization-app\n```\n\n2. Then, using any code editor of your choice, open the boilerplate repository's directory.\n3. Open the `manifest.json` file and update its metadata, according to your scenario. It's essential that you update the following fields:\n\n- `vendor` - The app owner. That is, the VTEX account responsible for the app development, maintenance, and distribution.\n- `name` - The app name. It should concisely express the app's purpose. They must be comprised of lowercase letters separated by hyphens. Special characters, such as `*` and `@`, and numbers at the beginning of the name are not recommended.\n\n4. Open the `pages/pages.json` file and replace `{example-payment-auth-app}` with the app `name` set in step 3.\n5. Using your terminal, go to the app's directory and run the following command:\n\n```shell\nvtex link\n```\n\n> ℹ️ Once you [link the app](https://vtex.io/docs/recipes/development/linking-an-app/), your computer's local files will sync to our cloud development environment. This means that any change done locally in the code you are working on will be sent to the cloud and then reflected in the workspace in which you are working.\n\n### Step 3: Running the *Payment* app\n\n1. Using your browser, go to `http://{workspace}--{account}.myvtex.com/checkout?workspace={workspace}`.\n\n> ⚠️ Remember to replace the values between the curly brackets according to your scenario\n\n2. Open the *browser Developer tools* and run the following command:\n\n```javascript\nwindow.transactionAppName = '{app-name}'\n```\n\nNow, if you go through the *checkout process*, you'll notice an additional verification step (set in our *Payment* app) after the *Order confirmation*.\n\n\n### Step 4: Deploying the *Payment* app\n\n> ℹ️ Before deploying your app, we recommend that you perform tests and check if everything is as expected. For that, go to `http://{workspace}--{store}.myvtex.com`. Add products to your store's cart and go to the shopping cart page. Open your browser DevTools and run the following command to get the `orderFormId` value: `vtexjs.checkout.orderFormId`. Now, inject the `orderFormId` value in `vtexcommercestable`, using:\n`http://{workspace}--{account}.myvtex.com/checkout?workspace={workspace}&orderFormId={orderFormId}`.\n\nOnce you're happy with the changes, follow our documentation on [making your new app version publicly available](https://vtex.io/docs/recipes/development/making-your-new-app-version-publicly-available/) to run your app on master.\n\n## Modus Operandi\n\nAfter developing and implementing the *Payment* app, your store will profit from having an additional verification step in its checkout process.\n\nTo make the best use of the *Payment* app, this section discusses the following topics:\n\n- Understanding the checkout response.\n- Handling the order payload.\n- Injecting external scripts.\n\n### Understanding the checkout response\n\nAfter the order placement, there's a validation step to check whether the transaction is approved or not.\n\nIf the transaction is approved, the checkout UI redirects to the *Order Placed* page. Otherwise, it shows a warning pop-up.\n\nIn our *Payment* app, this validation is performed through the `transactionValidation.vtex` event, which, when triggered, sends the payment status to the checkout UI according to the following [method](https://github.com/vtex-apps/payment-authorization-app-example/blob/3e5742c87a2771998009cff4fecacb092bb3362b/react/index.js#L22):\n\n```javascript\nrespondTransaction = (status) => {\n window.$(window).trigger('transactionValidation.vtex', [status])\n}\n```\n\nNotice that the `respondTransaction` function receives the `status` boolean value, which resolves (`status == true`) or rejects (`status == false`) an order placement.\n\nHence, whenever the `transactionValidation.vtex` event occurs, the Checkout UI checks the payment status and is redirected according to the `status` value provided to the `respondTransaction` function\n\n### Handling the order payload\n\nThe `appPayload` is what the *Payment* app receives as `props` and it consists of a serialized JSON of the order payload.\n\nThus, to access this information, just run the following command:\n\n```javascript\nconst { appPayload } = this.props // This appPayload is a serialized JSON (as string).\n```\n\nThe expected response is a JSON object consisting of the data needed for the Payment app to allow or deny an order placement. Thus, depending on the payment processes implemented in your store, the `appPayload` fields may vary.\n\nTake the following example:\n\n```json\n{\n \"timeToCancel\": 300,\n \"transactionApproveLink\": \"https://...\"\n}\n```\n\n### Injecting external scripts\n\nTo run external scripts on your *Payment* app, you need to inject the following script on the head of the checkout `html`. \n\nTo do so, you have to do a DOM injection. For that, you should do:\n\n```javascript\nconst head = document.getElementsByTagName('head')[0]\n\nconst js = document.createElement('script')\njs.id = {{script-id}}\njs.src = {{script-src}}\njs.async = true;\njs.defer = true;\njs.onload = {{callback-onload}}\n\nhead.appendChild(js)\n```\n\nThere is an example for the script injection [here](https://github.com/vtex-apps/payment-authorization-app-example/blob/3e5742c87a2771998009cff4fecacb092bb3362b/react/index.js#L41)\n\n> ℹ️ Keep in mind that if the external `js` script handles DOM manipulation, then you should use React's [`ref`](https://reactjs.org/docs/refs-and-the-dom.html) to create a `div` container and hand it over to the library. There's also an [example](https://github.com/vtex-apps/payment-authorization-app-example/blob/3e5742c87a2771998009cff4fecacb092bb3362b/react/index.js#L11) for doing so in this repo.\n\n```"
}
] |
code_example-payment-authorization-app_2f7d3282
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of example-payment-authorization-app/pages/pages.json from the example-payment-authorization-app VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"extensions\": {\n \"checkout/transactions/example-payment-auth-app\": {\n \"component\": \"index\"\n }\n }\n}\n\n```"
}
] |
code_example-payment-authorization-app_1afb2bce
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of example-payment-authorization-app/react/index.tsx from the example-payment-authorization-app VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React, { Component, Fragment } from 'react'\nimport styles from './index.css'\n\ninterface InjectScriptProps {\n id: string\n src: string\n onLoad: (this: GlobalEventHandlers, ev: Event) => void\n}\n\ntype Props = {\n appPayload: string\n}\n\ntype State = {\n scriptLoaded: boolean\n loading: boolean\n}\n\nclass ExampleTransactionAuthApp extends Component<Props, State> {\n divContainer: React.RefObject<HTMLDivElement>\n\n constructor(props: Props) {\n super(props)\n this.state = {\n scriptLoaded: false,\n loading: false,\n }\n\n this.divContainer = React.createRef()\n }\n\n componentWillMount = () => {\n this.injectScript({\n id: 'google-recaptcha-v2',\n src: 'https://recaptcha.net/recaptcha/api.js?render=explicit',\n onLoad: this.handleOnLoad\n })\n }\n\n componentDidMount() {\n // In case you want to remove payment loading in order to show an UI.\n window.$(window).trigger('removePaymentLoading.vtex')\n }\n\n respondTransaction = (status: boolean) => {\n window.$(window).trigger('transactionValidation.vtex', [status])\n }\n\n handleOnLoad = () => {\n this.setState({ scriptLoaded: true })\n grecaptcha.ready(() => {\n if (this.divContainer.current) {\n grecaptcha.render(this.divContainer.current, {\n sitekey: '------>REPATCHA_V2_SITE_KEY<------', //Replace with site key\n theme: 'dark',\n callback: this.onVerify,\n })\n }\n })\n }\n\n onVerify = () => {\n const parsedPayload = JSON.parse(this.props.appPayload)\n this.setState({ loading: true })\n\n fetch(parsedPayload.approvePaymentUrl).then(() => {\n this.respondTransaction(true)\n })\n }\n\n cancelTransaction = () => {\n const parsedPayload = JSON.parse(this.props.appPayload)\n this.setState({ loading: true })\n\n fetch(parsedPayload.denyPaymentUrl).then(() => {\n this.respondTransaction(false)\n })\n }\n\n confirmTransation = () => {\n const parsedPayload = JSON.parse(this.props.appPayload)\n this.setState({ loading: true })\n\n fetch(parsedPayload.approvePaymentUrl).then(() => {\n this.respondTransaction(true)\n })\n }\n\n injectScript = ({ id, src, onLoad }: InjectScriptProps) => {\n if (document.getElementById(id)) {\n return\n }\n\n const head = document.getElementsByTagName('head')[0]\n\n const js = document.createElement('script')\n js.id = id\n js.src = src\n js.async = true\n js.defer = true\n js.onload = onLoad\n\n head.appendChild(js)\n }\n\n render() {\n const { scriptLoaded, loading } = this.state\n\n return (\n <div className={styles.wrapper}>\n {scriptLoaded && !loading ? (\n <Fragment>\n <div className=\"g-recaptcha\" ref={this.divContainer}></div>\n <button\n id=\"payment-app-confirm\"\n className={styles.buttonSuccess}\n onClick={this.confirmTransation}>\n Confirmar\n </button>\n </Fragment>\n ) : (\n <h2>Carregando...</h2>\n )}\n\n {!loading && (\n <button\n id=\"payment-app-cancel\"\n className={styles.buttonDanger}\n onClick={this.cancelTransaction}>\n Cancelar\n </button>\n )}\n </div>\n )\n }\n}\n\nexport default ExampleTransactionAuthApp\n\n```"
}
] |
code_example-payment-authorization-app_ff98851c
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of example-payment-authorization-app/react/index.css from the example-payment-authorization-app VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```css\n.wrapper {\n align-items: center;\n background: white;\n display: flex;\n flex-direction: column;\n height: 500px;\n justify-content: center;\n left: 0;\n margin-left: auto;\n margin-right: auto;\n position: absolute;\n right: 0;\n width: 500px;\n top: 0;\n box-shadow: 0px 0px 26px 0px rgba(0, 0, 0, 0.42);\n z-index: 999;\n}\n\n.buttonDanger {\n color: #fff;\n background-color: #d9534f;\n border-color: #d43f3a;\n}\n\n.buttonSuccess {\n color: #fff;\n background-color: #8bc34a;\n border-color: #8bc34a;\n}\n\n.appPayload {\n width: 100%;\n word-break: break-word;\n}\n\n```"
}
] |
code_example-payment-authorization-app_807eec1a
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of example-payment-authorization-app/react/package.json from the example-payment-authorization-app VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"name\": \"yes-no-app\",\n \"version\": \"1.1.0\",\n \"main\": \"index.js\",\n \"license\": \"MIT\",\n \"dependencies\": {\n \"react\": \"16.8.6\",\n \"react-dom\": \"16.8.6\"\n },\n \"devDependencies\": {\n \"@types/grecaptcha\": \"^3.0.4\",\n \"@types/node\": \"12.6.2\",\n \"@types/react\": \"16.8.6\"\n }\n}\n\n```"
}
] |
code_example-payment-authorization-app_cf3d6524
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of example-payment-authorization-app/react/typings/global.d.ts from the example-payment-authorization-app VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\ndeclare module '*.css' {\n interface IClassNames {\n [className: string]: string\n }\n const classNames: IClassNames\n export = classNames\n}\n\ninterface Window {\n vtexjs: VTEXJS\n $: any // JQuery types\n}\n```"
}
] |
code_device-detector_5ff294b4
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of device-detector/docs/README.md from the device-detector VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```markdown\n# Device Detector\n\nUse this app's HOC or hook to find out current device's viewport size.\n\n### Usage\n\n#### useDevice\n\nReturns an object with the format of `DeviceInfo` defined as:\n```js\ninterface DeviceInfo {\n device: Device\n isMobile: boolean\n}\n\nenum Device {\n phone = 'phone',\n tablet = 'tablet',\n desktop = 'desktop',\n}\n```\n\n```js\nimport { useDevice } from 'vtex.device-detector'\nconst MyComponent = props => {\n const { isMobile } = useDevice()\n if (isMobile) { \n // is phone or tablet!\n }\n return ...\n}\n```\n\nor\n\n```js\nimport { useDevice } from 'vtex.device-detector'\nconst MyComponent = props => {\n const { device } = useDevice()\n if (device === 'tablet') { \n //is tablet!\n }\n return ...\n}\n```\n\n#### withDevice\n\nIt is a HOC, it injects two props (`isMobile` and `device`) into your component's props:\n\n```js\ntype WithDeviceProps = Props & {\n isMobile: boolean\n device: Device\n}\nenum Device {\n phone = 'phone',\n tablet = 'tablet',\n desktop = 'desktop',\n}\n```\n\n```js\nimport { withDevice } from 'vtex.device-detector'\nconst MyComponent = props => {\n if (props.isMobile) { \n // is phone or tablet!\n }\n return ...\n}\n\nexport default withDevice(MyComponent)\n```\n\nor\n\n```js\nimport { useDevice } from 'vtex.device-detector'\nconst MyComponent = props => {\n if (props.device === 'tablet') { \n //is tablet!\n }\n return ...\n}\n\nexport default withDevice(MyComponent)\n```\n\n```"
}
] |
code_device-detector_7cbabe54
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of device-detector/react/DeviceDetector.tsx from the device-detector VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport type { FC } from 'react'\nimport type { RenderContext } from 'vtex.render-runtime'\n\nimport useDevice from './useDevice'\n\ntype Device = RenderContext.RenderContext['deviceInfo']['type']\n\nexport interface DeviceInfo {\n device: Device\n isMobile: boolean\n}\n\ninterface Props {\n children?: (deviceInfo: DeviceInfo) => React.ReactElement\n}\n\nconst DeviceDetector: FC<Props> = ({ children }) => {\n const { device, isMobile } = useDevice()\n\n if (!children) {\n return null\n }\n\n return children({ device, isMobile })\n}\n\nexport default DeviceDetector\n\n```"
}
] |
code_device-detector_d37512f7
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of device-detector/react/useDevice.tsx from the device-detector VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport { useRuntime } from 'vtex.render-runtime'\nimport type { RenderContext } from 'vtex.render-runtime'\n\ntype Device = RenderContext.RenderContext['deviceInfo']['type']\n\nexport interface DeviceInfo {\n device: Device\n isMobile: boolean\n}\n\nconst useDevice = () => {\n const { deviceInfo, hints } = useRuntime()\n\n if (!deviceInfo) {\n /** Fallback code to support transition to device info coming\n * from render-runtime. Should be removed in the near future */\n\n return {\n device: (hints.phone\n ? 'phone'\n : hints.tablet\n ? 'tablet'\n : 'desktop') as Device,\n isMobile: hints.mobile,\n }\n }\n\n const { type: device, isMobile } = deviceInfo\n\n return { device, isMobile }\n}\n\nexport default useDevice\n\n```"
}
] |
code_device-detector_d684a15d
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of device-detector/react/package.json from the device-detector VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"scripts\": {\n \"test\": \"vtex-test-tools test\",\n \"lint\": \"tsc --noEmit && eslint --ext ts,tsx .\"\n },\n \"dependencies\": {\n \"@vtex/tsconfig\": \"^0.5.6\",\n \"react\": \"^16.8.3\",\n \"react-dom\": \"^16.8.3\"\n },\n \"devDependencies\": {\n \"@types/jest\": \"^24.0.11\",\n \"@types/node\": \"^11.13.0\",\n \"@types/react\": \"^16.8.10\",\n \"@types/react-intl\": \"^2.3.17\",\n \"@vtex/test-tools\": \"^3.3.2\",\n \"apollo-client\": \"^2.5.1\",\n \"typescript\": \"3.9.7\",\n \"vtex.render-runtime\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.render-runtime@8.126.4/public/@types/vtex.render-runtime\"\n },\n \"version\": \"0.2.6\"\n}\n\n```"
}
] |
code_device-detector_831a7134
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of device-detector/react/withDevice.tsx from the device-detector VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\nimport type { ComponentType } from 'react'\n\nimport useDevice from './useDevice'\n\nfunction withDevice<P>(Component: ComponentType<P>) {\n const WithDeviceHOC = ({ ...props }: P) => {\n const { isMobile, device } = useDevice()\n\n return <Component device={device} isMobile={isMobile} {...props} />\n }\n\n return WithDeviceHOC\n}\n\nexport default withDevice\n\n```"
}
] |
code_device-detector_e5d7273d
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of device-detector/store/interfaces.json from the device-detector VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"base-store-component\": {\n \"component\": \"Example\"\n }\n}\n```"
}
] |
code_partytown_3a6ce6b8
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of partytown/utils/build.js from the partytown VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\n/* eslint-disable no-await-in-loop */\nconst fs = require('fs')\n\nconst Mustache = require('mustache')\nconst { minify } = require('html-minifier')\n\nfunction writeFile() {\n const headBuffer = fs.readFileSync('./src/head.html')\n const partytowBuffer = fs.readFileSync('./public/~partytown/partytown.js')\n const manifest = JSON.parse(fs.readFileSync('./manifest.json'))\n\n fs.writeFileSync(\n './pixel/head.html',\n `${Mustache.render(headBuffer.toString(), {\n version: manifest.version,\n })}<script>${partytowBuffer.toString()}</script>`\n )\n}\n\nfunction minifyFile() {\n const headBuffer = fs.readFileSync('./pixel/head.html')\n\n fs.writeFileSync(\n './pixel/head.html',\n minify(headBuffer.toString(), { minifyJS: true, collapseWhitespace: false })\n )\n}\n\nasync function build() {\n writeFile()\n minifyFile()\n}\n\nbuild()\n\n```"
}
] |
code_partytown_1e4cef99
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of partytown/docs/README.md from the partytown VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```markdown\n📢 Use this project, [contribute](https://github.com/vtex-apps/CHANGEME) to it or open issues to help evolve it using [Store Discussion](https://github.com/vtex-apps/store-discussion).\n\n# Partytown\n\n<!-- DOCS-IGNORE:start -->\n<!-- ALL-CONTRIBUTORS-BADGE:START - Do not remove or modify this section -->\n[](#contributors-)\n<!-- ALL-CONTRIBUTORS-BADGE:END -->\n<!-- DOCS-IGNORE:end -->\n\nPartytown is app to manage your third party scripts.\n\n> ℹ️ **Partytown is currently in closed beta**. Which means it's still not a final version and may have flaws. We recommend always testing all scripts while implementing this guide.\n\n> ℹ️ If you are using `experimentalLazyLoad` we recommend to disable it for `vtex.partytown` and any other pixel you want to run in partytown.\n\n## Usage\n### Installing partytown\n\nInstall the `vtex.partytown` on your new workspace by running `vtex install vtex.partytown@0.x`\n\n### Migrating your pixel app to the partytown format\n\n1. Open the `pixel/head.html` file\n\n2. Add the `type=\"text/partytown\"` attribute to each individual `<script>` tag\n```diff\n- <script>...</script>\n+ <script type=\"text/partytown\">...</script>\n```\n\n3. (Optional) If you want to access some global variables added to the `window` by the pixel apps, you need to declare it. Go to the `https://{{myworkspace}}--{{myaccount}}.myvtex.com/admin/apps` URL, select the `partytown` app and then add the name of the variables you want to access in the `Forward` field.\n\n\n\n\n## Known Issues\n\n### Uncaught TypeError: Cannot convert undefined or null to object\n\n```\nUncaught TypeError: Cannot convert undefined or null to object\n at Function.getPrototypeOf (<anonymous>)\n at readOwnImplementation (partytown-sandbox-sw.js?v=0.7.4:492:38)\n at partytown-sandbox-sw.js?v=0.7.4:478:75\n at Array.map (<anonymous>)\n at readImplementations (partytown-sandbox-sw.js?v=0.7.4:478:19)\n at readMainPlatform (partytown-sandbox-sw.js?v=0.7.4:450:27)\n at partytown-sandbox-sw.js?v=0.7.4:542:56\n at worker.onmessage (partytown-sandbox-sw.js?v=0.7.4:552:69)\n```\n\nVTEX uses the [history npm lib](https://www.npmjs.com/package/history). Partytown doesn't have support for this lib, that's why this error is thrown.\nEven with this error, partytown will work correctly as long as your script does not use the History API.\n\n## Debug\nTo make sure that partytown is able to run scripts, install partytown in a development workspace and observe if the following message is printed in the browser console. \n\n\n```\nPartytown was able to run this script. If you are having problems running your script, it is possible that there is a compatibility issue between your script and partytown.\n```\n\n## Development\n\nModify the `src/head.html` file and run the `yar run build` command.\n\n<!-- TODO: Documentation -->\n\n```"
}
] |
code_partytown_d65da7fc
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of partytown/react/package.json from the partytown VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"scripts\": {\n \"test\": \"vtex-test-tools test\"\n },\n \"devDependencies\": {\n \"@apollo/react-testing\": \"^3.1.3\",\n \"@types/graphql\": \"^14.5.0\",\n \"@types/jest\": \"^25.1.5\",\n \"@types/node\": \"^13.11.0\",\n \"@types/react\": \"^16.9.31\",\n \"@types/react-intl\": \"^3.0.0\",\n \"@vtex/test-tools\": \"^3.1.0\",\n \"apollo-cache-inmemory\": \"^1.6.5\",\n \"apollo-client\": \"^2.6.8\",\n \"graphql\": \"^14.5.4\",\n \"react-intl\": \"^3.11.0\",\n \"typescript\": \"3.9.7\",\n \"vtex.pixel-interfaces\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.pixel-interfaces@1.1.1/public/_types/react\",\n \"vtex.render-runtime\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.render-runtime@8.124.3/public/@types/vtex.render-runtime\"\n },\n \"version\": \"0.0.1\"\n}\n\n```"
}
] |
code_partytown_711691b7
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of partytown/store/interfaces.json from the partytown VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"pixel.partytown\": {\n \"component\": \"index\"\n }\n}\n\n```"
}
] |
code_partytown_fd6e72cb
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of partytown/public/~partytown/partytown-sw.js from the partytown VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\n/* Partytown 0.7.4 - MIT builder.io */\nconst e = new Map(),\n t = (e, t) => ({ F: e.F, p: t }),\n r = (e, t) =>\n new Response(e, {\n headers: {\n 'content-type': t || 'text/html',\n 'Cache-Control': 'no-store',\n },\n })\n;(self.oninstall = () => self.skipWaiting()),\n (self.onactivate = () => self.clients.claim()),\n (self.onmessage = t => {\n const r = t.data,\n n = e.get(r.F)\n n && (e.delete(r.F), clearTimeout(n[1]), n[0](r))\n }),\n (self.onfetch = n => {\n const s = n.request,\n i = new URL(s.url).pathname\n i.endsWith('sw.html')\n ? n.respondWith(\n r(\n '<!DOCTYPE html><html><head><meta charset=\"utf-8\"><script type=\"module\">/* Partytown 0.7.4 - MIT builder.io */\\n(e=>{const t=()=>{},r=e=>e.length,n=e=>{var t,r,n;try{const r=null===(t=null==e?void 0:e.constructor)||void 0===t?void 0:t.name;if(r)return r}catch(e){}try{const t=null===(n=null===(r=null==e?void 0:e.__zone_symbol__originalInstance)||void 0===r?void 0:r.constructor)||void 0===n?void 0:n.name;if(t)return t}catch(e){}return\"\"},s=(e,t)=>e.startsWith(t),i=e=>!(s(e,\"webkit\")||s(e,\"toJSON\")||s(e,\"constructor\")||s(e,\"toString\")||s(e,\"_\")),o=e=>11===e.nodeType&&e.host?\"#s\":e.nodeName,a=()=>Math.round(Math.random()*Number.MAX_SAFE_INTEGER).toString(36),l={Anchor:\"a\",DList:\"dl\",Image:\"img\",OList:\"ol\",Paragraph:\"p\",Quote:\"q\",TableCaption:\"caption\",TableCell:\"td\",TableCol:\"colgroup\",TableRow:\"tr\",TableSection:\"tbody\",UList:\"ul\"},c={Graphics:\"g\",SVG:\"svg\"},u=Symbol(),h=Symbol(),d=new Map,p=new Map,m={},g=new WeakMap,f=(e,t)=>{if(e)return(t=g.get(e))||(t=e[u])||v(e,t=a()),t},y=(e,t,r,n,s)=>{if((r=m[e])&&r.U){if(e===t)return r.U;if(n=r.U.document,\"d\"===(s=t.split(\".\").pop()))return n;if(\"e\"===s)return n.documentElement;if(\"h\"===s)return n.head;if(\"b\"===s)return n.body}return d.get(t)},v=(e,t,r)=>{e&&(d.set(t,e),e[u]=t,e[h]=r=Date.now(),r>w+5e3&&(d.forEach(((e,t)=>{e[h]<w&&e.nodeType&&!e.isConnected&&d.delete(t)})),w=r))};let w=0;const $=e.parent,S=document.implementation.createHTMLDocument(),b=$.partytown||{},E=(b.lib||\"/~partytown/\")+\"\",T=(e,t,r)=>{const n=((e,t)=>{return r=e,n={value:t},Object.defineProperty(r,\"name\",{...n,configurable:!0});var r,n})(class extends m[e].U.HTMLElement{},r[0]);return\"connectedCallback,disconnectedCallback,attributeChangedCallback,adoptedCallback\".split(\",\").map((r=>n.prototype[r]=function(...n){t.postMessage([15,e,f(this),r,n])})),n.observedAttributes=r[1],n},C=(e,t,r,i,a)=>void 0!==t&&(i=typeof t)?\"string\"===i||\"number\"===i||\"boolean\"===i||null==t?[0,t]:\"function\"===i?[6]:(r=r||new Set)&&Array.isArray(t)?r.has(t)?[1,[]]:r.add(t)&&[1,t.map((t=>C(e,t,r)))]:\"object\"===i?x(t)?[14,{name:t.name,message:t.message,stack:t.stack}]:\"\"===(a=n(t))?[2,{}]:\"Window\"===a?[3,[e,e]]:\"HTMLCollection\"===a||\"NodeList\"===a?[7,Array.from(t).map((t=>C(e,t,r)[1]))]:a.endsWith(\"Event\")?[5,I(e,t,r)]:\"CSSRuleList\"===a?[12,Array.from(t).map(M)]:s(a,\"CSS\")&&a.endsWith(\"Rule\")?[11,M(t)]:\"CSSStyleDeclaration\"===a?[13,I(e,t,r)]:\"Attr\"===a?[10,[t.name,t.value]]:t.nodeType?[3,[e,f(t),o(t)]]:[2,I(e,t,r,!0,!0)]:void 0:t,I=(e,t,r,s,o,a,l,c)=>{if(a={},!r.has(t))for(l in r.add(t),t)i(l)&&(c=\"path\"===l&&n(t).endsWith(\"Event\")?t.composedPath():t[l],(s||\"function\"!=typeof c)&&(o||\"\"!==c)&&(a[l]=C(e,c,r)));return a},M=e=>{let t,r={};for(t in e)U.includes(t)&&(r[t]=String(e[t]));return r},x=t=>t instanceof e.top.Error,N=(t,r,n,s)=>r?(n=r[0],s=r[1],0===n?s:4===n?L(t,s):1===n?s.map((e=>N(t,e))):3===n?y(s[0],s[1]):5===n?R(A(t,s)):2===n?A(t,s):8===n?s:9===n?new e[r[2]](s):void 0):void 0,L=(e,{V:t,w:r,L:n},s)=>((s=p.get(n))||(s=function(...s){e.postMessage([9,{V:t,w:r,L:n,R:C(t,this),b:C(t,s)}])},p.set(n,s)),s),R=e=>new(\"detail\"in e?CustomEvent:Event)(e.type,e),A=(e,t,r,n)=>{for(n in r={},t)r[n]=N(e,t[n]);return r},U=\"cssText,selectorText,href,media,namespaceURI,prefix,name,conditionText\".split(\",\"),P=async(e,t)=>{let n,s,i,o,a,l,c={F:t.F},u=r(t.Q),h=0;for(;h<u;h++)try{l=h===u-1,n=t.Q[h],s=n.V,i=n.a,!m[s]&&s.startsWith(\"f_\")&&await new Promise((e=>{let t=0,r=()=>{m[s]||t++>1e3?e():requestAnimationFrame(r)};r()})),1===i[0]&&i[1]in m[s].U?v(new m[s].U[i[1]](...N(e,i[2])),n.w):(o=y(s,n.w),o?(a=j(e,s,o,i,l,n.r),n.d&&(\"string\"==typeof n.d?v(a,n.d):m[n.d.V]={V:n.d.V,U:{document:a}}),\"object\"==typeof(d=a)&&d&&d.then&&(a=await a,l&&(c.z=!0)),l&&(c.M=C(s,a))):c.p=n.w+\" not found\")}catch(e){l?c.p=String(e.stack||e):console.error(e)}var d;return c},j=(e,t,s,i,o,a)=>{let l,c,u,h,d,p=0,m=r(i);for(;p<m;p++){c=i[p],l=i[p+1],u=i[p-1];try{if(!Array.isArray(l))if(\"string\"==typeof c||\"number\"==typeof c){if(p+1===m&&a)return d={},a.map((e=>d[e]=s[e])),d;s=s[c]}else{if(0===l)return void(s[u]=N(e,c));if(\"function\"==typeof s[u]&&(h=N(e,c),\"define\"===u&&\"CustomElementRegistry\"===n(s)&&(h[1]=T(t,e,h[1])),\"insertRule\"===u&&h[1]>r(s.cssRules)&&(h[1]=r(s.cssRules)),s=s[u].apply(s,h),\"play\"===u))return Promise.resolve()}}catch(e){if(o)throw e;console.debug(e)}}return s},O=(e,t)=>{let n,s,i,o=t.V,a=t.U,l=a.document;l&&l.body?(n=l.querySelector(\\'script[type=\"text/partytown\"]:not([data-ptid]):not([data-pterror]):not([async]):not([defer])\\'),n||(n=l.querySelector(\\'script[type=\"text/partytown\"]:not([data-ptid]):not([data-pterror])\\')),n?(n.dataset.ptid=s=f(n,o),i={V:o,w:s},n.src?(i.S=n.src,i.H=n.dataset.ptsrc||n.src):i.j=n.innerHTML,e.postMessage([7,i])):(t.x||(t.x=1,((e,t,n)=>{let s,i,o=n._ptf,a=(n.partytown||{}).forward||[],l=(r,n)=>e.postMessage([10,{V:t,q:r,b:C(t,Array.from(n))}]);if(n._ptf=void 0,a.map((e=>{i=n,e.split(\".\").map(((e,t,n)=>{i=i[n[t]]=t+1<r(n)?i[n[t]]||(\"push\"===n[t+1]?[]:{}):(...e)=>l(n,e)}))})),o)for(s=0;s<r(o);s+=2)l(o[s],o[s+1])})(e,o,a),l.dispatchEvent(new CustomEvent(\"pt0\"))),e.postMessage([8,o]))):requestAnimationFrame((()=>O(e,t)))},k=(e,t,r)=>{if(!g.has(r)){g.set(r,t);const n=r.document,s=r.history,i=g.get(r.parent);let o=!1;const a=[],l=e=>{o?e():a.push(e)},c=()=>{e.postMessage([5,{V:t,J:i,S:n.baseURI,T:n.visibilityState}]),setTimeout((()=>{o=!0,a.forEach((e=>{e()}))}))},u=s.pushState.bind(s),h=s.replaceState.bind(s),d=(r,s,i,o)=>()=>{setTimeout((()=>{e.postMessage([13,{V:t,type:r,state:s,url:n.baseURI,newUrl:i,oldUrl:o}])}))};s.pushState=(e,t,r)=>{u(e,t,r),l(d(0,e,null==r?void 0:r.toString()))},s.replaceState=(e,t,r)=>{h(e,t,r),l(d(1,e,null==r?void 0:r.toString()))},r.addEventListener(\"popstate\",(e=>{l(d(2,e.state))})),r.addEventListener(\"hashchange\",(e=>{l(d(3,{},e.newURL,e.oldURL))})),r.addEventListener(\"ptupdate\",(()=>{O(e,m[t])})),n.addEventListener(\"visibilitychange\",(()=>e.postMessage([14,t,n.visibilityState]))),m[t]={V:t,U:r},\"complete\"===n.readyState?c():r.addEventListener(\"load\",c)}},H=()=>{const e=S.createElement(\"i\"),t=S.createTextNode(\"\"),r=S.createComment(\"\"),n=S.createDocumentFragment(),s=S.createElement(\"p\").attachShadow({mode:\"open\"}),i=J($,\"IntersectionObserver\"),o=J($,\"MutationObserver\"),a=J($,\"ResizeObserver\"),l=$.performance,c=$.screen,u=[[$.history],[l],[l.navigation],[l.timing],[c],[c.orientation],[$.visualViewport],[i,12],[o,12],[a,12],[t],[r],[n],[s],[e],[e.attributes],[e.classList],[e.dataset],[e.style],[S],[S.doctype]],h=[F(\"Window\",$),F(\"Node\",t)],d={i:JSON.stringify(b,((e,t)=>(\"function\"==typeof t&&(t=String(t)).startsWith(e+\"(\")&&(t=\"function \"+t),t))),v:B(u,h),C:new URL(E,$.location)+\"\",I:origin,D:q(\"localStorage\"),O:q(\"sessionStorage\")};return G(d.v,$,\"IntersectionObserverEntry\"),d},V=()=>{const e=Object.getOwnPropertyNames($).map((e=>((e,t,r,n)=>{if(r=t.match(/^(HTML|SVG)(.+)Element$/))return n=r[2],\"S\"==t[0]?e.createElementNS(\"http://www.w3.org/2000/svg\",c[n]||n.slice(0,2).toLowerCase()+n.slice(2)):e.createElement(l[n]||n)})(S,e))).filter((e=>e)).map((e=>[e]));return B(e,[])},D=new Set([\"Object\"]),B=(e,t)=>(e.filter((e=>e[0])).map((e=>{const t=e[0],r=e[1],s=n(t);return[s,$[s].prototype,t,r]})).map((([e,r,n,s])=>W(D,t,e,r,n,s))),t),F=(e,t,r)=>{let n=[],s=[e,\"Object\",n];for(r in t)_(n,t,r);return s},W=(e,t,r,s,i,a)=>{if(!e.has(r)){e.add(r);const l=Object.getPrototypeOf(s),c=n(l),u=[],h=Object.getOwnPropertyDescriptors(s);W(e,t,c,l,i,a);for(const e in h)_(u,i,e);t.push([r,c,u,a,o(i)])}},_=(e,t,r,s,o,a)=>{try{i(r)&&isNaN(r[0])&&\"all\"!==r&&(\"function\"==(o=typeof(s=t[r]))?(String(s).includes(\"[native\")||Object.getPrototypeOf(t)[r])&&e.push([r,5]):\"object\"===o&&null!=s?\"Object\"!==(a=n(s))&&self[a]&&e.push([r,s.nodeType||a]):\"symbol\"!==o&&(r.toUpperCase()===r?e.push([r,6,s]):e.push([r,6])))}catch(e){console.warn(e)}},q=e=>{let t,n=[],s=0,i=r($[e]);for(;s<i;s++)t=$[e].key(s),n.push([t,$[e].getItem(t)]);return n},J=(e,r)=>void 0!==e[r]?new e[r](t):0,G=(e,t,r)=>{void 0!==t[r]&&e.push([r,\"Object\",Object.keys(t[r].prototype).map((e=>[e,6])),12])};let Z;(t=>{const r=e.navigator.serviceWorker;return r.getRegistration().then((e=>(r.addEventListener(\"message\",(t=>{return r=t.data,n=t=>e.active&&e.active.postMessage(t),P(Z,r).then(n);var r,n})),(e,t)=>{0===t[0]?e.postMessage([1,H()]):2===t[0]?e.postMessage([3,V()]):((e,t,r)=>{4===t[0]?k(e,a(),$):(r=m[t[1]])&&(7===t[0]?requestAnimationFrame((()=>O(e,r))):6===t[0]&&((e,t,r,n,s)=>{(s=t.U.document.querySelector(`[data-ptid=\"${r}\"]`))&&(n?s.dataset.pterror=n:s.type+=\"-x\",delete s.dataset.ptid),O(e,t)})(e,r,t[2],t[3]))})(e,t)})))})().then((e=>{e&&(Z=new Worker(URL.createObjectURL(new Blob([\\'/* Partytown 0.7.4 - MIT builder.io */\\\\n(e=>{const t=Symbol(),r=Symbol(),n=Symbol(),i=Symbol(),s=Symbol(),o=Symbol(),a=Symbol(),l=Symbol(),c=new Map,$={},d=new WeakMap,u=[],h={},p=new Map,g=new Map,m={},f=new Map,w=new Map,y=\"about:blank\",v=e=>e.split(\",\"),S=e=>{if(e=h.C+e,new URL(e).origin!=location.origin)throw\"Invalid \"+e;return e},I=v(\"clientWidth,clientHeight,clientTop,clientLeft,innerWidth,innerHeight,offsetWidth,offsetHeight,offsetTop,offsetLeft,outerWidth,outerHeight,pageXOffset,pageYOffset,scrollWidth,scrollHeight,scrollTop,scrollLeft\"),b=v(\"childElementCount,children,firstElementChild,lastElementChild,nextElementSibling,previousElementSibling\"),M=v(\"insertBefore,remove,removeChild,replaceChild\"),T=v(\"className,width,height,hidden,innerHTML,innerText,textContent\"),E=v(\"setAttribute,setAttributeNS,setProperty\"),N=v(\"addEventListener,dispatchEvent,removeEventListener\"),x=N.concat(E,v(\"add,observe,remove,unobserve\")),L=/^[A-Z_]([A-Z0-9-]*[A-Z0-9])?$/,C=()=>{},R=e=>e.length,H=e=>{var t,r,n;try{const r=null===(t=null==e?void 0:e.constructor)||void 0===t?void 0:t.name;if(r)return r}catch(e){}try{const t=null===(n=null===(r=null==e?void 0:e.__zone_symbol__originalInstance)||void 0===r?void 0:r.constructor)||void 0===n?void 0:n.name;if(t)return t}catch(e){}return\"\"},W=[],P=()=>Math.round(Math.random()*Number.MAX_SAFE_INTEGER).toString(36),A=\"text/partytown\",O=(e,t,r)=>Object.defineProperty(e,t,{...r,configurable:!0}),j=(e,t)=>O(e,\"name\",{value:t}),k=(e,t,r)=>O(e.prototype,t,r),D=(e,t)=>Object.defineProperties(e.prototype,t),U=(e,t,r)=>k(e,t,{value:r,writable:!0}),_=(e,t)=>t in e[o],B=(e,t)=>e[o][t],F=(e,t,r)=>e[o][t]=r,V=(e,t,r,n,i)=>(!(i=c.get(t))&&r&&m[e]&&(i=m[e].k(r,t,n),c.set(t,i)),i),z=(e,t)=>U(e,\"nodeType\",t),X=(e,t)=>t.map((t=>k(e,t,{get(){let e=q(this,t),r=w.get(e);return r||(r=de(this,[t]),w.set(e,r)),r}}))),q=(e,n,i)=>[e[t],e[r],n,...(i||W).map((e=>String(e&&e[t]?e[r]:e)))].join(\".\"),G=(e,t)=>v(t).map((t=>k(e,t,{get(){return _(this,t)||F(this,t,de(this,[t])),B(this,t)},set(e){B(this,t)!==e&&ue(this,[t],e),F(this,t,e)}}))),J=e=>I.map((t=>k(e,t,{get(){const e=f.get(q(this,t));if(\"number\"==typeof e)return e;const r=de(this,[t],I);return r&&\"object\"==typeof r?(Object.entries(r).map((([e,t])=>f.set(q(this,e),t))),r[t]):r}}))),Z=(e,t)=>t.map((t=>{e.prototype[t]=function(...e){let r=q(this,t,e),n=f.get(r);return n||(n=he(this,[t],e),f.set(r,n)),n}})),Y=(e,n,i,s,o)=>{return void 0!==i&&(o=typeof i)?\"string\"===o||\"boolean\"===o||\"number\"===o||null==i?[0,i]:\"function\"===o?[4,{V:e,w:n,L:(a=i,(l=d.get(a))||(d.set(a,l=P()),$[l]=a),l)}]:(s=s||new Set)&&Array.isArray(i)?s.has(i)?[1,[]]:s.add(i)&&[1,i.map((t=>Y(e,n,t,s)))]:\"object\"===o?i[r]?[3,[i[t],i[r]]]:i instanceof Event?[5,Q(e,n,i,!1,s)]:K&&i instanceof TrustedHTML?[0,i.toString()]:i instanceof ArrayBuffer?[8,i]:ArrayBuffer.isView(i)?[9,i.buffer,H(i)]:[2,Q(e,n,i,!0,s)]:void 0:i;var a,l},K=\"undefined\"!=typeof TrustedHTML,Q=(e,t,r,n,i,s,o,a)=>{if(s={},!i.has(r))for(o in i.add(r),r)a=r[o],(n||\"function\"!=typeof a)&&(s[o]=Y(e,t,a,i));return s},ee=(e,n)=>e?Y(e[t],e[r],n):[0,n],te=(e,t,r,n,i,s,o,a)=>{if(n){if(i=n[0],s=n[1],0===i||11===i||12===i)return s;if(4===i)return ne(r,s);if(6===i)return e&&r.length>0?(...t)=>he(m[e].U,r,t,1):C;if(3===i)return re(s);if(7===i)return new se(s.map(re));if(10===i)return new oe(s);if(1===i)return s.map((n=>te(e,t,r,n)));if(14===i)return new ie(s);for(a in o={},s)o[a]=te(e,t,[...r,a],s[a]);if(13===i)return new m[e].U.CSSStyleDeclaration(e,t,r,o);if(5===i){if(\"message\"===o.type&&o.origin){let e,t=JSON.stringify(o.data),r=u.find((e=>e.m===t));r&&(e=m[r.V],e&&(o.source=e.U,o.origin=e.E.origin))}return new Proxy(new Event(o.type,o),{get:(e,t)=>t in o?o[t]:\"function\"==typeof e[String(t)]?C:e[String(t)]})}if(2===i)return o}},re=([e,t,r])=>t===e&&m[e]?m[e].U:V(e,t,r),ne=(e,{V:t,w:r,G:n,L:i})=>($[i]||d.set($[i]=function(...i){const s=V(t,r,n);return he(s,e,i)},i),$[i]);class ie extends Error{constructor(e){super(e.message),this.name=e.name,this.message=e.message,this.stack=e.stack}}class se{constructor(e){(this._=e).map(((e,t)=>this[t]=e))}entries(){return this._.entries()}forEach(e,t){this._.map(e,t)}item(e){return this[e]}keys(){return this._.keys()}get length(){return R(this._)}values(){return this._.values()}[Symbol.iterator](){return this._[Symbol.iterator]()}}const oe=class{constructor(e){this.name=e[0],this.value=e[1]}get nodeName(){return this.name}get nodeType(){return 2}},ae=(e,t,r)=>console.warn(`Partytown unable to ${e} cross-origin ${t}: `+r.E),le=[],ce=(e,n,i,o,a,l)=>{if(e[s]){if(le.push({V:e[t],w:e[r],a:[...e[s],...n],d:o,r:a}),3===i)h.K([12,{F:P(),Q:[...le]}],l?[l instanceof ArrayBuffer?l:l.buffer]:void 0),le.length=0;else if(1===i)return $e(!0);h.c=setTimeout($e,20)}},$e=e=>{if(clearTimeout(h.c),R(le)){const t=le[R(le)-1],r={F:P(),Q:[...le]};if(le.length=0,e){const e=((e,t)=>{const r=new XMLHttpRequest;return r.open(\"POST\",S(\"proxytown\"),!1),r.send(JSON.stringify(t)),JSON.parse(r.responseText)})(0,r),n=e.z,i=te(t.V,t.w,t.a,e.M);if(e.p){if(n)return Promise.reject(e.p);throw new Error(e.p)}return n?Promise.resolve(i):i}h.K([12,r])}},de=(e,t,r,n)=>h.i.get&&(n=h.i.get(ge(e,t)))!==a?n:n=ce(e,t,1,void 0,r),ue=(e,t,r,n)=>{if(h.i.set){if((n=h.i.set({value:r,prevent:l,...ge(e,t)}))===l)return;n!==a&&(r=n)}T.some((e=>t.includes(e)))&&(f.clear(),t[t.length-1]),t=[...t,ee(e,r),0],ce(e,t,2)},he=(e,t,r,n,i,s,o,l)=>h.i.apply&&(o=h.i.apply({args:r,...ge(e,t)}))!==a?o:(l=t[R(t)-1],t=[...t,ee(e,r)],n=n||(x.includes(l)?2:1),\"setAttribute\"===l&&_(e,r[0])?F(e,r[0],r[1]):M.includes(l)?(f.clear(),w.clear()):E.includes(l)&&(n=2,f.clear()),o=ce(e,t,n,i,void 0,s)),pe=(e,t,r)=>{ce(e,[1,t,ee(e,r)],1)},ge=(e,r)=>({name:r.join(\".\"),continue:a,nodeName:e[n],constructor:H(e),instance:e,window:m[e[t]].U}),me=(e,t,r,n,i)=>{let s,o,a=t=>((t=r.get(e.origin))||r.set(e.origin,t=[]),t),l=e=>a().findIndex((t=>t[fe]===e)),c={getItem:e=>(s=l(e),s>-1?a()[s][we]:null),setItem(r,o){s=l(r),s>-1?a()[s][we]=o:a().push([r,o]),n?he(e,[t,\"setItem\"],[r,o],2):ae(\"set\",t,i)},removeItem(r){s=l(r),s>-1&&a().splice(s,1),n?he(e,[t,\"removeItem\"],[r],2):ae(\"remove\",t,i)},key:e=>(o=a()[e],o?o[fe]:null),clear(){a().length=0,n?he(e,[t,\"clear\"],W,2):ae(\"clear\",t,i)},get length(){return a().length}};e[t]=new Proxy(c,{get:(e,t)=>Reflect.has(e,t)?Reflect.get(e,t):e.getItem(t),set:(e,t,r)=>(e.setItem(t,r),!0),has:(e,t)=>!!Reflect.has(e,t)||\"string\"==typeof t&&null!==e.getItem(t),deleteProperty:(e,t)=>(e.removeItem(t),!0)})},fe=0,we=1,ye=(e,t,r)=>{e[r]=j(class extends t{constructor(e,t,r,i){return super(e,t,r,i||{}),new Proxy(this,{get:(e,t)=>e[t]?e[t]:(e[t]||\"string\"!=typeof t||e[n][t]||(e[n][t]=de(e,[t])),e[n][t]),set:(e,t,r)=>(e[n][t]=r,ue(e,[t],r),f.clear(),!0)})}setProperty(...e){this[n][e[0]]=e[1],he(this,[\"setProperty\"],e,2),e[0],f.clear()}getPropertyValue(e){return this[e]}removeProperty(e){let t=this[n][e];return he(this,[\"removeProperty\"],[e],2),f.clear(),this[n][e]=void 0,t}},r)},ve=(e,t)=>{e[t]=j(class{constructor(e){this.ownerNode=e}get cssRules(){const e=this.ownerNode;return new Proxy({},{get(t,r){const n=String(r);return\"item\"===n?t=>Ie(e,t):\"length\"===n?Se(e).length:isNaN(n)?t[r]:Ie(e,n)}})}insertRule(e,t){const r=Se(this.ownerNode);return(t=void 0===t?0:t)>=0&&t<=r.length&&(he(this.ownerNode,[\"sheet\",\"insertRule\"],[e,t],2),r.splice(t,0,0)),this.ownerNode,f.clear(),t}deleteRule(e){he(this.ownerNode,[\"sheet\",\"deleteRule\"],[e],2),Se(this.ownerNode).splice(e,1),this.ownerNode,f.clear()}get type(){return\"text/css\"}},t);const r={sheet:{get(){return new e[t](this)}}};D(e.HTMLStyleElement,r)},Se=(e,t)=>((t=B(e,2))||(t=de(e,[\"sheet\",\"cssRules\"]),F(e,2,t)),t),Ie=(e,t,r)=>(0===(r=Se(e))[t]&&(r[t]=de(e,[\"sheet\",\"cssRules\",parseInt(t,10)])),r[t]),be=\"0.7.4\",Me=(e,t,r,n,i)=>{try{e.l=t,Te(e,r)}catch(e){console.error(r,e),i=String(e.stack||e)}return e.l=\"\",i},Te=(e,t,r)=>{e.N=1,t=`with(this){${t.replace(/\\\\\\\\bthis\\\\\\\\b/g,\"(thi$(this)?window:this)\").replace(/\\\\\\\\/\\\\\\\\/# so/g,\"//Xso\")}\\\\\\\\n;function thi$(t){return t===this}};${(h.i.globalFns||[]).filter((e=>/[a-zA-Z_$][0-9a-zA-Z_$]*/.test(e))).map((e=>`(typeof ${e}==\\\\\\'function\\\\\\'&&(this.${e}=${e}))`)).join(\";\")};`+(r?\"\\\\\\\\n//# sourceURL=\"+r:\"\"),e.A||(t=t.replace(/.postMessage\\\\\\\\(/g,`.postMessage(\\\\\\'${e.V}\\\\\\',`)),new Function(t).call(e.U),e.N=0},Ee=(e,t,r)=>{(r=B(e,t))&&setTimeout((()=>r.map((e=>e({type:t})))))},Ne=(e,t,r,n,i,s)=>{for(n=e.E;!n.host&&(n=(e=m[e.J]).E,e.V!==e.J););return i=new URL(t||\"\",n),r&&h.i.resolveUrl&&(s=h.i.resolveUrl(i,n,r))?s:i},xe=(e,t,r)=>Ne(e,t,r)+\"\",Le=()=>`<script src=\"${S(\"partytown.js?v=\"+be)}\"><\\\\\\\\/script>`,Ce=e=>class{constructor(){this.s=\"\",this.l=[],this.e=[],this.style={}}get src(){return this.s}set src(t){this.s=t,fetch(xe(e,t,\"image\"),{mode:\"no-cors\",credentials:\"include\",keepalive:!0}).then((e=>{e.ok||0===e.status?this.l.map((e=>e({type:\"load\"}))):this.e.map((e=>e({type:\"error\"})))}),(()=>this.e.forEach((e=>e({type:\"error\"})))))}addEventListener(e,t){\"load\"===e&&this.l.push(t),\"error\"===e&&this.e.push(t)}get onload(){return this.l[0]}set onload(e){this.l=[e]}get onerror(){return this.e[0]}set onerror(e){this.e=[e]}},Re={addEventListener:{value(...e){const t=e[0],r=B(this,t)||[];r.push(e[1]),F(this,t,r)}},async:{get:C,set:C},defer:{get:C,set:C},onload:{get(){let e=B(this,\"load\");return e&&e[0]||null},set(e){F(this,\"load\",e?[e]:null)}},onerror:{get(){let e=B(this,\"error\");return e&&e[0]||null},set(e){F(this,\"error\",e?[e]:null)}},getAttribute:{value(e){return\"src\"===e?this.src:he(this,[\"getAttribute\"],[e])}},setAttribute:{value(e,t){He.includes(e)?this[e]=t:he(this,[\"setAttribute\"],[e,t])}}},He=v(\"src,type\"),We=(e,t)=>{const r={innerHTML:Pe,innerText:Pe,src:{get(){return B(this,4)||\"\"},set(e){const r=xe(t,e,null),n=h.i;e=xe(t,e,\"script\"),F(this,4,e),ue(this,[\"src\"],e),r!==e&&ue(this,[\"dataset\",\"ptsrc\"],r),this.type&&n.loadScriptsOnMainThread&&n.loadScriptsOnMainThread.some((t=>t===e))&&ue(this,[\"type\"],\"text/javascript\")}},textContent:Pe,type:{get(){return de(this,[\"type\"])},set(e){Ae(e)||(F(this,5,e),ue(this,[\"type\"],e))}},...Re};D(e,r)},Pe={get(){const e=de(this,[\"type\"]);return Ae(e)?B(this,3)||\"\":de(this,[\"innerHTML\"])},set(e){F(this,3,e)}},Ae=e=>!e||\"text/javascript\"===e,Oe=(e,i,s)=>{const o=h.i,a=j(class extends s{appendChild(e){return this.insertBefore(e,null)}get href(){}set href(e){}insertBefore(e,s){var a,l;const c=e[t]=this[t],$=e[r],d=e[n],u=\"SCRIPT\"===d,p=\"IFRAME\"===d;if(u){const t=B(e,3),r=B(e,5);if(t){if(Ae(r)){const r=e.id;if(r&&(null===(l=null===(a=o.loadScriptsOnMainThread)||void 0===a?void 0:a.includes)||void 0===l?void 0:l.call(a,r)))ue(e,[\"type\"],\"text/javascript\");else{const r=Me(i,$,t,0,\"\"),n=r?\"pterror\":\"ptid\",s=r||$;ue(e,[\"type\"],A+\"-x\"),ue(e,[\"dataset\",n],s)}}ue(e,[\"innerHTML\"],t)}}if(he(this,[\"insertBefore\"],[e,s],2),p){const t=B(e,0);if(t&&t.startsWith(\"javascript:\")){const e=t.split(\"javascript:\")[1];Me(i,$,e,0,\"\")}((e,t)=>{let r,n,i=0,s=()=>{m[e]&&m[e].x&&!m[e].y?(r=B(t,1)?\"error\":\"load\",n=B(t,r),n&&n.map((e=>e({type:r})))):i++>2e3?(n=B(t,\"error\"),n&&n.map((e=>e({type:\"error\"})))):setTimeout(s,9)};s()})($,e)}return u&&($e(!0),h.K([7,c])),e}get nodeName(){return\"#s\"===this[n]?\"#document-fragment\":this[n]}get nodeType(){return 3}get ownerDocument(){return i.n}},\"Node\");X(a,v(\"childNodes,firstChild,isConnected,lastChild,nextSibling,parentElement,parentNode,previousSibling\")),e.Node=a},je=v(\"AUDIO,CANVAS,VIDEO\"),ke=v(\"Audio,MediaSource\"),De=(e,r,n)=>{D(e,{body:{get:()=>r.e},cookie:{get(){return r.A?de(this,[\"cookie\"]):(ae(\"get\",\"cookie\",r),\"\")},set(e){r.A&&ue(this,[\"cookie\"],e)}},createElement:{value(e){if(e=e.toUpperCase(),!L.test(e))throw e+\" not valid\";const r=\"IFRAME\"===e,n=this[t],i=(r?\"f_\":\"\")+P();he(this,[\"createElement\"],[e],2,i);const s=V(n,i,e);if(r)et({V:i,J:n,S:y},!0).U.fetch=fetch,ue(s,[\"srcdoc\"],Le());else if(\"SCRIPT\"===e){const e=B(s,5);Ae(e)&&ue(s,[\"type\"],A)}return s}},createElementNS:{value(e,r){const n=P(),i=V(this[t],n,r,e);return he(this,[\"createElementNS\"],[e,r],2,n),i}},createTextNode:{value(e){const r=this[t],n=P(),i=V(r,n,\"#text\");return he(this,[\"createTextNode\"],[e],2,n),i}},createEvent:{value:e=>new Event(e)},currentScript:{get(){return r.l?V(this[t],r.l,\"SCRIPT\"):null}},defaultView:{get:()=>n?null:r.U},documentElement:{get:()=>r.o},getElementsByTagName:{value(e){return\"BODY\"===(e=e.toUpperCase())?[r.e]:\"HEAD\"===e?[r.s]:he(this,[\"getElementsByTagName\"],[e])}},head:{get:()=>r.s},images:{get(){return de(this,[\"images\"])}},implementation:{get(){return{hasFeature:()=>!0,createHTMLDocument:e=>{const t=P();return he(this,[\"implementation\",\"createHTMLDocument\"],[e],1,{V:t}),et({V:t,J:t,S:r.E+\"\",T:\"hidden\"},!0,!0).n}}}},location:{get:()=>r.E,set(e){r.E.href=e+\"\"}},nodeType:{value:9},parentNode:{value:null},parentElement:{value:null},readyState:{value:\"complete\"},visibilityState:{get:()=>r.T||\"visible\"}}),G(e,\"compatMode,referrer,forms\")},Ue=(e,t)=>{D(e,{parentElement:{get(){return this.parentNode}},parentNode:{get:()=>t.o}})},_e=(e,t)=>{D(e,{localName:{get(){return this[n].toLowerCase()}},namespaceURI:{get(){return this[i]||\"http://www.w3.org/1999/xhtml\"}},nodeType:{value:1},tagName:{get(){return this[n]}}}),X(e,b),G(e,\"id\"),J(t),Z(t,v(\"getClientRects,getBoundingClientRect\"))},Be=(e,t)=>{const r={};v(\"hash,host,hostname,href,origin,pathname,port,protocol,search\").map((e=>{r[e]={get(){let r,n=B(this,4);return\"string\"!=typeof n&&(r=de(this,[\"href\"]),F(this,4,r),n=new URL(r)[e]),Ne(t,n,null)[e]},set(r){let n;if(\"href\"===e)if((e=>{try{return new URL(e),!0}catch(e){return!1}})(r))n=new URL(r);else{const e=t.E.href;n=Ne(t,e,null),n.href=new URL(r+\"\",n.href)}else n=Ne(t,this.href,null),n[e]=r;F(this,4,n.href),ue(this,[\"href\"],n.href)}}})),D(e,r)},Fe=(e,t)=>{const r={contentDocument:{get(){return qe(this).n}},contentWindow:{get(){return qe(this).U}},src:{get(){let e=B(this,0);return e&&e.startsWith(\"javascript:\")?e:(e=qe(this).E.href,e.startsWith(\"about:\")?\"\":e)},set(e){if(e)if(e.startsWith(\"javascript:\"))F(this,0,e);else if(!e.startsWith(\"about:\")){let t,r=new XMLHttpRequest,n=qe(this);n.E.href=e=xe(n,e,\"iframe\"),n.y=1,F(this,1,void 0),r.open(\"GET\",e,!1),r.send(),t=r.status,t>199&&t<300?(ue(this,[\"srcdoc\"],`<base href=\"${e}\">`+r.responseText.replace(ze,((e,t)=>{const r=[];let n,i=!1;for(;n=Xe.exec(t);){let[e]=n;e.startsWith(\"type=\")&&(i=!0,e=e.replace(/(application|text)\\\\\\\\/javascript/,A)),r.push(e)}return i||r.push(\\\\\\'type=\"text/partytown\"\\\\\\'),`<script ${r.join(\" \")}>`}))+Le()),$e(!0),h.K([7,n.V])):(F(this,1,t),n.y=0)}}},...Re};D(e,r)},Ve=\"((?:\\\\\\\\\\\\\\\\w|-)+(?:=(?:(?:\\\\\\\\\\\\\\\\w|-)+|\\\\\\'[^\\\\\\']*\\\\\\'|\\\\\\\\\"[^\\\\\\\\\"]*\\\\\\\\\")?)?)\",ze=new RegExp(`<script\\\\\\\\\\\\\\\\s*((${Ve}\\\\\\\\\\\\\\\\s*)*)>`,\"mg\"),Xe=new RegExp(Ve,\"mg\"),qe=e=>{const n=e[r];return m[n]||et({V:n,J:e[t],S:de(e,[\"src\"])||y},!0),m[n]},Ge=e=>{const t=(e,t)=>{const{a:r,b:n,c:i,d:s,e:o,f:a}=he(e,[t],W);return new DOMMatrixReadOnly([r,n,i,s,o,a])},r={...e,getCTM:{value:function(){return t(this,\"getCTM\")}},getScreenCTM:{value:function(){return t(this,\"getScreenCTM\")}}};D(e,r)},Je=(e,t)=>{e.NamedNodeMap=j(class extends t{constructor(e,t,r){return super(e,t,r),new Proxy(this,{get(e,t){const r=Ye[t];return r?r.bind(e,[t]):de(e,[t])},set(e,t,r){if(Ye[t])throw new Error(\"Can\\\\\\'t set read-only property: \"+String(t));return ue(e,[t],r),!0}})}},\"NamedNodeMap\")};function Ze(e,...t){return he(this,e,t,1)}const Ye={getNamedItem:Ze,getNamedItemNS:Ze,item:Ze,removeNamedItem:Ze,removeNamedItemNS:Ze,setNamedItem:Ze,setNamedItemNS:Ze},Ke=(a,l,c,$,d,f)=>{let w,I,M;const T=class{constructor(e,l,c,$,d){this[t]=e||a,this[r]=l||w||P(),this[s]=c||[],this[n]=$||I,this[i]=d||M,this[o]={},w=I=M=void 0}},E=new(j(class extends URL{assign(){}reload(){}replace(){}},\"Location\"))(c),x=E.origin===h.I||E.origin===y,L=l===a,C={},W=()=>{let e,t,r=[];for(e in m)t=m[e],t.J!==a||t.B||r.push(t);return r},A=j(class extends T{constructor(){super(a,a);let n,i,o=this,c=0,u=()=>{c||((h.u||(e.g=[de,ue,he,pe,D,P,t,r,s],h.t(S(\"partytown-media.js?v=\"+be)),h.u=e.f,delete e.f),h.u)(T,Y,C,o,ke),c=1)},m={},y=(e,t,r)=>{je.includes(e)&&u();const n=m[e]?m[e]:e.includes(\"-\")?m.UNKNOWN:m.I;return w=t,I=e,M=r,new n};var N,R;if(o.Window=A,o.name=name+a,Oe(o,C,T),(e=>{e.NodeList=j(se,\"NodeList\")})(o),Je(o,T),ye(o,T,\"CSSStyleDeclaration\"),((e,t,r)=>{e[r]=j(class extends t{now(){return performance.now()}},r)})(o,T,\"Performance\"),((e,t)=>{const r=\"customElements\",n=new Map;e.customElements={define(i,s,o){n.set(i,s),t[i.toUpperCase()]=s;const a=[s.name,s.observedAttributes];he(e,[r,\"define\"],[i,a,o])},get:t=>n.get(t)||he(e,[r,\"get\"],[t]),whenDefined:t=>n.has(t)?Promise.resolve():he(e,[r,\"whenDefined\"],[t]),upgrade:t=>he(e,[r,\"upgrade\"],[t])}})(o,m),h.v.map((([e,t,n,i,l])=>{const c=Qe[e]?q:\"EventTarget\"===t?Y:\"Object\"===t?T:o[t],$=o[e]=j(12===i?class extends T{constructor(...t){super(),pe(this,e,t)}}:o[e]||class extends c{},e);l&&(m[l]=$),n.map((([e,t,n])=>{e in $.prototype||e in c.prototype||(\"string\"==typeof t?k($,e,{get(){if(!_(this,e)){const n=this[r],i=[...this[s],e],l=o[t];l&&F(this,e,new l(a,n,i))}return B(this,e)},set(t){F(this,e,t)}}):5===t?U($,e,(function(...t){return he(this,[e],t)})):t>0&&(void 0!==n?U($,e,n):k($,e,{get(){return de(this,[e])},set(t){return ue(this,[e],t)}})))}))})),v(\"atob,btoa,crypto,indexedDB,setTimeout,setInterval,clearTimeout,clearInterval\").map((t=>{delete A.prototype[t],t in o||(n=e[t],null!=n&&(o[t]=\"function\"!=typeof n||n.toString().startsWith(\"class\")?n:n.bind(e)))})),Object.getOwnPropertyNames(e).map((t=>{t in o||(o[t]=e[t])})),ke.map((e=>O(o,e,{get:()=>(u(),o[e])}))),\"trustedTypes\"in e&&(o.trustedTypes=e.trustedTypes),_e(o.Element,o.HTMLElement),De(o.Document,C,f),N=o.DocumentFragment,z(N,11),X(N,b),Be(o.HTMLAnchorElement,C),R=o.HTMLFormElement,D(R,{}),G(R,\"elements\"),Fe(o.HTMLIFrameElement),We(o.HTMLScriptElement,C),Ge(o.SVGGraphicsElement),Ue(o.HTMLHeadElement,C),Ue(o.HTMLBodyElement,C),((e,t)=>{D(e,{parentElement:{value:null},parentNode:{get:()=>t.n}})})(o.HTMLHtmlElement,C),ve(o,\"CSSStyleSheet\"),z(o.Comment,8),z(o.DocumentType,10),Object.assign(C,{V:a,J:l,U:new Proxy(o,{get:(e,t)=>{var r;if(\"string\"!=typeof t||isNaN(t))return(null===(r=h.i.mainWindowAccessors)||void 0===r?void 0:r.includes(t))?de(this,[t]):e[t];{let e=W()[t];return e?e.U:void 0}},has:()=>!0}),n:y(\"#document\",a+\".d\"),o:y(\"HTML\",a+\".e\"),s:y(\"HEAD\",a+\".h\"),e:y(\"BODY\",a+\".b\"),E:E,T:$,A:x,B:L,k:y}),o.requestAnimationFrame=e=>setTimeout((()=>e(performance.now())),9),o.cancelAnimationFrame=e=>clearTimeout(e),o.requestIdleCallback=(e,t)=>(t=Date.now(),setTimeout((()=>e({didTimeout:!1,timeRemaining:()=>Math.max(0,50-(Date.now()-t))})),1)),o.cancelIdleCallback=e=>clearTimeout(e),me(o,\"localStorage\",p,x,C),me(o,\"sessionStorage\",g,x,C),x||(o.indexeddb=void 0),d)i={},o.history={pushState(e){i=e},replaceState(e){i=e},get state(){return i},length:0},o.indexeddb=void 0;else{const e=o.history.pushState.bind(o.history),t=o.history.replaceState.bind(o.history);o.history.pushState=(t,r,n)=>{!1!==C.$propagateHistoryChange$&&e(t,r,n)},o.history.replaceState=(e,r,n)=>{!1!==C.$propagateHistoryChange$&&t(e,r,n)}}o.Worker=void 0}addEventListener(...e){\"load\"===e[0]?C.N&&setTimeout((()=>e[1]({type:\"load\"}))):he(this,[\"addEventListener\"],e,2)}get body(){return C.e}get document(){return C.n}get documentElement(){return C.o}fetch(e,t){return e=\"string\"==typeof e||e instanceof URL?String(e):e.url,fetch(xe(C,e,\"fetch\"),t)}get frames(){return C.U}get frameElement(){return L?null:V(l,a,\"IFRAME\")}get globalThis(){return C.U}get head(){return C.s}get length(){return W().length}get location(){return E}set location(e){E.href=e+\"\"}get Image(){return Ce(C)}get navigator(){return(e=>{let t,r={sendBeacon:(t,r)=>{try{return fetch(xe(e,t,null),{method:\"POST\",body:r,mode:\"no-cors\",keepalive:!0}),!0}catch(e){return console.error(e),!1}}};for(t in navigator)r[t]=navigator[t];return r})(C)}get origin(){return E.origin}set origin(e){}get parent(){for(let e in m)if(m[e].V===l)return m[e].U;return C.U}postMessage(...e){m[e[0]]&&(R(u)>50&&u.splice(0,5),u.push({V:e[0],m:JSON.stringify(e[1])}),e=e.slice(1)),he(this,[\"postMessage\"],e,3)}get self(){return C.U}get top(){for(let e in m)if(m[e].B)return m[e].U;return C.U}get window(){return C.U}get XMLHttpRequest(){const e=XMLHttpRequest,t=String(e),r=j(class extends e{open(...e){e[1]=xe(C,e[1],\"xhr\"),super.open(...e)}set withCredentials(e){}toString(){return t}},H(e));return r.prototype.constructor.toString=()=>t,r}},\"Window\"),q=class extends T{constructor(e,t,r,n){return super(e,t,r,n),new Proxy(this,{get:(e,t)=>de(e,[t]),set:(e,t,r)=>(ue(e,[t],r),!0)})}},Y=class extends T{};return N.map((e=>Y.prototype[e]=function(...t){return he(this,[e],t,2)})),G(A,\"devicePixelRatio\"),J(A),Z(A,[\"getComputedStyle\"]),new A,C},Qe={DOMStringMap:1,NamedNodeMap:1},et=({V:e,J:t,S:r,T:n},i,s)=>(m[e]||(m[e]=Ke(e,t,r,n,i,s)),h.K([7,e]),m[e]),tt=[],rt=t=>{const r=t.data,n=r[0],i=r[1];if(h.x)if(7===n)(async e=>{let t,r=e.V,n=e.w,i=V(r,n,\"SCRIPT\"),s=e.j,o=e.S,a=e.H,l=\"\",c=m[r],$=[\"text/jscript\",\"text/javascript\",\"text/x-javascript\",\"application/javascript\",\"application/x-javascript\",\"text/ecmascript\",\"text/x-ecmascript\",\"application/ecmascript\"];if(o)try{if(o=Ne(c,o,\"script\")+\"\",F(i,4,o),t=await fetch(o),t.ok){let e=t.headers.get(\"content-type\");$.some((t=>{var r,n,i;return null===(i=null===(r=null==e?void 0:e.toLowerCase)||void 0===r?void 0:(n=r.call(e)).includes)||void 0===i?void 0:i.call(n,t)}))&&(s=await t.text(),c.l=n,Te(c,s,a||o)),Ee(i,\"load\")}else l=t.statusText,Ee(i,\"error\")}catch(e){console.error(e),l=String(e.stack||e),Ee(i,\"error\")}else s&&(l=Me(c,n,s,0,l));c.l=\"\",h.K([6,r,n,l])})(i);else if(9===n)(({V:e,w:t,L:r,R:n,b:i})=>{if($[r])try{$[r].apply(te(e,t,[],n),te(e,t,[],i))}catch(e){console.error(e)}})(i);else if(10===n)(({V:e,q:t,b:r})=>{try{let n=m[e].U,i=0,s=R(t);for(;i<s;i++)i+1<s?n=n[t[i]]:n[t[i]].apply(n,te(null,e,[],r))}catch(e){console.error(e)}})(i);else if(5===n)et(i);else if(8===n)m[i].x=1,m[i].y=0;else if(14===n)m[i].T=r[2];else if(13===n){const e=i.V,t=m[e];t.E.href=i.url,function(e,t,r){const n=t.U.history;switch(r.type){case 0:t.$propagateHistoryChange$=!1;try{n.pushState(r.state,\"\",r.newUrl)}catch(e){}t.$propagateHistoryChange$=!0;break;case 1:t.$propagateHistoryChange$=!1;try{n.replaceState(r.state,\"\",r.newUrl)}catch(e){}t.$propagateHistoryChange$=!0}}(i.V,t,i)}else 15===n&&((e,t,r,n,i)=>{const s=V(t,r);s&&\"function\"==typeof s[n]&&s[n].apply(s,i)})(...r);else 1===n?((t=>{const r=h.i=JSON.parse(t.i),n=t.I;h.t=importScripts.bind(e),h.v=t.v,h.C=t.C,h.I=n,h.K=postMessage.bind(e),h.P=t.P,p.set(n,t.D),g.set(n,t.O),e.importScripts=void 0,delete e.postMessage,delete e.WorkerGlobalScope,v(\"resolveUrl,get,set,apply\").map((e=>{r[e]&&(r[e]=new Function(\"return \"+r[e])())}))})(i),h.K([2])):3===n?(h.v=[...h.v,...i],h.x=1,h.K([4]),[...tt].map(rt),tt.length=0):tt.push(t)};e.onmessage=rt,postMessage([0])})(self);\\\\n\\'],{type:\"text/javascript\"})),{name:\"Partytown 🎉\"}),Z.onmessage=t=>{const r=t.data;12===r[0]?P(Z,r[1]):e(Z,r)},$.addEventListener(\"pt1\",(e=>k(Z,f(e.detail.frameElement),e.detail))))}))})(window);\\n</script></head></html>'\n )\n )\n : i.endsWith('proxytown') &&\n n.respondWith(\n (n =>\n new Promise(async s => {\n const i = await n.clone().json(),\n o = await (r =>\n new Promise(async n => {\n const s = [\n ...(await self.clients.matchAll()),\n ].sort((e, t) =>\n e.url > t.url ? -1 : e.url < t.url ? 1 : 0\n )[0]\n if (s) {\n const i = [\n n,\n setTimeout(() => {\n e.delete(r.F), n(t(r, 'Timeout'))\n }, 1e4),\n ]\n e.set(r.F, i), s.postMessage(r)\n } else n(t(r, 'NoParty'))\n }))(i)\n s(r(JSON.stringify(o), 'application/json'))\n }))(s)\n )\n })\n\n```"
}
] |
code_partytown_657f66af
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of partytown/public/~partytown/partytown-atomics.js from the partytown VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\n/* Partytown 0.7.4 - MIT builder.io */\n;(e => {\n const t = () => {},\n r = e => e.length,\n n = e => {\n var t, r, n\n try {\n const r =\n null === (t = null == e ? void 0 : e.constructor) || void 0 === t\n ? void 0\n : t.name\n if (r) return r\n } catch (e) {}\n try {\n const t =\n null ===\n (n =\n null ===\n (r = null == e ? void 0 : e.__zone_symbol__originalInstance) ||\n void 0 === r\n ? void 0\n : r.constructor) || void 0 === n\n ? void 0\n : n.name\n if (t) return t\n } catch (e) {}\n return ''\n },\n s = (e, t) => e.startsWith(t),\n i = e =>\n !(\n s(e, 'webkit') ||\n s(e, 'toJSON') ||\n s(e, 'constructor') ||\n s(e, 'toString') ||\n s(e, '_')\n ),\n o = e => (11 === e.nodeType && e.host ? '#s' : e.nodeName),\n a = () => Math.round(Math.random() * Number.MAX_SAFE_INTEGER).toString(36),\n l = {\n Anchor: 'a',\n DList: 'dl',\n Image: 'img',\n OList: 'ol',\n Paragraph: 'p',\n Quote: 'q',\n TableCaption: 'caption',\n TableCell: 'td',\n TableCol: 'colgroup',\n TableRow: 'tr',\n TableSection: 'tbody',\n UList: 'ul',\n },\n c = { Graphics: 'g', SVG: 'svg' },\n u = Symbol(),\n h = Symbol(),\n d = new Map(),\n p = new Map(),\n m = {},\n g = new WeakMap(),\n f = (e, t) => {\n if (e) return (t = g.get(e)) || (t = e[u]) || v(e, (t = a())), t\n },\n y = (e, t, r, n, s) => {\n if ((r = m[e]) && r.U) {\n if (e === t) return r.U\n if (((n = r.U.document), 'd' === (s = t.split('.').pop()))) return n\n if ('e' === s) return n.documentElement\n if ('h' === s) return n.head\n if ('b' === s) return n.body\n }\n return d.get(t)\n },\n v = (e, t, r) => {\n e &&\n (d.set(t, e),\n (e[u] = t),\n (e[h] = r = Date.now()),\n r > w + 5e3 &&\n (d.forEach((e, t) => {\n e[h] < w && e.nodeType && !e.isConnected && d.delete(t)\n }),\n (w = r)))\n }\n let w = 0\n const $ = e.parent,\n S = document.implementation.createHTMLDocument(),\n b = $.partytown || {},\n E = (b.lib || '/~partytown/') + '',\n T = (e, t, r) => {\n const n = ((e, t) => {\n return (\n (r = e),\n (n = { value: t }),\n Object.defineProperty(r, 'name', { ...n, configurable: !0 })\n )\n var r, n\n })(class extends m[e].U.HTMLElement {}, r[0])\n return (\n 'connectedCallback,disconnectedCallback,attributeChangedCallback,adoptedCallback'\n .split(',')\n .map(\n r =>\n (n.prototype[r] = function (...n) {\n t.postMessage([15, e, f(this), r, n])\n })\n ),\n (n.observedAttributes = r[1]),\n n\n )\n },\n C = (e, t, r, i, a) =>\n void 0 !== t && (i = typeof t)\n ? 'string' === i || 'number' === i || 'boolean' === i || null == t\n ? [0, t]\n : 'function' === i\n ? [6]\n : (r = r || new Set()) && Array.isArray(t)\n ? r.has(t)\n ? [1, []]\n : r.add(t) && [1, t.map(t => C(e, t, r))]\n : 'object' === i\n ? N(t)\n ? [14, { name: t.name, message: t.message, stack: t.stack }]\n : '' === (a = n(t))\n ? [2, {}]\n : 'Window' === a\n ? [3, [e, e]]\n : 'HTMLCollection' === a || 'NodeList' === a\n ? [7, Array.from(t).map(t => C(e, t, r)[1])]\n : a.endsWith('Event')\n ? [5, I(e, t, r)]\n : 'CSSRuleList' === a\n ? [12, Array.from(t).map(M)]\n : s(a, 'CSS') && a.endsWith('Rule')\n ? [11, M(t)]\n : 'CSSStyleDeclaration' === a\n ? [13, I(e, t, r)]\n : 'Attr' === a\n ? [10, [t.name, t.value]]\n : t.nodeType\n ? [3, [e, f(t), o(t)]]\n : [2, I(e, t, r, !0, !0)]\n : void 0\n : t,\n I = (e, t, r, s, o, a, l, c) => {\n if (((a = {}), !r.has(t)))\n for (l in (r.add(t), t))\n i(l) &&\n ((c =\n 'path' === l && n(t).endsWith('Event') ? t.composedPath() : t[l]),\n (s || 'function' != typeof c) &&\n (o || '' !== c) &&\n (a[l] = C(e, c, r)))\n return a\n },\n M = e => {\n let t,\n r = {}\n for (t in e) P.includes(t) && (r[t] = String(e[t]))\n return r\n },\n N = t => t instanceof e.top.Error,\n x = (t, r, n, s) =>\n r\n ? ((n = r[0]),\n (s = r[1]),\n 0 === n\n ? s\n : 4 === n\n ? L(t, s)\n : 1 === n\n ? s.map(e => x(t, e))\n : 3 === n\n ? y(s[0], s[1])\n : 5 === n\n ? R(A(t, s))\n : 2 === n\n ? A(t, s)\n : 8 === n\n ? s\n : 9 === n\n ? new e[r[2]](s)\n : void 0)\n : void 0,\n L = (e, { V: t, w: r, L: n }, s) => (\n (s = p.get(n)) ||\n ((s = function (...s) {\n e.postMessage([9, { V: t, w: r, L: n, R: C(t, this), b: C(t, s) }])\n }),\n p.set(n, s)),\n s\n ),\n R = e => new ('detail' in e ? CustomEvent : Event)(e.type, e),\n A = (e, t, r, n) => {\n for (n in ((r = {}), t)) r[n] = x(e, t[n])\n return r\n },\n P = 'cssText,selectorText,href,media,namespaceURI,prefix,name,conditionText'.split(\n ','\n ),\n U = async (e, t) => {\n let n,\n s,\n i,\n o,\n a,\n l,\n c = { F: t.F },\n u = r(t.Q),\n h = 0\n for (; h < u; h++)\n try {\n ;(l = h === u - 1),\n (n = t.Q[h]),\n (s = n.V),\n (i = n.a),\n !m[s] &&\n s.startsWith('f_') &&\n (await new Promise(e => {\n let t = 0,\n r = () => {\n m[s] || t++ > 1e3 ? e() : requestAnimationFrame(r)\n }\n r()\n })),\n 1 === i[0] && i[1] in m[s].U\n ? v(new m[s].U[i[1]](...x(e, i[2])), n.w)\n : ((o = y(s, n.w)),\n o\n ? ((a = j(e, s, o, i, l, n.r)),\n n.d &&\n ('string' == typeof n.d\n ? v(a, n.d)\n : (m[n.d.V] = { V: n.d.V, U: { document: a } })),\n 'object' == typeof (d = a) &&\n d &&\n d.then &&\n ((a = await a), l && (c.z = !0)),\n l && (c.M = C(s, a)))\n : (c.p = n.w + ' not found'))\n } catch (e) {\n l ? (c.p = String(e.stack || e)) : console.error(e)\n }\n var d\n return c\n },\n j = (e, t, s, i, o, a) => {\n let l,\n c,\n u,\n h,\n d,\n p = 0,\n m = r(i)\n for (; p < m; p++) {\n ;(c = i[p]), (l = i[p + 1]), (u = i[p - 1])\n try {\n if (!Array.isArray(l))\n if ('string' == typeof c || 'number' == typeof c) {\n if (p + 1 === m && a)\n return (d = {}), a.map(e => (d[e] = s[e])), d\n s = s[c]\n } else {\n if (0 === l) return void (s[u] = x(e, c))\n if (\n 'function' == typeof s[u] &&\n ((h = x(e, c)),\n 'define' === u &&\n 'CustomElementRegistry' === n(s) &&\n (h[1] = T(t, e, h[1])),\n 'insertRule' === u &&\n h[1] > r(s.cssRules) &&\n (h[1] = r(s.cssRules)),\n (s = s[u].apply(s, h)),\n 'play' === u)\n )\n return Promise.resolve()\n }\n } catch (e) {\n if (o) throw e\n console.debug(e)\n }\n }\n return s\n },\n H = (e, t) => {\n let n,\n s,\n i,\n o = t.V,\n a = t.U,\n l = a.document\n l && l.body\n ? ((n = l.querySelector(\n 'script[type=\"text/partytown\"]:not([data-ptid]):not([data-pterror]):not([async]):not([defer])'\n )),\n n ||\n (n = l.querySelector(\n 'script[type=\"text/partytown\"]:not([data-ptid]):not([data-pterror])'\n )),\n n\n ? ((n.dataset.ptid = s = f(n, o)),\n (i = { V: o, w: s }),\n n.src\n ? ((i.S = n.src), (i.H = n.dataset.ptsrc || n.src))\n : (i.j = n.innerHTML),\n e.postMessage([7, i]))\n : (t.x ||\n ((t.x = 1),\n ((e, t, n) => {\n let s,\n i,\n o = n._ptf,\n a = (n.partytown || {}).forward || [],\n l = (r, n) =>\n e.postMessage([\n 10,\n { V: t, q: r, b: C(t, Array.from(n)) },\n ])\n if (\n ((n._ptf = void 0),\n a.map(e => {\n ;(i = n),\n e.split('.').map((e, t, n) => {\n i = i[n[t]] =\n t + 1 < r(n)\n ? i[n[t]] || ('push' === n[t + 1] ? [] : {})\n : (...e) => l(n, e)\n })\n }),\n o)\n )\n for (s = 0; s < r(o); s += 2) l(o[s], o[s + 1])\n })(e, o, a),\n l.dispatchEvent(new CustomEvent('pt0'))),\n e.postMessage([8, o])))\n : requestAnimationFrame(() => H(e, t))\n },\n O = (e, t, r) => {\n if (!g.has(r)) {\n g.set(r, t)\n const n = r.document,\n s = r.history,\n i = g.get(r.parent)\n let o = !1\n const a = [],\n l = e => {\n o ? e() : a.push(e)\n },\n c = () => {\n e.postMessage([\n 5,\n { V: t, J: i, S: n.baseURI, T: n.visibilityState },\n ]),\n setTimeout(() => {\n ;(o = !0),\n a.forEach(e => {\n e()\n })\n })\n },\n u = s.pushState.bind(s),\n h = s.replaceState.bind(s),\n d = (r, s, i, o) => () => {\n setTimeout(() => {\n e.postMessage([\n 13,\n {\n V: t,\n type: r,\n state: s,\n url: n.baseURI,\n newUrl: i,\n oldUrl: o,\n },\n ])\n })\n }\n ;(s.pushState = (e, t, r) => {\n u(e, t, r), l(d(0, e, null == r ? void 0 : r.toString()))\n }),\n (s.replaceState = (e, t, r) => {\n h(e, t, r), l(d(1, e, null == r ? void 0 : r.toString()))\n }),\n r.addEventListener('popstate', e => {\n l(d(2, e.state))\n }),\n r.addEventListener('hashchange', e => {\n l(d(3, {}, e.newURL, e.oldURL))\n }),\n r.addEventListener('ptupdate', () => {\n H(e, m[t])\n }),\n n.addEventListener('visibilitychange', () =>\n e.postMessage([14, t, n.visibilityState])\n ),\n (m[t] = { V: t, U: r }),\n 'complete' === n.readyState ? c() : r.addEventListener('load', c)\n }\n },\n k = () => {\n const e = Object.getOwnPropertyNames($)\n .map(e =>\n ((e, t, r, n) => {\n if ((r = t.match(/^(HTML|SVG)(.+)Element$/)))\n return (\n (n = r[2]),\n 'S' == t[0]\n ? e.createElementNS(\n 'http://www.w3.org/2000/svg',\n c[n] || n.slice(0, 2).toLowerCase() + n.slice(2)\n )\n : e.createElement(l[n] || n)\n )\n })(S, e)\n )\n .filter(e => e)\n .map(e => [e])\n return B(e, [])\n },\n V = new Set(['Object']),\n B = (e, t) => (\n e\n .filter(e => e[0])\n .map(e => {\n const t = e[0],\n r = e[1],\n s = n(t)\n return [s, $[s].prototype, t, r]\n })\n .map(([e, r, n, s]) => D(V, t, e, r, n, s)),\n t\n ),\n F = (e, t, r) => {\n let n = [],\n s = [e, 'Object', n]\n for (r in t) W(n, t, r)\n return s\n },\n D = (e, t, r, s, i, a) => {\n if (!e.has(r)) {\n e.add(r)\n const l = Object.getPrototypeOf(s),\n c = n(l),\n u = [],\n h = Object.getOwnPropertyDescriptors(s)\n D(e, t, c, l, i, a)\n for (const e in h) W(u, i, e)\n t.push([r, c, u, a, o(i)])\n }\n },\n W = (e, t, r, s, o, a) => {\n try {\n i(r) &&\n isNaN(r[0]) &&\n 'all' !== r &&\n ('function' == (o = typeof (s = t[r]))\n ? (String(s).includes('[native') || Object.getPrototypeOf(t)[r]) &&\n e.push([r, 5])\n : 'object' === o && null != s\n ? 'Object' !== (a = n(s)) && self[a] && e.push([r, s.nodeType || a])\n : 'symbol' !== o &&\n (r.toUpperCase() === r ? e.push([r, 6, s]) : e.push([r, 6])))\n } catch (e) {\n console.warn(e)\n }\n },\n _ = e => {\n let t,\n n = [],\n s = 0,\n i = r($[e])\n for (; s < i; s++) (t = $[e].key(s)), n.push([t, $[e].getItem(t)])\n return n\n },\n J = (e, r) => (void 0 !== e[r] ? new e[r](t) : 0)\n let q\n ;(async e => {\n const t = new SharedArrayBuffer(1073741824),\n r = new Int32Array(t)\n return (n, s) => {\n const i = s[0],\n o = s[1]\n if (0 === i) {\n const e = (() => {\n const e = S.createElement('i'),\n t = S.createTextNode(''),\n r = S.createComment(''),\n n = S.createDocumentFragment(),\n s = S.createElement('p').attachShadow({ mode: 'open' }),\n i = J($, 'IntersectionObserver'),\n o = J($, 'MutationObserver'),\n a = J($, 'ResizeObserver'),\n l = $.performance,\n c = $.screen,\n u = [\n [$.history],\n [l],\n [l.navigation],\n [l.timing],\n [c],\n [c.orientation],\n [$.visualViewport],\n [i, 12],\n [o, 12],\n [a, 12],\n [t],\n [r],\n [n],\n [s],\n [e],\n [e.attributes],\n [e.classList],\n [e.dataset],\n [e.style],\n [S],\n [S.doctype],\n ],\n h = [F('Window', $), F('Node', t)],\n d = {\n i: JSON.stringify(\n b,\n (e, t) => (\n 'function' == typeof t &&\n (t = String(t)).startsWith(e + '(') &&\n (t = 'function ' + t),\n t\n )\n ),\n v: B(u, h),\n C: new URL(E, $.location) + '',\n I: origin,\n D: _('localStorage'),\n O: _('sessionStorage'),\n }\n return (\n ((e, t, r) => {\n void 0 !== t[r] &&\n e.push([\n r,\n 'Object',\n Object.keys(t[r].prototype).map(e => [e, 6]),\n 12,\n ])\n })(d.v, $, 'IntersectionObserverEntry'),\n d\n )\n })()\n ;(e.P = t), n.postMessage([1, e])\n } else\n 2 === s[0]\n ? n.postMessage([3, k()])\n : 11 === i\n ? e(o, e => {\n const t = JSON.stringify(e),\n n = t.length\n for (let e = 0; e < n; e++) r[e + 1] = t.charCodeAt(e)\n ;(r[0] = n), Atomics.notify(r, 0)\n })\n : ((e, t, r) => {\n 4 === t[0]\n ? O(e, a(), $)\n : (r = m[t[1]]) &&\n (7 === t[0]\n ? requestAnimationFrame(() => H(e, r))\n : 6 === t[0] &&\n ((e, t, r, n, s) => {\n ;(s = t.U.document.querySelector(\n `[data-ptid=\"${r}\"]`\n )) &&\n (n ? (s.dataset.pterror = n) : (s.type += '-x'),\n delete s.dataset.ptid),\n H(e, t)\n })(e, r, t[2], t[3]))\n })(n, s)\n }\n })((e, t) => U(q, e).then(t)).then(e => {\n e &&\n ((q = new Worker(\n URL.createObjectURL(\n new Blob(\n [\n '/* Partytown 0.7.4 - MIT builder.io */\\n(e=>{const t=Symbol(),r=Symbol(),n=Symbol(),i=Symbol(),s=Symbol(),o=Symbol(),a=Symbol(),l=Symbol(),c=new Map,$={},d=new WeakMap,u=[],h={},p=new Map,g=new Map,m={},f=new Map,w=new Map,y=\"about:blank\",v=e=>e.split(\",\"),S=e=>{if(e=h.C+e,new URL(e).origin!=location.origin)throw\"Invalid \"+e;return e},I=v(\"clientWidth,clientHeight,clientTop,clientLeft,innerWidth,innerHeight,offsetWidth,offsetHeight,offsetTop,offsetLeft,outerWidth,outerHeight,pageXOffset,pageYOffset,scrollWidth,scrollHeight,scrollTop,scrollLeft\"),b=v(\"childElementCount,children,firstElementChild,lastElementChild,nextElementSibling,previousElementSibling\"),M=v(\"insertBefore,remove,removeChild,replaceChild\"),T=v(\"className,width,height,hidden,innerHTML,innerText,textContent\"),E=v(\"setAttribute,setAttributeNS,setProperty\"),N=v(\"addEventListener,dispatchEvent,removeEventListener\"),x=N.concat(E,v(\"add,observe,remove,unobserve\")),L=/^[A-Z_]([A-Z0-9-]*[A-Z0-9])?$/,C=()=>{},R=e=>e.length,A=e=>{var t,r,n;try{const r=null===(t=null==e?void 0:e.constructor)||void 0===t?void 0:t.name;if(r)return r}catch(e){}try{const t=null===(n=null===(r=null==e?void 0:e.__zone_symbol__originalInstance)||void 0===r?void 0:r.constructor)||void 0===n?void 0:n.name;if(t)return t}catch(e){}return\"\"},W=[],H=()=>Math.round(Math.random()*Number.MAX_SAFE_INTEGER).toString(36),P=\"text/partytown\",O=(e,t,r)=>Object.defineProperty(e,t,{...r,configurable:!0}),j=(e,t)=>O(e,\"name\",{value:t}),D=(e,t,r)=>O(e.prototype,t,r),k=(e,t)=>Object.defineProperties(e.prototype,t),U=(e,t,r)=>D(e,t,{value:r,writable:!0}),_=(e,t)=>t in e[o],B=(e,t)=>e[o][t],F=(e,t,r)=>e[o][t]=r,V=(e,t,r,n,i)=>(!(i=c.get(t))&&r&&m[e]&&(i=m[e].k(r,t,n),c.set(t,i)),i),z=(e,t)=>U(e,\"nodeType\",t),G=(e,t)=>t.map((t=>D(e,t,{get(){let e=X(this,t),r=w.get(e);return r||(r=de(this,[t]),w.set(e,r)),r}}))),X=(e,n,i)=>[e[t],e[r],n,...(i||W).map((e=>String(e&&e[t]?e[r]:e)))].join(\".\"),q=(e,t)=>v(t).map((t=>D(e,t,{get(){return _(this,t)||F(this,t,de(this,[t])),B(this,t)},set(e){B(this,t)!==e&&ue(this,[t],e),F(this,t,e)}}))),Z=e=>I.map((t=>D(e,t,{get(){const e=f.get(X(this,t));if(\"number\"==typeof e)return e;const r=de(this,[t],I);return r&&\"object\"==typeof r?(Object.entries(r).map((([e,t])=>f.set(X(this,e),t))),r[t]):r}}))),J=(e,t)=>t.map((t=>{e.prototype[t]=function(...e){let r=X(this,t,e),n=f.get(r);return n||(n=he(this,[t],e),f.set(r,n)),n}})),Y=(e,n,i,s,o)=>{return void 0!==i&&(o=typeof i)?\"string\"===o||\"boolean\"===o||\"number\"===o||null==i?[0,i]:\"function\"===o?[4,{V:e,w:n,L:(a=i,(l=d.get(a))||(d.set(a,l=H()),$[l]=a),l)}]:(s=s||new Set)&&Array.isArray(i)?s.has(i)?[1,[]]:s.add(i)&&[1,i.map((t=>Y(e,n,t,s)))]:\"object\"===o?i[r]?[3,[i[t],i[r]]]:i instanceof Event?[5,Q(e,n,i,!1,s)]:K&&i instanceof TrustedHTML?[0,i.toString()]:i instanceof ArrayBuffer?[8,i]:ArrayBuffer.isView(i)?[9,i.buffer,A(i)]:[2,Q(e,n,i,!0,s)]:void 0:i;var a,l},K=\"undefined\"!=typeof TrustedHTML,Q=(e,t,r,n,i,s,o,a)=>{if(s={},!i.has(r))for(o in i.add(r),r)a=r[o],(n||\"function\"!=typeof a)&&(s[o]=Y(e,t,a,i));return s},ee=(e,n)=>e?Y(e[t],e[r],n):[0,n],te=(e,t,r,n,i,s,o,a)=>{if(n){if(i=n[0],s=n[1],0===i||11===i||12===i)return s;if(4===i)return ne(r,s);if(6===i)return e&&r.length>0?(...t)=>he(m[e].U,r,t,1):C;if(3===i)return re(s);if(7===i)return new se(s.map(re));if(10===i)return new oe(s);if(1===i)return s.map((n=>te(e,t,r,n)));if(14===i)return new ie(s);for(a in o={},s)o[a]=te(e,t,[...r,a],s[a]);if(13===i)return new m[e].U.CSSStyleDeclaration(e,t,r,o);if(5===i){if(\"message\"===o.type&&o.origin){let e,t=JSON.stringify(o.data),r=u.find((e=>e.m===t));r&&(e=m[r.V],e&&(o.source=e.U,o.origin=e.E.origin))}return new Proxy(new Event(o.type,o),{get:(e,t)=>t in o?o[t]:\"function\"==typeof e[String(t)]?C:e[String(t)]})}if(2===i)return o}},re=([e,t,r])=>t===e&&m[e]?m[e].U:V(e,t,r),ne=(e,{V:t,w:r,G:n,L:i})=>($[i]||d.set($[i]=function(...i){const s=V(t,r,n);return he(s,e,i)},i),$[i]);class ie extends Error{constructor(e){super(e.message),this.name=e.name,this.message=e.message,this.stack=e.stack}}class se{constructor(e){(this._=e).map(((e,t)=>this[t]=e))}entries(){return this._.entries()}forEach(e,t){this._.map(e,t)}item(e){return this[e]}keys(){return this._.keys()}get length(){return R(this._)}values(){return this._.values()}[Symbol.iterator](){return this._[Symbol.iterator]()}}const oe=class{constructor(e){this.name=e[0],this.value=e[1]}get nodeName(){return this.name}get nodeType(){return 2}},ae=(e,t,r)=>console.warn(`Partytown unable to ${e} cross-origin ${t}: `+r.E),le=[],ce=(e,n,i,o,a,l)=>{if(e[s]){if(le.push({V:e[t],w:e[r],a:[...e[s],...n],d:o,r:a}),3===i)h.K([12,{F:H(),Q:[...le]}],l?[l instanceof ArrayBuffer?l:l.buffer]:void 0),le.length=0;else if(1===i)return $e(!0);h.c=setTimeout($e,20)}},$e=e=>{if(clearTimeout(h.c),R(le)){const t=le[R(le)-1],r={F:H(),Q:[...le]};if(le.length=0,e){const e=((e,t)=>{const r=e.P,n=new Int32Array(r);Atomics.store(n,0,0),e.K([11,t]),Atomics.wait(n,0,0);let i=Atomics.load(n,0),s=\"\",o=0;for(;o<i;o++)s+=String.fromCharCode(n[o+1]);return JSON.parse(s)})(h,r),n=e.z,i=te(t.V,t.w,t.a,e.M);if(e.p){if(n)return Promise.reject(e.p);throw new Error(e.p)}return n?Promise.resolve(i):i}h.K([12,r])}},de=(e,t,r,n)=>h.i.get&&(n=h.i.get(ge(e,t)))!==a?n:n=ce(e,t,1,void 0,r),ue=(e,t,r,n)=>{if(h.i.set){if((n=h.i.set({value:r,prevent:l,...ge(e,t)}))===l)return;n!==a&&(r=n)}T.some((e=>t.includes(e)))&&(f.clear(),t[t.length-1]),t=[...t,ee(e,r),0],ce(e,t,2)},he=(e,t,r,n,i,s,o,l)=>h.i.apply&&(o=h.i.apply({args:r,...ge(e,t)}))!==a?o:(l=t[R(t)-1],t=[...t,ee(e,r)],n=n||(x.includes(l)?2:1),\"setAttribute\"===l&&_(e,r[0])?F(e,r[0],r[1]):M.includes(l)?(f.clear(),w.clear()):E.includes(l)&&(n=2,f.clear()),o=ce(e,t,n,i,void 0,s)),pe=(e,t,r)=>{ce(e,[1,t,ee(e,r)],1)},ge=(e,r)=>({name:r.join(\".\"),continue:a,nodeName:e[n],constructor:A(e),instance:e,window:m[e[t]].U}),me=(e,t,r,n,i)=>{let s,o,a=t=>((t=r.get(e.origin))||r.set(e.origin,t=[]),t),l=e=>a().findIndex((t=>t[fe]===e)),c={getItem:e=>(s=l(e),s>-1?a()[s][we]:null),setItem(r,o){s=l(r),s>-1?a()[s][we]=o:a().push([r,o]),n?he(e,[t,\"setItem\"],[r,o],2):ae(\"set\",t,i)},removeItem(r){s=l(r),s>-1&&a().splice(s,1),n?he(e,[t,\"removeItem\"],[r],2):ae(\"remove\",t,i)},key:e=>(o=a()[e],o?o[fe]:null),clear(){a().length=0,n?he(e,[t,\"clear\"],W,2):ae(\"clear\",t,i)},get length(){return a().length}};e[t]=new Proxy(c,{get:(e,t)=>Reflect.has(e,t)?Reflect.get(e,t):e.getItem(t),set:(e,t,r)=>(e.setItem(t,r),!0),has:(e,t)=>!!Reflect.has(e,t)||\"string\"==typeof t&&null!==e.getItem(t),deleteProperty:(e,t)=>(e.removeItem(t),!0)})},fe=0,we=1,ye=(e,t,r)=>{e[r]=j(class extends t{constructor(e,t,r,i){return super(e,t,r,i||{}),new Proxy(this,{get:(e,t)=>e[t]?e[t]:(e[t]||\"string\"!=typeof t||e[n][t]||(e[n][t]=de(e,[t])),e[n][t]),set:(e,t,r)=>(e[n][t]=r,ue(e,[t],r),f.clear(),!0)})}setProperty(...e){this[n][e[0]]=e[1],he(this,[\"setProperty\"],e,2),e[0],f.clear()}getPropertyValue(e){return this[e]}removeProperty(e){let t=this[n][e];return he(this,[\"removeProperty\"],[e],2),f.clear(),this[n][e]=void 0,t}},r)},ve=(e,t)=>{e[t]=j(class{constructor(e){this.ownerNode=e}get cssRules(){const e=this.ownerNode;return new Proxy({},{get(t,r){const n=String(r);return\"item\"===n?t=>Ie(e,t):\"length\"===n?Se(e).length:isNaN(n)?t[r]:Ie(e,n)}})}insertRule(e,t){const r=Se(this.ownerNode);return(t=void 0===t?0:t)>=0&&t<=r.length&&(he(this.ownerNode,[\"sheet\",\"insertRule\"],[e,t],2),r.splice(t,0,0)),this.ownerNode,f.clear(),t}deleteRule(e){he(this.ownerNode,[\"sheet\",\"deleteRule\"],[e],2),Se(this.ownerNode).splice(e,1),this.ownerNode,f.clear()}get type(){return\"text/css\"}},t);const r={sheet:{get(){return new e[t](this)}}};k(e.HTMLStyleElement,r)},Se=(e,t)=>((t=B(e,2))||(t=de(e,[\"sheet\",\"cssRules\"]),F(e,2,t)),t),Ie=(e,t,r)=>(0===(r=Se(e))[t]&&(r[t]=de(e,[\"sheet\",\"cssRules\",parseInt(t,10)])),r[t]),be=\"0.7.4\",Me=(e,t,r,n,i)=>{try{e.l=t,Te(e,r)}catch(e){console.error(r,e),i=String(e.stack||e)}return e.l=\"\",i},Te=(e,t,r)=>{e.N=1,t=`with(this){${t.replace(/\\\\bthis\\\\b/g,\"(thi$(this)?window:this)\").replace(/\\\\/\\\\/# so/g,\"//Xso\")}\\\\n;function thi$(t){return t===this}};${(h.i.globalFns||[]).filter((e=>/[a-zA-Z_$][0-9a-zA-Z_$]*/.test(e))).map((e=>`(typeof ${e}==\\'function\\'&&(this.${e}=${e}))`)).join(\";\")};`+(r?\"\\\\n//# sourceURL=\"+r:\"\"),e.A||(t=t.replace(/.postMessage\\\\(/g,`.postMessage(\\'${e.V}\\',`)),new Function(t).call(e.U),e.N=0},Ee=(e,t,r)=>{(r=B(e,t))&&setTimeout((()=>r.map((e=>e({type:t})))))},Ne=(e,t,r,n,i,s)=>{for(n=e.E;!n.host&&(n=(e=m[e.J]).E,e.V!==e.J););return i=new URL(t||\"\",n),r&&h.i.resolveUrl&&(s=h.i.resolveUrl(i,n,r))?s:i},xe=(e,t,r)=>Ne(e,t,r)+\"\",Le=()=>`<script src=\"${S(\"partytown.js?v=\"+be)}\"><\\\\/script>`,Ce=e=>class{constructor(){this.s=\"\",this.l=[],this.e=[],this.style={}}get src(){return this.s}set src(t){this.s=t,fetch(xe(e,t,\"image\"),{mode:\"no-cors\",credentials:\"include\",keepalive:!0}).then((e=>{e.ok||0===e.status?this.l.map((e=>e({type:\"load\"}))):this.e.map((e=>e({type:\"error\"})))}),(()=>this.e.forEach((e=>e({type:\"error\"})))))}addEventListener(e,t){\"load\"===e&&this.l.push(t),\"error\"===e&&this.e.push(t)}get onload(){return this.l[0]}set onload(e){this.l=[e]}get onerror(){return this.e[0]}set onerror(e){this.e=[e]}},Re={addEventListener:{value(...e){const t=e[0],r=B(this,t)||[];r.push(e[1]),F(this,t,r)}},async:{get:C,set:C},defer:{get:C,set:C},onload:{get(){let e=B(this,\"load\");return e&&e[0]||null},set(e){F(this,\"load\",e?[e]:null)}},onerror:{get(){let e=B(this,\"error\");return e&&e[0]||null},set(e){F(this,\"error\",e?[e]:null)}},getAttribute:{value(e){return\"src\"===e?this.src:he(this,[\"getAttribute\"],[e])}},setAttribute:{value(e,t){Ae.includes(e)?this[e]=t:he(this,[\"setAttribute\"],[e,t])}}},Ae=v(\"src,type\"),We=(e,t)=>{const r={innerHTML:He,innerText:He,src:{get(){return B(this,4)||\"\"},set(e){const r=xe(t,e,null),n=h.i;e=xe(t,e,\"script\"),F(this,4,e),ue(this,[\"src\"],e),r!==e&&ue(this,[\"dataset\",\"ptsrc\"],r),this.type&&n.loadScriptsOnMainThread&&n.loadScriptsOnMainThread.some((t=>t===e))&&ue(this,[\"type\"],\"text/javascript\")}},textContent:He,type:{get(){return de(this,[\"type\"])},set(e){Pe(e)||(F(this,5,e),ue(this,[\"type\"],e))}},...Re};k(e,r)},He={get(){const e=de(this,[\"type\"]);return Pe(e)?B(this,3)||\"\":de(this,[\"innerHTML\"])},set(e){F(this,3,e)}},Pe=e=>!e||\"text/javascript\"===e,Oe=(e,i,s)=>{const o=h.i,a=j(class extends s{appendChild(e){return this.insertBefore(e,null)}get href(){}set href(e){}insertBefore(e,s){var a,l;const c=e[t]=this[t],$=e[r],d=e[n],u=\"SCRIPT\"===d,p=\"IFRAME\"===d;if(u){const t=B(e,3),r=B(e,5);if(t){if(Pe(r)){const r=e.id;if(r&&(null===(l=null===(a=o.loadScriptsOnMainThread)||void 0===a?void 0:a.includes)||void 0===l?void 0:l.call(a,r)))ue(e,[\"type\"],\"text/javascript\");else{const r=Me(i,$,t,0,\"\"),n=r?\"pterror\":\"ptid\",s=r||$;ue(e,[\"type\"],P+\"-x\"),ue(e,[\"dataset\",n],s)}}ue(e,[\"innerHTML\"],t)}}if(he(this,[\"insertBefore\"],[e,s],2),p){const t=B(e,0);if(t&&t.startsWith(\"javascript:\")){const e=t.split(\"javascript:\")[1];Me(i,$,e,0,\"\")}((e,t)=>{let r,n,i=0,s=()=>{m[e]&&m[e].x&&!m[e].y?(r=B(t,1)?\"error\":\"load\",n=B(t,r),n&&n.map((e=>e({type:r})))):i++>2e3?(n=B(t,\"error\"),n&&n.map((e=>e({type:\"error\"})))):setTimeout(s,9)};s()})($,e)}return u&&($e(!0),h.K([7,c])),e}get nodeName(){return\"#s\"===this[n]?\"#document-fragment\":this[n]}get nodeType(){return 3}get ownerDocument(){return i.n}},\"Node\");G(a,v(\"childNodes,firstChild,isConnected,lastChild,nextSibling,parentElement,parentNode,previousSibling\")),e.Node=a},je=v(\"AUDIO,CANVAS,VIDEO\"),De=v(\"Audio,MediaSource\"),ke=(e,r,n)=>{k(e,{body:{get:()=>r.e},cookie:{get(){return r.A?de(this,[\"cookie\"]):(ae(\"get\",\"cookie\",r),\"\")},set(e){r.A&&ue(this,[\"cookie\"],e)}},createElement:{value(e){if(e=e.toUpperCase(),!L.test(e))throw e+\" not valid\";const r=\"IFRAME\"===e,n=this[t],i=(r?\"f_\":\"\")+H();he(this,[\"createElement\"],[e],2,i);const s=V(n,i,e);if(r)et({V:i,J:n,S:y},!0).U.fetch=fetch,ue(s,[\"srcdoc\"],Le());else if(\"SCRIPT\"===e){const e=B(s,5);Pe(e)&&ue(s,[\"type\"],P)}return s}},createElementNS:{value(e,r){const n=H(),i=V(this[t],n,r,e);return he(this,[\"createElementNS\"],[e,r],2,n),i}},createTextNode:{value(e){const r=this[t],n=H(),i=V(r,n,\"#text\");return he(this,[\"createTextNode\"],[e],2,n),i}},createEvent:{value:e=>new Event(e)},currentScript:{get(){return r.l?V(this[t],r.l,\"SCRIPT\"):null}},defaultView:{get:()=>n?null:r.U},documentElement:{get:()=>r.o},getElementsByTagName:{value(e){return\"BODY\"===(e=e.toUpperCase())?[r.e]:\"HEAD\"===e?[r.s]:he(this,[\"getElementsByTagName\"],[e])}},head:{get:()=>r.s},images:{get(){return de(this,[\"images\"])}},implementation:{get(){return{hasFeature:()=>!0,createHTMLDocument:e=>{const t=H();return he(this,[\"implementation\",\"createHTMLDocument\"],[e],1,{V:t}),et({V:t,J:t,S:r.E+\"\",T:\"hidden\"},!0,!0).n}}}},location:{get:()=>r.E,set(e){r.E.href=e+\"\"}},nodeType:{value:9},parentNode:{value:null},parentElement:{value:null},readyState:{value:\"complete\"},visibilityState:{get:()=>r.T||\"visible\"}}),q(e,\"compatMode,referrer,forms\")},Ue=(e,t)=>{k(e,{parentElement:{get(){return this.parentNode}},parentNode:{get:()=>t.o}})},_e=(e,t)=>{k(e,{localName:{get(){return this[n].toLowerCase()}},namespaceURI:{get(){return this[i]||\"http://www.w3.org/1999/xhtml\"}},nodeType:{value:1},tagName:{get(){return this[n]}}}),G(e,b),q(e,\"id\"),Z(t),J(t,v(\"getClientRects,getBoundingClientRect\"))},Be=(e,t)=>{const r={};v(\"hash,host,hostname,href,origin,pathname,port,protocol,search\").map((e=>{r[e]={get(){let r,n=B(this,4);return\"string\"!=typeof n&&(r=de(this,[\"href\"]),F(this,4,r),n=new URL(r)[e]),Ne(t,n,null)[e]},set(r){let n;if(\"href\"===e)if((e=>{try{return new URL(e),!0}catch(e){return!1}})(r))n=new URL(r);else{const e=t.E.href;n=Ne(t,e,null),n.href=new URL(r+\"\",n.href)}else n=Ne(t,this.href,null),n[e]=r;F(this,4,n.href),ue(this,[\"href\"],n.href)}}})),k(e,r)},Fe=(e,t)=>{const r={contentDocument:{get(){return Xe(this).n}},contentWindow:{get(){return Xe(this).U}},src:{get(){let e=B(this,0);return e&&e.startsWith(\"javascript:\")?e:(e=Xe(this).E.href,e.startsWith(\"about:\")?\"\":e)},set(e){if(e)if(e.startsWith(\"javascript:\"))F(this,0,e);else if(!e.startsWith(\"about:\")){let t,r=new XMLHttpRequest,n=Xe(this);n.E.href=e=xe(n,e,\"iframe\"),n.y=1,F(this,1,void 0),r.open(\"GET\",e,!1),r.send(),t=r.status,t>199&&t<300?(ue(this,[\"srcdoc\"],`<base href=\"${e}\">`+r.responseText.replace(ze,((e,t)=>{const r=[];let n,i=!1;for(;n=Ge.exec(t);){let[e]=n;e.startsWith(\"type=\")&&(i=!0,e=e.replace(/(application|text)\\\\/javascript/,P)),r.push(e)}return i||r.push(\\'type=\"text/partytown\"\\'),`<script ${r.join(\" \")}>`}))+Le()),$e(!0),h.K([7,n.V])):(F(this,1,t),n.y=0)}}},...Re};k(e,r)},Ve=\"((?:\\\\\\\\w|-)+(?:=(?:(?:\\\\\\\\w|-)+|\\'[^\\']*\\'|\\\\\"[^\\\\\"]*\\\\\")?)?)\",ze=new RegExp(`<script\\\\\\\\s*((${Ve}\\\\\\\\s*)*)>`,\"mg\"),Ge=new RegExp(Ve,\"mg\"),Xe=e=>{const n=e[r];return m[n]||et({V:n,J:e[t],S:de(e,[\"src\"])||y},!0),m[n]},qe=e=>{const t=(e,t)=>{const{a:r,b:n,c:i,d:s,e:o,f:a}=he(e,[t],W);return new DOMMatrixReadOnly([r,n,i,s,o,a])},r={...e,getCTM:{value:function(){return t(this,\"getCTM\")}},getScreenCTM:{value:function(){return t(this,\"getScreenCTM\")}}};k(e,r)},Ze=(e,t)=>{e.NamedNodeMap=j(class extends t{constructor(e,t,r){return super(e,t,r),new Proxy(this,{get(e,t){const r=Ye[t];return r?r.bind(e,[t]):de(e,[t])},set(e,t,r){if(Ye[t])throw new Error(\"Can\\'t set read-only property: \"+String(t));return ue(e,[t],r),!0}})}},\"NamedNodeMap\")};function Je(e,...t){return he(this,e,t,1)}const Ye={getNamedItem:Je,getNamedItemNS:Je,item:Je,removeNamedItem:Je,removeNamedItemNS:Je,setNamedItem:Je,setNamedItemNS:Je},Ke=(a,l,c,$,d,f)=>{let w,I,M;const T=class{constructor(e,l,c,$,d){this[t]=e||a,this[r]=l||w||H(),this[s]=c||[],this[n]=$||I,this[i]=d||M,this[o]={},w=I=M=void 0}},E=new(j(class extends URL{assign(){}reload(){}replace(){}},\"Location\"))(c),x=E.origin===h.I||E.origin===y,L=l===a,C={},W=()=>{let e,t,r=[];for(e in m)t=m[e],t.J!==a||t.B||r.push(t);return r},P=j(class extends T{constructor(){super(a,a);let n,i,o=this,c=0,u=()=>{c||((h.u||(e.g=[de,ue,he,pe,k,H,t,r,s],h.t(S(\"partytown-media.js?v=\"+be)),h.u=e.f,delete e.f),h.u)(T,Y,C,o,De),c=1)},m={},y=(e,t,r)=>{je.includes(e)&&u();const n=m[e]?m[e]:e.includes(\"-\")?m.UNKNOWN:m.I;return w=t,I=e,M=r,new n};var N,R;if(o.Window=P,o.name=name+a,Oe(o,C,T),(e=>{e.NodeList=j(se,\"NodeList\")})(o),Ze(o,T),ye(o,T,\"CSSStyleDeclaration\"),((e,t,r)=>{e[r]=j(class extends t{now(){return performance.now()}},r)})(o,T,\"Performance\"),((e,t)=>{const r=\"customElements\",n=new Map;e.customElements={define(i,s,o){n.set(i,s),t[i.toUpperCase()]=s;const a=[s.name,s.observedAttributes];he(e,[r,\"define\"],[i,a,o])},get:t=>n.get(t)||he(e,[r,\"get\"],[t]),whenDefined:t=>n.has(t)?Promise.resolve():he(e,[r,\"whenDefined\"],[t]),upgrade:t=>he(e,[r,\"upgrade\"],[t])}})(o,m),h.v.map((([e,t,n,i,l])=>{const c=Qe[e]?X:\"EventTarget\"===t?Y:\"Object\"===t?T:o[t],$=o[e]=j(12===i?class extends T{constructor(...t){super(),pe(this,e,t)}}:o[e]||class extends c{},e);l&&(m[l]=$),n.map((([e,t,n])=>{e in $.prototype||e in c.prototype||(\"string\"==typeof t?D($,e,{get(){if(!_(this,e)){const n=this[r],i=[...this[s],e],l=o[t];l&&F(this,e,new l(a,n,i))}return B(this,e)},set(t){F(this,e,t)}}):5===t?U($,e,(function(...t){return he(this,[e],t)})):t>0&&(void 0!==n?U($,e,n):D($,e,{get(){return de(this,[e])},set(t){return ue(this,[e],t)}})))}))})),v(\"atob,btoa,crypto,indexedDB,setTimeout,setInterval,clearTimeout,clearInterval\").map((t=>{delete P.prototype[t],t in o||(n=e[t],null!=n&&(o[t]=\"function\"!=typeof n||n.toString().startsWith(\"class\")?n:n.bind(e)))})),Object.getOwnPropertyNames(e).map((t=>{t in o||(o[t]=e[t])})),De.map((e=>O(o,e,{get:()=>(u(),o[e])}))),\"trustedTypes\"in e&&(o.trustedTypes=e.trustedTypes),_e(o.Element,o.HTMLElement),ke(o.Document,C,f),N=o.DocumentFragment,z(N,11),G(N,b),Be(o.HTMLAnchorElement,C),R=o.HTMLFormElement,k(R,{}),q(R,\"elements\"),Fe(o.HTMLIFrameElement),We(o.HTMLScriptElement,C),qe(o.SVGGraphicsElement),Ue(o.HTMLHeadElement,C),Ue(o.HTMLBodyElement,C),((e,t)=>{k(e,{parentElement:{value:null},parentNode:{get:()=>t.n}})})(o.HTMLHtmlElement,C),ve(o,\"CSSStyleSheet\"),z(o.Comment,8),z(o.DocumentType,10),Object.assign(C,{V:a,J:l,U:new Proxy(o,{get:(e,t)=>{var r;if(\"string\"!=typeof t||isNaN(t))return(null===(r=h.i.mainWindowAccessors)||void 0===r?void 0:r.includes(t))?de(this,[t]):e[t];{let e=W()[t];return e?e.U:void 0}},has:()=>!0}),n:y(\"#document\",a+\".d\"),o:y(\"HTML\",a+\".e\"),s:y(\"HEAD\",a+\".h\"),e:y(\"BODY\",a+\".b\"),E:E,T:$,A:x,B:L,k:y}),o.requestAnimationFrame=e=>setTimeout((()=>e(performance.now())),9),o.cancelAnimationFrame=e=>clearTimeout(e),o.requestIdleCallback=(e,t)=>(t=Date.now(),setTimeout((()=>e({didTimeout:!1,timeRemaining:()=>Math.max(0,50-(Date.now()-t))})),1)),o.cancelIdleCallback=e=>clearTimeout(e),me(o,\"localStorage\",p,x,C),me(o,\"sessionStorage\",g,x,C),x||(o.indexeddb=void 0),d)i={},o.history={pushState(e){i=e},replaceState(e){i=e},get state(){return i},length:0},o.indexeddb=void 0;else{const e=o.history.pushState.bind(o.history),t=o.history.replaceState.bind(o.history);o.history.pushState=(t,r,n)=>{!1!==C.$propagateHistoryChange$&&e(t,r,n)},o.history.replaceState=(e,r,n)=>{!1!==C.$propagateHistoryChange$&&t(e,r,n)}}o.Worker=void 0}addEventListener(...e){\"load\"===e[0]?C.N&&setTimeout((()=>e[1]({type:\"load\"}))):he(this,[\"addEventListener\"],e,2)}get body(){return C.e}get document(){return C.n}get documentElement(){return C.o}fetch(e,t){return e=\"string\"==typeof e||e instanceof URL?String(e):e.url,fetch(xe(C,e,\"fetch\"),t)}get frames(){return C.U}get frameElement(){return L?null:V(l,a,\"IFRAME\")}get globalThis(){return C.U}get head(){return C.s}get length(){return W().length}get location(){return E}set location(e){E.href=e+\"\"}get Image(){return Ce(C)}get navigator(){return(e=>{let t,r={sendBeacon:(t,r)=>{try{return fetch(xe(e,t,null),{method:\"POST\",body:r,mode:\"no-cors\",keepalive:!0}),!0}catch(e){return console.error(e),!1}}};for(t in navigator)r[t]=navigator[t];return r})(C)}get origin(){return E.origin}set origin(e){}get parent(){for(let e in m)if(m[e].V===l)return m[e].U;return C.U}postMessage(...e){m[e[0]]&&(R(u)>50&&u.splice(0,5),u.push({V:e[0],m:JSON.stringify(e[1])}),e=e.slice(1)),he(this,[\"postMessage\"],e,3)}get self(){return C.U}get top(){for(let e in m)if(m[e].B)return m[e].U;return C.U}get window(){return C.U}get XMLHttpRequest(){const e=XMLHttpRequest,t=String(e),r=j(class extends e{open(...e){e[1]=xe(C,e[1],\"xhr\"),super.open(...e)}set withCredentials(e){}toString(){return t}},A(e));return r.prototype.constructor.toString=()=>t,r}},\"Window\"),X=class extends T{constructor(e,t,r,n){return super(e,t,r,n),new Proxy(this,{get:(e,t)=>de(e,[t]),set:(e,t,r)=>(ue(e,[t],r),!0)})}},Y=class extends T{};return N.map((e=>Y.prototype[e]=function(...t){return he(this,[e],t,2)})),q(P,\"devicePixelRatio\"),Z(P),J(P,[\"getComputedStyle\"]),new P,C},Qe={DOMStringMap:1,NamedNodeMap:1},et=({V:e,J:t,S:r,T:n},i,s)=>(m[e]||(m[e]=Ke(e,t,r,n,i,s)),h.K([7,e]),m[e]),tt=[],rt=t=>{const r=t.data,n=r[0],i=r[1];if(h.x)if(7===n)(async e=>{let t,r=e.V,n=e.w,i=V(r,n,\"SCRIPT\"),s=e.j,o=e.S,a=e.H,l=\"\",c=m[r],$=[\"text/jscript\",\"text/javascript\",\"text/x-javascript\",\"application/javascript\",\"application/x-javascript\",\"text/ecmascript\",\"text/x-ecmascript\",\"application/ecmascript\"];if(o)try{if(o=Ne(c,o,\"script\")+\"\",F(i,4,o),t=await fetch(o),t.ok){let e=t.headers.get(\"content-type\");$.some((t=>{var r,n,i;return null===(i=null===(r=null==e?void 0:e.toLowerCase)||void 0===r?void 0:(n=r.call(e)).includes)||void 0===i?void 0:i.call(n,t)}))&&(s=await t.text(),c.l=n,Te(c,s,a||o)),Ee(i,\"load\")}else l=t.statusText,Ee(i,\"error\")}catch(e){console.error(e),l=String(e.stack||e),Ee(i,\"error\")}else s&&(l=Me(c,n,s,0,l));c.l=\"\",h.K([6,r,n,l])})(i);else if(9===n)(({V:e,w:t,L:r,R:n,b:i})=>{if($[r])try{$[r].apply(te(e,t,[],n),te(e,t,[],i))}catch(e){console.error(e)}})(i);else if(10===n)(({V:e,q:t,b:r})=>{try{let n=m[e].U,i=0,s=R(t);for(;i<s;i++)i+1<s?n=n[t[i]]:n[t[i]].apply(n,te(null,e,[],r))}catch(e){console.error(e)}})(i);else if(5===n)et(i);else if(8===n)m[i].x=1,m[i].y=0;else if(14===n)m[i].T=r[2];else if(13===n){const e=i.V,t=m[e];t.E.href=i.url,function(e,t,r){const n=t.U.history;switch(r.type){case 0:t.$propagateHistoryChange$=!1;try{n.pushState(r.state,\"\",r.newUrl)}catch(e){}t.$propagateHistoryChange$=!0;break;case 1:t.$propagateHistoryChange$=!1;try{n.replaceState(r.state,\"\",r.newUrl)}catch(e){}t.$propagateHistoryChange$=!0}}(i.V,t,i)}else 15===n&&((e,t,r,n,i)=>{const s=V(t,r);s&&\"function\"==typeof s[n]&&s[n].apply(s,i)})(...r);else 1===n?((t=>{const r=h.i=JSON.parse(t.i),n=t.I;h.t=importScripts.bind(e),h.v=t.v,h.C=t.C,h.I=n,h.K=postMessage.bind(e),h.P=t.P,p.set(n,t.D),g.set(n,t.O),e.importScripts=void 0,delete e.postMessage,delete e.WorkerGlobalScope,v(\"resolveUrl,get,set,apply\").map((e=>{r[e]&&(r[e]=new Function(\"return \"+r[e])())}))})(i),h.K([2])):3===n?(h.v=[...h.v,...i],h.x=1,h.K([4]),[...tt].map(rt),tt.length=0):tt.push(t)};e.onmessage=rt,postMessage([0])})(self);\\n',\n ],\n { type: 'text/javascript' }\n )\n ),\n { name: 'Partytown 🎉' }\n )),\n (q.onmessage = t => {\n const r = t.data\n 12 === r[0] ? U(q, r[1]) : e(q, r)\n }),\n $.addEventListener('pt1', e => O(q, f(e.detail.frameElement), e.detail)))\n })\n})(window)\n\n```"
}
] |
code_partytown_cbab5392
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of partytown/public/~partytown/partytown.js from the partytown VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\n/* Partytown 0.7.4 - MIT builder.io */\n!(function (t, e, n, i, r, o, a, d, s, c, p, l) {\n function u() {\n l ||\n ((l = 1),\n '/' == (a = (o.lib || '/~partytown/') + (o.debug ? 'debug/' : ''))[0] &&\n ((s = e.querySelectorAll('script[type=\"text/partytown\"]')),\n i != t\n ? i.dispatchEvent(new CustomEvent('pt1', { detail: t }))\n : ((d = setTimeout(w, 1e4)),\n e.addEventListener('pt0', f),\n r\n ? h(1)\n : n.serviceWorker\n ? n.serviceWorker\n .register(a + (o.swPath || 'partytown-sw.js'), { scope: a })\n .then(function (t) {\n t.active\n ? h()\n : t.installing &&\n t.installing.addEventListener(\n 'statechange',\n function (t) {\n 'activated' == t.target.state && h()\n }\n )\n }, console.error)\n : w())))\n }\n function h(t) {\n ;(c = e.createElement(t ? 'script' : 'iframe')),\n t ||\n (c.setAttribute(\n 'style',\n 'display:block;width:0;height:0;border:0;visibility:hidden'\n ),\n c.setAttribute('aria-hidden', !0)),\n (c.src =\n a +\n 'partytown-' +\n (t ? 'atomics.js?v=0.7.4' : 'sandbox-sw.html?' + Date.now())),\n e.body.appendChild(c)\n }\n function w(t, n) {\n for (f(), t = 0; t < s.length; t++)\n ((n = e.createElement('script')).innerHTML = s[t].innerHTML),\n e.head.appendChild(n)\n c && c.parentNode.removeChild(c)\n }\n function f() {\n clearTimeout(d)\n }\n ;(o = t.partytown || {}),\n i == t &&\n (o.forward || []).map(function (e) {\n ;(p = t),\n e.split('.').map(function (e, n, i) {\n p = p[i[n]] =\n n + 1 < i.length\n ? 'push' == i[n + 1]\n ? []\n : p[i[n]] || {}\n : function () {\n ;(t._ptf = t._ptf || []).push(i, arguments)\n }\n })\n }),\n 'complete' == e.readyState\n ? u()\n : (t.addEventListener('DOMContentLoaded', u),\n t.addEventListener('load', u))\n})(window, document, navigator, top, window.crossOriginIsolated)\n\n```"
}
] |
code_partytown_bde4692a
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of partytown/public/~partytown/partytown-media.js from the partytown VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\n/* Partytown 0.7.4 - MIT builder.io */\n;(e => {\n const [t, s, n, r, i, a, o, d, u] = e.g\n delete e.g\n const c = Symbol(),\n h = Symbol(),\n f = Symbol(),\n p = Symbol(),\n g = Symbol(),\n l = Symbol(),\n m = [],\n v = (e, t, s) => (e[t] = S(t, s)),\n S = (e, t) => Object.defineProperty(t, 'name', { value: e }),\n b = (e, t) => {\n const r = {\n getContext: {\n value(e, t) {\n return (\n this[c] ||\n (this[c] = (e.includes('webgl') ? g : p)(this, e, t)),\n this[c]\n )\n },\n },\n },\n h = v(\n t,\n 'CanvasGradient',\n class extends e {\n addColorStop(...e) {\n n(this, ['addColorStop'], e, 2)\n }\n }\n ),\n f = v(\n t,\n 'CanvasPattern',\n class extends e {\n setTransform(...e) {\n n(this, ['setTransform'], e, 2)\n }\n }\n ),\n p = (e, t, r) => {\n const i = e[o],\n c = a(),\n f = { [o]: i, [d]: c, [u]: [] },\n p = n(e, ['getContext'], [t, r], 1, c),\n g = 'getContextAttributes,getImageData,getLineDash,getTransform,isPointInPath,isPointInStroke,measureText'.split(\n ','\n ),\n l = {\n get: (e, t) =>\n 'string' == typeof t && t in p\n ? 'function' == typeof p[t]\n ? (...e) => {\n if (t.startsWith('create')) {\n const r = a()\n return (\n n(f, [t], e, 2, r),\n 'createImageData' === t || 'createPattern' === t\n ? ((s = `${t}()`),\n console.warn(`${s} not implemented`),\n { setTransform: () => {} })\n : new h(i, r)\n )\n }\n var s\n const r = g.includes(t) ? 1 : 2\n return n(f, [t], e, r)\n }\n : p[t]\n : e[t],\n set: (e, t, n) => (\n 'string' == typeof t && t in p\n ? (p[t] !== n && 'function' != typeof n && s(f, [t], n),\n (p[t] = n))\n : (e[t] = n),\n !0\n ),\n }\n return new Proxy(p, l)\n },\n g = (e, t, r) => {\n const i = e[o],\n c = a(),\n h = { [o]: i, [d]: c, [u]: [] },\n f = n(e, ['getContext'], [t, r], 1, c),\n p = {\n get: (e, t) =>\n 'string' == typeof t\n ? 'function' != typeof f[t]\n ? f[t]\n : (...e) => n(h, [t], e, m(t))\n : e[t],\n set: (e, t, n) => (\n 'string' == typeof t && t in f\n ? (f[t] !== n && 'function' != typeof n && s(h, [t], n),\n (f[t] = n))\n : (e[t] = n),\n !0\n ),\n }\n return new Proxy(f, p)\n },\n l = 'checkFramebufferStatus,makeXRCompatible'.split(','),\n m = e =>\n e.startsWith('create') ||\n e.startsWith('get') ||\n e.startsWith('is') ||\n l.includes(e)\n ? 1\n : 2\n v(t, 'CanvasGradient', h),\n v(t, 'CanvasPattern', f),\n i(t.HTMLCanvasElement, r)\n },\n y = (e, u, c, b) => {\n var y, T\n b.Audio = S(\n 'HTMLAudioElement',\n class {\n constructor(e) {\n const t = c.k('audio', a())\n return (t.src = e), t\n }\n }\n )\n const w = class extends e {\n get enabled() {\n return t(this, ['enabled'])\n }\n set enabled(e) {\n s(this, ['enabled'], e)\n }\n get id() {\n return t(this, ['id'])\n }\n get kind() {\n return t(this, ['kind'])\n }\n get label() {\n return t(this, ['label'])\n }\n get language() {\n return t(this, ['language'])\n }\n get sourceBuffer() {\n return new x(this)\n }\n },\n E = class {\n constructor(e) {\n const s = 'audioTracks',\n r = e[o],\n i = e[d]\n return new Proxy(\n {\n addEventListener(...t) {\n n(e, [s, 'addEventListener'], t, 3)\n },\n getTrackById: (...t) => n(e, [s, 'getTrackById'], t),\n get length() {\n return t(e, [s, 'length'])\n },\n removeEventListener(...t) {\n n(e, [s, 'removeEventListener'], t, 3)\n },\n },\n {\n get: (e, t) =>\n 'number' == typeof t ? new w(r, i, [s, t]) : e[t],\n }\n )\n }\n },\n k = v(\n b,\n 'SourceBufferList',\n class extends Array {\n constructor(e) {\n super(), (this[h] = e)\n }\n addEventListener(...e) {\n n(this[h], ['sourceBuffers', 'addEventListener'], e, 3)\n }\n removeEventListener(...e) {\n n(this[h], ['sourceBuffers', 'removeEventListener'], e, 3)\n }\n }\n ),\n x = v(\n b,\n 'SourceBuffer',\n ((T = class extends u {\n constructor(e) {\n super(e[o], e[d], ['sourceBuffers']),\n (this[y] = []),\n (this[h] = e)\n }\n abort() {\n const e = R(this)\n n(this, [e, 'appendWindowStart'], m, 1)\n }\n addEventListener(...e) {\n const t = R(this)\n n(this, [t, 'addEventListener'], e, 3)\n }\n appendBuffer(e) {\n this[g].push(['appendBuffer', [e], e]), M(this)\n }\n get appendWindowStart() {\n const e = R(this)\n return t(this, [e, 'appendWindowStart'])\n }\n set appendWindowStart(e) {\n const t = R(this)\n s(this, [t, 'appendWindowStart'], e)\n }\n get appendWindowEnd() {\n const e = R(this)\n return t(this, [e, 'appendWindowEnd'])\n }\n set appendWindowEnd(e) {\n const t = R(this)\n s(this, [t, 'appendWindowEnd'], e)\n }\n get buffered() {\n const e = this[h],\n t = R(this)\n return new B(e[o], e[d], ['sourceBuffers', t, 'buffered'])\n }\n changeType(e) {\n const t = R(this)\n n(this, [t, 'changeType'], [e], 2)\n }\n get mode() {\n const e = R(this)\n return t(this, [e, 'mode'])\n }\n set mode(e) {\n const t = R(this)\n s(this, [t, 'mode'], e)\n }\n remove(e, t) {\n this[g].push(['remove', [e, t]]), M(this)\n }\n removeEventListener(...e) {\n const t = R(this)\n n(this, [t, 'removeEventListener'], e, 3)\n }\n get timestampOffset() {\n const e = R(this)\n return t(this, [e, 'timestampOffset'])\n }\n set timestampOffset(e) {\n const t = R(this)\n s(this, [t, 'timestampOffset'], e)\n }\n get updating() {\n const e = R(this)\n return t(this, [e, 'updating'])\n }\n }),\n (y = g),\n T)\n ),\n B = v(\n b,\n 'TimeRanges',\n class extends e {\n start(...e) {\n return n(this, ['start'], e)\n }\n end(...e) {\n return n(this, ['end'], e)\n }\n get length() {\n return t(this, ['length'])\n }\n }\n ),\n R = e => (e ? e[h][p].indexOf(e) : -1),\n M = e => {\n if (e[g].length) {\n if (!e.updating) {\n const t = e[g].shift()\n if (t) {\n const s = R(e)\n n(e, [s, t[0]], t[1], 3, void 0, t[2])\n }\n }\n setTimeout(() => M(e), 50)\n }\n },\n W = {\n buffered: {\n get() {\n return (\n this[l] ||\n ((this[l] = new B(this[o], this[d], ['buffered'])),\n setTimeout(() => {\n this[l] = void 0\n }, 5e3)),\n this[l]\n )\n },\n },\n readyState: {\n get() {\n return 4 === this[f]\n ? 4\n : ('number' != typeof this[f] &&\n ((this[f] = t(this, ['readyState'])),\n setTimeout(() => {\n this[f] = void 0\n }, 1e3)),\n this[f])\n },\n },\n }\n v(\n b,\n 'MediaSource',\n class extends u {\n constructor() {\n super(c.V), (this[p] = new k(this)), r(this, 'MediaSource', m)\n }\n get activeSourceBuffers() {\n return []\n }\n addSourceBuffer(e) {\n const t = new x(this)\n return this[p].push(t), n(this, ['addSourceBuffer'], [e]), t\n }\n clearLiveSeekableRange() {\n n(this, ['clearLiveSeekableRange'], m, 2)\n }\n get duration() {\n return t(this, ['duration'])\n }\n set duration(e) {\n s(this, ['duration'], e)\n }\n endOfStream(e) {\n n(this, ['endOfStream'], [e], 3)\n }\n get readyState() {\n return t(this, ['readyState'])\n }\n removeSourceBuffer(e) {\n const t = R(e)\n t > -1 &&\n (this[p].splice(t, 1), n(this, ['removeSourceBuffer'], [t], 1))\n }\n setLiveSeekableRange(e, t) {\n n(this, ['setLiveSeekableRange'], [e, t], 2)\n }\n get sourceBuffers() {\n return this[p]\n }\n static isTypeSupported(e) {\n if (!L.has(e)) {\n const t = n(b, ['MediaSource', 'isTypeSupported'], [e])\n L.set(e, t)\n }\n return L.get(e)\n }\n }\n )\n const C = (b.URL = S('URL', class extends URL {}))\n 'audioTracks' in b.HTMLMediaElement.prototype &&\n (v(b, 'AudioTrackList', E),\n v(b, 'AudioTrack', w),\n (W.audioTracks = {\n get() {\n return new E(this)\n },\n })),\n i(b.HTMLMediaElement, W),\n (C.createObjectURL = e => n(b, ['URL', 'createObjectURL'], [e])),\n (C.revokeObjectURL = e => n(b, ['URL', 'revokeObjectURL'], [e]))\n },\n L = new Map()\n e.f = (e, t, s, n, r) => {\n r.map(e => {\n delete n[e]\n }),\n b(e, n),\n y(e, t, s, n)\n }\n})(self)\n\n```"
}
] |
code_partytown_cc111c68
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of partytown/public/metadata/messages/es-AR.json from the partytown VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"name\": \"\",\n \"headline\": \"\",\n \"overview\": \"\",\n \"features\": [],\n \"additionalInformation\": \"\",\n \"websiteURL\": \"https://vtex.com/\",\n \"support\": {\n \"url\": \"https://support.vtex.com/hc/requests\"\n }\n}\n\n```"
}
] |
code_partytown_b0641292
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of partytown/public/metadata/messages/pt-BR.json from the partytown VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"name\": \"\",\n \"headline\": \"\",\n \"overview\": \"\",\n \"features\": [],\n \"additionalInformation\": \"\",\n \"websiteURL\": \"https://vtex.com/\",\n \"support\": {\n \"url\": \"https://support.vtex.com/hc/requests\"\n }\n}\n\n```"
}
] |
code_partytown_a4a94dce
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of partytown/public/metadata/messages/en-US.json from the partytown VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"name\": \"\",\n \"headline\": \"\",\n \"overview\": \"\",\n \"features\": [],\n \"additionalInformation\": \"\",\n \"websiteURL\": \"https://vtex.com/\",\n \"support\": {\n \"url\": \"https://support.vtex.com/hc/requests\"\n }\n}\n\n```"
}
] |
code_partytown_8a44d964
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of partytown/public/~partytown/debug/partytown-sandbox-sw.js from the partytown VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\n/* Partytown 0.7.4 - MIT builder.io */\n;(window => {\n const isPromise = v => 'object' == typeof v && v && v.then\n const noop = () => {}\n const len = obj => obj.length\n const getConstructorName = obj => {\n var _a, _b, _c\n try {\n const constructorName =\n null === (_a = null == obj ? void 0 : obj.constructor) || void 0 === _a\n ? void 0\n : _a.name\n if (constructorName) {\n return constructorName\n }\n } catch (e) {}\n try {\n const zoneJsConstructorName =\n null ===\n (_c =\n null ===\n (_b =\n null == obj ? void 0 : obj.__zone_symbol__originalInstance) ||\n void 0 === _b\n ? void 0\n : _b.constructor) || void 0 === _c\n ? void 0\n : _c.name\n if (zoneJsConstructorName) {\n return zoneJsConstructorName\n }\n } catch (e) {}\n return ''\n }\n const startsWith = (str, val) => str.startsWith(val)\n const isValidMemberName = memberName =>\n !(\n startsWith(memberName, 'webkit') ||\n startsWith(memberName, 'toJSON') ||\n startsWith(memberName, 'constructor') ||\n startsWith(memberName, 'toString') ||\n startsWith(memberName, '_')\n )\n const getNodeName = node =>\n 11 === node.nodeType && node.host ? '#s' : node.nodeName\n const randomId = () =>\n Math.round(Math.random() * Number.MAX_SAFE_INTEGER).toString(36)\n const defineConstructorName = (Cstr, value) =>\n ((obj, memberName, descriptor) =>\n Object.defineProperty(obj, memberName, {\n ...descriptor,\n configurable: true,\n }))(Cstr, 'name', {\n value: value,\n })\n const htmlConstructorTags = {\n Anchor: 'a',\n DList: 'dl',\n Image: 'img',\n OList: 'ol',\n Paragraph: 'p',\n Quote: 'q',\n TableCaption: 'caption',\n TableCell: 'td',\n TableCol: 'colgroup',\n TableRow: 'tr',\n TableSection: 'tbody',\n UList: 'ul',\n }\n const svgConstructorTags = {\n Graphics: 'g',\n SVG: 'svg',\n }\n const InstanceIdKey = Symbol()\n const CreatedKey = Symbol()\n const instances = new Map()\n const mainRefs = new Map()\n const winCtxs = {}\n const windowIds = new WeakMap()\n const getAndSetInstanceId = (instance, instanceId) => {\n if (instance) {\n if ((instanceId = windowIds.get(instance))) {\n return instanceId\n }\n ;(instanceId = instance[InstanceIdKey]) ||\n setInstanceId(instance, (instanceId = randomId()))\n return instanceId\n }\n }\n const getInstance = (winId, instanceId, win, doc, docId) => {\n if ((win = winCtxs[winId]) && win.$window$) {\n if (winId === instanceId) {\n return win.$window$\n }\n doc = win.$window$.document\n docId = instanceId.split('.').pop()\n if ('d' === docId) {\n return doc\n }\n if ('e' === docId) {\n return doc.documentElement\n }\n if ('h' === docId) {\n return doc.head\n }\n if ('b' === docId) {\n return doc.body\n }\n }\n return instances.get(instanceId)\n }\n const setInstanceId = (instance, instanceId, now) => {\n if (instance) {\n instances.set(instanceId, instance)\n instance[InstanceIdKey] = instanceId\n instance[CreatedKey] = now = Date.now()\n if (now > lastCleanup + 5e3) {\n instances.forEach((storedInstance, instanceId) => {\n storedInstance[CreatedKey] < lastCleanup &&\n storedInstance.nodeType &&\n !storedInstance.isConnected &&\n instances.delete(instanceId)\n })\n lastCleanup = now\n }\n }\n }\n let lastCleanup = 0\n const mainWindow = window.parent\n const docImpl = document.implementation.createHTMLDocument()\n const config = mainWindow.partytown || {}\n const libPath = (config.lib || '/~partytown/') + 'debug/'\n const logMain = msg => {\n console.debug.apply(console, [\n '%cMain 🌎',\n 'background: #717171; color: white; padding: 2px 3px; border-radius: 2px; font-size: 0.8em;',\n msg,\n ])\n }\n const winIds = []\n const normalizedWinId = winId => {\n winIds.includes(winId) || winIds.push(winId)\n return winIds.indexOf(winId) + 1\n }\n const defineCustomElement = (winId, worker, ceData) => {\n const Cstr = defineConstructorName(\n class extends winCtxs[winId].$window$.HTMLElement {},\n ceData[0]\n )\n const ceCallbackMethods = 'connectedCallback,disconnectedCallback,attributeChangedCallback,adoptedCallback'.split(\n ','\n )\n ceCallbackMethods.map(\n callbackMethodName =>\n (Cstr.prototype[callbackMethodName] = function (...args) {\n worker.postMessage([\n 15,\n winId,\n getAndSetInstanceId(this),\n callbackMethodName,\n args,\n ])\n })\n )\n Cstr.observedAttributes = ceData[1]\n return Cstr\n }\n const serializeForWorker = ($winId$, value, added, type, cstrName) =>\n void 0 !== value && (type = typeof value)\n ? 'string' === type ||\n 'number' === type ||\n 'boolean' === type ||\n null == value\n ? [0, value]\n : 'function' === type\n ? [6]\n : (added = added || new Set()) && Array.isArray(value)\n ? added.has(value)\n ? [1, []]\n : added.add(value) && [\n 1,\n value.map(v => serializeForWorker($winId$, v, added)),\n ]\n : 'object' === type\n ? serializedValueIsError(value)\n ? [\n 14,\n {\n name: value.name,\n message: value.message,\n stack: value.stack,\n },\n ]\n : '' === (cstrName = getConstructorName(value))\n ? [2, {}]\n : 'Window' === cstrName\n ? [3, [$winId$, $winId$]]\n : 'HTMLCollection' === cstrName || 'NodeList' === cstrName\n ? [\n 7,\n Array.from(value).map(\n v => serializeForWorker($winId$, v, added)[1]\n ),\n ]\n : cstrName.endsWith('Event')\n ? [5, serializeObjectForWorker($winId$, value, added)]\n : 'CSSRuleList' === cstrName\n ? [12, Array.from(value).map(serializeCssRuleForWorker)]\n : startsWith(cstrName, 'CSS') && cstrName.endsWith('Rule')\n ? [11, serializeCssRuleForWorker(value)]\n : 'CSSStyleDeclaration' === cstrName\n ? [13, serializeObjectForWorker($winId$, value, added)]\n : 'Attr' === cstrName\n ? [10, [value.name, value.value]]\n : value.nodeType\n ? [3, [$winId$, getAndSetInstanceId(value), getNodeName(value)]]\n : [2, serializeObjectForWorker($winId$, value, added, true, true)]\n : void 0\n : value\n const serializeObjectForWorker = (\n winId,\n obj,\n added,\n includeFunctions,\n includeEmptyStrings,\n serializedObj,\n propName,\n propValue\n ) => {\n serializedObj = {}\n if (!added.has(obj)) {\n added.add(obj)\n for (propName in obj) {\n if (isValidMemberName(propName)) {\n propValue =\n 'path' === propName && getConstructorName(obj).endsWith('Event')\n ? obj.composedPath()\n : obj[propName]\n ;(includeFunctions || 'function' != typeof propValue) &&\n (includeEmptyStrings || '' !== propValue) &&\n (serializedObj[propName] = serializeForWorker(\n winId,\n propValue,\n added\n ))\n }\n }\n }\n return serializedObj\n }\n const serializeCssRuleForWorker = cssRule => {\n let obj = {}\n let key\n for (key in cssRule) {\n validCssRuleProps.includes(key) && (obj[key] = String(cssRule[key]))\n }\n return obj\n }\n const serializedValueIsError = value => value instanceof window.top.Error\n const deserializeFromWorker = (\n worker,\n serializedTransfer,\n serializedType,\n serializedValue\n ) => {\n if (serializedTransfer) {\n serializedType = serializedTransfer[0]\n serializedValue = serializedTransfer[1]\n return 0 === serializedType\n ? serializedValue\n : 4 === serializedType\n ? deserializeRefFromWorker(worker, serializedValue)\n : 1 === serializedType\n ? serializedValue.map(v => deserializeFromWorker(worker, v))\n : 3 === serializedType\n ? getInstance(serializedValue[0], serializedValue[1])\n : 5 === serializedType\n ? constructEvent(deserializeObjectFromWorker(worker, serializedValue))\n : 2 === serializedType\n ? deserializeObjectFromWorker(worker, serializedValue)\n : 8 === serializedType\n ? serializedValue\n : 9 === serializedType\n ? new window[serializedTransfer[2]](serializedValue)\n : void 0\n }\n }\n const deserializeRefFromWorker = (\n worker,\n { $winId$: $winId$, $instanceId$: $instanceId$, $refId$: $refId$ },\n ref\n ) => {\n ref = mainRefs.get($refId$)\n if (!ref) {\n ref = function (...args) {\n worker.postMessage([\n 9,\n {\n $winId$: $winId$,\n $instanceId$: $instanceId$,\n $refId$: $refId$,\n $thisArg$: serializeForWorker($winId$, this),\n $args$: serializeForWorker($winId$, args),\n },\n ])\n }\n mainRefs.set($refId$, ref)\n }\n return ref\n }\n const constructEvent = eventProps =>\n new ('detail' in eventProps ? CustomEvent : Event)(\n eventProps.type,\n eventProps\n )\n const deserializeObjectFromWorker = (worker, serializedValue, obj, key) => {\n obj = {}\n for (key in serializedValue) {\n obj[key] = deserializeFromWorker(worker, serializedValue[key])\n }\n return obj\n }\n const validCssRuleProps = 'cssText,selectorText,href,media,namespaceURI,prefix,name,conditionText'.split(\n ','\n )\n const mainAccessHandler = async (worker, accessReq) => {\n let accessRsp = {\n $msgId$: accessReq.$msgId$,\n }\n let totalTasks = len(accessReq.$tasks$)\n let i = 0\n let task\n let winId\n let applyPath\n let instance\n let rtnValue\n let isLast\n for (; i < totalTasks; i++) {\n try {\n isLast = i === totalTasks - 1\n task = accessReq.$tasks$[i]\n winId = task.$winId$\n applyPath = task.$applyPath$\n !winCtxs[winId] &&\n winId.startsWith('f_') &&\n (await new Promise(resolve => {\n let check = 0\n let callback = () => {\n winCtxs[winId] || check++ > 1e3\n ? resolve()\n : requestAnimationFrame(callback)\n }\n callback()\n }))\n if (1 === applyPath[0] && applyPath[1] in winCtxs[winId].$window$) {\n setInstanceId(\n new winCtxs[winId].$window$[applyPath[1]](\n ...deserializeFromWorker(worker, applyPath[2])\n ),\n task.$instanceId$\n )\n } else {\n instance = getInstance(winId, task.$instanceId$)\n if (instance) {\n rtnValue = applyToInstance(\n worker,\n winId,\n instance,\n applyPath,\n isLast,\n task.$groupedGetters$\n )\n task.$assignInstanceId$ &&\n ('string' == typeof task.$assignInstanceId$\n ? setInstanceId(rtnValue, task.$assignInstanceId$)\n : (winCtxs[task.$assignInstanceId$.$winId$] = {\n $winId$: task.$assignInstanceId$.$winId$,\n $window$: {\n document: rtnValue,\n },\n }))\n if (isPromise(rtnValue)) {\n rtnValue = await rtnValue\n isLast && (accessRsp.$isPromise$ = true)\n }\n isLast &&\n (accessRsp.$rtnValue$ = serializeForWorker(winId, rtnValue))\n } else {\n accessRsp.$error$ = `Error finding instance \"${\n task.$instanceId$\n }\" on window ${normalizedWinId(winId)}`\n console.error(accessRsp.$error$, task)\n }\n }\n } catch (e) {\n isLast ? (accessRsp.$error$ = String(e.stack || e)) : console.error(e)\n }\n }\n return accessRsp\n }\n const applyToInstance = (\n worker,\n winId,\n instance,\n applyPath,\n isLast,\n groupedGetters\n ) => {\n let i = 0\n let l = len(applyPath)\n let next\n let current\n let previous\n let args\n let groupedRtnValues\n for (; i < l; i++) {\n current = applyPath[i]\n next = applyPath[i + 1]\n previous = applyPath[i - 1]\n try {\n if (!Array.isArray(next)) {\n if ('string' == typeof current || 'number' == typeof current) {\n if (i + 1 === l && groupedGetters) {\n groupedRtnValues = {}\n groupedGetters.map(\n propName => (groupedRtnValues[propName] = instance[propName])\n )\n return groupedRtnValues\n }\n instance = instance[current]\n } else {\n if (0 === next) {\n instance[previous] = deserializeFromWorker(worker, current)\n return\n }\n if ('function' == typeof instance[previous]) {\n args = deserializeFromWorker(worker, current)\n 'define' === previous &&\n 'CustomElementRegistry' === getConstructorName(instance) &&\n (args[1] = defineCustomElement(winId, worker, args[1]))\n 'insertRule' === previous &&\n args[1] > len(instance.cssRules) &&\n (args[1] = len(instance.cssRules))\n instance = instance[previous].apply(instance, args)\n if ('play' === previous) {\n return Promise.resolve()\n }\n }\n }\n }\n } catch (err) {\n if (isLast) {\n throw err\n }\n console.debug('Non-blocking setter error:', err)\n }\n }\n return instance\n }\n const readNextScript = (worker, winCtx) => {\n let $winId$ = winCtx.$winId$\n let win = winCtx.$window$\n let doc = win.document\n let scriptSelector =\n 'script[type=\"text/partytown\"]:not([data-ptid]):not([data-pterror])'\n let scriptElm\n let $instanceId$\n let scriptData\n if (doc && doc.body) {\n scriptElm = doc.querySelector(\n 'script[type=\"text/partytown\"]:not([data-ptid]):not([data-pterror]):not([async]):not([defer])'\n )\n scriptElm || (scriptElm = doc.querySelector(scriptSelector))\n if (scriptElm) {\n scriptElm.dataset.ptid = $instanceId$ = getAndSetInstanceId(\n scriptElm,\n $winId$\n )\n scriptData = {\n $winId$: $winId$,\n $instanceId$: $instanceId$,\n }\n if (scriptElm.src) {\n scriptData.$url$ = scriptElm.src\n scriptData.$orgUrl$ = scriptElm.dataset.ptsrc || scriptElm.src\n } else {\n scriptData.$content$ = scriptElm.innerHTML\n }\n worker.postMessage([7, scriptData])\n } else {\n if (!winCtx.$isInitialized$) {\n winCtx.$isInitialized$ = 1\n ;((worker, $winId$, win) => {\n let queuedForwardCalls = win._ptf\n let forwards = (win.partytown || {}).forward || []\n let i\n let mainForwardFn\n let forwardCall = ($forward$, args) =>\n worker.postMessage([\n 10,\n {\n $winId$: $winId$,\n $forward$: $forward$,\n $args$: serializeForWorker($winId$, Array.from(args)),\n },\n ])\n win._ptf = void 0\n forwards.map(forwardProps => {\n mainForwardFn = win\n forwardProps.split('.').map((_, i, arr) => {\n mainForwardFn = mainForwardFn[arr[i]] =\n i + 1 < len(arr)\n ? mainForwardFn[arr[i]] || ('push' === arr[i + 1] ? [] : {})\n : (...args) => forwardCall(arr, args)\n })\n })\n if (queuedForwardCalls) {\n for (i = 0; i < len(queuedForwardCalls); i += 2) {\n forwardCall(queuedForwardCalls[i], queuedForwardCalls[i + 1])\n }\n }\n })(worker, $winId$, win)\n doc.dispatchEvent(new CustomEvent('pt0'))\n {\n const winType = win === win.top ? 'top' : 'iframe'\n logMain(\n `Executed ${winType} window ${normalizedWinId(\n $winId$\n )} environment scripts in ${(\n performance.now() - winCtx.$startTime$\n ).toFixed(1)}ms`\n )\n }\n }\n worker.postMessage([8, $winId$])\n }\n } else {\n requestAnimationFrame(() => readNextScript(worker, winCtx))\n }\n }\n const registerWindow = (worker, $winId$, $window$) => {\n if (!windowIds.has($window$)) {\n windowIds.set($window$, $winId$)\n const doc = $window$.document\n const history = $window$.history\n const $parentWinId$ = windowIds.get($window$.parent)\n let initialised = false\n const onInitialisedQueue = []\n const onInitialised = callback => {\n initialised ? callback() : onInitialisedQueue.push(callback)\n }\n const sendInitEnvData = () => {\n worker.postMessage([\n 5,\n {\n $winId$: $winId$,\n $parentWinId$: $parentWinId$,\n $url$: doc.baseURI,\n $visibilityState$: doc.visibilityState,\n },\n ])\n setTimeout(() => {\n initialised = true\n onInitialisedQueue.forEach(callback => {\n callback()\n })\n })\n }\n const pushState = history.pushState.bind(history)\n const replaceState = history.replaceState.bind(history)\n const onLocationChange = (type, state, newUrl, oldUrl) => () => {\n setTimeout(() => {\n worker.postMessage([\n 13,\n {\n $winId$: $winId$,\n type: type,\n state: state,\n url: doc.baseURI,\n newUrl: newUrl,\n oldUrl: oldUrl,\n },\n ])\n })\n }\n history.pushState = (state, _, newUrl) => {\n pushState(state, _, newUrl)\n onInitialised(\n onLocationChange(\n 0,\n state,\n null == newUrl ? void 0 : newUrl.toString()\n )\n )\n }\n history.replaceState = (state, _, newUrl) => {\n replaceState(state, _, newUrl)\n onInitialised(\n onLocationChange(\n 1,\n state,\n null == newUrl ? void 0 : newUrl.toString()\n )\n )\n }\n $window$.addEventListener('popstate', event => {\n onInitialised(onLocationChange(2, event.state))\n })\n $window$.addEventListener('hashchange', event => {\n onInitialised(onLocationChange(3, {}, event.newURL, event.oldURL))\n })\n $window$.addEventListener('ptupdate', () => {\n readNextScript(worker, winCtxs[$winId$])\n })\n doc.addEventListener('visibilitychange', () =>\n worker.postMessage([14, $winId$, doc.visibilityState])\n )\n winCtxs[$winId$] = {\n $winId$: $winId$,\n $window$: $window$,\n }\n winCtxs[$winId$].$startTime$ = performance.now()\n {\n const winType = $winId$ === $parentWinId$ ? 'top' : 'iframe'\n logMain(`Registered ${winType} window ${normalizedWinId($winId$)}`)\n }\n 'complete' === doc.readyState\n ? sendInitEnvData()\n : $window$.addEventListener('load', sendInitEnvData)\n }\n }\n const onMessageFromWebWorker = (worker, msg, winCtx) => {\n if (4 === msg[0]) {\n registerWindow(worker, randomId(), mainWindow)\n } else {\n winCtx = winCtxs[msg[1]]\n winCtx &&\n (7 === msg[0]\n ? requestAnimationFrame(() => readNextScript(worker, winCtx))\n : 6 === msg[0] &&\n ((worker, winCtx, instanceId, errorMsg, scriptElm) => {\n scriptElm = winCtx.$window$.document.querySelector(\n `[data-ptid=\"${instanceId}\"]`\n )\n if (scriptElm) {\n errorMsg\n ? (scriptElm.dataset.pterror = errorMsg)\n : (scriptElm.type += '-x')\n delete scriptElm.dataset.ptid\n }\n readNextScript(worker, winCtx)\n })(worker, winCtx, msg[2], msg[3]))\n }\n }\n const readMainPlatform = () => {\n const elm = docImpl.createElement('i')\n const textNode = docImpl.createTextNode('')\n const comment = docImpl.createComment('')\n const frag = docImpl.createDocumentFragment()\n const shadowRoot = docImpl.createElement('p').attachShadow({\n mode: 'open',\n })\n const intersectionObserver = getGlobalConstructor(\n mainWindow,\n 'IntersectionObserver'\n )\n const mutationObserver = getGlobalConstructor(\n mainWindow,\n 'MutationObserver'\n )\n const resizeObserver = getGlobalConstructor(mainWindow, 'ResizeObserver')\n const perf = mainWindow.performance\n const screen = mainWindow.screen\n const impls = [\n [mainWindow.history],\n [perf],\n [perf.navigation],\n [perf.timing],\n [screen],\n [screen.orientation],\n [mainWindow.visualViewport],\n [intersectionObserver, 12],\n [mutationObserver, 12],\n [resizeObserver, 12],\n [textNode],\n [comment],\n [frag],\n [shadowRoot],\n [elm],\n [elm.attributes],\n [elm.classList],\n [elm.dataset],\n [elm.style],\n [docImpl],\n [docImpl.doctype],\n ]\n const initialInterfaces = [\n readImplementation('Window', mainWindow),\n readImplementation('Node', textNode),\n ]\n const $config$ = JSON.stringify(config, (k, v) => {\n if ('function' == typeof v) {\n v = String(v)\n v.startsWith(k + '(') && (v = 'function ' + v)\n }\n return v\n })\n const initWebWorkerData = {\n $config$: $config$,\n $interfaces$: readImplementations(impls, initialInterfaces),\n $libPath$: new URL(libPath, mainWindow.location) + '',\n $origin$: origin,\n $localStorage$: readStorage('localStorage'),\n $sessionStorage$: readStorage('sessionStorage'),\n }\n addGlobalConstructorUsingPrototype(\n initWebWorkerData.$interfaces$,\n mainWindow,\n 'IntersectionObserverEntry'\n )\n return initWebWorkerData\n }\n const readMainInterfaces = () => {\n const elms = Object.getOwnPropertyNames(mainWindow)\n .map(interfaceName =>\n ((doc, interfaceName, r, tag) => {\n r = interfaceName.match(/^(HTML|SVG)(.+)Element$/)\n if (r) {\n tag = r[2]\n return 'S' == interfaceName[0]\n ? doc.createElementNS(\n 'http://www.w3.org/2000/svg',\n svgConstructorTags[tag] ||\n tag.slice(0, 2).toLowerCase() + tag.slice(2)\n )\n : doc.createElement(htmlConstructorTags[tag] || tag)\n }\n })(docImpl, interfaceName)\n )\n .filter(elm => elm)\n .map(elm => [elm])\n return readImplementations(elms, [])\n }\n const cstrs = new Set(['Object'])\n const readImplementations = (impls, interfaces) => {\n const cstrImpls = impls\n .filter(implData => implData[0])\n .map(implData => {\n const impl = implData[0]\n const interfaceType = implData[1]\n const cstrName = getConstructorName(impl)\n const CstrPrototype = mainWindow[cstrName].prototype\n return [cstrName, CstrPrototype, impl, interfaceType]\n })\n cstrImpls.map(([cstrName, CstrPrototype, impl, intefaceType]) =>\n readOwnImplementation(\n cstrs,\n interfaces,\n cstrName,\n CstrPrototype,\n impl,\n intefaceType\n )\n )\n return interfaces\n }\n const readImplementation = (cstrName, impl, memberName) => {\n let interfaceMembers = []\n let interfaceInfo = [cstrName, 'Object', interfaceMembers]\n for (memberName in impl) {\n readImplementationMember(interfaceMembers, impl, memberName)\n }\n return interfaceInfo\n }\n const readOwnImplementation = (\n cstrs,\n interfaces,\n cstrName,\n CstrPrototype,\n impl,\n interfaceType\n ) => {\n if (!cstrs.has(cstrName)) {\n cstrs.add(cstrName)\n const SuperCstr = Object.getPrototypeOf(CstrPrototype)\n const superCstrName = getConstructorName(SuperCstr)\n const interfaceMembers = []\n const propDescriptors = Object.getOwnPropertyDescriptors(CstrPrototype)\n readOwnImplementation(\n cstrs,\n interfaces,\n superCstrName,\n SuperCstr,\n impl,\n interfaceType\n )\n for (const memberName in propDescriptors) {\n readImplementationMember(interfaceMembers, impl, memberName)\n }\n interfaces.push([\n cstrName,\n superCstrName,\n interfaceMembers,\n interfaceType,\n getNodeName(impl),\n ])\n }\n }\n const readImplementationMember = (\n interfaceMembers,\n implementation,\n memberName,\n value,\n memberType,\n cstrName\n ) => {\n try {\n if (\n isValidMemberName(memberName) &&\n isNaN(memberName[0]) &&\n 'all' !== memberName\n ) {\n value = implementation[memberName]\n memberType = typeof value\n if ('function' === memberType) {\n ;(String(value).includes('[native') ||\n Object.getPrototypeOf(implementation)[memberName]) &&\n interfaceMembers.push([memberName, 5])\n } else if ('object' === memberType && null != value) {\n cstrName = getConstructorName(value)\n 'Object' !== cstrName &&\n self[cstrName] &&\n interfaceMembers.push([memberName, value.nodeType || cstrName])\n } else {\n 'symbol' !== memberType &&\n (memberName.toUpperCase() === memberName\n ? interfaceMembers.push([memberName, 6, value])\n : interfaceMembers.push([memberName, 6]))\n }\n }\n } catch (e) {\n console.warn(e)\n }\n }\n const readStorage = storageName => {\n let items = []\n let i = 0\n let l = len(mainWindow[storageName])\n let key\n for (; i < l; i++) {\n key = mainWindow[storageName].key(i)\n items.push([key, mainWindow[storageName].getItem(key)])\n }\n return items\n }\n const getGlobalConstructor = (mainWindow, cstrName) =>\n void 0 !== mainWindow[cstrName] ? new mainWindow[cstrName](noop) : 0\n const addGlobalConstructorUsingPrototype = (\n $interfaces$,\n mainWindow,\n cstrName\n ) => {\n void 0 !== mainWindow[cstrName] &&\n $interfaces$.push([\n cstrName,\n 'Object',\n Object.keys(mainWindow[cstrName].prototype).map(propName => [\n propName,\n 6,\n ]),\n 12,\n ])\n }\n let worker\n ;(receiveMessage => {\n const swContainer = window.navigator.serviceWorker\n return swContainer.getRegistration().then(swRegistration => {\n swContainer.addEventListener('message', ev =>\n receiveMessage(\n ev.data,\n accessRsp =>\n swRegistration.active &&\n swRegistration.active.postMessage(accessRsp)\n )\n )\n return (worker, msg) => {\n 0 === msg[0]\n ? worker.postMessage([1, readMainPlatform()])\n : 2 === msg[0]\n ? worker.postMessage([3, readMainInterfaces()])\n : onMessageFromWebWorker(worker, msg)\n }\n })\n })((accessReq, responseCallback) =>\n mainAccessHandler(worker, accessReq).then(responseCallback)\n ).then(onMessageHandler => {\n if (onMessageHandler) {\n worker = new Worker(libPath + 'partytown-ww-sw.js?v=0.7.4', {\n name: 'Partytown 🎉',\n })\n worker.onmessage = ev => {\n const msg = ev.data\n 12 === msg[0]\n ? mainAccessHandler(worker, msg[1])\n : onMessageHandler(worker, msg)\n }\n logMain('Created Partytown web worker (0.7.4)')\n worker.onerror = ev => console.error('Web Worker Error', ev)\n mainWindow.addEventListener('pt1', ev =>\n registerWindow(\n worker,\n getAndSetInstanceId(ev.detail.frameElement),\n ev.detail\n )\n )\n }\n })\n})(window)\n\n```"
}
] |
code_partytown_30e4977b
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of partytown/public/~partytown/debug/partytown-sw.js from the partytown VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\n/* Partytown 0.7.4 - MIT builder.io */\nconst resolves = new Map()\n\nconst swMessageError = (accessReq, $error$) => ({\n $msgId$: accessReq.$msgId$,\n $error$: $error$,\n})\n\nconst httpRequestFromWebWorker = req =>\n new Promise(async resolve => {\n const accessReq = await req.clone().json()\n const responseData = await (accessReq =>\n new Promise(async resolve => {\n const clients = await self.clients.matchAll()\n const client = [...clients].sort((a, b) =>\n a.url > b.url ? -1 : a.url < b.url ? 1 : 0\n )[0]\n if (client) {\n const timeout = 12e4\n const msgResolve = [\n resolve,\n setTimeout(() => {\n resolves.delete(accessReq.$msgId$)\n resolve(swMessageError(accessReq, 'Timeout'))\n }, timeout),\n ]\n resolves.set(accessReq.$msgId$, msgResolve)\n client.postMessage(accessReq)\n } else {\n resolve(swMessageError(accessReq, 'NoParty'))\n }\n }))(accessReq)\n resolve(response(JSON.stringify(responseData), 'application/json'))\n })\n\nconst response = (body, contentType) =>\n new Response(body, {\n headers: {\n 'content-type': contentType || 'text/html',\n 'Cache-Control': 'no-store',\n },\n })\n\nself.oninstall = () => self.skipWaiting()\n\nself.onactivate = () => self.clients.claim()\n\nself.onmessage = ev => {\n const accessRsp = ev.data\n const r = resolves.get(accessRsp.$msgId$)\n if (r) {\n resolves.delete(accessRsp.$msgId$)\n clearTimeout(r[1])\n r[0](accessRsp)\n }\n}\n\nself.onfetch = ev => {\n const req = ev.request\n const url = new URL(req.url)\n const pathname = url.pathname\n if (pathname.endsWith('sw.html')) {\n ev.respondWith(\n response(\n '<!DOCTYPE html><html><head><meta charset=\"utf-8\"><script src=\"./partytown-sandbox-sw.js?v=0.7.4\"></script></head></html>'\n )\n )\n } else {\n pathname.endsWith('proxytown') &&\n ev.respondWith(httpRequestFromWebWorker(req))\n }\n}\n\n```"
}
] |
code_partytown_20d8ac12
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of partytown/public/~partytown/debug/partytown-atomics.js from the partytown VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\n/* Partytown 0.7.4 - MIT builder.io */\n;(window => {\n const isPromise = v => 'object' == typeof v && v && v.then\n const noop = () => {}\n const len = obj => obj.length\n const getConstructorName = obj => {\n var _a, _b, _c\n try {\n const constructorName =\n null === (_a = null == obj ? void 0 : obj.constructor) || void 0 === _a\n ? void 0\n : _a.name\n if (constructorName) {\n return constructorName\n }\n } catch (e) {}\n try {\n const zoneJsConstructorName =\n null ===\n (_c =\n null ===\n (_b =\n null == obj ? void 0 : obj.__zone_symbol__originalInstance) ||\n void 0 === _b\n ? void 0\n : _b.constructor) || void 0 === _c\n ? void 0\n : _c.name\n if (zoneJsConstructorName) {\n return zoneJsConstructorName\n }\n } catch (e) {}\n return ''\n }\n const startsWith = (str, val) => str.startsWith(val)\n const isValidMemberName = memberName =>\n !(\n startsWith(memberName, 'webkit') ||\n startsWith(memberName, 'toJSON') ||\n startsWith(memberName, 'constructor') ||\n startsWith(memberName, 'toString') ||\n startsWith(memberName, '_')\n )\n const getNodeName = node =>\n 11 === node.nodeType && node.host ? '#s' : node.nodeName\n const randomId = () =>\n Math.round(Math.random() * Number.MAX_SAFE_INTEGER).toString(36)\n const defineConstructorName = (Cstr, value) =>\n ((obj, memberName, descriptor) =>\n Object.defineProperty(obj, memberName, {\n ...descriptor,\n configurable: true,\n }))(Cstr, 'name', {\n value: value,\n })\n const htmlConstructorTags = {\n Anchor: 'a',\n DList: 'dl',\n Image: 'img',\n OList: 'ol',\n Paragraph: 'p',\n Quote: 'q',\n TableCaption: 'caption',\n TableCell: 'td',\n TableCol: 'colgroup',\n TableRow: 'tr',\n TableSection: 'tbody',\n UList: 'ul',\n }\n const svgConstructorTags = {\n Graphics: 'g',\n SVG: 'svg',\n }\n const InstanceIdKey = Symbol()\n const CreatedKey = Symbol()\n const instances = new Map()\n const mainRefs = new Map()\n const winCtxs = {}\n const windowIds = new WeakMap()\n const getAndSetInstanceId = (instance, instanceId) => {\n if (instance) {\n if ((instanceId = windowIds.get(instance))) {\n return instanceId\n }\n ;(instanceId = instance[InstanceIdKey]) ||\n setInstanceId(instance, (instanceId = randomId()))\n return instanceId\n }\n }\n const getInstance = (winId, instanceId, win, doc, docId) => {\n if ((win = winCtxs[winId]) && win.$window$) {\n if (winId === instanceId) {\n return win.$window$\n }\n doc = win.$window$.document\n docId = instanceId.split('.').pop()\n if ('d' === docId) {\n return doc\n }\n if ('e' === docId) {\n return doc.documentElement\n }\n if ('h' === docId) {\n return doc.head\n }\n if ('b' === docId) {\n return doc.body\n }\n }\n return instances.get(instanceId)\n }\n const setInstanceId = (instance, instanceId, now) => {\n if (instance) {\n instances.set(instanceId, instance)\n instance[InstanceIdKey] = instanceId\n instance[CreatedKey] = now = Date.now()\n if (now > lastCleanup + 5e3) {\n instances.forEach((storedInstance, instanceId) => {\n storedInstance[CreatedKey] < lastCleanup &&\n storedInstance.nodeType &&\n !storedInstance.isConnected &&\n instances.delete(instanceId)\n })\n lastCleanup = now\n }\n }\n }\n let lastCleanup = 0\n const mainWindow = window.parent\n const docImpl = document.implementation.createHTMLDocument()\n const config = mainWindow.partytown || {}\n const libPath = (config.lib || '/~partytown/') + 'debug/'\n const logMain = msg => {\n console.debug.apply(console, [\n '%cMain 🌎',\n 'background: #717171; color: white; padding: 2px 3px; border-radius: 2px; font-size: 0.8em;',\n msg,\n ])\n }\n const winIds = []\n const normalizedWinId = winId => {\n winIds.includes(winId) || winIds.push(winId)\n return winIds.indexOf(winId) + 1\n }\n const defineCustomElement = (winId, worker, ceData) => {\n const Cstr = defineConstructorName(\n class extends winCtxs[winId].$window$.HTMLElement {},\n ceData[0]\n )\n const ceCallbackMethods = 'connectedCallback,disconnectedCallback,attributeChangedCallback,adoptedCallback'.split(\n ','\n )\n ceCallbackMethods.map(\n callbackMethodName =>\n (Cstr.prototype[callbackMethodName] = function (...args) {\n worker.postMessage([\n 15,\n winId,\n getAndSetInstanceId(this),\n callbackMethodName,\n args,\n ])\n })\n )\n Cstr.observedAttributes = ceData[1]\n return Cstr\n }\n const serializeForWorker = ($winId$, value, added, type, cstrName) =>\n void 0 !== value && (type = typeof value)\n ? 'string' === type ||\n 'number' === type ||\n 'boolean' === type ||\n null == value\n ? [0, value]\n : 'function' === type\n ? [6]\n : (added = added || new Set()) && Array.isArray(value)\n ? added.has(value)\n ? [1, []]\n : added.add(value) && [\n 1,\n value.map(v => serializeForWorker($winId$, v, added)),\n ]\n : 'object' === type\n ? serializedValueIsError(value)\n ? [\n 14,\n {\n name: value.name,\n message: value.message,\n stack: value.stack,\n },\n ]\n : '' === (cstrName = getConstructorName(value))\n ? [2, {}]\n : 'Window' === cstrName\n ? [3, [$winId$, $winId$]]\n : 'HTMLCollection' === cstrName || 'NodeList' === cstrName\n ? [\n 7,\n Array.from(value).map(\n v => serializeForWorker($winId$, v, added)[1]\n ),\n ]\n : cstrName.endsWith('Event')\n ? [5, serializeObjectForWorker($winId$, value, added)]\n : 'CSSRuleList' === cstrName\n ? [12, Array.from(value).map(serializeCssRuleForWorker)]\n : startsWith(cstrName, 'CSS') && cstrName.endsWith('Rule')\n ? [11, serializeCssRuleForWorker(value)]\n : 'CSSStyleDeclaration' === cstrName\n ? [13, serializeObjectForWorker($winId$, value, added)]\n : 'Attr' === cstrName\n ? [10, [value.name, value.value]]\n : value.nodeType\n ? [3, [$winId$, getAndSetInstanceId(value), getNodeName(value)]]\n : [2, serializeObjectForWorker($winId$, value, added, true, true)]\n : void 0\n : value\n const serializeObjectForWorker = (\n winId,\n obj,\n added,\n includeFunctions,\n includeEmptyStrings,\n serializedObj,\n propName,\n propValue\n ) => {\n serializedObj = {}\n if (!added.has(obj)) {\n added.add(obj)\n for (propName in obj) {\n if (isValidMemberName(propName)) {\n propValue =\n 'path' === propName && getConstructorName(obj).endsWith('Event')\n ? obj.composedPath()\n : obj[propName]\n ;(includeFunctions || 'function' != typeof propValue) &&\n (includeEmptyStrings || '' !== propValue) &&\n (serializedObj[propName] = serializeForWorker(\n winId,\n propValue,\n added\n ))\n }\n }\n }\n return serializedObj\n }\n const serializeCssRuleForWorker = cssRule => {\n let obj = {}\n let key\n for (key in cssRule) {\n validCssRuleProps.includes(key) && (obj[key] = String(cssRule[key]))\n }\n return obj\n }\n const serializedValueIsError = value => value instanceof window.top.Error\n const deserializeFromWorker = (\n worker,\n serializedTransfer,\n serializedType,\n serializedValue\n ) => {\n if (serializedTransfer) {\n serializedType = serializedTransfer[0]\n serializedValue = serializedTransfer[1]\n return 0 === serializedType\n ? serializedValue\n : 4 === serializedType\n ? deserializeRefFromWorker(worker, serializedValue)\n : 1 === serializedType\n ? serializedValue.map(v => deserializeFromWorker(worker, v))\n : 3 === serializedType\n ? getInstance(serializedValue[0], serializedValue[1])\n : 5 === serializedType\n ? constructEvent(deserializeObjectFromWorker(worker, serializedValue))\n : 2 === serializedType\n ? deserializeObjectFromWorker(worker, serializedValue)\n : 8 === serializedType\n ? serializedValue\n : 9 === serializedType\n ? new window[serializedTransfer[2]](serializedValue)\n : void 0\n }\n }\n const deserializeRefFromWorker = (\n worker,\n { $winId$: $winId$, $instanceId$: $instanceId$, $refId$: $refId$ },\n ref\n ) => {\n ref = mainRefs.get($refId$)\n if (!ref) {\n ref = function (...args) {\n worker.postMessage([\n 9,\n {\n $winId$: $winId$,\n $instanceId$: $instanceId$,\n $refId$: $refId$,\n $thisArg$: serializeForWorker($winId$, this),\n $args$: serializeForWorker($winId$, args),\n },\n ])\n }\n mainRefs.set($refId$, ref)\n }\n return ref\n }\n const constructEvent = eventProps =>\n new ('detail' in eventProps ? CustomEvent : Event)(\n eventProps.type,\n eventProps\n )\n const deserializeObjectFromWorker = (worker, serializedValue, obj, key) => {\n obj = {}\n for (key in serializedValue) {\n obj[key] = deserializeFromWorker(worker, serializedValue[key])\n }\n return obj\n }\n const validCssRuleProps = 'cssText,selectorText,href,media,namespaceURI,prefix,name,conditionText'.split(\n ','\n )\n const mainAccessHandler = async (worker, accessReq) => {\n let accessRsp = {\n $msgId$: accessReq.$msgId$,\n }\n let totalTasks = len(accessReq.$tasks$)\n let i = 0\n let task\n let winId\n let applyPath\n let instance\n let rtnValue\n let isLast\n for (; i < totalTasks; i++) {\n try {\n isLast = i === totalTasks - 1\n task = accessReq.$tasks$[i]\n winId = task.$winId$\n applyPath = task.$applyPath$\n !winCtxs[winId] &&\n winId.startsWith('f_') &&\n (await new Promise(resolve => {\n let check = 0\n let callback = () => {\n winCtxs[winId] || check++ > 1e3\n ? resolve()\n : requestAnimationFrame(callback)\n }\n callback()\n }))\n if (1 === applyPath[0] && applyPath[1] in winCtxs[winId].$window$) {\n setInstanceId(\n new winCtxs[winId].$window$[applyPath[1]](\n ...deserializeFromWorker(worker, applyPath[2])\n ),\n task.$instanceId$\n )\n } else {\n instance = getInstance(winId, task.$instanceId$)\n if (instance) {\n rtnValue = applyToInstance(\n worker,\n winId,\n instance,\n applyPath,\n isLast,\n task.$groupedGetters$\n )\n task.$assignInstanceId$ &&\n ('string' == typeof task.$assignInstanceId$\n ? setInstanceId(rtnValue, task.$assignInstanceId$)\n : (winCtxs[task.$assignInstanceId$.$winId$] = {\n $winId$: task.$assignInstanceId$.$winId$,\n $window$: {\n document: rtnValue,\n },\n }))\n if (isPromise(rtnValue)) {\n rtnValue = await rtnValue\n isLast && (accessRsp.$isPromise$ = true)\n }\n isLast &&\n (accessRsp.$rtnValue$ = serializeForWorker(winId, rtnValue))\n } else {\n accessRsp.$error$ = `Error finding instance \"${\n task.$instanceId$\n }\" on window ${normalizedWinId(winId)}`\n console.error(accessRsp.$error$, task)\n }\n }\n } catch (e) {\n isLast ? (accessRsp.$error$ = String(e.stack || e)) : console.error(e)\n }\n }\n return accessRsp\n }\n const applyToInstance = (\n worker,\n winId,\n instance,\n applyPath,\n isLast,\n groupedGetters\n ) => {\n let i = 0\n let l = len(applyPath)\n let next\n let current\n let previous\n let args\n let groupedRtnValues\n for (; i < l; i++) {\n current = applyPath[i]\n next = applyPath[i + 1]\n previous = applyPath[i - 1]\n try {\n if (!Array.isArray(next)) {\n if ('string' == typeof current || 'number' == typeof current) {\n if (i + 1 === l && groupedGetters) {\n groupedRtnValues = {}\n groupedGetters.map(\n propName => (groupedRtnValues[propName] = instance[propName])\n )\n return groupedRtnValues\n }\n instance = instance[current]\n } else {\n if (0 === next) {\n instance[previous] = deserializeFromWorker(worker, current)\n return\n }\n if ('function' == typeof instance[previous]) {\n args = deserializeFromWorker(worker, current)\n 'define' === previous &&\n 'CustomElementRegistry' === getConstructorName(instance) &&\n (args[1] = defineCustomElement(winId, worker, args[1]))\n 'insertRule' === previous &&\n args[1] > len(instance.cssRules) &&\n (args[1] = len(instance.cssRules))\n instance = instance[previous].apply(instance, args)\n if ('play' === previous) {\n return Promise.resolve()\n }\n }\n }\n }\n } catch (err) {\n if (isLast) {\n throw err\n }\n console.debug('Non-blocking setter error:', err)\n }\n }\n return instance\n }\n const readNextScript = (worker, winCtx) => {\n let $winId$ = winCtx.$winId$\n let win = winCtx.$window$\n let doc = win.document\n let scriptSelector =\n 'script[type=\"text/partytown\"]:not([data-ptid]):not([data-pterror])'\n let scriptElm\n let $instanceId$\n let scriptData\n if (doc && doc.body) {\n scriptElm = doc.querySelector(\n 'script[type=\"text/partytown\"]:not([data-ptid]):not([data-pterror]):not([async]):not([defer])'\n )\n scriptElm || (scriptElm = doc.querySelector(scriptSelector))\n if (scriptElm) {\n scriptElm.dataset.ptid = $instanceId$ = getAndSetInstanceId(\n scriptElm,\n $winId$\n )\n scriptData = {\n $winId$: $winId$,\n $instanceId$: $instanceId$,\n }\n if (scriptElm.src) {\n scriptData.$url$ = scriptElm.src\n scriptData.$orgUrl$ = scriptElm.dataset.ptsrc || scriptElm.src\n } else {\n scriptData.$content$ = scriptElm.innerHTML\n }\n worker.postMessage([7, scriptData])\n } else {\n if (!winCtx.$isInitialized$) {\n winCtx.$isInitialized$ = 1\n ;((worker, $winId$, win) => {\n let queuedForwardCalls = win._ptf\n let forwards = (win.partytown || {}).forward || []\n let i\n let mainForwardFn\n let forwardCall = ($forward$, args) =>\n worker.postMessage([\n 10,\n {\n $winId$: $winId$,\n $forward$: $forward$,\n $args$: serializeForWorker($winId$, Array.from(args)),\n },\n ])\n win._ptf = void 0\n forwards.map(forwardProps => {\n mainForwardFn = win\n forwardProps.split('.').map((_, i, arr) => {\n mainForwardFn = mainForwardFn[arr[i]] =\n i + 1 < len(arr)\n ? mainForwardFn[arr[i]] || ('push' === arr[i + 1] ? [] : {})\n : (...args) => forwardCall(arr, args)\n })\n })\n if (queuedForwardCalls) {\n for (i = 0; i < len(queuedForwardCalls); i += 2) {\n forwardCall(queuedForwardCalls[i], queuedForwardCalls[i + 1])\n }\n }\n })(worker, $winId$, win)\n doc.dispatchEvent(new CustomEvent('pt0'))\n {\n const winType = win === win.top ? 'top' : 'iframe'\n logMain(\n `Executed ${winType} window ${normalizedWinId(\n $winId$\n )} environment scripts in ${(\n performance.now() - winCtx.$startTime$\n ).toFixed(1)}ms`\n )\n }\n }\n worker.postMessage([8, $winId$])\n }\n } else {\n requestAnimationFrame(() => readNextScript(worker, winCtx))\n }\n }\n const registerWindow = (worker, $winId$, $window$) => {\n if (!windowIds.has($window$)) {\n windowIds.set($window$, $winId$)\n const doc = $window$.document\n const history = $window$.history\n const $parentWinId$ = windowIds.get($window$.parent)\n let initialised = false\n const onInitialisedQueue = []\n const onInitialised = callback => {\n initialised ? callback() : onInitialisedQueue.push(callback)\n }\n const sendInitEnvData = () => {\n worker.postMessage([\n 5,\n {\n $winId$: $winId$,\n $parentWinId$: $parentWinId$,\n $url$: doc.baseURI,\n $visibilityState$: doc.visibilityState,\n },\n ])\n setTimeout(() => {\n initialised = true\n onInitialisedQueue.forEach(callback => {\n callback()\n })\n })\n }\n const pushState = history.pushState.bind(history)\n const replaceState = history.replaceState.bind(history)\n const onLocationChange = (type, state, newUrl, oldUrl) => () => {\n setTimeout(() => {\n worker.postMessage([\n 13,\n {\n $winId$: $winId$,\n type: type,\n state: state,\n url: doc.baseURI,\n newUrl: newUrl,\n oldUrl: oldUrl,\n },\n ])\n })\n }\n history.pushState = (state, _, newUrl) => {\n pushState(state, _, newUrl)\n onInitialised(\n onLocationChange(\n 0,\n state,\n null == newUrl ? void 0 : newUrl.toString()\n )\n )\n }\n history.replaceState = (state, _, newUrl) => {\n replaceState(state, _, newUrl)\n onInitialised(\n onLocationChange(\n 1,\n state,\n null == newUrl ? void 0 : newUrl.toString()\n )\n )\n }\n $window$.addEventListener('popstate', event => {\n onInitialised(onLocationChange(2, event.state))\n })\n $window$.addEventListener('hashchange', event => {\n onInitialised(onLocationChange(3, {}, event.newURL, event.oldURL))\n })\n $window$.addEventListener('ptupdate', () => {\n readNextScript(worker, winCtxs[$winId$])\n })\n doc.addEventListener('visibilitychange', () =>\n worker.postMessage([14, $winId$, doc.visibilityState])\n )\n winCtxs[$winId$] = {\n $winId$: $winId$,\n $window$: $window$,\n }\n winCtxs[$winId$].$startTime$ = performance.now()\n {\n const winType = $winId$ === $parentWinId$ ? 'top' : 'iframe'\n logMain(`Registered ${winType} window ${normalizedWinId($winId$)}`)\n }\n 'complete' === doc.readyState\n ? sendInitEnvData()\n : $window$.addEventListener('load', sendInitEnvData)\n }\n }\n const onMessageFromWebWorker = (worker, msg, winCtx) => {\n if (4 === msg[0]) {\n registerWindow(worker, randomId(), mainWindow)\n } else {\n winCtx = winCtxs[msg[1]]\n winCtx &&\n (7 === msg[0]\n ? requestAnimationFrame(() => readNextScript(worker, winCtx))\n : 6 === msg[0] &&\n ((worker, winCtx, instanceId, errorMsg, scriptElm) => {\n scriptElm = winCtx.$window$.document.querySelector(\n `[data-ptid=\"${instanceId}\"]`\n )\n if (scriptElm) {\n errorMsg\n ? (scriptElm.dataset.pterror = errorMsg)\n : (scriptElm.type += '-x')\n delete scriptElm.dataset.ptid\n }\n readNextScript(worker, winCtx)\n })(worker, winCtx, msg[2], msg[3]))\n }\n }\n const readMainInterfaces = () => {\n const elms = Object.getOwnPropertyNames(mainWindow)\n .map(interfaceName =>\n ((doc, interfaceName, r, tag) => {\n r = interfaceName.match(/^(HTML|SVG)(.+)Element$/)\n if (r) {\n tag = r[2]\n return 'S' == interfaceName[0]\n ? doc.createElementNS(\n 'http://www.w3.org/2000/svg',\n svgConstructorTags[tag] ||\n tag.slice(0, 2).toLowerCase() + tag.slice(2)\n )\n : doc.createElement(htmlConstructorTags[tag] || tag)\n }\n })(docImpl, interfaceName)\n )\n .filter(elm => elm)\n .map(elm => [elm])\n return readImplementations(elms, [])\n }\n const cstrs = new Set(['Object'])\n const readImplementations = (impls, interfaces) => {\n const cstrImpls = impls\n .filter(implData => implData[0])\n .map(implData => {\n const impl = implData[0]\n const interfaceType = implData[1]\n const cstrName = getConstructorName(impl)\n const CstrPrototype = mainWindow[cstrName].prototype\n return [cstrName, CstrPrototype, impl, interfaceType]\n })\n cstrImpls.map(([cstrName, CstrPrototype, impl, intefaceType]) =>\n readOwnImplementation(\n cstrs,\n interfaces,\n cstrName,\n CstrPrototype,\n impl,\n intefaceType\n )\n )\n return interfaces\n }\n const readImplementation = (cstrName, impl, memberName) => {\n let interfaceMembers = []\n let interfaceInfo = [cstrName, 'Object', interfaceMembers]\n for (memberName in impl) {\n readImplementationMember(interfaceMembers, impl, memberName)\n }\n return interfaceInfo\n }\n const readOwnImplementation = (\n cstrs,\n interfaces,\n cstrName,\n CstrPrototype,\n impl,\n interfaceType\n ) => {\n if (!cstrs.has(cstrName)) {\n cstrs.add(cstrName)\n const SuperCstr = Object.getPrototypeOf(CstrPrototype)\n const superCstrName = getConstructorName(SuperCstr)\n const interfaceMembers = []\n const propDescriptors = Object.getOwnPropertyDescriptors(CstrPrototype)\n readOwnImplementation(\n cstrs,\n interfaces,\n superCstrName,\n SuperCstr,\n impl,\n interfaceType\n )\n for (const memberName in propDescriptors) {\n readImplementationMember(interfaceMembers, impl, memberName)\n }\n interfaces.push([\n cstrName,\n superCstrName,\n interfaceMembers,\n interfaceType,\n getNodeName(impl),\n ])\n }\n }\n const readImplementationMember = (\n interfaceMembers,\n implementation,\n memberName,\n value,\n memberType,\n cstrName\n ) => {\n try {\n if (\n isValidMemberName(memberName) &&\n isNaN(memberName[0]) &&\n 'all' !== memberName\n ) {\n value = implementation[memberName]\n memberType = typeof value\n if ('function' === memberType) {\n ;(String(value).includes('[native') ||\n Object.getPrototypeOf(implementation)[memberName]) &&\n interfaceMembers.push([memberName, 5])\n } else if ('object' === memberType && null != value) {\n cstrName = getConstructorName(value)\n 'Object' !== cstrName &&\n self[cstrName] &&\n interfaceMembers.push([memberName, value.nodeType || cstrName])\n } else {\n 'symbol' !== memberType &&\n (memberName.toUpperCase() === memberName\n ? interfaceMembers.push([memberName, 6, value])\n : interfaceMembers.push([memberName, 6]))\n }\n }\n } catch (e) {\n console.warn(e)\n }\n }\n const readStorage = storageName => {\n let items = []\n let i = 0\n let l = len(mainWindow[storageName])\n let key\n for (; i < l; i++) {\n key = mainWindow[storageName].key(i)\n items.push([key, mainWindow[storageName].getItem(key)])\n }\n return items\n }\n const getGlobalConstructor = (mainWindow, cstrName) =>\n void 0 !== mainWindow[cstrName] ? new mainWindow[cstrName](noop) : 0\n const addGlobalConstructorUsingPrototype = (\n $interfaces$,\n mainWindow,\n cstrName\n ) => {\n void 0 !== mainWindow[cstrName] &&\n $interfaces$.push([\n cstrName,\n 'Object',\n Object.keys(mainWindow[cstrName].prototype).map(propName => [\n propName,\n 6,\n ]),\n 12,\n ])\n }\n let worker\n ;(async receiveMessage => {\n const sharedDataBuffer = new SharedArrayBuffer(1073741824)\n const sharedData = new Int32Array(sharedDataBuffer)\n return (worker, msg) => {\n const msgType = msg[0]\n const accessReq = msg[1]\n if (0 === msgType) {\n const initData = (() => {\n const elm = docImpl.createElement('i')\n const textNode = docImpl.createTextNode('')\n const comment = docImpl.createComment('')\n const frag = docImpl.createDocumentFragment()\n const shadowRoot = docImpl.createElement('p').attachShadow({\n mode: 'open',\n })\n const intersectionObserver = getGlobalConstructor(\n mainWindow,\n 'IntersectionObserver'\n )\n const mutationObserver = getGlobalConstructor(\n mainWindow,\n 'MutationObserver'\n )\n const resizeObserver = getGlobalConstructor(\n mainWindow,\n 'ResizeObserver'\n )\n const perf = mainWindow.performance\n const screen = mainWindow.screen\n const impls = [\n [mainWindow.history],\n [perf],\n [perf.navigation],\n [perf.timing],\n [screen],\n [screen.orientation],\n [mainWindow.visualViewport],\n [intersectionObserver, 12],\n [mutationObserver, 12],\n [resizeObserver, 12],\n [textNode],\n [comment],\n [frag],\n [shadowRoot],\n [elm],\n [elm.attributes],\n [elm.classList],\n [elm.dataset],\n [elm.style],\n [docImpl],\n [docImpl.doctype],\n ]\n const initialInterfaces = [\n readImplementation('Window', mainWindow),\n readImplementation('Node', textNode),\n ]\n const $config$ = JSON.stringify(config, (k, v) => {\n if ('function' == typeof v) {\n v = String(v)\n v.startsWith(k + '(') && (v = 'function ' + v)\n }\n return v\n })\n const initWebWorkerData = {\n $config$: $config$,\n $interfaces$: readImplementations(impls, initialInterfaces),\n $libPath$: new URL(libPath, mainWindow.location) + '',\n $origin$: origin,\n $localStorage$: readStorage('localStorage'),\n $sessionStorage$: readStorage('sessionStorage'),\n }\n addGlobalConstructorUsingPrototype(\n initWebWorkerData.$interfaces$,\n mainWindow,\n 'IntersectionObserverEntry'\n )\n return initWebWorkerData\n })()\n initData.$sharedDataBuffer$ = sharedDataBuffer\n worker.postMessage([1, initData])\n } else {\n 2 === msg[0]\n ? worker.postMessage([3, readMainInterfaces()])\n : 11 === msgType\n ? receiveMessage(accessReq, accessRsp => {\n const stringifiedData = JSON.stringify(accessRsp)\n const stringifiedDataLength = stringifiedData.length\n for (let i = 0; i < stringifiedDataLength; i++) {\n sharedData[i + 1] = stringifiedData.charCodeAt(i)\n }\n sharedData[0] = stringifiedDataLength\n Atomics.notify(sharedData, 0)\n })\n : onMessageFromWebWorker(worker, msg)\n }\n }\n })((accessReq, responseCallback) =>\n mainAccessHandler(worker, accessReq).then(responseCallback)\n ).then(onMessageHandler => {\n if (onMessageHandler) {\n worker = new Worker(libPath + 'partytown-ww-atomics.js?v=0.7.4', {\n name: 'Partytown 🎉',\n })\n worker.onmessage = ev => {\n const msg = ev.data\n 12 === msg[0]\n ? mainAccessHandler(worker, msg[1])\n : onMessageHandler(worker, msg)\n }\n logMain('Created Partytown web worker (0.7.4)')\n worker.onerror = ev => console.error('Web Worker Error', ev)\n mainWindow.addEventListener('pt1', ev =>\n registerWindow(\n worker,\n getAndSetInstanceId(ev.detail.frameElement),\n ev.detail\n )\n )\n }\n })\n})(window)\n\n```"
}
] |
code_partytown_d6a7405c
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of partytown/public/~partytown/debug/partytown-ww-atomics.js from the partytown VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\n/* Partytown 0.7.4 - MIT builder.io */\n;(self => {\n const WinIdKey = Symbol()\n const InstanceIdKey = Symbol()\n const InstanceDataKey = Symbol()\n const NamespaceKey = Symbol()\n const ApplyPathKey = Symbol()\n const InstanceStateKey = Symbol()\n const HookContinue = Symbol()\n const HookPrevent = Symbol()\n const webWorkerInstances = new Map()\n const webWorkerRefsByRefId = {}\n const webWorkerRefIdsByRef = new WeakMap()\n const postMessages = []\n const webWorkerCtx = {}\n const webWorkerlocalStorage = new Map()\n const webWorkerSessionStorage = new Map()\n const environments = {}\n const cachedDimensions = new Map()\n const cachedStructure = new Map()\n const commaSplit = str => str.split(',')\n const partytownLibUrl = url => {\n url = webWorkerCtx.$libPath$ + url\n if (new URL(url).origin != location.origin) {\n throw 'Invalid ' + url\n }\n return url\n }\n const getterDimensionPropNames = commaSplit(\n 'clientWidth,clientHeight,clientTop,clientLeft,innerWidth,innerHeight,offsetWidth,offsetHeight,offsetTop,offsetLeft,outerWidth,outerHeight,pageXOffset,pageYOffset,scrollWidth,scrollHeight,scrollTop,scrollLeft'\n )\n const elementStructurePropNames = commaSplit(\n 'childElementCount,children,firstElementChild,lastElementChild,nextElementSibling,previousElementSibling'\n )\n const structureChangingMethodNames = commaSplit(\n 'insertBefore,remove,removeChild,replaceChild'\n )\n const dimensionChangingSetterNames = commaSplit(\n 'className,width,height,hidden,innerHTML,innerText,textContent'\n )\n const dimensionChangingMethodNames = commaSplit(\n 'setAttribute,setAttributeNS,setProperty'\n )\n const eventTargetMethods = commaSplit(\n 'addEventListener,dispatchEvent,removeEventListener'\n )\n const nonBlockingMethods = eventTargetMethods.concat(\n dimensionChangingMethodNames,\n commaSplit('add,observe,remove,unobserve')\n )\n const IS_TAG_REG = /^[A-Z_]([A-Z0-9-]*[A-Z0-9])?$/\n const noop = () => {}\n const len = obj => obj.length\n const getConstructorName = obj => {\n var _a, _b, _c\n try {\n const constructorName =\n null === (_a = null == obj ? void 0 : obj.constructor) || void 0 === _a\n ? void 0\n : _a.name\n if (constructorName) {\n return constructorName\n }\n } catch (e) {}\n try {\n const zoneJsConstructorName =\n null ===\n (_c =\n null ===\n (_b =\n null == obj ? void 0 : obj.__zone_symbol__originalInstance) ||\n void 0 === _b\n ? void 0\n : _b.constructor) || void 0 === _c\n ? void 0\n : _c.name\n if (zoneJsConstructorName) {\n return zoneJsConstructorName\n }\n } catch (e) {}\n return ''\n }\n const EMPTY_ARRAY = []\n const randomId = () =>\n Math.round(Math.random() * Number.MAX_SAFE_INTEGER).toString(36)\n const SCRIPT_TYPE = 'text/partytown'\n const defineProperty = (obj, memberName, descriptor) =>\n Object.defineProperty(obj, memberName, {\n ...descriptor,\n configurable: true,\n })\n const defineConstructorName = (Cstr, value) =>\n defineProperty(Cstr, 'name', {\n value: value,\n })\n const definePrototypeProperty = (Cstr, memberName, descriptor) =>\n defineProperty(Cstr.prototype, memberName, descriptor)\n const definePrototypePropertyDescriptor = (Cstr, propertyDescriptorMap) =>\n Object.defineProperties(Cstr.prototype, propertyDescriptorMap)\n const definePrototypeValue = (Cstr, memberName, value) =>\n definePrototypeProperty(Cstr, memberName, {\n value: value,\n writable: true,\n })\n const hasInstanceStateValue = (instance, stateKey) =>\n stateKey in instance[InstanceStateKey]\n const getInstanceStateValue = (instance, stateKey) =>\n instance[InstanceStateKey][stateKey]\n const setInstanceStateValue = (instance, stateKey, stateValue) =>\n (instance[InstanceStateKey][stateKey] = stateValue)\n const setWorkerRef = (ref, refId) => {\n if (!(refId = webWorkerRefIdsByRef.get(ref))) {\n webWorkerRefIdsByRef.set(ref, (refId = randomId()))\n webWorkerRefsByRefId[refId] = ref\n }\n return refId\n }\n const getOrCreateNodeInstance = (\n winId,\n instanceId,\n nodeName,\n namespace,\n instance\n ) => {\n instance = webWorkerInstances.get(instanceId)\n if (!instance && nodeName && environments[winId]) {\n instance = environments[winId].$createNode$(\n nodeName,\n instanceId,\n namespace\n )\n webWorkerInstances.set(instanceId, instance)\n }\n return instance\n }\n const definePrototypeNodeType = (Cstr, nodeType) =>\n definePrototypeValue(Cstr, 'nodeType', nodeType)\n const cachedTreeProps = (Cstr, treeProps) =>\n treeProps.map(propName =>\n definePrototypeProperty(Cstr, propName, {\n get() {\n let cacheKey = getInstanceCacheKey(this, propName)\n let result = cachedStructure.get(cacheKey)\n if (!result) {\n result = getter(this, [propName])\n cachedStructure.set(cacheKey, result)\n }\n return result\n },\n })\n )\n const getInstanceCacheKey = (instance, memberName, args) =>\n [\n instance[WinIdKey],\n instance[InstanceIdKey],\n memberName,\n ...(args || EMPTY_ARRAY).map(arg =>\n String(arg && arg[WinIdKey] ? arg[InstanceIdKey] : arg)\n ),\n ].join('.')\n const cachedProps = (Cstr, propNames) =>\n commaSplit(propNames).map(propName =>\n definePrototypeProperty(Cstr, propName, {\n get() {\n hasInstanceStateValue(this, propName) ||\n setInstanceStateValue(this, propName, getter(this, [propName]))\n return getInstanceStateValue(this, propName)\n },\n set(val) {\n getInstanceStateValue(this, propName) !== val &&\n setter(this, [propName], val)\n setInstanceStateValue(this, propName, val)\n },\n })\n )\n const cachedDimensionProps = Cstr =>\n getterDimensionPropNames.map(propName =>\n definePrototypeProperty(Cstr, propName, {\n get() {\n const dimension = cachedDimensions.get(\n getInstanceCacheKey(this, propName)\n )\n if ('number' == typeof dimension) {\n return dimension\n }\n const groupedDimensions = getter(\n this,\n [propName],\n getterDimensionPropNames\n )\n if (groupedDimensions && 'object' == typeof groupedDimensions) {\n Object.entries(\n groupedDimensions\n ).map(([dimensionPropName, value]) =>\n cachedDimensions.set(\n getInstanceCacheKey(this, dimensionPropName),\n value\n )\n )\n return groupedDimensions[propName]\n }\n return groupedDimensions\n },\n })\n )\n const cachedDimensionMethods = (Cstr, dimensionMethodNames) =>\n dimensionMethodNames.map(methodName => {\n Cstr.prototype[methodName] = function (...args) {\n let cacheKey = getInstanceCacheKey(this, methodName, args)\n let dimensions = cachedDimensions.get(cacheKey)\n if (!dimensions) {\n dimensions = callMethod(this, [methodName], args)\n cachedDimensions.set(cacheKey, dimensions)\n }\n return dimensions\n }\n })\n const serializeForMain = ($winId$, $instanceId$, value, added, type) =>\n void 0 !== value && (type = typeof value)\n ? 'string' === type ||\n 'boolean' === type ||\n 'number' === type ||\n null == value\n ? [0, value]\n : 'function' === type\n ? [\n 4,\n {\n $winId$: $winId$,\n $instanceId$: $instanceId$,\n $refId$: setWorkerRef(value),\n },\n ]\n : (added = added || new Set()) && Array.isArray(value)\n ? added.has(value)\n ? [1, []]\n : added.add(value) && [\n 1,\n value.map(v => serializeForMain($winId$, $instanceId$, v, added)),\n ]\n : 'object' === type\n ? value[InstanceIdKey]\n ? [3, [value[WinIdKey], value[InstanceIdKey]]]\n : value instanceof Event\n ? [\n 5,\n serializeObjectForMain(\n $winId$,\n $instanceId$,\n value,\n false,\n added\n ),\n ]\n : supportsTrustedHTML && value instanceof TrustedHTML\n ? [0, value.toString()]\n : value instanceof ArrayBuffer\n ? [8, value]\n : ArrayBuffer.isView(value)\n ? [9, value.buffer, getConstructorName(value)]\n : [\n 2,\n serializeObjectForMain($winId$, $instanceId$, value, true, added),\n ]\n : void 0\n : value\n const supportsTrustedHTML = 'undefined' != typeof TrustedHTML\n const serializeObjectForMain = (\n winId,\n instanceId,\n obj,\n includeFunctions,\n added,\n serializedObj,\n propName,\n propValue\n ) => {\n serializedObj = {}\n if (!added.has(obj)) {\n added.add(obj)\n for (propName in obj) {\n propValue = obj[propName]\n ;(includeFunctions || 'function' != typeof propValue) &&\n (serializedObj[propName] = serializeForMain(\n winId,\n instanceId,\n propValue,\n added\n ))\n }\n }\n return serializedObj\n }\n const serializeInstanceForMain = (instance, value) =>\n instance\n ? serializeForMain(instance[WinIdKey], instance[InstanceIdKey], value)\n : [0, value]\n const deserializeFromMain = (\n winId,\n instanceId,\n applyPath,\n serializedValueTransfer,\n serializedType,\n serializedValue,\n obj,\n key\n ) => {\n if (serializedValueTransfer) {\n serializedType = serializedValueTransfer[0]\n serializedValue = serializedValueTransfer[1]\n if (\n 0 === serializedType ||\n 11 === serializedType ||\n 12 === serializedType\n ) {\n return serializedValue\n }\n if (4 === serializedType) {\n return deserializeRefFromMain(applyPath, serializedValue)\n }\n if (6 === serializedType) {\n return winId && applyPath.length > 0\n ? (...args) =>\n callMethod(environments[winId].$window$, applyPath, args, 1)\n : noop\n }\n if (3 === serializedType) {\n return getOrCreateSerializedInstance(serializedValue)\n }\n if (7 === serializedType) {\n return new NodeList(serializedValue.map(getOrCreateSerializedInstance))\n }\n if (10 === serializedType) {\n return new Attr(serializedValue)\n }\n if (1 === serializedType) {\n return serializedValue.map(v =>\n deserializeFromMain(winId, instanceId, applyPath, v)\n )\n }\n if (14 === serializedType) {\n return new CustomError(serializedValue)\n }\n obj = {}\n for (key in serializedValue) {\n obj[key] = deserializeFromMain(\n winId,\n instanceId,\n [...applyPath, key],\n serializedValue[key]\n )\n }\n if (13 === serializedType) {\n return new environments[winId].$window$.CSSStyleDeclaration(\n winId,\n instanceId,\n applyPath,\n obj\n )\n }\n if (5 === serializedType) {\n if ('message' === obj.type && obj.origin) {\n let postMessageKey = JSON.stringify(obj.data)\n let postMessageData = postMessages.find(\n pm => pm.$data$ === postMessageKey\n )\n let env\n if (postMessageData) {\n env = environments[postMessageData.$winId$]\n if (env) {\n obj.source = env.$window$\n obj.origin = env.$location$.origin\n }\n }\n }\n return new Proxy(new Event(obj.type, obj), {\n get: (target, propName) =>\n propName in obj\n ? obj[propName]\n : 'function' == typeof target[String(propName)]\n ? noop\n : target[String(propName)],\n })\n }\n if (2 === serializedType) {\n return obj\n }\n }\n }\n const getOrCreateSerializedInstance = ([winId, instanceId, nodeName]) =>\n instanceId === winId && environments[winId]\n ? environments[winId].$window$\n : getOrCreateNodeInstance(winId, instanceId, nodeName)\n const deserializeRefFromMain = (\n applyPath,\n {\n $winId$: $winId$,\n $instanceId$: $instanceId$,\n $nodeName$: $nodeName$,\n $refId$: $refId$,\n }\n ) => {\n webWorkerRefsByRefId[$refId$] ||\n webWorkerRefIdsByRef.set(\n (webWorkerRefsByRefId[$refId$] = function (...args) {\n const instance = getOrCreateNodeInstance(\n $winId$,\n $instanceId$,\n $nodeName$\n )\n return callMethod(instance, applyPath, args)\n }),\n $refId$\n )\n return webWorkerRefsByRefId[$refId$]\n }\n class CustomError extends Error {\n constructor(errorObject) {\n super(errorObject.message)\n this.name = errorObject.name\n this.message = errorObject.message\n this.stack = errorObject.stack\n }\n }\n class NodeList {\n constructor(nodes) {\n ;(this._ = nodes).map((node, index) => (this[index] = node))\n }\n entries() {\n return this._.entries()\n }\n forEach(cb, thisArg) {\n this._.map(cb, thisArg)\n }\n item(index) {\n return this[index]\n }\n keys() {\n return this._.keys()\n }\n get length() {\n return len(this._)\n }\n values() {\n return this._.values()\n }\n [Symbol.iterator]() {\n return this._[Symbol.iterator]()\n }\n }\n const Attr = class {\n constructor(serializedAttr) {\n this.name = serializedAttr[0]\n this.value = serializedAttr[1]\n }\n get nodeName() {\n return this.name\n }\n get nodeType() {\n return 2\n }\n }\n const warnCrossOrgin = (apiType, apiName, env) =>\n console.warn(\n `Partytown unable to ${apiType} cross-origin ${apiName}: ` +\n env.$location$\n )\n const logWorker = (msg, winId) => {\n try {\n const config = webWorkerCtx.$config$\n if (config.logStackTraces) {\n const frames = new Error().stack.split('\\n')\n const i = frames.findIndex(f => f.includes('logWorker'))\n msg += '\\n' + frames.slice(i + 1).join('\\n')\n }\n let prefix\n let color\n if (winId) {\n prefix = `Worker (${normalizedWinId(winId)}) 🎉`\n color = winColor(winId)\n } else {\n prefix = self.name\n color = '#9844bf'\n }\n if (webWorkerCtx.lastLog !== msg) {\n webWorkerCtx.lastLog = msg\n console.debug.apply(console, [\n `%c${prefix}`,\n `background: ${color}; color: white; padding: 2px 3px; border-radius: 2px; font-size: 0.8em;`,\n msg,\n ])\n }\n } catch (e) {}\n }\n const winIds = []\n const normalizedWinId = winId => {\n winIds.includes(winId) || winIds.push(winId)\n return winIds.indexOf(winId) + 1\n }\n const winColor = winId => {\n const colors = ['#00309e', '#ea3655', '#eea727']\n const index = normalizedWinId(winId) - 1\n return colors[index] || colors[colors.length - 1]\n }\n const getTargetProp = (target, applyPath) => {\n let n = ''\n if (target) {\n const cstrName = getConstructorName(target)\n if ('Window' === cstrName) {\n n = ''\n } else if ('string' == typeof target[InstanceDataKey]) {\n let nodeName = target[InstanceDataKey]\n n =\n '#text' === nodeName\n ? 'textNode.'\n : '#comment' === nodeName\n ? 'commentNode.'\n : '#document' === nodeName\n ? 'document.'\n : 'html' === nodeName\n ? 'doctype.'\n : nodeName.toLowerCase() + '.'\n } else {\n n =\n 'nodeType' in target && 2 === target.nodeType\n ? 'attributes.'\n : 'CanvasRenderingContext2D' === cstrName\n ? 'context2D.'\n : 'CanvasRenderingContextWebGL' === cstrName\n ? 'contextWebGL.'\n : 'CSSStyleDeclaration' === cstrName\n ? 'style.'\n : 'MutationObserver' === cstrName\n ? 'mutationObserver.'\n : 'NamedNodeMap' === cstrName\n ? 'namedNodeMap.'\n : 'ResizeObserver' === cstrName\n ? 'resizeObserver.'\n : cstrName.substring(0, 1).toLowerCase() +\n cstrName.substring(1) +\n '.'\n }\n target[ApplyPathKey] &&\n target[ApplyPathKey].length &&\n (n += [...target[ApplyPathKey]].join('.') + '.')\n }\n if (applyPath.length > 1) {\n const first = applyPath.slice(0, applyPath.length - 1)\n const last = applyPath[applyPath.length - 1]\n if (!isNaN(last)) {\n return n + `${first.join('.')}[${last}]`\n }\n }\n return n + applyPath.join('.')\n }\n const getLogValue = (applyPath, v) => {\n const type = typeof v\n if (void 0 === v) {\n return 'undefined'\n }\n if ('boolean' === type || 'number' === type || null == v) {\n return JSON.stringify(v)\n }\n if ('string' === type) {\n return applyPath.includes('cookie')\n ? JSON.stringify(v.slice(0, 10) + '...')\n : JSON.stringify(v.length > 50 ? v.slice(0, 40) + '...' : v)\n }\n if (Array.isArray(v)) {\n return `[${v.map(getLogValue).join(', ')}]`\n }\n if ('object' === type) {\n const instanceId = v[InstanceIdKey]\n const cstrName = getConstructorName(v)\n if ('string' == typeof instanceId) {\n if ('Window' === cstrName) {\n return 'window'\n }\n if ('string' == typeof v[InstanceDataKey]) {\n if (1 === v.nodeType) {\n return `<${v[InstanceDataKey].toLowerCase()}>`\n }\n if (10 === v.nodeType) {\n return `<!DOCTYPE ${v[InstanceDataKey]}>`\n }\n if (v.nodeType <= 11) {\n return v[InstanceDataKey]\n }\n }\n return '¯\\\\_(ツ)_/¯ instance obj'\n }\n return v[Symbol.iterator]\n ? `[${Array.from(v)\n .map(i => getLogValue(applyPath, i))\n .join(', ')}]`\n : 'value' in v\n ? 'string' == typeof v.value\n ? `\"${v.value}\"`\n : objToString(v.value)\n : objToString(v)\n }\n return (v => 'object' == typeof v && v && v.then)(v)\n ? 'Promise'\n : 'function' === type\n ? `ƒ() ${v.name || ''}`.trim()\n : `¯\\\\_(ツ)_/¯ ${String(v)}`.trim()\n }\n const objToString = obj => {\n const s = []\n for (let key in obj) {\n const value = obj[key]\n const type = typeof value\n 'string' === type\n ? s.push(`${key}: \"${value}\"`)\n : 'function' === type\n ? s.push(`${key}: ƒ`)\n : Array.isArray(type)\n ? s.push(`${key}: [..]`)\n : 'object' === type && value\n ? s.push(`${key}: {..}`)\n : s.push(`${key}: ${String(value)}`)\n }\n let str = s.join(', ')\n str.length > 200 && (str = str.substring(0, 200) + '..')\n return `{ ${str} }`\n }\n const logDimensionCacheClearStyle = (target, propName) => {\n ;(webWorkerCtx.$config$.logGetters || webWorkerCtx.$config$.logSetters) &&\n logWorker(\n `Dimension cache cleared from style.${propName} setter`,\n target[WinIdKey]\n )\n }\n const logDimensionCacheClearMethod = (target, methodName) => {\n ;(webWorkerCtx.$config$.logGetters || webWorkerCtx.$config$.logCalls) &&\n logWorker(\n `Dimension cache cleared from method call ${methodName}()`,\n target[WinIdKey]\n )\n }\n const taskQueue = []\n const queue = (\n instance,\n $applyPath$,\n callType,\n $assignInstanceId$,\n $groupedGetters$,\n buffer\n ) => {\n if (instance[ApplyPathKey]) {\n taskQueue.push({\n $winId$: instance[WinIdKey],\n $instanceId$: instance[InstanceIdKey],\n $applyPath$: [...instance[ApplyPathKey], ...$applyPath$],\n $assignInstanceId$: $assignInstanceId$,\n $groupedGetters$: $groupedGetters$,\n })\n taskQueue[len(taskQueue) - 1].$debug$ = ((\n target,\n applyPath,\n callType\n ) => {\n let m = getTargetProp(target, applyPath)\n 1 === callType\n ? (m += ' (blocking)')\n : 2 === callType\n ? (m += ' (non-blocking)')\n : 3 === callType && (m += ' (non-blocking, no-side-effect)')\n return m.trim()\n })(instance, $applyPath$, callType)\n buffer &&\n 3 !== callType &&\n console.error('buffer must be sent NonBlockingNoSideEffect')\n if (3 === callType) {\n webWorkerCtx.$postMessage$(\n [\n 12,\n {\n $msgId$: randomId(),\n $tasks$: [...taskQueue],\n },\n ],\n buffer\n ? [buffer instanceof ArrayBuffer ? buffer : buffer.buffer]\n : void 0\n )\n taskQueue.length = 0\n } else if (1 === callType) {\n return sendToMain(true)\n }\n webWorkerCtx.$asyncMsgTimer$ = setTimeout(sendToMain, 20)\n }\n }\n const sendToMain = isBlocking => {\n clearTimeout(webWorkerCtx.$asyncMsgTimer$)\n if (len(taskQueue)) {\n webWorkerCtx.$config$.logMainAccess &&\n logWorker(`Main access, tasks sent: ${taskQueue.length}`)\n const endTask = taskQueue[len(taskQueue) - 1]\n const accessReq = {\n $msgId$: randomId(),\n $tasks$: [...taskQueue],\n }\n taskQueue.length = 0\n if (isBlocking) {\n const accessRsp = ((webWorkerCtx, accessReq) => {\n const sharedDataBuffer = webWorkerCtx.$sharedDataBuffer$\n const sharedData = new Int32Array(sharedDataBuffer)\n Atomics.store(sharedData, 0, 0)\n webWorkerCtx.$postMessage$([11, accessReq])\n Atomics.wait(sharedData, 0, 0)\n let dataLength = Atomics.load(sharedData, 0)\n let accessRespStr = ''\n let i = 0\n for (; i < dataLength; i++) {\n accessRespStr += String.fromCharCode(sharedData[i + 1])\n }\n return JSON.parse(accessRespStr)\n })(webWorkerCtx, accessReq)\n const isPromise = accessRsp.$isPromise$\n const rtnValue = deserializeFromMain(\n endTask.$winId$,\n endTask.$instanceId$,\n endTask.$applyPath$,\n accessRsp.$rtnValue$\n )\n if (accessRsp.$error$) {\n if (isPromise) {\n return Promise.reject(accessRsp.$error$)\n }\n throw new Error(accessRsp.$error$)\n }\n return isPromise ? Promise.resolve(rtnValue) : rtnValue\n }\n webWorkerCtx.$postMessage$([12, accessReq])\n }\n }\n const getter = (instance, applyPath, groupedGetters, rtnValue) => {\n if (webWorkerCtx.$config$.get) {\n rtnValue = webWorkerCtx.$config$.get(\n createHookOptions(instance, applyPath)\n )\n if (rtnValue !== HookContinue) {\n return rtnValue\n }\n }\n rtnValue = queue(instance, applyPath, 1, void 0, groupedGetters)\n ;((\n target,\n applyPath,\n rtnValue,\n restrictedToWorker = false,\n groupedGetters = false\n ) => {\n if (webWorkerCtx.$config$.logGetters) {\n try {\n const msg = `Get ${getTargetProp(\n target,\n applyPath\n )}, returned: ${getLogValue(applyPath, rtnValue)}${\n restrictedToWorker ? ' (restricted to worker)' : ''\n }${groupedGetters ? ' (grouped getter)' : ''}`\n msg.includes('Symbol(') || logWorker(msg, target[WinIdKey])\n } catch (e) {}\n }\n })(instance, applyPath, rtnValue, false, !!groupedGetters)\n return rtnValue\n }\n const setter = (instance, applyPath, value, hookSetterValue) => {\n if (webWorkerCtx.$config$.set) {\n hookSetterValue = webWorkerCtx.$config$.set({\n value: value,\n prevent: HookPrevent,\n ...createHookOptions(instance, applyPath),\n })\n if (hookSetterValue === HookPrevent) {\n return\n }\n hookSetterValue !== HookContinue && (value = hookSetterValue)\n }\n if (dimensionChangingSetterNames.some(s => applyPath.includes(s))) {\n cachedDimensions.clear()\n ;((target, propName) => {\n ;(webWorkerCtx.$config$.logGetters ||\n webWorkerCtx.$config$.logSetters) &&\n logWorker(\n `Dimension cache cleared from setter \"${propName}\"`,\n target[WinIdKey]\n )\n })(instance, applyPath[applyPath.length - 1])\n }\n applyPath = [...applyPath, serializeInstanceForMain(instance, value), 0]\n ;((target, applyPath, value, restrictedToWorker = false) => {\n if (webWorkerCtx.$config$.logSetters) {\n try {\n applyPath = applyPath.slice(0, applyPath.length - 2)\n logWorker(\n `Set ${getTargetProp(target, applyPath)}, value: ${getLogValue(\n applyPath,\n value\n )}${restrictedToWorker ? ' (restricted to worker)' : ''}`,\n target[WinIdKey]\n )\n } catch (e) {}\n }\n })(instance, applyPath, value)\n queue(instance, applyPath, 2)\n }\n const callMethod = (\n instance,\n applyPath,\n args,\n callType,\n assignInstanceId,\n buffer,\n rtnValue,\n methodName\n ) => {\n if (webWorkerCtx.$config$.apply) {\n rtnValue = webWorkerCtx.$config$.apply({\n args: args,\n ...createHookOptions(instance, applyPath),\n })\n if (rtnValue !== HookContinue) {\n return rtnValue\n }\n }\n methodName = applyPath[len(applyPath) - 1]\n applyPath = [...applyPath, serializeInstanceForMain(instance, args)]\n callType = callType || (nonBlockingMethods.includes(methodName) ? 2 : 1)\n if (\n 'setAttribute' === methodName &&\n hasInstanceStateValue(instance, args[0])\n ) {\n setInstanceStateValue(instance, args[0], args[1])\n } else if (structureChangingMethodNames.includes(methodName)) {\n cachedDimensions.clear()\n cachedStructure.clear()\n ;((target, methodName) => {\n ;(webWorkerCtx.$config$.logGetters || webWorkerCtx.$config$.logCalls) &&\n logWorker(\n `Dimension and DOM structure cache cleared from method call ${methodName}()`,\n target[WinIdKey]\n )\n })(instance, methodName)\n } else if (dimensionChangingMethodNames.includes(methodName)) {\n callType = 2\n cachedDimensions.clear()\n logDimensionCacheClearMethod(instance, methodName)\n }\n rtnValue = queue(\n instance,\n applyPath,\n callType,\n assignInstanceId,\n void 0,\n buffer\n )\n ;((target, applyPath, args, rtnValue) => {\n if (webWorkerCtx.$config$.logCalls) {\n try {\n applyPath = applyPath.slice(0, applyPath.length - 1)\n logWorker(\n `Call ${getTargetProp(target, applyPath)}(${args\n .map(v => getLogValue(applyPath, v))\n .join(', ')}), returned: ${getLogValue(applyPath, rtnValue)}`,\n target[WinIdKey]\n )\n } catch (e) {}\n }\n })(instance, applyPath, args, rtnValue)\n return rtnValue\n }\n const constructGlobal = (instance, cstrName, args) => {\n ;((target, cstrName, args) => {\n if (webWorkerCtx.$config$.logCalls) {\n try {\n logWorker(\n `Construct new ${cstrName}(${args\n .map(v => getLogValue([], v))\n .join(', ')})`,\n target[WinIdKey]\n )\n } catch (e) {}\n }\n })(instance, cstrName, args)\n queue(instance, [1, cstrName, serializeInstanceForMain(instance, args)], 1)\n }\n const createHookOptions = (instance, applyPath) => ({\n name: applyPath.join('.'),\n continue: HookContinue,\n nodeName: instance[InstanceDataKey],\n constructor: getConstructorName(instance),\n instance: instance,\n window: environments[instance[WinIdKey]].$window$,\n })\n const addStorageApi = (win, storageName, storages, isSameOrigin, env) => {\n let getItems = items => {\n items = storages.get(win.origin)\n items || storages.set(win.origin, (items = []))\n return items\n }\n let getIndexByKey = key => getItems().findIndex(i => i[STORAGE_KEY] === key)\n let index\n let item\n let storage = {\n getItem(key) {\n index = getIndexByKey(key)\n return index > -1 ? getItems()[index][STORAGE_VALUE] : null\n },\n setItem(key, value) {\n index = getIndexByKey(key)\n index > -1\n ? (getItems()[index][STORAGE_VALUE] = value)\n : getItems().push([key, value])\n isSameOrigin\n ? callMethod(win, [storageName, 'setItem'], [key, value], 2)\n : warnCrossOrgin('set', storageName, env)\n },\n removeItem(key) {\n index = getIndexByKey(key)\n index > -1 && getItems().splice(index, 1)\n isSameOrigin\n ? callMethod(win, [storageName, 'removeItem'], [key], 2)\n : warnCrossOrgin('remove', storageName, env)\n },\n key(index) {\n item = getItems()[index]\n return item ? item[STORAGE_KEY] : null\n },\n clear() {\n getItems().length = 0\n isSameOrigin\n ? callMethod(win, [storageName, 'clear'], EMPTY_ARRAY, 2)\n : warnCrossOrgin('clear', storageName, env)\n },\n get length() {\n return getItems().length\n },\n }\n win[storageName] = new Proxy(storage, {\n get: (target, key) =>\n Reflect.has(target, key)\n ? Reflect.get(target, key)\n : target.getItem(key),\n set(target, key, value) {\n target.setItem(key, value)\n return true\n },\n has: (target, key) =>\n !!Reflect.has(target, key) ||\n ('string' == typeof key && null !== target.getItem(key)),\n deleteProperty(target, key) {\n target.removeItem(key)\n return true\n },\n })\n }\n const STORAGE_KEY = 0\n const STORAGE_VALUE = 1\n const createCSSStyleDeclarationCstr = (win, WorkerBase, cstrName) => {\n win[cstrName] = defineConstructorName(\n class extends WorkerBase {\n constructor(winId, instanceId, applyPath, styles) {\n super(winId, instanceId, applyPath, styles || {})\n return new Proxy(this, {\n get(target, propName) {\n if (target[propName]) {\n return target[propName]\n }\n target[propName] ||\n 'string' != typeof propName ||\n target[InstanceDataKey][propName] ||\n (target[InstanceDataKey][propName] = getter(target, [propName]))\n return target[InstanceDataKey][propName]\n },\n set(target, propName, propValue) {\n target[InstanceDataKey][propName] = propValue\n setter(target, [propName], propValue)\n logDimensionCacheClearStyle(target, propName)\n cachedDimensions.clear()\n return true\n },\n })\n }\n setProperty(...args) {\n this[InstanceDataKey][args[0]] = args[1]\n callMethod(this, ['setProperty'], args, 2)\n logDimensionCacheClearStyle(this, args[0])\n cachedDimensions.clear()\n }\n getPropertyValue(propName) {\n return this[propName]\n }\n removeProperty(propName) {\n let value = this[InstanceDataKey][propName]\n callMethod(this, ['removeProperty'], [propName], 2)\n logDimensionCacheClearStyle(this, propName)\n cachedDimensions.clear()\n this[InstanceDataKey][propName] = void 0\n return value\n }\n },\n cstrName\n )\n }\n const createCSSStyleSheetConstructor = (win, cssStyleSheetCstrName) => {\n win[cssStyleSheetCstrName] = defineConstructorName(\n class {\n constructor(ownerNode) {\n this.ownerNode = ownerNode\n }\n get cssRules() {\n const ownerNode = this.ownerNode\n return new Proxy(\n {},\n {\n get(target, propKey) {\n const propName = String(propKey)\n return 'item' === propName\n ? index => getCssRule(ownerNode, index)\n : 'length' === propName\n ? getCssRules(ownerNode).length\n : isNaN(propName)\n ? target[propKey]\n : getCssRule(ownerNode, propName)\n },\n }\n )\n }\n insertRule(ruleText, index) {\n const cssRules = getCssRules(this.ownerNode)\n index = void 0 === index ? 0 : index\n if (index >= 0 && index <= cssRules.length) {\n callMethod(\n this.ownerNode,\n ['sheet', 'insertRule'],\n [ruleText, index],\n 2\n )\n cssRules.splice(index, 0, 0)\n }\n logDimensionCacheClearMethod(this.ownerNode, 'insertRule')\n cachedDimensions.clear()\n return index\n }\n deleteRule(index) {\n callMethod(this.ownerNode, ['sheet', 'deleteRule'], [index], 2)\n getCssRules(this.ownerNode).splice(index, 1)\n logDimensionCacheClearMethod(this.ownerNode, 'deleteRule')\n cachedDimensions.clear()\n }\n get type() {\n return 'text/css'\n }\n },\n cssStyleSheetCstrName\n )\n const HTMLStyleDescriptorMap = {\n sheet: {\n get() {\n return new win[cssStyleSheetCstrName](this)\n },\n },\n }\n definePrototypePropertyDescriptor(\n win.HTMLStyleElement,\n HTMLStyleDescriptorMap\n )\n }\n const getCssRules = (ownerNode, cssRules) => {\n cssRules = getInstanceStateValue(ownerNode, 2)\n if (!cssRules) {\n cssRules = getter(ownerNode, ['sheet', 'cssRules'])\n setInstanceStateValue(ownerNode, 2, cssRules)\n }\n return cssRules\n }\n const getCssRule = (ownerNode, index, cssRules) => {\n cssRules = getCssRules(ownerNode)\n 0 === cssRules[index] &&\n (cssRules[index] = getter(ownerNode, [\n 'sheet',\n 'cssRules',\n parseInt(index, 10),\n ]))\n return cssRules[index]\n }\n const runScriptContent = (\n env,\n instanceId,\n scriptContent,\n winId,\n errorMsg\n ) => {\n try {\n webWorkerCtx.$config$.logScriptExecution &&\n logWorker(\n `Execute script: ${scriptContent\n .substring(0, 100)\n .split('\\n')\n .map(l => l.trim())\n .join(' ')\n .trim()\n .substring(0, 60)}...`,\n winId\n )\n env.$currentScriptId$ = instanceId\n run(env, scriptContent)\n } catch (contentError) {\n console.error(scriptContent, contentError)\n errorMsg = String(contentError.stack || contentError)\n }\n env.$currentScriptId$ = ''\n return errorMsg\n }\n const run = (env, scriptContent, scriptUrl) => {\n env.$runWindowLoadEvent$ = 1\n scriptContent =\n `with(this){${scriptContent\n .replace(/\\bthis\\b/g, '(thi$(this)?window:this)')\n .replace(/\\/\\/# so/g, '//Xso')}\\n;function thi$(t){return t===this}};${(\n webWorkerCtx.$config$.globalFns || []\n )\n .filter(globalFnName => /[a-zA-Z_$][0-9a-zA-Z_$]*/.test(globalFnName))\n .map(g => `(typeof ${g}=='function'&&(this.${g}=${g}))`)\n .join(';')};` + (scriptUrl ? '\\n//# sourceURL=' + scriptUrl : '')\n env.$isSameOrigin$ ||\n (scriptContent = scriptContent.replace(\n /.postMessage\\(/g,\n `.postMessage('${env.$winId$}',`\n ))\n new Function(scriptContent).call(env.$window$)\n env.$runWindowLoadEvent$ = 0\n }\n const runStateLoadHandlers = (instance, type, handlers) => {\n handlers = getInstanceStateValue(instance, type)\n handlers &&\n setTimeout(() =>\n handlers.map(cb =>\n cb({\n type: type,\n })\n )\n )\n }\n const resolveToUrl = (\n env,\n url,\n type,\n baseLocation,\n resolvedUrl,\n configResolvedUrl\n ) => {\n baseLocation = env.$location$\n while (!baseLocation.host) {\n env = environments[env.$parentWinId$]\n baseLocation = env.$location$\n if (env.$winId$ === env.$parentWinId$) {\n break\n }\n }\n resolvedUrl = new URL(url || '', baseLocation)\n if (type && webWorkerCtx.$config$.resolveUrl) {\n configResolvedUrl = webWorkerCtx.$config$.resolveUrl(\n resolvedUrl,\n baseLocation,\n type\n )\n if (configResolvedUrl) {\n return configResolvedUrl\n }\n }\n return resolvedUrl\n }\n const resolveUrl = (env, url, type) => resolveToUrl(env, url, type) + ''\n const getPartytownScript = () =>\n `<script src=\"${partytownLibUrl('partytown.js?v=0.7.4')}\"><\\/script>`\n const createImageConstructor = env =>\n class HTMLImageElement {\n constructor() {\n this.s = ''\n this.l = []\n this.e = []\n this.style = {}\n }\n get src() {\n return this.s\n }\n set src(src) {\n webWorkerCtx.$config$.logImageRequests &&\n logWorker(\n `Image() request: ${resolveUrl(env, src, 'image')}`,\n env.$winId$\n )\n this.s = src\n fetch(resolveUrl(env, src, 'image'), {\n mode: 'no-cors',\n credentials: 'include',\n keepalive: true,\n }).then(\n rsp => {\n rsp.ok || 0 === rsp.status\n ? this.l.map(cb =>\n cb({\n type: 'load',\n })\n )\n : this.e.map(cb =>\n cb({\n type: 'error',\n })\n )\n },\n () =>\n this.e.forEach(cb =>\n cb({\n type: 'error',\n })\n )\n )\n }\n addEventListener(eventName, cb) {\n 'load' === eventName && this.l.push(cb)\n 'error' === eventName && this.e.push(cb)\n }\n get onload() {\n return this.l[0]\n }\n set onload(cb) {\n this.l = [cb]\n }\n get onerror() {\n return this.e[0]\n }\n set onerror(cb) {\n this.e = [cb]\n }\n }\n const HTMLSrcElementDescriptorMap = {\n addEventListener: {\n value(...args) {\n const eventName = args[0]\n const callbacks = getInstanceStateValue(this, eventName) || []\n callbacks.push(args[1])\n setInstanceStateValue(this, eventName, callbacks)\n },\n },\n async: {\n get: noop,\n set: noop,\n },\n defer: {\n get: noop,\n set: noop,\n },\n onload: {\n get() {\n let callbacks = getInstanceStateValue(this, 'load')\n return (callbacks && callbacks[0]) || null\n },\n set(cb) {\n setInstanceStateValue(this, 'load', cb ? [cb] : null)\n },\n },\n onerror: {\n get() {\n let callbacks = getInstanceStateValue(this, 'error')\n return (callbacks && callbacks[0]) || null\n },\n set(cb) {\n setInstanceStateValue(this, 'error', cb ? [cb] : null)\n },\n },\n getAttribute: {\n value(attrName) {\n return 'src' === attrName\n ? this.src\n : callMethod(this, ['getAttribute'], [attrName])\n },\n },\n setAttribute: {\n value(attrName, attrValue) {\n scriptAttrPropNames.includes(attrName)\n ? (this[attrName] = attrValue)\n : callMethod(this, ['setAttribute'], [attrName, attrValue])\n },\n },\n }\n const scriptAttrPropNames = commaSplit('src,type')\n const patchHTMLScriptElement = (WorkerHTMLScriptElement, env) => {\n const HTMLScriptDescriptorMap = {\n innerHTML: innerHTMLDescriptor,\n innerText: innerHTMLDescriptor,\n src: {\n get() {\n return getInstanceStateValue(this, 4) || ''\n },\n set(url) {\n const orgUrl = resolveUrl(env, url, null)\n const config = webWorkerCtx.$config$\n url = resolveUrl(env, url, 'script')\n setInstanceStateValue(this, 4, url)\n setter(this, ['src'], url)\n orgUrl !== url && setter(this, ['dataset', 'ptsrc'], orgUrl)\n if (this.type && config.loadScriptsOnMainThread) {\n const shouldExecuteScriptViaMainThread = config.loadScriptsOnMainThread.some(\n scriptUrl => scriptUrl === url\n )\n shouldExecuteScriptViaMainThread &&\n setter(this, ['type'], 'text/javascript')\n }\n },\n },\n textContent: innerHTMLDescriptor,\n type: {\n get() {\n return getter(this, ['type'])\n },\n set(type) {\n if (!isScriptJsType(type)) {\n setInstanceStateValue(this, 5, type)\n setter(this, ['type'], type)\n }\n },\n },\n ...HTMLSrcElementDescriptorMap,\n }\n definePrototypePropertyDescriptor(\n WorkerHTMLScriptElement,\n HTMLScriptDescriptorMap\n )\n }\n const innerHTMLDescriptor = {\n get() {\n const type = getter(this, ['type'])\n return isScriptJsType(type)\n ? getInstanceStateValue(this, 3) || ''\n : getter(this, ['innerHTML'])\n },\n set(scriptContent) {\n setInstanceStateValue(this, 3, scriptContent)\n },\n }\n const isScriptJsType = scriptType =>\n !scriptType || 'text/javascript' === scriptType\n const createNodeCstr = (win, env, WorkerBase) => {\n const config = webWorkerCtx.$config$\n const WorkerNode = defineConstructorName(\n class extends WorkerBase {\n appendChild(node) {\n return this.insertBefore(node, null)\n }\n get href() {}\n set href(_) {}\n insertBefore(newNode, referenceNode) {\n var _a, _b\n const winId = (newNode[WinIdKey] = this[WinIdKey])\n const instanceId = newNode[InstanceIdKey]\n const nodeName = newNode[InstanceDataKey]\n const isScript = 'SCRIPT' === nodeName\n const isIFrame = 'IFRAME' === nodeName\n if (isScript) {\n const scriptContent = getInstanceStateValue(newNode, 3)\n const scriptType = getInstanceStateValue(newNode, 5)\n if (scriptContent) {\n if (isScriptJsType(scriptType)) {\n const scriptId = newNode.id\n const loadOnMainThread =\n scriptId &&\n (null ===\n (_b =\n null === (_a = config.loadScriptsOnMainThread) ||\n void 0 === _a\n ? void 0\n : _a.includes) || void 0 === _b\n ? void 0\n : _b.call(_a, scriptId))\n if (loadOnMainThread) {\n setter(newNode, ['type'], 'text/javascript')\n } else {\n const errorMsg = runScriptContent(\n env,\n instanceId,\n scriptContent,\n winId,\n ''\n )\n const datasetType = errorMsg ? 'pterror' : 'ptid'\n const datasetValue = errorMsg || instanceId\n setter(newNode, ['type'], 'text/partytown-x')\n setter(newNode, ['dataset', datasetType], datasetValue)\n }\n }\n setter(newNode, ['innerHTML'], scriptContent)\n }\n }\n callMethod(this, ['insertBefore'], [newNode, referenceNode], 2)\n if (isIFrame) {\n const src = getInstanceStateValue(newNode, 0)\n if (src && src.startsWith('javascript:')) {\n const scriptContent = src.split('javascript:')[1]\n runScriptContent(env, instanceId, scriptContent, winId, '')\n }\n ;((winId, iframe) => {\n let i = 0\n let type\n let handlers\n let callback = () => {\n if (\n environments[winId] &&\n environments[winId].$isInitialized$ &&\n !environments[winId].$isLoading$\n ) {\n type = getInstanceStateValue(iframe, 1) ? 'error' : 'load'\n handlers = getInstanceStateValue(iframe, type)\n handlers &&\n handlers.map(handler =>\n handler({\n type: type,\n })\n )\n } else if (i++ > 2e3) {\n handlers = getInstanceStateValue(iframe, 'error')\n handlers &&\n handlers.map(handler =>\n handler({\n type: 'error',\n })\n )\n } else {\n setTimeout(callback, 9)\n }\n }\n callback()\n })(instanceId, newNode)\n }\n if (isScript) {\n sendToMain(true)\n webWorkerCtx.$postMessage$([7, winId])\n }\n return newNode\n }\n get nodeName() {\n return '#s' === this[InstanceDataKey]\n ? '#document-fragment'\n : this[InstanceDataKey]\n }\n get nodeType() {\n return 3\n }\n get ownerDocument() {\n return env.$document$\n }\n },\n 'Node'\n )\n cachedTreeProps(\n WorkerNode,\n commaSplit(\n 'childNodes,firstChild,isConnected,lastChild,nextSibling,parentElement,parentNode,previousSibling'\n )\n )\n win.Node = WorkerNode\n }\n const htmlMedia = commaSplit('AUDIO,CANVAS,VIDEO')\n const windowMediaConstructors = commaSplit('Audio,MediaSource')\n const patchDocument = (WorkerDocument, env, isDocumentImplementation) => {\n const DocumentDescriptorMap = {\n body: {\n get: () => env.$body$,\n },\n cookie: {\n get() {\n if (env.$isSameOrigin$) {\n return getter(this, ['cookie'])\n }\n warnCrossOrgin('get', 'cookie', env)\n return ''\n },\n set(value) {\n if (env.$isSameOrigin$) {\n setter(this, ['cookie'], value)\n } else {\n warnCrossOrgin('set', 'cookie', env)\n }\n },\n },\n createElement: {\n value(tagName) {\n tagName = tagName.toUpperCase()\n if (!IS_TAG_REG.test(tagName)) {\n throw tagName + ' not valid'\n }\n const isIframe = 'IFRAME' === tagName\n const winId = this[WinIdKey]\n const instanceId = (isIframe ? 'f_' : '') + randomId()\n callMethod(this, ['createElement'], [tagName], 2, instanceId)\n const elm = getOrCreateNodeInstance(winId, instanceId, tagName)\n if (isIframe) {\n const env = createEnvironment(\n {\n $winId$: instanceId,\n $parentWinId$: winId,\n $url$: 'about:blank',\n },\n true\n )\n env.$window$.fetch = fetch\n setter(elm, ['srcdoc'], getPartytownScript())\n } else if ('SCRIPT' === tagName) {\n const scriptType = getInstanceStateValue(elm, 5)\n isScriptJsType(scriptType) &&\n setter(elm, ['type'], 'text/partytown')\n }\n return elm\n },\n },\n createElementNS: {\n value(namespace, tagName) {\n const instanceId = randomId()\n const nsElm = getOrCreateNodeInstance(\n this[WinIdKey],\n instanceId,\n tagName,\n namespace\n )\n callMethod(\n this,\n ['createElementNS'],\n [namespace, tagName],\n 2,\n instanceId\n )\n return nsElm\n },\n },\n createTextNode: {\n value(text) {\n const winId = this[WinIdKey]\n const instanceId = randomId()\n const textNode = getOrCreateNodeInstance(winId, instanceId, '#text')\n callMethod(this, ['createTextNode'], [text], 2, instanceId)\n return textNode\n },\n },\n createEvent: {\n value: type => new Event(type),\n },\n currentScript: {\n get() {\n return env.$currentScriptId$\n ? getOrCreateNodeInstance(\n this[WinIdKey],\n env.$currentScriptId$,\n 'SCRIPT'\n )\n : null\n },\n },\n defaultView: {\n get: () => (isDocumentImplementation ? null : env.$window$),\n },\n documentElement: {\n get: () => env.$documentElement$,\n },\n getElementsByTagName: {\n value(tagName) {\n tagName = tagName.toUpperCase()\n return 'BODY' === tagName\n ? [env.$body$]\n : 'HEAD' === tagName\n ? [env.$head$]\n : callMethod(this, ['getElementsByTagName'], [tagName])\n },\n },\n head: {\n get: () => env.$head$,\n },\n images: {\n get() {\n return getter(this, ['images'])\n },\n },\n implementation: {\n get() {\n return {\n hasFeature: () => true,\n createHTMLDocument: title => {\n const $winId$ = randomId()\n callMethod(\n this,\n ['implementation', 'createHTMLDocument'],\n [title],\n 1,\n {\n $winId$: $winId$,\n }\n )\n const docEnv = createEnvironment(\n {\n $winId$: $winId$,\n $parentWinId$: $winId$,\n $url$: env.$location$ + '',\n $visibilityState$: 'hidden',\n },\n true,\n true\n )\n return docEnv.$document$\n },\n }\n },\n },\n location: {\n get: () => env.$location$,\n set(url) {\n env.$location$.href = url + ''\n },\n },\n nodeType: {\n value: 9,\n },\n parentNode: {\n value: null,\n },\n parentElement: {\n value: null,\n },\n readyState: {\n value: 'complete',\n },\n visibilityState: {\n get: () => env.$visibilityState$ || 'visible',\n },\n }\n definePrototypePropertyDescriptor(WorkerDocument, DocumentDescriptorMap)\n cachedProps(WorkerDocument, 'compatMode,referrer,forms')\n }\n const patchDocumentElementChild = (WokerDocumentElementChild, env) => {\n const DocumentElementChildDescriptorMap = {\n parentElement: {\n get() {\n return this.parentNode\n },\n },\n parentNode: {\n get: () => env.$documentElement$,\n },\n }\n definePrototypePropertyDescriptor(\n WokerDocumentElementChild,\n DocumentElementChildDescriptorMap\n )\n }\n const patchElement = (WorkerElement, WorkerHTMLElement) => {\n const ElementDescriptorMap = {\n localName: {\n get() {\n return this[InstanceDataKey].toLowerCase()\n },\n },\n namespaceURI: {\n get() {\n return this[NamespaceKey] || 'http://www.w3.org/1999/xhtml'\n },\n },\n nodeType: {\n value: 1,\n },\n tagName: {\n get() {\n return this[InstanceDataKey]\n },\n },\n }\n definePrototypePropertyDescriptor(WorkerElement, ElementDescriptorMap)\n cachedTreeProps(WorkerElement, elementStructurePropNames)\n cachedProps(WorkerElement, 'id')\n cachedDimensionProps(WorkerHTMLElement)\n cachedDimensionMethods(\n WorkerHTMLElement,\n commaSplit('getClientRects,getBoundingClientRect')\n )\n }\n const patchHTMLAnchorElement = (WorkerHTMLAnchorElement, env) => {\n const HTMLAnchorDescriptorMap = {}\n commaSplit(\n 'hash,host,hostname,href,origin,pathname,port,protocol,search'\n ).map(anchorProp => {\n HTMLAnchorDescriptorMap[anchorProp] = {\n get() {\n let value = getInstanceStateValue(this, 4)\n let href\n if ('string' != typeof value) {\n href = getter(this, ['href'])\n setInstanceStateValue(this, 4, href)\n value = new URL(href)[anchorProp]\n }\n return resolveToUrl(env, value, null)[anchorProp]\n },\n set(value) {\n let url\n if ('href' === anchorProp) {\n if (\n (url => {\n try {\n new URL(url)\n return true\n } catch (_) {\n return false\n }\n })(value)\n ) {\n url = new URL(value)\n } else {\n const baseHref = env.$location$.href\n url = resolveToUrl(env, baseHref, null)\n url.href = new URL(value + '', url.href)\n }\n } else {\n url = resolveToUrl(env, this.href, null)\n url[anchorProp] = value\n }\n setInstanceStateValue(this, 4, url.href)\n setter(this, ['href'], url.href)\n },\n }\n })\n definePrototypePropertyDescriptor(\n WorkerHTMLAnchorElement,\n HTMLAnchorDescriptorMap\n )\n }\n const patchHTMLIFrameElement = (WorkerHTMLIFrameElement, env) => {\n const HTMLIFrameDescriptorMap = {\n contentDocument: {\n get() {\n return getIframeEnv(this).$document$\n },\n },\n contentWindow: {\n get() {\n return getIframeEnv(this).$window$\n },\n },\n src: {\n get() {\n let src = getInstanceStateValue(this, 0)\n if (src && src.startsWith('javascript:')) {\n return src\n }\n src = getIframeEnv(this).$location$.href\n return src.startsWith('about:') ? '' : src\n },\n set(src) {\n if (src) {\n if (src.startsWith('javascript:')) {\n setInstanceStateValue(this, 0, src)\n } else if (!src.startsWith('about:')) {\n let xhr = new XMLHttpRequest()\n let xhrStatus\n let env = getIframeEnv(this)\n env.$location$.href = src = resolveUrl(env, src, 'iframe')\n env.$isLoading$ = 1\n setInstanceStateValue(this, 1, void 0)\n xhr.open('GET', src, false)\n xhr.send()\n xhrStatus = xhr.status\n if (xhrStatus > 199 && xhrStatus < 300) {\n setter(\n this,\n ['srcdoc'],\n `<base href=\"${src}\">` +\n (function (text) {\n return text.replace(SCRIPT_TAG_REGEXP, (_, attrs) => {\n const parts = []\n let hasType = false\n let match\n while ((match = ATTR_REGEXP.exec(attrs))) {\n let [keyValue] = match\n if (keyValue.startsWith('type=')) {\n hasType = true\n keyValue = keyValue.replace(\n /(application|text)\\/javascript/,\n SCRIPT_TYPE\n )\n }\n parts.push(keyValue)\n }\n hasType || parts.push('type=\"text/partytown\"')\n return `<script ${parts.join(' ')}>`\n })\n })(xhr.responseText) +\n getPartytownScript()\n )\n sendToMain(true)\n webWorkerCtx.$postMessage$([7, env.$winId$])\n } else {\n setInstanceStateValue(this, 1, xhrStatus)\n env.$isLoading$ = 0\n }\n }\n }\n },\n },\n ...HTMLSrcElementDescriptorMap,\n }\n definePrototypePropertyDescriptor(\n WorkerHTMLIFrameElement,\n HTMLIFrameDescriptorMap\n )\n }\n const ATTR_REGEXP_STR = '((?:\\\\w|-)+(?:=(?:(?:\\\\w|-)+|\\'[^\\']*\\'|\"[^\"]*\")?)?)'\n const SCRIPT_TAG_REGEXP = new RegExp(\n `<script\\\\s*((${ATTR_REGEXP_STR}\\\\s*)*)>`,\n 'mg'\n )\n const ATTR_REGEXP = new RegExp(ATTR_REGEXP_STR, 'mg')\n const getIframeEnv = iframe => {\n const $winId$ = iframe[InstanceIdKey]\n environments[$winId$] ||\n createEnvironment(\n {\n $winId$: $winId$,\n $parentWinId$: iframe[WinIdKey],\n $url$: getter(iframe, ['src']) || 'about:blank',\n },\n true\n )\n return environments[$winId$]\n }\n const patchSvgElement = WorkerSVGGraphicsElement => {\n const getMatrix = (elm, methodName) => {\n const { a: a, b: b, c: c, d: d, e: e, f: f } = callMethod(\n elm,\n [methodName],\n EMPTY_ARRAY\n )\n return new DOMMatrixReadOnly([a, b, c, d, e, f])\n }\n const SVGGraphicsElementDescriptorMap = {\n ...WorkerSVGGraphicsElement,\n getCTM: {\n value: function () {\n return getMatrix(this, 'getCTM')\n },\n },\n getScreenCTM: {\n value: function () {\n return getMatrix(this, 'getScreenCTM')\n },\n },\n }\n definePrototypePropertyDescriptor(\n WorkerSVGGraphicsElement,\n SVGGraphicsElementDescriptorMap\n )\n }\n const createNamedNodeMapCstr = (win, WorkerBase) => {\n win.NamedNodeMap = defineConstructorName(\n class NamedNodeMap extends WorkerBase {\n constructor(winId, instanceId, applyPath) {\n super(winId, instanceId, applyPath)\n return new Proxy(this, {\n get(target, propName) {\n const handler = NAMED_NODE_MAP_HANDLERS[propName]\n return handler\n ? handler.bind(target, [propName])\n : getter(target, [propName])\n },\n set(target, propName, propValue) {\n const handler = NAMED_NODE_MAP_HANDLERS[propName]\n if (handler) {\n throw new Error(\n \"Can't set read-only property: \" + String(propName)\n )\n }\n setter(target, [propName], propValue)\n return true\n },\n })\n }\n },\n 'NamedNodeMap'\n )\n }\n function method(applyPath, ...args) {\n return callMethod(this, applyPath, args, 1)\n }\n const NAMED_NODE_MAP_HANDLERS = {\n getNamedItem: method,\n getNamedItemNS: method,\n item: method,\n removeNamedItem: method,\n removeNamedItemNS: method,\n setNamedItem: method,\n setNamedItemNS: method,\n }\n const createWindow = (\n $winId$,\n $parentWinId$,\n url,\n $visibilityState$,\n isIframeWindow,\n isDocumentImplementation\n ) => {\n let cstrInstanceId\n let cstrNodeName\n let cstrNamespace\n const WorkerBase = class {\n constructor(winId, instanceId, applyPath, instanceData, namespace) {\n this[WinIdKey] = winId || $winId$\n this[InstanceIdKey] = instanceId || cstrInstanceId || randomId()\n this[ApplyPathKey] = applyPath || []\n this[InstanceDataKey] = instanceData || cstrNodeName\n this[NamespaceKey] = namespace || cstrNamespace\n this[InstanceStateKey] = {}\n cstrInstanceId = cstrNodeName = cstrNamespace = void 0\n }\n }\n const WorkerLocation = defineConstructorName(\n class extends URL {\n assign() {\n logWorker('location.assign(), noop')\n }\n reload() {\n logWorker('location.reload(), noop')\n }\n replace() {\n logWorker('location.replace(), noop')\n }\n },\n 'Location'\n )\n const $location$ = new WorkerLocation(url)\n const $isSameOrigin$ =\n $location$.origin === webWorkerCtx.$origin$ ||\n 'about:blank' === $location$.origin\n const $isTopWindow$ = $parentWinId$ === $winId$\n const env = {}\n const getChildEnvs = () => {\n let childEnv = []\n let envWinId\n let otherEnv\n for (envWinId in environments) {\n otherEnv = environments[envWinId]\n otherEnv.$parentWinId$ !== $winId$ ||\n otherEnv.$isTopWindow$ ||\n childEnv.push(otherEnv)\n }\n return childEnv\n }\n const WorkerWindow = defineConstructorName(\n class extends WorkerBase {\n constructor() {\n super($winId$, $winId$)\n let win = this\n let value\n let historyState\n let hasInitializedMedia = 0\n let initWindowMedia = () => {\n if (!hasInitializedMedia) {\n ;(() => {\n if (!webWorkerCtx.$initWindowMedia$) {\n self.$bridgeToMedia$ = [\n getter,\n setter,\n callMethod,\n constructGlobal,\n definePrototypePropertyDescriptor,\n randomId,\n WinIdKey,\n InstanceIdKey,\n ApplyPathKey,\n ]\n webWorkerCtx.$importScripts$(\n partytownLibUrl('partytown-media.js?v=0.7.4')\n )\n webWorkerCtx.$initWindowMedia$ = self.$bridgeFromMedia$\n delete self.$bridgeFromMedia$\n }\n return webWorkerCtx.$initWindowMedia$\n })()(\n WorkerBase,\n WorkerEventTargetProxy,\n env,\n win,\n windowMediaConstructors\n )\n hasInitializedMedia = 1\n }\n }\n let nodeCstrs = {}\n let $createNode$ = (nodeName, instanceId, namespace) => {\n htmlMedia.includes(nodeName) && initWindowMedia()\n const NodeCstr = nodeCstrs[nodeName]\n ? nodeCstrs[nodeName]\n : nodeName.includes('-')\n ? nodeCstrs.UNKNOWN\n : nodeCstrs.I\n cstrInstanceId = instanceId\n cstrNodeName = nodeName\n cstrNamespace = namespace\n return new NodeCstr()\n }\n win.Window = WorkerWindow\n win.name = name + `${normalizedWinId($winId$)} (${$winId$})`\n createNodeCstr(win, env, WorkerBase)\n ;(win => {\n win.NodeList = defineConstructorName(NodeList, 'NodeList')\n })(win)\n createNamedNodeMapCstr(win, WorkerBase)\n createCSSStyleDeclarationCstr(win, WorkerBase, 'CSSStyleDeclaration')\n ;((win, WorkerBase, cstrName) => {\n win[cstrName] = defineConstructorName(\n class extends WorkerBase {\n now() {\n return performance.now()\n }\n },\n cstrName\n )\n })(win, WorkerBase, 'Performance')\n ;((win, nodeCstrs) => {\n const registry = new Map()\n win.customElements = {\n define(tagName, Cstr, opts) {\n registry.set(tagName, Cstr)\n nodeCstrs[tagName.toUpperCase()] = Cstr\n const ceData = [Cstr.name, Cstr.observedAttributes]\n callMethod(\n win,\n ['customElements', 'define'],\n [tagName, ceData, opts]\n )\n },\n get: tagName =>\n registry.get(tagName) ||\n callMethod(win, ['customElements', 'get'], [tagName]),\n whenDefined: tagName =>\n registry.has(tagName)\n ? Promise.resolve()\n : callMethod(\n win,\n ['customElements', 'whenDefined'],\n [tagName]\n ),\n upgrade: elm =>\n callMethod(win, ['customElements', 'upgrade'], [elm]),\n }\n })(win, nodeCstrs)\n webWorkerCtx.$interfaces$.map(\n ([cstrName, superCstrName, members, interfaceType, nodeName]) => {\n const SuperCstr = TrapConstructors[cstrName]\n ? WorkerTrapProxy\n : 'EventTarget' === superCstrName\n ? WorkerEventTargetProxy\n : 'Object' === superCstrName\n ? WorkerBase\n : win[superCstrName]\n const Cstr = (win[cstrName] = defineConstructorName(\n 12 === interfaceType\n ? class extends WorkerBase {\n constructor(...args) {\n super()\n constructGlobal(this, cstrName, args)\n }\n }\n : win[cstrName] || class extends SuperCstr {},\n cstrName\n ))\n nodeName && (nodeCstrs[nodeName] = Cstr)\n members.map(([memberName, memberType, staticValue]) => {\n memberName in Cstr.prototype ||\n memberName in SuperCstr.prototype ||\n ('string' == typeof memberType\n ? definePrototypeProperty(Cstr, memberName, {\n get() {\n if (!hasInstanceStateValue(this, memberName)) {\n const instanceId = this[InstanceIdKey]\n const applyPath = [\n ...this[ApplyPathKey],\n memberName,\n ]\n const PropCstr = win[memberType]\n PropCstr &&\n setInstanceStateValue(\n this,\n memberName,\n new PropCstr($winId$, instanceId, applyPath)\n )\n }\n return getInstanceStateValue(this, memberName)\n },\n set(value) {\n setInstanceStateValue(this, memberName, value)\n },\n })\n : 5 === memberType\n ? definePrototypeValue(\n Cstr,\n memberName,\n function (...args) {\n return callMethod(this, [memberName], args)\n }\n )\n : memberType > 0 &&\n (void 0 !== staticValue\n ? definePrototypeValue(Cstr, memberName, staticValue)\n : definePrototypeProperty(Cstr, memberName, {\n get() {\n return getter(this, [memberName])\n },\n set(value) {\n return setter(this, [memberName], value)\n },\n })))\n })\n }\n )\n commaSplit(\n 'atob,btoa,crypto,indexedDB,setTimeout,setInterval,clearTimeout,clearInterval'\n ).map(globalName => {\n delete WorkerWindow.prototype[globalName]\n if (!(globalName in win)) {\n value = self[globalName]\n null != value &&\n (win[globalName] =\n 'function' != typeof value ||\n value.toString().startsWith('class')\n ? value\n : value.bind(self))\n }\n })\n Object.getOwnPropertyNames(self).map(globalName => {\n globalName in win || (win[globalName] = self[globalName])\n })\n windowMediaConstructors.map(cstrName =>\n defineProperty(win, cstrName, {\n get() {\n initWindowMedia()\n return win[cstrName]\n },\n })\n )\n 'trustedTypes' in self && (win.trustedTypes = self.trustedTypes)\n patchElement(win.Element, win.HTMLElement)\n patchDocument(win.Document, env, isDocumentImplementation)\n ;(WorkerDocumentFragment => {\n definePrototypeNodeType(WorkerDocumentFragment, 11)\n cachedTreeProps(WorkerDocumentFragment, elementStructurePropNames)\n })(win.DocumentFragment)\n patchHTMLAnchorElement(win.HTMLAnchorElement, env)\n ;(WorkerHTMLFormElement => {\n definePrototypePropertyDescriptor(WorkerHTMLFormElement, {})\n cachedProps(WorkerHTMLFormElement, 'elements')\n })(win.HTMLFormElement)\n patchHTMLIFrameElement(win.HTMLIFrameElement)\n patchHTMLScriptElement(win.HTMLScriptElement, env)\n patchSvgElement(win.SVGGraphicsElement)\n patchDocumentElementChild(win.HTMLHeadElement, env)\n patchDocumentElementChild(win.HTMLBodyElement, env)\n ;((WorkerHTMLHtmlElement, env) => {\n const DocumentElementDescriptorMap = {\n parentElement: {\n value: null,\n },\n parentNode: {\n get: () => env.$document$,\n },\n }\n definePrototypePropertyDescriptor(\n WorkerHTMLHtmlElement,\n DocumentElementDescriptorMap\n )\n })(win.HTMLHtmlElement, env)\n createCSSStyleSheetConstructor(win, 'CSSStyleSheet')\n definePrototypeNodeType(win.Comment, 8)\n definePrototypeNodeType(win.DocumentType, 10)\n Object.assign(env, {\n $winId$: $winId$,\n $parentWinId$: $parentWinId$,\n $window$: new Proxy(win, {\n get: (win, propName) => {\n var _a\n if ('string' != typeof propName || isNaN(propName)) {\n return (\n null === (_a = webWorkerCtx.$config$.mainWindowAccessors) ||\n void 0 === _a\n ? void 0\n : _a.includes(propName)\n )\n ? getter(this, [propName])\n : win[propName]\n }\n {\n let frame = getChildEnvs()[propName]\n return frame ? frame.$window$ : void 0\n }\n },\n has: () => true,\n }),\n $document$: $createNode$('#document', $winId$ + '.d'),\n $documentElement$: $createNode$('HTML', $winId$ + '.e'),\n $head$: $createNode$('HEAD', $winId$ + '.h'),\n $body$: $createNode$('BODY', $winId$ + '.b'),\n $location$: $location$,\n $visibilityState$: $visibilityState$,\n $isSameOrigin$: $isSameOrigin$,\n $isTopWindow$: $isTopWindow$,\n $createNode$: $createNode$,\n })\n win.requestAnimationFrame = cb =>\n setTimeout(() => cb(performance.now()), 9)\n win.cancelAnimationFrame = id => clearTimeout(id)\n win.requestIdleCallback = (cb, start) => {\n start = Date.now()\n return setTimeout(\n () =>\n cb({\n didTimeout: false,\n timeRemaining: () => Math.max(0, 50 - (Date.now() - start)),\n }),\n 1\n )\n }\n win.cancelIdleCallback = id => clearTimeout(id)\n addStorageApi(\n win,\n 'localStorage',\n webWorkerlocalStorage,\n $isSameOrigin$,\n env\n )\n addStorageApi(\n win,\n 'sessionStorage',\n webWorkerSessionStorage,\n $isSameOrigin$,\n env\n )\n $isSameOrigin$ || (win.indexeddb = void 0)\n if (isIframeWindow) {\n historyState = {}\n win.history = {\n pushState(stateObj) {\n historyState = stateObj\n },\n replaceState(stateObj) {\n historyState = stateObj\n },\n get state() {\n return historyState\n },\n length: 0,\n }\n win.indexeddb = void 0\n } else {\n const originalPushState = win.history.pushState.bind(win.history)\n const originalReplaceState = win.history.replaceState.bind(\n win.history\n )\n win.history.pushState = (stateObj, _, newUrl) => {\n false !== env.$propagateHistoryChange$ &&\n originalPushState(stateObj, _, newUrl)\n }\n win.history.replaceState = (stateObj, _, newUrl) => {\n false !== env.$propagateHistoryChange$ &&\n originalReplaceState(stateObj, _, newUrl)\n }\n }\n win.Worker = void 0\n }\n addEventListener(...args) {\n 'load' === args[0]\n ? env.$runWindowLoadEvent$ &&\n setTimeout(() =>\n args[1]({\n type: 'load',\n })\n )\n : callMethod(this, ['addEventListener'], args, 2)\n }\n get body() {\n return env.$body$\n }\n get document() {\n return env.$document$\n }\n get documentElement() {\n return env.$documentElement$\n }\n fetch(input, init) {\n input =\n 'string' == typeof input || input instanceof URL\n ? String(input)\n : input.url\n return fetch(resolveUrl(env, input, 'fetch'), init)\n }\n get frames() {\n return env.$window$\n }\n get frameElement() {\n return $isTopWindow$\n ? null\n : getOrCreateNodeInstance($parentWinId$, $winId$, 'IFRAME')\n }\n get globalThis() {\n return env.$window$\n }\n get head() {\n return env.$head$\n }\n get length() {\n return getChildEnvs().length\n }\n get location() {\n return $location$\n }\n set location(loc) {\n $location$.href = loc + ''\n }\n get Image() {\n return createImageConstructor(env)\n }\n get navigator() {\n return (env => {\n let key\n let nav = {\n sendBeacon: (url, body) => {\n if (webWorkerCtx.$config$.logSendBeaconRequests) {\n try {\n logWorker(\n `sendBeacon: ${resolveUrl(env, url, null)}${\n body ? ', data: ' + JSON.stringify(body) : ''\n }`\n )\n } catch (e) {\n console.error(e)\n }\n }\n try {\n fetch(resolveUrl(env, url, null), {\n method: 'POST',\n body: body,\n mode: 'no-cors',\n keepalive: true,\n })\n return true\n } catch (e) {\n console.error(e)\n return false\n }\n },\n }\n for (key in navigator) {\n nav[key] = navigator[key]\n }\n return nav\n })(env)\n }\n get origin() {\n return $location$.origin\n }\n set origin(_) {}\n get parent() {\n for (let envWinId in environments) {\n if (environments[envWinId].$winId$ === $parentWinId$) {\n return environments[envWinId].$window$\n }\n }\n return env.$window$\n }\n postMessage(...args) {\n if (environments[args[0]]) {\n len(postMessages) > 50 && postMessages.splice(0, 5)\n postMessages.push({\n $winId$: args[0],\n $data$: JSON.stringify(args[1]),\n })\n args = args.slice(1)\n }\n callMethod(this, ['postMessage'], args, 3)\n }\n get self() {\n return env.$window$\n }\n get top() {\n for (let envWinId in environments) {\n if (environments[envWinId].$isTopWindow$) {\n return environments[envWinId].$window$\n }\n }\n return env.$window$\n }\n get window() {\n return env.$window$\n }\n get XMLHttpRequest() {\n const Xhr = XMLHttpRequest\n const str = String(Xhr)\n const ExtendedXhr = defineConstructorName(\n class extends Xhr {\n open(...args) {\n args[1] = resolveUrl(env, args[1], 'xhr')\n super.open(...args)\n }\n set withCredentials(_) {}\n toString() {\n return str\n }\n },\n getConstructorName(Xhr)\n )\n ExtendedXhr.prototype.constructor.toString = () => str\n return ExtendedXhr\n }\n },\n 'Window'\n )\n const WorkerTrapProxy = class extends WorkerBase {\n constructor(winId, instanceId, applyPath, nodeName) {\n super(winId, instanceId, applyPath, nodeName)\n return new Proxy(this, {\n get: (instance, propName) => getter(instance, [propName]),\n set(instance, propName, propValue) {\n setter(instance, [propName], propValue)\n return true\n },\n })\n }\n }\n const WorkerEventTargetProxy = class extends WorkerBase {}\n eventTargetMethods.map(\n methodName =>\n (WorkerEventTargetProxy.prototype[methodName] = function (...args) {\n return callMethod(this, [methodName], args, 2)\n })\n )\n cachedProps(WorkerWindow, 'devicePixelRatio')\n cachedDimensionProps(WorkerWindow)\n cachedDimensionMethods(WorkerWindow, ['getComputedStyle'])\n new WorkerWindow()\n return env\n }\n const TrapConstructors = {\n DOMStringMap: 1,\n NamedNodeMap: 1,\n }\n const createEnvironment = (\n {\n $winId$: $winId$,\n $parentWinId$: $parentWinId$,\n $url$: $url$,\n $visibilityState$: $visibilityState$,\n },\n isIframeWindow,\n isDocumentImplementation\n ) => {\n if (!environments[$winId$]) {\n environments[$winId$] = createWindow(\n $winId$,\n $parentWinId$,\n $url$,\n $visibilityState$,\n isIframeWindow,\n isDocumentImplementation\n )\n {\n const winType = $winId$ === $parentWinId$ ? 'top' : 'iframe'\n logWorker(\n `Created ${winType} window ${normalizedWinId($winId$)} environment`,\n $winId$\n )\n }\n }\n webWorkerCtx.$postMessage$([7, $winId$])\n return environments[$winId$]\n }\n const queuedEvents = []\n const receiveMessageFromSandboxToWorker = ev => {\n const msg = ev.data\n const msgType = msg[0]\n const msgValue = msg[1]\n if (webWorkerCtx.$isInitialized$) {\n if (7 === msgType) {\n ;(async initScript => {\n let winId = initScript.$winId$\n let instanceId = initScript.$instanceId$\n let instance = getOrCreateNodeInstance(winId, instanceId, 'SCRIPT')\n let scriptContent = initScript.$content$\n let scriptSrc = initScript.$url$\n let scriptOrgSrc = initScript.$orgUrl$\n let errorMsg = ''\n let env = environments[winId]\n let rsp\n let javascriptContentTypes = [\n 'text/jscript',\n 'text/javascript',\n 'text/x-javascript',\n 'application/javascript',\n 'application/x-javascript',\n 'text/ecmascript',\n 'text/x-ecmascript',\n 'application/ecmascript',\n ]\n if (scriptSrc) {\n try {\n scriptSrc = resolveToUrl(env, scriptSrc, 'script') + ''\n setInstanceStateValue(instance, 4, scriptSrc)\n webWorkerCtx.$config$.logScriptExecution &&\n logWorker(`Execute script src: ${scriptOrgSrc}`, winId)\n rsp = await fetch(scriptSrc)\n if (rsp.ok) {\n let responseContentType = rsp.headers.get('content-type')\n let shouldExecute = javascriptContentTypes.some(ct => {\n var _a, _b, _c\n return null ===\n (_c =\n null ===\n (_a =\n null == responseContentType\n ? void 0\n : responseContentType.toLowerCase) || void 0 === _a\n ? void 0\n : (_b = _a.call(responseContentType)).includes) ||\n void 0 === _c\n ? void 0\n : _c.call(_b, ct)\n })\n if (shouldExecute) {\n scriptContent = await rsp.text()\n env.$currentScriptId$ = instanceId\n run(env, scriptContent, scriptOrgSrc || scriptSrc)\n }\n runStateLoadHandlers(instance, 'load')\n } else {\n errorMsg = rsp.statusText\n runStateLoadHandlers(instance, 'error')\n }\n } catch (urlError) {\n console.error(urlError)\n errorMsg = String(urlError.stack || urlError)\n runStateLoadHandlers(instance, 'error')\n }\n } else {\n scriptContent &&\n (errorMsg = runScriptContent(\n env,\n instanceId,\n scriptContent,\n winId,\n errorMsg\n ))\n }\n env.$currentScriptId$ = ''\n webWorkerCtx.$postMessage$([6, winId, instanceId, errorMsg])\n })(msgValue)\n } else if (9 === msgType) {\n ;(({\n $winId$: $winId$,\n $instanceId$: $instanceId$,\n $refId$: $refId$,\n $thisArg$: $thisArg$,\n $args$: $args$,\n }) => {\n if (webWorkerRefsByRefId[$refId$]) {\n try {\n webWorkerRefsByRefId[$refId$].apply(\n deserializeFromMain($winId$, $instanceId$, [], $thisArg$),\n deserializeFromMain($winId$, $instanceId$, [], $args$)\n )\n } catch (e) {\n console.error(e)\n }\n }\n })(msgValue)\n } else if (10 === msgType) {\n ;(({ $winId$: $winId$, $forward$: $forward$, $args$: $args$ }) => {\n try {\n let target = environments[$winId$].$window$\n let i = 0\n let l = len($forward$)\n for (; i < l; i++) {\n i + 1 < l\n ? (target = target[$forward$[i]])\n : target[$forward$[i]].apply(\n target,\n deserializeFromMain(null, $winId$, [], $args$)\n )\n }\n } catch (e) {\n console.error(e)\n }\n })(msgValue)\n } else if (5 === msgType) {\n createEnvironment(msgValue)\n } else if (8 === msgType) {\n if (1 !== environments[msgValue].$isInitialized$) {\n const winId = msgValue\n const env = environments[winId]\n const winType = env.$winId$ === env.$parentWinId$ ? 'top' : 'iframe'\n logWorker(\n `Initialized ${winType} window ${normalizedWinId(\n winId\n )} environment 🎉`,\n winId\n )\n }\n environments[msgValue].$isInitialized$ = 1\n environments[msgValue].$isLoading$ = 0\n } else if (14 === msgType) {\n environments[msgValue].$visibilityState$ = msg[2]\n } else if (13 === msgType) {\n const $winId$ = msgValue.$winId$\n const env = environments[$winId$]\n env.$location$.href = msgValue.url\n !(function ($winId$, env, data) {\n const history = env.$window$.history\n switch (data.type) {\n case 0:\n env.$propagateHistoryChange$ = false\n try {\n history.pushState(data.state, '', data.newUrl)\n } catch (e) {}\n env.$propagateHistoryChange$ = true\n break\n\n case 1:\n env.$propagateHistoryChange$ = false\n try {\n history.replaceState(data.state, '', data.newUrl)\n } catch (e) {}\n env.$propagateHistoryChange$ = true\n }\n })(msgValue.$winId$, env, msgValue)\n } else {\n 15 === msgType &&\n ((_type, winId, instanceId, callbackName, args) => {\n const elm = getOrCreateNodeInstance(winId, instanceId)\n elm &&\n 'function' == typeof elm[callbackName] &&\n elm[callbackName].apply(elm, args)\n })(...msg)\n }\n } else if (1 === msgType) {\n ;(initWebWorkerData => {\n const config = (webWorkerCtx.$config$ = JSON.parse(\n initWebWorkerData.$config$\n ))\n const locOrigin = initWebWorkerData.$origin$\n webWorkerCtx.$importScripts$ = importScripts.bind(self)\n webWorkerCtx.$interfaces$ = initWebWorkerData.$interfaces$\n webWorkerCtx.$libPath$ = initWebWorkerData.$libPath$\n webWorkerCtx.$origin$ = locOrigin\n webWorkerCtx.$postMessage$ = postMessage.bind(self)\n webWorkerCtx.$sharedDataBuffer$ = initWebWorkerData.$sharedDataBuffer$\n webWorkerlocalStorage.set(locOrigin, initWebWorkerData.$localStorage$)\n webWorkerSessionStorage.set(\n locOrigin,\n initWebWorkerData.$sessionStorage$\n )\n self.importScripts = void 0\n delete self.postMessage\n delete self.WorkerGlobalScope\n commaSplit('resolveUrl,get,set,apply').map(configName => {\n config[configName] &&\n (config[configName] = new Function(\n 'return ' + config[configName]\n )())\n })\n })(msgValue)\n webWorkerCtx.$postMessage$([2])\n } else if (3 === msgType) {\n webWorkerCtx.$interfaces$ = [...webWorkerCtx.$interfaces$, ...msgValue]\n webWorkerCtx.$isInitialized$ = 1\n logWorker('Initialized web worker')\n webWorkerCtx.$postMessage$([4])\n queuedEvents.length &&\n logWorker(`Queued ready messages: ${queuedEvents.length}`)\n ;[...queuedEvents].map(receiveMessageFromSandboxToWorker)\n queuedEvents.length = 0\n } else {\n queuedEvents.push(ev)\n }\n }\n self.onmessage = receiveMessageFromSandboxToWorker\n postMessage([0])\n})(self)\n\n```"
}
] |
code_partytown_1a4b89f3
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of partytown/public/~partytown/debug/partytown.js from the partytown VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\n/* Partytown 0.7.4 - MIT builder.io */\n!(function (\n win,\n doc,\n nav,\n top,\n useAtomics,\n config,\n libPath,\n timeout,\n scripts,\n sandbox,\n mainForwardFn,\n isReady\n) {\n function ready() {\n if (!isReady) {\n isReady = 1\n libPath =\n (config.lib || '/~partytown/') +\n (false !== config.debug ? 'debug/' : '')\n if ('/' == libPath[0]) {\n scripts = doc.querySelectorAll('script[type=\"text/partytown\"]')\n if (top != win) {\n top.dispatchEvent(\n new CustomEvent('pt1', {\n detail: win,\n })\n )\n } else {\n timeout = setTimeout(fallback, 1e4)\n doc.addEventListener('pt0', clearFallback)\n useAtomics\n ? loadSandbox(1)\n : nav.serviceWorker\n ? nav.serviceWorker\n .register(libPath + (config.swPath || 'partytown-sw.js'), {\n scope: libPath,\n })\n .then(function (swRegistration) {\n if (swRegistration.active) {\n loadSandbox()\n } else if (swRegistration.installing) {\n swRegistration.installing.addEventListener(\n 'statechange',\n function (ev) {\n 'activated' == ev.target.state && loadSandbox()\n }\n )\n } else {\n console.warn(swRegistration)\n }\n }, console.error)\n : fallback()\n }\n } else {\n console.warn('Partytown config.lib url must start with \"/\"')\n }\n }\n }\n function loadSandbox(isAtomics) {\n sandbox = doc.createElement(isAtomics ? 'script' : 'iframe')\n if (!isAtomics) {\n sandbox.setAttribute(\n 'style',\n 'display:block;width:0;height:0;border:0;visibility:hidden'\n )\n sandbox.setAttribute('aria-hidden', !0)\n }\n sandbox.src =\n libPath +\n 'partytown-' +\n (isAtomics ? 'atomics.js?v=0.7.4' : 'sandbox-sw.html?' + Date.now())\n doc.body.appendChild(sandbox)\n }\n function fallback(i, script) {\n console.warn('Partytown script fallback')\n clearFallback()\n for (i = 0; i < scripts.length; i++) {\n script = doc.createElement('script')\n script.innerHTML = scripts[i].innerHTML\n doc.head.appendChild(script)\n }\n sandbox && sandbox.parentNode.removeChild(sandbox)\n }\n function clearFallback() {\n clearTimeout(timeout)\n }\n config = win.partytown || {}\n top == win &&\n (config.forward || []).map(function (forwardProps) {\n mainForwardFn = win\n forwardProps.split('.').map(function (_, i, forwardPropsArr) {\n mainForwardFn = mainForwardFn[forwardPropsArr[i]] =\n i + 1 < forwardPropsArr.length\n ? 'push' == forwardPropsArr[i + 1]\n ? []\n : mainForwardFn[forwardPropsArr[i]] || {}\n : function () {\n ;(win._ptf = win._ptf || []).push(forwardPropsArr, arguments)\n }\n })\n })\n if ('complete' == doc.readyState) {\n ready()\n } else {\n win.addEventListener('DOMContentLoaded', ready)\n win.addEventListener('load', ready)\n }\n})(window, document, navigator, top, window.crossOriginIsolated)\n\n```"
}
] |
code_partytown_e0cea937
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of partytown/public/~partytown/debug/partytown-media.js from the partytown VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\n/* Partytown 0.7.4 - MIT builder.io */\n;(self => {\n const [\n getter,\n setter,\n callMethod,\n constructGlobal,\n definePrototypePropertyDescriptor,\n randomId,\n WinIdKey,\n InstanceIdKey,\n ApplyPathKey,\n ] = self.$bridgeToMedia$\n delete self.$bridgeToMedia$\n const ContextKey = Symbol()\n const MediaSourceKey = Symbol()\n const ReadyStateKey = Symbol()\n const SourceBuffersKey = Symbol()\n const SourceBufferTasksKey = Symbol()\n const TimeRangesKey = Symbol()\n const EMPTY_ARRAY = []\n const defineCstr = (win, cstrName, Cstr) =>\n (win[cstrName] = defineCstrName(cstrName, Cstr))\n const defineCstrName = (cstrName, Cstr) =>\n Object.defineProperty(Cstr, 'name', {\n value: cstrName,\n })\n const initCanvas = (WorkerBase, win) => {\n const HTMLCanvasDescriptorMap = {\n getContext: {\n value(contextType, contextAttributes) {\n this[ContextKey] ||\n (this[ContextKey] = (contextType.includes('webgl')\n ? createContextWebGL\n : createContext2D)(this, contextType, contextAttributes))\n return this[ContextKey]\n },\n },\n }\n const WorkerCanvasGradient = defineCstr(\n win,\n 'CanvasGradient',\n class extends WorkerBase {\n addColorStop(...args) {\n callMethod(this, ['addColorStop'], args, 2)\n }\n }\n )\n const WorkerCanvasPattern = defineCstr(\n win,\n 'CanvasPattern',\n class extends WorkerBase {\n setTransform(...args) {\n callMethod(this, ['setTransform'], args, 2)\n }\n }\n )\n const createContext2D = (\n canvasInstance,\n contextType,\n contextAttributes\n ) => {\n const winId = canvasInstance[WinIdKey]\n const ctxInstanceId = randomId()\n const ctxInstance = {\n [WinIdKey]: winId,\n [InstanceIdKey]: ctxInstanceId,\n [ApplyPathKey]: [],\n }\n const ctx = callMethod(\n canvasInstance,\n ['getContext'],\n [contextType, contextAttributes],\n 1,\n ctxInstanceId\n )\n const ctx2dGetterMethods = 'getContextAttributes,getImageData,getLineDash,getTransform,isPointInPath,isPointInStroke,measureText'.split(\n ','\n )\n const CanvasRenderingContext2D = {\n get: (target, propName) =>\n 'string' == typeof propName && propName in ctx\n ? 'function' == typeof ctx[propName]\n ? (...args) => {\n if (propName.startsWith('create')) {\n const instanceId = randomId()\n callMethod(ctxInstance, [propName], args, 2, instanceId)\n if (\n 'createImageData' === propName ||\n 'createPattern' === propName\n ) {\n ;(api => {\n console.warn(`${api} not implemented`)\n })(`${propName}()`)\n return {\n setTransform: () => {},\n }\n }\n return new WorkerCanvasGradient(winId, instanceId)\n }\n const methodCallType = ctx2dGetterMethods.includes(propName)\n ? 1\n : 2\n return callMethod(\n ctxInstance,\n [propName],\n args,\n methodCallType\n )\n }\n : ctx[propName]\n : target[propName],\n set(target, propName, value) {\n if ('string' == typeof propName && propName in ctx) {\n ctx[propName] !== value &&\n 'function' != typeof value &&\n setter(ctxInstance, [propName], value)\n ctx[propName] = value\n } else {\n target[propName] = value\n }\n return true\n },\n }\n return new Proxy(ctx, CanvasRenderingContext2D)\n }\n const createContextWebGL = (\n canvasInstance,\n contextType,\n contextAttributes\n ) => {\n const winId = canvasInstance[WinIdKey]\n const ctxInstanceId = randomId()\n const ctxInstance = {\n [WinIdKey]: winId,\n [InstanceIdKey]: ctxInstanceId,\n [ApplyPathKey]: [],\n }\n const ctx = callMethod(\n canvasInstance,\n ['getContext'],\n [contextType, contextAttributes],\n 1,\n ctxInstanceId\n )\n const WebGLRenderingContextHandler = {\n get: (target, propName) =>\n 'string' == typeof propName\n ? 'function' != typeof ctx[propName]\n ? ctx[propName]\n : (...args) =>\n callMethod(\n ctxInstance,\n [propName],\n args,\n getWebGlMethodCallType(propName)\n )\n : target[propName],\n set(target, propName, value) {\n if ('string' == typeof propName && propName in ctx) {\n ctx[propName] !== value &&\n 'function' != typeof value &&\n setter(ctxInstance, [propName], value)\n ctx[propName] = value\n } else {\n target[propName] = value\n }\n return true\n },\n }\n return new Proxy(ctx, WebGLRenderingContextHandler)\n }\n const ctxWebGLGetterMethods = 'checkFramebufferStatus,makeXRCompatible'.split(\n ','\n )\n const getWebGlMethodCallType = methodName =>\n methodName.startsWith('create') ||\n methodName.startsWith('get') ||\n methodName.startsWith('is') ||\n ctxWebGLGetterMethods.includes(methodName)\n ? 1\n : 2\n defineCstr(win, 'CanvasGradient', WorkerCanvasGradient)\n defineCstr(win, 'CanvasPattern', WorkerCanvasPattern)\n definePrototypePropertyDescriptor(\n win.HTMLCanvasElement,\n HTMLCanvasDescriptorMap\n )\n }\n const initMedia = (WorkerBase, WorkerEventTargetProxy, env, win) => {\n var _a, _b\n win.Audio = defineCstrName(\n 'HTMLAudioElement',\n class {\n constructor(src) {\n const audio = env.$createNode$('audio', randomId())\n audio.src = src\n return audio\n }\n }\n )\n const WorkerAudioTrack = class extends WorkerBase {\n get enabled() {\n return getter(this, ['enabled'])\n }\n set enabled(value) {\n setter(this, ['enabled'], value)\n }\n get id() {\n return getter(this, ['id'])\n }\n get kind() {\n return getter(this, ['kind'])\n }\n get label() {\n return getter(this, ['label'])\n }\n get language() {\n return getter(this, ['language'])\n }\n get sourceBuffer() {\n return new WorkerSourceBuffer(this)\n }\n }\n const WorkerAudioTrackList = class {\n constructor(mediaElm) {\n const winId = mediaElm[WinIdKey]\n const instanceId = mediaElm[InstanceIdKey]\n const instance = {\n addEventListener(...args) {\n callMethod(mediaElm, ['audioTracks', 'addEventListener'], args, 3)\n },\n getTrackById: (...args) =>\n callMethod(mediaElm, ['audioTracks', 'getTrackById'], args),\n get length() {\n return getter(mediaElm, ['audioTracks', 'length'])\n },\n removeEventListener(...args) {\n callMethod(\n mediaElm,\n ['audioTracks', 'removeEventListener'],\n args,\n 3\n )\n },\n }\n return new Proxy(instance, {\n get: (target, propName) =>\n 'number' == typeof propName\n ? new WorkerAudioTrack(winId, instanceId, [\n 'audioTracks',\n propName,\n ])\n : target[propName],\n })\n }\n }\n const WorkerSourceBufferList = defineCstr(\n win,\n 'SourceBufferList',\n class extends Array {\n constructor(mediaSource) {\n super()\n this[MediaSourceKey] = mediaSource\n }\n addEventListener(...args) {\n callMethod(\n this[MediaSourceKey],\n ['sourceBuffers', 'addEventListener'],\n args,\n 3\n )\n }\n removeEventListener(...args) {\n callMethod(\n this[MediaSourceKey],\n ['sourceBuffers', 'removeEventListener'],\n args,\n 3\n )\n }\n }\n )\n const WorkerSourceBuffer = defineCstr(\n win,\n 'SourceBuffer',\n ((_b = class extends WorkerEventTargetProxy {\n constructor(mediaSource) {\n super(mediaSource[WinIdKey], mediaSource[InstanceIdKey], [\n 'sourceBuffers',\n ])\n this[_a] = []\n this[MediaSourceKey] = mediaSource\n }\n abort() {\n const sbIndex = getSourceBufferIndex(this)\n callMethod(this, [sbIndex, 'appendWindowStart'], EMPTY_ARRAY, 1)\n }\n addEventListener(...args) {\n const sbIndex = getSourceBufferIndex(this)\n callMethod(this, [sbIndex, 'addEventListener'], args, 3)\n }\n appendBuffer(buf) {\n this[SourceBufferTasksKey].push(['appendBuffer', [buf], buf])\n drainSourceBufferQueue(this)\n }\n get appendWindowStart() {\n const sbIndex = getSourceBufferIndex(this)\n return getter(this, [sbIndex, 'appendWindowStart'])\n }\n set appendWindowStart(value) {\n const sbIndex = getSourceBufferIndex(this)\n setter(this, [sbIndex, 'appendWindowStart'], value)\n }\n get appendWindowEnd() {\n const sbIndex = getSourceBufferIndex(this)\n return getter(this, [sbIndex, 'appendWindowEnd'])\n }\n set appendWindowEnd(value) {\n const sbIndex = getSourceBufferIndex(this)\n setter(this, [sbIndex, 'appendWindowEnd'], value)\n }\n get buffered() {\n const mediaSource = this[MediaSourceKey]\n const sbIndex = getSourceBufferIndex(this)\n const timeRanges = new WorkerTimeRanges(\n mediaSource[WinIdKey],\n mediaSource[InstanceIdKey],\n ['sourceBuffers', sbIndex, 'buffered']\n )\n return timeRanges\n }\n changeType(mimeType) {\n const sbIndex = getSourceBufferIndex(this)\n callMethod(this, [sbIndex, 'changeType'], [mimeType], 2)\n }\n get mode() {\n const sbIndex = getSourceBufferIndex(this)\n return getter(this, [sbIndex, 'mode'])\n }\n set mode(value) {\n const sbIndex = getSourceBufferIndex(this)\n setter(this, [sbIndex, 'mode'], value)\n }\n remove(start, end) {\n this[SourceBufferTasksKey].push(['remove', [start, end]])\n drainSourceBufferQueue(this)\n }\n removeEventListener(...args) {\n const sbIndex = getSourceBufferIndex(this)\n callMethod(this, [sbIndex, 'removeEventListener'], args, 3)\n }\n get timestampOffset() {\n const sbIndex = getSourceBufferIndex(this)\n return getter(this, [sbIndex, 'timestampOffset'])\n }\n set timestampOffset(value) {\n const sbIndex = getSourceBufferIndex(this)\n setter(this, [sbIndex, 'timestampOffset'], value)\n }\n get updating() {\n const sbIndex = getSourceBufferIndex(this)\n return getter(this, [sbIndex, 'updating'])\n }\n }),\n (_a = SourceBufferTasksKey),\n _b)\n )\n const WorkerTimeRanges = defineCstr(\n win,\n 'TimeRanges',\n class extends WorkerBase {\n start(...args) {\n return callMethod(this, ['start'], args)\n }\n end(...args) {\n return callMethod(this, ['end'], args)\n }\n get length() {\n return getter(this, ['length'])\n }\n }\n )\n const getSourceBufferIndex = sourceBuffer => {\n if (sourceBuffer) {\n const mediaSource = sourceBuffer[MediaSourceKey]\n const sourceBufferList = mediaSource[SourceBuffersKey]\n return sourceBufferList.indexOf(sourceBuffer)\n }\n return -1\n }\n const drainSourceBufferQueue = sourceBuffer => {\n if (sourceBuffer[SourceBufferTasksKey].length) {\n if (!sourceBuffer.updating) {\n const task = sourceBuffer[SourceBufferTasksKey].shift()\n if (task) {\n const sbIndex = getSourceBufferIndex(sourceBuffer)\n callMethod(\n sourceBuffer,\n [sbIndex, task[0]],\n task[1],\n 3,\n void 0,\n task[2]\n )\n }\n }\n setTimeout(() => drainSourceBufferQueue(sourceBuffer), 50)\n }\n }\n const HTMLMediaDescriptorMap = {\n buffered: {\n get() {\n if (!this[TimeRangesKey]) {\n this[TimeRangesKey] = new WorkerTimeRanges(\n this[WinIdKey],\n this[InstanceIdKey],\n ['buffered']\n )\n setTimeout(() => {\n this[TimeRangesKey] = void 0\n }, 5e3)\n }\n return this[TimeRangesKey]\n },\n },\n readyState: {\n get() {\n if (4 === this[ReadyStateKey]) {\n return 4\n }\n if ('number' != typeof this[ReadyStateKey]) {\n this[ReadyStateKey] = getter(this, ['readyState'])\n setTimeout(() => {\n this[ReadyStateKey] = void 0\n }, 1e3)\n }\n return this[ReadyStateKey]\n },\n },\n }\n defineCstr(\n win,\n 'MediaSource',\n class extends WorkerEventTargetProxy {\n constructor() {\n super(env.$winId$)\n this[SourceBuffersKey] = new WorkerSourceBufferList(this)\n constructGlobal(this, 'MediaSource', EMPTY_ARRAY)\n }\n get activeSourceBuffers() {\n return []\n }\n addSourceBuffer(mimeType) {\n const sourceBuffer = new WorkerSourceBuffer(this)\n this[SourceBuffersKey].push(sourceBuffer)\n callMethod(this, ['addSourceBuffer'], [mimeType])\n return sourceBuffer\n }\n clearLiveSeekableRange() {\n callMethod(this, ['clearLiveSeekableRange'], EMPTY_ARRAY, 2)\n }\n get duration() {\n return getter(this, ['duration'])\n }\n set duration(value) {\n setter(this, ['duration'], value)\n }\n endOfStream(endOfStreamError) {\n callMethod(this, ['endOfStream'], [endOfStreamError], 3)\n }\n get readyState() {\n return getter(this, ['readyState'])\n }\n removeSourceBuffer(sourceBuffer) {\n const index = getSourceBufferIndex(sourceBuffer)\n if (index > -1) {\n this[SourceBuffersKey].splice(index, 1)\n callMethod(this, ['removeSourceBuffer'], [index], 1)\n }\n }\n setLiveSeekableRange(start, end) {\n callMethod(this, ['setLiveSeekableRange'], [start, end], 2)\n }\n get sourceBuffers() {\n return this[SourceBuffersKey]\n }\n static isTypeSupported(mimeType) {\n if (!isStaticTypeSupported.has(mimeType)) {\n const isSupported = callMethod(\n win,\n ['MediaSource', 'isTypeSupported'],\n [mimeType]\n )\n isStaticTypeSupported.set(mimeType, isSupported)\n }\n return isStaticTypeSupported.get(mimeType)\n }\n }\n )\n const winURL = (win.URL = defineCstrName('URL', class extends URL {}))\n const hasAudioTracks = 'audioTracks' in win.HTMLMediaElement.prototype\n if (hasAudioTracks) {\n defineCstr(win, 'AudioTrackList', WorkerAudioTrackList)\n defineCstr(win, 'AudioTrack', WorkerAudioTrack)\n HTMLMediaDescriptorMap.audioTracks = {\n get() {\n return new WorkerAudioTrackList(this)\n },\n }\n }\n definePrototypePropertyDescriptor(\n win.HTMLMediaElement,\n HTMLMediaDescriptorMap\n )\n winURL.createObjectURL = obj =>\n callMethod(win, ['URL', 'createObjectURL'], [obj])\n winURL.revokeObjectURL = obj =>\n callMethod(win, ['URL', 'revokeObjectURL'], [obj])\n }\n const isStaticTypeSupported = new Map()\n self.$bridgeFromMedia$ = (\n WorkerBase,\n WorkerEventTargetProxy,\n env,\n win,\n windowMediaConstructors\n ) => {\n windowMediaConstructors.map(mediaCstrName => {\n delete win[mediaCstrName]\n })\n initCanvas(WorkerBase, win)\n initMedia(WorkerBase, WorkerEventTargetProxy, env, win)\n }\n})(self)\n\n```"
}
] |
code_partytown_12c9b3ed
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of partytown/public/~partytown/debug/partytown-ww-sw.js from the partytown VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\n/* Partytown 0.7.4 - MIT builder.io */\n;(self => {\n const WinIdKey = Symbol()\n const InstanceIdKey = Symbol()\n const InstanceDataKey = Symbol()\n const NamespaceKey = Symbol()\n const ApplyPathKey = Symbol()\n const InstanceStateKey = Symbol()\n const HookContinue = Symbol()\n const HookPrevent = Symbol()\n const webWorkerInstances = new Map()\n const webWorkerRefsByRefId = {}\n const webWorkerRefIdsByRef = new WeakMap()\n const postMessages = []\n const webWorkerCtx = {}\n const webWorkerlocalStorage = new Map()\n const webWorkerSessionStorage = new Map()\n const environments = {}\n const cachedDimensions = new Map()\n const cachedStructure = new Map()\n const commaSplit = str => str.split(',')\n const partytownLibUrl = url => {\n url = webWorkerCtx.$libPath$ + url\n if (new URL(url).origin != location.origin) {\n throw 'Invalid ' + url\n }\n return url\n }\n const getterDimensionPropNames = commaSplit(\n 'clientWidth,clientHeight,clientTop,clientLeft,innerWidth,innerHeight,offsetWidth,offsetHeight,offsetTop,offsetLeft,outerWidth,outerHeight,pageXOffset,pageYOffset,scrollWidth,scrollHeight,scrollTop,scrollLeft'\n )\n const elementStructurePropNames = commaSplit(\n 'childElementCount,children,firstElementChild,lastElementChild,nextElementSibling,previousElementSibling'\n )\n const structureChangingMethodNames = commaSplit(\n 'insertBefore,remove,removeChild,replaceChild'\n )\n const dimensionChangingSetterNames = commaSplit(\n 'className,width,height,hidden,innerHTML,innerText,textContent'\n )\n const dimensionChangingMethodNames = commaSplit(\n 'setAttribute,setAttributeNS,setProperty'\n )\n const eventTargetMethods = commaSplit(\n 'addEventListener,dispatchEvent,removeEventListener'\n )\n const nonBlockingMethods = eventTargetMethods.concat(\n dimensionChangingMethodNames,\n commaSplit('add,observe,remove,unobserve')\n )\n const IS_TAG_REG = /^[A-Z_]([A-Z0-9-]*[A-Z0-9])?$/\n const noop = () => {}\n const len = obj => obj.length\n const getConstructorName = obj => {\n var _a, _b, _c\n try {\n const constructorName =\n null === (_a = null == obj ? void 0 : obj.constructor) || void 0 === _a\n ? void 0\n : _a.name\n if (constructorName) {\n return constructorName\n }\n } catch (e) {}\n try {\n const zoneJsConstructorName =\n null ===\n (_c =\n null ===\n (_b =\n null == obj ? void 0 : obj.__zone_symbol__originalInstance) ||\n void 0 === _b\n ? void 0\n : _b.constructor) || void 0 === _c\n ? void 0\n : _c.name\n if (zoneJsConstructorName) {\n return zoneJsConstructorName\n }\n } catch (e) {}\n return ''\n }\n const EMPTY_ARRAY = []\n const randomId = () =>\n Math.round(Math.random() * Number.MAX_SAFE_INTEGER).toString(36)\n const SCRIPT_TYPE = 'text/partytown'\n const defineProperty = (obj, memberName, descriptor) =>\n Object.defineProperty(obj, memberName, {\n ...descriptor,\n configurable: true,\n })\n const defineConstructorName = (Cstr, value) =>\n defineProperty(Cstr, 'name', {\n value: value,\n })\n const definePrototypeProperty = (Cstr, memberName, descriptor) =>\n defineProperty(Cstr.prototype, memberName, descriptor)\n const definePrototypePropertyDescriptor = (Cstr, propertyDescriptorMap) =>\n Object.defineProperties(Cstr.prototype, propertyDescriptorMap)\n const definePrototypeValue = (Cstr, memberName, value) =>\n definePrototypeProperty(Cstr, memberName, {\n value: value,\n writable: true,\n })\n const hasInstanceStateValue = (instance, stateKey) =>\n stateKey in instance[InstanceStateKey]\n const getInstanceStateValue = (instance, stateKey) =>\n instance[InstanceStateKey][stateKey]\n const setInstanceStateValue = (instance, stateKey, stateValue) =>\n (instance[InstanceStateKey][stateKey] = stateValue)\n const setWorkerRef = (ref, refId) => {\n if (!(refId = webWorkerRefIdsByRef.get(ref))) {\n webWorkerRefIdsByRef.set(ref, (refId = randomId()))\n webWorkerRefsByRefId[refId] = ref\n }\n return refId\n }\n const getOrCreateNodeInstance = (\n winId,\n instanceId,\n nodeName,\n namespace,\n instance\n ) => {\n instance = webWorkerInstances.get(instanceId)\n if (!instance && nodeName && environments[winId]) {\n instance = environments[winId].$createNode$(\n nodeName,\n instanceId,\n namespace\n )\n webWorkerInstances.set(instanceId, instance)\n }\n return instance\n }\n const definePrototypeNodeType = (Cstr, nodeType) =>\n definePrototypeValue(Cstr, 'nodeType', nodeType)\n const cachedTreeProps = (Cstr, treeProps) =>\n treeProps.map(propName =>\n definePrototypeProperty(Cstr, propName, {\n get() {\n let cacheKey = getInstanceCacheKey(this, propName)\n let result = cachedStructure.get(cacheKey)\n if (!result) {\n result = getter(this, [propName])\n cachedStructure.set(cacheKey, result)\n }\n return result\n },\n })\n )\n const getInstanceCacheKey = (instance, memberName, args) =>\n [\n instance[WinIdKey],\n instance[InstanceIdKey],\n memberName,\n ...(args || EMPTY_ARRAY).map(arg =>\n String(arg && arg[WinIdKey] ? arg[InstanceIdKey] : arg)\n ),\n ].join('.')\n const cachedProps = (Cstr, propNames) =>\n commaSplit(propNames).map(propName =>\n definePrototypeProperty(Cstr, propName, {\n get() {\n hasInstanceStateValue(this, propName) ||\n setInstanceStateValue(this, propName, getter(this, [propName]))\n return getInstanceStateValue(this, propName)\n },\n set(val) {\n getInstanceStateValue(this, propName) !== val &&\n setter(this, [propName], val)\n setInstanceStateValue(this, propName, val)\n },\n })\n )\n const cachedDimensionProps = Cstr =>\n getterDimensionPropNames.map(propName =>\n definePrototypeProperty(Cstr, propName, {\n get() {\n const dimension = cachedDimensions.get(\n getInstanceCacheKey(this, propName)\n )\n if ('number' == typeof dimension) {\n return dimension\n }\n const groupedDimensions = getter(\n this,\n [propName],\n getterDimensionPropNames\n )\n if (groupedDimensions && 'object' == typeof groupedDimensions) {\n Object.entries(\n groupedDimensions\n ).map(([dimensionPropName, value]) =>\n cachedDimensions.set(\n getInstanceCacheKey(this, dimensionPropName),\n value\n )\n )\n return groupedDimensions[propName]\n }\n return groupedDimensions\n },\n })\n )\n const cachedDimensionMethods = (Cstr, dimensionMethodNames) =>\n dimensionMethodNames.map(methodName => {\n Cstr.prototype[methodName] = function (...args) {\n let cacheKey = getInstanceCacheKey(this, methodName, args)\n let dimensions = cachedDimensions.get(cacheKey)\n if (!dimensions) {\n dimensions = callMethod(this, [methodName], args)\n cachedDimensions.set(cacheKey, dimensions)\n }\n return dimensions\n }\n })\n const serializeForMain = ($winId$, $instanceId$, value, added, type) =>\n void 0 !== value && (type = typeof value)\n ? 'string' === type ||\n 'boolean' === type ||\n 'number' === type ||\n null == value\n ? [0, value]\n : 'function' === type\n ? [\n 4,\n {\n $winId$: $winId$,\n $instanceId$: $instanceId$,\n $refId$: setWorkerRef(value),\n },\n ]\n : (added = added || new Set()) && Array.isArray(value)\n ? added.has(value)\n ? [1, []]\n : added.add(value) && [\n 1,\n value.map(v => serializeForMain($winId$, $instanceId$, v, added)),\n ]\n : 'object' === type\n ? value[InstanceIdKey]\n ? [3, [value[WinIdKey], value[InstanceIdKey]]]\n : value instanceof Event\n ? [\n 5,\n serializeObjectForMain(\n $winId$,\n $instanceId$,\n value,\n false,\n added\n ),\n ]\n : supportsTrustedHTML && value instanceof TrustedHTML\n ? [0, value.toString()]\n : value instanceof ArrayBuffer\n ? [8, value]\n : ArrayBuffer.isView(value)\n ? [9, value.buffer, getConstructorName(value)]\n : [\n 2,\n serializeObjectForMain($winId$, $instanceId$, value, true, added),\n ]\n : void 0\n : value\n const supportsTrustedHTML = 'undefined' != typeof TrustedHTML\n const serializeObjectForMain = (\n winId,\n instanceId,\n obj,\n includeFunctions,\n added,\n serializedObj,\n propName,\n propValue\n ) => {\n serializedObj = {}\n if (!added.has(obj)) {\n added.add(obj)\n for (propName in obj) {\n propValue = obj[propName]\n ;(includeFunctions || 'function' != typeof propValue) &&\n (serializedObj[propName] = serializeForMain(\n winId,\n instanceId,\n propValue,\n added\n ))\n }\n }\n return serializedObj\n }\n const serializeInstanceForMain = (instance, value) =>\n instance\n ? serializeForMain(instance[WinIdKey], instance[InstanceIdKey], value)\n : [0, value]\n const deserializeFromMain = (\n winId,\n instanceId,\n applyPath,\n serializedValueTransfer,\n serializedType,\n serializedValue,\n obj,\n key\n ) => {\n if (serializedValueTransfer) {\n serializedType = serializedValueTransfer[0]\n serializedValue = serializedValueTransfer[1]\n if (\n 0 === serializedType ||\n 11 === serializedType ||\n 12 === serializedType\n ) {\n return serializedValue\n }\n if (4 === serializedType) {\n return deserializeRefFromMain(applyPath, serializedValue)\n }\n if (6 === serializedType) {\n return winId && applyPath.length > 0\n ? (...args) =>\n callMethod(environments[winId].$window$, applyPath, args, 1)\n : noop\n }\n if (3 === serializedType) {\n return getOrCreateSerializedInstance(serializedValue)\n }\n if (7 === serializedType) {\n return new NodeList(serializedValue.map(getOrCreateSerializedInstance))\n }\n if (10 === serializedType) {\n return new Attr(serializedValue)\n }\n if (1 === serializedType) {\n return serializedValue.map(v =>\n deserializeFromMain(winId, instanceId, applyPath, v)\n )\n }\n if (14 === serializedType) {\n return new CustomError(serializedValue)\n }\n obj = {}\n for (key in serializedValue) {\n obj[key] = deserializeFromMain(\n winId,\n instanceId,\n [...applyPath, key],\n serializedValue[key]\n )\n }\n if (13 === serializedType) {\n return new environments[winId].$window$.CSSStyleDeclaration(\n winId,\n instanceId,\n applyPath,\n obj\n )\n }\n if (5 === serializedType) {\n if ('message' === obj.type && obj.origin) {\n let postMessageKey = JSON.stringify(obj.data)\n let postMessageData = postMessages.find(\n pm => pm.$data$ === postMessageKey\n )\n let env\n if (postMessageData) {\n env = environments[postMessageData.$winId$]\n if (env) {\n obj.source = env.$window$\n obj.origin = env.$location$.origin\n }\n }\n }\n return new Proxy(new Event(obj.type, obj), {\n get: (target, propName) =>\n propName in obj\n ? obj[propName]\n : 'function' == typeof target[String(propName)]\n ? noop\n : target[String(propName)],\n })\n }\n if (2 === serializedType) {\n return obj\n }\n }\n }\n const getOrCreateSerializedInstance = ([winId, instanceId, nodeName]) =>\n instanceId === winId && environments[winId]\n ? environments[winId].$window$\n : getOrCreateNodeInstance(winId, instanceId, nodeName)\n const deserializeRefFromMain = (\n applyPath,\n {\n $winId$: $winId$,\n $instanceId$: $instanceId$,\n $nodeName$: $nodeName$,\n $refId$: $refId$,\n }\n ) => {\n webWorkerRefsByRefId[$refId$] ||\n webWorkerRefIdsByRef.set(\n (webWorkerRefsByRefId[$refId$] = function (...args) {\n const instance = getOrCreateNodeInstance(\n $winId$,\n $instanceId$,\n $nodeName$\n )\n return callMethod(instance, applyPath, args)\n }),\n $refId$\n )\n return webWorkerRefsByRefId[$refId$]\n }\n class CustomError extends Error {\n constructor(errorObject) {\n super(errorObject.message)\n this.name = errorObject.name\n this.message = errorObject.message\n this.stack = errorObject.stack\n }\n }\n class NodeList {\n constructor(nodes) {\n ;(this._ = nodes).map((node, index) => (this[index] = node))\n }\n entries() {\n return this._.entries()\n }\n forEach(cb, thisArg) {\n this._.map(cb, thisArg)\n }\n item(index) {\n return this[index]\n }\n keys() {\n return this._.keys()\n }\n get length() {\n return len(this._)\n }\n values() {\n return this._.values()\n }\n [Symbol.iterator]() {\n return this._[Symbol.iterator]()\n }\n }\n const Attr = class {\n constructor(serializedAttr) {\n this.name = serializedAttr[0]\n this.value = serializedAttr[1]\n }\n get nodeName() {\n return this.name\n }\n get nodeType() {\n return 2\n }\n }\n const warnCrossOrgin = (apiType, apiName, env) =>\n console.warn(\n `Partytown unable to ${apiType} cross-origin ${apiName}: ` +\n env.$location$\n )\n const logWorker = (msg, winId) => {\n try {\n const config = webWorkerCtx.$config$\n if (config.logStackTraces) {\n const frames = new Error().stack.split('\\n')\n const i = frames.findIndex(f => f.includes('logWorker'))\n msg += '\\n' + frames.slice(i + 1).join('\\n')\n }\n let prefix\n let color\n if (winId) {\n prefix = `Worker (${normalizedWinId(winId)}) 🎉`\n color = winColor(winId)\n } else {\n prefix = self.name\n color = '#9844bf'\n }\n if (webWorkerCtx.lastLog !== msg) {\n webWorkerCtx.lastLog = msg\n console.debug.apply(console, [\n `%c${prefix}`,\n `background: ${color}; color: white; padding: 2px 3px; border-radius: 2px; font-size: 0.8em;`,\n msg,\n ])\n }\n } catch (e) {}\n }\n const winIds = []\n const normalizedWinId = winId => {\n winIds.includes(winId) || winIds.push(winId)\n return winIds.indexOf(winId) + 1\n }\n const winColor = winId => {\n const colors = ['#00309e', '#ea3655', '#eea727']\n const index = normalizedWinId(winId) - 1\n return colors[index] || colors[colors.length - 1]\n }\n const getTargetProp = (target, applyPath) => {\n let n = ''\n if (target) {\n const cstrName = getConstructorName(target)\n if ('Window' === cstrName) {\n n = ''\n } else if ('string' == typeof target[InstanceDataKey]) {\n let nodeName = target[InstanceDataKey]\n n =\n '#text' === nodeName\n ? 'textNode.'\n : '#comment' === nodeName\n ? 'commentNode.'\n : '#document' === nodeName\n ? 'document.'\n : 'html' === nodeName\n ? 'doctype.'\n : nodeName.toLowerCase() + '.'\n } else {\n n =\n 'nodeType' in target && 2 === target.nodeType\n ? 'attributes.'\n : 'CanvasRenderingContext2D' === cstrName\n ? 'context2D.'\n : 'CanvasRenderingContextWebGL' === cstrName\n ? 'contextWebGL.'\n : 'CSSStyleDeclaration' === cstrName\n ? 'style.'\n : 'MutationObserver' === cstrName\n ? 'mutationObserver.'\n : 'NamedNodeMap' === cstrName\n ? 'namedNodeMap.'\n : 'ResizeObserver' === cstrName\n ? 'resizeObserver.'\n : cstrName.substring(0, 1).toLowerCase() +\n cstrName.substring(1) +\n '.'\n }\n target[ApplyPathKey] &&\n target[ApplyPathKey].length &&\n (n += [...target[ApplyPathKey]].join('.') + '.')\n }\n if (applyPath.length > 1) {\n const first = applyPath.slice(0, applyPath.length - 1)\n const last = applyPath[applyPath.length - 1]\n if (!isNaN(last)) {\n return n + `${first.join('.')}[${last}]`\n }\n }\n return n + applyPath.join('.')\n }\n const getLogValue = (applyPath, v) => {\n const type = typeof v\n if (void 0 === v) {\n return 'undefined'\n }\n if ('boolean' === type || 'number' === type || null == v) {\n return JSON.stringify(v)\n }\n if ('string' === type) {\n return applyPath.includes('cookie')\n ? JSON.stringify(v.slice(0, 10) + '...')\n : JSON.stringify(v.length > 50 ? v.slice(0, 40) + '...' : v)\n }\n if (Array.isArray(v)) {\n return `[${v.map(getLogValue).join(', ')}]`\n }\n if ('object' === type) {\n const instanceId = v[InstanceIdKey]\n const cstrName = getConstructorName(v)\n if ('string' == typeof instanceId) {\n if ('Window' === cstrName) {\n return 'window'\n }\n if ('string' == typeof v[InstanceDataKey]) {\n if (1 === v.nodeType) {\n return `<${v[InstanceDataKey].toLowerCase()}>`\n }\n if (10 === v.nodeType) {\n return `<!DOCTYPE ${v[InstanceDataKey]}>`\n }\n if (v.nodeType <= 11) {\n return v[InstanceDataKey]\n }\n }\n return '¯\\\\_(ツ)_/¯ instance obj'\n }\n return v[Symbol.iterator]\n ? `[${Array.from(v)\n .map(i => getLogValue(applyPath, i))\n .join(', ')}]`\n : 'value' in v\n ? 'string' == typeof v.value\n ? `\"${v.value}\"`\n : objToString(v.value)\n : objToString(v)\n }\n return (v => 'object' == typeof v && v && v.then)(v)\n ? 'Promise'\n : 'function' === type\n ? `ƒ() ${v.name || ''}`.trim()\n : `¯\\\\_(ツ)_/¯ ${String(v)}`.trim()\n }\n const objToString = obj => {\n const s = []\n for (let key in obj) {\n const value = obj[key]\n const type = typeof value\n 'string' === type\n ? s.push(`${key}: \"${value}\"`)\n : 'function' === type\n ? s.push(`${key}: ƒ`)\n : Array.isArray(type)\n ? s.push(`${key}: [..]`)\n : 'object' === type && value\n ? s.push(`${key}: {..}`)\n : s.push(`${key}: ${String(value)}`)\n }\n let str = s.join(', ')\n str.length > 200 && (str = str.substring(0, 200) + '..')\n return `{ ${str} }`\n }\n const logDimensionCacheClearStyle = (target, propName) => {\n ;(webWorkerCtx.$config$.logGetters || webWorkerCtx.$config$.logSetters) &&\n logWorker(\n `Dimension cache cleared from style.${propName} setter`,\n target[WinIdKey]\n )\n }\n const logDimensionCacheClearMethod = (target, methodName) => {\n ;(webWorkerCtx.$config$.logGetters || webWorkerCtx.$config$.logCalls) &&\n logWorker(\n `Dimension cache cleared from method call ${methodName}()`,\n target[WinIdKey]\n )\n }\n const taskQueue = []\n const queue = (\n instance,\n $applyPath$,\n callType,\n $assignInstanceId$,\n $groupedGetters$,\n buffer\n ) => {\n if (instance[ApplyPathKey]) {\n taskQueue.push({\n $winId$: instance[WinIdKey],\n $instanceId$: instance[InstanceIdKey],\n $applyPath$: [...instance[ApplyPathKey], ...$applyPath$],\n $assignInstanceId$: $assignInstanceId$,\n $groupedGetters$: $groupedGetters$,\n })\n taskQueue[len(taskQueue) - 1].$debug$ = ((\n target,\n applyPath,\n callType\n ) => {\n let m = getTargetProp(target, applyPath)\n 1 === callType\n ? (m += ' (blocking)')\n : 2 === callType\n ? (m += ' (non-blocking)')\n : 3 === callType && (m += ' (non-blocking, no-side-effect)')\n return m.trim()\n })(instance, $applyPath$, callType)\n buffer &&\n 3 !== callType &&\n console.error('buffer must be sent NonBlockingNoSideEffect')\n if (3 === callType) {\n webWorkerCtx.$postMessage$(\n [\n 12,\n {\n $msgId$: randomId(),\n $tasks$: [...taskQueue],\n },\n ],\n buffer\n ? [buffer instanceof ArrayBuffer ? buffer : buffer.buffer]\n : void 0\n )\n taskQueue.length = 0\n } else if (1 === callType) {\n return sendToMain(true)\n }\n webWorkerCtx.$asyncMsgTimer$ = setTimeout(sendToMain, 20)\n }\n }\n const sendToMain = isBlocking => {\n clearTimeout(webWorkerCtx.$asyncMsgTimer$)\n if (len(taskQueue)) {\n webWorkerCtx.$config$.logMainAccess &&\n logWorker(`Main access, tasks sent: ${taskQueue.length}`)\n const endTask = taskQueue[len(taskQueue) - 1]\n const accessReq = {\n $msgId$: randomId(),\n $tasks$: [...taskQueue],\n }\n taskQueue.length = 0\n if (isBlocking) {\n const accessRsp = ((webWorkerCtx, accessReq) => {\n const xhr = new XMLHttpRequest()\n xhr.open('POST', partytownLibUrl('proxytown'), false)\n xhr.send(JSON.stringify(accessReq))\n return JSON.parse(xhr.responseText)\n })(0, accessReq)\n const isPromise = accessRsp.$isPromise$\n const rtnValue = deserializeFromMain(\n endTask.$winId$,\n endTask.$instanceId$,\n endTask.$applyPath$,\n accessRsp.$rtnValue$\n )\n if (accessRsp.$error$) {\n if (isPromise) {\n return Promise.reject(accessRsp.$error$)\n }\n throw new Error(accessRsp.$error$)\n }\n return isPromise ? Promise.resolve(rtnValue) : rtnValue\n }\n webWorkerCtx.$postMessage$([12, accessReq])\n }\n }\n const getter = (instance, applyPath, groupedGetters, rtnValue) => {\n if (webWorkerCtx.$config$.get) {\n rtnValue = webWorkerCtx.$config$.get(\n createHookOptions(instance, applyPath)\n )\n if (rtnValue !== HookContinue) {\n return rtnValue\n }\n }\n rtnValue = queue(instance, applyPath, 1, void 0, groupedGetters)\n ;((\n target,\n applyPath,\n rtnValue,\n restrictedToWorker = false,\n groupedGetters = false\n ) => {\n if (webWorkerCtx.$config$.logGetters) {\n try {\n const msg = `Get ${getTargetProp(\n target,\n applyPath\n )}, returned: ${getLogValue(applyPath, rtnValue)}${\n restrictedToWorker ? ' (restricted to worker)' : ''\n }${groupedGetters ? ' (grouped getter)' : ''}`\n msg.includes('Symbol(') || logWorker(msg, target[WinIdKey])\n } catch (e) {}\n }\n })(instance, applyPath, rtnValue, false, !!groupedGetters)\n return rtnValue\n }\n const setter = (instance, applyPath, value, hookSetterValue) => {\n if (webWorkerCtx.$config$.set) {\n hookSetterValue = webWorkerCtx.$config$.set({\n value: value,\n prevent: HookPrevent,\n ...createHookOptions(instance, applyPath),\n })\n if (hookSetterValue === HookPrevent) {\n return\n }\n hookSetterValue !== HookContinue && (value = hookSetterValue)\n }\n if (dimensionChangingSetterNames.some(s => applyPath.includes(s))) {\n cachedDimensions.clear()\n ;((target, propName) => {\n ;(webWorkerCtx.$config$.logGetters ||\n webWorkerCtx.$config$.logSetters) &&\n logWorker(\n `Dimension cache cleared from setter \"${propName}\"`,\n target[WinIdKey]\n )\n })(instance, applyPath[applyPath.length - 1])\n }\n applyPath = [...applyPath, serializeInstanceForMain(instance, value), 0]\n ;((target, applyPath, value, restrictedToWorker = false) => {\n if (webWorkerCtx.$config$.logSetters) {\n try {\n applyPath = applyPath.slice(0, applyPath.length - 2)\n logWorker(\n `Set ${getTargetProp(target, applyPath)}, value: ${getLogValue(\n applyPath,\n value\n )}${restrictedToWorker ? ' (restricted to worker)' : ''}`,\n target[WinIdKey]\n )\n } catch (e) {}\n }\n })(instance, applyPath, value)\n queue(instance, applyPath, 2)\n }\n const callMethod = (\n instance,\n applyPath,\n args,\n callType,\n assignInstanceId,\n buffer,\n rtnValue,\n methodName\n ) => {\n if (webWorkerCtx.$config$.apply) {\n rtnValue = webWorkerCtx.$config$.apply({\n args: args,\n ...createHookOptions(instance, applyPath),\n })\n if (rtnValue !== HookContinue) {\n return rtnValue\n }\n }\n methodName = applyPath[len(applyPath) - 1]\n applyPath = [...applyPath, serializeInstanceForMain(instance, args)]\n callType = callType || (nonBlockingMethods.includes(methodName) ? 2 : 1)\n if (\n 'setAttribute' === methodName &&\n hasInstanceStateValue(instance, args[0])\n ) {\n setInstanceStateValue(instance, args[0], args[1])\n } else if (structureChangingMethodNames.includes(methodName)) {\n cachedDimensions.clear()\n cachedStructure.clear()\n ;((target, methodName) => {\n ;(webWorkerCtx.$config$.logGetters || webWorkerCtx.$config$.logCalls) &&\n logWorker(\n `Dimension and DOM structure cache cleared from method call ${methodName}()`,\n target[WinIdKey]\n )\n })(instance, methodName)\n } else if (dimensionChangingMethodNames.includes(methodName)) {\n callType = 2\n cachedDimensions.clear()\n logDimensionCacheClearMethod(instance, methodName)\n }\n rtnValue = queue(\n instance,\n applyPath,\n callType,\n assignInstanceId,\n void 0,\n buffer\n )\n ;((target, applyPath, args, rtnValue) => {\n if (webWorkerCtx.$config$.logCalls) {\n try {\n applyPath = applyPath.slice(0, applyPath.length - 1)\n logWorker(\n `Call ${getTargetProp(target, applyPath)}(${args\n .map(v => getLogValue(applyPath, v))\n .join(', ')}), returned: ${getLogValue(applyPath, rtnValue)}`,\n target[WinIdKey]\n )\n } catch (e) {}\n }\n })(instance, applyPath, args, rtnValue)\n return rtnValue\n }\n const constructGlobal = (instance, cstrName, args) => {\n ;((target, cstrName, args) => {\n if (webWorkerCtx.$config$.logCalls) {\n try {\n logWorker(\n `Construct new ${cstrName}(${args\n .map(v => getLogValue([], v))\n .join(', ')})`,\n target[WinIdKey]\n )\n } catch (e) {}\n }\n })(instance, cstrName, args)\n queue(instance, [1, cstrName, serializeInstanceForMain(instance, args)], 1)\n }\n const createHookOptions = (instance, applyPath) => ({\n name: applyPath.join('.'),\n continue: HookContinue,\n nodeName: instance[InstanceDataKey],\n constructor: getConstructorName(instance),\n instance: instance,\n window: environments[instance[WinIdKey]].$window$,\n })\n const addStorageApi = (win, storageName, storages, isSameOrigin, env) => {\n let getItems = items => {\n items = storages.get(win.origin)\n items || storages.set(win.origin, (items = []))\n return items\n }\n let getIndexByKey = key => getItems().findIndex(i => i[STORAGE_KEY] === key)\n let index\n let item\n let storage = {\n getItem(key) {\n index = getIndexByKey(key)\n return index > -1 ? getItems()[index][STORAGE_VALUE] : null\n },\n setItem(key, value) {\n index = getIndexByKey(key)\n index > -1\n ? (getItems()[index][STORAGE_VALUE] = value)\n : getItems().push([key, value])\n isSameOrigin\n ? callMethod(win, [storageName, 'setItem'], [key, value], 2)\n : warnCrossOrgin('set', storageName, env)\n },\n removeItem(key) {\n index = getIndexByKey(key)\n index > -1 && getItems().splice(index, 1)\n isSameOrigin\n ? callMethod(win, [storageName, 'removeItem'], [key], 2)\n : warnCrossOrgin('remove', storageName, env)\n },\n key(index) {\n item = getItems()[index]\n return item ? item[STORAGE_KEY] : null\n },\n clear() {\n getItems().length = 0\n isSameOrigin\n ? callMethod(win, [storageName, 'clear'], EMPTY_ARRAY, 2)\n : warnCrossOrgin('clear', storageName, env)\n },\n get length() {\n return getItems().length\n },\n }\n win[storageName] = new Proxy(storage, {\n get: (target, key) =>\n Reflect.has(target, key)\n ? Reflect.get(target, key)\n : target.getItem(key),\n set(target, key, value) {\n target.setItem(key, value)\n return true\n },\n has: (target, key) =>\n !!Reflect.has(target, key) ||\n ('string' == typeof key && null !== target.getItem(key)),\n deleteProperty(target, key) {\n target.removeItem(key)\n return true\n },\n })\n }\n const STORAGE_KEY = 0\n const STORAGE_VALUE = 1\n const createCSSStyleDeclarationCstr = (win, WorkerBase, cstrName) => {\n win[cstrName] = defineConstructorName(\n class extends WorkerBase {\n constructor(winId, instanceId, applyPath, styles) {\n super(winId, instanceId, applyPath, styles || {})\n return new Proxy(this, {\n get(target, propName) {\n if (target[propName]) {\n return target[propName]\n }\n target[propName] ||\n 'string' != typeof propName ||\n target[InstanceDataKey][propName] ||\n (target[InstanceDataKey][propName] = getter(target, [propName]))\n return target[InstanceDataKey][propName]\n },\n set(target, propName, propValue) {\n target[InstanceDataKey][propName] = propValue\n setter(target, [propName], propValue)\n logDimensionCacheClearStyle(target, propName)\n cachedDimensions.clear()\n return true\n },\n })\n }\n setProperty(...args) {\n this[InstanceDataKey][args[0]] = args[1]\n callMethod(this, ['setProperty'], args, 2)\n logDimensionCacheClearStyle(this, args[0])\n cachedDimensions.clear()\n }\n getPropertyValue(propName) {\n return this[propName]\n }\n removeProperty(propName) {\n let value = this[InstanceDataKey][propName]\n callMethod(this, ['removeProperty'], [propName], 2)\n logDimensionCacheClearStyle(this, propName)\n cachedDimensions.clear()\n this[InstanceDataKey][propName] = void 0\n return value\n }\n },\n cstrName\n )\n }\n const createCSSStyleSheetConstructor = (win, cssStyleSheetCstrName) => {\n win[cssStyleSheetCstrName] = defineConstructorName(\n class {\n constructor(ownerNode) {\n this.ownerNode = ownerNode\n }\n get cssRules() {\n const ownerNode = this.ownerNode\n return new Proxy(\n {},\n {\n get(target, propKey) {\n const propName = String(propKey)\n return 'item' === propName\n ? index => getCssRule(ownerNode, index)\n : 'length' === propName\n ? getCssRules(ownerNode).length\n : isNaN(propName)\n ? target[propKey]\n : getCssRule(ownerNode, propName)\n },\n }\n )\n }\n insertRule(ruleText, index) {\n const cssRules = getCssRules(this.ownerNode)\n index = void 0 === index ? 0 : index\n if (index >= 0 && index <= cssRules.length) {\n callMethod(\n this.ownerNode,\n ['sheet', 'insertRule'],\n [ruleText, index],\n 2\n )\n cssRules.splice(index, 0, 0)\n }\n logDimensionCacheClearMethod(this.ownerNode, 'insertRule')\n cachedDimensions.clear()\n return index\n }\n deleteRule(index) {\n callMethod(this.ownerNode, ['sheet', 'deleteRule'], [index], 2)\n getCssRules(this.ownerNode).splice(index, 1)\n logDimensionCacheClearMethod(this.ownerNode, 'deleteRule')\n cachedDimensions.clear()\n }\n get type() {\n return 'text/css'\n }\n },\n cssStyleSheetCstrName\n )\n const HTMLStyleDescriptorMap = {\n sheet: {\n get() {\n return new win[cssStyleSheetCstrName](this)\n },\n },\n }\n definePrototypePropertyDescriptor(\n win.HTMLStyleElement,\n HTMLStyleDescriptorMap\n )\n }\n const getCssRules = (ownerNode, cssRules) => {\n cssRules = getInstanceStateValue(ownerNode, 2)\n if (!cssRules) {\n cssRules = getter(ownerNode, ['sheet', 'cssRules'])\n setInstanceStateValue(ownerNode, 2, cssRules)\n }\n return cssRules\n }\n const getCssRule = (ownerNode, index, cssRules) => {\n cssRules = getCssRules(ownerNode)\n 0 === cssRules[index] &&\n (cssRules[index] = getter(ownerNode, [\n 'sheet',\n 'cssRules',\n parseInt(index, 10),\n ]))\n return cssRules[index]\n }\n const runScriptContent = (\n env,\n instanceId,\n scriptContent,\n winId,\n errorMsg\n ) => {\n try {\n webWorkerCtx.$config$.logScriptExecution &&\n logWorker(\n `Execute script: ${scriptContent\n .substring(0, 100)\n .split('\\n')\n .map(l => l.trim())\n .join(' ')\n .trim()\n .substring(0, 60)}...`,\n winId\n )\n env.$currentScriptId$ = instanceId\n run(env, scriptContent)\n } catch (contentError) {\n console.error(scriptContent, contentError)\n errorMsg = String(contentError.stack || contentError)\n }\n env.$currentScriptId$ = ''\n return errorMsg\n }\n const run = (env, scriptContent, scriptUrl) => {\n env.$runWindowLoadEvent$ = 1\n scriptContent =\n `with(this){${scriptContent\n .replace(/\\bthis\\b/g, '(thi$(this)?window:this)')\n .replace(/\\/\\/# so/g, '//Xso')}\\n;function thi$(t){return t===this}};${(\n webWorkerCtx.$config$.globalFns || []\n )\n .filter(globalFnName => /[a-zA-Z_$][0-9a-zA-Z_$]*/.test(globalFnName))\n .map(g => `(typeof ${g}=='function'&&(this.${g}=${g}))`)\n .join(';')};` + (scriptUrl ? '\\n//# sourceURL=' + scriptUrl : '')\n env.$isSameOrigin$ ||\n (scriptContent = scriptContent.replace(\n /.postMessage\\(/g,\n `.postMessage('${env.$winId$}',`\n ))\n new Function(scriptContent).call(env.$window$)\n env.$runWindowLoadEvent$ = 0\n }\n const runStateLoadHandlers = (instance, type, handlers) => {\n handlers = getInstanceStateValue(instance, type)\n handlers &&\n setTimeout(() =>\n handlers.map(cb =>\n cb({\n type: type,\n })\n )\n )\n }\n const resolveToUrl = (\n env,\n url,\n type,\n baseLocation,\n resolvedUrl,\n configResolvedUrl\n ) => {\n baseLocation = env.$location$\n while (!baseLocation.host) {\n env = environments[env.$parentWinId$]\n baseLocation = env.$location$\n if (env.$winId$ === env.$parentWinId$) {\n break\n }\n }\n resolvedUrl = new URL(url || '', baseLocation)\n if (type && webWorkerCtx.$config$.resolveUrl) {\n configResolvedUrl = webWorkerCtx.$config$.resolveUrl(\n resolvedUrl,\n baseLocation,\n type\n )\n if (configResolvedUrl) {\n return configResolvedUrl\n }\n }\n return resolvedUrl\n }\n const resolveUrl = (env, url, type) => resolveToUrl(env, url, type) + ''\n const getPartytownScript = () =>\n `<script src=\"${partytownLibUrl('partytown.js?v=0.7.4')}\"><\\/script>`\n const createImageConstructor = env =>\n class HTMLImageElement {\n constructor() {\n this.s = ''\n this.l = []\n this.e = []\n this.style = {}\n }\n get src() {\n return this.s\n }\n set src(src) {\n webWorkerCtx.$config$.logImageRequests &&\n logWorker(\n `Image() request: ${resolveUrl(env, src, 'image')}`,\n env.$winId$\n )\n this.s = src\n fetch(resolveUrl(env, src, 'image'), {\n mode: 'no-cors',\n credentials: 'include',\n keepalive: true,\n }).then(\n rsp => {\n rsp.ok || 0 === rsp.status\n ? this.l.map(cb =>\n cb({\n type: 'load',\n })\n )\n : this.e.map(cb =>\n cb({\n type: 'error',\n })\n )\n },\n () =>\n this.e.forEach(cb =>\n cb({\n type: 'error',\n })\n )\n )\n }\n addEventListener(eventName, cb) {\n 'load' === eventName && this.l.push(cb)\n 'error' === eventName && this.e.push(cb)\n }\n get onload() {\n return this.l[0]\n }\n set onload(cb) {\n this.l = [cb]\n }\n get onerror() {\n return this.e[0]\n }\n set onerror(cb) {\n this.e = [cb]\n }\n }\n const HTMLSrcElementDescriptorMap = {\n addEventListener: {\n value(...args) {\n const eventName = args[0]\n const callbacks = getInstanceStateValue(this, eventName) || []\n callbacks.push(args[1])\n setInstanceStateValue(this, eventName, callbacks)\n },\n },\n async: {\n get: noop,\n set: noop,\n },\n defer: {\n get: noop,\n set: noop,\n },\n onload: {\n get() {\n let callbacks = getInstanceStateValue(this, 'load')\n return (callbacks && callbacks[0]) || null\n },\n set(cb) {\n setInstanceStateValue(this, 'load', cb ? [cb] : null)\n },\n },\n onerror: {\n get() {\n let callbacks = getInstanceStateValue(this, 'error')\n return (callbacks && callbacks[0]) || null\n },\n set(cb) {\n setInstanceStateValue(this, 'error', cb ? [cb] : null)\n },\n },\n getAttribute: {\n value(attrName) {\n return 'src' === attrName\n ? this.src\n : callMethod(this, ['getAttribute'], [attrName])\n },\n },\n setAttribute: {\n value(attrName, attrValue) {\n scriptAttrPropNames.includes(attrName)\n ? (this[attrName] = attrValue)\n : callMethod(this, ['setAttribute'], [attrName, attrValue])\n },\n },\n }\n const scriptAttrPropNames = commaSplit('src,type')\n const patchHTMLScriptElement = (WorkerHTMLScriptElement, env) => {\n const HTMLScriptDescriptorMap = {\n innerHTML: innerHTMLDescriptor,\n innerText: innerHTMLDescriptor,\n src: {\n get() {\n return getInstanceStateValue(this, 4) || ''\n },\n set(url) {\n const orgUrl = resolveUrl(env, url, null)\n const config = webWorkerCtx.$config$\n url = resolveUrl(env, url, 'script')\n setInstanceStateValue(this, 4, url)\n setter(this, ['src'], url)\n orgUrl !== url && setter(this, ['dataset', 'ptsrc'], orgUrl)\n if (this.type && config.loadScriptsOnMainThread) {\n const shouldExecuteScriptViaMainThread = config.loadScriptsOnMainThread.some(\n scriptUrl => scriptUrl === url\n )\n shouldExecuteScriptViaMainThread &&\n setter(this, ['type'], 'text/javascript')\n }\n },\n },\n textContent: innerHTMLDescriptor,\n type: {\n get() {\n return getter(this, ['type'])\n },\n set(type) {\n if (!isScriptJsType(type)) {\n setInstanceStateValue(this, 5, type)\n setter(this, ['type'], type)\n }\n },\n },\n ...HTMLSrcElementDescriptorMap,\n }\n definePrototypePropertyDescriptor(\n WorkerHTMLScriptElement,\n HTMLScriptDescriptorMap\n )\n }\n const innerHTMLDescriptor = {\n get() {\n const type = getter(this, ['type'])\n return isScriptJsType(type)\n ? getInstanceStateValue(this, 3) || ''\n : getter(this, ['innerHTML'])\n },\n set(scriptContent) {\n setInstanceStateValue(this, 3, scriptContent)\n },\n }\n const isScriptJsType = scriptType =>\n !scriptType || 'text/javascript' === scriptType\n const createNodeCstr = (win, env, WorkerBase) => {\n const config = webWorkerCtx.$config$\n const WorkerNode = defineConstructorName(\n class extends WorkerBase {\n appendChild(node) {\n return this.insertBefore(node, null)\n }\n get href() {}\n set href(_) {}\n insertBefore(newNode, referenceNode) {\n var _a, _b\n const winId = (newNode[WinIdKey] = this[WinIdKey])\n const instanceId = newNode[InstanceIdKey]\n const nodeName = newNode[InstanceDataKey]\n const isScript = 'SCRIPT' === nodeName\n const isIFrame = 'IFRAME' === nodeName\n if (isScript) {\n const scriptContent = getInstanceStateValue(newNode, 3)\n const scriptType = getInstanceStateValue(newNode, 5)\n if (scriptContent) {\n if (isScriptJsType(scriptType)) {\n const scriptId = newNode.id\n const loadOnMainThread =\n scriptId &&\n (null ===\n (_b =\n null === (_a = config.loadScriptsOnMainThread) ||\n void 0 === _a\n ? void 0\n : _a.includes) || void 0 === _b\n ? void 0\n : _b.call(_a, scriptId))\n if (loadOnMainThread) {\n setter(newNode, ['type'], 'text/javascript')\n } else {\n const errorMsg = runScriptContent(\n env,\n instanceId,\n scriptContent,\n winId,\n ''\n )\n const datasetType = errorMsg ? 'pterror' : 'ptid'\n const datasetValue = errorMsg || instanceId\n setter(newNode, ['type'], 'text/partytown-x')\n setter(newNode, ['dataset', datasetType], datasetValue)\n }\n }\n setter(newNode, ['innerHTML'], scriptContent)\n }\n }\n callMethod(this, ['insertBefore'], [newNode, referenceNode], 2)\n if (isIFrame) {\n const src = getInstanceStateValue(newNode, 0)\n if (src && src.startsWith('javascript:')) {\n const scriptContent = src.split('javascript:')[1]\n runScriptContent(env, instanceId, scriptContent, winId, '')\n }\n ;((winId, iframe) => {\n let i = 0\n let type\n let handlers\n let callback = () => {\n if (\n environments[winId] &&\n environments[winId].$isInitialized$ &&\n !environments[winId].$isLoading$\n ) {\n type = getInstanceStateValue(iframe, 1) ? 'error' : 'load'\n handlers = getInstanceStateValue(iframe, type)\n handlers &&\n handlers.map(handler =>\n handler({\n type: type,\n })\n )\n } else if (i++ > 2e3) {\n handlers = getInstanceStateValue(iframe, 'error')\n handlers &&\n handlers.map(handler =>\n handler({\n type: 'error',\n })\n )\n } else {\n setTimeout(callback, 9)\n }\n }\n callback()\n })(instanceId, newNode)\n }\n if (isScript) {\n sendToMain(true)\n webWorkerCtx.$postMessage$([7, winId])\n }\n return newNode\n }\n get nodeName() {\n return '#s' === this[InstanceDataKey]\n ? '#document-fragment'\n : this[InstanceDataKey]\n }\n get nodeType() {\n return 3\n }\n get ownerDocument() {\n return env.$document$\n }\n },\n 'Node'\n )\n cachedTreeProps(\n WorkerNode,\n commaSplit(\n 'childNodes,firstChild,isConnected,lastChild,nextSibling,parentElement,parentNode,previousSibling'\n )\n )\n win.Node = WorkerNode\n }\n const htmlMedia = commaSplit('AUDIO,CANVAS,VIDEO')\n const windowMediaConstructors = commaSplit('Audio,MediaSource')\n const patchDocument = (WorkerDocument, env, isDocumentImplementation) => {\n const DocumentDescriptorMap = {\n body: {\n get: () => env.$body$,\n },\n cookie: {\n get() {\n if (env.$isSameOrigin$) {\n return getter(this, ['cookie'])\n }\n warnCrossOrgin('get', 'cookie', env)\n return ''\n },\n set(value) {\n if (env.$isSameOrigin$) {\n setter(this, ['cookie'], value)\n } else {\n warnCrossOrgin('set', 'cookie', env)\n }\n },\n },\n createElement: {\n value(tagName) {\n tagName = tagName.toUpperCase()\n if (!IS_TAG_REG.test(tagName)) {\n throw tagName + ' not valid'\n }\n const isIframe = 'IFRAME' === tagName\n const winId = this[WinIdKey]\n const instanceId = (isIframe ? 'f_' : '') + randomId()\n callMethod(this, ['createElement'], [tagName], 2, instanceId)\n const elm = getOrCreateNodeInstance(winId, instanceId, tagName)\n if (isIframe) {\n const env = createEnvironment(\n {\n $winId$: instanceId,\n $parentWinId$: winId,\n $url$: 'about:blank',\n },\n true\n )\n env.$window$.fetch = fetch\n setter(elm, ['srcdoc'], getPartytownScript())\n } else if ('SCRIPT' === tagName) {\n const scriptType = getInstanceStateValue(elm, 5)\n isScriptJsType(scriptType) &&\n setter(elm, ['type'], 'text/partytown')\n }\n return elm\n },\n },\n createElementNS: {\n value(namespace, tagName) {\n const instanceId = randomId()\n const nsElm = getOrCreateNodeInstance(\n this[WinIdKey],\n instanceId,\n tagName,\n namespace\n )\n callMethod(\n this,\n ['createElementNS'],\n [namespace, tagName],\n 2,\n instanceId\n )\n return nsElm\n },\n },\n createTextNode: {\n value(text) {\n const winId = this[WinIdKey]\n const instanceId = randomId()\n const textNode = getOrCreateNodeInstance(winId, instanceId, '#text')\n callMethod(this, ['createTextNode'], [text], 2, instanceId)\n return textNode\n },\n },\n createEvent: {\n value: type => new Event(type),\n },\n currentScript: {\n get() {\n return env.$currentScriptId$\n ? getOrCreateNodeInstance(\n this[WinIdKey],\n env.$currentScriptId$,\n 'SCRIPT'\n )\n : null\n },\n },\n defaultView: {\n get: () => (isDocumentImplementation ? null : env.$window$),\n },\n documentElement: {\n get: () => env.$documentElement$,\n },\n getElementsByTagName: {\n value(tagName) {\n tagName = tagName.toUpperCase()\n return 'BODY' === tagName\n ? [env.$body$]\n : 'HEAD' === tagName\n ? [env.$head$]\n : callMethod(this, ['getElementsByTagName'], [tagName])\n },\n },\n head: {\n get: () => env.$head$,\n },\n images: {\n get() {\n return getter(this, ['images'])\n },\n },\n implementation: {\n get() {\n return {\n hasFeature: () => true,\n createHTMLDocument: title => {\n const $winId$ = randomId()\n callMethod(\n this,\n ['implementation', 'createHTMLDocument'],\n [title],\n 1,\n {\n $winId$: $winId$,\n }\n )\n const docEnv = createEnvironment(\n {\n $winId$: $winId$,\n $parentWinId$: $winId$,\n $url$: env.$location$ + '',\n $visibilityState$: 'hidden',\n },\n true,\n true\n )\n return docEnv.$document$\n },\n }\n },\n },\n location: {\n get: () => env.$location$,\n set(url) {\n env.$location$.href = url + ''\n },\n },\n nodeType: {\n value: 9,\n },\n parentNode: {\n value: null,\n },\n parentElement: {\n value: null,\n },\n readyState: {\n value: 'complete',\n },\n visibilityState: {\n get: () => env.$visibilityState$ || 'visible',\n },\n }\n definePrototypePropertyDescriptor(WorkerDocument, DocumentDescriptorMap)\n cachedProps(WorkerDocument, 'compatMode,referrer,forms')\n }\n const patchDocumentElementChild = (WokerDocumentElementChild, env) => {\n const DocumentElementChildDescriptorMap = {\n parentElement: {\n get() {\n return this.parentNode\n },\n },\n parentNode: {\n get: () => env.$documentElement$,\n },\n }\n definePrototypePropertyDescriptor(\n WokerDocumentElementChild,\n DocumentElementChildDescriptorMap\n )\n }\n const patchElement = (WorkerElement, WorkerHTMLElement) => {\n const ElementDescriptorMap = {\n localName: {\n get() {\n return this[InstanceDataKey].toLowerCase()\n },\n },\n namespaceURI: {\n get() {\n return this[NamespaceKey] || 'http://www.w3.org/1999/xhtml'\n },\n },\n nodeType: {\n value: 1,\n },\n tagName: {\n get() {\n return this[InstanceDataKey]\n },\n },\n }\n definePrototypePropertyDescriptor(WorkerElement, ElementDescriptorMap)\n cachedTreeProps(WorkerElement, elementStructurePropNames)\n cachedProps(WorkerElement, 'id')\n cachedDimensionProps(WorkerHTMLElement)\n cachedDimensionMethods(\n WorkerHTMLElement,\n commaSplit('getClientRects,getBoundingClientRect')\n )\n }\n const patchHTMLAnchorElement = (WorkerHTMLAnchorElement, env) => {\n const HTMLAnchorDescriptorMap = {}\n commaSplit(\n 'hash,host,hostname,href,origin,pathname,port,protocol,search'\n ).map(anchorProp => {\n HTMLAnchorDescriptorMap[anchorProp] = {\n get() {\n let value = getInstanceStateValue(this, 4)\n let href\n if ('string' != typeof value) {\n href = getter(this, ['href'])\n setInstanceStateValue(this, 4, href)\n value = new URL(href)[anchorProp]\n }\n return resolveToUrl(env, value, null)[anchorProp]\n },\n set(value) {\n let url\n if ('href' === anchorProp) {\n if (\n (url => {\n try {\n new URL(url)\n return true\n } catch (_) {\n return false\n }\n })(value)\n ) {\n url = new URL(value)\n } else {\n const baseHref = env.$location$.href\n url = resolveToUrl(env, baseHref, null)\n url.href = new URL(value + '', url.href)\n }\n } else {\n url = resolveToUrl(env, this.href, null)\n url[anchorProp] = value\n }\n setInstanceStateValue(this, 4, url.href)\n setter(this, ['href'], url.href)\n },\n }\n })\n definePrototypePropertyDescriptor(\n WorkerHTMLAnchorElement,\n HTMLAnchorDescriptorMap\n )\n }\n const patchHTMLIFrameElement = (WorkerHTMLIFrameElement, env) => {\n const HTMLIFrameDescriptorMap = {\n contentDocument: {\n get() {\n return getIframeEnv(this).$document$\n },\n },\n contentWindow: {\n get() {\n return getIframeEnv(this).$window$\n },\n },\n src: {\n get() {\n let src = getInstanceStateValue(this, 0)\n if (src && src.startsWith('javascript:')) {\n return src\n }\n src = getIframeEnv(this).$location$.href\n return src.startsWith('about:') ? '' : src\n },\n set(src) {\n if (src) {\n if (src.startsWith('javascript:')) {\n setInstanceStateValue(this, 0, src)\n } else if (!src.startsWith('about:')) {\n let xhr = new XMLHttpRequest()\n let xhrStatus\n let env = getIframeEnv(this)\n env.$location$.href = src = resolveUrl(env, src, 'iframe')\n env.$isLoading$ = 1\n setInstanceStateValue(this, 1, void 0)\n xhr.open('GET', src, false)\n xhr.send()\n xhrStatus = xhr.status\n if (xhrStatus > 199 && xhrStatus < 300) {\n setter(\n this,\n ['srcdoc'],\n `<base href=\"${src}\">` +\n (function (text) {\n return text.replace(SCRIPT_TAG_REGEXP, (_, attrs) => {\n const parts = []\n let hasType = false\n let match\n while ((match = ATTR_REGEXP.exec(attrs))) {\n let [keyValue] = match\n if (keyValue.startsWith('type=')) {\n hasType = true\n keyValue = keyValue.replace(\n /(application|text)\\/javascript/,\n SCRIPT_TYPE\n )\n }\n parts.push(keyValue)\n }\n hasType || parts.push('type=\"text/partytown\"')\n return `<script ${parts.join(' ')}>`\n })\n })(xhr.responseText) +\n getPartytownScript()\n )\n sendToMain(true)\n webWorkerCtx.$postMessage$([7, env.$winId$])\n } else {\n setInstanceStateValue(this, 1, xhrStatus)\n env.$isLoading$ = 0\n }\n }\n }\n },\n },\n ...HTMLSrcElementDescriptorMap,\n }\n definePrototypePropertyDescriptor(\n WorkerHTMLIFrameElement,\n HTMLIFrameDescriptorMap\n )\n }\n const ATTR_REGEXP_STR = '((?:\\\\w|-)+(?:=(?:(?:\\\\w|-)+|\\'[^\\']*\\'|\"[^\"]*\")?)?)'\n const SCRIPT_TAG_REGEXP = new RegExp(\n `<script\\\\s*((${ATTR_REGEXP_STR}\\\\s*)*)>`,\n 'mg'\n )\n const ATTR_REGEXP = new RegExp(ATTR_REGEXP_STR, 'mg')\n const getIframeEnv = iframe => {\n const $winId$ = iframe[InstanceIdKey]\n environments[$winId$] ||\n createEnvironment(\n {\n $winId$: $winId$,\n $parentWinId$: iframe[WinIdKey],\n $url$: getter(iframe, ['src']) || 'about:blank',\n },\n true\n )\n return environments[$winId$]\n }\n const patchSvgElement = WorkerSVGGraphicsElement => {\n const getMatrix = (elm, methodName) => {\n const { a: a, b: b, c: c, d: d, e: e, f: f } = callMethod(\n elm,\n [methodName],\n EMPTY_ARRAY\n )\n return new DOMMatrixReadOnly([a, b, c, d, e, f])\n }\n const SVGGraphicsElementDescriptorMap = {\n ...WorkerSVGGraphicsElement,\n getCTM: {\n value: function () {\n return getMatrix(this, 'getCTM')\n },\n },\n getScreenCTM: {\n value: function () {\n return getMatrix(this, 'getScreenCTM')\n },\n },\n }\n definePrototypePropertyDescriptor(\n WorkerSVGGraphicsElement,\n SVGGraphicsElementDescriptorMap\n )\n }\n const createNamedNodeMapCstr = (win, WorkerBase) => {\n win.NamedNodeMap = defineConstructorName(\n class NamedNodeMap extends WorkerBase {\n constructor(winId, instanceId, applyPath) {\n super(winId, instanceId, applyPath)\n return new Proxy(this, {\n get(target, propName) {\n const handler = NAMED_NODE_MAP_HANDLERS[propName]\n return handler\n ? handler.bind(target, [propName])\n : getter(target, [propName])\n },\n set(target, propName, propValue) {\n const handler = NAMED_NODE_MAP_HANDLERS[propName]\n if (handler) {\n throw new Error(\n \"Can't set read-only property: \" + String(propName)\n )\n }\n setter(target, [propName], propValue)\n return true\n },\n })\n }\n },\n 'NamedNodeMap'\n )\n }\n function method(applyPath, ...args) {\n return callMethod(this, applyPath, args, 1)\n }\n const NAMED_NODE_MAP_HANDLERS = {\n getNamedItem: method,\n getNamedItemNS: method,\n item: method,\n removeNamedItem: method,\n removeNamedItemNS: method,\n setNamedItem: method,\n setNamedItemNS: method,\n }\n const createWindow = (\n $winId$,\n $parentWinId$,\n url,\n $visibilityState$,\n isIframeWindow,\n isDocumentImplementation\n ) => {\n let cstrInstanceId\n let cstrNodeName\n let cstrNamespace\n const WorkerBase = class {\n constructor(winId, instanceId, applyPath, instanceData, namespace) {\n this[WinIdKey] = winId || $winId$\n this[InstanceIdKey] = instanceId || cstrInstanceId || randomId()\n this[ApplyPathKey] = applyPath || []\n this[InstanceDataKey] = instanceData || cstrNodeName\n this[NamespaceKey] = namespace || cstrNamespace\n this[InstanceStateKey] = {}\n cstrInstanceId = cstrNodeName = cstrNamespace = void 0\n }\n }\n const WorkerLocation = defineConstructorName(\n class extends URL {\n assign() {\n logWorker('location.assign(), noop')\n }\n reload() {\n logWorker('location.reload(), noop')\n }\n replace() {\n logWorker('location.replace(), noop')\n }\n },\n 'Location'\n )\n const $location$ = new WorkerLocation(url)\n const $isSameOrigin$ =\n $location$.origin === webWorkerCtx.$origin$ ||\n 'about:blank' === $location$.origin\n const $isTopWindow$ = $parentWinId$ === $winId$\n const env = {}\n const getChildEnvs = () => {\n let childEnv = []\n let envWinId\n let otherEnv\n for (envWinId in environments) {\n otherEnv = environments[envWinId]\n otherEnv.$parentWinId$ !== $winId$ ||\n otherEnv.$isTopWindow$ ||\n childEnv.push(otherEnv)\n }\n return childEnv\n }\n const WorkerWindow = defineConstructorName(\n class extends WorkerBase {\n constructor() {\n super($winId$, $winId$)\n let win = this\n let value\n let historyState\n let hasInitializedMedia = 0\n let initWindowMedia = () => {\n if (!hasInitializedMedia) {\n ;(() => {\n if (!webWorkerCtx.$initWindowMedia$) {\n self.$bridgeToMedia$ = [\n getter,\n setter,\n callMethod,\n constructGlobal,\n definePrototypePropertyDescriptor,\n randomId,\n WinIdKey,\n InstanceIdKey,\n ApplyPathKey,\n ]\n webWorkerCtx.$importScripts$(\n partytownLibUrl('partytown-media.js?v=0.7.4')\n )\n webWorkerCtx.$initWindowMedia$ = self.$bridgeFromMedia$\n delete self.$bridgeFromMedia$\n }\n return webWorkerCtx.$initWindowMedia$\n })()(\n WorkerBase,\n WorkerEventTargetProxy,\n env,\n win,\n windowMediaConstructors\n )\n hasInitializedMedia = 1\n }\n }\n let nodeCstrs = {}\n let $createNode$ = (nodeName, instanceId, namespace) => {\n htmlMedia.includes(nodeName) && initWindowMedia()\n const NodeCstr = nodeCstrs[nodeName]\n ? nodeCstrs[nodeName]\n : nodeName.includes('-')\n ? nodeCstrs.UNKNOWN\n : nodeCstrs.I\n cstrInstanceId = instanceId\n cstrNodeName = nodeName\n cstrNamespace = namespace\n return new NodeCstr()\n }\n win.Window = WorkerWindow\n win.name = name + `${normalizedWinId($winId$)} (${$winId$})`\n createNodeCstr(win, env, WorkerBase)\n ;(win => {\n win.NodeList = defineConstructorName(NodeList, 'NodeList')\n })(win)\n createNamedNodeMapCstr(win, WorkerBase)\n createCSSStyleDeclarationCstr(win, WorkerBase, 'CSSStyleDeclaration')\n ;((win, WorkerBase, cstrName) => {\n win[cstrName] = defineConstructorName(\n class extends WorkerBase {\n now() {\n return performance.now()\n }\n },\n cstrName\n )\n })(win, WorkerBase, 'Performance')\n ;((win, nodeCstrs) => {\n const registry = new Map()\n win.customElements = {\n define(tagName, Cstr, opts) {\n registry.set(tagName, Cstr)\n nodeCstrs[tagName.toUpperCase()] = Cstr\n const ceData = [Cstr.name, Cstr.observedAttributes]\n callMethod(\n win,\n ['customElements', 'define'],\n [tagName, ceData, opts]\n )\n },\n get: tagName =>\n registry.get(tagName) ||\n callMethod(win, ['customElements', 'get'], [tagName]),\n whenDefined: tagName =>\n registry.has(tagName)\n ? Promise.resolve()\n : callMethod(\n win,\n ['customElements', 'whenDefined'],\n [tagName]\n ),\n upgrade: elm =>\n callMethod(win, ['customElements', 'upgrade'], [elm]),\n }\n })(win, nodeCstrs)\n webWorkerCtx.$interfaces$.map(\n ([cstrName, superCstrName, members, interfaceType, nodeName]) => {\n const SuperCstr = TrapConstructors[cstrName]\n ? WorkerTrapProxy\n : 'EventTarget' === superCstrName\n ? WorkerEventTargetProxy\n : 'Object' === superCstrName\n ? WorkerBase\n : win[superCstrName]\n const Cstr = (win[cstrName] = defineConstructorName(\n 12 === interfaceType\n ? class extends WorkerBase {\n constructor(...args) {\n super()\n constructGlobal(this, cstrName, args)\n }\n }\n : win[cstrName] || class extends SuperCstr {},\n cstrName\n ))\n nodeName && (nodeCstrs[nodeName] = Cstr)\n members.map(([memberName, memberType, staticValue]) => {\n memberName in Cstr.prototype ||\n memberName in SuperCstr.prototype ||\n ('string' == typeof memberType\n ? definePrototypeProperty(Cstr, memberName, {\n get() {\n if (!hasInstanceStateValue(this, memberName)) {\n const instanceId = this[InstanceIdKey]\n const applyPath = [\n ...this[ApplyPathKey],\n memberName,\n ]\n const PropCstr = win[memberType]\n PropCstr &&\n setInstanceStateValue(\n this,\n memberName,\n new PropCstr($winId$, instanceId, applyPath)\n )\n }\n return getInstanceStateValue(this, memberName)\n },\n set(value) {\n setInstanceStateValue(this, memberName, value)\n },\n })\n : 5 === memberType\n ? definePrototypeValue(\n Cstr,\n memberName,\n function (...args) {\n return callMethod(this, [memberName], args)\n }\n )\n : memberType > 0 &&\n (void 0 !== staticValue\n ? definePrototypeValue(Cstr, memberName, staticValue)\n : definePrototypeProperty(Cstr, memberName, {\n get() {\n return getter(this, [memberName])\n },\n set(value) {\n return setter(this, [memberName], value)\n },\n })))\n })\n }\n )\n commaSplit(\n 'atob,btoa,crypto,indexedDB,setTimeout,setInterval,clearTimeout,clearInterval'\n ).map(globalName => {\n delete WorkerWindow.prototype[globalName]\n if (!(globalName in win)) {\n value = self[globalName]\n null != value &&\n (win[globalName] =\n 'function' != typeof value ||\n value.toString().startsWith('class')\n ? value\n : value.bind(self))\n }\n })\n Object.getOwnPropertyNames(self).map(globalName => {\n globalName in win || (win[globalName] = self[globalName])\n })\n windowMediaConstructors.map(cstrName =>\n defineProperty(win, cstrName, {\n get() {\n initWindowMedia()\n return win[cstrName]\n },\n })\n )\n 'trustedTypes' in self && (win.trustedTypes = self.trustedTypes)\n patchElement(win.Element, win.HTMLElement)\n patchDocument(win.Document, env, isDocumentImplementation)\n ;(WorkerDocumentFragment => {\n definePrototypeNodeType(WorkerDocumentFragment, 11)\n cachedTreeProps(WorkerDocumentFragment, elementStructurePropNames)\n })(win.DocumentFragment)\n patchHTMLAnchorElement(win.HTMLAnchorElement, env)\n ;(WorkerHTMLFormElement => {\n definePrototypePropertyDescriptor(WorkerHTMLFormElement, {})\n cachedProps(WorkerHTMLFormElement, 'elements')\n })(win.HTMLFormElement)\n patchHTMLIFrameElement(win.HTMLIFrameElement)\n patchHTMLScriptElement(win.HTMLScriptElement, env)\n patchSvgElement(win.SVGGraphicsElement)\n patchDocumentElementChild(win.HTMLHeadElement, env)\n patchDocumentElementChild(win.HTMLBodyElement, env)\n ;((WorkerHTMLHtmlElement, env) => {\n const DocumentElementDescriptorMap = {\n parentElement: {\n value: null,\n },\n parentNode: {\n get: () => env.$document$,\n },\n }\n definePrototypePropertyDescriptor(\n WorkerHTMLHtmlElement,\n DocumentElementDescriptorMap\n )\n })(win.HTMLHtmlElement, env)\n createCSSStyleSheetConstructor(win, 'CSSStyleSheet')\n definePrototypeNodeType(win.Comment, 8)\n definePrototypeNodeType(win.DocumentType, 10)\n Object.assign(env, {\n $winId$: $winId$,\n $parentWinId$: $parentWinId$,\n $window$: new Proxy(win, {\n get: (win, propName) => {\n var _a\n if ('string' != typeof propName || isNaN(propName)) {\n return (\n null === (_a = webWorkerCtx.$config$.mainWindowAccessors) ||\n void 0 === _a\n ? void 0\n : _a.includes(propName)\n )\n ? getter(this, [propName])\n : win[propName]\n }\n {\n let frame = getChildEnvs()[propName]\n return frame ? frame.$window$ : void 0\n }\n },\n has: () => true,\n }),\n $document$: $createNode$('#document', $winId$ + '.d'),\n $documentElement$: $createNode$('HTML', $winId$ + '.e'),\n $head$: $createNode$('HEAD', $winId$ + '.h'),\n $body$: $createNode$('BODY', $winId$ + '.b'),\n $location$: $location$,\n $visibilityState$: $visibilityState$,\n $isSameOrigin$: $isSameOrigin$,\n $isTopWindow$: $isTopWindow$,\n $createNode$: $createNode$,\n })\n win.requestAnimationFrame = cb =>\n setTimeout(() => cb(performance.now()), 9)\n win.cancelAnimationFrame = id => clearTimeout(id)\n win.requestIdleCallback = (cb, start) => {\n start = Date.now()\n return setTimeout(\n () =>\n cb({\n didTimeout: false,\n timeRemaining: () => Math.max(0, 50 - (Date.now() - start)),\n }),\n 1\n )\n }\n win.cancelIdleCallback = id => clearTimeout(id)\n addStorageApi(\n win,\n 'localStorage',\n webWorkerlocalStorage,\n $isSameOrigin$,\n env\n )\n addStorageApi(\n win,\n 'sessionStorage',\n webWorkerSessionStorage,\n $isSameOrigin$,\n env\n )\n $isSameOrigin$ || (win.indexeddb = void 0)\n if (isIframeWindow) {\n historyState = {}\n win.history = {\n pushState(stateObj) {\n historyState = stateObj\n },\n replaceState(stateObj) {\n historyState = stateObj\n },\n get state() {\n return historyState\n },\n length: 0,\n }\n win.indexeddb = void 0\n } else {\n const originalPushState = win.history.pushState.bind(win.history)\n const originalReplaceState = win.history.replaceState.bind(\n win.history\n )\n win.history.pushState = (stateObj, _, newUrl) => {\n false !== env.$propagateHistoryChange$ &&\n originalPushState(stateObj, _, newUrl)\n }\n win.history.replaceState = (stateObj, _, newUrl) => {\n false !== env.$propagateHistoryChange$ &&\n originalReplaceState(stateObj, _, newUrl)\n }\n }\n win.Worker = void 0\n }\n addEventListener(...args) {\n 'load' === args[0]\n ? env.$runWindowLoadEvent$ &&\n setTimeout(() =>\n args[1]({\n type: 'load',\n })\n )\n : callMethod(this, ['addEventListener'], args, 2)\n }\n get body() {\n return env.$body$\n }\n get document() {\n return env.$document$\n }\n get documentElement() {\n return env.$documentElement$\n }\n fetch(input, init) {\n input =\n 'string' == typeof input || input instanceof URL\n ? String(input)\n : input.url\n return fetch(resolveUrl(env, input, 'fetch'), init)\n }\n get frames() {\n return env.$window$\n }\n get frameElement() {\n return $isTopWindow$\n ? null\n : getOrCreateNodeInstance($parentWinId$, $winId$, 'IFRAME')\n }\n get globalThis() {\n return env.$window$\n }\n get head() {\n return env.$head$\n }\n get length() {\n return getChildEnvs().length\n }\n get location() {\n return $location$\n }\n set location(loc) {\n $location$.href = loc + ''\n }\n get Image() {\n return createImageConstructor(env)\n }\n get navigator() {\n return (env => {\n let key\n let nav = {\n sendBeacon: (url, body) => {\n if (webWorkerCtx.$config$.logSendBeaconRequests) {\n try {\n logWorker(\n `sendBeacon: ${resolveUrl(env, url, null)}${\n body ? ', data: ' + JSON.stringify(body) : ''\n }`\n )\n } catch (e) {\n console.error(e)\n }\n }\n try {\n fetch(resolveUrl(env, url, null), {\n method: 'POST',\n body: body,\n mode: 'no-cors',\n keepalive: true,\n })\n return true\n } catch (e) {\n console.error(e)\n return false\n }\n },\n }\n for (key in navigator) {\n nav[key] = navigator[key]\n }\n return nav\n })(env)\n }\n get origin() {\n return $location$.origin\n }\n set origin(_) {}\n get parent() {\n for (let envWinId in environments) {\n if (environments[envWinId].$winId$ === $parentWinId$) {\n return environments[envWinId].$window$\n }\n }\n return env.$window$\n }\n postMessage(...args) {\n if (environments[args[0]]) {\n len(postMessages) > 50 && postMessages.splice(0, 5)\n postMessages.push({\n $winId$: args[0],\n $data$: JSON.stringify(args[1]),\n })\n args = args.slice(1)\n }\n callMethod(this, ['postMessage'], args, 3)\n }\n get self() {\n return env.$window$\n }\n get top() {\n for (let envWinId in environments) {\n if (environments[envWinId].$isTopWindow$) {\n return environments[envWinId].$window$\n }\n }\n return env.$window$\n }\n get window() {\n return env.$window$\n }\n get XMLHttpRequest() {\n const Xhr = XMLHttpRequest\n const str = String(Xhr)\n const ExtendedXhr = defineConstructorName(\n class extends Xhr {\n open(...args) {\n args[1] = resolveUrl(env, args[1], 'xhr')\n super.open(...args)\n }\n set withCredentials(_) {}\n toString() {\n return str\n }\n },\n getConstructorName(Xhr)\n )\n ExtendedXhr.prototype.constructor.toString = () => str\n return ExtendedXhr\n }\n },\n 'Window'\n )\n const WorkerTrapProxy = class extends WorkerBase {\n constructor(winId, instanceId, applyPath, nodeName) {\n super(winId, instanceId, applyPath, nodeName)\n return new Proxy(this, {\n get: (instance, propName) => getter(instance, [propName]),\n set(instance, propName, propValue) {\n setter(instance, [propName], propValue)\n return true\n },\n })\n }\n }\n const WorkerEventTargetProxy = class extends WorkerBase {}\n eventTargetMethods.map(\n methodName =>\n (WorkerEventTargetProxy.prototype[methodName] = function (...args) {\n return callMethod(this, [methodName], args, 2)\n })\n )\n cachedProps(WorkerWindow, 'devicePixelRatio')\n cachedDimensionProps(WorkerWindow)\n cachedDimensionMethods(WorkerWindow, ['getComputedStyle'])\n new WorkerWindow()\n return env\n }\n const TrapConstructors = {\n DOMStringMap: 1,\n NamedNodeMap: 1,\n }\n const createEnvironment = (\n {\n $winId$: $winId$,\n $parentWinId$: $parentWinId$,\n $url$: $url$,\n $visibilityState$: $visibilityState$,\n },\n isIframeWindow,\n isDocumentImplementation\n ) => {\n if (!environments[$winId$]) {\n environments[$winId$] = createWindow(\n $winId$,\n $parentWinId$,\n $url$,\n $visibilityState$,\n isIframeWindow,\n isDocumentImplementation\n )\n {\n const winType = $winId$ === $parentWinId$ ? 'top' : 'iframe'\n logWorker(\n `Created ${winType} window ${normalizedWinId($winId$)} environment`,\n $winId$\n )\n }\n }\n webWorkerCtx.$postMessage$([7, $winId$])\n return environments[$winId$]\n }\n const queuedEvents = []\n const receiveMessageFromSandboxToWorker = ev => {\n const msg = ev.data\n const msgType = msg[0]\n const msgValue = msg[1]\n if (webWorkerCtx.$isInitialized$) {\n if (7 === msgType) {\n ;(async initScript => {\n let winId = initScript.$winId$\n let instanceId = initScript.$instanceId$\n let instance = getOrCreateNodeInstance(winId, instanceId, 'SCRIPT')\n let scriptContent = initScript.$content$\n let scriptSrc = initScript.$url$\n let scriptOrgSrc = initScript.$orgUrl$\n let errorMsg = ''\n let env = environments[winId]\n let rsp\n let javascriptContentTypes = [\n 'text/jscript',\n 'text/javascript',\n 'text/x-javascript',\n 'application/javascript',\n 'application/x-javascript',\n 'text/ecmascript',\n 'text/x-ecmascript',\n 'application/ecmascript',\n ]\n if (scriptSrc) {\n try {\n scriptSrc = resolveToUrl(env, scriptSrc, 'script') + ''\n setInstanceStateValue(instance, 4, scriptSrc)\n webWorkerCtx.$config$.logScriptExecution &&\n logWorker(`Execute script src: ${scriptOrgSrc}`, winId)\n rsp = await fetch(scriptSrc)\n if (rsp.ok) {\n let responseContentType = rsp.headers.get('content-type')\n let shouldExecute = javascriptContentTypes.some(ct => {\n var _a, _b, _c\n return null ===\n (_c =\n null ===\n (_a =\n null == responseContentType\n ? void 0\n : responseContentType.toLowerCase) || void 0 === _a\n ? void 0\n : (_b = _a.call(responseContentType)).includes) ||\n void 0 === _c\n ? void 0\n : _c.call(_b, ct)\n })\n if (shouldExecute) {\n scriptContent = await rsp.text()\n env.$currentScriptId$ = instanceId\n run(env, scriptContent, scriptOrgSrc || scriptSrc)\n }\n runStateLoadHandlers(instance, 'load')\n } else {\n errorMsg = rsp.statusText\n runStateLoadHandlers(instance, 'error')\n }\n } catch (urlError) {\n console.error(urlError)\n errorMsg = String(urlError.stack || urlError)\n runStateLoadHandlers(instance, 'error')\n }\n } else {\n scriptContent &&\n (errorMsg = runScriptContent(\n env,\n instanceId,\n scriptContent,\n winId,\n errorMsg\n ))\n }\n env.$currentScriptId$ = ''\n webWorkerCtx.$postMessage$([6, winId, instanceId, errorMsg])\n })(msgValue)\n } else if (9 === msgType) {\n ;(({\n $winId$: $winId$,\n $instanceId$: $instanceId$,\n $refId$: $refId$,\n $thisArg$: $thisArg$,\n $args$: $args$,\n }) => {\n if (webWorkerRefsByRefId[$refId$]) {\n try {\n webWorkerRefsByRefId[$refId$].apply(\n deserializeFromMain($winId$, $instanceId$, [], $thisArg$),\n deserializeFromMain($winId$, $instanceId$, [], $args$)\n )\n } catch (e) {\n console.error(e)\n }\n }\n })(msgValue)\n } else if (10 === msgType) {\n ;(({ $winId$: $winId$, $forward$: $forward$, $args$: $args$ }) => {\n try {\n let target = environments[$winId$].$window$\n let i = 0\n let l = len($forward$)\n for (; i < l; i++) {\n i + 1 < l\n ? (target = target[$forward$[i]])\n : target[$forward$[i]].apply(\n target,\n deserializeFromMain(null, $winId$, [], $args$)\n )\n }\n } catch (e) {\n console.error(e)\n }\n })(msgValue)\n } else if (5 === msgType) {\n createEnvironment(msgValue)\n } else if (8 === msgType) {\n if (1 !== environments[msgValue].$isInitialized$) {\n const winId = msgValue\n const env = environments[winId]\n const winType = env.$winId$ === env.$parentWinId$ ? 'top' : 'iframe'\n logWorker(\n `Initialized ${winType} window ${normalizedWinId(\n winId\n )} environment 🎉`,\n winId\n )\n }\n environments[msgValue].$isInitialized$ = 1\n environments[msgValue].$isLoading$ = 0\n } else if (14 === msgType) {\n environments[msgValue].$visibilityState$ = msg[2]\n } else if (13 === msgType) {\n const $winId$ = msgValue.$winId$\n const env = environments[$winId$]\n env.$location$.href = msgValue.url\n !(function ($winId$, env, data) {\n const history = env.$window$.history\n switch (data.type) {\n case 0:\n env.$propagateHistoryChange$ = false\n try {\n history.pushState(data.state, '', data.newUrl)\n } catch (e) {}\n env.$propagateHistoryChange$ = true\n break\n\n case 1:\n env.$propagateHistoryChange$ = false\n try {\n history.replaceState(data.state, '', data.newUrl)\n } catch (e) {}\n env.$propagateHistoryChange$ = true\n }\n })(msgValue.$winId$, env, msgValue)\n } else {\n 15 === msgType &&\n ((_type, winId, instanceId, callbackName, args) => {\n const elm = getOrCreateNodeInstance(winId, instanceId)\n elm &&\n 'function' == typeof elm[callbackName] &&\n elm[callbackName].apply(elm, args)\n })(...msg)\n }\n } else if (1 === msgType) {\n ;(initWebWorkerData => {\n const config = (webWorkerCtx.$config$ = JSON.parse(\n initWebWorkerData.$config$\n ))\n const locOrigin = initWebWorkerData.$origin$\n webWorkerCtx.$importScripts$ = importScripts.bind(self)\n webWorkerCtx.$interfaces$ = initWebWorkerData.$interfaces$\n webWorkerCtx.$libPath$ = initWebWorkerData.$libPath$\n webWorkerCtx.$origin$ = locOrigin\n webWorkerCtx.$postMessage$ = postMessage.bind(self)\n webWorkerCtx.$sharedDataBuffer$ = initWebWorkerData.$sharedDataBuffer$\n webWorkerlocalStorage.set(locOrigin, initWebWorkerData.$localStorage$)\n webWorkerSessionStorage.set(\n locOrigin,\n initWebWorkerData.$sessionStorage$\n )\n self.importScripts = void 0\n delete self.postMessage\n delete self.WorkerGlobalScope\n commaSplit('resolveUrl,get,set,apply').map(configName => {\n config[configName] &&\n (config[configName] = new Function(\n 'return ' + config[configName]\n )())\n })\n })(msgValue)\n webWorkerCtx.$postMessage$([2])\n } else if (3 === msgType) {\n webWorkerCtx.$interfaces$ = [...webWorkerCtx.$interfaces$, ...msgValue]\n webWorkerCtx.$isInitialized$ = 1\n logWorker('Initialized web worker')\n webWorkerCtx.$postMessage$([4])\n queuedEvents.length &&\n logWorker(`Queued ready messages: ${queuedEvents.length}`)\n ;[...queuedEvents].map(receiveMessageFromSandboxToWorker)\n queuedEvents.length = 0\n } else {\n queuedEvents.push(ev)\n }\n }\n self.onmessage = receiveMessageFromSandboxToWorker\n postMessage([0])\n})(self)\n\n```"
}
] |
code_partytown_52f270a5
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of partytown/react/typings/events.d.ts from the partytown VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nexport interface PixelMessage extends MessageEvent {\n data:\n | ProductViewData\n | ProductClickData\n | OrderPlacedData\n | OrderPlacedTrackedData\n | PageViewData\n | ProductImpressionData\n | AddToCartData\n | RemoveToCartData\n | CartChangedData\n | HomePageInfo\n | ProductPageInfoData\n | SearchPageInfoData\n | UserData\n | CartIdData\n | PromoViewData\n | PromotionClickData\n | NewsletterSubscriptionData\n}\n\nexport interface EventData {\n event: string\n eventName: string\n currency: string\n}\n\nexport interface PageInfoData extends EventData {\n event: 'pageInfo'\n eventName: 'vtex:pageInfo'\n accountName: string\n pageTitle: string\n pageUrl: string\n}\n\nexport interface UserData extends PageInfoData {\n eventType: 'userData'\n eventName: 'vtex:userData'\n firstName?: string\n lastName?: string\n document?: string\n id?: string\n email?: string\n phone?: string\n isAuthenticated: boolean\n}\n\nexport interface CartIdData extends PageInfoData {\n eventType: 'cartId'\n eventName: 'vtex:cartId'\n cartId: string\n}\n\nexport interface HomePageInfo extends PageInfoData {\n eventType: 'homeView'\n}\n\nexport interface ProductPageInfoData extends PageInfoData {\n eventType: 'productPageInfo'\n}\n\nexport interface SearchPageInfoData extends PageInfoData {\n eventType:\n | 'internalSiteSearchView'\n | 'categoryView'\n | 'departmentView'\n | 'emptySearchView'\n category?: CategoryMetaData\n department?: DepartmentMetaData\n search?: SearchMetaData\n}\n\ninterface CategoryMetaData {\n id: string\n name: string\n}\n\ninterface DepartmentMetaData {\n id: string\n name: string\n}\n\ninterface SearchMetaData {\n term: string\n category: CategoryMetaData\n results: number\n}\n\nexport interface PageViewData extends EventData {\n event: 'pageView'\n eventName: 'vtex:pageView'\n pageTitle: string\n pageUrl: string\n referrer: string\n}\n\nexport interface AddToCartData extends EventData {\n event: 'addToCart'\n eventName: 'vtex:addToCart'\n items: CartItem[]\n}\n\nexport interface RemoveToCartData extends EventData {\n event: 'removeFromCart'\n eventName: 'vtex:removeFromCart'\n items: CartItem[]\n}\n\nexport interface CartChangedData extends EventData {\n event: 'cartChanged'\n eventName: 'vtex:cartChanged'\n items: CartItem[]\n}\n\nexport interface OrderPlacedData extends Order, EventData {\n event: 'orderPlaced'\n eventName: 'vtex:orderPlaced'\n}\n\nexport interface OrderPlacedTrackedData extends Order, EventData {\n event: 'orderPlacedTracked'\n eventName: 'vtex:orderPlacedTracked'\n}\n\nexport interface ProductViewData extends EventData {\n event: 'productView'\n eventName: 'vtex:productView'\n product: Product\n}\n\nexport interface ProductClickData extends EventData {\n event: 'productClick'\n eventName: 'vtex:productClick'\n product: ProductSummary\n list?: string\n}\n\nexport interface ProductImpressionData extends EventData {\n event: 'productImpression'\n eventName: 'vtex:productImpression'\n impressions: Impression[]\n product?: ProductSummary // deprecated, use impressions list!\n position?: number // deprecated, use impressions list!\n list: string\n}\n\nexport interface CartData extends EventData {\n event: 'cart'\n eventName: 'vtex:cart'\n orderForm: OrderForm\n}\n\nexport interface PromoViewData extends EventData {\n event: 'promoView'\n eventName: 'vtex:promoView'\n promotions: Promotion[]\n}\n\nexport interface PromotionClickData extends EventData {\n event: 'promotionClick'\n eventName: 'vtex:promotionClick'\n promotions: Promotion[]\n}\n\nexport interface NewsletterSubscriptionData extends EventData {\n event: 'newsletterSubscription'\n eventName: 'vtex:newsletterSubscription'\n name: string\n email: string\n phone: string\n}\n\ninterface Promotion {\n id?: string\n name?: string\n creative?: string\n position?: string\n}\n\ninterface CartItem {\n brand: string\n ean: string\n category: string\n detailUrl: string\n imageUrl: string\n name: string\n price: number\n productId: string\n productRefId: string\n quantity: number\n seller: string\n sellerName: string\n skuId: string\n variant: string\n}\n\nexport interface OrderForm {\n id: string\n items: CartItem[]\n}\n\nexport interface Order {\n accountName: string\n corporateName: string\n coupon: string\n currency: string\n openTextField: string\n orderGroup: string\n salesChannel: string\n visitorAddressCity: string\n visitorAddressComplement: string\n visitorAddressCountry: string\n visitorAddressNeighborhood: string\n visitorAddressNumber: string\n visitorAddressPostalCode: string\n visitorAddressState: string\n visitorAddressStreet: string\n visitorContactInfo: string[]\n visitorContactPhone: string\n visitorType: string\n transactionId: string\n transactionDate: string\n transactionAffiliation: string\n transactionTotal: number\n transactionShipping: number\n transactionSubtotal: number\n transactionDiscounts: number\n transactionTax: number\n transactionCurrency: string\n transactionPaymentType: PaymentType[]\n transactionShippingMethod: ShippingMethod[]\n transactionLatestShippingEstimate: Date\n transactionProducts: ProductOrder[]\n transactionPayment: {\n id: string\n }\n}\n\nexport interface Impression {\n product: ProductSummary\n position: number\n}\n\nexport interface PaymentType {\n group: string\n paymentSystemName: string\n installments: number\n value: number\n}\n\nexport interface ShippingMethod {\n itemId: string\n selectedSla: string\n}\n\nexport interface ProductOrder {\n id: string\n name: string\n sku: string\n skuRefId: string\n skuName: string\n productRefId: string\n ean: string\n slug: string\n brand: string\n brandId: string\n seller: string\n sellerId: string\n category: string\n categoryId: string\n categoryTree: string[]\n categoryIdTree: string[]\n priceTags: PriceTag[]\n originalPrice: number\n price: number\n sellingPrice: number\n tax: number\n quantity: number\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n components: any[]\n measurementUnit: string\n unitMultiplier: number\n}\n\nexport interface PriceTag {\n identifier: string\n isPercentual: boolean\n value: number\n}\n\nexport interface Product {\n brand: string\n brandId: string\n categories: string[]\n categoryId: string\n categoryTree: Array<{ id: string; name: string }>\n detailUrl: string\n items: Item[]\n linkText: string\n productId: string\n productName: string\n productReference: string\n selectedSku: Item\n}\n\nexport interface Item {\n itemId: string\n name: string\n ean: string\n referenceId: { Key: string; Value: string }\n imageUrl: string\n sellers: Seller[]\n}\n\nexport interface ProductSummary {\n brand: string\n brandId: string\n categories: string[]\n items: ItemSummary[]\n linkText: string\n productId: string\n productName: string\n productReference: string\n sku: ItemSummary\n}\n\ninterface ItemSummary {\n itemId: string\n ean: string\n name: string\n referenceId: { Key: string; Value: string }\n seller: Seller\n sellers: Seller[]\n}\n\nexport interface Seller {\n commertialOffer: CommertialOffer\n sellerId: string\n sellerName: string\n}\n\nexport interface CommertialOffer {\n Price: number\n ListPrice: number\n AvailableQuantity: number\n}\n\n```"
}
] |
code_partytown_9c99429b
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of partytown/react/typings/global.d.ts from the partytown VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\ninterface Window extends Window {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n dataLayer: any[]\n}\n\n```"
}
] |
code_css-handles_78f12b80
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of css-handles/docs/README.md from the css-handles VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```markdown\n# CSS Handles\n\nUtility for generating CSS handles for store components.\n\n<!-- @import \"[TOC]\" {cmd=\"toc\" depthFrom=3 depthTo=6 orderedList=false} -->\n\n<!-- code_chunk_output -->\n\n- [useCssHandles](#usecsshandles)\n- [useCustomClasses](#usecustomclasses)\n- [createCssHandlesContext](#createcsshandlescontext)\n - [Example of issues that `createCssHandlesContext` solves](#example-of-issues-that-createcsshandlescontext-solves)\n - [Example with the usage of `createCssHandlesContext`](#example-with-the-usage-of-createcsshandlescontext)\n\n<!-- /code_chunk_output -->\n\n## API\n\n### useCssHandles\n\nThe `useCssHandles` hook creates handles that are used to customize parts of an app. These names are unique for each app, so two apps using the same handle identifier will not receive the same class name. It returns an object of type `CssHandlesBag`, which you can check out below.\n\nThis hook is extensible via the `classes` option, so other apps that import this component can customize the classes. See the docs for the `useCustomClasses` hook for more information.\n\nThere are cases where multiple components of a block have handles. In this cases, `useCssHandles` must be called only on the root component (the entrypoint of the block) and it must receive the handles of all nested components. To learn more about this use case, check out the `useContextCssHandles` hook.\n\n| Parameter | Type | Description | Default value |\n| --------- | ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------- |\n| `handles` | `[string]` |  List of handles to be created. The array is preferably a const (see example below) | `undefined` |\n| `options` | `CssHandlesOptions` | Configurations that change how the hook must behave. | `{}` |\n\n- `CssHandlesOptions` object:\n\n| Keys | Type | Description | Default value |\n| --------------- | ------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| `migrationFrom` | `string | [string]` | Used to preserve the behavior of a block when migrating code from one app to another. Receives APP IDs and creates additional handles for each one of them. | `undefined` |\n| `classes` | `CustomCSSClasses` | Used to override the default handle definitions. The value must be received via props, thus giving the parent component the ability incorporate the handles of its children in its API. To understand more about this option, read about the `useCustomClasses` hook. | `undefined` |\n\n- `CssHandlesBag` object:\n\n| Keys | Type | Description |\n| --------------- | -------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| `handles` | `Record<string, string>` | An object where the keys are the handles and its values are the classes. |\n| `withModifiers` | `function(string, string[]) => string` | Appends modifier suffixes to the CSS handles, for selection of specific items. The first argument receives the name of a handle, and the second argument might be a list or a string of the modifier to be appended. |\n\n- Example of usage:\n\n```tsx\nimport React from 'react'\nimport { useCssHandles } from 'vtex.css-handles'\n\n/* Using `as const at the end` hints to Typescript that this array\n * won't change, thus allowing autocomplete and other goodies. */\nconst CSS_HANDLES = ['container', 'background', 'text', 'item'] as const\n\nfunction MyExampleComponent({ classes }) {\n const { handles, withModifiers } = useCssHandles(CSS_HANDLES, { classes })\n\n return (\n <div className={handles.container}>\n <div className={`${handles.background} bg-red`}>\n <h1 className={`${handles.text} f1 c-white`}>Hello world</h1>\n <ul>\n {['blue', 'yellow', 'green'].map((color) => (\n <li\n {/*\n * Appends modifier suffixes to the CSS handles.\n * For example, `item item--color` */}\n className={`${withModifiers('item', color)} bg-${color}`}\n key={color}\n >\n Color {color}\n </li>\n ))}\n </ul>\n </div>\n </div>\n )\n}\n\nexport default MyExampleComponent\n```\n\n### useCustomClasses\n\nThe `useCustomClasses` hook acts as a handle API overrider. This hook is used to create new handles that can override the ones present on child components. It exists so a parent component can incorporate its children handle API into its own. The parent may determine if modifiers on the children should be applied, or change the names of the handles.\n\nThis hook receives a function and an array of dependencies, just like other React hooks such as `useEffect`. The function must return an object containing `CustomClassValue` values. The result can then be provided to its children via the `classes` prop, as demonstrated on the example below.\n\n| Parameter | Type | Description | Default value |\n| --------- | ------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------ | ------------- |\n| `classes` | `function => CustomClassValue` |  A function that returns a `CustomClassValue` object. | `undefined` |\n| `deps` | `any[]` | Array of dependencies. If any of the dependences change, the hook function is called again. | `[]` |\n\n- `CustomClassValue` object\n\nThe keys of the `CustomClassValue` object should match the name of the handles of the child it is going to override. The values must be of type `string | CustomClassItem | [string | CustomClassItem]`. See example below for more details.\n\n- `CustomClassItem` object\n\n| Parameter | Type | Description | Default value |\n| --------------- | --------- | ----------------------------------------------------------------------------------- | ---------------------------------------------------------------- |\n| `name` | `string` | Sets the name of the child handle. Avoid using the same name for multiple children. | Name of the `CustomClassValue` key corresponding to this object. |\n| `withModifiers` | `boolean` | Defines if the child will be able to run withModifiers on that specific handle. | `true` |\n\n- Example of usage (related to the previous example):\n\n```tsx\nimport React from 'react'\nimport { useCssHandles, useCustomClasses } from 'vtex.css-handles'\n\n// That is the example above\nimport MyExampleComponent from './MyExampleComponent'\n\nfunction MyComponent() {\n const classes = useCustomClasses(() => {\n container: 'foobar childContainer',\n text: ['anArray', 'example'],\n item: ['db', { name: 'myItem', applyModifiers: true }],\n })\n\n return (\n <div>\n {/* ChildComponent will now render:\n - The handle \"container\" will render the class \"foobar childContainer\"\n - The handle \"background\" was not customized, it will render the original handle\n - The handle \"text\" will render the classes \"anArray example\"\n - The handle \"item\" will render the class \"db myItem\" and will apply the modifiers applied to the class \"myItem\", example: \"db myItem myItem--red\".\n */}\n <MyExampleComponent classes={classes} />\n </div>\n )\n}\n\nexport default MyComponent\n```\n\n### createCssHandlesContext\n\nThe `createCssHandlesContext` function can be used to create a context provider and consumer for handles. It makes easier to manage handles that are located in components of different levels of the tree, avoiding [prop drilling](https://kentcdodds.com/blog/prop-drilling).\n\nThe function expects a list of handle names as input:\n\n| Parameter | Type | Description | Default value |\n| --------- | ---------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------- |\n| `handles` | `[string]` |  List of handles to be supported by the whole block. The array is preferably a const (see example below) | `undefined` |\n\nThe function outputs a `CssHandlesProvider` component and a `useContextCssHandles` hook.\n\n1. The `CssHandlesProvider` is used on the public component to provide all the `handles` and the `withModifier` function to its children via context. You should wrap your component with the provider as shown on the example bellow.\n2. Children of the public component that have handles of their own should use the `useContextCssHandles`. It outputs a `CssHandlesBag` just like the `useCssHandles` hook, and expects no input.\n\n#### Example of issues that `createCssHandlesContext` solves\n\n```tsx\n/* PublicAPIComponent.tsx */\nimport React from 'react'\nimport { useCssHandles } from 'vtex.css-handles'\n\nimport { NestedPrivateComponent } from './NestedPrivateComponent'\n\n/**\n * Problem: the nested handles are not included in the API of PublicAPIComponent.\n * TypeScript will complain if the user passes the class \"nestedPublicHandle\",\n * as \"nestedPublicHandle\" handle does not exist in PublicAPIComponent API.\n */\nconst CSS_HANDLES = ['root'] as const\n\nconst PublicAPIComponent({ classes }) {\n const { handles, withModifiers } = useCssHandles(CSS_HANDLES, { classes })\n\n return (\n <div className={handles.root}>\n {/* Problem: we need to pass the classes prop down. */}\n <NestedPrivateComponent classes={classes} />\n </div>\n )\n}\n\nexport default PublicAPIComponent\n```\n\n```tsx\n/* NestedPrivateComponent.tsx */\nimport React from 'react'\nimport { useCssHandles } from 'vtex.css-handles'\n\nconst CSS_HANDLES = ['nestedPublicHandle'] as const\n\n/**\n * Problem: if this component had another nested component it would need to pass\n * the classes prop down again!\n */\nconst NestedPrivateComponent({ classes }) {\n const { handles } = useCssHandles(CSS_HANDLES, { classes })\n\n return <div className={handles.nestedPublicHandle}>Nested Component</div>\n}\n\nexport default NestedPrivateComponent\n```\n\n#### Example with the usage of `createCssHandlesContext`\n\n```tsx\n/* PublicAPIComponent.tsx */\nimport React from 'react'\nimport { useCssHandles } from 'vtex.css-handles'\n\nimport { CssHandlesProvider } from './cssHandlesContext'\nimport { NestedPrivateComponent } from './NestedPrivateComponent'\n\n/**\n * Solution: include the NestedPrivateComponent CSS handles in the\n * PublicAPIComponent API.\n */\nexport const CSS_HANDLES = ['root', ...NestedPrivateComponent.cssHandles] as const\n\nconst PublicAPIComponent({ classes }) {\n const { handles, withModifiers } = useCssHandles(CSS_HANDLES, { classes })\n\n return (\n {/* Solution: provide handles by context */}\n <CssHandlesProvider handles={handles} withModifiers={withModifiers}>\n <div className={handles.root}>\n {/* Solution: no need to pass the classes prop down */}\n <NestedPrivateComponent />\n </div>\n </CssHandlesProvider>\n )\n}\n\nexport default PublicAPIComponent\n```\n\n```tsx\n/* NestedPrivateComponent.tsx */\nimport React from 'react'\n\nimport { useContextCssHandles } from './cssHandlesContext.ts'\n\n/*\n * Solution: if this component had another nested component, just merge the nested\n * component CSS Handles here, just like we did in PublicAPIComponent.\n */\nconst CSS_HANDLES = ['nestedPublicHandle'] as const\n\nconst NestedPrivateComponent() {\n // Use the hook created by `createCssHandlesContext`\n const { handles } = useContextCssHandles()\n\n return <div className={handles.nestedPublicHandle}>Nested Component</div>\n}\n\nNestedPrivateComponent.cssHandles = CSS_HANDLES\n\nexport default NestedPrivateComponent\n```\n\n```ts\n/* cssHandlesContext.ts */\nimport { createCssHandlesContext } from 'vtex.css-handles'\n\nimport { CSS_HANDLES } from './PublicAPIComponent'\n\nconst { CssHandlesProvider, useContextCssHandles } = createCssHandlesContext(\n CSS_HANDLES\n)\n\nexport { CssHandlesProvider, useContextCssHandles }\n```\n\n```"
}
] |
code_css-handles_0511d406
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of css-handles/react/createCssHandlesContext.tsx from the css-handles VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React, {\n createContext,\n useContext,\n useMemo,\n PropsWithChildren,\n} from 'react'\n\nimport type { CssHandlesList, CssHandlesBag } from './CssHandlesTypes'\n\ninterface ProviderProps<T extends CssHandlesList> {\n withModifiers: CssHandlesBag<T>['withModifiers']\n handles: CssHandlesBag<T>['handles']\n}\n\nexport default function createCssHandlesContext<T extends CssHandlesList>(\n _handles: T\n) {\n const Context = createContext<CssHandlesBag<T> | null>(null)\n\n const useContextCssHandles = () => {\n return useContext(Context) as CssHandlesBag<T>\n }\n\n const CssHandlesProvider = ({\n withModifiers,\n handles,\n children,\n }: PropsWithChildren<ProviderProps<T>>) => {\n const value = useMemo(\n () => ({\n handles,\n withModifiers,\n }),\n [withModifiers, handles]\n )\n\n return <Context.Provider value={value}>{children}</Context.Provider>\n }\n\n return {\n CssHandlesProvider,\n useContextCssHandles,\n }\n}\n\n```"
}
] |
code_css-handles_f2c5d72c
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of css-handles/react/CssHandlesTypes.ts from the css-handles VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { SYMBOL_CUSTOM_CLASSES } from './useCustomClasses'\n\nexport type ValuesOf<T extends readonly unknown[]> = T[number]\n\ntype CustomClassItem =\n | string\n | {\n name: string\n applyModifiers?: boolean\n }\n\nexport type CssHandlesList = readonly string[]\n\nexport type CssHandles<T extends CssHandlesList> = Record<ValuesOf<T>, string>\n\nexport type WithModifiers<T extends CssHandlesList> = (\n handleName: ValuesOf<T>,\n modifier: string | string[]\n) => string\n\n/**\n * Collection of css handle utilities returned by `useCssHandles`\n */\nexport type CssHandlesBag<T extends CssHandlesList> = {\n handles: CssHandles<T>\n withModifiers: WithModifiers<T>\n}\n\n/**\n * Props added to a wrapped component via `withCssHandles`\n */\nexport type WithCssHandlesBag<T extends CssHandlesList, Props> = Props &\n CssHandlesBag<T>\n\nexport type CustomClassValue = CustomClassItem | CustomClassItem[]\n\nexport type CustomClasses<T extends CssHandlesList> = {\n [key in ValuesOf<T>]?: CustomClassValue\n} & {\n /**\n * Internal custom classes key\n * @private\n */\n __useCustomClasses: typeof SYMBOL_CUSTOM_CLASSES\n}\n\nexport interface CssHandlesOptions<T extends CssHandlesList> {\n migrationFrom?: string | string[]\n classes?: CustomClasses<T>\n}\n\n```"
}
] |
code_css-handles_38fbe973
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of css-handles/react/applyModifiers.ts from the css-handles VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { validateModifier } from './modules/modifier'\n\nconst applyModifiers = (handles: string, modifier: string | string[]) => {\n const normalizedModifiers =\n typeof modifier === 'string' ? [modifier] : modifier\n\n if (!Array.isArray(normalizedModifiers)) {\n console.error(\n 'Invalid modifier type on `cssHandles.applyModifier`. Please use either a string or an array of strings'\n )\n\n return handles\n }\n\n const splitHandles = handles.split(' ')\n\n const modifiedHandles = normalizedModifiers\n .map((currentModifier) => {\n const isValid = validateModifier(currentModifier)\n\n if (!isValid) {\n return ''\n }\n\n return splitHandles\n .map((handle) => `${handle}--${currentModifier}`)\n .join(' ')\n .trim()\n })\n .filter((l) => l.length > 0)\n .join(' ')\n .trim()\n\n return splitHandles.concat(modifiedHandles).join(' ').trim()\n}\n\nexport default applyModifiers\n\n```"
}
] |
code_css-handles_ac07a75b
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of css-handles/react/package.json from the css-handles VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"scripts\": {\n \"test\": \"vtex-test-tools test\"\n },\n \"dependencies\": {\n \"apollo-client\": \"^2.6.3\",\n \"react\": \"^16.10.1\",\n \"react-apollo\": \"^2.5.8\",\n \"react-dom\": \"^16.8.6\",\n \"react-intl\": \"^2.9.0\"\n },\n \"devDependencies\": {\n \"@apollo/react-testing\": \"^4.0.0\",\n \"@types/react\": \"^16.9.56\",\n \"@vtex/test-tools\": \"^3.3.2\",\n \"@vtex/tsconfig\": \"^0.5.2\",\n \"typescript\": \"3.9.7\",\n \"vtex.render-runtime\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.render-runtime@8.124.3/public/@types/vtex.render-runtime\"\n },\n \"version\": \"1.0.1\"\n}\n\n```"
}
] |
code_css-handles_acc51f3d
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of css-handles/react/withCssHandles.tsx from the css-handles VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React, { ComponentType } from 'react'\n\nimport useCssHandles from './useCssHandles'\nimport type {\n CssHandlesList,\n CssHandlesOptions,\n CssHandlesBag,\n} from './CssHandlesTypes'\n\n// eslint-disable-next-line @typescript-eslint/ban-types\nconst withCssHandles = <T extends CssHandlesList, Props = {}>(\n handles: T,\n options?: CssHandlesOptions<T>\n) => (Component: ComponentType<Props & CssHandlesBag<T>>) => {\n const EnhancedComponent = (props: Props) => {\n const handlesBag = useCssHandles(handles, options)\n\n return <Component {...props} {...handlesBag} />\n }\n\n const displayName = Component.displayName ?? Component.name ?? 'Component'\n\n EnhancedComponent.displayName = `withCssHandles(${displayName})`\n\n return EnhancedComponent\n}\n\nexport default withCssHandles\n\n```"
}
] |
code_css-handles_c1e1ea12
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of css-handles/react/useCssHandles.tsx from the css-handles VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport { useMemo } from 'react'\n\nimport { useExtension } from './hooks/useExtension'\nimport {\n computeCustomClassValue,\n ComputedCustomClass,\n} from './modules/customClasses'\nimport { validateModifier } from './modules/modifier'\nimport applyModifiers from './applyModifiers'\nimport { SYMBOL_CUSTOM_CLASSES } from './useCustomClasses'\nimport type {\n CssHandlesList,\n CssHandles,\n CssHandlesOptions,\n ValuesOf,\n CssHandlesBag,\n CustomClassValue,\n} from './CssHandlesTypes'\n\nconst VALID_CSS_HANDLE_PATTERN = /^[^\\d][\\w-]+$/\nconst APP_NAME_PATTERN = /([^.]+)\\.([^@]+)@(\\d+)/\n\n/** Verifies if the handle contains only letters, numbers and -, and does not begin with a number */\nconst validateCssHandle = (handle: string) =>\n VALID_CSS_HANDLE_PATTERN.test(handle)\n\nconst parseComponentName = (componentName: string) => {\n const [, vendor, name, major] = componentName.match(APP_NAME_PATTERN) ?? []\n\n return { vendor, name, major }\n}\n\nconst normalizeComponentName = (componentName: string) => {\n const { vendor, name, major } = parseComponentName(componentName)\n\n if (vendor && name && major) {\n return `${vendor}-${name}-${major}-x`\n }\n\n return null\n}\n\nconst generateCssHandles = <T extends CssHandlesList>(\n namespace: string,\n handles: T,\n modifiers?: string | string[]\n) => {\n return handles.reduce((acc, handle: ValuesOf<T>) => {\n const isValid = !!namespace && validateCssHandle(handle)\n const transformedHandle = `${namespace}-${handle}`\n\n acc[handle] = isValid\n ? modifiers\n ? applyModifiers(transformedHandle, modifiers)\n : transformedHandle\n : ''\n\n if (!isValid) {\n console.error(\n `Invalid CSS handle \"${handle}\". It should only contain letters or numbers, and should start with a letter.`\n )\n }\n\n return acc\n }, {} as CssHandles<T>)\n}\n\n/**\n * Useful for creating CSS handles without creating a CSS file with empty\n * declarations.\n * Receives an array of strings (e.g. ['foo', 'bar']) and returns an\n * object with generated css class names, e.g.\n * { foo: 'vendor-appname-1-x-foo', bar: 'vendor-appname-1-x-bar' }.\n */\nconst useCssHandles = <T extends CssHandlesList>(\n handleList: T,\n options: CssHandlesOptions<T> = {}\n): CssHandlesBag<T> => {\n const extension = useExtension()\n\n const { content = {}, props = {}, component = '' } = extension ?? {}\n const blockClass = props.cssHandle || content.blockClass || props.blockClass\n const { migrationFrom, classes: handlesOverride } = options\n\n const values = useMemo<CssHandlesBag<T>>(() => {\n const normalizedComponent = normalizeComponentName(component)\n\n const namespaces = normalizedComponent ? [normalizedComponent] : []\n const handlesSet = new Set<ValuesOf<T>>(handleList)\n const handles = {} as CssHandles<T>\n const computedCustomClasses = new Map<ValuesOf<T>, ComputedCustomClass>()\n\n if (migrationFrom) {\n const migrations = Array.isArray(migrationFrom)\n ? migrationFrom\n : [migrationFrom]\n\n const normalizedMigrations = migrations\n .map(normalizeComponentName)\n .filter(\n (current) => !!current && current !== normalizedComponent\n ) as string[]\n\n namespaces.push(...normalizedMigrations)\n }\n\n if (handlesOverride) {\n if (\n process.env.NODE_ENV === 'development' &&\n handlesOverride.__useCustomClasses !== SYMBOL_CUSTOM_CLASSES\n ) {\n throw new Error(\n \"[css-handles] Invalid 'classes' option. Use the 'useCustomClasses' hook to generate a valid 'classes' object.\"\n )\n }\n\n Object.keys(handlesOverride).forEach((handleName: ValuesOf<T>) => {\n // the secret symbol can be safely ignored here\n if (handleName === '__useCustomClasses') return\n\n // side-effect to remove handles that we don't need to generate full names\n handlesSet.delete(handleName)\n\n const computedCustomClass = computeCustomClassValue(\n handlesOverride[handleName] as Required<CustomClassValue>\n )\n\n handles[handleName] = computedCustomClass.classNames.join(' ')\n computedCustomClasses.set(handleName, computedCustomClass)\n })\n }\n\n // `handlesToGenerate` are handles that were not overriden by classes\n const handlesToGenerate = [...handlesSet]\n\n namespaces.forEach((componentName) => {\n const namespaceHandles = generateCssHandles(\n componentName,\n handlesToGenerate,\n blockClass\n )\n\n Object.keys(namespaceHandles).forEach((key: ValuesOf<T>) => {\n if (key in handles) {\n handles[key] = `${handles[key]} ${namespaceHandles[key]}`\n } else {\n handles[key] = namespaceHandles[key]\n }\n })\n })\n\n const withModifiers = (id: ValuesOf<T>, modifier: string | string[]) => {\n const normalizedModifiers =\n typeof modifier === 'string' ? [modifier] : modifier\n\n if (!Array.isArray(normalizedModifiers)) {\n console.error(\n 'Invalid modifier type on `withModifier`. Please use either a string or an array of strings'\n )\n\n return handles[id]\n }\n\n let baseClassNames: string[] = []\n let classesToApplyModifiers: string[] = []\n\n const computedCustomClass = computedCustomClasses.get(id)\n\n if (computedCustomClass) {\n baseClassNames = computedCustomClass.classNames\n classesToApplyModifiers = computedCustomClass.toApplyModifiers\n } else {\n baseClassNames = handles[id].split(' ')\n classesToApplyModifiers = baseClassNames\n }\n\n const modifiedClasses = normalizedModifiers\n .map((currentModifier) => {\n const isValid = validateModifier(currentModifier)\n\n if (!isValid) {\n return ''\n }\n\n return classesToApplyModifiers\n .map((className) => `${className}--${currentModifier}`)\n .join(' ')\n .trim()\n })\n .filter((l) => l.length > 0)\n .join(' ')\n .trim()\n\n return baseClassNames.concat(modifiedClasses).join(' ').trim()\n }\n\n return {\n handles,\n withModifiers,\n }\n }, [blockClass, component, handleList, migrationFrom, handlesOverride])\n\n return values\n}\n\nexport default useCssHandles\n\n```"
}
] |
code_css-handles_2dd9bf23
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of css-handles/react/useCustomClasses.ts from the css-handles VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { useMemo } from 'react'\n\nimport type { CustomClasses, CssHandlesList } from './CssHandlesTypes'\n\nexport const SYMBOL_CUSTOM_CLASSES: unique symbol = Symbol('customClasses')\n\nconst useCustomClasses = <T extends CssHandlesList>(\n classes: () => Omit<CustomClasses<T>, '__useCustomClasses'>,\n deps: unknown[] = []\n): CustomClasses<T> => {\n // we know what we're doing *wink wink*\n // eslint-disable-next-line react-hooks/exhaustive-deps\n const memo = useMemo(classes, deps) as CustomClasses<T>\n\n // __useCustomClasses is added to guarantee that consumers will use this hooks\n // instead of just passing a new object at every render\n memo.__useCustomClasses = SYMBOL_CUSTOM_CLASSES\n\n return memo\n}\n\nexport default useCustomClasses\n\n```"
}
] |
code_css-handles_f5173489
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of css-handles/react/__fixtures__/Nested.tsx from the css-handles VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\n\nimport { useContextCssHandles } from './handles'\n\nconst Nested = () => {\n const { handles } = useContextCssHandles()\n\n return <div className={handles.nested}>Nested content</div>\n}\n\nNested.handles = ['nested'] as const\n\nexport default Nested\n\n```"
}
] |
code_css-handles_f9a7091b
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of css-handles/react/__fixtures__/Root.tsx from the css-handles VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\n\nimport useCssHandles from '../useCssHandles'\nimport { CustomClasses } from '../CssHandlesTypes'\nimport { CssHandlesProvider } from './handles'\nimport Nested from './Nested'\n\nexport const ROOT_HANDLES = ['root', ...Nested.handles] as const\n\ninterface Props {\n classes?: CustomClasses<typeof ROOT_HANDLES>\n}\n\nconst Root = ({ classes }: Props) => {\n const { handles, withModifiers } = useCssHandles(ROOT_HANDLES, { classes })\n\n return (\n <CssHandlesProvider withModifiers={withModifiers} handles={handles}>\n <div className={handles.root}>\n Root Component\n <Nested />\n </div>\n </CssHandlesProvider>\n )\n}\n\nexport default Root\n\n```"
}
] |
code_css-handles_28d61b80
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of css-handles/react/__fixtures__/handles.ts from the css-handles VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport createCssHandlesContext from '../createCssHandlesContext'\nimport { ROOT_HANDLES } from './Root'\n\nconst { CssHandlesProvider, useContextCssHandles } = createCssHandlesContext(\n ROOT_HANDLES\n)\n\nexport { CssHandlesProvider, useContextCssHandles }\n\n```"
}
] |
code_css-handles_bd53e754
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of css-handles/react/__tests__/useCssHandles.test.tsx from the css-handles VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport useCssHandles from '../useCssHandles'\nimport { useExtension } from '../hooks/useExtension'\nimport { SYMBOL_CUSTOM_CLASSES } from '../useCustomClasses'\nimport { resetInvalidModifiers } from '../modules/modifier'\n\njest.mock('react', () => ({\n useMemo: (callback: () => any) => callback(),\n}))\n\njest.mock('../hooks/useExtension', () => ({\n useExtension: jest.fn(() => ({\n component: 'vtex.app@2.1.0',\n props: {\n blockClass: 'blockClass',\n },\n })),\n}))\n\njest.useFakeTimers()\n\nconst mockedUseExtension = useExtension as jest.Mock\nconst consoleError = jest.spyOn(console, 'error').mockImplementation()\n\ndescribe('basic usage', () => {\n it('should apply proper classes to proper handles', () => {\n const CSS_HANDLES = ['element1', 'element2']\n\n const { handles } = useCssHandles(CSS_HANDLES)\n\n expect(handles).toStrictEqual({\n element1: 'vtex-app-2-x-element1 vtex-app-2-x-element1--blockClass',\n element2: 'vtex-app-2-x-element2 vtex-app-2-x-element2--blockClass',\n })\n })\n\n it('should not apply blockClasses if not available', () => {\n const CSS_HANDLES = ['element1', 'element2']\n\n mockedUseExtension.mockImplementationOnce(() => ({\n component: 'vtex.app@2.1.0',\n props: {},\n }))\n\n const { handles } = useCssHandles(CSS_HANDLES)\n\n expect(handles).toStrictEqual({\n element1: 'vtex-app-2-x-element1',\n element2: 'vtex-app-2-x-element2',\n })\n })\n\n it('make invalid class names be transformed to empty strings', () => {\n const CSS_HANDLES = ['element1', 'element-2', 'element+3', '4element']\n\n mockedUseExtension.mockImplementationOnce(() => ({\n component: 'vtex.app@2.1.0',\n props: {},\n }))\n\n const { handles } = useCssHandles(CSS_HANDLES)\n\n expect(handles).toStrictEqual({\n element1: 'vtex-app-2-x-element1',\n 'element-2': 'vtex-app-2-x-element-2',\n 'element+3': '',\n '4element': '',\n })\n })\n})\n\ndescribe('migration', () => {\n it('should add both the current app and the migration app', () => {\n const CSS_HANDLES = ['element1', 'element2']\n\n const { handles } = useCssHandles(CSS_HANDLES, {\n migrationFrom: 'vtex.previous-app@3.0.0',\n })\n\n expect(handles).toStrictEqual({\n element1:\n 'vtex-app-2-x-element1 vtex-app-2-x-element1--blockClass vtex-previous-app-3-x-element1 vtex-previous-app-3-x-element1--blockClass',\n element2:\n 'vtex-app-2-x-element2 vtex-app-2-x-element2--blockClass vtex-previous-app-3-x-element2 vtex-previous-app-3-x-element2--blockClass',\n })\n })\n\n it('should add more than one migration if needed', () => {\n const CSS_HANDLES = ['element1', 'element2']\n\n const { handles } = useCssHandles(CSS_HANDLES, {\n migrationFrom: ['vtex.previous-app@2.0.0', 'vtex.previous-app@3.0.0'],\n })\n\n expect(handles).toStrictEqual({\n element1:\n 'vtex-app-2-x-element1 vtex-app-2-x-element1--blockClass vtex-previous-app-2-x-element1 vtex-previous-app-2-x-element1--blockClass vtex-previous-app-3-x-element1 vtex-previous-app-3-x-element1--blockClass',\n element2:\n 'vtex-app-2-x-element2 vtex-app-2-x-element2--blockClass vtex-previous-app-2-x-element2 vtex-previous-app-2-x-element2--blockClass vtex-previous-app-3-x-element2 vtex-previous-app-3-x-element2--blockClass',\n })\n })\n\n it('doesnt repeat the migration if the current app happens to be the same as the migration one', () => {\n const CSS_HANDLES = ['element1', 'element2']\n\n const { handles } = useCssHandles(CSS_HANDLES, {\n migrationFrom: [\n 'vtex.previous-app@2.0.0',\n 'vtex.previous-app@3.0.0',\n 'vtex.app@2.1.0',\n ],\n })\n\n expect(handles).toStrictEqual({\n element1:\n 'vtex-app-2-x-element1 vtex-app-2-x-element1--blockClass vtex-previous-app-2-x-element1 vtex-previous-app-2-x-element1--blockClass vtex-previous-app-3-x-element1 vtex-previous-app-3-x-element1--blockClass',\n element2:\n 'vtex-app-2-x-element2 vtex-app-2-x-element2--blockClass vtex-previous-app-2-x-element2 vtex-previous-app-2-x-element2--blockClass vtex-previous-app-3-x-element2 vtex-previous-app-3-x-element2--blockClass',\n })\n })\n})\n\ndescribe('custom classes', () => {\n it('should override handles with passed custom classes', () => {\n const CSS_HANDLES = [\n 'element1',\n 'element2',\n 'element3',\n 'element4',\n 'element5',\n 'element6',\n 'element7',\n 'element8',\n ] as const\n\n const { handles } = useCssHandles(CSS_HANDLES, {\n classes: {\n element2: 'a',\n element3: ['b'],\n element4: { name: 'a' },\n element5: [{ name: 'a' }],\n element6: ['a', { name: 'b' }],\n element7: ['a', 'b'],\n element8: [{ name: 'a' }, { name: 'b' }],\n __useCustomClasses: SYMBOL_CUSTOM_CLASSES,\n },\n })\n\n expect(handles).toMatchObject({\n element1: 'vtex-app-2-x-element1 vtex-app-2-x-element1--blockClass',\n element2: 'a',\n element3: 'b',\n element4: 'a',\n element5: 'a',\n element6: 'a b',\n element7: 'a b',\n element8: 'a b',\n })\n })\n})\n\ndescribe('withModifiers', () => {\n beforeEach(() => {\n consoleError.mockClear()\n resetInvalidModifiers()\n })\n\n it('should work with no custom classes', () => {\n const CSS_HANDLES = ['handle1'] as const\n\n const { withModifiers } = useCssHandles(CSS_HANDLES)\n\n const singleMod = withModifiers('handle1', 'mod')\n const multiMod = withModifiers('handle1', ['mod', 'mod2'])\n // @ts-expect-error passing wrong param for tests\n const multiNullMod = withModifiers('handle1', ['mod', null, 'mod2'])\n\n expect(singleMod).toBe(\n 'vtex-app-2-x-handle1 vtex-app-2-x-handle1--blockClass vtex-app-2-x-handle1--mod vtex-app-2-x-handle1--blockClass--mod'\n )\n expect(multiMod).toBe(\n 'vtex-app-2-x-handle1 vtex-app-2-x-handle1--blockClass vtex-app-2-x-handle1--mod vtex-app-2-x-handle1--blockClass--mod vtex-app-2-x-handle1--mod2 vtex-app-2-x-handle1--blockClass--mod2'\n )\n expect(multiNullMod).toBe(\n 'vtex-app-2-x-handle1 vtex-app-2-x-handle1--blockClass vtex-app-2-x-handle1--mod vtex-app-2-x-handle1--blockClass--mod vtex-app-2-x-handle1--mod2 vtex-app-2-x-handle1--blockClass--mod2'\n )\n })\n\n it('should not add an invalid modifier parameter', () => {\n const CSS_HANDLES = ['handle1'] as const\n\n const { withModifiers } = useCssHandles(CSS_HANDLES)\n\n const invalidModifierParam = 1\n // @ts-expect-error passing wrong param for test\n const result = withModifiers('handle1', invalidModifierParam)\n\n expect(consoleError).toHaveBeenCalledWith(\n 'Invalid modifier type on `withModifier`. Please use either a string or an array of strings'\n )\n expect(result).toBe('vtex-app-2-x-handle1 vtex-app-2-x-handle1--blockClass')\n })\n\n it('should not add an invalid modifier value', async () => {\n const CSS_HANDLES = ['handle1'] as const\n\n const { withModifiers } = useCssHandles(CSS_HANDLES)\n\n const invalidModifierValue = 'i.n.v.a.l.i.d'\n const result = withModifiers('handle1', invalidModifierValue)\n\n jest.runAllTimers()\n\n expect(consoleError).toHaveBeenLastCalledWith(\n 'Invalid CSS modifiers. All modifiers should be strings, and only contain letters, numbers, or -. Found: i.n.v.a.l.i.d'\n )\n expect(result).toBe('vtex-app-2-x-handle1 vtex-app-2-x-handle1--blockClass')\n })\n\n it('should apply modifiers only on custom classes with applyModifiers', () => {\n const CSS_HANDLES = ['handle1', 'handle2', 'handle3'] as const\n\n const { withModifiers } = useCssHandles(CSS_HANDLES, {\n classes: {\n handle1: 'customClass',\n handle2: [\n 'customClass',\n { name: 'anotherClass', applyModifiers: true },\n ],\n handle3: { name: 'customClass', applyModifiers: true },\n __useCustomClasses: SYMBOL_CUSTOM_CLASSES,\n },\n })\n\n const handle1 = withModifiers('handle1', 'mod')\n const handle2 = withModifiers('handle2', 'mod')\n const handle3 = withModifiers('handle3', 'mod')\n\n expect(handle1).toBe('customClass')\n expect(handle2).toBe('customClass anotherClass anotherClass--mod')\n expect(handle3).toBe('customClass customClass--mod')\n })\n\n it('should apply modifier on all passed classes in the same name', () => {\n const CSS_HANDLES = ['handle1', 'handle2', 'handle3'] as const\n\n const { withModifiers } = useCssHandles(CSS_HANDLES, {\n classes: {\n handle1: { name: 'customClass1 customClass2', applyModifiers: true },\n __useCustomClasses: SYMBOL_CUSTOM_CLASSES,\n },\n })\n\n const handle1 = withModifiers('handle1', 'mod')\n\n expect(handle1).toBe(\n 'customClass1 customClass2 customClass1--mod customClass2--mod'\n )\n })\n})\n\n```"
}
] |
code_css-handles_64fa6fd3
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of css-handles/react/__tests__/createCssHandlesContext.test.tsx from the css-handles VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\nimport { render } from '@vtex/test-tools/react'\n\nimport { SYMBOL_CUSTOM_CLASSES } from '../useCustomClasses'\nimport Root from '../__fixtures__/Root'\n\njest.mock('../hooks/useExtension', () => ({\n useExtension: jest.fn(() => ({\n component: 'vtex.app@2.1.0',\n })),\n}))\n\ntest('should create nested CSS Handles', () => {\n const { container } = render(<Root />)\n\n const rootElement = container.querySelector('.vtex-app-2-x-root')\n const nestedElement = container.querySelector('.vtex-app-2-x-nested')\n\n expect(rootElement).toBeInTheDocument()\n expect(nestedElement).toBeInTheDocument()\n})\n\ntest('should work with custom classes', () => {\n const { container } = render(\n <Root\n classes={{\n root: 'customRoot',\n __useCustomClasses: SYMBOL_CUSTOM_CLASSES,\n }}\n />\n )\n\n const rootElement = container.querySelector('.customRoot')\n const nestedElement = container.querySelector('.vtex-app-2-x-nested')\n\n expect(rootElement).toBeInTheDocument()\n expect(nestedElement).toBeInTheDocument()\n})\n\n```"
}
] |
code_css-handles_c0b8f72e
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of css-handles/react/__tests__/applyModifiers.test.tsx from the css-handles VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport applyModifiers from '../applyModifiers'\n\njest.spyOn(console, 'error').mockImplementation()\n\ndescribe('applyModifier', () => {\n it('should apply a single modifier properly', () => {\n const handle = 'vtex-app-2-x-handle vtex-app-2-x-handle--blockClass'\n const modifier = 'test'\n\n const modified = applyModifiers(handle, modifier)\n\n expect(modified).toBe(\n 'vtex-app-2-x-handle vtex-app-2-x-handle--blockClass vtex-app-2-x-handle--test vtex-app-2-x-handle--blockClass--test'\n )\n })\n it('should apply multiple modifiers properly', () => {\n const handle = 'vtex-app-2-x-handle vtex-app-2-x-handle--blockClass'\n const modifiers = ['test', 'test2']\n\n const modified = applyModifiers(handle, modifiers)\n\n expect(modified).toBe(\n 'vtex-app-2-x-handle vtex-app-2-x-handle--blockClass vtex-app-2-x-handle--test vtex-app-2-x-handle--blockClass--test vtex-app-2-x-handle--test2 vtex-app-2-x-handle--blockClass--test2'\n )\n })\n it('should not apply modifier if its not a string', () => {\n const handle = 'vtex-app-2-x-handle vtex-app-2-x-handle--blockClass'\n const modifier = 0 as any\n\n const modified = applyModifiers(handle, modifier)\n\n expect(modified).toBe('vtex-app-2-x-handle vtex-app-2-x-handle--blockClass')\n })\n\n describe('validation', () => {\n it('should refrain from applying a modifier from an array if its not a string', () => {\n const handle = 'vtex-app-2-x-handle vtex-app-2-x-handle--blockClass'\n const modifiers = ['ok', 0, null] as any\n\n const modified = applyModifiers(handle, modifiers)\n\n expect(modified).toBe(\n 'vtex-app-2-x-handle vtex-app-2-x-handle--blockClass vtex-app-2-x-handle--ok vtex-app-2-x-handle--blockClass--ok'\n )\n })\n it('should not apply a modifier with spaces, should allow with dashes', () => {\n const handle = 'vtex-app-2-x-handle vtex-app-2-x-handle--blockClass'\n const modifiers = ['ok', 'test 1', 'test-2', 'test\\t3', 'test\\n4']\n\n const modified = applyModifiers(handle, modifiers)\n\n expect(modified).toBe(\n 'vtex-app-2-x-handle vtex-app-2-x-handle--blockClass vtex-app-2-x-handle--ok vtex-app-2-x-handle--blockClass--ok vtex-app-2-x-handle--test-2 vtex-app-2-x-handle--blockClass--test-2'\n )\n })\n it('should not apply a modifier if its empty', () => {\n const handle = 'vtex-app-2-x-handle vtex-app-2-x-handle--blockClass'\n const modifiers = ['ok', '', '\\t', ' ']\n\n const modified = applyModifiers(handle, modifiers)\n\n expect(modified).toBe(\n 'vtex-app-2-x-handle vtex-app-2-x-handle--blockClass vtex-app-2-x-handle--ok vtex-app-2-x-handle--blockClass--ok'\n )\n })\n })\n})\n\n```"
}
] |
code_css-handles_95b04d02
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of css-handles/react/__tests__/useCustomClasses.test.ts from the css-handles VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { renderHook } from '@vtex/test-tools/react'\n\nimport useCustomClasses, { SYMBOL_CUSTOM_CLASSES } from '../useCustomClasses'\n\ntest('returns the same object keyed with \"__useCustomClasses\"', () => {\n const obj = {\n container: 'potato-container',\n wrapper: [{ name: 'wrapper' }, 'wrapper--potato'],\n item: { name: 'item' },\n }\n\n const callback = jest.fn(() => ({ ...obj }))\n\n const { result } = renderHook(() => {\n return useCustomClasses(callback)\n })\n\n expect(result.current.__useCustomClasses).toBe(SYMBOL_CUSTOM_CLASSES)\n expect(result.current).toMatchObject(obj)\n expect(callback).toHaveBeenCalledTimes(1)\n})\n\ntest('memoizes the result with no dependencies', () => {\n const obj = {\n container: 'potato-container',\n wrapper: [{ name: 'wrapper' }, 'wrapper--potato'],\n item: { name: 'item' },\n }\n\n const callback = jest.fn(() => ({ ...obj }))\n\n const { rerender } = renderHook(() => {\n return useCustomClasses(callback)\n })\n\n rerender()\n rerender()\n\n expect(callback).toHaveBeenCalledTimes(1)\n})\n\ntest('returns new object when dependencies change', () => {\n const obj = {\n container: 'potato-container',\n wrapper: [{ name: 'wrapper' }, 'wrapper--potato'],\n item: { name: 'item' },\n }\n\n let dependency = 'foo'\n\n const callback = jest.fn(() => ({ ...obj }))\n\n const { rerender } = renderHook(() => {\n return useCustomClasses(callback, [dependency])\n })\n\n expect(callback).toHaveBeenCalledTimes(1)\n rerender()\n\n dependency = 'bar'\n\n rerender()\n expect(callback).toHaveBeenCalledTimes(2)\n})\n\n```"
}
] |
code_css-handles_30d7d31b
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of css-handles/react/__tests__/withCssHandles.test.tsx from the css-handles VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React, { FC } from 'react'\nimport { render } from '@vtex/test-tools/react'\n\nimport withCssHandles from '../withCssHandles'\nimport { useExtension } from '../hooks/useExtension'\nimport type {\n CssHandlesList,\n CssHandlesBag,\n CssHandlesOptions,\n} from '../CssHandlesTypes'\n\njest.mock('../hooks/useExtension', () => ({\n useExtension: jest.fn(() => ({\n component: 'vtex.app@2.1.0',\n props: {\n blockClass: 'blockClass',\n },\n })),\n}))\n\ndescribe('withCssHandles', () => {\n const renderComponent = (\n handlesNames: CssHandlesList,\n options?: CssHandlesOptions<any>\n ) => {\n type InternalProps = CssHandlesBag<typeof handlesNames>\n\n const ExampleComponent: FC<InternalProps> = ({ handles }) => {\n return (\n <div\n data-testid=\"test-div\"\n className={Object.values(handles).join(' ')}\n />\n )\n }\n\n const EnhancedComponent = withCssHandles<typeof handlesNames>(\n handlesNames,\n options\n )(ExampleComponent)\n\n return render(<EnhancedComponent />)\n }\n\n it('should apply proper classes to proper handles', () => {\n const CSS_HANDLES = ['element1', 'element2'] as const\n const { getByTestId } = renderComponent(CSS_HANDLES)\n\n expect(getByTestId('test-div').className).toBe(\n 'vtex-app-2-x-element1 vtex-app-2-x-element1--blockClass vtex-app-2-x-element2 vtex-app-2-x-element2--blockClass'\n )\n })\n\n it('should not apply blockClasses if not available', () => {\n const CSS_HANDLES = ['element1', 'element2'] as const\n\n ;(useExtension as any).mockImplementationOnce(() => ({\n component: 'vtex.app@2.1.0',\n props: {},\n }))\n\n const { getByTestId } = renderComponent(CSS_HANDLES)\n\n expect(getByTestId('test-div').className).toBe(\n 'vtex-app-2-x-element1 vtex-app-2-x-element2'\n )\n })\n\n describe('migration', () => {\n it('should add both the current app and the migration app', () => {\n const CSS_HANDLES = ['element1', 'element2']\n const options = {\n migrationFrom: 'vtex.previous-app@3.0.0',\n }\n\n const { getByTestId } = renderComponent(CSS_HANDLES, options)\n\n expect(getByTestId('test-div').className).toBe(\n 'vtex-app-2-x-element1 vtex-app-2-x-element1--blockClass vtex-previous-app-3-x-element1 vtex-previous-app-3-x-element1--blockClass vtex-app-2-x-element2 vtex-app-2-x-element2--blockClass vtex-previous-app-3-x-element2 vtex-previous-app-3-x-element2--blockClass'\n )\n })\n\n it('should add more than one migration if needed', () => {\n const CSS_HANDLES = ['element1', 'element2']\n const options = {\n migrationFrom: ['vtex.previous-app@2.0.0', 'vtex.previous-app@3.0.0'],\n }\n\n const { getByTestId } = renderComponent(CSS_HANDLES, options)\n\n expect(getByTestId('test-div').className).toBe(\n 'vtex-app-2-x-element1 vtex-app-2-x-element1--blockClass vtex-previous-app-2-x-element1 vtex-previous-app-2-x-element1--blockClass vtex-previous-app-3-x-element1 vtex-previous-app-3-x-element1--blockClass vtex-app-2-x-element2 vtex-app-2-x-element2--blockClass vtex-previous-app-2-x-element2 vtex-previous-app-2-x-element2--blockClass vtex-previous-app-3-x-element2 vtex-previous-app-3-x-element2--blockClass'\n )\n })\n\n it('doesnt repeat the migration if the current app happens to be the same as the migration one', () => {\n const CSS_HANDLES = ['element1', 'element2']\n const options = {\n migrationFrom: [\n 'vtex.previous-app@2.0.0',\n 'vtex.previous-app@3.0.0',\n 'vtex.app@2.1.0',\n ],\n }\n\n const { getByTestId } = renderComponent(CSS_HANDLES, options)\n\n expect(getByTestId('test-div').className).toBe(\n 'vtex-app-2-x-element1 vtex-app-2-x-element1--blockClass vtex-previous-app-2-x-element1 vtex-previous-app-2-x-element1--blockClass vtex-previous-app-3-x-element1 vtex-previous-app-3-x-element1--blockClass vtex-app-2-x-element2 vtex-app-2-x-element2--blockClass vtex-previous-app-2-x-element2 vtex-previous-app-2-x-element2--blockClass vtex-previous-app-3-x-element2 vtex-previous-app-3-x-element2--blockClass'\n )\n })\n })\n})\n\n```"
}
] |
code_css-handles_37663aa3
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of css-handles/react/hooks/useExtension.tsx from the css-handles VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\n// @ts-expect-error - private API\nimport { useRuntime, useTreePath } from 'vtex.render-runtime'\n\n/** This code has been copied and adapted from vtex.render-runtime,\n * while it doesn't export this hook */\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\ninterface Extension {\n /* eslint-disable @typescript-eslint/no-explicit-any */\n props?: Record<string, any>\n component?: string\n [key: string]: any\n}\n\nexport const useExtension = ({ children }: Options = {}): Extension | null => {\n // @ts-expect-error - private API\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 as Extension) || null\n}\n\n```"
}
] |
code_css-handles_e1398510
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of css-handles/react/modules/customClasses.ts from the css-handles VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { CustomClassValue } from '../CssHandlesTypes'\n\nexport type ComputedCustomClass = {\n toApplyModifiers: string[]\n classNames: string[]\n}\n\nexport function computeCustomClassValue(customClass: CustomClassValue) {\n customClass = Array.isArray(customClass) ? customClass : [customClass]\n\n return customClass.filter(Boolean).reduce<ComputedCustomClass>(\n (acc, className) => {\n if (typeof className === 'string') {\n acc.classNames.push(className)\n\n return acc\n }\n\n const names = className.name.split(' ')\n\n acc.classNames.push(...names)\n\n if (className.applyModifiers) {\n acc.toApplyModifiers.push(...names)\n }\n\n return acc\n },\n { toApplyModifiers: [], classNames: [] }\n )\n}\n\n```"
}
] |
code_css-handles_7c94c645
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of css-handles/react/modules/modifier.ts from the css-handles VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nconst INVALID_MODIFIER_PATTERN = /[^A-z0-9-]/\n\nconst MODIFIER_ERROR_LOG_DELAY = 3000\n\n/** Simplified debounce */\nfunction debounce(fn: () => void, delay: number) {\n let timeout: NodeJS.Timeout | undefined\n\n return () => {\n if (timeout) {\n clearTimeout(timeout)\n timeout = undefined\n }\n\n timeout = setTimeout(fn, delay)\n }\n}\n\ntype InvalidModifier = unknown\n\nconst invalidModifiers = new Set<InvalidModifier>([])\n\n// Useful for testing purposes\nexport const resetInvalidModifiers = () => {\n invalidModifiers.clear()\n}\n\nconst displayModifierErrors = debounce(() => {\n console.error(\n `Invalid CSS modifiers. All modifiers should be strings, and only contain letters, numbers, or -. Found: ${Array.from(\n invalidModifiers.values()\n ).join(', ')}`\n )\n invalidModifiers.clear()\n}, MODIFIER_ERROR_LOG_DELAY)\n\n/** Accumulates modifier errors to log them on a single error,\n * rather than a potentially huge wall of errors.\n */\nfunction logModifierError(modifier: InvalidModifier) {\n if (process.env.NODE_ENV === 'production') {\n return\n }\n\n invalidModifiers.add(modifier)\n displayModifierErrors()\n}\n\nexport const validateModifier = (modifier: string) => {\n if (typeof modifier !== 'string') {\n logModifierError(modifier)\n\n return false\n }\n\n /* This is not an error, so doesn't log any message, but should\n * invalidate the current modifier and not include it */\n if (modifier === '') {\n return false\n }\n\n if (INVALID_MODIFIER_PATTERN.test(modifier)) {\n logModifierError(modifier)\n\n return false\n }\n\n return true\n}\n\n```"
}
] |
code_minicart_50a77f54
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of minicart/messages/sl.json from the minicart VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"admin/editor.minicart.title\": \"Mini košarica\",\n \"admin/editor.minicart.description\": \"Enostavna mini košarica, ki kaže vse izdelke, ki ste jih dodali notri\",\n \"admin/editor.minicart.showDiscount.title\": \"Kaže količino prihranjenega denarja\",\n \"admin/editor.minicart.iconLabel.title\": \"Besedilo, ki se pokaže zraven ikone\",\n \"admin/editor.minicart.labelMiniCartEmpty.title\": \"Besedilo, ki se prikaže, ko je mini košarica prazna\",\n \"admin/editor.minicart.linkButtonFinishShopping.title\": \"Povezava za preusmeritev, ko kliknete na gumb Pojdi na plačilo\",\n \"admin/editor.minicart.labelButtonFinishShopping.title\": \"Besedilo, ki se prikaže v gumbu zaključi nakupovanje\",\n \"admin/editor.minicart.showShippingCost.title\": \"Kaže stroške odpošiljanja nad nogo\",\n \"admin/editor.minicart.type.title\": \"Vrsta mini košarice\",\n \"admin/editor.minicart.type.popup\": \"Pojavno\",\n \"admin/editor.minicart.type.sidebar\": \"Stranska vrstica\",\n \"store/finish-shopping-button-label\": \"Pojdite na plačilo\",\n \"store/minicart-empty\": \"Vaša košarica je prazna!\",\n \"store/sidebar-title\": \"Moja mini košarica\",\n \"store/minicart-content-footer-discount\": \"Shrani\",\n \"store/minicart.error-removal\": \"Odstranjevanje izdelka ni uspelo, poskusite znova\",\n \"store/minicart.shipping-cost\": \"Skupni stroški odpošiljanja\",\n \"store/minicart.checkout-failure\": \"Nekaj je šlo narobe. Poskusite znova.\",\n \"store/minicart.go-to-checkout\": \"Pojdite na plačilo\",\n \"store/minicart.empty-state\": \"Vaša košarica je prazna.\",\n \"store/minicart.title\": \"Košarica\"\n}\n\n```"
}
] |
code_minicart_cbb34ad9
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of minicart/messages/hu.json from the minicart VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"admin/editor.minicart.title\": \"Mini kosár\",\n \"admin/editor.minicart.description\": \"Egyszerű mini kosár, amely megjeleníti az összes hozzáadott terméket\",\n \"admin/editor.minicart.showDiscount.title\": \"A megtakarított összeg megjelenítése\",\n \"admin/editor.minicart.iconLabel.title\": \"Az ikon mellett megjelenő szöveg\",\n \"admin/editor.minicart.labelMiniCartEmpty.title\": \"A szöveg akkor jelenik meg, ha a mini kosár üres\",\n \"admin/editor.minicart.linkButtonFinishShopping.title\": \"Az átirányításra mutató hivatkozás az Ugrás a pénztárhoz gombra kattintást követően\",\n \"admin/editor.minicart.labelButtonFinishShopping.title\": \"A vásárlás befejezése gombban megjelenő szöveg\",\n \"admin/editor.minicart.showShippingCost.title\": \"A szállítási költség megjelenítése a lábléc felett\",\n \"admin/editor.minicart.type.title\": \"Mini kosár típusa\",\n \"admin/editor.minicart.type.popup\": \"Előugró ablak\",\n \"admin/editor.minicart.type.sidebar\": \"Oldalsáv\",\n \"store/finish-shopping-button-label\": \"Ugrás a pénztárhoz\",\n \"store/minicart-empty\": \"A kosár üres!\",\n \"store/sidebar-title\": \"Saját mini kosár\",\n \"store/minicart-content-footer-discount\": \"Mentés\",\n \"store/minicart.error-removal\": \"A tétel eltávolítása sikertelen, próbálja újra\",\n \"store/minicart.shipping-cost\": \"Teljes szállítási költség\",\n \"store/minicart.checkout-failure\": \"Hiba történt. Próbálja újra.\",\n \"store/minicart.go-to-checkout\": \"Ugrás a pénztárhoz\",\n \"store/minicart.empty-state\": \"A kosár üres.\",\n \"store/minicart.title\": \"Kosár\"\n}\n\n```"
}
] |
code_minicart_af8a4c7e
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of minicart/messages/nl.json from the minicart VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"admin/editor.minicart.title\": \"Mini winkelwagen\",\n \"admin/editor.minicart.description\": \"Een eenvoudige mini winkelwagen die alle producten laat zien die eraan zijn toegevoegd\",\n \"admin/editor.minicart.showDiscount.title\": \"Toon de hoeveelheid gespaard geld\",\n \"admin/editor.minicart.iconLabel.title\": \"Tekst die naast het pictogram moet verschijnen\",\n \"admin/editor.minicart.labelMiniCartEmpty.title\": \"Tekst die moet verschijnen als de mini cart leeg is\",\n \"admin/editor.minicart.linkButtonFinishShopping.title\": \"Link naar omleiding nadat u op de knop ga naar afrekenen hebt geklikt\",\n \"admin/editor.minicart.labelButtonFinishShopping.title\": \"Tekst die moet verschijnen in de knop winkelen voltooien\",\n \"admin/editor.minicart.showShippingCost.title\": \"Toon de verzendkosten boven de voettekst\",\n \"admin/editor.minicart.type.title\": \"Type mini winkelwagen\",\n \"admin/editor.minicart.type.popup\": \"Popup\",\n \"admin/editor.minicart.type.sidebar\": \"Sidebar\",\n \"store/finish-shopping-button-label\": \"Ga naar de kassa\",\n \"store/minicart-empty\": \"Uw winkelwagen is leeg!\",\n \"store/sidebar-title\": \"Mijn mini winkelwagen\",\n \"store/minicart-content-footer-discount\": \"Opslaan\",\n \"store/minicart.error-removal\": \"Itemverwijdering is mislukt, probeer het opnieuw\",\n \"store/minicart.shipping-cost\": \"Totale verzendkosten\",\n \"store/minicart.checkout-failure\": \"Er is iets misgegaan. Probeer het nog eens.\",\n \"store/minicart.go-to-checkout\": \"Ga naar de kassa\",\n \"store/minicart.empty-state\": \"Uw winkelwagen is leeg.\",\n \"store/minicart.title\": \"Winkelwagen\"\n}\n\n```"
}
] |
code_minicart_e2ce9a64
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of minicart/messages/ja.json from the minicart VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"admin/editor.minicart.title\": \"ミニカート\",\n \"admin/editor.minicart.description\": \"追加されたすべての製品を表示するシンプルなミニカート\",\n \"admin/editor.minicart.showDiscount.title\": \"節約できた金額を表示する\",\n \"admin/editor.minicart.iconLabel.title\": \"アイコンの隣に表示されるテキスト\",\n \"admin/editor.minicart.labelMiniCartEmpty.title\": \"ミニカートが空の時に表示されるテキスト\",\n \"admin/editor.minicart.linkButtonFinishShopping.title\": \"[チェックアウトに進む] ボタンをクリックしたときのリダイレクト先リンク\",\n \"admin/editor.minicart.labelButtonFinishShopping.title\": \"買い物を終えるボタンの中で表示されるテキスト\",\n \"admin/editor.minicart.showShippingCost.title\": \"フッターの上に発送コストを表示する\",\n \"admin/editor.minicart.type.title\": \"ミニカートタイプ\",\n \"admin/editor.minicart.type.popup\": \"ポップアップ\",\n \"admin/editor.minicart.type.sidebar\": \"サイドバー\",\n \"store/finish-shopping-button-label\": \"チェックアウトに進む\",\n \"store/minicart-empty\": \"カートは空です!\",\n \"store/sidebar-title\": \"マイミニカート\",\n \"store/minicart-content-footer-discount\": \"保存\",\n \"store/minicart.error-removal\": \"項目を削除できませんでした。もう一度やり直してください\",\n \"store/minicart.shipping-cost\": \"合計発送コスト\",\n \"store/minicart.checkout-failure\": \"エラーが発生しました。もう一度やり直してください。\",\n \"store/minicart.go-to-checkout\": \"チェックアウトに進む\",\n \"store/minicart.empty-state\": \"カートは空です。\",\n \"store/minicart.title\": \"カート\"\n}\n\n```"
}
] |
code_minicart_5b2238ae
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of minicart/messages/de.json from the minicart VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"admin/editor.minicart.title\": \"Mini-Wagen\",\n \"admin/editor.minicart.description\": \"Ein einfacher Mini-Wagen, der alle hinzugefügten Produkte anzeigt\",\n \"admin/editor.minicart.showDiscount.title\": \"Zeigen Sie die Menge des gesparten Geldes an\",\n \"admin/editor.minicart.iconLabel.title\": \"Text, der neben dem Symbol erscheint\",\n \"admin/editor.minicart.labelMiniCartEmpty.title\": \"Text, der erscheint, wenn der Mini-Wagen leer ist\",\n \"admin/editor.minicart.linkButtonFinishShopping.title\": \"Link zur Weiterleitung nach Klicken auf die Schaltfläche Zur Kasse gehen\",\n \"admin/editor.minicart.labelButtonFinishShopping.title\": \"Text, der in der Schaltfläche Einkauf beenden erscheint\",\n \"admin/editor.minicart.showShippingCost.title\": \"Die Versandkosten über der Fußzeile anzeigen\",\n \"admin/editor.minicart.type.title\": \"Mini-Wagentyp\",\n \"admin/editor.minicart.type.popup\": \"Pop Up\",\n \"admin/editor.minicart.type.sidebar\": \"Seitenleiste\",\n \"store/finish-shopping-button-label\": \"Zur Kasse gehen\",\n \"store/minicart-empty\": \"Ihr Einkaufswagen ist leer!\",\n \"store/sidebar-title\": \"Mein Mini-Wagen\",\n \"store/minicart-content-footer-discount\": \"Speichern\",\n \"store/minicart.error-removal\": \"Das Entfernen des Artikels ist fehlgeschlagen, bitte versuchen Sie es erneut\",\n \"store/minicart.shipping-cost\": \"Gesamte Versandkosten\",\n \"store/minicart.checkout-failure\": \"Etwas ist schief gelaufen, bitte versuchen Sie es später noch einmal.\",\n \"store/minicart.go-to-checkout\": \"Zur Kasse gehen\",\n \"store/minicart.empty-state\": \"Ihr Einkaufswagen ist leer.\",\n \"store/minicart.title\": \"Einkaufswagen\"\n}\n\n```"
}
] |
code_minicart_393949e4
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of minicart/messages/ru.json from the minicart VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"admin/editor.minicart.title\": \"Мини-корзина\",\n \"admin/editor.minicart.description\": \"Простая мини-корзина, в которой показаны все товары\",\n \"admin/editor.minicart.showDiscount.title\": \"Показать количество сэкономленных денег\",\n \"admin/editor.minicart.iconLabel.title\": \"Текст, который появляется рядом со значком\",\n \"admin/editor.minicart.labelMiniCartEmpty.title\": \"Текст, который появляется, когда мини-корзина пуста\",\n \"admin/editor.minicart.linkButtonFinishShopping.title\": \"Ссылка для переадресации после нажатия кнопки Перейти к оформлению заказа\",\n \"admin/editor.minicart.labelButtonFinishShopping.title\": \"Текст, который будет отображаться на кнопке завершения покупки\",\n \"admin/editor.minicart.showShippingCost.title\": \"Показать стоимость доставки выше нижнего колонтитула\",\n \"admin/editor.minicart.type.title\": \"Тип мини-корзины\",\n \"admin/editor.minicart.type.popup\": \"Всплывающее окно\",\n \"admin/editor.minicart.type.sidebar\": \"Боковая панель\",\n \"store/finish-shopping-button-label\": \"Перейти к оформлению заказа\",\n \"store/minicart-empty\": \"Ваша корзина пуста!\",\n \"store/sidebar-title\": \"Моя мини-корзина\",\n \"store/minicart-content-footer-discount\": \"Сохранить\",\n \"store/minicart.error-removal\": \"Не удалось удалить товар. Повторите попытку\",\n \"store/minicart.shipping-cost\": \"Общая стоимость доставки\",\n \"store/minicart.checkout-failure\": \"Что-то пошло не так. Пожалуйста, попробуйте еще раз.\",\n \"store/minicart.go-to-checkout\": \"Перейти к оформлению заказа\",\n \"store/minicart.empty-state\": \"Ваша корзина пуста.\",\n \"store/minicart.title\": \"Корзина\"\n}\n\n```"
}
] |
code_minicart_6385f383
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of minicart/messages/pl.json from the minicart VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"admin/editor.minicart.title\": \"Mini koszyk\",\n \"admin/editor.minicart.description\": \"Prosty mini koszyk, który pokazuje wszystkie produkty dodane do niego\",\n \"admin/editor.minicart.showDiscount.title\": \"Pokaż sumę zaoszczędzonych pieniędzy\",\n \"admin/editor.minicart.iconLabel.title\": \"Tekst pojawiający się obok ikony\",\n \"admin/editor.minicart.labelMiniCartEmpty.title\": \"Tekst pojawiający się, gdy mini koszyk jest pusty\",\n \"admin/editor.minicart.linkButtonFinishShopping.title\": \"Link do przekierowania po kliknięciu przycisku Idź do kasy\",\n \"admin/editor.minicart.labelButtonFinishShopping.title\": \"Tekst pojawiający się w przycisku zakończ zakupy\",\n \"admin/editor.minicart.showShippingCost.title\": \"Pokaż koszt wysyłki powyżej stopki\",\n \"admin/editor.minicart.type.title\": \"Typ mini koszyka\",\n \"admin/editor.minicart.type.popup\": \"Wyskakujące okno\",\n \"admin/editor.minicart.type.sidebar\": \"Pasek boczny\",\n \"store/finish-shopping-button-label\": \"Idź do kasy\",\n \"store/minicart-empty\": \"Twój koszyk jest pusty!\",\n \"store/sidebar-title\": \"Mój mini koszyk\",\n \"store/minicart-content-footer-discount\": \"Zapisz\",\n \"store/minicart.error-removal\": \"Niepowodzenie usunięcia pozycji, spróbuj ponownie\",\n \"store/minicart.shipping-cost\": \"Ogólny koszt wysyłki\",\n \"store/minicart.checkout-failure\": \"Coś poszło nie tak. Spróbuj ponownie.\",\n \"store/minicart.go-to-checkout\": \"Idź do kasy\",\n \"store/minicart.empty-state\": \"Twój koszyk jest pusty.\",\n \"store/minicart.title\": \"Koszyk\"\n}\n\n```"
}
] |
code_minicart_0e56f8e7
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of minicart/messages/uk.json from the minicart VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"admin/editor.minicart.title\": \"Міні-кошик\",\n \"admin/editor.minicart.description\": \"Невеличкий міні-кошик, який показує всі додані продукти\",\n \"admin/editor.minicart.showDiscount.title\": \"Показує кількість зекономлених грошей\",\n \"admin/editor.minicart.iconLabel.title\": \"Текст, який з’явиться поруч із піктограмою\",\n \"admin/editor.minicart.labelMiniCartEmpty.title\": \"Текст, який з’являється, коли міні-кошик порожній\",\n \"admin/editor.minicart.linkButtonFinishShopping.title\": \"Посилання для переадресації після натискання кнопки Перейти до оформлення замовлення\",\n \"admin/editor.minicart.labelButtonFinishShopping.title\": \"Текст, який відображатиметься у кнопці завершення покупки\",\n \"admin/editor.minicart.showShippingCost.title\": \"Показати вартість доставки вище нижнього колонтитулу\",\n \"admin/editor.minicart.type.title\": \"Тип міні-кошика\",\n \"admin/editor.minicart.type.popup\": \"Спливаючий\",\n \"admin/editor.minicart.type.sidebar\": \"Бічна панель\",\n \"store/finish-shopping-button-label\": \"Перейти до оформлення замовлення\",\n \"store/minicart-empty\": \"Ваш кошик порожній!\",\n \"store/sidebar-title\": \"Мій міні-кошик\",\n \"store/minicart-content-footer-discount\": \"Зберегти\",\n \"store/minicart.error-removal\": \"Видалення елемента не відбулося. Повторіть спробу\",\n \"store/minicart.shipping-cost\": \"Загальна вартість доставки\",\n \"store/minicart.checkout-failure\": \"Щось пішло не так, будь ласка, спробуйте ще раз.\",\n \"store/minicart.go-to-checkout\": \"Перейти до оформлення замовлення\",\n \"store/minicart.empty-state\": \"Ваш кошик порожній.\",\n \"store/minicart.title\": \"Кошик\"\n}\n\n```"
}
] |
code_minicart_4e9c8e50
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of minicart/messages/fi.json from the minicart VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"admin/editor.minicart.title\": \"Miniostoskori\",\n \"admin/editor.minicart.description\": \"Yksinkertainen miniostoskori, joka näyttää kaikki siihen lisätyt tuotteet\",\n \"admin/editor.minicart.showDiscount.title\": \"Näytä säästetyn rahan määrä\",\n \"admin/editor.minicart.iconLabel.title\": \"Kuvakkeen vieressä näkyvä teksti\",\n \"admin/editor.minicart.labelMiniCartEmpty.title\": \"Teksti, joka näkyy miniostoskorin ollessa tyhjä\",\n \"admin/editor.minicart.linkButtonFinishShopping.title\": \"Linkki, joka uudelleenohjaa, kun Siirry maksamaan -painiketta napsautetaan\",\n \"admin/editor.minicart.labelButtonFinishShopping.title\": \"Valmis-painikkeessa näkyvä teksti\",\n \"admin/editor.minicart.showShippingCost.title\": \"Näytä toimituskulu alatunnisteen yläpuolella\",\n \"admin/editor.minicart.type.title\": \"Miniostoskorin tyyppi\",\n \"admin/editor.minicart.type.popup\": \"Ponnahdusikkuna\",\n \"admin/editor.minicart.type.sidebar\": \"Sivupalkki\",\n \"store/finish-shopping-button-label\": \"Siirry kassalle\",\n \"store/minicart-empty\": \"Ostoskorisi on tyhjä!\",\n \"store/sidebar-title\": \"Oma miniostoskorini\",\n \"store/minicart-content-footer-discount\": \"Tallenna\",\n \"store/minicart.error-removal\": \"Tuotteen poistaminen epäonnistui, yritä uudelleen\",\n \"store/minicart.shipping-cost\": \"Toimituskulu yhteensä\",\n \"store/minicart.checkout-failure\": \"Jotain meni vikaan. Yritä uudelleen.\",\n \"store/minicart.go-to-checkout\": \"Siirry kassalle\",\n \"store/minicart.empty-state\": \"Ostoskorisi on tyhjä.\",\n \"store/minicart.title\": \"Ostoskori\"\n}\n\n```"
}
] |
code_minicart_a387d706
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of minicart/messages/sk.json from the minicart VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"admin/editor.minicart.title\": \"Mini košík\",\n \"admin/editor.minicart.description\": \"Jednoduchý malý vozík, ktorý zobrazuje všetky pridané produkty\",\n \"admin/editor.minicart.showDiscount.title\": \"Zobraziť ušetrené peniaze\",\n \"admin/editor.minicart.iconLabel.title\": \"Text sa zobrazí vedľa ikony\",\n \"admin/editor.minicart.labelMiniCartEmpty.title\": \"Text, ktorý sa objaví, keď je mini košík prázdny\",\n \"admin/editor.minicart.linkButtonFinishShopping.title\": \"Odkaz na presmerovanie po kliknutí na tlačidlo Prejsť k pokladni\",\n \"admin/editor.minicart.labelButtonFinishShopping.title\": \"Text sa zobrazí v tlačidle dokončenia nákupu\",\n \"admin/editor.minicart.showShippingCost.title\": \"Zobraziť prepravné náklady nad pätou strany\",\n \"admin/editor.minicart.type.title\": \"Typ mini košíka\",\n \"admin/editor.minicart.type.popup\": \"Vyskakovacie okno\",\n \"admin/editor.minicart.type.sidebar\": \"Bočný panel\",\n \"store/finish-shopping-button-label\": \"Prejsť k pokladni\",\n \"store/minicart-empty\": \"Váš košík je prázdny!\",\n \"store/sidebar-title\": \"Môj mini košík\",\n \"store/minicart-content-footer-discount\": \"Uložiť\",\n \"store/minicart.error-removal\": \"Odstránenie položky zlyhalo, skúste to znova\",\n \"store/minicart.shipping-cost\": \"Celkové náklady na dopravu\",\n \"store/minicart.checkout-failure\": \"Niečo sa nepodarilo. Skúste to znova.\",\n \"store/minicart.go-to-checkout\": \"Prejsť k pokladni\",\n \"store/minicart.empty-state\": \"Váš košík je prázdny.\",\n \"store/minicart.title\": \"Košík\"\n}\n\n```"
}
] |
code_minicart_4ac7d41b
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of minicart/messages/pt.json from the minicart VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"admin/editor.minicart.title\": \"Carrinho de compras\",\n \"admin/editor.minicart.description\": \"Um carrinho de compras que mostra todos os produtos adicionados a ele\",\n \"admin/editor.minicart.showDiscount.title\": \"Mostrar a quantidade de dinheiro economizado\",\n \"admin/editor.minicart.iconLabel.title\": \"Texto que irá aparecer ao lado do ícone\",\n \"admin/editor.minicart.labelMiniCartEmpty.title\": \"Texto que irá aparecer quando o carrinho estiver vazio\",\n \"admin/editor.minicart.linkButtonFinishShopping.title\": \"Link de redirecionamento ao clicar no botão de finalizar compra\",\n \"admin/editor.minicart.labelButtonFinishShopping.title\": \"Texto que irá aparecer no botão de finalizar compra\",\n \"admin/editor.minicart.showShippingCost.title\": \"Mostrar o valor do frete\",\n \"admin/editor.minicart.type.title\": \"Tipo de carrinho de compras\",\n \"admin/editor.minicart.type.popup\": \"Pop up\",\n \"admin/editor.minicart.type.sidebar\": \"Barra lateral\",\n \"store/finish-shopping-button-label\": \"Finalizar compra\",\n \"store/minicart-empty\": \"Seu carrinho está vazio!\",\n \"store/sidebar-title\": \"Meu carrinho\",\n \"store/minicart-content-footer-discount\": \"Economize\",\n \"store/minicart.error-removal\": \"Erro ao remover o item. Por favor, tente novamente.\",\n \"store/minicart.shipping-cost\": \"Valor do frete\",\n \"store/minicart.checkout-failure\": \"Algo deu errado. Por favor, tente novamente.\",\n \"store/minicart.go-to-checkout\": \"Ir para o checkout\",\n \"store/minicart.empty-state\": \"Seu carrinho está vazio.\",\n \"store/minicart.title\": \"Carrinho\"\n}\n\n```"
}
] |
code_minicart_b61f5c85
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of minicart/messages/en.json from the minicart VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"admin/editor.minicart.title\": \"Mini Cart\",\n \"admin/editor.minicart.description\": \"A simple mini cart that shows all products added to it\",\n \"admin/editor.minicart.showDiscount.title\": \"Show the quantity of saved money\",\n \"admin/editor.minicart.iconLabel.title\": \"Text to appear next to the icon\",\n \"admin/editor.minicart.labelMiniCartEmpty.title\": \"Text to appear when the mini cart is empty\",\n \"admin/editor.minicart.linkButtonFinishShopping.title\": \"Link to redirect after clicking in the Go to Checkout button\",\n \"admin/editor.minicart.labelButtonFinishShopping.title\": \"Text to appear in the finish shopping button\",\n \"admin/editor.minicart.showShippingCost.title\": \"Show the shipping cost above footer\",\n \"admin/editor.minicart.type.title\": \"Mini Cart Type\",\n \"admin/editor.minicart.type.popup\": \"Pop Up\",\n \"admin/editor.minicart.type.sidebar\": \"Sidebar\",\n \"store/finish-shopping-button-label\": \"Go to checkout\",\n \"store/minicart-empty\": \"Your cart is empty!\",\n \"store/sidebar-title\": \"My mini cart\",\n \"store/minicart-content-footer-discount\": \"Save\",\n \"store/minicart.error-removal\": \"Item removal failed, please try again\",\n \"store/minicart.shipping-cost\": \"Total shipping cost\",\n \"store/minicart.checkout-failure\": \"Something went wrong. Please, try again.\",\n \"store/minicart.go-to-checkout\": \"Go to checkout\",\n \"store/minicart.empty-state\": \"Your cart is empty.\",\n \"store/minicart.title\": \"Cart\"\n}\n\n```"
}
] |
code_minicart_daba896f
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of minicart/messages/it.json from the minicart VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"admin/editor.minicart.title\": \"Mini Carrello\",\n \"admin/editor.minicart.description\": \"Un semplice mini carrello che mostra tutti i prodotti aggiunti\",\n \"admin/editor.minicart.showDiscount.title\": \"Mostra l'ammontare del denaro risparmiato\",\n \"admin/editor.minicart.iconLabel.title\": \"Testo che appare accanto all'icona\",\n \"admin/editor.minicart.labelMiniCartEmpty.title\": \"Testo che appare quando il mini carrello è vuoto\",\n \"admin/editor.minicart.linkButtonFinishShopping.title\": \"Link di reindirizzamento quando si clicca sul tasto \\\"Vai al checkout\\\"\",\n \"admin/editor.minicart.labelButtonFinishShopping.title\": \"Testo da visualizzare sul tasto \\\"Termina l'acquisto\\\"\",\n \"admin/editor.minicart.showShippingCost.title\": \"Mostra i costi di spedizione sopra al piè di pagina\",\n \"admin/editor.minicart.type.title\": \"Tipo di Mini Carrello\",\n \"admin/editor.minicart.type.popup\": \"Pop Up\",\n \"admin/editor.minicart.type.sidebar\": \"Barra laterale\",\n \"store/finish-shopping-button-label\": \"Vai alla cassa\",\n \"store/minicart-empty\": \"Il tuo carrello è vuoto!\",\n \"store/sidebar-title\": \"Il mio mini carrello\",\n \"store/minicart-content-footer-discount\": \"Salvare\",\n \"store/minicart.error-removal\": \"Rimozione dell'articolo non riuscita, si prega di riprovare\",\n \"store/minicart.shipping-cost\": \"Costo totale della spedizione\",\n \"store/minicart.checkout-failure\": \"Qualcosa è andato storto, si prega di riprovare.\",\n \"store/minicart.go-to-checkout\": \"Vai alla cassa\",\n \"store/minicart.empty-state\": \"Il tuo carrello è vuoto.\",\n \"store/minicart.title\": \"Carrello\"\n}\n\n```"
}
] |
code_minicart_5cdc711f
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of minicart/messages/fr.json from the minicart VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"admin/editor.minicart.title\": \"Mini panier\",\n \"admin/editor.minicart.description\": \"Un simple mini panier qui montre tous les produits qui y sont ajoutés\",\n \"admin/editor.minicart.showDiscount.title\": \"Afficher le montant économisé\",\n \"admin/editor.minicart.iconLabel.title\": \"Texte affiché à côté de l’icône\",\n \"admin/editor.minicart.labelMiniCartEmpty.title\": \"Texte affiché lorsque le mini chariot est vide\",\n \"admin/editor.minicart.linkButtonFinishShopping.title\": \"Lien de redirection après avoir cliqué sur le bouton Paiement\",\n \"admin/editor.minicart.labelButtonFinishShopping.title\": \"Texte affiché avec le bouton Terminer les achats\",\n \"admin/editor.minicart.showShippingCost.title\": \"Afficher les frais d’expédition en bas de page\",\n \"admin/editor.minicart.type.title\": \"Type Mini panier\",\n \"admin/editor.minicart.type.popup\": \"Pop up\",\n \"admin/editor.minicart.type.sidebar\": \"Barre latérale\",\n \"store/finish-shopping-button-label\": \"Payer\",\n \"store/minicart-empty\": \"Votre panier est vide !\",\n \"store/sidebar-title\": \"Mon mini panier\",\n \"store/minicart-content-footer-discount\": \"Enregistrer\",\n \"store/minicart.error-removal\": \"Le retrait de l’article a échoué, veuillez réessayer\",\n \"store/minicart.shipping-cost\": \"Total des frais de port\",\n \"store/minicart.checkout-failure\": \"Tentative échouée. Veuillez réessayez.\",\n \"store/minicart.go-to-checkout\": \"Payer\",\n \"store/minicart.empty-state\": \"Votre panier est vide.\",\n \"store/minicart.title\": \"Panier\"\n}\n\n```"
}
] |
code_minicart_d7a28395
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of minicart/messages/el.json from the minicart VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"admin/editor.minicart.title\": \"Μίνι Καλάθι\",\n \"admin/editor.minicart.description\": \"Απλό μίνι καλάθι που δείχνει όλα τα προϊόντα που προστίθενται σε αυτό\",\n \"admin/editor.minicart.showDiscount.title\": \"Προβολή της ποσότητας αποταμιευμένων χρημάτων\",\n \"admin/editor.minicart.iconLabel.title\": \"Κείμενο που εμφανίζεται δίπλα στο εικονίδιο\",\n \"admin/editor.minicart.labelMiniCartEmpty.title\": \"Κείμενο που εμφανίζεται όταν το μίνι καλάθι είναι άδειο\",\n \"admin/editor.minicart.linkButtonFinishShopping.title\": \"Σύνδεσμος για ανακατεύθυνση αφού γίνει κλικ στο πλήκτρο Μετάβαση στην Ολοκλήρωση Αγοράς\",\n \"admin/editor.minicart.labelButtonFinishShopping.title\": \"Κείμενο που εμφανίζεται στο πλήκτρο ολοκλήρωσης των αγορών\",\n \"admin/editor.minicart.showShippingCost.title\": \"Προβολή του κόστους αγορών πάνω από το υποσέλιδο\",\n \"admin/editor.minicart.type.title\": \"Τύπος Μίνι Καλαθιού\",\n \"admin/editor.minicart.type.popup\": \"Αναδυόμενο\",\n \"admin/editor.minicart.type.sidebar\": \"Πλευρική γραμμή\",\n \"store/finish-shopping-button-label\": \"Μεταβείτε στην ολοκλήρωση αγοράς\",\n \"store/minicart-empty\": \"Το καλάθι σας είναι άδειο!\",\n \"store/sidebar-title\": \"Το δικό μου μίνι καλάθι\",\n \"store/minicart-content-footer-discount\": \"Αποθήκευση\",\n \"store/minicart.error-removal\": \"Η αφαίρεση προϊόντος απέτυχε, δοκιμάστε ξανά\",\n \"store/minicart.shipping-cost\": \"Συνολικό κόστος αποστολής\",\n \"store/minicart.checkout-failure\": \"Κάτι πήγε στραβά. Δοκιμάστε ξανά.\",\n \"store/minicart.go-to-checkout\": \"Μεταβείτε στην ολοκλήρωση αγοράς\",\n \"store/minicart.empty-state\": \"Το καλάθι σας είναι άδειο.\",\n \"store/minicart.title\": \"Καλάθι\"\n}\n\n```"
}
] |
code_minicart_aabf0083
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of minicart/messages/bg.json from the minicart VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"admin/editor.minicart.title\": \"Мини количка\",\n \"admin/editor.minicart.description\": \"Проста мини количка, която показва всички добавени в нея продукти\",\n \"admin/editor.minicart.showDiscount.title\": \"Показва сумата спестени пари\",\n \"admin/editor.minicart.iconLabel.title\": \"Текст, който се появява до иконата\",\n \"admin/editor.minicart.labelMiniCartEmpty.title\": \"Текст, който се появява ако мини количката е празна\",\n \"admin/editor.minicart.linkButtonFinishShopping.title\": \"Линк за пренасочване при натискане на бутона Преминаване към финализиране\",\n \"admin/editor.minicart.labelButtonFinishShopping.title\": \"Текст, който се появява в бутона за завършване на покупката\",\n \"admin/editor.minicart.showShippingCost.title\": \"Показване на цената за доставка над долния колонтитул\",\n \"admin/editor.minicart.type.title\": \"Вид на мини количката\",\n \"admin/editor.minicart.type.popup\": \"Изскачащ\",\n \"admin/editor.minicart.type.sidebar\": \"Странична лента\",\n \"store/finish-shopping-button-label\": \"Преминаване към финализиране\",\n \"store/minicart-empty\": \"Вашата количка е празна!\",\n \"store/sidebar-title\": \"Моята мини количка\",\n \"store/minicart-content-footer-discount\": \"Запазване\",\n \"store/minicart.error-removal\": \"Неуспешно отстраняване на елемента. Моля, опитайте отново\",\n \"store/minicart.shipping-cost\": \"Обща стойност на доставката\",\n \"store/minicart.checkout-failure\": \"Нещо се обърка, моля, опитайте отново.\",\n \"store/minicart.go-to-checkout\": \"Преминаване към финализиране\",\n \"store/minicart.empty-state\": \"Вашата количка е празна.\",\n \"store/minicart.title\": \"Количка\"\n}\n\n```"
}
] |
code_minicart_6783ffdf
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of minicart/messages/ro.json from the minicart VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"admin/editor.minicart.title\": \"Mini Cart\",\n \"admin/editor.minicart.description\": \"Un mini cart simplu care afișează toate produsele adăugate în el\",\n \"admin/editor.minicart.showDiscount.title\": \"Arată cantitatea banilor economisiți\",\n \"admin/editor.minicart.iconLabel.title\": \"Text care să apară lângă iconiță\",\n \"admin/editor.minicart.labelMiniCartEmpty.title\": \"Text care să apară când mini cart-ul este gol\",\n \"admin/editor.minicart.linkButtonFinishShopping.title\": \"Link pentru redirecționare după apăsarea butonului Go to Checkout\",\n \"admin/editor.minicart.labelButtonFinishShopping.title\": \"Text care să apară în butonul Finish Shopping\",\n \"admin/editor.minicart.showShippingCost.title\": \"Arată costul de expediere deasupra textului de subsol\",\n \"admin/editor.minicart.type.title\": \"Tip Mini Cart\",\n \"admin/editor.minicart.type.popup\": \"Pop Up\",\n \"admin/editor.minicart.type.sidebar\": \"Bară laterală\",\n \"store/finish-shopping-button-label\": \"Finalizează comanda\",\n \"store/minicart-empty\": \"Coșul tău de cumpărături este gol!\",\n \"store/sidebar-title\": \"Mini cart-ul meu\",\n \"store/minicart-content-footer-discount\": \"Salvează\",\n \"store/minicart.error-removal\": \"E eșuat ștergerea articolului, te rugăm încearcă din nou\",\n \"store/minicart.shipping-cost\": \"Total costuri livrare\",\n \"store/minicart.checkout-failure\": \"A apărut o eroare. Te rugăm să încerci din nou.\",\n \"store/minicart.go-to-checkout\": \"Finalizează comanda\",\n \"store/minicart.empty-state\": \"Coșul tău de cumpărături este gol.\",\n \"store/minicart.title\": \"Coș de cumpărături\"\n}\n\n```"
}
] |
code_minicart_42501c0d
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of minicart/messages/ca.json from the minicart VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"admin/editor.minicart.title\": \"Minicarretó\",\n \"admin/editor.minicart.description\": \"Un minicarretó senzill en què es mostren tots els productes que hi heu afegit\",\n \"admin/editor.minicart.showDiscount.title\": \"Mostra la quantitat de diners estalviats\",\n \"admin/editor.minicart.iconLabel.title\": \"Text que es mostra al costat de la icona\",\n \"admin/editor.minicart.labelMiniCartEmpty.title\": \"Text que es mostra quan el minicarretó està buit\",\n \"admin/editor.minicart.linkButtonFinishShopping.title\": \"Enllaç de redirecció després de fer clic al botó Ves a la caixa\",\n \"admin/editor.minicart.labelButtonFinishShopping.title\": \"Text que es mostra al botó per finalitzar la compra\",\n \"admin/editor.minicart.showShippingCost.title\": \"Mostra el cost de l'enviament sobre el peu de pàgina\",\n \"admin/editor.minicart.type.title\": \"Tipus de minicarretó\",\n \"admin/editor.minicart.type.popup\": \"Emergent\",\n \"admin/editor.minicart.type.sidebar\": \"Barra lateral\",\n \"store/finish-shopping-button-label\": \"Ves a la caixa\",\n \"store/minicart-empty\": \"El carretó és buit\",\n \"store/sidebar-title\": \"El meu minicarretó\",\n \"store/minicart-content-footer-discount\": \"Desa\",\n \"store/minicart.error-removal\": \"No s'ha pogut suprimir l'element. Torneu-ho a provar.\",\n \"store/minicart.shipping-cost\": \"Cost de l'enviament total\",\n \"store/minicart.checkout-failure\": \"Alguna cosa no ha anat bé. Torneu-ho a provar.\",\n \"store/minicart.go-to-checkout\": \"Ves a la caixa\",\n \"store/minicart.empty-state\": \"El carretó és buit.\",\n \"store/minicart.title\": \"Carretó\"\n}\n\n```"
}
] |
code_minicart_e44a6380
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of minicart/messages/context.json from the minicart VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"admin/editor.minicart.title\": \"admin/editor.minicart.title\",\n \"admin/editor.minicart.description\": \"admin/editor.minicart.description\",\n \"admin/editor.minicart.showDiscount.title\": \"admin/editor.minicart.showDiscount.title\",\n \"admin/editor.minicart.iconLabel.title\": \"admin/editor.minicart.iconLabel.title\",\n \"admin/editor.minicart.labelMiniCartEmpty.title\": \"admin/editor.minicart.labelMiniCartEmpty.title\",\n \"admin/editor.minicart.linkButtonFinishShopping.title\": \"admin/editor.minicart.linkButtonFinishShopping.title\",\n \"admin/editor.minicart.labelButtonFinishShopping.title\": \"admin/editor.minicart.labelButtonFinishShopping.title\",\n \"admin/editor.minicart.showShippingCost.title\": \"admin/editor.minicart.showShippingCost.title\",\n \"admin/editor.minicart.type.title\": \"admin/editor.minicart.type.title\",\n \"admin/editor.minicart.type.popup\": \"admin/editor.minicart.type.popup\",\n \"admin/editor.minicart.type.sidebar\": \"admin/editor.minicart.type.sidebar\",\n \"store/finish-shopping-button-label\": \"store/finish-shopping-button-label\",\n \"store/minicart-empty\": \"store/minicart-empty\",\n \"store/sidebar-title\": \"store/sidebar-title\",\n \"store/minicart-content-footer-discount\": \"store/minicart-content-footer-discount\",\n \"store/minicart.error-removal\": \"store/minicart.error-removal\",\n \"store/minicart.shipping-cost\": \"store/minicart.shipping-cost\",\n \"store/minicart.checkout-failure\": \"Message showed when there is a problem to a request to the server.\",\n \"store/minicart.go-to-checkout\": \"Go to checkout\",\n \"store/minicart.empty-state\": \"store/cart.empty-state\",\n \"store/minicart.title\": \"store/cart.empty-state\"\n}\n\n```"
}
] |
code_minicart_84a185e6
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of minicart/messages/ko.json from the minicart VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"admin/editor.minicart.title\": \"미니 카트\",\n \"admin/editor.minicart.description\": \"추가된 모든 제품을 보여주는 간단한 미니 카트\",\n \"admin/editor.minicart.showDiscount.title\": \"저축 금액 표시\",\n \"admin/editor.minicart.iconLabel.title\": \"아이콘 옆에 표시할 텍스트\",\n \"admin/editor.minicart.labelMiniCartEmpty.title\": \"미니 카트가 비어있을 때 표시되는 텍스트\",\n \"admin/editor.minicart.linkButtonFinishShopping.title\": \"결제 화면으로 가기 버튼을 클릭한 후 리디렉션할 링크\",\n \"admin/editor.minicart.labelButtonFinishShopping.title\": \"쇼핑 완료 버튼에 표시할 텍스트\",\n \"admin/editor.minicart.showShippingCost.title\": \"푸터 위에 배송비 표시\",\n \"admin/editor.minicart.type.title\": \"미니 카트 유형\",\n \"admin/editor.minicart.type.popup\": \"팝업\",\n \"admin/editor.minicart.type.sidebar\": \"사이드바\",\n \"store/finish-shopping-button-label\": \"결제 화면으로 가기\",\n \"store/minicart-empty\": \"장바구니가 비어 있습니다!\",\n \"store/sidebar-title\": \"내 미니 카트\",\n \"store/minicart-content-footer-discount\": \"저장\",\n \"store/minicart.error-removal\": \"항목을 제거하지 못했습니다, 다시 시도하십시오\",\n \"store/minicart.shipping-cost\": \"총 배송비\",\n \"store/minicart.checkout-failure\": \"문제가 발생했습니다. 나중에 다시 시도하십시오.\",\n \"store/minicart.go-to-checkout\": \"결제 화면으로 가기\",\n \"store/minicart.empty-state\": \"장바구니가 비어 있습니다.\",\n \"store/minicart.title\": \"장바구니\"\n}\n\n```"
}
] |
code_minicart_834a2d25
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of minicart/messages/cs.json from the minicart VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"admin/editor.minicart.title\": \"Minikošík\",\n \"admin/editor.minicart.description\": \"Jednoduchý minikošík, který zobrazuje všechny do něj přidané produkty\",\n \"admin/editor.minicart.showDiscount.title\": \"Zobrazit objem ušetřených peněz\",\n \"admin/editor.minicart.iconLabel.title\": \"Text k zobrazení vedle ikony\",\n \"admin/editor.minicart.labelMiniCartEmpty.title\": \"Text k zobrazení v případě prázdného minikošíku\",\n \"admin/editor.minicart.linkButtonFinishShopping.title\": \"Link k přesměrování po kliknutí na tlačítko Přejít k pokladně\",\n \"admin/editor.minicart.labelButtonFinishShopping.title\": \"Text k zobrazení v tlačítku Dokončit nákup\",\n \"admin/editor.minicart.showShippingCost.title\": \"Zobrazit náklady na dopravu nad zápatím\",\n \"admin/editor.minicart.type.title\": \"Typ minikošíku\",\n \"admin/editor.minicart.type.popup\": \"Vyskakovací\",\n \"admin/editor.minicart.type.sidebar\": \"Postranní panel\",\n \"store/finish-shopping-button-label\": \"Přejít k pokladně\",\n \"store/minicart-empty\": \"Váš košík je prázdný!\",\n \"store/sidebar-title\": \"Můj minikošík\",\n \"store/minicart-content-footer-discount\": \"Uložit\",\n \"store/minicart.error-removal\": \"Odstranění položky se nezdařilo, zkuste to prosím znovu\",\n \"store/minicart.shipping-cost\": \"Celkové náklady na dopravu\",\n \"store/minicart.checkout-failure\": \"Došlo k chybě, zkuste to znovu.\",\n \"store/minicart.go-to-checkout\": \"Přejít k pokladně\",\n \"store/minicart.empty-state\": \"Váš košík je prázdný.\",\n \"store/minicart.title\": \"Košík\"\n}\n\n```"
}
] |
code_minicart_81ce0426
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of minicart/messages/id.json from the minicart VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"admin/editor.minicart.title\": \"Troli Mini\",\n \"admin/editor.minicart.description\": \"Troli mini sederhana yang menampilkan semua produk yang ditambah ke troli\",\n \"admin/editor.minicart.showDiscount.title\": \"Menampilkan jumlah uang yang dihemat\",\n \"admin/editor.minicart.iconLabel.title\": \"Teks akan muncul di samping ikon\",\n \"admin/editor.minicart.labelMiniCartEmpty.title\": \"Teks akan muncul saat troli mini kosong\",\n \"admin/editor.minicart.linkButtonFinishShopping.title\": \"Tautan untuk mengalihkan setelah mengklik tombol Lanjut ke Checkout\",\n \"admin/editor.minicart.labelButtonFinishShopping.title\": \"Teks akan muncul di tombol selesai belanja\",\n \"admin/editor.minicart.showShippingCost.title\": \"Tampilkan ongkos kirim di atas footer\",\n \"admin/editor.minicart.type.title\": \"Jenis Troli Mini\",\n \"admin/editor.minicart.type.popup\": \"Pop Up\",\n \"admin/editor.minicart.type.sidebar\": \"Bilah sisi\",\n \"store/finish-shopping-button-label\": \"Lanjut ke checkout\",\n \"store/minicart-empty\": \"Troli Anda kosong!\",\n \"store/sidebar-title\": \"Troli mini saya\",\n \"store/minicart-content-footer-discount\": \"Simpan\",\n \"store/minicart.error-removal\": \"Gagal menghapus item, silakan coba lagi\",\n \"store/minicart.shipping-cost\": \"Total ongkos kirim\",\n \"store/minicart.checkout-failure\": \"Terjadi kesalahan. Silakan coba lagi.\",\n \"store/minicart.go-to-checkout\": \"Lanjut ke checkout\",\n \"store/minicart.empty-state\": \"Troli Anda kosong.\",\n \"store/minicart.title\": \"Troli\"\n}\n\n```"
}
] |
code_minicart_3d5fe8dc
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of minicart/messages/no.json from the minicart VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"admin/editor.minicart.title\": \"Minihandlevogn\",\n \"admin/editor.minicart.description\": \"En enkel minihandlevogn som viser alle produktene som er lagt til\",\n \"admin/editor.minicart.showDiscount.title\": \"Vis mengden sparte penger\",\n \"admin/editor.minicart.iconLabel.title\": \"Tekst som skal vises ved siden av ikonet\",\n \"admin/editor.minicart.labelMiniCartEmpty.title\": \"Tekst som skal vises når minihandlevognen er tom\",\n \"admin/editor.minicart.linkButtonFinishShopping.title\": \"Link til omdirigering etter å ha klikket på Gå til kassen-knappen\",\n \"admin/editor.minicart.labelButtonFinishShopping.title\": \"Tekst som skal vises i Ferdig å handle-knappen\",\n \"admin/editor.minicart.showShippingCost.title\": \"Vis fraktkostnaden over bunnteksten\",\n \"admin/editor.minicart.type.title\": \"Type minihandlevogn\",\n \"admin/editor.minicart.type.popup\": \"Popup\",\n \"admin/editor.minicart.type.sidebar\": \"Sidefelt\",\n \"store/finish-shopping-button-label\": \"Gå til kassen\",\n \"store/minicart-empty\": \"Handlevognen din er tom!\",\n \"store/sidebar-title\": \"Min minihandlevogn\",\n \"store/minicart-content-footer-discount\": \"Lagre\",\n \"store/minicart.error-removal\": \"Fjerning av vare mislyktes. Prøv igjen\",\n \"store/minicart.shipping-cost\": \"Total fraktkostnad\",\n \"store/minicart.checkout-failure\": \"Noe gikk galt. Prøv igjen.\",\n \"store/minicart.go-to-checkout\": \"Gå til kassen\",\n \"store/minicart.empty-state\": \"Handlevognen din er tom.\",\n \"store/minicart.title\": \"Handlevogn\"\n}\n\n```"
}
] |
code_minicart_166bc9a1
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of minicart/messages/da.json from the minicart VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"admin/editor.minicart.title\": \"Minikurv\",\n \"admin/editor.minicart.description\": \"En simpel minikurv, der viser alle produkter, der er tilføjet\",\n \"admin/editor.minicart.showDiscount.title\": \"Vis mængden af sparede penge\",\n \"admin/editor.minicart.iconLabel.title\": \"Tekst der vises ved siden af ikonet\",\n \"admin/editor.minicart.labelMiniCartEmpty.title\": \"Tekst, der skal vises, når minikurven er tom\",\n \"admin/editor.minicart.linkButtonFinishShopping.title\": \"Link til omdirigering efter at have klikket på knappen Gå til kassen\",\n \"admin/editor.minicart.labelButtonFinishShopping.title\": \"Tekst, der skal vises på slutkøbsknappen\",\n \"admin/editor.minicart.showShippingCost.title\": \"Vis forsendelsesomkostninger over sidefoden\",\n \"admin/editor.minicart.type.title\": \"Minikurv type\",\n \"admin/editor.minicart.type.popup\": \"Pop op\",\n \"admin/editor.minicart.type.sidebar\": \"Sidebjælke\",\n \"store/finish-shopping-button-label\": \"Gå til betaling\",\n \"store/minicart-empty\": \"Din kurv er tom!\",\n \"store/sidebar-title\": \"Min minikurv\",\n \"store/minicart-content-footer-discount\": \"Gem\",\n \"store/minicart.error-removal\": \"Kunne ikke fjerne vare, prøv venligst igen\",\n \"store/minicart.shipping-cost\": \"Samlede forsendelsesomkostninger\",\n \"store/minicart.checkout-failure\": \"Der gik noget galt, prøv venligst igen.\",\n \"store/minicart.go-to-checkout\": \"Gå til betaling\",\n \"store/minicart.empty-state\": \"Din kurv er tom.\",\n \"store/minicart.title\": \"Kurv\"\n}\n\n```"
}
] |
code_minicart_98097f7b
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of minicart/messages/th.json from the minicart VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"admin/editor.minicart.title\": \"รถเข็นขนาดเล็ก\",\n \"admin/editor.minicart.description\": \"รถเข็นขนาดเล็กที่แสดงผลิตถัณฑ์ทั้งหมดที่เพิ่มลงไป\",\n \"admin/editor.minicart.showDiscount.title\": \"แสดงจำนวนเงินที่ประหยัดได้\",\n \"admin/editor.minicart.iconLabel.title\": \"ข้อความจะปรากฏถัดจากไอคอน\",\n \"admin/editor.minicart.labelMiniCartEmpty.title\": \"ข้อความจะปรากฏเมื่อไม่มีสินค้าในรถเข็นขนาดเล็ก\",\n \"admin/editor.minicart.linkButtonFinishShopping.title\": \"ลิงก์เพื่อเปลี่ยนเส้นทางหลังคลิกปุ่มไปที่หน้าชำระเงิน\",\n \"admin/editor.minicart.labelButtonFinishShopping.title\": \"ข้อความจะปรากฏบนปุ่มซื้อสินค้าเสร็จ\",\n \"admin/editor.minicart.showShippingCost.title\": \"แสดงค่าจัดส่งเหนือส่วนท้ายของหน้า\",\n \"admin/editor.minicart.type.title\": \"ประเภทรถเข็นขนาดเล็ก\",\n \"admin/editor.minicart.type.popup\": \"ปรากฏขึ้นมา\",\n \"admin/editor.minicart.type.sidebar\": \"แถบด้านข้าง\",\n \"store/finish-shopping-button-label\": \"ไปที่หน้าชำระเงิน\",\n \"store/minicart-empty\": \"ไม่มีสินค้าในรถเข็นของคุณ!\",\n \"store/sidebar-title\": \"รถเข็นขนาดเล็กของฉัน\",\n \"store/minicart-content-footer-discount\": \"บันทึก\",\n \"store/minicart.error-removal\": \"ลบสินค้าไม่สำเร็จ กรุณาลองอีกครั้ง\",\n \"store/minicart.shipping-cost\": \"ค่าจัดส่งรวมทั้งหมด\",\n \"store/minicart.checkout-failure\": \"มีบางอย่างผิดพลาด กรุณาลองอีกครั้ง\",\n \"store/minicart.go-to-checkout\": \"ไปที่หน้าชำระเงิน\",\n \"store/minicart.empty-state\": \"ไม่มีสินค้าในรถเข็นของคุณ\",\n \"store/minicart.title\": \"รถเข็น\"\n}\n\n```"
}
] |
code_minicart_7098efc5
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of minicart/messages/sv.json from the minicart VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"admin/editor.minicart.title\": \"Mini kundvagn\",\n \"admin/editor.minicart.description\": \"En enkel mini kundvagn som visar alla produkter som läggs till i den\",\n \"admin/editor.minicart.showDiscount.title\": \"Visa mängden sparade pengar\",\n \"admin/editor.minicart.iconLabel.title\": \"Text som visas bredvid ikonen\",\n \"admin/editor.minicart.labelMiniCartEmpty.title\": \"Text som ska visas när mini kundvagnen är tom\",\n \"admin/editor.minicart.linkButtonFinishShopping.title\": \"Länk till omdirigering efter att man har klickat på knappen Gå till kassan\",\n \"admin/editor.minicart.labelButtonFinishShopping.title\": \"Text som ska visas på knappen slutför köp\",\n \"admin/editor.minicart.showShippingCost.title\": \"Visa fraktkostnaden ovanför sidfoten\",\n \"admin/editor.minicart.type.title\": \"Typ av mini kundvagn\",\n \"admin/editor.minicart.type.popup\": \"Pop Up\",\n \"admin/editor.minicart.type.sidebar\": \"Sidofält\",\n \"store/finish-shopping-button-label\": \"Gå till kassan\",\n \"store/minicart-empty\": \"Din kundvagn är tom!\",\n \"store/sidebar-title\": \"Min mini kundvagn\",\n \"store/minicart-content-footer-discount\": \"Spara\",\n \"store/minicart.error-removal\": \"Borttagning av föremål misslyckades, vänligen försök igen\",\n \"store/minicart.shipping-cost\": \"Total fraktkostnad\",\n \"store/minicart.checkout-failure\": \"Någonting gick fel, vänligen försök igen.\",\n \"store/minicart.go-to-checkout\": \"Gå till kassan\",\n \"store/minicart.empty-state\": \"Din kundvagn är tom.\",\n \"store/minicart.title\": \"Kundvagn\"\n}\n\n```"
}
] |
code_minicart_8c544618
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of minicart/messages/nn.json from the minicart VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"admin/editor.minicart.title\": \"Minihandlevogn\",\n \"admin/editor.minicart.description\": \"En enkel minihandlevogn som viser alle produktene som er lagt til\",\n \"admin/editor.minicart.showDiscount.title\": \"Vis mengden sparte penger\",\n \"admin/editor.minicart.iconLabel.title\": \"Tekst som skal vises ved siden av ikonet\",\n \"admin/editor.minicart.labelMiniCartEmpty.title\": \"Tekst som skal vises når minihandlevognen er tom\",\n \"admin/editor.minicart.linkButtonFinishShopping.title\": \"Link til omdirigering etter å ha klikket på Gå til kassen-knappen\",\n \"admin/editor.minicart.labelButtonFinishShopping.title\": \"Tekst som skal vises i Ferdig å handle-knappen\",\n \"admin/editor.minicart.showShippingCost.title\": \"Vis fraktkostnaden over bunnteksten\",\n \"admin/editor.minicart.type.title\": \"Type minihandlevogn\",\n \"admin/editor.minicart.type.popup\": \"Popup\",\n \"admin/editor.minicart.type.sidebar\": \"Sidefelt\",\n \"store/finish-shopping-button-label\": \"Gå til kassen\",\n \"store/minicart-empty\": \"Handlevognen din er tom!\",\n \"store/sidebar-title\": \"Min minihandlevogn\",\n \"store/minicart-content-footer-discount\": \"Lagre\",\n \"store/minicart.error-removal\": \"Fjerning av vare mislyktes. Prøv igjen\",\n \"store/minicart.shipping-cost\": \"Total fraktkostnad\",\n \"store/minicart.checkout-failure\": \"Noe gikk galt. Prøv igjen.\",\n \"store/minicart.go-to-checkout\": \"Gå til kassen\",\n \"store/minicart.empty-state\": \"Handlevognen din er tom.\",\n \"store/minicart.title\": \"Handlevogn\"\n}\n\n```"
}
] |
code_minicart_9064e3a0
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of minicart/messages/es.json from the minicart VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"admin/editor.minicart.title\": \"Minicart\",\n \"admin/editor.minicart.description\": \"Un simple resumen que muestra todos los productos agregados al carrito\",\n \"admin/editor.minicart.showDiscount.title\": \"Mostrar la cantidad de dinero ahorrado\",\n \"admin/editor.minicart.iconLabel.title\": \"Texto que aparecerá junto al ícono\",\n \"admin/editor.minicart.labelMiniCartEmpty.title\": \"Texto que aparecerá cuando el carrito esté vacío\",\n \"admin/editor.minicart.linkButtonFinishShopping.title\": \"Link de redirección al hacer clic en el botón \\\"Ir al checkout\\\"\",\n \"admin/editor.minicart.labelButtonFinishShopping.title\": \"Texto que aparecerá en el botón de finalizar la compra\",\n \"admin/editor.minicart.showShippingCost.title\": \"Mostrar los costos de envío sobre el pie de página\",\n \"admin/editor.minicart.type.title\": \"Tipo de carrito\",\n \"admin/editor.minicart.type.popup\": \"Ventana emergente\",\n \"admin/editor.minicart.type.sidebar\": \"Barra lateral\",\n \"store/finish-shopping-button-label\": \"Ir al checkout\",\n \"store/minicart-empty\": \"¡Tu carrito está vacío!\",\n \"store/sidebar-title\": \"Mi carrito\",\n \"store/minicart-content-footer-discount\": \"Guardar\",\n \"store/minicart.error-removal\": \"Error al eliminar el ítem. Por favor, vuelve a intentarlo.\",\n \"store/minicart.shipping-cost\": \"Costo total del envío\",\n \"store/minicart.checkout-failure\": \"Se produjo un error. Por favor, vuelve a intentarlo.\",\n \"store/minicart.go-to-checkout\": \"Ir al checkout\",\n \"store/minicart.empty-state\": \"Tu carrito está vacío.\",\n \"store/minicart.title\": \"Carrito\"\n}\n\n```"
}
] |
code_minicart_e4314d3a
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of minicart/messages/ar.json from the minicart VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"admin/editor.minicart.title\": \"عربة شراء صغيرة\",\n \"admin/editor.minicart.description\": \"عربة صغيرة بسيطة تعرض جميع المنتجات المضافة إليها\",\n \"admin/editor.minicart.showDiscount.title\": \"اعرض كمية الأموال التي تم توفيرها\",\n \"admin/editor.minicart.iconLabel.title\": \"النص الذي سيظهر بجانب الرمز\",\n \"admin/editor.minicart.labelMiniCartEmpty.title\": \"النص الذي سيظهر عندما تكون العربة الصغيرة فارغة\",\n \"admin/editor.minicart.linkButtonFinishShopping.title\": \"رابط لإعادة التوجيه بعد النقر فوق الزر الذهاب إلى الدفع\",\n \"admin/editor.minicart.labelButtonFinishShopping.title\": \"النص الذي سيظهر في زر إنهاء التسوق\",\n \"admin/editor.minicart.showShippingCost.title\": \"إظهار تكلفة الشحن فوق التذييل\",\n \"admin/editor.minicart.type.title\": \"نوع عربة التسوق الصغيرة\",\n \"admin/editor.minicart.type.popup\": \"نافدة منبثقة\",\n \"admin/editor.minicart.type.sidebar\": \"الشريط الجانبي\",\n \"store/finish-shopping-button-label\": \"الذهاب إلى الدفع\",\n \"store/minicart-empty\": \"عربتك فارغة!\",\n \"store/sidebar-title\": \"عربة الشراء الصغيرة الخاصة بي\",\n \"store/minicart-content-footer-discount\": \"حفظ\",\n \"store/minicart.error-removal\": \"فشل إزالة العنصر، يرجى المحاولة مرة أخرى\",\n \"store/minicart.shipping-cost\": \"إجمالي تكلفة الشحن\",\n \"store/minicart.checkout-failure\": \"حدث خطأ ما. يرجى المحاولة مرة أخرى.\",\n \"store/minicart.go-to-checkout\": \"الذهاب إلى الدفع\",\n \"store/minicart.empty-state\": \"عربتك فارغة.\",\n \"store/minicart.title\": \"العربة\"\n}\n\n```"
}
] |
code_minicart_00f64eea
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of minicart/docs/README.md from the minicart VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```markdown\n📢 Use this project, [contribute](https://github.com/vtex-apps/minicart) to it or open issues to help evolve it using [Store Discussion](https://github.com/vtex-apps/store-discussion).\n\n# Minicart\n\n<!-- ALL-CONTRIBUTORS-BADGE:START - Do not remove or modify this section -->\n[](#contributors-)\n<!-- ALL-CONTRIBUTORS-BADGE:END -->\n\n> ⚠️ Minicart v1 block has been deprecated in favor of Minicart v2, which can be customized using the blocks defined by [Product List](https://developers.vtex.com/docs/apps/vtex.product-list) and [Checkout Summary](https://developers.vtex.com/docs/apps/vtex.checkout-summary). If you still use Minicart v1, see the [Minicart v1 documentation](https://github.com/vtex-apps/minicart/blob/383d7bbd3295f06d1b5854a0add561a872e1515c/docs/README.md).\n\nThe Minicart is a block that displays a summary list of all items added to the shopping cart, fetched from the Checkout OrderForm API.\n\n\n\n## Configurating Minicart\n\n1. Import the Minicart app to your theme dependencies in the `manifest.json`, as shown below:\n\n```json\n\"dependencies\": {\n \"vtex.minicart\": \"2.x\"\n}\n```\n\n2. Add the `minicart.v2` block to your `header`. For example:\n\n```json\n\"header.full\": {\n \"blocks\": [\"header-layout.desktop\", \"header-layout.mobile\"]\n },\n\n \"header-layout.desktop\": {\n \"children\": [\n \"header-row#1-desktop\",\n ]\n },\n\n \"header-row#1-desktop\": {\n \"children\": [\"minicart.v2\"],\n },\n```\n\n> ⚠️ Minicart v2 will only effectively function if the store uses the [`add-to-cart` app](https://developers.vtex.com/docs/apps/vtex.add-to-cart-button) instead of the [`buy-button` block](https://developers.vtex.com/docs/apps/vtex.store-components/buybutton) in blocks such as the Shelf and the Product Details page. This is because Minicart v2 was built based on an indirect dependency on the Add to Cart button. This means that even if Minicart v2 is correctly configured in the code, it cannot be rendered by other shopping buttons, such as the Buy button.\n\n| Prop name | Type | Description | Default value |\n| ---------------------- | ------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------- |\n| `variation` | `enum` | Minicart behavior when rendered. Possible values for displaying the VTEX Minicart are: `popup` (appears as a pop-up window on the homepage), `drawer` (appears as a sidebar), `link` (redirects the user to the Checkout page when clicked), `popupWithLink` (combines `link` and `popup` functionalities), and `block` (displays the Minicart as a fixed block on the page). | `drawer` |\n| `drawerSlideDirection` | `enum` | Slide direction for the `drawer` Minicart opening. Possible values are: `rightToLeft` or `leftToRight`. | `rightToLeft` |\n| `linkVariationUrl` | `string` | Link associated with the `link` Minicart. | `undefined` |\n| `maxDrawerWidth` | `number` | Maximum width (in pixels) for the `drawer` Minicart when opened. | `440` |\n| `openOnHover` | `boolean` | Indicates whether the `popup` Minicart should open when the user hovers over it. | `false` |\n| `quantityDisplay` | `enum` | Shows the quantity badge even when the amount of products in the cart is zero. Possible values are: `always` or `not-empty` or `never`. | `not-empty` |\n| `itemCountMode` | `enum` | Quantity badge behavior when displaying the total items added to Minicart. Possible values are: `total` (quantity badge displays the number of items added to the cart), `distinct` (only displays the number of different products added to the cart), `totalAvailable` (displays the number of available items added to the cart), and `distinctAvailable` (displays the number of different _and_ available products added to the cart). | `distinct` |\n| `backdropMode` | `enum` | Controls whether the backdrop should be displayed when the `drawer` Minicart is opened or not. Possible values are: `visible` (renders the backdrop) or `none` (renders the `drawer` without backdrop). | `none` |\n| `MinicartIcon` | `block` | Icon displayed on the Minicart button. This prop value must match the block name responsible for rendering the desired icon. | `icon-cart` (from the [Store Icons](https://developers.vtex.com/docs/guides/vtex-store-icons/) app) |\n| `customPixelEventId` | `string` | Store event ID responsible for triggering the `minicart.v2` to automatically open on the interface. | `undefined` |\n| `customPixelEventName` | `string` | Store event name responsible for triggering the `minicart.v2` to automatically open on the interface. Some examples are: `'addToCart'` and `'removeFromCart'`. Note that using this prop will make the `minicart.v2` open in **every** event with the specified name if no `customPixelEventId` is specified. | `undefined` |\n| `classes` | `CustomCSSClasses` | Used to override default CSS handles. To better understand how this prop works, we recommend reading about it [here](https://github.com/vtex-apps/css-handles#usecustomclasses). Note that this is only useful when importing this block as a React component. | `undefined` |\n\n### Advanced configurations\n\nThe default implementation for `minicart.v2` can be highly customizable by using other blocks. Currently, its default implementation is as follows:\n\n```jsonc\n// This is the default block implementation for the minicart-layout\n{\n \"minicart.v2\": {\n \"props\": {\n \"MinicartIcon\": \"icon-cart#minicart-icon\"\n },\n \"children\": [\"minicart-base-content\"]\n },\n \"icon-cart#minicart-icon\": {\n \"props\": {\n \"size\": 24\n }\n },\n \"minicart-base-content\": {\n \"blocks\": [\"minicart-empty-state\"],\n \"children\": [\"minicart-product-list\", \"flex-layout.row#minicart-footer\"]\n },\n \"flex-layout.row#minicart-footer\": {\n \"props\": {\n \"blockClass\": \"minicart-footer\"\n },\n \"children\": [\"flex-layout.col#minicart-footer\"]\n },\n \"flex-layout.col#minicart-footer\": {\n \"children\": [\"minicart-summary\", \"minicart-checkout-button\"]\n },\n \"minicart-product-list\": {\n \"blocks\": [\"product-list#minicart\"]\n },\n \"product-list#minicart\": {\n \"blocks\": [\"product-list-content-mobile\"]\n },\n \"minicart-summary\": {\n \"blocks\": [\"checkout-summary.compact#minicart\"]\n },\n \"minicart-checkout-button\": {\n \"props\": {\n \"finishShoppingButtonLink\": \"/checkout/#/orderform\"\n }\n },\n\n \"checkout-summary.compact#minicart\": {\n \"children\": [\"summary-totalizers#minicart\"],\n \"props\": {\n \"totalizersToShow\": [\"Items\", \"Discounts\"]\n }\n },\n \"summary-totalizers#minicart\": {\n \"props\": {\n \"showTotal\": true,\n \"showDeliveryTotal\": false\n }\n },\n \"minicart-empty-state\": {\n \"children\": [\"flex-layout.row#empty-state\"]\n },\n \"flex-layout.row#empty-state\": {\n \"children\": [\"flex-layout.col#empty-state\"]\n },\n \"flex-layout.col#empty-state\": {\n \"children\": [\n \"icon-cart#minicart-empty-state\",\n \"rich-text#minicart-default-empty-state\"\n ],\n \"props\": {\n \"horizontalAlign\": \"center\",\n \"verticalAlign\": \"middle\",\n \"rowGap\": 5\n }\n },\n \"icon-cart#minicart-empty-state\": {\n \"props\": {\n \"size\": 64,\n \"blockClass\": \"minicart-empty-state\"\n }\n },\n \"rich-text#minicart-default-empty-state\": {\n \"props\": {\n \"text\": \"Your cart is empty.\"\n }\n }\n}\n```\n\nThe default implementation of `minicart.v2` consists of the `JSON` code shown above, which is used behind the scenes whenever you use this block in your store.\n\nTo customize the Minicart configuration, you can copy the code and modify it to your needs.\n\nFor detailed instructions on how to configure each of the blocks that make up `minicart.v2`, read the [Product List](https://developers.vtex.com/docs/apps/vtex.product-list) and [Checkout Summary](https://developers.vtex.com/docs/apps/vtex.checkout-summary) documentations.\n\n## Customization\n\nTo apply CSS customizations to this and other blocks, follow the instructions given in the recipe on [Using CSS handles for store customization](https://developers.vtex.com/docs/guides/vtex-io-documentation-using-css-handles-for-store-customization).\n\n| CSS handles |\n| ------------------------------- |\n| `arrowUp` |\n| `minicartCheckoutButton` |\n| `minicartContainer` |\n| `minicartContentContainer` |\n| `minicartFooter` |\n| `minicartIconContainer` |\n| `minicartProductListContainer` |\n| `minicartQuantityBadge` |\n| `minicartSideBarContentWrapper` |\n| `minicartTitle` |\n| `minicartWrapperContainer` |\n| `popupChildrenContainer` |\n| `popupContentContainer` |\n| `popupWrapper` |\n\n## Contributors\n\nThanks goes to these wonderful people ([emoji key](https://allcontributors.org/docs/en/emoji-key)):\n\n<!-- ALL-CONTRIBUTORS-LIST:START - Do not remove or modify this section -->\n<!-- prettier-ignore-start -->\n<!-- markdownlint-disable -->\n<table>\n <tr>\n <td align=\"center\"><a href=\"https://github.com/lucasayb\"><img src=\"https://avatars2.githubusercontent.com/u/17356081?v=4\" width=\"100px;\" alt=\"\"/><br /><sub><b>Lucas Antônio Yamamoto Borges</b></sub></a><br /><a href=\"https://github.com/vtex-apps/minicart/commits?author=lucasayb\" title=\"Code\">💻</a></td>\n <td align=\"center\"><a href=\"https://github.com/lucaspacheco-acct\"><img src=\"https://avatars0.githubusercontent.com/u/59736416?v=4\" width=\"100px;\" alt=\"\"/><br /><sub><b>lucaspacheco-acct</b></sub></a><br /><a href=\"https://github.com/vtex-apps/minicart/commits?author=lucaspacheco-acct\" title=\"Code\">💻</a></td>\n <td align=\"center\"><a href=\"https://github.com/gustavopvasconcellos\"><img src=\"https://avatars1.githubusercontent.com/u/49173685?v=4\" width=\"100px;\" alt=\"\"/><br /><sub><b>gustavopvasconcellos</b></sub></a><br /><a href=\"https://github.com/vtex-apps/minicart/commits?author=gustavopvasconcellos\" title=\"Code\">💻</a></td>\n </tr>\n</table>\n\n<!-- markdownlint-enable -->\n<!-- prettier-ignore-end -->\n<!-- ALL-CONTRIBUTORS-LIST:END -->\n\nThis project follows the [all-contributors](https://github.com/all-contributors/all-contributors) specification. Contributions of any kind welcome!\n\n```"
}
] |
code_minicart_bebbf5c8
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of minicart/react/ProductList.tsx from the minicart VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React, { FC, useCallback } from 'react'\nimport { useOrderForm } from 'vtex.order-manager/OrderForm'\nimport { useOrderItems } from 'vtex.order-items/OrderItems'\nimport { ExtensionPoint } from 'vtex.render-runtime'\nimport { usePixel } from 'vtex.pixel-manager'\nimport { CssHandlesTypes, useCssHandles } from 'vtex.css-handles'\n\nimport { mapCartItemToPixel } from './modules/pixelHelper'\n\nconst CSS_HANDLES = ['minicartProductListContainer'] as const\n\ninterface Props {\n renderAsChildren: boolean\n splitItem?: boolean\n classes?: CssHandlesTypes.CustomClasses<typeof CSS_HANDLES>\n}\n\nconst ProductList: FC<Props> = ({\n renderAsChildren,\n splitItem = true,\n classes,\n}) => {\n const {\n orderForm: { items },\n } = useOrderForm()\n const { updateQuantity, removeItem } = useOrderItems()\n const { push } = usePixel()\n const { handles } = useCssHandles(CSS_HANDLES, { classes })\n\n const options = {\n allowedOutdatedData: ['paymentData'],\n splitItem,\n }\n\n const handleQuantityChange = useCallback(\n (_: string, quantity: number, item: OrderFormItemWithIndex) => {\n if (quantity === item.quantity) {\n return\n }\n\n const quantityIncreased = quantity > item.quantity\n\n if (quantityIncreased) {\n const adjustedItem = {\n ...mapCartItemToPixel(item),\n quantity: quantity - item.quantity,\n }\n\n push({\n event: 'addToCart',\n items: [adjustedItem],\n })\n } else {\n const adjustedItem = {\n ...mapCartItemToPixel(item),\n quantity: item.quantity - quantity,\n }\n\n push({\n event: 'removeFromCart',\n items: [adjustedItem],\n })\n }\n\n updateQuantity({ index: item.index, quantity }, options)\n },\n [options, push, updateQuantity]\n )\n\n const handleRemove = useCallback(\n (uniqueId: string, item: OrderFormItem) => {\n const adjustedItem = mapCartItemToPixel(item)\n push({\n event: 'removeFromCart',\n items: [adjustedItem],\n })\n removeItem({ uniqueId }, options)\n },\n [options, push, removeItem]\n )\n\n return (\n <div\n /* \n This prevents an interaction with the quantity selector\n inside of a product in the ProductList to bubble up a\n mouseleave event to the Popup component, which would result\n in the minicart being closed (when openOnHover = true). \n */\n onMouseLeave={e => e.stopPropagation()}\n className={`${handles.minicartProductListContainer} ${\n renderAsChildren ? 'w-100 h-100' : ''\n } overflow-y-auto ph4 ph6-l`}\n >\n <ExtensionPoint\n id=\"product-list\"\n items={items}\n onQuantityChange={handleQuantityChange}\n onRemove={handleRemove}\n />\n </div>\n )\n}\n\nexport default ProductList\n\n```"
}
] |
code_minicart_b88cc53e
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of minicart/react/MinicartContext.tsx from the minicart VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React, { createContext, useReducer, useContext, FC } from 'react'\nimport { useDevice } from 'vtex.device-detector'\n\ninterface OpenMinicartAction {\n type: 'OPEN_MINICART'\n}\ninterface CloseMinicartAction {\n type: 'CLOSE_MINICART'\n}\ninterface SetOpenBehaviorAction {\n type: 'SET_OPEN_BEHAVIOR'\n value: 'click' | 'hover'\n}\n\ninterface State {\n variation: MinicartVariationType\n open: boolean\n hasBeenOpened: boolean\n /** Controls the minicart opening behavior */\n openBehavior: 'click' | 'hover'\n /** Value provided by the user to openOnHover prop */\n openOnHoverProp: boolean\n}\n\ninterface Props {\n openOnHover?: boolean\n variation?: MinicartVariationType\n}\n\ntype Action = OpenMinicartAction | CloseMinicartAction | SetOpenBehaviorAction\ntype Dispatch = (action: Action) => void\n\nexport const MinicartStateContext = createContext<State | undefined>(undefined)\nconst MinicartDispatchContext = createContext<Dispatch | undefined>(undefined)\n\nfunction minicartContextReducer(state: State, action: Action): State {\n switch (action.type) {\n case 'OPEN_MINICART':\n return {\n ...state,\n open: true,\n hasBeenOpened: true,\n }\n case 'CLOSE_MINICART':\n return {\n ...state,\n open: false,\n }\n case 'SET_OPEN_BEHAVIOR':\n return {\n ...state,\n openBehavior: action.value,\n }\n default:\n return state\n }\n}\n\nconst checkVariationIsPopup = (variation: string): boolean => {\n return variation === 'popup' || variation === 'popupWithLink'\n}\n\nconst MinicartContextProvider: FC<Props> = ({\n variation = 'drawer',\n openOnHover: openOnHoverProp = false,\n children,\n}) => {\n const { isMobile } = useDevice()\n const isPopup = checkVariationIsPopup(variation)\n\n // This prevents a popup minicart from being used on a mobile device\n const resolvedVariation =\n isPopup && (isMobile || (window && window.innerWidth <= 480))\n ? 'drawer'\n : variation\n\n const [state, dispatch] = useReducer(minicartContextReducer, {\n variation: resolvedVariation,\n open: false,\n hasBeenOpened: false,\n openOnHoverProp,\n openBehavior:\n checkVariationIsPopup(resolvedVariation) && openOnHoverProp\n ? 'hover'\n : 'click',\n })\n\n return (\n <MinicartStateContext.Provider value={state}>\n <MinicartDispatchContext.Provider value={dispatch}>\n {children}\n </MinicartDispatchContext.Provider>\n </MinicartStateContext.Provider>\n )\n}\n\nfunction useMinicartState() {\n const context = useContext(MinicartStateContext)\n if (context === undefined) {\n throw new Error(\n 'useMinicartState must be used within a MinicartContextProvider'\n )\n }\n return context\n}\n\nfunction useMinicartDispatch() {\n const context = useContext(MinicartDispatchContext)\n\n if (context === undefined) {\n throw new Error(\n 'useMinicartDispatch must be used within a MinicartContextProvider'\n )\n }\n return context\n}\n\nexport { MinicartContextProvider, useMinicartDispatch, useMinicartState }\n\n```"
}
] |
code_minicart_34971af2
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of minicart/react/styles.css from the minicart VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```css\n.drawerStyles {\n height: 100%;\n}\n\n.popupStyles {\n max-height: 600px;\n}\n\n.minicartEmptyStateContainerDefault {\n width: 340px;\n}\n\n.minicartQuantityBadgeDefault {\n top: -0.7rem;\n right: -0.8rem;\n}\n\n.popupBoxPosition {\n right: -40px;\n width: 364px;\n top: 100%;\n}\n\n.popupArrowUp {\n right: 7px;\n}\n```"
}
] |
code_minicart_6972848e
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of minicart/react/Minicart.tsx from the minicart VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React, { FC, useCallback, useState } from 'react'\nimport { IconCart } from 'vtex.store-icons'\nimport { BackdropMode } from 'vtex.store-drawer'\nimport { useOrderForm } from 'vtex.order-manager/OrderForm'\nimport { ResponsiveValuesTypes } from 'vtex.responsive-values'\nimport { useCheckoutURL } from 'vtex.checkout-resources/Utils'\nimport { PixelEventTypes } from 'vtex.pixel-manager'\nimport { useCssHandles, CssHandlesTypes } from 'vtex.css-handles'\n\nimport PopupMode, {\n CSS_HANDLES as PopupModeCssHandles,\n} from './components/Popup'\nimport DrawerMode, {\n CSS_HANDLES as DrawerModeCssHandles,\n} from './components/DrawerMode'\nimport MinicartIconButton, {\n CSS_HANDLES as MinicartIconButtonCssHandles,\n} from './components/MinicartIconButton'\nimport useCartIdPixel from './modules/useCartIdPixel'\nimport { MinicartCssHandlesProvider } from './components/CssHandlesContext'\nimport { MinicartContextProvider, useMinicartState } from './MinicartContext'\nimport useViewCartPixel from './modules/useViewCartPixel'\n\nexport const CSS_HANDLES = [\n ...PopupModeCssHandles,\n ...DrawerModeCssHandles,\n ...MinicartIconButtonCssHandles,\n 'minicartWrapperContainer',\n 'minicartContainer',\n] as const\n\ninterface MinicartProps {\n variation?: MinicartVariationType\n openOnHover?: boolean\n linkVariationUrl?: string\n maxDrawerWidth?: number | string\n MinicartIcon?: React.ComponentType\n drawerSlideDirection?: SlideDirectionType\n quantityDisplay?: QuantityDisplayType\n itemCountMode?: MinicartTotalItemsType\n backdropMode?: ResponsiveValuesTypes.ResponsiveValue<BackdropMode>\n customPixelEventId?: string\n customPixelEventName?: PixelEventTypes.EventName\n classes?: CssHandlesTypes.CustomClasses<typeof CSS_HANDLES>\n}\n\nexport const Minicart: FC<MinicartProps> = ({\n children,\n backdropMode,\n linkVariationUrl,\n maxDrawerWidth = 400,\n MinicartIcon = IconCart,\n quantityDisplay = 'not-empty',\n itemCountMode = 'distinct',\n drawerSlideDirection = 'rightToLeft',\n customPixelEventId,\n customPixelEventName,\n classes,\n}) => {\n const { handles, withModifiers } = useCssHandles(CSS_HANDLES, { classes })\n\n const { orderForm }: OrderFormContext = useOrderForm()\n\n const { variation, open } = useMinicartState()\n const [isDrawerOpen, setIsDrawerOpen] = useState(open ?? false)\n const { url: checkoutUrl } = useCheckoutURL()\n\n const onDrawerVisibilityChanged = useCallback(\n (visible: boolean) => {\n setIsDrawerOpen(visible)\n },\n [setIsDrawerOpen]\n )\n\n // for Popup it uses \"open\" and for Drawer it uses \"isDrawerOpen\" to send view_cart pixel event\n useViewCartPixel(\n variation === 'drawer' ? isDrawerOpen : open,\n orderForm?.items\n )\n\n if (variation === 'link') {\n return (\n <aside\n className={`${handles.minicartWrapperContainer} relative fr flex items-center`}\n >\n <div className={`${handles.minicartContainer} flex flex-column`}>\n <a href={linkVariationUrl ?? checkoutUrl}>\n <MinicartCssHandlesProvider\n handles={handles}\n withModifiers={withModifiers}\n >\n <MinicartIconButton\n variation={variation}\n Icon={MinicartIcon}\n itemCountMode={itemCountMode}\n quantityDisplay={quantityDisplay}\n />\n </MinicartCssHandlesProvider>\n </a>\n </div>\n </aside>\n )\n }\n\n if (variation === 'block') {\n return (\n <aside\n className={`${handles.minicartWrapperContainer} relative fr flex items-center`}\n >\n <div className={`${handles.minicartContainer} flex flex-column`}>\n {children}\n </div>\n </aside>\n )\n }\n\n return (\n <aside\n className={`${handles.minicartWrapperContainer} relative fr flex items-center`}\n >\n <div className={`${handles.minicartContainer} flex flex-column`}>\n <MinicartCssHandlesProvider\n handles={handles}\n withModifiers={withModifiers}\n >\n {variation === 'drawer' ? (\n <DrawerMode\n Icon={MinicartIcon}\n backdropMode={backdropMode}\n itemCountMode={itemCountMode}\n maxDrawerWidth={maxDrawerWidth}\n quantityDisplay={quantityDisplay}\n drawerSlideDirection={drawerSlideDirection}\n customPixelEventId={customPixelEventId}\n customPixelEventName={customPixelEventName}\n onVisibilityChanged={onDrawerVisibilityChanged}\n >\n {children}\n </DrawerMode>\n ) : (\n <PopupMode\n Icon={MinicartIcon}\n itemCountMode={itemCountMode}\n quantityDisplay={quantityDisplay}\n customPixelEventId={customPixelEventId}\n customPixelEventName={customPixelEventName}\n variation={variation}\n >\n {children}\n </PopupMode>\n )}\n </MinicartCssHandlesProvider>\n </div>\n </aside>\n )\n}\n\nconst CartIdPixel = () => {\n const { orderForm, loading }: OrderFormContext = useOrderForm()\n\n const orderFormId = !loading && orderForm ? orderForm.id : undefined\n\n useCartIdPixel(orderFormId)\n\n return null\n}\n\nconst EnhancedMinicart = (props: MinicartProps) => (\n <MinicartContextProvider\n variation={props.variation}\n openOnHover={props.openOnHover}\n >\n <CartIdPixel />\n <Minicart {...props} />\n </MinicartContextProvider>\n)\n\nexport default EnhancedMinicart\n\n```"
}
] |
code_minicart_978e8921
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of minicart/react/package.json from the minicart VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"name\": \"vtex.minicart\",\n \"version\": \"2.68.0\",\n \"description\": \"A MiniCart Component.\",\n \"scripts\": {\n \"pretest\": \"yarn\",\n \"test\": \"vtex-test-tools test\",\n \"lint\": \"eslint --ext ts,tsx .\",\n \"lint:fix\": \"eslint --ext ts,tsx . --fix\"\n },\n \"devDependencies\": {\n \"@apollo/react-testing\": \"^3.1.3\",\n \"@types/debounce\": \"^1.2.0\",\n \"@types/jest\": \"^25.1.4\",\n \"@types/node\": \"^13.9.8\",\n \"@types/react\": \"^16.9.31\",\n \"@vtex/test-tools\": \"^3.1.0\",\n \"@vtex/tsconfig\": \"^0.4.4\",\n \"apollo-cache-inmemory\": \"^1.6.5\",\n \"babel-eslint\": \"^10.1.0\",\n \"typescript\": \"3.9.7\",\n \"vtex.checkout-graphql\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.checkout-graphql@0.66.0/public/@types/vtex.checkout-graphql\",\n \"vtex.checkout-resources\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.checkout-resources@0.49.0/public/@types/vtex.checkout-resources\",\n \"vtex.checkout-summary\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.checkout-summary@0.22.0/public/@types/vtex.checkout-summary\",\n \"vtex.css-handles\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.css-handles@1.0.0/public/@types/vtex.css-handles\",\n \"vtex.device-detector\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.device-detector@0.2.6/public/@types/vtex.device-detector\",\n \"vtex.flex-layout\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.flex-layout@0.21.0/public/@types/vtex.flex-layout\",\n \"vtex.order-items\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.order-items@0.13.21/public/@types/vtex.order-items\",\n \"vtex.order-manager\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.order-manager@0.12.0/public/@types/vtex.order-manager\",\n \"vtex.pixel-manager\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.pixel-manager@1.9.0/public/@types/vtex.pixel-manager\",\n \"vtex.product-list\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.product-list@0.37.1/public/@types/vtex.product-list\",\n \"vtex.product-summary\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.product-summary@2.82.0/public/@types/vtex.product-summary\",\n \"vtex.react-portal\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.react-portal@0.4.1/public/@types/vtex.react-portal\",\n \"vtex.render-runtime\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.render-runtime@8.133.0/public/@types/vtex.render-runtime\",\n \"vtex.responsive-values\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.responsive-values@0.4.2/public/@types/vtex.responsive-values\",\n \"vtex.rich-text\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.rich-text@0.16.0/public/@types/vtex.rich-text\",\n \"vtex.sandbox\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.sandbox@0.5.1/public/@types/vtex.sandbox\",\n \"vtex.store-components\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.store-components@3.167.0/public/@types/vtex.store-components\",\n \"vtex.store-drawer\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.store-drawer@0.16.2/public/@types/vtex.store-drawer\",\n \"vtex.store-graphql\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.store-graphql@2.161.2/public/@types/vtex.store-graphql\",\n \"vtex.store-icons\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.store-icons@0.18.0/public/@types/vtex.store-icons\",\n \"vtex.store-resources\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.store-resources@0.89.0/public/@types/vtex.store-resources\",\n \"vtex.styleguide\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.styleguide@9.146.3/public/@types/vtex.styleguide\"\n },\n \"dependencies\": {\n \"apollo-client\": \"2.6.4\",\n \"classnames\": \"^2.2.6\",\n \"debounce\": \"^1.2.0\",\n \"graphql\": \"^14.6.0\",\n \"graphql-tag\": \"^2.10.1\",\n \"hoist-non-react-statics\": \"^3.3.0\",\n \"prop-types\": \"^15.7.2\",\n \"ramda\": \"^0.26.1\",\n \"react\": \"^16.8.4\",\n \"react-apollo\": \"3.1.3\",\n \"react-intl\": \"3.9.1\",\n \"react-outside-click-handler\": \"^1.2.2\"\n }\n}\n\n```"
}
] |
code_minicart_413fbe12
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of minicart/react/index.jsx from the minicart VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```jsx\n/* eslint-disable no-shadow */\n/* eslint-disable no-restricted-imports */\nimport classNames from 'classnames'\nimport { compose, map, partition, path, pathOr, pick, isNil, prop } from 'ramda'\nimport React, {\n useState,\n useEffect,\n useCallback,\n useRef,\n useContext,\n useMemo,\n} from 'react'\nimport { graphql, withApollo } from 'react-apollo'\nimport { injectIntl } from 'react-intl'\nimport { ButtonWithIcon, ToastContext } from 'vtex.styleguide'\nimport { useRuntime } from 'vtex.render-runtime'\nimport { IconCart } from 'vtex.store-icons'\nimport orderFormQuery from 'vtex.store-resources/QueryOrderForm'\nimport addToCart from 'vtex.store-resources/MutationAddToCart'\nimport updateItems from 'vtex.store-resources/MutationUpdateItems'\nimport { usePixel } from 'vtex.pixel-manager/PixelContext'\nimport ProductPrice from 'vtex.store-components/ProductPrice'\nimport { useCheckoutURL } from 'vtex.checkout-resources/Utils'\n\nimport MiniCartContent from './legacy/components/MiniCartContent'\nimport Sidebar from './legacy/components/Sidebar'\nimport Popup from './legacy/components/Popup'\nimport { shouldShowItem } from './legacy/utils/itemsHelper'\nimport {\n mapBuyButtonItemToPixel,\n mapCartItemToPixel,\n} from './modules/pixelHelper'\nimport fullMinicartQuery from './legacy/localState/graphql/fullMinicartQuery.gql'\nimport updateItemsMutation from './legacy/localState/graphql/updateItemsMutation.gql'\nimport updateOrderFormMutation from './legacy/localState/graphql/updateOrderFormMutation.gql'\nimport updateLocalItemStatusMutation from './legacy/localState/graphql/updateLocalItemStatusMutation.gql'\nimport setMinicartOpenMutation from './legacy/localState/graphql/setMinicartOpenMutation.gql'\nimport createLocalState, { ITEMS_STATUS } from './legacy/localState'\nimport styles from './legacy/minicart.css'\nimport useMarketingSessionParams from './legacy/hooks/useMarketingSessionParams'\nimport useCartIdPixel from './modules/useCartIdPixel'\nimport useViewCartPixel from './modules/useViewCartPixel'\n\nconst DEFAULT_LABEL_CLASSES = ''\nconst DEFAULT_ICON_CLASSES = 'gray'\n\nconst useOffline = () => {\n const [isOffline, setOffline] = useState(() =>\n typeof navigator !== 'undefined'\n ? !pathOr(true, ['onLine'], navigator)\n : false\n )\n\n useEffect(() => {\n const updateStatus = () => {\n if (navigator) {\n const offline = !pathOr(true, ['onLine'], navigator)\n setOffline(offline)\n }\n }\n\n window.addEventListener('online', updateStatus)\n window.addEventListener('offline', updateStatus)\n\n return () => {\n window.removeEventListener('online', updateStatus)\n window.removeEventListener('offline', updateStatus)\n }\n }, [])\n\n return isOffline\n}\n\nconst useLinkState = client => {\n useEffect(() => {\n const { resolvers, initialState } = createLocalState(client)\n client.addResolvers(resolvers)\n // Add the initial state to if there is not there\n try {\n client.readQuery({ query: fullMinicartQuery })\n } catch (err) {\n client.writeData({ data: initialState })\n }\n\n const minicartData = JSON.parse(localStorage.getItem('minicart'))\n\n if (minicartData) {\n client.writeData({\n data: {\n minicart: {\n __typename: 'Minicart',\n items: JSON.stringify(minicartData),\n },\n },\n })\n }\n }, [client])\n}\n\nconst useUpdateOrderFormOnState = (data, minicartState, updateOrderForm) => {\n // This ref guarantees that the first remote order form after mount will be saved on state, regardless of minicart state\n const hasSavedRemoteOrderFormRef = useRef(false)\n useEffect(\n () => {\n const updateLocalOrderForm = async () => {\n const orderFormData = JSON.parse(localStorage.getItem('orderForm'))\n\n const remoteOrderForm = data.orderForm\n\n if (remoteOrderForm || !orderFormData) {\n const forceRemoteOrderform =\n !hasSavedRemoteOrderFormRef.current && remoteOrderForm\n if (\n forceRemoteOrderform ||\n (!path(['orderForm'], minicartState) && remoteOrderForm)\n ) {\n hasSavedRemoteOrderFormRef.current = true\n await updateOrderForm(remoteOrderForm)\n }\n } else if (!path(['orderForm'], minicartState)) {\n await updateOrderForm(orderFormData)\n }\n }\n\n updateLocalOrderForm()\n },\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [data, minicartState]\n )\n}\n\nconst partitionItemsAddUpdate = clientItems => {\n return partition(compose(isNil, prop('cartIndex')), clientItems)\n}\n\n/**\n * Minicart component\n */\nconst MiniCart = ({\n labelClasses = DEFAULT_LABEL_CLASSES,\n iconClasses = DEFAULT_ICON_CLASSES,\n openOnHover = false,\n client,\n setMinicartOpen,\n labelMiniCartEmpty,\n linkButtonFinishShopping,\n labelButtonFinishShopping,\n iconSize,\n iconLabel,\n showTotalItemsQty,\n showPrice,\n showDiscount,\n data,\n linkState,\n type,\n hideContent,\n showShippingCost,\n updateOrderForm,\n intl,\n updateItemsMutation,\n addToCartMutation,\n updateLocalItemStatus,\n iconsProps,\n}) => {\n useLinkState(client)\n\n const [isUpdatingOrderForm, setUpdatingOrderForm] = useState(false)\n const isOffline = useOffline()\n\n const {\n hints: { mobile },\n navigate,\n } = useRuntime()\n const { showToast } = useContext(ToastContext)\n\n const minicartState = linkState.minicart || {}\n\n const localOrderForm = useMemo(() => {\n try {\n return JSON.parse(minicartState.orderForm)\n } catch (e) {\n return undefined\n }\n }, [minicartState.orderForm])\n\n const orderForm = pathOr(localOrderForm, ['orderForm'], data)\n const orderFormId =\n orderForm && orderForm.orderFormId ? orderForm.orderFormId : undefined\n\n useCartIdPixel(orderFormId)\n\n const minicartItems = useMemo(() => {\n try {\n return JSON.parse(minicartState.items)\n } catch (e) {\n return []\n }\n }, [minicartState.items])\n\n const modifiedItems = useMemo(\n () =>\n minicartItems.filter(\n ({ localStatus }) => localStatus === ITEMS_STATUS.MODIFIED\n ),\n [minicartItems]\n )\n\n useUpdateOrderFormOnState(data, minicartState, updateOrderForm)\n\n // synchronize values with local storage\n useEffect(() => {\n if (orderForm) {\n localStorage.setItem('minicart', JSON.stringify(minicartItems))\n localStorage.setItem('orderForm', JSON.stringify(orderForm))\n }\n }, [minicartItems, orderForm])\n\n const { utmParams, utmiParams } = useMarketingSessionParams()\n\n const addItems = useCallback(\n items => {\n if (!items.length || !orderFormId) {\n return null\n }\n\n return addToCartMutation({\n variables: {\n orderFormId,\n items,\n ...(utmParams ? { utmParams } : {}),\n ...(utmiParams ? { utmiParams } : {}),\n },\n })\n },\n [orderFormId, addToCartMutation, utmParams, utmiParams]\n )\n\n const mutateUpdateItems = useCallback(\n items => {\n if (!items.length || !orderFormId) {\n return null\n }\n\n return updateItemsMutation({\n variables: { orderFormId, items },\n })\n },\n [orderFormId, updateItemsMutation]\n )\n\n const { push } = usePixel()\n\n const orderFormRef = useRef(orderForm)\n\n const { url: checkoutUrl } = useCheckoutURL()\n\n useEffect(() => {\n orderFormRef.current = orderForm\n }, [orderForm])\n\n useEffect(\n () => {\n if (!isOffline) {\n updateLocalItemStatus()\n }\n },\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [isOffline]\n )\n\n useEffect(\n () => {\n let isCurrent = true\n\n const syncItemsWithServer = async () => {\n if (!modifiedItems.length) {\n return\n }\n\n const prevOrderForm = orderFormRef.current\n\n try {\n setUpdatingOrderForm(true)\n\n const [itemsToAdd, itemsToUpdate] = partitionItemsAddUpdate(\n modifiedItems\n )\n const pickProps = map(\n pick(['id', 'index', 'quantity', 'seller', 'options'])\n )\n\n // server mutation\n const updateItemsResponse = await mutateUpdateItems(\n pickProps(itemsToUpdate)\n )\n\n // server mutation\n const addItemsResponse = await addItems(pickProps(itemsToAdd))\n\n if (itemsToAdd.length > 0) {\n push({\n event: 'addToCart',\n items: itemsToAdd.map(mapBuyButtonItemToPixel),\n })\n }\n\n if (!isCurrent) {\n return\n }\n\n const newOrderForm = pathOr(\n path(['data', 'updateItems'], updateItemsResponse),\n ['data', 'addItem'],\n addItemsResponse\n )\n\n push({\n event: 'cartChanged',\n items:\n newOrderForm && newOrderForm.items\n ? newOrderForm.items.map(mapCartItemToPixel)\n : [],\n })\n\n setUpdatingOrderForm(false)\n await updateOrderForm(newOrderForm, true)\n } catch (err) {\n // TODO: Toast error message into Alert\n console.error(err)\n\n if (!isCurrent) {\n return\n }\n\n // Rollback items and orderForm\n setUpdatingOrderForm(false)\n await updateOrderForm(prevOrderForm, true)\n\n showToast({\n message: intl.formatMessage({\n id: 'store/minicart.checkout-failure',\n }),\n })\n }\n }\n\n if (isOffline) {\n setUpdatingOrderForm(updating => (updating ? false : updating))\n return\n }\n\n syncItemsWithServer()\n\n return () => {\n isCurrent = false\n }\n },\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [\n intl,\n isOffline,\n showToast,\n addItems,\n mutateUpdateItems,\n modifiedItems,\n push,\n ]\n )\n\n const handleClickButton = event => {\n if (!hideContent) {\n setMinicartOpen(!minicartState.isOpen)\n }\n event.persist()\n }\n\n const handleUpdateContentVisibility = () => {\n setMinicartOpen(false)\n }\n\n const handleClickProduct = detailUrl => {\n setMinicartOpen(false)\n navigate({\n to: detailUrl,\n })\n }\n\n const getFilteredItems = () => {\n return minicartItems.filter(shouldShowItem)\n }\n\n const itemsToShow = getFilteredItems()\n const totalItemsSum = arr =>\n arr.reduce((sum, product) => sum + product.quantity, 0)\n const quantity = showTotalItemsQty\n ? totalItemsSum(itemsToShow)\n : itemsToShow.length\n\n const isSizeLarge =\n (type && type === 'sidebar') ||\n mobile ||\n (window && window.innerWidth <= 480)\n\n const isOpen = pathOr(false, ['isOpen'], minicartState)\n\n useViewCartPixel(isOpen, minicartItems)\n\n const miniCartContent = (\n <MiniCartContent\n isSizeLarge={isSizeLarge}\n itemsToShow={itemsToShow}\n orderForm={{\n ...orderForm,\n items: minicartItems,\n }}\n loading={data.loading}\n showDiscount={showDiscount}\n labelMiniCartEmpty={labelMiniCartEmpty}\n linkButton={linkButtonFinishShopping || checkoutUrl}\n labelButton={labelButtonFinishShopping}\n onClickProduct={handleClickProduct}\n onClickAction={handleUpdateContentVisibility}\n showShippingCost={showShippingCost}\n updatingOrderForm={isUpdatingOrderForm}\n iconsProps={iconsProps}\n />\n )\n\n const priceClasses = classNames(\n `${styles.label} dn-m db-l t-action--small ${labelClasses}`,\n {\n pl6: quantity > 0,\n pl4: quantity <= 0,\n }\n )\n\n const isPriceVisible = showPrice && orderForm && orderForm.value > 0\n const iconLabelClasses = classNames(\n `${styles.label} dn-m db-l ${\n isPriceVisible ? 't-mini' : 't-action--small'\n } ${labelClasses}`,\n {\n pl6: quantity > 0,\n pl4: quantity <= 0,\n }\n )\n\n // This feature should only work for the popup minicart\n const shouldOpenOnHover = openOnHover && !isSizeLarge\n\n return (\n <aside className={`${styles.container} relative fr flex items-center`}>\n <div\n onMouseEnter={\n shouldOpenOnHover ? () => setMinicartOpen(true) : undefined\n }\n className=\"flex flex-column\"\n >\n <ButtonWithIcon\n icon={\n <span className={`relative ${iconClasses}`}>\n <IconCart size={iconSize} {...iconsProps} />\n {quantity > 0 && (\n <span\n data-testid=\"item-qty\"\n className={`${styles.badge} c-on-emphasis absolute t-mini bg-emphasis br4 w1 h1 pa1 flex justify-center items-center lh-solid`}\n >\n {quantity}\n </span>\n )}\n </span>\n }\n variation=\"tertiary\"\n onClick={handleClickButton}\n >\n {(iconLabel || isPriceVisible) && (\n <span className=\"flex items-center\">\n <span className=\"flex flex-column items-start\">\n {iconLabel && (\n <span className={iconLabelClasses}>{iconLabel}</span>\n )}\n {isPriceVisible && (\n <span data-testid=\"total-price\" className={priceClasses}>\n <div>\n <ProductPrice\n showLabels={false}\n showListPrice={false}\n sellingPrice={orderForm.value}\n />\n </div>\n </span>\n )}\n </span>\n </span>\n )}\n </ButtonWithIcon>\n {!hideContent &&\n (isSizeLarge ? (\n <Sidebar\n quantity={quantity}\n iconSize={iconSize}\n onOutsideClick={handleUpdateContentVisibility}\n isOpen={isOpen}\n iconsProps={iconsProps}\n >\n {miniCartContent}\n </Sidebar>\n ) : (\n isOpen && (\n <Popup onOutsideClick={handleUpdateContentVisibility}>\n {miniCartContent}\n </Popup>\n )\n ))}\n </div>\n </aside>\n )\n}\n\nconst withLinkStateUpdateItemsMutation = graphql(updateItemsMutation, {\n name: 'updateLinkStateItems',\n props: ({ updateLinkStateItems }) => ({\n updateLinkStateItems: items =>\n updateLinkStateItems({ variables: { items } }),\n }),\n})\n\nconst withLinkStateUpdateOrderFormMutation = graphql(updateOrderFormMutation, {\n name: 'updateOrderForm',\n props: ({ updateOrderForm }) => ({\n updateOrderForm: (orderForm, forceUpdateItems = false) =>\n updateOrderForm({ variables: { orderForm, forceUpdateItems } }),\n }),\n})\n\nconst withLinkStateUpdateLocalItemStatusMutation = graphql(\n updateLocalItemStatusMutation,\n {\n name: 'updateLocalItemStatus',\n }\n)\n\nconst withLinkStateSetIsOpenMutation = graphql(setMinicartOpenMutation, {\n name: 'setMinicartOpen',\n props: ({ setMinicartOpen }) => ({\n setMinicartOpen: isOpen => setMinicartOpen({ variables: { isOpen } }),\n }),\n})\n\nconst EnhancedMinicart = compose(\n graphql(orderFormQuery, { options: { ssr: false } }),\n graphql(fullMinicartQuery, { name: 'linkState', ssr: false }),\n graphql(addToCart, { name: 'addToCartMutation' }),\n graphql(updateItems, { name: 'updateItemsMutation' }),\n withApollo,\n withLinkStateUpdateItemsMutation,\n withLinkStateUpdateOrderFormMutation,\n withLinkStateUpdateLocalItemStatusMutation,\n withLinkStateSetIsOpenMutation,\n injectIntl\n)(MiniCart)\n\nEnhancedMinicart.schema = {\n title: 'admin/editor.minicart.title',\n description: 'admin/editor.minicart.description',\n type: 'object',\n properties: {\n type: {\n title: 'admin/editor.minicart.type.title',\n type: 'string',\n default: 'popup',\n enum: ['popup', 'sidebar'],\n enumNames: [\n 'admin/editor.minicart.type.popup',\n 'admin/editor.minicart.type.sidebar',\n ],\n widget: {\n 'ui:widget': 'radio',\n 'ui:options': {\n inline: true,\n },\n },\n isLayout: true,\n },\n iconLabel: {\n title: 'admin/editor.minicart.iconLabel.title',\n type: 'string',\n isLayout: false,\n },\n showDiscount: {\n title: 'admin/editor.minicart.showDiscount.title',\n type: 'boolean',\n isLayout: true,\n },\n labelMiniCartEmpty: {\n title: 'admin/editor.minicart.labelMiniCartEmpty.title',\n type: 'string',\n isLayout: false,\n },\n linkButtonFinishShopping: {\n title: 'admin/editor.minicart.linkButtonFinishShopping.title',\n type: 'string',\n isLayout: false,\n },\n labelButtonFinishShopping: {\n title: 'admin/editor.minicart.labelButtonFinishShopping.title',\n type: 'string',\n isLayout: false,\n }\n },\n}\n\nexport default EnhancedMinicart\n\n```"
}
] |
code_minicart_75de2472
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of minicart/react/BaseContent.tsx from the minicart VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React, {\n FC,\n useEffect,\n Children,\n ReactElement,\n Fragment,\n memo,\n} from 'react'\nimport { FormattedMessage } from 'react-intl'\nimport {\n ExtensionPoint,\n useTreePath,\n useRuntime,\n RenderContext,\n} from 'vtex.render-runtime'\nimport { useOrderForm } from 'vtex.order-manager/OrderForm'\nimport { CssHandlesTypes, useCssHandles } from 'vtex.css-handles'\n\nimport { useMinicartState } from './MinicartContext'\nimport styles from './styles.css'\nimport { mapCartItemToPixel } from './modules/pixelHelper'\nimport useDebouncedPush from './modules/debouncedPixelHook'\nimport CheckoutButton from './CheckoutButton'\n\nconst CSS_HANDLES = [\n 'minicartContentContainer',\n 'minicartProductListContainer',\n 'minicartTitle',\n 'minicartFooter',\n] as const\n\ninterface Props {\n sideBarMode: boolean\n finishShoppingButtonLink: string\n classes?: CssHandlesTypes.CustomClasses<typeof CSS_HANDLES>\n}\n\n// eslint-disable-next-line react/display-name\nconst MinicartHeader: FC<{ minicartTitleHandle: string }> = memo(\n ({ minicartTitleHandle }) => (\n <h3\n className={`${minicartTitleHandle} t-heading-3 mv2 ph4 ph6-l c-on-base`}\n >\n <FormattedMessage id=\"store/minicart.title\" />\n </h3>\n )\n)\n\nconst Content: FC<Props> = ({\n finishShoppingButtonLink,\n classes,\n children,\n}) => {\n const { orderForm, loading }: OrderFormContext = useOrderForm()\n const push = useDebouncedPush()\n const { handles } = useCssHandles(CSS_HANDLES, { classes })\n const { variation } = useMinicartState()\n const { extensions } = useRuntime() as RenderContext\n const { treePath } = useTreePath()\n\n useEffect(() => {\n if (loading) {\n return\n }\n\n // if additionalInfo is undefined for the most recent item, orderForm is still updating\n // and therefore we should not emit the pixel event yet\n if (\n orderForm.items.length > 0 &&\n orderForm.items[orderForm.items.length - 1].additionalInfo === undefined\n ) {\n return\n }\n\n push({\n event: 'cartChanged',\n items: orderForm.items.map(mapCartItemToPixel),\n })\n }, [push, loading, orderForm.items])\n\n const minicartContentClasses = `${handles.minicartContentContainer} ${\n variation === 'drawer' ? styles.drawerStyles : styles.popupStyles\n } flex flex-column justify-between`\n\n const minicartFooterClasses = `${handles.minicartFooter} ${\n variation === 'drawer' ? '' : 'pv3'\n } sticky`\n\n const isCartEmpty = !loading && orderForm.items.length === 0\n\n /**\n * The logic below is to check if the user provided the blocks\n * 'minicart-product-list' and 'minicart-summary' via 'blocks'\n * instead of 'children' in their implementation of 'minicart-base-content'.\n * The blocksFromUserImplementation variable represents the result of concatenating\n * the 'blocks' and the 'children' arrays from blocks.json.\n */\n const blocksFromUserImplementation = extensions[treePath].blocks\n const minicartBlocksFromUserImplementation = blocksFromUserImplementation?.filter(\n block =>\n !block.children &&\n (block.extensionPointId === 'minicart-product-list' ||\n block.extensionPointId === 'minicart-summary')\n )\n const shouldRenderUsingBlocks =\n minicartBlocksFromUserImplementation?.length === 2\n\n if (isCartEmpty) {\n return (\n <Fragment>\n <MinicartHeader minicartTitleHandle={handles.minicartTitle} />\n <ExtensionPoint id=\"minicart-empty-state\" />\n </Fragment>\n )\n }\n\n if (shouldRenderUsingBlocks) {\n return (\n <div className={minicartContentClasses}>\n <div\n className={`w-100 h-100 overflow-y-auto ${handles.minicartProductListContainer}`}\n >\n <MinicartHeader minicartTitleHandle={handles.minicartTitle} />\n <ExtensionPoint id=\"minicart-product-list\" />\n </div>\n <div className={minicartFooterClasses}>\n <ExtensionPoint id=\"minicart-summary\" />\n <CheckoutButton finishShoppingButtonLink={finishShoppingButtonLink} />\n </div>\n </div>\n )\n }\n\n return (\n <div className={minicartContentClasses}>\n <MinicartHeader minicartTitleHandle={handles.minicartTitle} />\n {Children.map(children, child =>\n React.cloneElement(child as ReactElement, { renderAsChildren: true })\n )}\n </div>\n )\n}\n\nexport default Content\n\n```"
}
] |
code_minicart_4847e8f3
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of minicart/react/EmptyState.tsx from the minicart VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React, { FC } from 'react'\nimport { useCssHandles, CssHandlesTypes } from 'vtex.css-handles'\n\nconst CSS_HANDLES = ['minicartEmptyStateContainer'] as const\n\ninterface Props {\n classes?: CssHandlesTypes.CustomClasses<typeof CSS_HANDLES>\n}\n\nconst EmptyState: FC<Props> = ({ classes, children }) => {\n const { handles } = useCssHandles(CSS_HANDLES, { classes })\n\n return (\n <div\n className={`${handles.minicartEmptyStateContainer} h-100 flex flex-column justify-center`}\n >\n {children}\n </div>\n )\n}\n\nexport default EmptyState\n\n```"
}
] |
code_minicart_88df3668
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of minicart/react/CheckoutButton.tsx from the minicart VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\nimport { FormattedMessage } from 'react-intl'\nimport { Button } from 'vtex.styleguide'\nimport { CssHandlesTypes, useCssHandles } from 'vtex.css-handles'\nimport { useCheckoutURL } from 'vtex.checkout-resources/Utils'\n\nimport useCheckout from './modules/checkoutHook'\n\nconst CSS_HANDLES = ['minicartCheckoutButton'] as const\n\ninterface Props {\n finishShoppingButtonLink: string\n classes?: CssHandlesTypes.CustomClasses<typeof CSS_HANDLES>\n}\n\nconst CheckoutButton: StoreFunctionComponent<Props> = ({\n finishShoppingButtonLink,\n classes,\n}): JSX.Element => {\n const { url: checkoutUrl } = useCheckoutURL()\n const { handles } = useCssHandles(CSS_HANDLES, { classes })\n const goToCheckout = useCheckout()\n\n return (\n <div className={`${handles.minicartCheckoutButton} mv3 ph4 ph6-l`}>\n <Button\n id=\"proceed-to-checkout\"\n onClick={() => goToCheckout(finishShoppingButtonLink || checkoutUrl)}\n variation=\"primary\"\n block\n >\n <FormattedMessage id=\"store/minicart.go-to-checkout\" />\n </Button>\n </div>\n )\n}\n\nCheckoutButton.schema = {\n title: 'store/finish-shopping-button-label',\n}\n\nexport default CheckoutButton\n\n```"
}
] |
code_minicart_a8aa2b16
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of minicart/react/Summary.tsx from the minicart VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React, { FC } from 'react'\nimport { ExtensionPoint } from 'vtex.render-runtime'\nimport { OrderForm as OrderFormComponent } from 'vtex.order-manager'\nimport { useCssHandles, CssHandlesTypes } from 'vtex.css-handles'\n\nconst CSS_HANDLES = ['minicartSummary'] as const\n\ninterface Props {\n classes?: CssHandlesTypes.CustomClasses<typeof CSS_HANDLES>\n}\n\nconst Summary: FC<Props> = ({ classes }) => {\n const { useOrderForm } = OrderFormComponent\n\n const {\n orderForm: { totalizers, value, items, paymentData },\n } = useOrderForm()\n\n const { handles } = useCssHandles(CSS_HANDLES, { classes })\n\n const originalValue =\n items?.reduce(\n (total: number, item: OrderFormItem) =>\n (total as number) +\n ((item?.listPrice as number) ?? 0) * (item?.quantity ?? 1),\n 0\n ) ?? 0\n\n return (\n <div className={`${handles.minicartSummary} ph4 ph6-l pt5`}>\n <ExtensionPoint\n id=\"checkout-summary\"\n totalizers={totalizers}\n paymentData={paymentData}\n total={value}\n originalTotal={originalValue}\n />\n </div>\n )\n}\n\nexport default Summary\n\n```"
}
] |
code_minicart_e2444006
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of minicart/store/blocks.jsonc from the minicart VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n// This is the default blocks implementation for the minicart-layout\n{\n \"minicart.v2\": {\n \"children\": [\"minicart-base-content\"]\n },\n \"minicart-base-content\": {\n \"blocks\": [\"minicart-empty-state\"],\n \"children\": [\"minicart-product-list\", \"flex-layout.row#minicart-footer\"]\n },\n \"flex-layout.row#minicart-footer\": {\n \"props\": {\n \"blockClass\": \"minicart-footer\"\n },\n \"children\": [\"flex-layout.col#minicart-footer\"]\n },\n \"flex-layout.col#minicart-footer\": {\n \"children\": [\"minicart-summary\", \"minicart-checkout-button\"]\n },\n \"minicart-product-list\": {\n \"blocks\": [\"product-list#minicart\"]\n },\n \"product-list#minicart\": {\n \"blocks\": [\"product-list-content-mobile\"]\n },\n \"minicart-summary\": {\n \"blocks\": [\"checkout-summary.compact#minicart\"]\n },\n\n \"checkout-summary.compact#minicart\": {\n \"children\": [\"summary-totalizers#minicart\"],\n \"props\": {\n \"totalizersToShow\": [\"Items\", \"Discounts\"]\n }\n },\n \"summary-totalizers#minicart\": {\n \"props\": {\n \"showTotal\": true,\n \"showDeliveryTotal\": false\n }\n },\n \"minicart-empty-state\": {\n \"children\": [\"flex-layout.row#empty-state\"]\n },\n \"flex-layout.row#empty-state\": {\n \"children\": [\"flex-layout.col#empty-state\"]\n },\n \"flex-layout.col#empty-state\": {\n \"children\": [\n \"icon-cart#minicart-empty-state\",\n \"rich-text#minicart-default-empty-state\"\n ],\n \"props\": {\n \"horizontalAlign\": \"center\",\n \"verticalAlign\": \"middle\",\n \"rowGap\": 5\n }\n },\n \"icon-cart#minicart-empty-state\": {\n \"props\": {\n \"size\": 64,\n \"blockClass\": \"minicart-empty-state\"\n }\n },\n \"rich-text#minicart-default-empty-state\": {\n \"props\": {\n \"text\": \"Your cart is empty.\"\n }\n }\n}\n\n```"
}
] |
code_minicart_19508493
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of minicart/store/interfaces.json from the minicart VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"minicart\": {\n \"allowed\": [\"sandbox\", \"product-summary\"],\n \"component\": \"index\"\n },\n \"minicart.v2\": {\n \"component\": \"Minicart\",\n \"composition\": \"children\"\n },\n \"minicart-base-content\": {\n \"component\": \"BaseContent\",\n \"allowed\": [\n \"minicart-product-list\",\n \"minicart-summary\",\n \"minicart-empty-state\"\n ],\n \"composition\": \"children\",\n \"render\": \"lazy\"\n },\n \"minicart-product-list\": {\n \"component\": \"ProductList\",\n \"allowed\": [\"product-list\"]\n },\n \"minicart-checkout-button\": {\n \"component\": \"CheckoutButton\",\n \"content\": {\n \"title\": \"store/finish-shopping-button-label\",\n \"properties\": {\n \"finishShoppingButtonLink\": {\n \"type\": \"string\",\n \"title\": \"admin/editor.minicart.linkButtonFinishShopping.title\",\n \"default\": \"/checkout/#/cart\"\n }\n }\n }\n },\n \"minicart-summary\": {\n \"component\": \"Summary\",\n \"allowed\": [\"checkout-summary\"],\n \"render\": \"lazy\"\n },\n \"minicart-empty-state\": {\n \"component\": \"EmptyState\",\n \"composition\": \"children\",\n \"render\": \"lazy\"\n }\n}\n\n```"
}
] |
code_minicart_0d51fb6c
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of minicart/styles/css/vtex.store-icons.css from the minicart VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```css\n.cartIcon--minicart-empty-state {\n color: #979899;\n}\n```"
}
] |
code_minicart_8ae5daaf
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of minicart/styles/css/vtex.flex-layout.css from the minicart VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```css\n.flexRow--minicart-footer {\n box-shadow: 0px 0px 12px rgba(0, 0, 0, 0.15);\n}\n```"
}
] |
code_minicart_af13493b
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of minicart/react/typings/OrderForm.ts from the minicart VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\ninterface OrderFormContext {\n orderForm: OrderForm\n loading: boolean\n}\n\ninterface OrderFormItem {\n additionalInfo: ItemAdditionalInfo\n availability: string\n detailUrl: string\n id: string\n imageUrl: string\n listPrice: number\n measurementUnit: string\n name: string\n price: number\n productId: string\n quantity: number\n sellingPrice: number\n skuName: string\n skuSpecifications: SKUSpecification[]\n uniqueId: string\n productCategories: Record<string, string>\n productCategoryIds: string\n productRefId: string\n refId: string\n parentItemIndex: number | null\n}\n\ninterface OrderFormItemWithIndex extends OrderFormItem {\n index: number\n}\n\ninterface ItemAdditionalInfo {\n brandName: string\n}\n\ninterface SKUSpecification {\n fieldName: string\n fieldValues: string[]\n}\n\ninterface OrderForm {\n id: string\n items: OrderFormItem[]\n marketingData: MarketingData\n totalizers: Totalizer[]\n value: number\n messages: OrderFormMessages\n}\n\ninterface MarketingData {\n coupon: string\n}\n\ninterface Totalizer {\n id: string\n name: string\n value: number\n}\n\ninterface OrderFormMessages {\n couponMessages: Message[]\n generalMessages: Message[]\n}\n\ninterface Message {\n code: string\n status: string\n text: string\n}\n\n```"
}
] |
code_minicart_a420a783
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of minicart/react/typings/vtex.store-drawer.d.ts from the minicart VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\ndeclare module 'vtex.store-drawer' {\n const Drawer: React.FC<any>\n type BackdropMode = 'visible' | 'none'\n}\n\n```"
}
] |
code_minicart_a588ee07
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of minicart/react/typings/css.ts from the minicart VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\ndeclare module '*.css' {\n const css: Record<string, string>\n export default css\n}\n\n```"
}
] |
code_minicart_68b95b6d
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of minicart/react/typings/vtex.render-runtime.d.ts from the minicart VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nexport {}\n\ndeclare module 'vtex.render-runtime' {\n export function useTreePath(): {\n treePath: string\n }\n}\n\n```"
}
] |
code_minicart_51cfb205
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of minicart/react/typings/vtex.order-items.d.ts from the minicart VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\ndeclare module 'vtex.order-items'\ndeclare module 'vtex.order-items/*'\n\n```"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.