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

[User] Show me the implementation of partytown/public/~partytown/partytown-atomics.js from the partytown VTEX app.

[Assistant]
Here's the implementation:

```javascript
/* Partytown 0.7.4 - MIT builder.io */
;(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
          ? N(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) P.includes(t) && (r[t] = String(e[t]))
      return r
    },
    N = t => t instanceof e.top.Error,
    x = (t, r, n, s) =>
      r
        ? ((n = r[0]),
          (s = r[1]),
          0 === n
            ? s
            : 4 === n
            ? L(t, s)
            : 1 === n
            ? s.map(e => x(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] = x(e, t[n])
      return r
    },
    P = 'cssText,selectorText,href,media,namespaceURI,prefix,name,conditionText'.split(
      ','
    ),
    U = 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]](...x(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] = x(e, c))
              if (
                'function' == typeof s[u] &&
                ((h = x(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
    },
    H = (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(() => H(e, t))
    },
    O = (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', () => {
            H(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)
      }
    },
    k = () => {
      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, [])
    },
    V = 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]) => D(V, t, e, r, n, s)),
      t
    ),
    F = (e, t, r) => {
      let n = [],
        s = [e, 'Object', n]
      for (r in t) W(n, t, r)
      return s
    },
    D = (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)
        D(e, t, c, l, i, a)
        for (const e in h) W(u, i, e)
        t.push([r, c, u, a, o(i)])
      }
    },
    W = (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)
      }
    },
    _ = 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)
  let q
  ;(async e => {
    const t = new SharedArrayBuffer(1073741824),
      r = new Int32Array(t)
    return (n, s) => {
      const i = s[0],
        o = s[1]
      if (0 === i) {
        const e = (() => {
          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: _('localStorage'),
              O: _('sessionStorage'),
            }
          return (
            ((e, t, r) => {
              void 0 !== t[r] &&
                e.push([
                  r,
                  'Object',
                  Object.keys(t[r].prototype).map(e => [e, 6]),
                  12,
                ])
            })(d.v, $, 'IntersectionObserverEntry'),
            d
          )
        })()
        ;(e.P = t), n.postMessage([1, e])
      } else
        2 === s[0]
          ? n.postMessage([3, k()])
          : 11 === i
          ? e(o, e => {
              const t = JSON.stringify(e),
                n = t.length
              for (let e = 0; e < n; e++) r[e + 1] = t.charCodeAt(e)
              ;(r[0] = n), Atomics.notify(r, 0)
            })
          : ((e, t, r) => {
              4 === t[0]
                ? O(e, a(), $)
                : (r = m[t[1]]) &&
                  (7 === t[0]
                    ? requestAnimationFrame(() => H(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),
                          H(e, t)
                      })(e, r, t[2], t[3]))
            })(n, s)
    }
  })((e, t) => U(q, e).then(t)).then(e => {
    e &&
      ((q = 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,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',
            ],
            { type: 'text/javascript' }
          )
        ),
        { name: 'Partytown 🎉' }
      )),
      (q.onmessage = t => {
        const r = t.data
        12 === r[0] ? U(q, r[1]) : e(q, r)
      }),
      $.addEventListener('pt1', e => O(q, f(e.detail.frameElement), e.detail)))
  })
})(window)

```


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

[User] Show me the implementation of partytown/public/~partytown/partytown.js from the partytown VTEX app.

[Assistant]
Here's the implementation:

```javascript
/* Partytown 0.7.4 - MIT builder.io */
!(function (t, e, n, i, r, o, a, d, s, c, p, l) {
  function u() {
    l ||
      ((l = 1),
      '/' == (a = (o.lib || '/~partytown/') + (o.debug ? 'debug/' : ''))[0] &&
        ((s = e.querySelectorAll('script[type="text/partytown"]')),
        i != t
          ? i.dispatchEvent(new CustomEvent('pt1', { detail: t }))
          : ((d = setTimeout(w, 1e4)),
            e.addEventListener('pt0', f),
            r
              ? h(1)
              : n.serviceWorker
              ? n.serviceWorker
                  .register(a + (o.swPath || 'partytown-sw.js'), { scope: a })
                  .then(function (t) {
                    t.active
                      ? h()
                      : t.installing &&
                        t.installing.addEventListener(
                          'statechange',
                          function (t) {
                            'activated' == t.target.state && h()
                          }
                        )
                  }, console.error)
              : w())))
  }
  function h(t) {
    ;(c = e.createElement(t ? 'script' : 'iframe')),
      t ||
        (c.setAttribute(
          'style',
          'display:block;width:0;height:0;border:0;visibility:hidden'
        ),
        c.setAttribute('aria-hidden', !0)),
      (c.src =
        a +
        'partytown-' +
        (t ? 'atomics.js?v=0.7.4' : 'sandbox-sw.html?' + Date.now())),
      e.body.appendChild(c)
  }
  function w(t, n) {
    for (f(), t = 0; t < s.length; t++)
      ((n = e.createElement('script')).innerHTML = s[t].innerHTML),
        e.head.appendChild(n)
    c && c.parentNode.removeChild(c)
  }
  function f() {
    clearTimeout(d)
  }
  ;(o = t.partytown || {}),
    i == t &&
      (o.forward || []).map(function (e) {
        ;(p = t),
          e.split('.').map(function (e, n, i) {
            p = p[i[n]] =
              n + 1 < i.length
                ? 'push' == i[n + 1]
                  ? []
                  : p[i[n]] || {}
                : function () {
                    ;(t._ptf = t._ptf || []).push(i, arguments)
                  }
          })
      }),
    'complete' == e.readyState
      ? u()
      : (t.addEventListener('DOMContentLoaded', u),
        t.addEventListener('load', u))
})(window, document, navigator, top, window.crossOriginIsolated)

```


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

[User] Show me the implementation of partytown/public/~partytown/partytown-media.js from the partytown VTEX app.

[Assistant]
Here's the implementation:

```javascript
/* Partytown 0.7.4 - MIT builder.io */
;(e => {
  const [t, s, n, r, i, a, o, d, u] = e.g
  delete e.g
  const c = Symbol(),
    h = Symbol(),
    f = Symbol(),
    p = Symbol(),
    g = Symbol(),
    l = Symbol(),
    m = [],
    v = (e, t, s) => (e[t] = S(t, s)),
    S = (e, t) => Object.defineProperty(t, 'name', { value: e }),
    b = (e, t) => {
      const r = {
          getContext: {
            value(e, t) {
              return (
                this[c] ||
                  (this[c] = (e.includes('webgl') ? g : p)(this, e, t)),
                this[c]
              )
            },
          },
        },
        h = v(
          t,
          'CanvasGradient',
          class extends e {
            addColorStop(...e) {
              n(this, ['addColorStop'], e, 2)
            }
          }
        ),
        f = v(
          t,
          'CanvasPattern',
          class extends e {
            setTransform(...e) {
              n(this, ['setTransform'], e, 2)
            }
          }
        ),
        p = (e, t, r) => {
          const i = e[o],
            c = a(),
            f = { [o]: i, [d]: c, [u]: [] },
            p = n(e, ['getContext'], [t, r], 1, c),
            g = 'getContextAttributes,getImageData,getLineDash,getTransform,isPointInPath,isPointInStroke,measureText'.split(
              ','
            ),
            l = {
              get: (e, t) =>
                'string' == typeof t && t in p
                  ? 'function' == typeof p[t]
                    ? (...e) => {
                        if (t.startsWith('create')) {
                          const r = a()
                          return (
                            n(f, [t], e, 2, r),
                            'createImageData' === t || 'createPattern' === t
                              ? ((s = `${t}()`),
                                console.warn(`${s} not implemented`),
                                { setTransform: () => {} })
                              : new h(i, r)
                          )
                        }
                        var s
                        const r = g.includes(t) ? 1 : 2
                        return n(f, [t], e, r)
                      }
                    : p[t]
                  : e[t],
              set: (e, t, n) => (
                'string' == typeof t && t in p
                  ? (p[t] !== n && 'function' != typeof n && s(f, [t], n),
                    (p[t] = n))
                  : (e[t] = n),
                !0
              ),
            }
          return new Proxy(p, l)
        },
        g = (e, t, r) => {
          const i = e[o],
            c = a(),
            h = { [o]: i, [d]: c, [u]: [] },
            f = n(e, ['getContext'], [t, r], 1, c),
            p = {
              get: (e, t) =>
                'string' == typeof t
                  ? 'function' != typeof f[t]
                    ? f[t]
                    : (...e) => n(h, [t], e, m(t))
                  : e[t],
              set: (e, t, n) => (
                'string' == typeof t && t in f
                  ? (f[t] !== n && 'function' != typeof n && s(h, [t], n),
                    (f[t] = n))
                  : (e[t] = n),
                !0
              ),
            }
          return new Proxy(f, p)
        },
        l = 'checkFramebufferStatus,makeXRCompatible'.split(','),
        m = e =>
          e.startsWith('create') ||
          e.startsWith('get') ||
          e.startsWith('is') ||
          l.includes(e)
            ? 1
            : 2
      v(t, 'CanvasGradient', h),
        v(t, 'CanvasPattern', f),
        i(t.HTMLCanvasElement, r)
    },
    y = (e, u, c, b) => {
      var y, T
      b.Audio = S(
        'HTMLAudioElement',
        class {
          constructor(e) {
            const t = c.k('audio', a())
            return (t.src = e), t
          }
        }
      )
      const w = class extends e {
          get enabled() {
            return t(this, ['enabled'])
          }
          set enabled(e) {
            s(this, ['enabled'], e)
          }
          get id() {
            return t(this, ['id'])
          }
          get kind() {
            return t(this, ['kind'])
          }
          get label() {
            return t(this, ['label'])
          }
          get language() {
            return t(this, ['language'])
          }
          get sourceBuffer() {
            return new x(this)
          }
        },
        E = class {
          constructor(e) {
            const s = 'audioTracks',
              r = e[o],
              i = e[d]
            return new Proxy(
              {
                addEventListener(...t) {
                  n(e, [s, 'addEventListener'], t, 3)
                },
                getTrackById: (...t) => n(e, [s, 'getTrackById'], t),
                get length() {
                  return t(e, [s, 'length'])
                },
                removeEventListener(...t) {
                  n(e, [s, 'removeEventListener'], t, 3)
                },
              },
              {
                get: (e, t) =>
                  'number' == typeof t ? new w(r, i, [s, t]) : e[t],
              }
            )
          }
        },
        k = v(
          b,
          'SourceBufferList',
          class extends Array {
            constructor(e) {
              super(), (this[h] = e)
            }
            addEventListener(...e) {
              n(this[h], ['sourceBuffers', 'addEventListener'], e, 3)
            }
            removeEventListener(...e) {
              n(this[h], ['sourceBuffers', 'removeEventListener'], e, 3)
            }
          }
        ),
        x = v(
          b,
          'SourceBuffer',
          ((T = class extends u {
            constructor(e) {
              super(e[o], e[d], ['sourceBuffers']),
                (this[y] = []),
                (this[h] = e)
            }
            abort() {
              const e = R(this)
              n(this, [e, 'appendWindowStart'], m, 1)
            }
            addEventListener(...e) {
              const t = R(this)
              n(this, [t, 'addEventListener'], e, 3)
            }
            appendBuffer(e) {
              this[g].push(['appendBuffer', [e], e]), M(this)
            }
            get appendWindowStart() {
              const e = R(this)
              return t(this, [e, 'appendWindowStart'])
            }
            set appendWindowStart(e) {
              const t = R(this)
              s(this, [t, 'appendWindowStart'], e)
            }
            get appendWindowEnd() {
              const e = R(this)
              return t(this, [e, 'appendWindowEnd'])
            }
            set appendWindowEnd(e) {
              const t = R(this)
              s(this, [t, 'appendWindowEnd'], e)
            }
            get buffered() {
              const e = this[h],
                t = R(this)
              return new B(e[o], e[d], ['sourceBuffers', t, 'buffered'])
            }
            changeType(e) {
              const t = R(this)
              n(this, [t, 'changeType'], [e], 2)
            }
            get mode() {
              const e = R(this)
              return t(this, [e, 'mode'])
            }
            set mode(e) {
              const t = R(this)
              s(this, [t, 'mode'], e)
            }
            remove(e, t) {
              this[g].push(['remove', [e, t]]), M(this)
            }
            removeEventListener(...e) {
              const t = R(this)
              n(this, [t, 'removeEventListener'], e, 3)
            }
            get timestampOffset() {
              const e = R(this)
              return t(this, [e, 'timestampOffset'])
            }
            set timestampOffset(e) {
              const t = R(this)
              s(this, [t, 'timestampOffset'], e)
            }
            get updating() {
              const e = R(this)
              return t(this, [e, 'updating'])
            }
          }),
          (y = g),
          T)
        ),
        B = v(
          b,
          'TimeRanges',
          class extends e {
            start(...e) {
              return n(this, ['start'], e)
            }
            end(...e) {
              return n(this, ['end'], e)
            }
            get length() {
              return t(this, ['length'])
            }
          }
        ),
        R = e => (e ? e[h][p].indexOf(e) : -1),
        M = e => {
          if (e[g].length) {
            if (!e.updating) {
              const t = e[g].shift()
              if (t) {
                const s = R(e)
                n(e, [s, t[0]], t[1], 3, void 0, t[2])
              }
            }
            setTimeout(() => M(e), 50)
          }
        },
        W = {
          buffered: {
            get() {
              return (
                this[l] ||
                  ((this[l] = new B(this[o], this[d], ['buffered'])),
                  setTimeout(() => {
                    this[l] = void 0
                  }, 5e3)),
                this[l]
              )
            },
          },
          readyState: {
            get() {
              return 4 === this[f]
                ? 4
                : ('number' != typeof this[f] &&
                    ((this[f] = t(this, ['readyState'])),
                    setTimeout(() => {
                      this[f] = void 0
                    }, 1e3)),
                  this[f])
            },
          },
        }
      v(
        b,
        'MediaSource',
        class extends u {
          constructor() {
            super(c.V), (this[p] = new k(this)), r(this, 'MediaSource', m)
          }
          get activeSourceBuffers() {
            return []
          }
          addSourceBuffer(e) {
            const t = new x(this)
            return this[p].push(t), n(this, ['addSourceBuffer'], [e]), t
          }
          clearLiveSeekableRange() {
            n(this, ['clearLiveSeekableRange'], m, 2)
          }
          get duration() {
            return t(this, ['duration'])
          }
          set duration(e) {
            s(this, ['duration'], e)
          }
          endOfStream(e) {
            n(this, ['endOfStream'], [e], 3)
          }
          get readyState() {
            return t(this, ['readyState'])
          }
          removeSourceBuffer(e) {
            const t = R(e)
            t > -1 &&
              (this[p].splice(t, 1), n(this, ['removeSourceBuffer'], [t], 1))
          }
          setLiveSeekableRange(e, t) {
            n(this, ['setLiveSeekableRange'], [e, t], 2)
          }
          get sourceBuffers() {
            return this[p]
          }
          static isTypeSupported(e) {
            if (!L.has(e)) {
              const t = n(b, ['MediaSource', 'isTypeSupported'], [e])
              L.set(e, t)
            }
            return L.get(e)
          }
        }
      )
      const C = (b.URL = S('URL', class extends URL {}))
      'audioTracks' in b.HTMLMediaElement.prototype &&
        (v(b, 'AudioTrackList', E),
        v(b, 'AudioTrack', w),
        (W.audioTracks = {
          get() {
            return new E(this)
          },
        })),
        i(b.HTMLMediaElement, W),
        (C.createObjectURL = e => n(b, ['URL', 'createObjectURL'], [e])),
        (C.revokeObjectURL = e => n(b, ['URL', 'revokeObjectURL'], [e]))
    },
    L = new Map()
  e.f = (e, t, s, n, r) => {
    r.map(e => {
      delete n[e]
    }),
      b(e, n),
      y(e, t, s, n)
  }
})(self)

```


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

[User] Show me the implementation of partytown/public/metadata/messages/es-AR.json from the partytown VTEX app.

[Assistant]
Here's the implementation:

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

```


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

[User] Show me the implementation of partytown/public/metadata/messages/pt-BR.json from the partytown VTEX app.

[Assistant]
Here's the implementation:

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

```


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

[User] Show me the implementation of partytown/public/metadata/messages/en-US.json from the partytown VTEX app.

[Assistant]
Here's the implementation:

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

```


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

[User] Show me the implementation of partytown/public/~partytown/debug/partytown-sandbox-sw.js from the partytown VTEX app.

[Assistant]
Here's the implementation:

```javascript
/* Partytown 0.7.4 - MIT builder.io */
;(window => {
  const isPromise = v => 'object' == typeof v && v && v.then
  const noop = () => {}
  const len = obj => obj.length
  const getConstructorName = obj => {
    var _a, _b, _c
    try {
      const constructorName =
        null === (_a = null == obj ? void 0 : obj.constructor) || void 0 === _a
          ? void 0
          : _a.name
      if (constructorName) {
        return constructorName
      }
    } catch (e) {}
    try {
      const zoneJsConstructorName =
        null ===
          (_c =
            null ===
              (_b =
                null == obj ? void 0 : obj.__zone_symbol__originalInstance) ||
            void 0 === _b
              ? void 0
              : _b.constructor) || void 0 === _c
          ? void 0
          : _c.name
      if (zoneJsConstructorName) {
        return zoneJsConstructorName
      }
    } catch (e) {}
    return ''
  }
  const startsWith = (str, val) => str.startsWith(val)
  const isValidMemberName = memberName =>
    !(
      startsWith(memberName, 'webkit') ||
      startsWith(memberName, 'toJSON') ||
      startsWith(memberName, 'constructor') ||
      startsWith(memberName, 'toString') ||
      startsWith(memberName, '_')
    )
  const getNodeName = node =>
    11 === node.nodeType && node.host ? '#s' : node.nodeName
  const randomId = () =>
    Math.round(Math.random() * Number.MAX_SAFE_INTEGER).toString(36)
  const defineConstructorName = (Cstr, value) =>
    ((obj, memberName, descriptor) =>
      Object.defineProperty(obj, memberName, {
        ...descriptor,
        configurable: true,
      }))(Cstr, 'name', {
      value: value,
    })
  const htmlConstructorTags = {
    Anchor: 'a',
    DList: 'dl',
    Image: 'img',
    OList: 'ol',
    Paragraph: 'p',
    Quote: 'q',
    TableCaption: 'caption',
    TableCell: 'td',
    TableCol: 'colgroup',
    TableRow: 'tr',
    TableSection: 'tbody',
    UList: 'ul',
  }
  const svgConstructorTags = {
    Graphics: 'g',
    SVG: 'svg',
  }
  const InstanceIdKey = Symbol()
  const CreatedKey = Symbol()
  const instances = new Map()
  const mainRefs = new Map()
  const winCtxs = {}
  const windowIds = new WeakMap()
  const getAndSetInstanceId = (instance, instanceId) => {
    if (instance) {
      if ((instanceId = windowIds.get(instance))) {
        return instanceId
      }
      ;(instanceId = instance[InstanceIdKey]) ||
        setInstanceId(instance, (instanceId = randomId()))
      return instanceId
    }
  }
  const getInstance = (winId, instanceId, win, doc, docId) => {
    if ((win = winCtxs[winId]) && win.$window$) {
      if (winId === instanceId) {
        return win.$window$
      }
      doc = win.$window$.document
      docId = instanceId.split('.').pop()
      if ('d' === docId) {
        return doc
      }
      if ('e' === docId) {
        return doc.documentElement
      }
      if ('h' === docId) {
        return doc.head
      }
      if ('b' === docId) {
        return doc.body
      }
    }
    return instances.get(instanceId)
  }
  const setInstanceId = (instance, instanceId, now) => {
    if (instance) {
      instances.set(instanceId, instance)
      instance[InstanceIdKey] = instanceId
      instance[CreatedKey] = now = Date.now()
      if (now > lastCleanup + 5e3) {
        instances.forEach((storedInstance, instanceId) => {
          storedInstance[CreatedKey] < lastCleanup &&
            storedInstance.nodeType &&
            !storedInstance.isConnected &&
            instances.delete(instanceId)
        })
        lastCleanup = now
      }
    }
  }
  let lastCleanup = 0
  const mainWindow = window.parent
  const docImpl = document.implementation.createHTMLDocument()
  const config = mainWindow.partytown || {}
  const libPath = (config.lib || '/~partytown/') + 'debug/'
  const logMain = msg => {
    console.debug.apply(console, [
      '%cMain 🌎',
      'background: #717171; color: white; padding: 2px 3px; border-radius: 2px; font-size: 0.8em;',
      msg,
    ])
  }
  const winIds = []
  const normalizedWinId = winId => {
    winIds.includes(winId) || winIds.push(winId)
    return winIds.indexOf(winId) + 1
  }
  const defineCustomElement = (winId, worker, ceData) => {
    const Cstr = defineConstructorName(
      class extends winCtxs[winId].$window$.HTMLElement {},
      ceData[0]
    )
    const ceCallbackMethods = 'connectedCallback,disconnectedCallback,attributeChangedCallback,adoptedCallback'.split(
      ','
    )
    ceCallbackMethods.map(
      callbackMethodName =>
        (Cstr.prototype[callbackMethodName] = function (...args) {
          worker.postMessage([
            15,
            winId,
            getAndSetInstanceId(this),
            callbackMethodName,
            args,
          ])
        })
    )
    Cstr.observedAttributes = ceData[1]
    return Cstr
  }
  const serializeForWorker = ($winId$, value, added, type, cstrName) =>
    void 0 !== value && (type = typeof value)
      ? 'string' === type ||
        'number' === type ||
        'boolean' === type ||
        null == value
        ? [0, value]
        : 'function' === type
        ? [6]
        : (added = added || new Set()) && Array.isArray(value)
        ? added.has(value)
          ? [1, []]
          : added.add(value) && [
              1,
              value.map(v => serializeForWorker($winId$, v, added)),
            ]
        : 'object' === type
        ? serializedValueIsError(value)
          ? [
              14,
              {
                name: value.name,
                message: value.message,
                stack: value.stack,
              },
            ]
          : '' === (cstrName = getConstructorName(value))
          ? [2, {}]
          : 'Window' === cstrName
          ? [3, [$winId$, $winId$]]
          : 'HTMLCollection' === cstrName || 'NodeList' === cstrName
          ? [
              7,
              Array.from(value).map(
                v => serializeForWorker($winId$, v, added)[1]
              ),
            ]
          : cstrName.endsWith('Event')
          ? [5, serializeObjectForWorker($winId$, value, added)]
          : 'CSSRuleList' === cstrName
          ? [12, Array.from(value).map(serializeCssRuleForWorker)]
          : startsWith(cstrName, 'CSS') && cstrName.endsWith('Rule')
          ? [11, serializeCssRuleForWorker(value)]
          : 'CSSStyleDeclaration' === cstrName
          ? [13, serializeObjectForWorker($winId$, value, added)]
          : 'Attr' === cstrName
          ? [10, [value.name, value.value]]
          : value.nodeType
          ? [3, [$winId$, getAndSetInstanceId(value), getNodeName(value)]]
          : [2, serializeObjectForWorker($winId$, value, added, true, true)]
        : void 0
      : value
  const serializeObjectForWorker = (
    winId,
    obj,
    added,
    includeFunctions,
    includeEmptyStrings,
    serializedObj,
    propName,
    propValue
  ) => {
    serializedObj = {}
    if (!added.has(obj)) {
      added.add(obj)
      for (propName in obj) {
        if (isValidMemberName(propName)) {
          propValue =
            'path' === propName && getConstructorName(obj).endsWith('Event')
              ? obj.composedPath()
              : obj[propName]
          ;(includeFunctions || 'function' != typeof propValue) &&
            (includeEmptyStrings || '' !== propValue) &&
            (serializedObj[propName] = serializeForWorker(
              winId,
              propValue,
              added
            ))
        }
      }
    }
    return serializedObj
  }
  const serializeCssRuleForWorker = cssRule => {
    let obj = {}
    let key
    for (key in cssRule) {
      validCssRuleProps.includes(key) && (obj[key] = String(cssRule[key]))
    }
    return obj
  }
  const serializedValueIsError = value => value instanceof window.top.Error
  const deserializeFromWorker = (
    worker,
    serializedTransfer,
    serializedType,
    serializedValue
  ) => {
    if (serializedTransfer) {
      serializedType = serializedTransfer[0]
      serializedValue = serializedTransfer[1]
      return 0 === serializedType
        ? serializedValue
        : 4 === serializedType
        ? deserializeRefFromWorker(worker, serializedValue)
        : 1 === serializedType
        ? serializedValue.map(v => deserializeFromWorker(worker, v))
        : 3 === serializedType
        ? getInstance(serializedValue[0], serializedValue[1])
        : 5 === serializedType
        ? constructEvent(deserializeObjectFromWorker(worker, serializedValue))
        : 2 === serializedType
        ? deserializeObjectFromWorker(worker, serializedValue)
        : 8 === serializedType
        ? serializedValue
        : 9 === serializedType
        ? new window[serializedTransfer[2]](serializedValue)
        : void 0
    }
  }
  const deserializeRefFromWorker = (
    worker,
    { $winId$: $winId$, $instanceId$: $instanceId$, $refId$: $refId$ },
    ref
  ) => {
    ref = mainRefs.get($refId$)
    if (!ref) {
      ref = function (...args) {
        worker.postMessage([
          9,
          {
            $winId$: $winId$,
            $instanceId$: $instanceId$,
            $refId$: $refId$,
            $thisArg$: serializeForWorker($winId$, this),
            $args$: serializeForWorker($winId$, args),
          },
        ])
      }
      mainRefs.set($refId$, ref)
    }
    return ref
  }
  const constructEvent = eventProps =>
    new ('detail' in eventProps ? CustomEvent : Event)(
      eventProps.type,
      eventProps
    )
  const deserializeObjectFromWorker = (worker, serializedValue, obj, key) => {
    obj = {}
    for (key in serializedValue) {
      obj[key] = deserializeFromWorker(worker, serializedValue[key])
    }
    return obj
  }
  const validCssRuleProps = 'cssText,selectorText,href,media,namespaceURI,prefix,name,conditionText'.split(
    ','
  )
  const mainAccessHandler = async (worker, accessReq) => {
    let accessRsp = {
      $msgId$: accessReq.$msgId$,
    }
    let totalTasks = len(accessReq.$tasks$)
    let i = 0
    let task
    let winId
    let applyPath
    let instance
    let rtnValue
    let isLast
    for (; i < totalTasks; i++) {
      try {
        isLast = i === totalTasks - 1
        task = accessReq.$tasks$[i]
        winId = task.$winId$
        applyPath = task.$applyPath$
        !winCtxs[winId] &&
          winId.startsWith('f_') &&
          (await new Promise(resolve => {
            let check = 0
            let callback = () => {
              winCtxs[winId] || check++ > 1e3
                ? resolve()
                : requestAnimationFrame(callback)
            }
            callback()
          }))
        if (1 === applyPath[0] && applyPath[1] in winCtxs[winId].$window$) {
          setInstanceId(
            new winCtxs[winId].$window$[applyPath[1]](
              ...deserializeFromWorker(worker, applyPath[2])
            ),
            task.$instanceId$
          )
        } else {
          instance = getInstance(winId, task.$instanceId$)
          if (instance) {
            rtnValue = applyToInstance(
              worker,
              winId,
              instance,
              applyPath,
              isLast,
              task.$groupedGetters$
            )
            task.$assignInstanceId$ &&
              ('string' == typeof task.$assignInstanceId$
                ? setInstanceId(rtnValue, task.$assignInstanceId$)
                : (winCtxs[task.$assignInstanceId$.$winId$] = {
                    $winId$: task.$assignInstanceId$.$winId$,
                    $window$: {
                      document: rtnValue,
                    },
                  }))
            if (isPromise(rtnValue)) {
              rtnValue = await rtnValue
              isLast && (accessRsp.$isPromise$ = true)
            }
            isLast &&
              (accessRsp.$rtnValue$ = serializeForWorker(winId, rtnValue))
          } else {
            accessRsp.$error$ = `Error finding instance "${
              task.$instanceId$
            }" on window ${normalizedWinId(winId)}`
            console.error(accessRsp.$error$, task)
          }
        }
      } catch (e) {
        isLast ? (accessRsp.$error$ = String(e.stack || e)) : console.error(e)
      }
    }
    return accessRsp
  }
  const applyToInstance = (
    worker,
    winId,
    instance,
    applyPath,
    isLast,
    groupedGetters
  ) => {
    let i = 0
    let l = len(applyPath)
    let next
    let current
    let previous
    let args
    let groupedRtnValues
    for (; i < l; i++) {
      current = applyPath[i]
      next = applyPath[i + 1]
      previous = applyPath[i - 1]
      try {
        if (!Array.isArray(next)) {
          if ('string' == typeof current || 'number' == typeof current) {
            if (i + 1 === l && groupedGetters) {
              groupedRtnValues = {}
              groupedGetters.map(
                propName => (groupedRtnValues[propName] = instance[propName])
              )
              return groupedRtnValues
            }
            instance = instance[current]
          } else {
            if (0 === next) {
              instance[previous] = deserializeFromWorker(worker, current)
              return
            }
            if ('function' == typeof instance[previous]) {
              args = deserializeFromWorker(worker, current)
              'define' === previous &&
                'CustomElementRegistry' === getConstructorName(instance) &&
                (args[1] = defineCustomElement(winId, worker, args[1]))
              'insertRule' === previous &&
                args[1] > len(instance.cssRules) &&
                (args[1] = len(instance.cssRules))
              instance = instance[previous].apply(instance, args)
              if ('play' === previous) {
                return Promise.resolve()
              }
            }
          }
        }
      } catch (err) {
        if (isLast) {
          throw err
        }
        console.debug('Non-blocking setter error:', err)
      }
    }
    return instance
  }
  const readNextScript = (worker, winCtx) => {
    let $winId$ = winCtx.$winId$
    let win = winCtx.$window$
    let doc = win.document
    let scriptSelector =
      'script[type="text/partytown"]:not([data-ptid]):not([data-pterror])'
    let scriptElm
    let $instanceId$
    let scriptData
    if (doc && doc.body) {
      scriptElm = doc.querySelector(
        'script[type="text/partytown"]:not([data-ptid]):not([data-pterror]):not([async]):not([defer])'
      )
      scriptElm || (scriptElm = doc.querySelector(scriptSelector))
      if (scriptElm) {
        scriptElm.dataset.ptid = $instanceId$ = getAndSetInstanceId(
          scriptElm,
          $winId$
        )
        scriptData = {
          $winId$: $winId$,
          $instanceId$: $instanceId$,
        }
        if (scriptElm.src) {
          scriptData.$url$ = scriptElm.src
          scriptData.$orgUrl$ = scriptElm.dataset.ptsrc || scriptElm.src
        } else {
          scriptData.$content$ = scriptElm.innerHTML
        }
        worker.postMessage([7, scriptData])
      } else {
        if (!winCtx.$isInitialized$) {
          winCtx.$isInitialized$ = 1
          ;((worker, $winId$, win) => {
            let queuedForwardCalls = win._ptf
            let forwards = (win.partytown || {}).forward || []
            let i
            let mainForwardFn
            let forwardCall = ($forward$, args) =>
              worker.postMessage([
                10,
                {
                  $winId$: $winId$,
                  $forward$: $forward$,
                  $args$: serializeForWorker($winId$, Array.from(args)),
                },
              ])
            win._ptf = void 0
            forwards.map(forwardProps => {
              mainForwardFn = win
              forwardProps.split('.').map((_, i, arr) => {
                mainForwardFn = mainForwardFn[arr[i]] =
                  i + 1 < len(arr)
                    ? mainForwardFn[arr[i]] || ('push' === arr[i + 1] ? [] : {})
                    : (...args) => forwardCall(arr, args)
              })
            })
            if (queuedForwardCalls) {
              for (i = 0; i < len(queuedForwardCalls); i += 2) {
                forwardCall(queuedForwardCalls[i], queuedForwardCalls[i + 1])
              }
            }
          })(worker, $winId$, win)
          doc.dispatchEvent(new CustomEvent('pt0'))
          {
            const winType = win === win.top ? 'top' : 'iframe'
            logMain(
              `Executed ${winType} window ${normalizedWinId(
                $winId$
              )} environment scripts in ${(
                performance.now() - winCtx.$startTime$
              ).toFixed(1)}ms`
            )
          }
        }
        worker.postMessage([8, $winId$])
      }
    } else {
      requestAnimationFrame(() => readNextScript(worker, winCtx))
    }
  }
  const registerWindow = (worker, $winId$, $window$) => {
    if (!windowIds.has($window$)) {
      windowIds.set($window$, $winId$)
      const doc = $window$.document
      const history = $window$.history
      const $parentWinId$ = windowIds.get($window$.parent)
      let initialised = false
      const onInitialisedQueue = []
      const onInitialised = callback => {
        initialised ? callback() : onInitialisedQueue.push(callback)
      }
      const sendInitEnvData = () => {
        worker.postMessage([
          5,
          {
            $winId$: $winId$,
            $parentWinId$: $parentWinId$,
            $url$: doc.baseURI,
            $visibilityState$: doc.visibilityState,
          },
        ])
        setTimeout(() => {
          initialised = true
          onInitialisedQueue.forEach(callback => {
            callback()
          })
        })
      }
      const pushState = history.pushState.bind(history)
      const replaceState = history.replaceState.bind(history)
      const onLocationChange = (type, state, newUrl, oldUrl) => () => {
        setTimeout(() => {
          worker.postMessage([
            13,
            {
              $winId$: $winId$,
              type: type,
              state: state,
              url: doc.baseURI,
              newUrl: newUrl,
              oldUrl: oldUrl,
            },
          ])
        })
      }
      history.pushState = (state, _, newUrl) => {
        pushState(state, _, newUrl)
        onInitialised(
          onLocationChange(
            0,
            state,
            null == newUrl ? void 0 : newUrl.toString()
          )
        )
      }
      history.replaceState = (state, _, newUrl) => {
        replaceState(state, _, newUrl)
        onInitialised(
          onLocationChange(
            1,
            state,
            null == newUrl ? void 0 : newUrl.toString()
          )
        )
      }
      $window$.addEventListener('popstate', event => {
        onInitialised(onLocationChange(2, event.state))
      })
      $window$.addEventListener('hashchange', event => {
        onInitialised(onLocationChange(3, {}, event.newURL, event.oldURL))
      })
      $window$.addEventListener('ptupdate', () => {
        readNextScript(worker, winCtxs[$winId$])
      })
      doc.addEventListener('visibilitychange', () =>
        worker.postMessage([14, $winId$, doc.visibilityState])
      )
      winCtxs[$winId$] = {
        $winId$: $winId$,
        $window$: $window$,
      }
      winCtxs[$winId$].$startTime$ = performance.now()
      {
        const winType = $winId$ === $parentWinId$ ? 'top' : 'iframe'
        logMain(`Registered ${winType} window ${normalizedWinId($winId$)}`)
      }
      'complete' === doc.readyState
        ? sendInitEnvData()
        : $window$.addEventListener('load', sendInitEnvData)
    }
  }
  const onMessageFromWebWorker = (worker, msg, winCtx) => {
    if (4 === msg[0]) {
      registerWindow(worker, randomId(), mainWindow)
    } else {
      winCtx = winCtxs[msg[1]]
      winCtx &&
        (7 === msg[0]
          ? requestAnimationFrame(() => readNextScript(worker, winCtx))
          : 6 === msg[0] &&
            ((worker, winCtx, instanceId, errorMsg, scriptElm) => {
              scriptElm = winCtx.$window$.document.querySelector(
                `[data-ptid="${instanceId}"]`
              )
              if (scriptElm) {
                errorMsg
                  ? (scriptElm.dataset.pterror = errorMsg)
                  : (scriptElm.type += '-x')
                delete scriptElm.dataset.ptid
              }
              readNextScript(worker, winCtx)
            })(worker, winCtx, msg[2], msg[3]))
    }
  }
  const readMainPlatform = () => {
    const elm = docImpl.createElement('i')
    const textNode = docImpl.createTextNode('')
    const comment = docImpl.createComment('')
    const frag = docImpl.createDocumentFragment()
    const shadowRoot = docImpl.createElement('p').attachShadow({
      mode: 'open',
    })
    const intersectionObserver = getGlobalConstructor(
      mainWindow,
      'IntersectionObserver'
    )
    const mutationObserver = getGlobalConstructor(
      mainWindow,
      'MutationObserver'
    )
    const resizeObserver = getGlobalConstructor(mainWindow, 'ResizeObserver')
    const perf = mainWindow.performance
    const screen = mainWindow.screen
    const impls = [
      [mainWindow.history],
      [perf],
      [perf.navigation],
      [perf.timing],
      [screen],
      [screen.orientation],
      [mainWindow.visualViewport],
      [intersectionObserver, 12],
      [mutationObserver, 12],
      [resizeObserver, 12],
      [textNode],
      [comment],
      [frag],
      [shadowRoot],
      [elm],
      [elm.attributes],
      [elm.classList],
      [elm.dataset],
      [elm.style],
      [docImpl],
      [docImpl.doctype],
    ]
    const initialInterfaces = [
      readImplementation('Window', mainWindow),
      readImplementation('Node', textNode),
    ]
    const $config$ = JSON.stringify(config, (k, v) => {
      if ('function' == typeof v) {
        v = String(v)
        v.startsWith(k + '(') && (v = 'function ' + v)
      }
      return v
    })
    const initWebWorkerData = {
      $config$: $config$,
      $interfaces$: readImplementations(impls, initialInterfaces),
      $libPath$: new URL(libPath, mainWindow.location) + '',
      $origin$: origin,
      $localStorage$: readStorage('localStorage'),
      $sessionStorage$: readStorage('sessionStorage'),
    }
    addGlobalConstructorUsingPrototype(
      initWebWorkerData.$interfaces$,
      mainWindow,
      'IntersectionObserverEntry'
    )
    return initWebWorkerData
  }
  const readMainInterfaces = () => {
    const elms = Object.getOwnPropertyNames(mainWindow)
      .map(interfaceName =>
        ((doc, interfaceName, r, tag) => {
          r = interfaceName.match(/^(HTML|SVG)(.+)Element$/)
          if (r) {
            tag = r[2]
            return 'S' == interfaceName[0]
              ? doc.createElementNS(
                  'http://www.w3.org/2000/svg',
                  svgConstructorTags[tag] ||
                    tag.slice(0, 2).toLowerCase() + tag.slice(2)
                )
              : doc.createElement(htmlConstructorTags[tag] || tag)
          }
        })(docImpl, interfaceName)
      )
      .filter(elm => elm)
      .map(elm => [elm])
    return readImplementations(elms, [])
  }
  const cstrs = new Set(['Object'])
  const readImplementations = (impls, interfaces) => {
    const cstrImpls = impls
      .filter(implData => implData[0])
      .map(implData => {
        const impl = implData[0]
        const interfaceType = implData[1]
        const cstrName = getConstructorName(impl)
        const CstrPrototype = mainWindow[cstrName].prototype
        return [cstrName, CstrPrototype, impl, interfaceType]
      })
    cstrImpls.map(([cstrName, CstrPrototype, impl, intefaceType]) =>
      readOwnImplementation(
        cstrs,
        interfaces,
        cstrName,
        CstrPrototype,
        impl,
        intefaceType
      )
    )
    return interfaces
  }
  const readImplementation = (cstrName, impl, memberName) => {
    let interfaceMembers = []
    let interfaceInfo = [cstrName, 'Object', interfaceMembers]
    for (memberName in impl) {
      readImplementationMember(interfaceMembers, impl, memberName)
    }
    return interfaceInfo
  }
  const readOwnImplementation = (
    cstrs,
    interfaces,
    cstrName,
    CstrPrototype,
    impl,
    interfaceType
  ) => {
    if (!cstrs.has(cstrName)) {
      cstrs.add(cstrName)
      const SuperCstr = Object.getPrototypeOf(CstrPrototype)
      const superCstrName = getConstructorName(SuperCstr)
      const interfaceMembers = []
      const propDescriptors = Object.getOwnPropertyDescriptors(CstrPrototype)
      readOwnImplementation(
        cstrs,
        interfaces,
        superCstrName,
        SuperCstr,
        impl,
        interfaceType
      )
      for (const memberName in propDescriptors) {
        readImplementationMember(interfaceMembers, impl, memberName)
      }
      interfaces.push([
        cstrName,
        superCstrName,
        interfaceMembers,
        interfaceType,
        getNodeName(impl),
      ])
    }
  }
  const readImplementationMember = (
    interfaceMembers,
    implementation,
    memberName,
    value,
    memberType,
    cstrName
  ) => {
    try {
      if (
        isValidMemberName(memberName) &&
        isNaN(memberName[0]) &&
        'all' !== memberName
      ) {
        value = implementation[memberName]
        memberType = typeof value
        if ('function' === memberType) {
          ;(String(value).includes('[native') ||
            Object.getPrototypeOf(implementation)[memberName]) &&
            interfaceMembers.push([memberName, 5])
        } else if ('object' === memberType && null != value) {
          cstrName = getConstructorName(value)
          'Object' !== cstrName &&
            self[cstrName] &&
            interfaceMembers.push([memberName, value.nodeType || cstrName])
        } else {
          'symbol' !== memberType &&
            (memberName.toUpperCase() === memberName
              ? interfaceMembers.push([memberName, 6, value])
              : interfaceMembers.push([memberName, 6]))
        }
      }
    } catch (e) {
      console.warn(e)
    }
  }
  const readStorage = storageName => {
    let items = []
    let i = 0
    let l = len(mainWindow[storageName])
    let key
    for (; i < l; i++) {
      key = mainWindow[storageName].key(i)
      items.push([key, mainWindow[storageName].getItem(key)])
    }
    return items
  }
  const getGlobalConstructor = (mainWindow, cstrName) =>
    void 0 !== mainWindow[cstrName] ? new mainWindow[cstrName](noop) : 0
  const addGlobalConstructorUsingPrototype = (
    $interfaces$,
    mainWindow,
    cstrName
  ) => {
    void 0 !== mainWindow[cstrName] &&
      $interfaces$.push([
        cstrName,
        'Object',
        Object.keys(mainWindow[cstrName].prototype).map(propName => [
          propName,
          6,
        ]),
        12,
      ])
  }
  let worker
  ;(receiveMessage => {
    const swContainer = window.navigator.serviceWorker
    return swContainer.getRegistration().then(swRegistration => {
      swContainer.addEventListener('message', ev =>
        receiveMessage(
          ev.data,
          accessRsp =>
            swRegistration.active &&
            swRegistration.active.postMessage(accessRsp)
        )
      )
      return (worker, msg) => {
        0 === msg[0]
          ? worker.postMessage([1, readMainPlatform()])
          : 2 === msg[0]
          ? worker.postMessage([3, readMainInterfaces()])
          : onMessageFromWebWorker(worker, msg)
      }
    })
  })((accessReq, responseCallback) =>
    mainAccessHandler(worker, accessReq).then(responseCallback)
  ).then(onMessageHandler => {
    if (onMessageHandler) {
      worker = new Worker(libPath + 'partytown-ww-sw.js?v=0.7.4', {
        name: 'Partytown 🎉',
      })
      worker.onmessage = ev => {
        const msg = ev.data
        12 === msg[0]
          ? mainAccessHandler(worker, msg[1])
          : onMessageHandler(worker, msg)
      }
      logMain('Created Partytown web worker (0.7.4)')
      worker.onerror = ev => console.error('Web Worker Error', ev)
      mainWindow.addEventListener('pt1', ev =>
        registerWindow(
          worker,
          getAndSetInstanceId(ev.detail.frameElement),
          ev.detail
        )
      )
    }
  })
})(window)

```


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

[User] Show me the implementation of partytown/public/~partytown/debug/partytown-sw.js from the partytown VTEX app.

[Assistant]
Here's the implementation:

```javascript
/* Partytown 0.7.4 - MIT builder.io */
const resolves = new Map()

const swMessageError = (accessReq, $error$) => ({
  $msgId$: accessReq.$msgId$,
  $error$: $error$,
})

const httpRequestFromWebWorker = req =>
  new Promise(async resolve => {
    const accessReq = await req.clone().json()
    const responseData = await (accessReq =>
      new Promise(async resolve => {
        const clients = await self.clients.matchAll()
        const client = [...clients].sort((a, b) =>
          a.url > b.url ? -1 : a.url < b.url ? 1 : 0
        )[0]
        if (client) {
          const timeout = 12e4
          const msgResolve = [
            resolve,
            setTimeout(() => {
              resolves.delete(accessReq.$msgId$)
              resolve(swMessageError(accessReq, 'Timeout'))
            }, timeout),
          ]
          resolves.set(accessReq.$msgId$, msgResolve)
          client.postMessage(accessReq)
        } else {
          resolve(swMessageError(accessReq, 'NoParty'))
        }
      }))(accessReq)
    resolve(response(JSON.stringify(responseData), 'application/json'))
  })

const response = (body, contentType) =>
  new Response(body, {
    headers: {
      'content-type': contentType || 'text/html',
      'Cache-Control': 'no-store',
    },
  })

self.oninstall = () => self.skipWaiting()

self.onactivate = () => self.clients.claim()

self.onmessage = ev => {
  const accessRsp = ev.data
  const r = resolves.get(accessRsp.$msgId$)
  if (r) {
    resolves.delete(accessRsp.$msgId$)
    clearTimeout(r[1])
    r[0](accessRsp)
  }
}

self.onfetch = ev => {
  const req = ev.request
  const url = new URL(req.url)
  const pathname = url.pathname
  if (pathname.endsWith('sw.html')) {
    ev.respondWith(
      response(
        '<!DOCTYPE html><html><head><meta charset="utf-8"><script src="./partytown-sandbox-sw.js?v=0.7.4"></script></head></html>'
      )
    )
  } else {
    pathname.endsWith('proxytown') &&
      ev.respondWith(httpRequestFromWebWorker(req))
  }
}

```