{"version":3,"file":"index.modern.mjs","sources":["../src/collected-scripts-by-page.tsx","../src/request-idle-callback-shim.ts","../src/gatsby-script.tsx"],"sourcesContent":["import { ScriptProps } from \"./gatsby-script\"\n\nconst _collectedScriptsByPage = new Map()\n\nexport const collectedScriptsByPage = {\n  get(pathname: string): Array<ScriptProps> {\n    return _collectedScriptsByPage.get(pathname) || []\n  },\n  set(pathname: string, collectedScript: ScriptProps): void {\n    const currentCollectedScripts = _collectedScriptsByPage.get(pathname) || []\n    currentCollectedScripts.push(collectedScript)\n    _collectedScriptsByPage.set(pathname, currentCollectedScripts)\n  },\n  delete(pathname: string): void {\n    _collectedScriptsByPage.delete(pathname)\n  },\n}\n","// https://developer.chrome.com/blog/using-requestidlecallback/#checking-for-requestidlecallback\n// https://github.com/vercel/next.js/blob/canary/packages/next/client/request-idle-callback.ts\n\nexport const requestIdleCallback =\n  (typeof self !== `undefined` &&\n    self.requestIdleCallback &&\n    self.requestIdleCallback.bind(window)) ||\n  function (cb: IdleRequestCallback): number {\n    const start = Date.now()\n    return setTimeout(function () {\n      cb({\n        didTimeout: false,\n        timeRemaining: function () {\n          return Math.max(0, 50 - (Date.now() - start))\n        },\n      })\n    }, 1) as unknown as number\n  }\n","import React, { useEffect } from \"react\"\nimport { collectedScriptsByPage } from \"./collected-scripts-by-page\"\nimport type { ReactElement, ScriptHTMLAttributes } from \"react\"\nimport { requestIdleCallback } from \"./request-idle-callback-shim\"\nimport { Location, useLocation } from \"@gatsbyjs/reach-router\"\n\nexport enum ScriptStrategy {\n  postHydrate = `post-hydrate`,\n  idle = `idle`,\n  offMainThread = `off-main-thread`,\n}\n\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport interface ScriptProps\n  extends Omit<ScriptHTMLAttributes<HTMLScriptElement>, `onLoad` | `onError`> {\n  id?: string\n  strategy?: ScriptStrategy | `post-hydrate` | `idle` | `off-main-thread`\n  children?: string\n  onLoad?: (event: Event) => void\n  onError?: (event: ErrorEvent) => void\n  forward?: Array<string>\n}\n\nconst handledProps = new Set([\n  `src`,\n  `strategy`,\n  `dangerouslySetInnerHTML`,\n  `children`,\n  `onLoad`,\n  `onError`,\n])\n\n// Used for de-duplication\nexport const scriptCache: Set<string> = new Set()\nexport const scriptCallbackCache: Map<\n  string,\n  {\n    load?: {\n      callbacks?: Array<(event: Event) => void>\n      event?: Event | undefined\n    }\n    error?: {\n      callbacks?: Array<(event: ErrorEvent) => void>\n      event?: ErrorEvent | undefined\n    }\n  }\n> = new Map()\n\n// Same pattern is used in Gatsby Link\nfunction GatsbyScriptLocationWrapper(props: ScriptProps): JSX.Element {\n  return <Location>{(): JSX.Element => <GatsbyScript {...props} />}</Location>\n}\n\nfunction GatsbyScript(props: ScriptProps): ReactElement | null {\n  const { src, strategy = ScriptStrategy.postHydrate } = props || {}\n\n  const { pathname } = useLocation()\n\n  useEffect(() => {\n    let details: IInjectedScriptDetails | null\n\n    switch (strategy) {\n      case ScriptStrategy.postHydrate:\n        details = injectScript(props)\n        break\n      case ScriptStrategy.idle:\n        requestIdleCallback(() => {\n          details = injectScript(props)\n        })\n        break\n      case ScriptStrategy.offMainThread:\n        {\n          const attributes = resolveAttributes(props)\n          collectedScriptsByPage.set(pathname, attributes)\n        }\n        break\n    }\n\n    return (): void => {\n      const { script, loadCallback, errorCallback } = details || {}\n\n      if (loadCallback) {\n        script?.removeEventListener(`load`, loadCallback)\n      }\n\n      if (errorCallback) {\n        script?.removeEventListener(`error`, errorCallback)\n      }\n\n      script?.remove()\n    }\n  }, [])\n\n  if (strategy === ScriptStrategy.offMainThread) {\n    const inlineScript = resolveInlineScript(props)\n    const attributes = resolveAttributes(props)\n\n    if (typeof window === `undefined`) {\n      collectedScriptsByPage.set(pathname, attributes)\n    }\n\n    if (inlineScript) {\n      return (\n        <script\n          type=\"text/partytown\"\n          data-strategy={strategy}\n          crossOrigin=\"anonymous\"\n          {...attributes}\n          dangerouslySetInnerHTML={{ __html: resolveInlineScript(props) }}\n        />\n      )\n    }\n    return (\n      <script\n        type=\"text/partytown\"\n        src={proxyPartytownUrl(src)}\n        data-strategy={strategy}\n        crossOrigin=\"anonymous\"\n        {...attributes}\n      />\n    )\n  }\n\n  return null\n}\n\ninterface IInjectedScriptDetails {\n  script: HTMLScriptElement | null\n  loadCallback: (event: Event) => void\n  errorCallback: (event: ErrorEvent) => void\n}\n\nfunction injectScript(props: ScriptProps): IInjectedScriptDetails | null {\n  const {\n    id,\n    src,\n    strategy = ScriptStrategy.postHydrate,\n    onLoad,\n    onError,\n  } = props || {}\n\n  const scriptKey = id || src\n\n  const callbackNames = [`load`, `error`]\n\n  const currentCallbacks = {\n    load: onLoad,\n    error: onError,\n  }\n\n  if (scriptKey) {\n    /**\n     * If a duplicate script is already loaded/errored, we replay load/error callbacks with the original event.\n     * If it's not yet loaded/errored, keep track of callbacks so we can call load/error callbacks for each when the event occurs.\n     */\n    for (const name of callbackNames) {\n      if (currentCallbacks?.[name]) {\n        const cachedCallbacks = scriptCallbackCache.get(scriptKey) || {}\n        const { callbacks = [] } = cachedCallbacks?.[name] || {}\n        callbacks.push(currentCallbacks?.[name])\n\n        if (cachedCallbacks?.[name]?.event) {\n          currentCallbacks?.[name]?.(cachedCallbacks?.[name]?.event)\n        } else {\n          scriptCallbackCache.set(scriptKey, {\n            ...cachedCallbacks,\n            [name]: {\n              callbacks,\n            },\n          })\n        }\n      }\n    }\n\n    // Avoid injecting duplicate scripts into the DOM\n    if (scriptCache.has(scriptKey)) {\n      return null\n    }\n  }\n\n  const inlineScript = resolveInlineScript(props)\n  const attributes = resolveAttributes(props)\n\n  const script = document.createElement(`script`)\n\n  if (id) {\n    script.id = id\n  }\n\n  script.dataset.strategy = strategy\n\n  for (const [key, value] of Object.entries(attributes)) {\n    script.setAttribute(key, value)\n  }\n\n  if (inlineScript) {\n    script.textContent = inlineScript\n  }\n\n  if (src) {\n    script.src = src\n  }\n\n  const wrappedCallbacks: Record<string, (event: Event | ErrorEvent) => void> =\n    {}\n\n  if (scriptKey) {\n    // Add listeners on injected scripts so events are cached for use in de-duplicated script callbacks\n    for (const name of callbackNames) {\n      const wrappedEventCallback = (event: Event | ErrorEvent): void =>\n        onEventCallback(event, scriptKey, name)\n      script.addEventListener(name, wrappedEventCallback)\n      wrappedCallbacks[`${name}Callback`] = wrappedEventCallback\n    }\n\n    scriptCache.add(scriptKey)\n  }\n\n  document.body.appendChild(script)\n\n  return {\n    script,\n    loadCallback: wrappedCallbacks.loadCallback,\n    errorCallback: wrappedCallbacks.errorCallback,\n  }\n}\n\nfunction resolveInlineScript(props: ScriptProps): string {\n  const { dangerouslySetInnerHTML, children = `` } = props || {}\n  const { __html: dangerousHTML = `` } = dangerouslySetInnerHTML || {}\n  return (dangerousHTML as string) || children\n}\n\nfunction resolveAttributes(props: ScriptProps): Record<string, string> {\n  const attributes: Record<string, string> = {}\n\n  for (const [key, value] of Object.entries(props)) {\n    if (handledProps.has(key)) {\n      continue\n    }\n    attributes[key] = value\n  }\n\n  return attributes\n}\n\nfunction proxyPartytownUrl(url: string | undefined): string | undefined {\n  if (!url) {\n    return undefined\n  }\n  return `/__third-party-proxy?url=${encodeURIComponent(url)}`\n}\n\nfunction onEventCallback(\n  event: Event | ErrorEvent,\n  scriptKey: string,\n  eventName: string\n): void {\n  const cachedCallbacks = scriptCallbackCache.get(scriptKey) || {}\n\n  for (const callback of cachedCallbacks?.[eventName]?.callbacks || []) {\n    callback(event)\n  }\n\n  scriptCallbackCache.set(scriptKey, { [eventName]: { event } })\n}\n\nexport { GatsbyScriptLocationWrapper as Script }\n"],"names":["_collectedScriptsByPage","Map","collectedScriptsByPage","get","pathname","set","collectedScript","currentCollectedScripts","push","delete","requestIdleCallback","self","bind","window","cb","start","Date","now","setTimeout","didTimeout","timeRemaining","Math","max","ScriptStrategy","handledProps","Set","scriptCache","scriptCallbackCache","GatsbyScriptLocationWrapper","props","React","createElement","Location","GatsbyScript","src","strategy","postHydrate","useLocation","useEffect","details","injectScript","idle","offMainThread","resolveAttributes","attributes","script","loadCallback","errorCallback","removeEventListener","remove","inlineScript","resolveInlineScript","_extends","type","crossOrigin","dangerouslySetInnerHTML","__html","proxyPartytownUrl","id","onLoad","onError","scriptKey","callbackNames","load","error","name","currentCallbacks","_cachedCallbacks$name","cachedCallbacks","callbacks","event","_currentCallbacks$nam","call","_cachedCallbacks$name2","has","document","dataset","key","value","Object","entries","setAttribute","textContent","wrappedCallbacks","wrappedEventCallback","onEventCallback","addEventListener","add","body","appendChild","children","dangerousHTML","url","encodeURIComponent","eventName","callback","_cachedCallbacks$even"],"mappings":"4UAEA,MAA6BA,EAAG,IAAIC,IAEDC,EAAG,CACpCC,IAAIC,GACKJ,EAAwBG,IAAIC,IAAa,GAElDC,IAAID,EAAkBE,GACpB,QAAgCN,EAAwBG,IAAIC,IAAa,GACzEG,EAAwBC,KAAKF,GAC7BN,EAAwBK,IAAID,EAAUG,EACxC,EACAE,OAAOL,GACLJ,EAAwBS,OAAOL,EACjC,GCZWM,EACiB,0BAC1BC,KAAKD,qBACLC,KAAKD,oBAAoBE,KAAKC,SAChC,SAAUC,GACR,MAAWC,EAAGC,KAAKC,MACnB,OAAiBC,WAAC,WAChBJ,EAAG,CACDK,YAAY,EACZC,cAAe,WACb,OAAWC,KAACC,IAAI,EAAG,IAAMN,KAAKC,MAAQF,GACxC,GAEJ,EAAG,EACL,ECXUQ,IAAAA,GAAZ,SAAYA,GACVA,EAAA,YAAA,eACAA,EAAA,KAAA,OACAA,EAAA,cAAA,iBACD,CAJD,CAAYA,IAAAA,EAIX,CAAA,IAaD,MAAkBC,EAAG,IAAIC,IAAI,CACtB,MACK,WACe,0BACf,WACF,SACC,YAIEC,EAA2B,QAC3BC,EAYT,QAGJ,SAAoCC,EAACC,gBACnC,OAAOC,EAACC,cAAAC,EAAU,KAAA,iBAAmBF,EAACC,cAAAE,EAAiBJ,GACzD,CAEA,SAASI,EAAaJ,GACpB,MAAMK,IAAEA,EAAGC,SAAEA,EAAWZ,EAAea,aAAgBP,GAAS,CAAA,GAE1DzB,S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