@shware/analytics 16.3.3 → 16.3.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/dist/hooks/use-outbound-click-analytics.cjs +14 -6
  2. package/dist/hooks/use-outbound-click-analytics.cjs.map +1 -1
  3. package/dist/hooks/use-outbound-click-analytics.d.cts +3 -2
  4. package/dist/hooks/use-outbound-click-analytics.d.cts.map +1 -1
  5. package/dist/hooks/use-outbound-click-analytics.d.mts +3 -2
  6. package/dist/hooks/use-outbound-click-analytics.d.mts.map +1 -1
  7. package/dist/hooks/use-outbound-click-analytics.mjs +14 -6
  8. package/dist/hooks/use-outbound-click-analytics.mjs.map +1 -1
  9. package/dist/next/index.cjs +2 -1
  10. package/dist/next/index.cjs.map +1 -1
  11. package/dist/next/index.d.cts.map +1 -1
  12. package/dist/next/index.d.mts.map +1 -1
  13. package/dist/next/index.mjs +2 -1
  14. package/dist/next/index.mjs.map +1 -1
  15. package/dist/third-parties/analytics-props.cjs +2 -1
  16. package/dist/third-parties/analytics-props.cjs.map +1 -1
  17. package/dist/third-parties/analytics-props.mjs +2 -1
  18. package/dist/third-parties/analytics-props.mjs.map +1 -1
  19. package/dist/third-parties/index.cjs +1 -0
  20. package/dist/third-parties/index.d.cts +2 -2
  21. package/dist/third-parties/index.d.mts +2 -2
  22. package/dist/third-parties/index.mjs +2 -2
  23. package/dist/third-parties/integration.cjs +31 -0
  24. package/dist/third-parties/integration.cjs.map +1 -1
  25. package/dist/third-parties/integration.d.cts +16 -0
  26. package/dist/third-parties/integration.d.cts.map +1 -1
  27. package/dist/third-parties/integration.d.mts +16 -0
  28. package/dist/third-parties/integration.d.mts.map +1 -1
  29. package/dist/third-parties/integration.mjs +29 -1
  30. package/dist/third-parties/integration.mjs.map +1 -1
  31. package/dist/third-parties/linkedin-insight-tag.cjs +2 -2
  32. package/dist/third-parties/linkedin-insight-tag.cjs.map +1 -1
  33. package/dist/third-parties/linkedin-insight-tag.d.cts.map +1 -1
  34. package/dist/third-parties/linkedin-insight-tag.d.mts.map +1 -1
  35. package/dist/third-parties/linkedin-insight-tag.mjs +2 -2
  36. package/dist/third-parties/linkedin-insight-tag.mjs.map +1 -1
  37. package/dist/third-parties/meta-pixel.cjs +1 -2
  38. package/dist/third-parties/meta-pixel.cjs.map +1 -1
  39. package/dist/third-parties/meta-pixel.d.cts.map +1 -1
  40. package/dist/third-parties/meta-pixel.d.mts.map +1 -1
  41. package/dist/third-parties/meta-pixel.mjs +2 -3
  42. package/dist/third-parties/meta-pixel.mjs.map +1 -1
  43. package/dist/third-parties/microsoft-uet.cjs +2 -5
  44. package/dist/third-parties/microsoft-uet.cjs.map +1 -1
  45. package/dist/third-parties/microsoft-uet.d.cts.map +1 -1
  46. package/dist/third-parties/microsoft-uet.d.mts.map +1 -1
  47. package/dist/third-parties/microsoft-uet.mjs +3 -6
  48. package/dist/third-parties/microsoft-uet.mjs.map +1 -1
  49. package/dist/third-parties/openai-pixel.cjs +1 -2
  50. package/dist/third-parties/openai-pixel.cjs.map +1 -1
  51. package/dist/third-parties/openai-pixel.d.cts.map +1 -1
  52. package/dist/third-parties/openai-pixel.d.mts.map +1 -1
  53. package/dist/third-parties/openai-pixel.mjs +2 -3
  54. package/dist/third-parties/openai-pixel.mjs.map +1 -1
  55. package/dist/third-parties/posthog.cjs +2 -2
  56. package/dist/third-parties/posthog.cjs.map +1 -1
  57. package/dist/third-parties/posthog.d.cts.map +1 -1
  58. package/dist/third-parties/posthog.d.mts.map +1 -1
  59. package/dist/third-parties/posthog.mjs +2 -2
  60. package/dist/third-parties/posthog.mjs.map +1 -1
  61. package/dist/third-parties/reddit-pixel.cjs +1 -2
  62. package/dist/third-parties/reddit-pixel.cjs.map +1 -1
  63. package/dist/third-parties/reddit-pixel.d.cts.map +1 -1
  64. package/dist/third-parties/reddit-pixel.d.mts.map +1 -1
  65. package/dist/third-parties/reddit-pixel.mjs +2 -3
  66. package/dist/third-parties/reddit-pixel.mjs.map +1 -1
  67. package/package.json +1 -1
@@ -1 +1 @@
1
- {"version":3,"file":"posthog.cjs","names":["getFirst"],"sources":["../../src/third-parties/posthog.ts"],"sourcesContent":["import type {\n CaptureResult,\n ExceptionAutoCaptureConfig,\n PostHog,\n PostHogConfig,\n Properties,\n} from '@posthog/types';\nimport type { UpdateVisitorDTO } from '../schema/index';\nimport type { EventName, TrackName, TrackProperties } from '../track/types';\nimport { getFirst } from '../utils/field';\nimport type { Integration } from './integration';\n\nexport type { PostHog, PostHogConfig } from '@posthog/types';\n\n/**\n * `window.posthog`, for calls that return nothing (`capture`, `identify`, `onFeatureFlags`, …):\n * the snippet's stub until the library loads, which queues them and replays them in order once it\n * has. A method that returns a value returns `undefined` on the stub — use `getLoadedPosthog` for\n * those. `undefined` on the server and before the snippet has run.\n *\n * Read off `window` rather than declared on it, so a host that also has `posthog-js`'s own types\n * does not get two conflicting declarations. The types come from `@posthog/types`, PostHog's\n * types-only package for the snippet, so the host installs nothing for them.\n */\nexport function getPosthog(): PostHog | undefined {\n if (typeof document === 'undefined') return undefined;\n return (window as { posthog?: PostHog }).posthog;\n}\n\n/**\n * The PostHog instance once the library has loaded, for the methods that return a value\n * (`getFeatureFlag`, `isFeatureEnabled`, `get_distinct_id`, …); `undefined` while only the stub is\n * there. To act when flags arrive, subscribe with `getPosthog()?.onFeatureFlags` instead, which\n * the stub queues.\n */\nexport function getLoadedPosthog(): PostHog | undefined {\n const posthog = getPosthog();\n return posthog?.__loaded ? posthog : undefined;\n}\n\nlet flagsReady: Promise<void> | undefined;\n\n/**\n * Resolves once PostHog has loaded its feature flags — or after `timeoutMs` (3 s by default),\n * since an ad blocker that stops the library would otherwise hold it forever; read the flags\n * after it with `useFeatureFlagVariantKey` / `getLoadedPosthog`, which are `undefined` in that\n * case. One promise per page, so React's `use()` can suspend on it:\n *\n * ```tsx\n * function Checkout() {\n * use(browser()); // react-dom: the server renders the <Suspense> fallback instead\n * use(posthogFlagsReady());\n * return useFeatureFlagVariantKey('new-checkout') === 'test' ? <NewCheckout /> : <OldCheckout />;\n * }\n * ```\n *\n * Waiting shows the fallback until the flags are in, instead of the default then the variant;\n * with server-evaluated flags in `config.bootstrap` it resolves as soon as the library loads.\n * Browser only: it never resolves on the server.\n */\nexport function posthogFlagsReady(timeoutMs = 3000): Promise<void> {\n if (typeof document === 'undefined') return new Promise(() => {});\n flagsReady ??= new Promise<void>((resolve) => {\n setTimeout(resolve, timeoutMs);\n const posthog = getPosthog();\n if (!posthog) return;\n // Queued on the stub; once loaded, called as soon as flags are (or already were) in.\n posthog.onFeatureFlags(() => resolve());\n });\n return flagsReady;\n}\n\nconst metrics = ['CLS', 'FCP', 'FID', 'INP', 'LCP', 'TTFB'];\n\nexport function sendPosthogEvent<T extends EventName>(\n name: TrackName<T>,\n properties?: TrackProperties<T>\n) {\n // `document`, not `window`: React Native defines `window` as an alias of `global`, so a\n // window check would pass there and then throw on `window.location`, which it has no such\n // alias for.\n if (typeof document === 'undefined') return;\n const posthog = getPosthog();\n if (!posthog) {\n console.warn('posthog has not been initialized');\n return false;\n }\n if (metrics.includes(name)) return;\n if (window.location.host.includes('127.0.0.1')) return;\n if (window.location.host.includes('localhost')) return;\n\n posthog.capture(name, properties);\n}\n\n/**\n * Identifies the visitor to PostHog as the signed-in user, by the user's id — the server's\n * `distinct_id` for the visitor once someone has signed in on it. Only a user: identifying an\n * anonymous visitor by its own id would make PostHog treat it as an identified person, and\n * PostHog does not merge one identified person into another when the user later signs in, so the\n * pre-sign-in events would stay split off.\n *\n * Without a user it is sign-out (`reset()`): PostHog's identity is reset, so the next person on\n * this page starts anonymous instead of merging into the one who left.\n */\nexport function setPosthogUser({ user_id, user_data }: Omit<UpdateVisitorDTO, 'tags'>) {\n const posthog = getPosthog();\n if (!posthog) {\n console.warn('posthog has not been initialized');\n return;\n }\n if (!user_id) {\n posthog.reset();\n return;\n }\n posthog.identify(user_id, { email: getFirst(user_data?.email) });\n}\n\n/**\n * Sends an error to PostHog's error tracking (`captureException`), as `sendPosthogEvent` does an\n * event: queued on the snippet's stub until the library loads, so it can be called from anywhere\n * at any time — an http client's error hook, a `catch` that recovers but should still be known.\n * Returns the `$exception` event, `undefined` while only the stub is there (or without PostHog).\n *\n * Never throws: reporting an error must not become a second one where it is called. The\n * `errorTracking` filter of `posthogAnalytics` applies, as to every exception.\n */\nexport function capturePosthogException(\n error: unknown,\n properties?: Properties\n): CaptureResult | undefined {\n try {\n return getPosthog()?.captureException(error, properties);\n } catch (e: unknown) {\n console.error('capturePosthogException: the error was not reported', e);\n return undefined;\n }\n}\n\n/** A substring of what it is matched against, or a regular expression tested on it. */\nexport type ErrorPattern = string | RegExp;\n\nexport interface PosthogErrorTrackingOptions {\n /**\n * The library's exception autocapture: window errors and unhandled rejections, on by default.\n * The same as `config.capture_exceptions`, which wins when both are set.\n */\n autocapture?: boolean | ExceptionAutoCaptureConfig;\n /**\n * Exceptions not sent, as Sentry's `ignoreErrors`: matched against `Type: message` and the\n * message alone of each error in the chain (`$exception_list`), e.g. `'UET is not defined'` for an\n * ad blocker stubbing a tag. Errors thrown by browser extensions need no entry: PostHog drops them\n * itself (`error_tracking.captureExtensionExceptions`).\n */\n ignoreErrors?: readonly ErrorPattern[];\n /**\n * Exceptions not sent by where they were thrown, as Sentry's `denyUrls`: matched against the\n * file of the error's innermost frame, e.g. `'/gsi/client'` for Google One Tap's own minified\n * errors, whose messages change with every build. An error of yours that only passed through\n * such a script (a callback it called) is still sent.\n */\n denyUrls?: readonly ErrorPattern[];\n}\n\n/**\n * A pattern as JSON: a regular expression by its source and flags, rebuilt in the snippet. `g`\n * and `y` are dropped: they make `test` resume from the last match, so one rule would match the\n * same message only every other time.\n */\ntype SerializedPattern = string | { source: string; flags: string };\n\nfunction serializePatterns(patterns: readonly ErrorPattern[] = []): SerializedPattern[] {\n return patterns.map((p) =>\n typeof p === 'string' ? p : { source: p.source, flags: p.flags.replace(/[gy]/g, '') }\n );\n}\n\n/**\n * The snippet's `before_send`, as source: `config` goes to `posthog.init` as JSON, which drops\n * functions, so the filter is written into the inline script instead — in place from the first\n * event, with no window before the app's bundle could install it. ES5, as the rest of the snippet.\n * Called with the rules (`off`, `errors`, `urls`); returns the `before_send` function.\n */\nconst EXCEPTION_FILTER = `function(r){\n function compile(ps){var o=[];for(var i=0;i<ps.length;i++){var p=ps[i];o.push(typeof p===\"string\"?p:new RegExp(p.source,p.flags))}return o}\n function any(ps,t){if(!t)return false;for(var i=0;i<ps.length;i++){var p=ps[i];if(typeof p===\"string\"?t.indexOf(p)!==-1:p.test(t))return true}return false}\n var errors=compile(r.errors),urls=compile(r.urls);\n return function(e){\n if(!e||e.event!==\"$exception\")return e;\n if(r.off)return null;\n var l=(e.properties&&e.properties.$exception_list)||[];\n for(var i=0;i<l.length;i++){var x=l[i]||{},v=x.value||\"\";if(any(errors,x.type?x.type+\": \"+v:v)||any(errors,v))return null}\n var f=l[0]&&l[0].stacktrace&&l[0].stacktrace.frames,u=f&&f.length?f[f.length-1].filename:\"\";\n return any(urls,u)?null:e;\n };\n}`;\n\n/**\n * The origin to preconnect to, or none for a relative URL (a reverse proxy on the site's own\n * origin). `new URL` in a try rather than `URL.canParse`, which Safari before 17 and Chrome before\n * 120 lack: this runs while the app sets up its analytics, where a throw takes the page down.\n */\nfunction originOf(url: string): string[] {\n try {\n return [new URL(url).origin];\n } catch {\n return [];\n }\n}\n\n/**\n * PostHog: every event, for behavior analysis. Loaded with PostHog's HTML snippet, which defines\n * a stub `window.posthog` and fetches the library (`array.js`) asynchronously from PostHog's\n * assets host, so it stays out of the app's bundle; calls made before it loads are queued.\n *\n * `config` is serialized into the snippet's `posthog.init` call, so only its JSON survives:\n * `api_host`, `defaults`, `bootstrap` (server-evaluated flags, so an experiment renders its variant\n * without a flicker), and the other plain options — functions such as `loaded` are dropped.\n */\nexport function posthogAnalytics(options: {\n token: `phc_${string}`;\n config: Partial<PostHogConfig> & { api_host: string };\n /**\n * PostHog's error tracking. `true` or options turn on exception autocapture and filter what is\n * sent (`ignoreErrors`, `denyUrls`); `false` sends no exception at all, autocaptured or\n * reported (`capturePosthogException`, `PosthogErrorBoundary`, `setupPosthogReactErrorHandler`) — for\n * local development, which would otherwise fill the production project's issues. Left out, the\n * library's own `config` decides, as before. Each exception carries the session id, so its issue\n * links to the session's replay.\n */\n errorTracking?: boolean | PosthogErrorTrackingOptions;\n}): Integration {\n // Where the snippet loads `array.js` from, by its own rule; a relative `api_host` (a reverse\n // proxy on the site's origin) needs no preconnect.\n const assets = options.config.api_host.replace('.i.posthog.com', '-assets.i.posthog.com');\n // `<` escaped: `config` is arbitrary JSON (a `bootstrap` can carry user data, a pattern any\n // text), and a `</script>` inside it would end this inline script early. `\\u003c` parses back\n // to the same value.\n const json = (value: unknown) => JSON.stringify(value).replace(/</g, '\\\\u003c');\n const token = JSON.stringify(options.token);\n const { errorTracking } = options;\n let init = `posthog.init(${token}, ${json(options.config)});`;\n if (errorTracking !== undefined) {\n const tracking = typeof errorTracking === 'object' ? errorTracking : {};\n const config = {\n ...options.config,\n capture_exceptions:\n options.config.capture_exceptions ?? (errorTracking && (tracking.autocapture ?? true)),\n };\n const rules = {\n off: !errorTracking,\n errors: serializePatterns(tracking.ignoreErrors),\n urls: serializePatterns(tracking.denyUrls),\n };\n // In a function, so `c` does not become a global of this classic script.\n init = `!function(){var c=${json(config)};c.before_send=(${EXCEPTION_FILTER})(${json(rules)});posthog.init(${token}, c)}();`;\n }\n return {\n type: 'analytics',\n track: sendPosthogEvent,\n setUser: setPosthogUser,\n preconnect: originOf(assets),\n script: {\n id: 'posthog-snippet',\n // The stub must exist before hydration, whose effects already track (`page_view`) and\n // identify; it is a few lines, and `array.js` still loads async. PostHog's own Next example\n // does the same. The snippet is PostHog's current one, verbatim\n // (posthog.com/docs/error-tracking/installation/web): it leaves an already loaded library in\n // place, inserts `array.js` once, and retries it on the next `init` if it failed to load.\n strategy: 'beforeInteractive',\n inline: `\n !function(t,e){var o,n,p,r;e.__SV||(window.posthog && window.posthog.__loaded)||(window.posthog=e,e._i=[],e.init=function(i,s,a){function g(t,e){var o=e.split(\".\");2==o.length&&(t=t[o[0]],e=o[1]),t[e]=function(){t.push([e].concat(Array.prototype.slice.call(arguments,0)))}}p||((p=t.createElement(\"script\")).type=\"text/javascript\",p.crossOrigin=\"anonymous\",p.async=!0,p.src=s.api_host.replace(\".i.posthog.com\",\"-assets.i.posthog.com\")+\"/static/array.js\",p.onerror=function(){p=null},(r=t.getElementsByTagName(\"script\")[0]).parentNode.insertBefore(p,r));var u=e;for(void 0!==a?u=e[a]=[]:a=\"posthog\",u.people=u.people||[],Object.defineProperty(u,\"toString\",{configurable:!0,enumerable:!0,writable:!0,value:function(t){var e=\"posthog\";return\"posthog\"!==a&&(e+=\".\"+a),t||(e+=\" (stub)\"),e}}),Object.defineProperty(u.people,\"toString\",{configurable:!0,enumerable:!0,writable:!0,value:function(){return u.toString(1)+\".people (stub)\"}}),o=\"init capture register register_once register_for_session unregister unregister_for_session getFeatureFlag getFeatureFlagResult isFeatureEnabled reloadFeatureFlags updateEarlyAccessFeatureEnrollment getEarlyAccessFeatures on onFeatureFlags onSessionId getSurveys getActiveMatchingSurveys renderSurvey canRenderSurvey getNextSurveyStep identify setPersonProperties group resetGroups setPersonPropertiesForFlags resetPersonPropertiesForFlags setGroupPropertiesForFlags resetGroupPropertiesForFlags reset get_distinct_id getGroups get_session_id get_session_replay_url alias set_config startSessionRecording stopSessionRecording sessionRecordingStarted captureException loadToolbar get_property getSessionProperty createPersonProfile opt_in_capturing opt_out_capturing has_opted_in_capturing has_opted_out_capturing clear_opt_in_out_capturing debug\".split(\" \"),n=0;n<o.length;n++)g(u,o[n]);e._i.push([i,s,a])},e.__SV=1)}(document,window.posthog||[]);\n ${init}\n `,\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;AAwBA,SAAgB,aAAkC;CAChD,IAAI,OAAO,aAAa,aAAa,OAAO,KAAA;CAC5C,OAAQ,OAAiC;AAC3C;;;;;;;AAQA,SAAgB,mBAAw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st"],"sources":["../../src/third-parties/posthog.ts"],"sourcesContent":["import type {\n CaptureResult,\n ExceptionAutoCaptureConfig,\n PostHog,\n PostHogConfig,\n Properties,\n} from '@posthog/types';\nimport type { UpdateVisitorDTO } from '../schema/index';\nimport type { EventName, TrackName, TrackProperties } from '../track/types';\nimport { getFirst } from '../utils/field';\nimport { type Integration, isLocalHost } from './integration';\n\nexport type { PostHog, PostHogConfig } from '@posthog/types';\n\n/**\n * `window.posthog`, for calls that return nothing (`capture`, `identify`, `onFeatureFlags`, …):\n * the snippet's stub until the library loads, which queues them and replays them in order once it\n * has. A method that returns a value returns `undefined` on the stub — use `getLoadedPosthog` for\n * those. `undefined` on the server and before the snippet has run.\n *\n * Read off `window` rather than declared on it, so a host that also has `posthog-js`'s own types\n * does not get two conflicting declarations. The types come from `@posthog/types`, PostHog's\n * types-only package for the snippet, so the host installs nothing for them.\n */\nexport function getPosthog(): PostHog | undefined {\n if (typeof document === 'undefined') return undefined;\n return (window as { posthog?: PostHog }).posthog;\n}\n\n/**\n * The PostHog instance once the library has loaded, for the methods that return a value\n * (`getFeatureFlag`, `isFeatureEnabled`, `get_distinct_id`, …); `undefined` while only the stub is\n * there. To act when flags arrive, subscribe with `getPosthog()?.onFeatureFlags` instead, which\n * the stub queues.\n */\nexport function getLoadedPosthog(): PostHog | undefined {\n const posthog = getPosthog();\n return posthog?.__loaded ? posthog : undefined;\n}\n\nlet flagsReady: Promise<void> | undefined;\n\n/**\n * Resolves once PostHog has loaded its feature flags — or after `timeoutMs` (3 s by default),\n * since an ad blocker that stops the library would otherwise hold it forever; read the flags\n * after it with `useFeatureFlagVariantKey` / `getLoadedPosthog`, which are `undefined` in that\n * case. One promise per page, so React's `use()` can suspend on it:\n *\n * ```tsx\n * function Checkout() {\n * use(browser()); // react-dom: the server renders the <Suspense> fallback instead\n * use(posthogFlagsReady());\n * return useFeatureFlagVariantKey('new-checkout') === 'test' ? <NewCheckout /> : <OldCheckout />;\n * }\n * ```\n *\n * Waiting shows the fallback until the flags are in, instead of the default then the variant;\n * with server-evaluated flags in `config.bootstrap` it resolves as soon as the library loads.\n * Browser only: it never resolves on the server.\n */\nexport function posthogFlagsReady(timeoutMs = 3000): Promise<void> {\n if (typeof document === 'undefined') return new Promise(() => {});\n flagsReady ??= new Promise<void>((resolve) => {\n setTimeout(resolve, timeoutMs);\n const posthog = getPosthog();\n if (!posthog) return;\n // Queued on the stub; once loaded, called as soon as flags are (or already were) in.\n posthog.onFeatureFlags(() => resolve());\n });\n return flagsReady;\n}\n\nconst metrics = ['CLS', 'FCP', 'FID', 'INP', 'LCP', 'TTFB'];\n\nexport function sendPosthogEvent<T extends EventName>(\n name: TrackName<T>,\n properties?: TrackProperties<T>\n) {\n // `document`, not `window`: React Native defines `window` as an alias of `global`, so a\n // window check would pass there and then throw on `window.location`, which it has no such\n // alias for.\n if (typeof document === 'undefined') return;\n const posthog = getPosthog();\n if (!posthog) {\n console.warn('posthog has not been initialized');\n return false;\n }\n if (metrics.includes(name)) return;\n if (isLocalHost()) return;\n\n posthog.capture(name, properties);\n}\n\n/**\n * Identifies the visitor to PostHog as the signed-in user, by the user's id — the server's\n * `distinct_id` for the visitor once someone has signed in on it. Only a user: identifying an\n * anonymous visitor by its own id would make PostHog treat it as an identified person, and\n * PostHog does not merge one identified person into another when the user later signs in, so the\n * pre-sign-in events would stay split off.\n *\n * Without a user it is sign-out (`reset()`): PostHog's identity is reset, so the next person on\n * this page starts anonymous instead of merging into the one who left.\n */\nexport function setPosthogUser({ user_id, user_data }: Omit<UpdateVisitorDTO, 'tags'>) {\n const posthog = getPosthog();\n if (!posthog) {\n console.warn('posthog has not been initialized');\n return;\n }\n if (!user_id) {\n posthog.reset();\n return;\n }\n posthog.identify(user_id, { email: getFirst(user_data?.email) });\n}\n\n/**\n * Sends an error to PostHog's error tracking (`captureException`), as `sendPosthogEvent` does an\n * event: queued on the snippet's stub until the library loads, so it can be called from anywhere\n * at any time — an http client's error hook, a `catch` that recovers but should still be known.\n * Returns the `$exception` event, `undefined` while only the stub is there (or without PostHog).\n *\n * Never throws: reporting an error must not become a second one where it is called. The\n * `errorTracking` filter of `posthogAnalytics` applies, as to every exception.\n */\nexport function capturePosthogException(\n error: unknown,\n properties?: Properties\n): CaptureResult | undefined {\n try {\n return getPosthog()?.captureException(error, properties);\n } catch (e: unknown) {\n console.error('capturePosthogException: the error was not reported', e);\n return undefined;\n }\n}\n\n/** A substring of what it is matched against, or a regular expression tested on it. */\nexport type ErrorPattern = string | RegExp;\n\nexport interface PosthogErrorTrackingOptions {\n /**\n * The library's exception autocapture: window errors and unhandled rejections, on by default.\n * The same as `config.capture_exceptions`, which wins when both are set.\n */\n autocapture?: boolean | ExceptionAutoCaptureConfig;\n /**\n * Exceptions not sent, as Sentry's `ignoreErrors`: matched against `Type: message` and the\n * message alone of each error in the chain (`$exception_list`), e.g. `'UET is not defined'` for an\n * ad blocker stubbing a tag. Errors thrown by browser extensions need no entry: PostHog drops them\n * itself (`error_tracking.captureExtensionExceptions`).\n */\n ignoreErrors?: readonly ErrorPattern[];\n /**\n * Exceptions not sent by where they were thrown, as Sentry's `denyUrls`: matched against the\n * file of the error's innermost frame, e.g. `'/gsi/client'` for Google One Tap's own minified\n * errors, whose messages change with every build. An error of yours that only passed through\n * such a script (a callback it called) is still sent.\n */\n denyUrls?: readonly ErrorPattern[];\n}\n\n/**\n * A pattern as JSON: a regular expression by its source and flags, rebuilt in the snippet. `g`\n * and `y` are dropped: they make `test` resume from the last match, so one rule would match the\n * same message only every other time.\n */\ntype SerializedPattern = string | { source: string; flags: string };\n\nfunction serializePatterns(patterns: readonly ErrorPattern[] = []): SerializedPattern[] {\n return patterns.map((p) =>\n typeof p === 'string' ? p : { source: p.source, flags: p.flags.replace(/[gy]/g, '') }\n );\n}\n\n/**\n * The snippet's `before_send`, as source: `config` goes to `posthog.init` as JSON, which drops\n * functions, so the filter is written into the inline script instead — in place from the first\n * event, with no window before the app's bundle could install it. ES5, as the rest of the snippet.\n * Called with the rules (`off`, `errors`, `urls`); returns the `before_send` function.\n */\nconst EXCEPTION_FILTER = `function(r){\n function compile(ps){var o=[];for(var i=0;i<ps.length;i++){var p=ps[i];o.push(typeof p===\"string\"?p:new RegExp(p.source,p.flags))}return o}\n function any(ps,t){if(!t)return false;for(var i=0;i<ps.length;i++){var p=ps[i];if(typeof p===\"string\"?t.indexOf(p)!==-1:p.test(t))return true}return false}\n var errors=compile(r.errors),urls=compile(r.urls);\n return function(e){\n if(!e||e.event!==\"$exception\")return e;\n if(r.off)return null;\n var l=(e.properties&&e.properties.$exception_list)||[];\n for(var i=0;i<l.length;i++){var x=l[i]||{},v=x.value||\"\";if(any(errors,x.type?x.type+\": \"+v:v)||any(errors,v))return null}\n var f=l[0]&&l[0].stacktrace&&l[0].stacktrace.frames,u=f&&f.length?f[f.length-1].filename:\"\";\n return any(urls,u)?null:e;\n };\n}`;\n\n/**\n * The origin to preconnect to, or none for a relative URL (a reverse proxy on the site's own\n * origin). `new URL` in a try rather than `URL.canParse`, which Safari before 17 and Chrome before\n * 120 lack: this runs while the app sets up its analytics, where a throw takes the page down.\n */\nfunction originOf(url: string): string[] {\n try {\n return [new URL(url).origin];\n } catch {\n return [];\n }\n}\n\n/**\n * PostHog: every event, for behavior analysis. Loaded with PostHog's HTML snippet, which defines\n * a stub `window.posthog` and fetches the library (`array.js`) asynchronously from PostHog's\n * assets host, so it stays out of the app's bundle; calls made before it loads are queued.\n *\n * `config` is serialized into the snippet's `posthog.init` call, so only its JSON survives:\n * `api_host`, `defaults`, `bootstrap` (server-evaluated flags, so an experiment renders its variant\n * without a flicker), and the other plain options — functions such as `loaded` are dropped.\n */\nexport function posthogAnalytics(options: {\n token: `phc_${string}`;\n config: Partial<PostHogConfig> & { api_host: string };\n /**\n * PostHog's error tracking. `true` or options turn on exception autocapture and filter what is\n * sent (`ignoreErrors`, `denyUrls`); `false` sends no exception at all, autocaptured or\n * reported (`capturePosthogException`, `PosthogErrorBoundary`, `setupPosthogReactErrorHandler`) — for\n * local development, which would otherwise fill the production project's issues. Left out, the\n * library's own `config` decides, as before. Each exception carries the session id, so its issue\n * links to the session's replay.\n */\n errorTracking?: boolean | PosthogErrorTrackingOptions;\n}): Integration {\n // Where the snippet loads `array.js` from, by its own rule; a relative `api_host` (a reverse\n // proxy on the site's origin) needs no preconnect.\n const assets = options.config.api_host.replace('.i.posthog.com', '-assets.i.posthog.com');\n // `<` escaped: `config` is arbitrary JSON (a `bootstrap` can carry user data, a pattern any\n // text), and a `</script>` inside it would end this inline script early. `\\u003c` parses back\n // to the same value.\n const json = (value: unknown) => JSON.stringify(value).replace(/</g, '\\\\u003c');\n const token = JSON.stringify(options.token);\n const { errorTracking } = options;\n let init = `posthog.init(${token}, ${json(options.config)});`;\n if (errorTracking !== undefined) {\n const tracking = typeof errorTracking === 'object' ? errorTracking : {};\n const config = {\n ...options.config,\n capture_exceptions:\n options.config.capture_exceptions ?? (errorTracking && (tracking.autocapture ?? true)),\n };\n const rules = {\n off: !errorTracking,\n errors: serializePatterns(tracking.ignoreErrors),\n urls: serializePatterns(tracking.denyUrls),\n };\n // In a function, so `c` does not become a global of this classic script.\n init = `!function(){var c=${json(config)};c.before_send=(${EXCEPTION_FILTER})(${json(rules)});posthog.init(${token}, c)}();`;\n }\n return {\n type: 'analytics',\n track: sendPosthogEvent,\n setUser: setPosthogUser,\n preconnect: originOf(assets),\n script: {\n id: 'posthog-snippet',\n // The stub must exist before hydration, whose effects already track (`page_view`) and\n // identify; it is a few lines, and `array.js` still loads async. PostHog's own Next example\n // does the same. The snippet is PostHog's current one, verbatim\n // (posthog.com/docs/error-tracking/installation/web): it leaves an already loaded library in\n // place, inserts `array.js` once, and retries it on the next `init` if it failed to load.\n strategy: 'beforeInteractive',\n inline: `\n !function(t,e){var o,n,p,r;e.__SV||(window.posthog && window.posthog.__loaded)||(window.posthog=e,e._i=[],e.init=function(i,s,a){function g(t,e){var o=e.split(\".\");2==o.length&&(t=t[o[0]],e=o[1]),t[e]=function(){t.push([e].concat(Array.prototype.slice.call(arguments,0)))}}p||((p=t.createElement(\"script\")).type=\"text/javascript\",p.crossOrigin=\"anonymous\",p.async=!0,p.src=s.api_host.replace(\".i.posthog.com\",\"-assets.i.posthog.com\")+\"/static/array.js\",p.onerror=function(){p=null},(r=t.getElementsByTagName(\"script\")[0]).parentNode.insertBefore(p,r));var u=e;for(void 0!==a?u=e[a]=[]:a=\"posthog\",u.people=u.people||[],Object.defineProperty(u,\"toString\",{configurable:!0,enumerable:!0,writable:!0,value:function(t){var e=\"posthog\";return\"posthog\"!==a&&(e+=\".\"+a),t||(e+=\" (stub)\"),e}}),Object.defineProperty(u.people,\"toString\",{configurable:!0,enumerable:!0,writable:!0,value:function(){return u.toString(1)+\".people (stub)\"}}),o=\"init capture register register_once register_for_session unregister unregister_for_session getFeatureFlag getFeatureFlagResult isFeatureEnabled reloadFeatureFlags updateEarlyAccessFeatureEnrollment getEarlyAccessFeatures on onFeatureFlags onSessionId getSurveys getActiveMatchingSurveys renderSurvey canRenderSurvey getNextSurveyStep identify setPersonProperties group resetGroups setPersonPropertiesForFlags resetPersonPropertiesForFlags setGroupPropertiesForFlags resetGroupPropertiesForFlags reset get_distinct_id getGroups get_session_id get_session_replay_url alias set_config startSessionRecording stopSessionRecording sessionRecordingStarted captureException loadToolbar get_property getSessionProperty createPersonProfile opt_in_capturing opt_out_capturing has_opted_in_capturing has_opted_out_capturing clear_opt_in_out_capturing debug\".split(\" \"),n=0;n<o.length;n++)g(u,o[n]);e._i.push([i,s,a])},e.__SV=1)}(document,window.posthog||[]);\n ${init}\n `,\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;AAwBA,SAAgB,aAAkC;CAChD,IAAI,OAAO,aAAa,aAAa,OAAO,KAAA;CAC5C,OAAQ,OAAiC;AAC3C;;;;;;;AAQA,SAAgB,mBAAwC;CACtD,MAAM,UAAU,WAAW;CAC3B,OAAO,SAAS,WAAW,UAAU,KAAA;AACvC;AAEA,IAAI;;;;;;;;;;;;;;;;;;;AAo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AiB,UAAU,WACzC,MAAM,UAAU,IAChB,aAAa,gBAAgB;;;;;;;;;;;wBA4Bf,iBAAiB,SAAS,aAAa,KAAK;;;;;;;;;;wBAsB5C,wBACd,gBACA,aAAa,aACZ;;YAUS,wBAAwB;iBAEnB;;;;;EAKf,wBAAwB;;;;;;;EAOxB,wBAAwB;;;;;;;EAOxB,oBAAoB;;;;;;;;;;;wBA0DN,iBAAiB;EAC/B;EACA,QAAQ,QAAQC;IAAmB;;;;;;;;;;EASnC,0BAA0B;IACxB"}
1
+ {"version":3,"file":"posthog.d.cts","names":["PostHog","PostHogConfig"],"sources":["../../src/third-parties/posthog.ts"],"mappings":";;;;;;;;;;;;;;wBAwBgB,cAAcA;;;;;;;wBAWd,oBAAoBA;;;;;;;;;;;;;;;;;;;wBAyBpB,kBAAkB,qBAAmB;wBAcrC,iBAAiB,UAAU,WACzC,MAAM,UAAU,IAChB,aAAa,gBAAgB;;;;;;;;;;;wBA2Bf,iBAAiB,SAAS,aAAa,KAAK;;;;;;;;;;wBAsB5C,wBACd,gBACA,aAAa,aACZ;;YAUS,wBAAwB;iBAEnB;;;;;EAKf,wBAAwB;;;;;;;EAOxB,wBAAwB;;;;;;;EAOxB,oBAAoB;;;;;;;;;;;wBA0DN,iBAAiB;EAC/B;EACA,QAAQ,QAAQC;IAAmB;;;;;;;;;;EASnC,0BAA0B;IACxB"}
@@ -1 +1 @@
1
- {"version":3,"file":"posthog.d.mts","names":["PostHog","PostHogConfig"],"sources":["../../src/third-parties/posthog.ts"],"mappings":";;;;;;;;;;;;;;wBAwBgB,cAAcA;;;;;;;wBAWd,oBAAoBA;;;;;;;;;;;;;;;;;;;wBAyBpB,kBAAkB,qBAAmB;wBAcrC,iBAAiB,UAAU,WACzC,MAAM,UAAU,IAChB,aAAa,gBAAgB;;;;;;;;;;;wBA4Bf,iBAAiB,SAAS,aAAa,KAAK;;;;;;;;;;wBAsB5C,wBACd,gBACA,aAAa,aACZ;;YAUS,wBAAwB;iBAEnB;;;;;EAKf,wBAAwB;;;;;;;EAOxB,wBAAwB;;;;;;;EAOxB,oBAAoB;;;;;;;;;;;wBA0DN,iBAAiB;EAC/B;EACA,QAAQ,QAAQC;IAAmB;;;;;;;;;;EASnC,0BAA0B;IACxB"}
1
+ {"version":3,"file":"posthog.d.mts","names":["PostHog","PostHogConfig"],"sources":["../../src/third-parties/posthog.ts"],"mappings":";;;;;;;;;;;;;;wBAwBgB,cAAcA;;;;;;;wBAWd,oBAAoBA;;;;;;;;;;;;;;;;;;;wBAyBpB,kBAAkB,qBAAmB;wBAcrC,iBAAiB,UAAU,WACzC,MAAM,UAAU,IAChB,aAAa,gBAAgB;;;;;;;;;;;wBA2Bf,iBAAiB,SAAS,aAAa,KAAK;;;;;;;;;;wBAsB5C,wBACd,gBACA,aAAa,aACZ;;YAUS,wBAAwB;iBAEnB;;;;;EAKf,wBAAwB;;;;;;;EAOxB,wBAAwB;;;;;;;EAOxB,oBAAoB;;;;;;;;;;;wBA0DN,iBAAiB;EAC/B;EACA,QAAQ,QAAQC;IAAmB;;;;;;;;;;EASnC,0BAA0B;IACxB"}
@@ -1,4 +1,5 @@
1
1
  import { getFirst } from "../utils/field.mjs";
2
+ import { isLocalHost } from "./integration.mjs";
2
3
  // src/third-parties/posthog.ts
3
4
  /**
4
5
  * `window.posthog`, for calls that return nothing (`capture`, `identify`, `onFeatureFlags`, …):
@@ -69,8 +70,7 @@ function sendPosthogEvent(name, properties) {
69
70
  return false;
70
71
  }
71
72
  if (metrics.includes(name)) return;
72
- if (window.location.host.includes("127.0.0.1")) return;
73
- if (window.location.host.includes("localhost")) return;
73
+ if (isLocalHost()) return;
74
74
  posthog.capture(name, properties);
75
75
  }
76
76
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"posthog.mjs","names":[],"sources":["../../src/third-parties/posthog.ts"],"sourcesContent":["import type {\n CaptureResult,\n ExceptionAutoCaptureConfig,\n PostHog,\n PostHogConfig,\n Properties,\n} from '@posthog/types';\nimport type { UpdateVisitorDTO } from '../schema/index';\nimport type { EventName, TrackName, TrackProperties } from '../track/types';\nimport { getFirst } from '../utils/field';\nimport type { Integration } from './integration';\n\nexport type { PostHog, PostHogConfig } from '@posthog/types';\n\n/**\n * `window.posthog`, for calls that return nothing (`capture`, `identify`, `onFeatureFlags`, …):\n * the snippet's stub until the library loads, which queues them and replays them in order once it\n * has. A method that returns a value returns `undefined` on the stub — use `getLoadedPosthog` for\n * those. `undefined` on the server and before the snippet has run.\n *\n * Read off `window` rather than declared on it, so a host that also has `posthog-js`'s own types\n * does not get two conflicting declarations. The types come from `@posthog/types`, PostHog's\n * types-only package for the snippet, so the host installs nothing for them.\n */\nexport function getPosthog(): PostHog | undefined {\n if (typeof document === 'undefined') return undefined;\n return (window as { posthog?: PostHog }).posthog;\n}\n\n/**\n * The PostHog instance once the library has loaded, for the methods that return a value\n * (`getFeatureFlag`, `isFeatureEnabled`, `get_distinct_id`, …); `undefined` while only the stub is\n * there. To act when flags arrive, subscribe with `getPosthog()?.onFeatureFlags` instead, which\n * the stub queues.\n */\nexport function getLoadedPosthog(): PostHog | undefined {\n const posthog = getPosthog();\n return posthog?.__loaded ? posthog : undefined;\n}\n\nlet flagsReady: Promise<void> | undefined;\n\n/**\n * Resolves once PostHog has loaded its feature flags — or after `timeoutMs` (3 s by default),\n * since an ad blocker that stops the library would otherwise hold it forever; read the flags\n * after it with `useFeatureFlagVariantKey` / `getLoadedPosthog`, which are `undefined` in that\n * case. One promise per page, so React's `use()` can suspend on it:\n *\n * ```tsx\n * function Checkout() {\n * use(browser()); // react-dom: the server renders the <Suspense> fallback instead\n * use(posthogFlagsReady());\n * return useFeatureFlagVariantKey('new-checkout') === 'test' ? <NewCheckout /> : <OldCheckout />;\n * }\n * ```\n *\n * Waiting shows the fallback until the flags are in, instead of the default then the variant;\n * with server-evaluated flags in `config.bootstrap` it resolves as soon as the library loads.\n * Browser only: it never resolves on the server.\n */\nexport function posthogFlagsReady(timeoutMs = 3000): Promise<void> {\n if (typeof document === 'undefined') return new Promise(() => {});\n flagsReady ??= new Promise<void>((resolve) => {\n setTimeout(resolve, timeoutMs);\n const posthog = getPosthog();\n if (!posthog) return;\n // Queued on the stub; once loaded, called as soon as flags are (or already were) in.\n posthog.onFeatureFlags(() => resolve());\n });\n return flagsReady;\n}\n\nconst metrics = ['CLS', 'FCP', 'FID', 'INP', 'LCP', 'TTFB'];\n\nexport function sendPosthogEvent<T extends EventName>(\n name: TrackName<T>,\n properties?: TrackProperties<T>\n) {\n // `document`, not `window`: React Native defines `window` as an alias of `global`, so a\n // window check would pass there and then throw on `window.location`, which it has no such\n // alias for.\n if (typeof document === 'undefined') return;\n const posthog = getPosthog();\n if (!posthog) {\n console.warn('posthog has not been initialized');\n return false;\n }\n if (metrics.includes(name)) return;\n if (window.location.host.includes('127.0.0.1')) return;\n if (window.location.host.includes('localhost')) return;\n\n posthog.capture(name, properties);\n}\n\n/**\n * Identifies the visitor to PostHog as the signed-in user, by the user's id — the server's\n * `distinct_id` for the visitor once someone has signed in on it. Only a user: identifying an\n * anonymous visitor by its own id would make PostHog treat it as an identified person, and\n * PostHog does not merge one identified person into another when the user later signs in, so the\n * pre-sign-in events would stay split off.\n *\n * Without a user it is sign-out (`reset()`): PostHog's identity is reset, so the next person on\n * this page starts anonymous instead of merging into the one who left.\n */\nexport function setPosthogUser({ user_id, user_data }: Omit<UpdateVisitorDTO, 'tags'>) {\n const posthog = getPosthog();\n if (!posthog) {\n console.warn('posthog has not been initialized');\n return;\n }\n if (!user_id) {\n posthog.reset();\n return;\n }\n posthog.identify(user_id, { email: getFirst(user_data?.email) });\n}\n\n/**\n * Sends an error to PostHog's error tracking (`captureException`), as `sendPosthogEvent` does an\n * event: queued on the snippet's stub until the library loads, so it can be called from anywhere\n * at any time — an http client's error hook, a `catch` that recovers but should still be known.\n * Returns the `$exception` event, `undefined` while only the stub is there (or without PostHog).\n *\n * Never throws: reporting an error must not become a second one where it is called. The\n * `errorTracking` filter of `posthogAnalytics` applies, as to every exception.\n */\nexport function capturePosthogException(\n error: unknown,\n properties?: Properties\n): CaptureResult | undefined {\n try {\n return getPosthog()?.captureException(error, properties);\n } catch (e: unknown) {\n console.error('capturePosthogException: the error was not reported', e);\n return undefined;\n }\n}\n\n/** A substring of what it is matched against, or a regular expression tested on it. */\nexport type ErrorPattern = string | RegExp;\n\nexport interface PosthogErrorTrackingOptions {\n /**\n * The library's exception autocapture: window errors and unhandled rejections, on by default.\n * The same as `config.capture_exceptions`, which wins when both are set.\n */\n autocapture?: boolean | ExceptionAutoCaptureConfig;\n /**\n * Exceptions not sent, as Sentry's `ignoreErrors`: matched against `Type: message` and the\n * message alone of each error in the chain (`$exception_list`), e.g. `'UET is not defined'` for an\n * ad blocker stubbing a tag. Errors thrown by browser extensions need no entry: PostHog drops them\n * itself (`error_tracking.captureExtensionExceptions`).\n */\n ignoreErrors?: readonly ErrorPattern[];\n /**\n * Exceptions not sent by where they were thrown, as Sentry's `denyUrls`: matched against the\n * file of the error's innermost frame, e.g. `'/gsi/client'` for Google One Tap's own minified\n * errors, whose messages change with every build. An error of yours that only passed through\n * such a script (a callback it called) is still sent.\n */\n denyUrls?: readonly ErrorPattern[];\n}\n\n/**\n * A pattern as JSON: a regular expression by its source and flags, rebuilt in the snippet. `g`\n * and `y` are dropped: they make `test` resume from the last match, so one rule would match the\n * same message only every other time.\n */\ntype SerializedPattern = string | { source: string; flags: string };\n\nfunction serializePatterns(patterns: readonly ErrorPattern[] = []): SerializedPattern[] {\n return patterns.map((p) =>\n typeof p === 'string' ? p : { source: p.source, flags: p.flags.replace(/[gy]/g, '') }\n );\n}\n\n/**\n * The snippet's `before_send`, as source: `config` goes to `posthog.init` as JSON, which drops\n * functions, so the filter is written into the inline script instead — in place from the first\n * event, with no window before the app's bundle could install it. ES5, as the rest of the snippet.\n * Called with the rules (`off`, `errors`, `urls`); returns the `before_send` function.\n */\nconst EXCEPTION_FILTER = `function(r){\n function compile(ps){var o=[];for(var i=0;i<ps.length;i++){var p=ps[i];o.push(typeof p===\"string\"?p:new RegExp(p.source,p.flags))}return o}\n function any(ps,t){if(!t)return false;for(var i=0;i<ps.length;i++){var p=ps[i];if(typeof p===\"string\"?t.indexOf(p)!==-1:p.test(t))return true}return false}\n var errors=compile(r.errors),urls=compile(r.urls);\n return function(e){\n if(!e||e.event!==\"$exception\")return e;\n if(r.off)return null;\n var l=(e.properties&&e.properties.$exception_list)||[];\n for(var i=0;i<l.length;i++){var x=l[i]||{},v=x.value||\"\";if(any(errors,x.type?x.type+\": \"+v:v)||any(errors,v))return null}\n var f=l[0]&&l[0].stacktrace&&l[0].stacktrace.frames,u=f&&f.length?f[f.length-1].filename:\"\";\n return any(urls,u)?null:e;\n };\n}`;\n\n/**\n * The origin to preconnect to, or none for a relative URL (a reverse proxy on the site's own\n * origin). `new URL` in a try rather than `URL.canParse`, which Safari before 17 and Chrome before\n * 120 lack: this runs while the app sets up its analytics, where a throw takes the page down.\n */\nfunction originOf(url: string): string[] {\n try {\n return [new URL(url).origin];\n } catch {\n return [];\n }\n}\n\n/**\n * PostHog: every event, for behavior analysis. Loaded with PostHog's HTML snippet, which defines\n * a stub `window.posthog` and fetches the library (`array.js`) asynchronously from PostHog's\n * assets host, so it stays out of the app's bundle; calls made before it loads are queued.\n *\n * `config` is serialized into the snippet's `posthog.init` call, so only its JSON survives:\n * `api_host`, `defaults`, `bootstrap` (server-evaluated flags, so an experiment renders its variant\n * without a flicker), and the other plain options — functions such as `loaded` are dropped.\n */\nexport function posthogAnalytics(options: {\n token: `phc_${string}`;\n config: Partial<PostHogConfig> & { api_host: string };\n /**\n * PostHog's error tracking. `true` or options turn on exception autocapture and filter what is\n * sent (`ignoreErrors`, `denyUrls`); `false` sends no exception at all, autocaptured or\n * reported (`capturePosthogException`, `PosthogErrorBoundary`, `setupPosthogReactErrorHandler`) — for\n * local development, which would otherwise fill the production project's issues. Left out, the\n * library's own `config` decides, as before. Each exception carries the session id, so its issue\n * links to the session's replay.\n */\n errorTracking?: boolean | PosthogErrorTrackingOptions;\n}): Integration {\n // Where the snippet loads `array.js` from, by its own rule; a relative `api_host` (a reverse\n // proxy on the site's origin) needs no preconnect.\n const assets = options.config.api_host.replace('.i.posthog.com', '-assets.i.posthog.com');\n // `<` escaped: `config` is arbitrary JSON (a `bootstrap` can carry user data, a pattern any\n // text), and a `</script>` inside it would end this inline script early. `\\u003c` parses back\n // to the same value.\n const json = (value: unknown) => JSON.stringify(value).replace(/</g, '\\\\u003c');\n const token = JSON.stringify(options.token);\n const { errorTracking } = options;\n let init = `posthog.init(${token}, ${json(options.config)});`;\n if (errorTracking !== undefined) {\n const tracking = typeof errorTracking === 'object' ? errorTracking : {};\n const config = {\n ...options.config,\n capture_exceptions:\n options.config.capture_exceptions ?? (errorTracking && (tracking.autocapture ?? true)),\n };\n const rules = {\n off: !errorTracking,\n errors: serializePatterns(tracking.ignoreErrors),\n urls: serializePatterns(tracking.denyUrls),\n };\n // In a function, so `c` does not become a global of this classic script.\n init = `!function(){var c=${json(config)};c.before_send=(${EXCEPTION_FILTER})(${json(rules)});posthog.init(${token}, c)}();`;\n }\n return {\n type: 'analytics',\n track: sendPosthogEvent,\n setUser: setPosthogUser,\n preconnect: originOf(assets),\n script: {\n id: 'posthog-snippet',\n // The stub must exist before hydration, whose effects already track (`page_view`) and\n // identify; it is a few lines, and `array.js` still loads async. PostHog's own Next example\n // does the same. The snippet is PostHog's current one, verbatim\n // (posthog.com/docs/error-tracking/installation/web): it leaves an already loaded library in\n // place, inserts `array.js` once, and retries it on the next `init` if it failed to load.\n strategy: 'beforeInteractive',\n inline: `\n !function(t,e){var o,n,p,r;e.__SV||(window.posthog && window.posthog.__loaded)||(window.posthog=e,e._i=[],e.init=function(i,s,a){function g(t,e){var o=e.split(\".\");2==o.length&&(t=t[o[0]],e=o[1]),t[e]=function(){t.push([e].concat(Array.prototype.slice.call(arguments,0)))}}p||((p=t.createElement(\"script\")).type=\"text/javascript\",p.crossOrigin=\"anonymous\",p.async=!0,p.src=s.api_host.replace(\".i.posthog.com\",\"-assets.i.posthog.com\")+\"/static/array.js\",p.onerror=function(){p=null},(r=t.getElementsByTagName(\"script\")[0]).parentNode.insertBefore(p,r));var u=e;for(void 0!==a?u=e[a]=[]:a=\"posthog\",u.people=u.people||[],Object.defineProperty(u,\"toString\",{configurable:!0,enumerable:!0,writable:!0,value:function(t){var e=\"posthog\";return\"posthog\"!==a&&(e+=\".\"+a),t||(e+=\" (stub)\"),e}}),Object.defineProperty(u.people,\"toString\",{configurable:!0,enumerable:!0,writable:!0,value:function(){return u.toString(1)+\".people (stub)\"}}),o=\"init capture register register_once register_for_session unregister unregister_for_session getFeatureFlag getFeatureFlagResult isFeatureEnabled reloadFeatureFlags updateEarlyAccessFeatureEnrollment getEarlyAccessFeatures on onFeatureFlags onSessionId getSurveys getActiveMatchingSurveys renderSurvey canRenderSurvey getNextSurveyStep identify setPersonProperties group resetGroups setPersonPropertiesForFlags resetPersonPropertiesForFlags setGroupPropertiesForFlags resetGroupPropertiesForFlags reset get_distinct_id getGroups get_session_id get_session_replay_url alias set_config startSessionRecording stopSessionRecording sessionRecordingStarted captureException loadToolbar get_property getSessionProperty createPersonProfile opt_in_capturing opt_out_capturing has_opted_in_capturing has_opted_out_capturing clear_opt_in_out_capturing debug\".split(\" \"),n=0;n<o.length;n++)g(u,o[n]);e._i.push([i,s,a])},e.__SV=1)}(document,window.posthog||[]);\n ${init}\n `,\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;AAwBA,SAAgB,aAAkC;CAChD,IAAI,OAAO,aAAa,aAAa,OAAO,KAAA;CAC5C,OAAQ,OAAiC;AAC3C;;;;;;;AAQA,SAAgB,mBAAwC;CACtD,MAAM,UAAU,WAAW;CAC3B,OAAO,SAAS,WAAW,UAAU,KAAA;AACvC;AAEA,IAAI;;;;;;;;;;;;;;;;;;;AAoBJ,SAAgB,kBAAkB,YAAY,KAAqB;CACjE,IAAI,OAAO,aAAa,aAAa,OAAO,IAAI,cAAc,CAAC,CAAC;CAChE,eAAe,IAA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vC,IAAI;EACF,OAAO,CAAC,IAAI,IAAI,GAAG,CAAC,CAAC,MAAM;CAC7B,QAAQ;EACN,OAAO,CAAC;CACV;AACF;;;;;;;;;;AAWA,SAAgB,iBAAiB,SAYjB;CAGd,MAAM,SAAS,QAAQ,OAAO,SAAS,QAAQ,kBAAkB,uBAAuB;CAIxF,MAAM,QAAQ,UAAmB,KAAK,UAAU,KAAK,CAAC,CAAC,QAAQ,MAAM,SAAS;CAC9E,MAAM,QAAQ,KAAK,UAAU,QAAQ,KAAK;CAC1C,MAAM,EAAE,kBAAkB;CAC1B,IAAI,OAAO,gBAAgB,MAAM,IAAI,KAAK,QAAQ,MAAM,EAAE;CAC1D,IAAI,kBAAkB,KAAA,GAAW;EAC/B,MAAM,WAAW,OAAO,kBAAkB,WAAW,gBAAgB,CAAC;EACtE,MAAM,SAAS;GACb,GAAG,QAAQ;GACX,oBACE,QAAQ,OAAO,uBAAuB,kBAAkB,SAAS,eAAe;EACpF;EACA,MAAM,QAAQ;GACZ,KAAK,CAAC;GACN,QAAQ,kBAAkB,SAAS,YAAY;GAC/C,MAAM,kBAAkB,SAAS,QAAQ;EAC3C;EAEA,OAAO,qBAAqB,KAAK,MAAM,EAAE,kBAAkB,iBAAiB,IAAI,KAAK,KAAK,EAAE,iBAAiB,MAAM;CACrH;CACA,OAAO;EACL,MAAM;EACN,OAAO;EACP,SAAS;EACT,YAAY,SAAS,MAAM;EAC3B,QAAQ;GACN,IAAI;GAMJ,UAAU;GACV,QAAQ;;UAEJ,KAAK;;EAEX;CACF;AACF"}
1
+ {"version":3,"file":"posthog.mjs","names":[],"sources":["../../src/third-parties/posthog.ts"],"sourcesContent":["import type {\n CaptureResult,\n ExceptionAutoCaptureConfig,\n PostHog,\n PostHogConfig,\n Properties,\n} from '@posthog/types';\nimport type { UpdateVisitorDTO } from '../schema/index';\nimport type { EventName, TrackName, TrackProperties } from '../track/types';\nimport { getFirst } from '../utils/field';\nimport { type Integration, isLocalHost } from './integration';\n\nexport type { PostHog, PostHogConfig } from '@posthog/types';\n\n/**\n * `window.posthog`, for calls that return nothing (`capture`, `identify`, `onFeatureFlags`, …):\n * the snippet's stub until the library loads, which queues them and replays them in order once it\n * has. A method that returns a value returns `undefined` on the stub — use `getLoadedPosthog` for\n * those. `undefined` on the server and before the snippet has run.\n *\n * Read off `window` rather than declared on it, so a host that also has `posthog-js`'s own types\n * does not get two conflicting declarations. The types come from `@posthog/types`, PostHog's\n * types-only package for the snippet, so the host installs nothing for them.\n */\nexport function getPosthog(): PostHog | undefined {\n if (typeof document === 'undefined') return undefined;\n return (window as { posthog?: PostHog }).posthog;\n}\n\n/**\n * The PostHog instance once the library has loaded, for the methods that return a value\n * (`getFeatureFlag`, `isFeatureEnabled`, `get_distinct_id`, …); `undefined` while only the stub is\n * there. To act when flags arrive, subscribe with `getPosthog()?.onFeatureFlags` instead, which\n * the stub queues.\n */\nexport function getLoadedPosthog(): PostHog | undefined {\n const posthog = getPosthog();\n return posthog?.__loaded ? posthog : undefined;\n}\n\nlet flagsReady: Promise<void> | undefined;\n\n/**\n * Resolves once PostHog has loaded its feature flags — or after `timeoutMs` (3 s by default),\n * since an ad blocker that stops the library would otherwise hold it forever; read the flags\n * after it with `useFeatureFlagVariantKey` / `getLoadedPosthog`, which are `undefined` in that\n * case. One promise per page, so React's `use()` can suspend on it:\n *\n * ```tsx\n * function Checkout() {\n * use(browser()); // react-dom: the server renders the <Suspense> fallback instead\n * use(posthogFlagsReady());\n * return useFeatureFlagVariantKey('new-checkout') === 'test' ? <NewCheckout /> : <OldCheckout />;\n * }\n * ```\n *\n * Waiting shows the fallback until the flags are in, instead of the default then the variant;\n * with server-evaluated flags in `config.bootstrap` it resolves as soon as the library loads.\n * Browser only: it never resolves on the server.\n */\nexport function posthogFlagsReady(timeoutMs = 3000): Promise<void> {\n if (typeof document === 'undefined') return new Promise(() => {});\n flagsReady ??= new Promise<void>((resolve) => {\n setTimeout(resolve, timeoutMs);\n const posthog = getPosthog();\n if (!posthog) return;\n // Queued on the stub; once loaded, called as soon as flags are (or already were) in.\n posthog.onFeatureFlags(() => resolve());\n });\n return flagsReady;\n}\n\nconst metrics = ['CLS', 'FCP', 'FID', 'INP', 'LCP', 'TTFB'];\n\nexport function sendPosthogEvent<T extends EventName>(\n name: TrackName<T>,\n properties?: TrackProperties<T>\n) {\n // `document`, not `window`: React Native defines `window` as an alias of `global`, so a\n // window check would pass there and then throw on `window.location`, which it has no such\n // alias for.\n if (typeof document === 'undefined') return;\n const posthog = getPosthog();\n if (!posthog) {\n console.warn('posthog has not been initialized');\n return false;\n }\n if (metrics.includes(name)) return;\n if (isLocalHost()) return;\n\n posthog.capture(name, properties);\n}\n\n/**\n * Identifies the visitor to PostHog as the signed-in user, by the user's id — the server's\n * `distinct_id` for the visitor once someone has signed in on it. Only a user: identifying an\n * anonymous visitor by its own id would make PostHog treat it as an identified person, and\n * PostHog does not merge one identified person into another when the user later signs in, so the\n * pre-sign-in events would stay split off.\n *\n * Without a user it is sign-out (`reset()`): PostHog's identity is reset, so the next person on\n * this page starts anonymous instead of merging into the one who left.\n */\nexport function setPosthogUser({ user_id, user_data }: Omit<UpdateVisitorDTO, 'tags'>) {\n const posthog = getPosthog();\n if (!posthog) {\n console.warn('posthog has not been initialized');\n return;\n }\n if (!user_id) {\n posthog.reset();\n return;\n }\n posthog.identify(user_id, { email: getFirst(user_data?.email) });\n}\n\n/**\n * Sends an error to PostHog's error tracking (`captureException`), as `sendPosthogEvent` does an\n * event: queued on the snippet's stub until the library loads, so it can be called from anywhere\n * at any time — an http client's error hook, a `catch` that recovers but should still be known.\n * Returns the `$exception` event, `undefined` while only the stub is there (or without PostHog).\n *\n * Never throws: reporting an error must not become a second one where it is called. The\n * `errorTracking` filter of `posthogAnalytics` applies, as to every exception.\n */\nexport function capturePosthogException(\n error: unknown,\n properties?: Properties\n): CaptureResult | undefined {\n try {\n return getPosthog()?.captureException(error, properties);\n } catch (e: unknown) {\n console.error('capturePosthogException: the error was not reported', e);\n return undefined;\n }\n}\n\n/** A substring of what it is matched against, or a regular expression tested on it. */\nexport type ErrorPattern = string | RegExp;\n\nexport interface PosthogErrorTrackingOptions {\n /**\n * The library's exception autocapture: window errors and unhandled rejections, on by default.\n * The same as `config.capture_exceptions`, which wins when both are set.\n */\n autocapture?: boolean | ExceptionAutoCaptureConfig;\n /**\n * Exceptions not sent, as Sentry's `ignoreErrors`: matched against `Type: message` and the\n * message alone of each error in the chain (`$exception_list`), e.g. `'UET is not defined'` for an\n * ad blocker stubbing a tag. Errors thrown by browser extensions need no entry: PostHog drops them\n * itself (`error_tracking.captureExtensionExceptions`).\n */\n ignoreErrors?: readonly ErrorPattern[];\n /**\n * Exceptions not sent by where they were thrown, as Sentry's `denyUrls`: matched against the\n * file of the error's innermost frame, e.g. `'/gsi/client'` for Google One Tap's own minified\n * errors, whose messages change with every build. An error of yours that only passed through\n * such a script (a callback it called) is still sent.\n */\n denyUrls?: readonly ErrorPattern[];\n}\n\n/**\n * A pattern as JSON: a regular expression by its source and flags, rebuilt in the snippet. `g`\n * and `y` are dropped: they make `test` resume from the last match, so one rule would match the\n * same message only every other time.\n */\ntype SerializedPattern = string | { source: string; flags: string };\n\nfunction serializePatterns(patterns: readonly ErrorPattern[] = []): SerializedPattern[] {\n return patterns.map((p) =>\n typeof p === 'string' ? p : { source: p.source, flags: p.flags.replace(/[gy]/g, '') }\n );\n}\n\n/**\n * The snippet's `before_send`, as source: `config` goes to `posthog.init` as JSON, which drops\n * functions, so the filter is written into the inline script instead — in place from the first\n * event, with no window before the app's bundle could install it. ES5, as the rest of the snippet.\n * Called with the rules (`off`, `errors`, `urls`); returns the `before_send` function.\n */\nconst EXCEPTION_FILTER = `function(r){\n function compile(ps){var o=[];for(var i=0;i<ps.length;i++){var p=ps[i];o.push(typeof p===\"string\"?p:new RegExp(p.source,p.flags))}return o}\n function any(ps,t){if(!t)return false;for(var i=0;i<ps.length;i++){var p=ps[i];if(typeof p===\"string\"?t.indexOf(p)!==-1:p.test(t))return true}return false}\n var errors=compile(r.errors),urls=compile(r.urls);\n return function(e){\n if(!e||e.event!==\"$exception\")return e;\n if(r.off)return null;\n var l=(e.properties&&e.properties.$exception_list)||[];\n for(var i=0;i<l.length;i++){var x=l[i]||{},v=x.value||\"\";if(any(errors,x.type?x.type+\": \"+v:v)||any(errors,v))return null}\n var f=l[0]&&l[0].stacktrace&&l[0].stacktrace.frames,u=f&&f.length?f[f.length-1].filename:\"\";\n return any(urls,u)?null:e;\n };\n}`;\n\n/**\n * The origin to preconnect to, or none for a relative URL (a reverse proxy on the site's own\n * origin). `new URL` in a try rather than `URL.canParse`, which Safari before 17 and Chrome before\n * 120 lack: this runs while the app sets up its analytics, where a throw takes the page down.\n */\nfunction originOf(url: string): string[] {\n try {\n return [new URL(url).origin];\n } catch {\n return [];\n }\n}\n\n/**\n * PostHog: every event, for behavior analysis. Loaded with PostHog's HTML snippet, which defines\n * a stub `window.posthog` and fetches the library (`array.js`) asynchronously from PostHog's\n * assets host, so it stays out of the app's bundle; calls made before it loads are queued.\n *\n * `config` is serialized into the snippet's `posthog.init` call, so only its JSON survives:\n * `api_host`, `defaults`, `bootstrap` (server-evaluated flags, so an experiment renders its variant\n * without a flicker), and the other plain options — functions such as `loaded` are dropped.\n */\nexport function posthogAnalytics(options: {\n token: `phc_${string}`;\n config: Partial<PostHogConfig> & { api_host: string };\n /**\n * PostHog's error tracking. `true` or options turn on exception autocapture and filter what is\n * sent (`ignoreErrors`, `denyUrls`); `false` sends no exception at all, autocaptured or\n * reported (`capturePosthogException`, `PosthogErrorBoundary`, `setupPosthogReactErrorHandler`) — for\n * local development, which would otherwise fill the production project's issues. Left out, the\n * library's own `config` decides, as before. Each exception carries the session id, so its issue\n * links to the session's replay.\n */\n errorTracking?: boolean | PosthogErrorTrackingOptions;\n}): Integration {\n // Where the snippet loads `array.js` from, by its own rule; a relative `api_host` (a reverse\n // proxy on the site's origin) needs no preconnect.\n const assets = options.config.api_host.replace('.i.posthog.com', '-assets.i.posthog.com');\n // `<` escaped: `config` is arbitrary JSON (a `bootstrap` can carry user data, a pattern any\n // text), and a `</script>` inside it would end this inline script early. `\\u003c` parses back\n // to the same value.\n const json = (value: unknown) => JSON.stringify(value).replace(/</g, '\\\\u003c');\n const token = JSON.stringify(options.token);\n const { errorTracking } = options;\n let init = `posthog.init(${token}, ${json(options.config)});`;\n if (errorTracking !== undefined) {\n const tracking = typeof errorTracking === 'object' ? errorTracking : {};\n const config = {\n ...options.config,\n capture_exceptions:\n options.config.capture_exceptions ?? (errorTracking && (tracking.autocapture ?? true)),\n };\n const rules = {\n off: !errorTracking,\n errors: serializePatterns(tracking.ignoreErrors),\n urls: serializePatterns(tracking.denyUrls),\n };\n // In a function, so `c` does not become a global of this classic script.\n init = `!function(){var c=${json(config)};c.before_send=(${EXCEPTION_FILTER})(${json(rules)});posthog.init(${token}, c)}();`;\n }\n return {\n type: 'analytics',\n track: sendPosthogEvent,\n setUser: setPosthogUser,\n preconnect: originOf(assets),\n script: {\n id: 'posthog-snippet',\n // The stub must exist before hydration, whose effects already track (`page_view`) and\n // identify; it is a few lines, and `array.js` still loads async. PostHog's own Next example\n // does the same. The snippet is PostHog's current one, verbatim\n // (posthog.com/docs/error-tracking/installation/web): it leaves an already loaded library in\n // place, inserts `array.js` once, and retries it on the next `init` if it failed to load.\n strategy: 'beforeInteractive',\n inline: `\n !function(t,e){var o,n,p,r;e.__SV||(window.posthog && window.posthog.__loaded)||(window.posthog=e,e._i=[],e.init=function(i,s,a){function g(t,e){var o=e.split(\".\");2==o.length&&(t=t[o[0]],e=o[1]),t[e]=function(){t.push([e].concat(Array.prototype.slice.call(arguments,0)))}}p||((p=t.createElement(\"script\")).type=\"text/javascript\",p.crossOrigin=\"anonymous\",p.async=!0,p.src=s.api_host.replace(\".i.posthog.com\",\"-assets.i.posthog.com\")+\"/static/array.js\",p.onerror=function(){p=null},(r=t.getElementsByTagName(\"script\")[0]).parentNode.insertBefore(p,r));var u=e;for(void 0!==a?u=e[a]=[]:a=\"posthog\",u.people=u.people||[],Object.defineProperty(u,\"toString\",{configurable:!0,enumerable:!0,writable:!0,value:function(t){var e=\"posthog\";return\"posthog\"!==a&&(e+=\".\"+a),t||(e+=\" (stub)\"),e}}),Object.defineProperty(u.people,\"toString\",{configurable:!0,enumerable:!0,writable:!0,value:function(){return u.toString(1)+\".people (stub)\"}}),o=\"init capture register register_once register_for_session unregister unregister_for_session getFeatureFlag getFeatureFlagResult isFeatureEnabled reloadFeatureFlags updateEarlyAccessFeatureEnrollment getEarlyAccessFeatures on onFeatureFlags onSessionId getSurveys getActiveMatchingSurveys renderSurvey canRenderSurvey getNextSurveyStep identify setPersonProperties group resetGroups setPersonPropertiesForFlags resetPersonPropertiesForFlags setGroupPropertiesForFlags resetGroupPropertiesForFlags reset get_distinct_id getGroups get_session_id get_session_replay_url alias set_config startSessionRecording stopSessionRecording sessionRecordingStarted captureException loadToolbar get_property getSessionProperty createPersonProfile opt_in_capturing opt_out_capturing has_opted_in_capturing has_opted_out_capturing clear_opt_in_out_capturing debug\".split(\" \"),n=0;n<o.length;n++)g(u,o[n]);e._i.push([i,s,a])},e.__SV=1)}(document,window.posthog||[]);\n ${init}\n `,\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;AAwBA,SAAgB,aAAkC;CAChD,IAAI,OAAO,aAAa,aAAa,OAAO,KAAA;CAC5C,OAAQ,OAAiC;AAC3C;;;;;;;AAQA,SAAgB,mBAAwC;CACtD,MAAM,UAAU,WAAW;CAC3B,OAAO,SAAS,WAAW,UAAU,KAAA;AACvC;AAEA,IAAI;;;;;;;;;;;;;;;;;;;AAoBJ,SAAgB,kBAAkB,YAAY,KAAqB;CACjE,IAAI,OAAO,aAAa,aAAa,OAAO,IAAI,cAAc,CAAC,CAAC;CAChE,eAAe,IAAI,SAAe,YAAY;EAC5C,WAAW,SAAS,SAAS;EAC7B,MAAM,UAAU,WAAW;EAC3B,IAAI,CAAC,SAAS;EAEd,QAAQ,qBAAqB,QAAQ,CAAC;CACxC,C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CAIxF,MAAM,QAAQ,UAAmB,KAAK,UAAU,KAAK,CAAC,CAAC,QAAQ,MAAM,SAAS;CAC9E,MAAM,QAAQ,KAAK,UAAU,QAAQ,KAAK;CAC1C,MAAM,EAAE,kBAAkB;CAC1B,IAAI,OAAO,gBAAgB,MAAM,IAAI,KAAK,QAAQ,MAAM,EAAE;CAC1D,IAAI,kBAAkB,KAAA,GAAW;EAC/B,MAAM,WAAW,OAAO,kBAAkB,WAAW,gBAAgB,CAAC;EACtE,MAAM,SAAS;GACb,GAAG,QAAQ;GACX,oBACE,QAAQ,OAAO,uBAAuB,kBAAkB,SAAS,eAAe;EACpF;EACA,MAAM,QAAQ;GACZ,KAAK,CAAC;GACN,QAAQ,kBAAkB,SAAS,YAAY;GAC/C,MAAM,kBAAkB,SAAS,QAAQ;EAC3C;EAEA,OAAO,qBAAqB,KAAK,MAAM,EAAE,kBAAkB,iBAAiB,IAAI,KAAK,KAAK,EAAE,iBAAiB,MAAM;CACrH;CACA,OAAO;EACL,MAAM;EACN,OAAO;EACP,SAAS;EACT,YAAY,SAAS,MAAM;EAC3B,QAAQ;GACN,IAAI;GAMJ,UAAU;GACV,QAAQ;;UAEJ,KAAK;;EAEX;CACF;AACF"}
@@ -17,8 +17,7 @@ function sendRedditEvent(name, properties, eventId) {
17
17
  return false;
18
18
  }
19
19
  if (metrics.includes(name)) return;
20
- if (window.location.host.includes("127.0.0.1")) return;
21
- if (window.location.host.includes("localhost")) return;
20
+ if (require_third_parties_integration.isLocalHost()) return;
22
21
  const [type, params] = require_track_rdt.mapRDTEvent(name, properties, eventId);
23
22
  if (type === "Custom") window.rdt("track", type, JSON.parse(JSON.stringify(params)));
24
23
  else window.rdt("track", type, JSON.parse(JSON.stringify(params)));
@@ -1 +1 @@
1
- {"version":3,"file":"reddit-pixel.cjs","names":["mapRDTEvent","getFirst","adsTracker","adEvents","isStandardRDTEvent"],"sources":["../../src/third-parties/reddit-pixel.ts"],"sourcesContent":["import type { UpdateVisitorDTO } from '../schema/index';\nimport { type PixelId, type RDT, isStandardRDTEvent, mapRDTEvent } from '../track/rdt';\nimport type { EventName, TrackName, TrackProperties } from '../track/types';\nimport { getFirst } from '../utils/field';\nimport { type AdsOptions, type Integration, adEvents, adsTracker } from './integration';\n\ndeclare global {\n interface Window {\n /** Undefined until the Reddit Pixel script has loaded. */\n rdt?: RDT['rdt'];\n }\n}\n\nconst metrics = ['CLS', 'FCP', 'FID', 'INP', 'LCP', 'TTFB'];\n\nexport function sendRedditEvent<T extends EventName>(\n name: TrackName<T>,\n properties?: TrackProperties<T>,\n eventId?: string\n) {\n if (typeof window === 'undefined' || !window.rdt) {\n console.warn('rdt has not been initialized');\n return false;\n }\n if (metrics.includes(name)) return;\n if (window.location.host.includes('127.0.0.1')) return;\n if (window.location.host.includes('localhost')) return;\n\n const [type, params] = mapRDTEvent(name, properties, eventId);\n // The two branches are identical on purpose: `rdt('track', ...)` is overloaded — a standard\n // event name carries its own params type, 'Custom' carries `CustomEventParams` — and what\n // `mapRDTEvent` returns is a union of both. Narrowing `type` is what picks a single overload.\n if (type === 'Custom') {\n window.rdt('track', type, JSON.parse(JSON.stringify(params)));\n } else {\n window.rdt('track', type, JSON.parse(JSON.stringify(params)));\n }\n}\n\nexport function setRedditUser(pixelId: PixelId) {\n return ({ user_id, user_data }: UpdateVisitorDTO) => {\n if (typeof window === 'undefined' || !window.rdt) {\n console.warn('rdt has not been initialized');\n return;\n }\n\n window.rdt('init', pixelId, {\n email: getFirst(user_data?.email),\n phoneNumber: getFirst(user_data?.phone_number),\n externalId: user_id,\n });\n };\n}\n\n/** Reddit Pixel: the events `mapRDTEvent` maps to a Reddit standard event, and `customEvents`. */\n/** Reddit's configuration, shared by `redditAds` and `redditConversions` on the server. */\nexport interface RedditAdsOptions extends AdsOptions {\n pixelId: PixelId;\n}\n\nexport function redditAds(options: RedditAdsOptions): Integration {\n // As the Ads console's tag: the pixel loads with its id.\n const src = `https://www.redditstatic.com/ads/pixel.js?pixel_id=${encodeURIComponent(options.pixelId)}`;\n return {\n type: 'ads',\n track: adsTracker(sendRedditEvent, adEvents(isStandardRDTEvent, options.customEvents)),\n setUser: setRedditUser(options.pixelId),\n script: {\n id: 'reddit-pixel',\n inline: `\n !function(w,d) {\n if(!w.rdt) {\n var p = w.rdt = function() {\n p.sendEvent ? p.sendEvent.apply(p,arguments) : p.callQueue.push(arguments)\n };\n p.callQueue = [];\n var t = d.createElement(\"script\");\n t.src = ${JSON.stringify(src)};\n t.async = !0;\n var s = d.getElementsByTagName(\"script\")[0];\n s.parentNode.insertBefore(t,s)\n }\n }(window, document);\n rdt('init', ${JSON.stringify(options.pixelId)});\n rdt('track', 'PageVisit');\n `,\n },\n };\n}\n"],"mappings":";;;;;AAaA,MAAM,UAAU;CAAC;CAAO;CAAO;CAAO;CAAO;CAAO;AAAM;AAE1D,SAAgB,gBACd,MACA,YACA,SACA;CACA,IAAI,OAAO,WAAW,eAAe,CAAC,OAAO,KAAK;EAChD,QAAQ,KAAK,8BAA8B;EAC3C,OAAO;CACT;CACA,IAAI,QAAQ,SAAS,IAAI,GAAG;CAC5B,IAAI,OAAO,SAAS,KAAK,SAAS,WAAW,GAAG;CAChD,IAAI,OAAO,SAAS,KAAK,SAAS,WAAW,GAAG;CAEhD,MAAM,CAAC,MAAM,UAAUA,kBAAAA,YAAY,MAAM,YAAY,OAAO;CAI5D,IAAI,SAAS,UACX,OAAO,IAAI,SAAS,MAAM,KAAK,MAAM,KAAK,UAAU,MAAM,CAAC,CAAC;MAE5D,OAAO,IAAI,SAAS,MAAM,KAAK,MAAM,KAAK,UAAU,MAAM,CAAC,CAAC;AAEhE;AAEA,SAAgB,cAAc,SAAkB;CAC9C,QAAQ,EAAE,SAAS,gBAAkC;EACnD,IAAI,OAAO,WAAW,eAAe,CAAC,OAAO,KAAK;GAChD,QAAQ,KAAK,8BAA8B;GAC3C;EACF;EAEA,OAAO,IAAI,QAAQ,SAAS;GAC1B,OAAOC,oBAAAA,SAAS,WAAW,KAAK;GAChC,aAAaA,oBAAAA,SAAS,WAAW,YAAY;GAC7C,YAAY;EACd,CAAC;CACH;AACF;AAQA,SAAgB,UAAU,SAAwC;CAEhE,MAAM,MAAM,sDAAsD,mBAAmB,QAAQ,OAAO;CACpG,OAAO;EACL,MAAM;EACN,OAAOC,kCAAAA,WAAW,iBAAiBC,kCAAAA,SAASC,kBAAAA,oBAAoB,QAAQ,YAAY,CAAC;EACrF,SAAS,cAAc,QAAQ,OAAO;EACtC,QAAQ;GACN,IAAI;GACJ,QAAQ;;;;;;;;sBAQQ,KAAK,UAAU,GAAG,EAAE;;;;;;sBAMpB,KAAK,UAAU,QAAQ,OAAO,EAAE;;;EAGlD;CACF;AACF"}
1
+ {"version":3,"file":"reddit-pixel.cjs","names":["isLocalHost","mapRDTEvent","getFirst","adsTracker","adEvents","isStandardRDTEvent"],"sources":["../../src/third-parties/reddit-pixel.ts"],"sourcesContent":["import type { UpdateVisitorDTO } from '../schema/index';\nimport { type PixelId, type RDT, isStandardRDTEvent, mapRDTEvent } from '../track/rdt';\nimport type { EventName, TrackName, TrackProperties } from '../track/types';\nimport { getFirst } from '../utils/field';\nimport {\n type AdsOptions,\n type Integration,\n adEvents,\n adsTracker,\n isLocalHost,\n} from './integration';\n\ndeclare global {\n interface Window {\n /** Undefined until the Reddit Pixel script has loaded. */\n rdt?: RDT['rdt'];\n }\n}\n\nconst metrics = ['CLS', 'FCP', 'FID', 'INP', 'LCP', 'TTFB'];\n\nexport function sendRedditEvent<T extends EventName>(\n name: TrackName<T>,\n properties?: TrackProperties<T>,\n eventId?: string\n) {\n if (typeof window === 'undefined' || !window.rdt) {\n console.warn('rdt has not been initialized');\n return false;\n }\n if (metrics.includes(name)) return;\n if (isLocalHost()) return;\n\n const [type, params] = mapRDTEvent(name, properties, eventId);\n // The two branches are identical on purpose: `rdt('track', ...)` is overloaded — a standard\n // event name carries its own params type, 'Custom' carries `CustomEventParams` — and what\n // `mapRDTEvent` returns is a union of both. Narrowing `type` is what picks a single overload.\n if (type === 'Custom') {\n window.rdt('track', type, JSON.parse(JSON.stringify(params)));\n } else {\n window.rdt('track', type, JSON.parse(JSON.stringify(params)));\n }\n}\n\nexport function setRedditUser(pixelId: PixelId) {\n return ({ user_id, user_data }: UpdateVisitorDTO) => {\n if (typeof window === 'undefined' || !window.rdt) {\n console.warn('rdt has not been initialized');\n return;\n }\n\n window.rdt('init', pixelId, {\n email: getFirst(user_data?.email),\n phoneNumber: getFirst(user_data?.phone_number),\n externalId: user_id,\n });\n };\n}\n\n/** Reddit Pixel: the events `mapRDTEvent` maps to a Reddit standard event, and `customEvents`. */\n/** Reddit's configuration, shared by `redditAds` and `redditConversions` on the server. */\nexport interface RedditAdsOptions extends AdsOptions {\n pixelId: PixelId;\n}\n\nexport function redditAds(options: RedditAdsOptions): Integration {\n // As the Ads console's tag: the pixel loads with its id.\n const src = `https://www.redditstatic.com/ads/pixel.js?pixel_id=${encodeURIComponent(options.pixelId)}`;\n return {\n type: 'ads',\n track: adsTracker(sendRedditEvent, adEvents(isStandardRDTEvent, options.customEvents)),\n setUser: setRedditUser(options.pixelId),\n script: {\n id: 'reddit-pixel',\n inline: `\n !function(w,d) {\n if(!w.rdt) {\n var p = w.rdt = function() {\n p.sendEvent ? p.sendEvent.apply(p,arguments) : p.callQueue.push(arguments)\n };\n p.callQueue = [];\n var t = d.createElement(\"script\");\n t.src = ${JSON.stringify(src)};\n t.async = !0;\n var s = d.getElementsByTagName(\"script\")[0];\n s.parentNode.insertBefore(t,s)\n }\n }(window, document);\n rdt('init', ${JSON.stringify(options.pixelId)});\n rdt('track', 'PageVisit');\n `,\n },\n };\n}\n"],"mappings":";;;;;AAmBA,MAAM,UAAU;CAAC;CAAO;CAAO;CAAO;CAAO;CAAO;AAAM;AAE1D,SAAgB,gBACd,MACA,YACA,SACA;CACA,IAAI,OAAO,WAAW,eAAe,CAAC,OAAO,KAAK;EAChD,QAAQ,KAAK,8BAA8B;EAC3C,OAAO;CACT;CACA,IAAI,QAAQ,SAA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
+ {"version":3,"file":"reddit-pixel.d.cts","names":[],"sources":["../../src/third-parties/reddit-pixel.ts"],"mappings":";;;;QAYQ;YACI;;IAER,MAAM;;;wBAMM,gBAAgB,UAAU,WACxC,MAAM,UAAU,IAChB,aAAa,gBAAgB,IAC7B;wBAoBc,cAAc,SAAS,aAAO,SAAA,aACZ;;;iBAgBjB,yBAAyB;EACxC,SAAS;;wBAGK,UAAU,SAAS,mBAAmB"}
@@ -1 +1 @@
1
- {"version":3,"file":"reddit-pixel.d.mts","names":[],"sources":["../../src/third-parties/reddit-pixel.ts"],"mappings":";;;;QAMQ;YACI;;IAER,MAAM;;;wBAMM,gBAAgB,UAAU,WACxC,MAAM,UAAU,IAChB,aAAa,gBAAgB,IAC7B;wBAqBc,cAAc,SAAS,aAAO,SAAA,aACZ;;;iBAgBjB,yBAAyB;EACxC,SAAS;;wBAGK,UAAU,SAAS,mBAAmB"}
1
+ {"version":3,"file":"reddit-pixel.d.mts","names":[],"sources":["../../src/third-parties/reddit-pixel.ts"],"mappings":";;;;QAYQ;YACI;;IAER,MAAM;;;wBAMM,gBAAgB,UAAU,WACxC,MAAM,UAAU,IAChB,aAAa,gBAAgB,IAC7B;wBAoBc,cAAc,SAAS,aAAO,SAAA,aACZ;;;iBAgBjB,yBAAyB;EACxC,SAAS;;wBAGK,UAAU,SAAS,mBAAmB"}
@@ -1,5 +1,5 @@
1
1
  import { getFirst } from "../utils/field.mjs";
2
- import { adEvents, adsTracker } from "./integration.mjs";
2
+ import { adEvents, adsTracker, isLocalHost } from "./integration.mjs";
3
3
  import { isStandardRDTEvent, mapRDTEvent } from "../track/rdt.mjs";
4
4
  // src/third-parties/reddit-pixel.ts
5
5
  const metrics = [
@@ -16,8 +16,7 @@ function sendRedditEvent(name, properties, eventId) {
16
16
  return false;
17
17
  }
18
18
  if (metrics.includes(name)) return;
19
- if (window.location.host.includes("127.0.0.1")) return;
20
- if (window.location.host.includes("localhost")) return;
19
+ if (isLocalHost()) return;
21
20
  const [type, params] = mapRDTEvent(name, properties, eventId);
22
21
  if (type === "Custom") window.rdt("track", type, JSON.parse(JSON.stringify(params)));
23
22
  else window.rdt("track", type, JSON.parse(JSON.stringify(params)));
@@ -1 +1 @@
1
- {"version":3,"file":"reddit-pixel.mjs","names":[],"sources":["../../src/third-parties/reddit-pixel.ts"],"sourcesContent":["import type { UpdateVisitorDTO } from '../schema/index';\nimport { type PixelId, type RDT, isStandardRDTEvent, mapRDTEvent } from '../track/rdt';\nimport type { EventName, TrackName, TrackProperties } from '../track/types';\nimport { getFirst } from '../utils/field';\nimport { type AdsOptions, type Integration, adEvents, adsTracker } from './integration';\n\ndeclare global {\n interface Window {\n /** Undefined until the Reddit Pixel script has loaded. */\n rdt?: RDT['rdt'];\n }\n}\n\nconst metrics = ['CLS', 'FCP', 'FID', 'INP', 'LCP', 'TTFB'];\n\nexport function sendRedditEvent<T extends EventName>(\n name: TrackName<T>,\n properties?: TrackProperties<T>,\n eventId?: string\n) {\n if (typeof window === 'undefined' || !window.rdt) {\n console.warn('rdt has not been initialized');\n return false;\n }\n if (metrics.includes(name)) return;\n if (window.location.host.includes('127.0.0.1')) return;\n if (window.location.host.includes('localhost')) return;\n\n const [type, params] = mapRDTEvent(name, properties, eventId);\n // The two branches are identical on purpose: `rdt('track', ...)` is overloaded — a standard\n // event name carries its own params type, 'Custom' carries `CustomEventParams` — and what\n // `mapRDTEvent` returns is a union of both. Narrowing `type` is what picks a single overload.\n if (type === 'Custom') {\n window.rdt('track', type, JSON.parse(JSON.stringify(params)));\n } else {\n window.rdt('track', type, JSON.parse(JSON.stringify(params)));\n }\n}\n\nexport function setRedditUser(pixelId: PixelId) {\n return ({ user_id, user_data }: UpdateVisitorDTO) => {\n if (typeof window === 'undefined' || !window.rdt) {\n console.warn('rdt has not been initialized');\n return;\n }\n\n window.rdt('init', pixelId, {\n email: getFirst(user_data?.email),\n phoneNumber: getFirst(user_data?.phone_number),\n externalId: user_id,\n });\n };\n}\n\n/** Reddit Pixel: the events `mapRDTEvent` maps to a Reddit standard event, and `customEvents`. */\n/** Reddit's configuration, shared by `redditAds` and `redditConversions` on the server. */\nexport interface RedditAdsOptions extends AdsOptions {\n pixelId: PixelId;\n}\n\nexport function redditAds(options: RedditAdsOptions): Integration {\n // As the Ads console's tag: the pixel loads with its id.\n const src = `https://www.redditstatic.com/ads/pixel.js?pixel_id=${encodeURIComponent(options.pixelId)}`;\n return {\n type: 'ads',\n track: adsTracker(sendRedditEvent, adEvents(isStandardRDTEvent, options.customEvents)),\n setUser: setRedditUser(options.pixelId),\n script: {\n id: 'reddit-pixel',\n inline: `\n !function(w,d) {\n if(!w.rdt) {\n var p = w.rdt = function() {\n p.sendEvent ? p.sendEvent.apply(p,arguments) : p.callQueue.push(arguments)\n };\n p.callQueue = [];\n var t = d.createElement(\"script\");\n t.src = ${JSON.stringify(src)};\n t.async = !0;\n var s = d.getElementsByTagName(\"script\")[0];\n s.parentNode.insertBefore(t,s)\n }\n }(window, document);\n rdt('init', ${JSON.stringify(options.pixelId)});\n rdt('track', 'PageVisit');\n `,\n },\n };\n}\n"],"mappings":";;;;AAaA,MAAM,UAAU;CAAC;CAAO;CAAO;CAAO;CAAO;CAAO;AAAM;AAE1D,SAAgB,gBACd,MACA,YACA,SACA;CACA,IAAI,OAAO,WAAW,eAAe,CAAC,OAAO,KAAK;EAChD,QAAQ,KAAK,8BAA8B;EAC3C,OAAO;CACT;CACA,IAAI,QAAQ,SAAS,IAAI,GAAG;CAC5B,IAAI,OAAO,SAAS,KAAK,SAAS,WAAW,GAAG;CAChD,IAAI,OAAO,SAAS,KAAK,SAAS,WAAW,GAAG;CAEhD,MAAM,CAAC,MAAM,UAAU,YAAY,MAAM,YAAY,OAAO;CAI5D,IAAI,SAAS,UACX,OAAO,IAAI,SAAS,MAAM,KAAK,MAAM,KAAK,UAAU,MAAM,CAAC,CAAC;MAE5D,OAAO,IAAI,SAAS,MAAM,KAAK,MAAM,KAAK,UAAU,MAAM,CAAC,CAAC;AAEhE;AAEA,SAAgB,cAAc,SAAkB;CAC9C,QAAQ,EAAE,SAAS,gBAAkC;EACnD,IAAI,OAAO,WAAW,eAAe,CAAC,OAAO,KAAK;GAChD,QAAQ,KAAK,8BAA8B;GAC3C;EACF;EAEA,OAAO,IAAI,QAAQ,SAAS;GAC1B,OAAO,SAAS,WAAW,KAAK;GAChC,aAAa,SAAS,WAAW,YAAY;GAC7C,YAAY;EACd,CAAC;CACH;AACF;AAQA,SAAgB,UAAU,SAAwC;CAEhE,MAAM,MAAM,sDAAsD,mBAAmB,QAAQ,OAAO;CACpG,OAAO;EACL,MAAM;EACN,OAAO,WAAW,iBAAiB,SAAS,oBAAoB,QAAQ,YAAY,CAAC;EACrF,SAAS,cAAc,QAAQ,OAAO;EACtC,QAAQ;GACN,IAAI;GACJ,QAAQ;;;;;;;;sBAQQ,KAAK,UAAU,GAAG,EAAE;;;;;;sBAMpB,KAAK,UAAU,QAAQ,OAAO,EAAE;;;EAGlD;CACF;AACF"}
1
+ {"version":3,"file":"reddit-pixel.mjs","names":[],"sources":["../../src/third-parties/reddit-pixel.ts"],"sourcesContent":["import type { UpdateVisitorDTO } from '../schema/index';\nimport { type PixelId, type RDT, isStandardRDTEvent, mapRDTEvent } from '../track/rdt';\nimport type { EventName, TrackName, TrackProperties } from '../track/types';\nimport { getFirst } from '../utils/field';\nimport {\n type AdsOptions,\n type Integration,\n adEvents,\n adsTracker,\n isLocalHost,\n} from './integration';\n\ndeclare global {\n interface Window {\n /** Undefined until the Reddit Pixel script has loaded. */\n rdt?: RDT['rdt'];\n }\n}\n\nconst metrics = ['CLS', 'FCP', 'FID', 'INP', 'LCP', 'TTFB'];\n\nexport function sendRedditEvent<T extends EventName>(\n name: TrackName<T>,\n properties?: TrackProperties<T>,\n eventId?: string\n) {\n if (typeof window === 'undefined' || !window.rdt) {\n console.warn('rdt has not been initialized');\n return false;\n }\n if (metrics.includes(name)) return;\n if (isLocalHost()) return;\n\n const [type, params] = mapRDTEvent(name, properties, eventId);\n // The two branches are identical on purpose: `rdt('track', ...)` is overloaded — a standard\n // event name carries its own params type, 'Custom' carries `CustomEventParams` — and what\n // `mapRDTEvent` returns is a union of both. Narrowing `type` is what picks a single overload.\n if (type === 'Custom') {\n window.rdt('track', type, JSON.parse(JSON.stringify(params)));\n } else {\n window.rdt('track', type, JSON.parse(JSON.stringify(params)));\n }\n}\n\nexport function setRedditUser(pixelId: PixelId) {\n return ({ user_id, user_data }: UpdateVisitorDTO) => {\n if (typeof window === 'undefined' || !window.rdt) {\n console.warn('rdt has not been initialized');\n return;\n }\n\n window.rdt('init', pixelId, {\n email: getFirst(user_data?.email),\n phoneNumber: getFirst(user_data?.phone_number),\n externalId: user_id,\n });\n };\n}\n\n/** Reddit Pixel: the events `mapRDTEvent` maps to a Reddit standard event, and `customEvents`. */\n/** Reddit's configuration, shared by `redditAds` and `redditConversions` on the server. */\nexport interface RedditAdsOptions extends AdsOptions {\n pixelId: PixelId;\n}\n\nexport function redditAds(options: RedditAdsOptions): Integration {\n // As the Ads console's tag: the pixel loads with its id.\n const src = `https://www.redditstatic.com/ads/pixel.js?pixel_id=${encodeURIComponent(options.pixelId)}`;\n return {\n type: 'ads',\n track: adsTracker(sendRedditEvent, adEvents(isStandardRDTEvent, options.customEvents)),\n setUser: setRedditUser(options.pixelId),\n script: {\n id: 'reddit-pixel',\n inline: `\n !function(w,d) {\n if(!w.rdt) {\n var p = w.rdt = function() {\n p.sendEvent ? p.sendEvent.apply(p,arguments) : p.callQueue.push(arguments)\n };\n p.callQueue = [];\n var t = d.createElement(\"script\");\n t.src = ${JSON.stringify(src)};\n t.async = !0;\n var s = d.getElementsByTagName(\"script\")[0];\n s.parentNode.insertBefore(t,s)\n }\n }(window, document);\n rdt('init', ${JSON.stringify(options.pixelId)});\n rdt('track', 'PageVisit');\n `,\n },\n };\n}\n"],"mappings":";;;;AAmBA,MAAM,UAAU;CAAC;CAAO;CAAO;CAAO;CAAO;CAAO;AAAM;AAE1D,SAAgB,gBACd,MACA,YACA,SACA;CACA,IAAI,OAAO,WAAW,eAAe,CAAC,OAAO,KAAK;EAChD,QAAQ,KAAK,8BAA8B;EAC3C,OAAO;CACT;CACA,IAAI,QAAQ,SAAS,IAAI,GAAG;CAC5B,IAAI,YAAY,GAAG;CAEnB,MAAM,CAAC,MAAM,UAAU,YAAY,MAAM,YAAY,OAAO;CAI5D,IAAI,SAAS,UACX,OAAO,IAAI,SAAS,MAAM,KAAK,MAAM,KAAK,UAAU,MAAM,CAAC,CAAC;MAE5D,OAAO,IAAI,SAAS,MAAM,KAAK,MAAM,KAAK,UAAU,MAAM,CAAC,CAAC;AAEhE;AAEA,SAAgB,cAAc,SAAkB;CAC9C,QAAQ,EAAE,SAAS,gBAAkC;EACnD,IAAI,OAAO,WAAW,eAAe,CAAC,OAAO,KAAK;GAChD,QAAQ,KAAK,8BAA8B;GAC3C;EACF;EAEA,OAAO,IAAI,QAAQ,SAAS;GAC1B,OAAO,SAAS,WAAW,KAAK;GAChC,aAAa,SAAS,WAAW,YAAY;GAC7C,YAAY;EACd,CAAC;CACH;AACF;AAQA,SAAgB,UAAU,SAAwC;CAEhE,MAAM,MAAM,sDAAsD,mBAAmB,QAAQ,OAAO;CACpG,OAAO;EACL,MAAM;EACN,OAAO,WAAW,iBAAiB,SAAS,oBAAoB,QAAQ,YAAY,CAAC;EACrF,SAAS,cAAc,QAAQ,OAAO;EACtC,QAAQ;GACN,IAAI;GACJ,QAAQ;;;;;;;;sBAQQ,KAAK,UAAU,GAAG,EAAE;;;;;;sBAMpB,KAAK,UAAU,QAAQ,OAAO,EAAE;;;EAGlD;CACF;AACF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@shware/analytics",
3
- "version": "16.3.3",
3
+ "version": "16.3.5",
4
4
  "private": false,
5
5
  "repository": {
6
6
  "type": "git",