{"version":3,"file":"tracking2.js","sources":["../src/common/polyfills.ts","../src/common/runAfterScriptLoaded.ts","../src/common/tracking.ts"],"sourcesContent":["export function polyfillURLparse(path: string, base: string | undefined): URL | null {\n  try {\n    return new URL(path, base)\n  } catch {\n    return null\n  }\n}\n\nexport function setDifferencePollyfill<T>(other: Iterable<T>): Set<T> {\n  // @ts-expect-error TS2683 - we have this as set<T>\n  const res = new Set<T>(this)\n  for (const item of other) {\n    res.delete(item)\n  }\n  return res\n}\n\nexport function applyPolyfills() {\n  if (!URL.parse) {\n    console.error('URL.parse undefined')\n    URL.parse = polyfillURLparse\n  }\n  // @ts-expect-error TS2550 - we are polyfilling now\n  if (!Set.prototype.difference) {\n    // @ts-expect-error TS2550 - we are polyfilling now\n    Set.prototype.difference = setDifferencePollyfill\n  }\n}\n","import { applyPolyfills } from './polyfills'\n\nexport type ScriptLoadedHandler = {\n  matches: (url: URL) => boolean\n  runAfterLoad: () => void\n}\n\nexport function runOnScriptLoaded(handler: ScriptLoadedHandler): void {\n  applyPolyfills()\n  const observer = new MutationObserver(\n    (mutationsList: MutationRecord[], observer: MutationObserver) =>\n      documentHeadChanged(mutationsList, observer, handler)\n  )\n  const hadNodeAlready = processNodeList(document.head.querySelectorAll('script'), handler)\n  if (!hadNodeAlready) {\n    observer.observe(document.head, {\n      attributes: false, // Watch for attribute changes\n      childList: true, // Watch for added/removed nodes\n      subtree: false // Watch the entire subtree, not just direct children\n    })\n  }\n}\n\nfunction documentHeadChanged(\n  mutationsList: MutationRecord[],\n  observer: MutationObserver,\n  handler: ScriptLoadedHandler\n) {\n  const mutationsWithAddedNodes = mutationsList.filter(\n    (item) => item.type == 'childList' && item.addedNodes?.length\n  )\n  for (const mutation of mutationsWithAddedNodes) {\n    if (processNodeList(mutation.addedNodes, handler)) {\n      observer.disconnect()\n      return\n    }\n  }\n}\n\nexport function processNodeList(nodes: NodeList, handler: ScriptLoadedHandler): boolean {\n  for (const node of nodes) {\n    if (processSingleNode(node, handler)) {\n      return true\n    }\n  }\n  return false\n}\n\nexport function processSingleNode(node: Node, handler: ScriptLoadedHandler): boolean {\n  if (node.nodeName != 'SCRIPT') {\n    return false\n  }\n  const element = node as Element\n  // @ts-expect-error TS7015\n  const src: string | undefined | null = element.attributes['src']?.value\n  if (!src) {\n    return false\n  }\n  const parsed = URL.parse(src)\n  if (!parsed) {\n    return false\n  }\n  if (handler.matches(parsed)) {\n    // @ts-expect-error TS2339\n    if (!element.onload) {\n      // @ts-expect-error TS2339\n      element.onload = () => handler.runAfterLoad()\n    } else {\n      handler.runAfterLoad()\n    }\n    return true\n  }\n  return false\n}\n","import { runOnScriptLoaded, type ScriptLoadedHandler } from './runAfterScriptLoaded'\nimport type { ServerSideUserData } from '@common/types'\nexport type Context = {\n  [index: string]: string | number\n}\nexport type UserId = string | number\n\nexport type ServerSideUserInfo = ServerSideUserData & {\n  userId: UserId | null\n}\n\nexport type TrackerInitializationHandler = {\n  handleInitialIdentify: () => Promise<void>\n}\nexport type Tracker = {\n  isAvailable: () => boolean\n  capture: (eventName: string, context: Context) => Promise<void>\n  identify: (userId: UserId, context: Context) => Promise<void>\n  getLastIdentified: () => string | null\n  logout: () => Promise<void>\n  init: (appTracker: TrackerInitializationHandler) => Promise<void>\n}\n\ntype Posthog = {\n  capture: (eventName: string, context: Context) => Promise<void>\n  identify: (userId: UserId, context: Context) => Promise<void>\n  reset: (device: boolean | undefined) => Promise<void>\n}\n\ndeclare const window: Window &\n  typeof globalThis & {\n    posthog: Posthog | undefined\n  }\n\nexport const NullTracker: Tracker = {\n  isAvailable: (): boolean => true,\n  capture: async (eventName: string, context: Context) => {}, // eslint-disable-line @typescript-eslint/no-unused-vars\n  identify: async (userId: UserId, context: Context) => {}, // eslint-disable-line @typescript-eslint/no-unused-vars\n  getLastIdentified: () => null,\n  logout: async () => {},\n  init: async (appTracker: TrackerInitializationHandler) => {} // eslint-disable-line @typescript-eslint/no-unused-vars\n}\n\nexport const PosthogTracker: Tracker = {\n  isAvailable: () => Boolean(window.posthog),\n  capture: async function (eventName: string, context: Context) {\n    // @ts-expect-error TS18048\n    await window.posthog.capture(eventName, context)\n  },\n  identify: async function (userId: UserId, context: Context) {\n    // @ts-expect-error TS18048\n    await window.posthog.identify(userId, context)\n  },\n\n  logout: async function () {\n    // @ts-expect-error TS18048\n    await window.posthog.reset(true)\n  },\n\n  getLastIdentified: function () {\n    // @ts-expect-error TS2339\n    const key = this.getLastIdentifiedLocalStorageKey()\n    const data = JSON.parse(window.localStorage[key] || '{}')\n    const userState = data['$user_state']\n    if (!userState || userState == 'anonymous') {\n      return null\n    }\n    return data.distinct_id\n  },\n  // @ts-expect-error TS2353\n  getLastIdentifiedLocalStorageKey: function (): string | null {\n    for (const key of Object.keys(window.localStorage)) {\n      const parts = key.split('_')\n      if (parts[parts.length - 1] == 'posthog') {\n        return key\n      }\n    }\n    return null\n  },\n\n  init: async function (appTracker: TrackerInitializationHandler) {\n    const posthogLoadedHandler: ScriptLoadedHandler = {\n      matches: (url: URL): boolean => !!url.host.split('.').find((x: string) => x == 'posthog'),\n      runAfterLoad: () => appTracker.handleInitialIdentify()\n    }\n    runOnScriptLoaded(posthogLoadedHandler)\n  }\n}\n\nexport class AppTracker {\n  private info: ServerSideUserInfo\n  private tracker: Tracker\n\n  constructor(info: ServerSideUserInfo, tracker: Tracker) {\n    this.info = info\n    this.tracker = tracker\n    this.tracker.init(this)\n  }\n\n  getTracker(): Tracker {\n    // We rely on google tag manager to load posthog, thus not initalizing anything here\n    // opt out etc. is expected to be handled on that front, so we just check for existence\n    if (this.tracker.isAvailable()) {\n      return this.tracker\n    }\n    return NullTracker\n  }\n\n  async trackEvent(eventName: string, context: Context) {\n    await this.getTracker().capture(eventName, context)\n  }\n\n  async identify(userId: UserId | null, context: Context) {\n    const tracker = this.getTracker()\n    const lastIdentified = tracker.getLastIdentified()\n    if (userId == lastIdentified) {\n      return // already identified\n    }\n    if (lastIdentified) {\n      await tracker.logout()\n    }\n    if (userId) {\n      await tracker.identify(userId, context)\n    }\n  }\n  async handleInitialIdentify() {\n    const isAccepted = window.localStorage.posthogAnalyticsAccepted\n    if (window.posthog) {\n      // @ts-expect-error TS2339\n      window.posthog.set_config({\n        persistence: isAccepted ? 'localStorage+cookie' : 'memory'\n      })\n    }\n    await this.identify(\n      this.info.userId,\n      ['firstName', 'lastName', 'email'].reduce((acc: Context, attr: string) => {\n        // @ts-expect-error TS7053 - attr is from above and exactly the 3 props dfined on ServerUserData\n        const val = this.info[attr]\n        if (val) {\n          acc[attr] = val\n        }\n        return acc\n      }, {})\n    )\n  }\n}\n"],"names":["polyfillURLparse","path","base","setDifferencePollyfill","other","res","item","applyPolyfills","runOnScriptLoaded","handler","observer","mutationsList","documentHeadChanged","processNodeList","mutationsWithAddedNodes","mutation","nodes","node","processSingleNode","element","src","parsed","NullTracker","eventName","context","userId","appTracker","PosthogTracker","key","data","userState","parts","url","x","AppTracker","info","tracker","lastIdentified","isAccepted","acc","attr","val"],"mappings":"6sCAAO,SAASA,EAAiBC,EAAcC,EAAsC,CACnF,GAAI,CACF,OAAO,IAAI,IAAID,EAAMC,CAAI,CAC3B,MAAQ,CACN,OAAO,IACT,CACF,CAEO,SAASC,EAA0BC,EAA4B,CAEpE,MAAMC,EAAM,IAAI,IAAO,IAAI,EAC3B,UAAWC,KAAQF,EACjBC,EAAI,OAAOC,CAAI,EAEjB,OAAOD,CACT,CAEO,SAASE,GAAiB,CAC1B,IAAI,QACP,QAAQ,MAAM,qBAAqB,EACnC,IAAI,MAAQP,GAGT,IAAI,UAAU,aAEjB,IAAI,UAAU,WAAaG,EAE/B,CCpBO,SAASK,EAAkBC,EAAoC,CACpEF,EAAA,EACA,MAAMG,EAAW,IAAI,iBACnB,CAACC,EAAiCD,IAChCE,EAAoBD,EAAeD,EAAUD,CAAO,CAAA,EAEjCI,EAAgB,SAAS,KAAK,iBAAiB,QAAQ,EAAGJ,CAAO,GAEtFC,EAAS,QAAQ,SAAS,KAAM,CAC9B,WAAY,GACZ,UAAW,GAC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