@shware/analytics 16.2.3 → 16.3.1

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.
package/README.md CHANGED
@@ -128,7 +128,19 @@ With server-evaluated flags, skip the wait: pass them in `config.bootstrap` and
128
128
  </PosthogProvider>
129
129
  ```
130
130
 
131
- For error tracking, `<PosthogErrorBoundary fallback={…}>` (with `posthog-js/react`'s props) sends a render error to PostHog with its component stack, tied to the session's replay, and renders `fallback` instead; an error before the library loads is queued on the stub. Errors outside render (event handlers, unhandled rejections) are the library's own exception autocapture: `capture_exceptions: true` in `config`. What no boundary of yours sees — an uncaught error, one a framework's boundary caught (TanStack Router's `errorComponent`), a hydration mismatch React recovered from — `setupReactErrorHandler()` reports from React 19's root options, in the client entry: `hydrateRoot(document, <StartClient />, { onUncaughtError: setupReactErrorHandler(), onCaughtError: setupReactErrorHandler(), onRecoverableError: setupReactErrorHandler() })`.
131
+ For error tracking, turn it on in `posthogAnalytics` with `errorTracking`: exception autocapture (window errors, unhandled rejections) and a filter for what is not yours to fix — `ignoreErrors` matched against each error's `Type: message`, `denyUrls` against the file of its innermost frame, as Sentry's options of the same names. `config` reaches `posthog.init` as JSON, which drops a `before_send` function, so the filter is written into the snippet and applies from the first event. `errorTracking: false` sends no exception at all, for local development:
132
+
133
+ ```ts
134
+ posthogAnalytics({
135
+ token: 'phc_…',
136
+ config: { api_host: 'https://us.i.posthog.com', defaults: '2026-01-30' },
137
+ errorTracking: isDev
138
+ ? false
139
+ : { ignoreErrors: ['UET is not defined'], denyUrls: ['/gsi/client'] },
140
+ });
141
+ ```
142
+
143
+ Each exception carries the session id, so its issue links to the session's replay. `capturePosthogException(error, properties?)` reports one yourself — from an http client's error hook, or a `catch` that recovers — queued on the stub like `sendPosthogEvent`, and never throws. `<PosthogErrorBoundary fallback={…}>` (with `posthog-js/react`'s props) sends a render error with its component stack and renders `fallback` instead. What no boundary of yours sees — an uncaught error, one a framework's boundary caught (TanStack Router's), a hydration mismatch React recovered from — `setupPosthogReactErrorHandler()` reports from React 19's root options in the client entry, logging it with `console.error` as React would (a callback replaces that logging): `hydrateRoot(document, <StartClient />, { onUncaughtError: setupPosthogReactErrorHandler(), onCaughtError: setupPosthogReactErrorHandler(), onRecoverableError: setupPosthogReactErrorHandler() })`. Every one of them goes through the `errorTracking` filter.
132
144
 
133
145
  Under `posthogFlagsReady()` with `config.bootstrap` the wait ends as soon as the library loads. On Next.js its snippet uses `next/script`'s `beforeInteractive`, so the stub exists before hydration tracks anything; render `<Analytics>` in the root layout for that. `<Analytics>` also preconnects to PostHog's assets host (`Integration.preconnect`, through `react-dom`'s `preconnect`), so `array.js` starts sooner. The `PostHog` and `PostHogConfig` types come from `@posthog/types`, PostHog's types-only package for the snippet, a dependency of this one: the host does not install `posthog-js` for them. In an app, `firebaseAnalytics()` (every event) and `metaAppEvents({ customEvents })` (the conversions Meta maps, like `metaAds`) are the `integrations`. A platform the SDK does not cover is an object implementing `Integration` (`type`, `track`, and optionally `setUser` and `script`).
134
146
 
@@ -43,7 +43,7 @@ function Analytics({ pathname, search, integrations, facebookAppId, nonce, repor
43
43
  exports.Analytics = Analytics;
44
44
  exports.PosthogErrorBoundary = require_react_posthog_error_boundary.PosthogErrorBoundary;
45
45
  exports.PosthogProvider = require_react_posthog.PosthogProvider;
46
- exports.setupReactErrorHandler = require_react_posthog_error_boundary.setupReactErrorHandler;
46
+ exports.setupPosthogReactErrorHandler = require_react_posthog_error_boundary.setupPosthogReactErrorHandler;
47
47
  exports.useActiveFeatureFlags = require_react_posthog.useActiveFeatureFlags;
48
48
  exports.useFeatureFlagEnabled = require_react_posthog.useFeatureFlagEnabled;
49
49
  exports.useFeatureFlagPayload = require_react_posthog.useFeatureFlagPayload;
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":["uetCustomerIdOf","IntegrationScripts"],"sources":["../../src/react/index.tsx"],"sourcesContent":["import { useOutboundClickAnalytics } from '../hooks/use-outbound-click-analytics';\nimport { useReportWebVitals } from '../hooks/use-report-web-vitals';\nimport { useUETIdSync } from '../hooks/use-uet-id-sync';\nimport { useWebAnalytics } from '../hooks/use-web-analytics';\nimport {\n type AnalyticsProps,\n IntegrationScripts,\n preconnectIntegrations,\n} from '../third-parties/analytics-props';\nimport { uetCustomerIdOf } from '../third-parties/microsoft-uet';\nimport { track } from '../track/index';\n\ninterface Props extends AnalyticsProps {\n /** The router's current path; a change reports a page view. */\n pathname: string;\n /** The router's current query string, with or without the leading `?`. */\n search: string;\n}\n\n/**\n * `<Analytics>` for any React router (TanStack Router, React Router, …): the host passes the\n * current location, e.g. `useLocation()`'s `pathname` and `searchStr` / `search`.\n */\nexport function Analytics({\n pathname,\n search,\n integrations,\n facebookAppId,\n nonce,\n reportWebVitals = true,\n}: Props) {\n useWebAnalytics(pathname, search);\n useOutboundClickAnalytics();\n useUETIdSync(uetCustomerIdOf(integrations));\n preconnectIntegrations(integrations);\n\n useReportWebVitals((metric) => {\n if (!reportWebVitals) return;\n const properties = {\n value: metric.delta,\n metric_id: metric.id,\n metric_value: metric.value,\n metric_delta: metric.delta,\n metric_rating: metric.rating,\n metric_navigation_type: metric.navigationType,\n non_interaction: true, // avoids affecting bounce rate.\n };\n track(metric.name, properties);\n });\n\n return (\n <>\n {facebookAppId && <meta property=\"fb:app_id\" content={facebookAppId} />}\n <IntegrationScripts integrations={integrations} nonce={nonce} />\n </>\n );\n}\n\nexport {\n PosthogProvider,\n useActiveFeatureFlags,\n useFeatureFlagEnabled,\n useFeatureFlagPayload,\n useFeatureFlagResult,\n useFeatureFlagVariantKey,\n usePostHog,\n} from './posthog';\nexport {\n PosthogErrorBoundary,\n type PosthogErrorBoundaryFallbackProps,\n type PosthogErrorBoundaryProps,\n setupReactErrorHandler,\n} from './posthog-error-boundary';\n"],"mappings":";;;;;;;;;;;;;;;;AAuBA,SAAgB,UAAU,EACxB,UACA,QACA,cACA,eACA,OACA,kBAAkB,QACV;CACR,gCAAA,gBAAgB,UAAU,MAAM;CAChC,2CAAA,0BAA0B;CAC1B,8BAAA,aAAaA,oCAAAA,gBAAgB,YAAY,CAAC;CAC1C,sCAAA,uBAAuB,YAAY;CAEnC,oCAAA,oBAAoB,WAAW;EAC7B,IAAI,CAAC,iBAAiB;EACtB,MAAM,aAAa;GACjB,OAAO,OAAO;GACd,WAAW,OAAO;GAClB,cAAc,OAAO;GACrB,cAAc,OAAO;GACrB,eAAe,OAAO;GACtB,wBAAwB,OAAO;GAC/B,iBAAiB;EACnB;EACA,oBAAA,MAAM,OAAO,MAAM,UAAU;CAC/B,CAAC;CAED,OACE,iBAAA,GAAA,kBAAA,KAAA,CAAA,kBAAA,UAAA,EAAA,UAAA,CACG,iBAAiB,iBAAA,GAAA,kBAAA,IAAA,CAAC,QAAD;EAAM,UAAS;EAAY,SAAS;CAAgB,CAAA,GACtE,iBAAA,GAAA,kBAAA,IAAA,CAACC,sCAAAA,oBAAD;EAAkC;EAAqB;CAAQ,CAAA,CAC/D,EAAA,CAAA;AAEN"}
1
+ {"version":3,"file":"index.cjs","names":["uetCustomerIdOf","IntegrationScripts"],"sources":["../../src/react/index.tsx"],"sourcesContent":["import { useOutboundClickAnalytics } from '../hooks/use-outbound-click-analytics';\nimport { useReportWebVitals } from '../hooks/use-report-web-vitals';\nimport { useUETIdSync } from '../hooks/use-uet-id-sync';\nimport { useWebAnalytics } from '../hooks/use-web-analytics';\nimport {\n type AnalyticsProps,\n IntegrationScripts,\n preconnectIntegrations,\n} from '../third-parties/analytics-props';\nimport { uetCustomerIdOf } from '../third-parties/microsoft-uet';\nimport { track } from '../track/index';\n\ninterface Props extends AnalyticsProps {\n /** The router's current path; a change reports a page view. */\n pathname: string;\n /** The router's current query string, with or without the leading `?`. */\n search: string;\n}\n\n/**\n * `<Analytics>` for any React router (TanStack Router, React Router, …): the host passes the\n * current location, e.g. `useLocation()`'s `pathname` and `searchStr` / `search`.\n */\nexport function Analytics({\n pathname,\n search,\n integrations,\n facebookAppId,\n nonce,\n reportWebVitals = true,\n}: Props) {\n useWebAnalytics(pathname, search);\n useOutboundClickAnalytics();\n useUETIdSync(uetCustomerIdOf(integrations));\n preconnectIntegrations(integrations);\n\n useReportWebVitals((metric) => {\n if (!reportWebVitals) return;\n const properties = {\n value: metric.delta,\n metric_id: metric.id,\n metric_value: metric.value,\n metric_delta: metric.delta,\n metric_rating: metric.rating,\n metric_navigation_type: metric.navigationType,\n non_interaction: true, // avoids affecting bounce rate.\n };\n track(metric.name, properties);\n });\n\n return (\n <>\n {facebookAppId && <meta property=\"fb:app_id\" content={facebookAppId} />}\n <IntegrationScripts integrations={integrations} nonce={nonce} />\n </>\n );\n}\n\nexport {\n PosthogProvider,\n useActiveFeatureFlags,\n useFeatureFlagEnabled,\n useFeatureFlagPayload,\n useFeatureFlagResult,\n useFeatureFlagVariantKey,\n usePostHog,\n} from './posthog';\nexport {\n PosthogErrorBoundary,\n type PosthogErrorBoundaryFallbackProps,\n type PosthogErrorBoundaryProps,\n setupPosthogReactErrorHandler,\n} from './posthog-error-boundary';\n"],"mappings":";;;;;;;;;;;;;;;;AAuBA,SAAgB,UAAU,EACxB,UACA,QACA,cACA,eACA,OACA,kBAAkB,QACV;CACR,gCAAA,gBAAgB,UAAU,MAAM;CAChC,2CAAA,0BAA0B;CAC1B,8BAAA,aAAaA,oCAAAA,gBAAgB,YAAY,CAAC;CAC1C,sCAAA,uBAAuB,YAAY;CAEnC,oCAAA,oBAAoB,WAAW;EAC7B,IAAI,CAAC,iBAAiB;EACtB,MAAM,aAAa;GACjB,OAAO,OAAO;GACd,WAAW,OAAO;GAClB,cAAc,OAAO;GACrB,cAAc,OAAO;GACrB,eAAe,OAAO;GACtB,wBAAwB,OAAO;GAC/B,iBAAiB;EACnB;EACA,oBAAA,MAAM,OAAO,MAAM,UAAU;CAC/B,CAAC;CAED,OACE,iBAAA,GAAA,kBAAA,KAAA,CAAA,kBAAA,UAAA,EAAA,UAAA,CACG,iBAAiB,iBAAA,GAAA,kBAAA,IAAA,CAAC,QAAD;EAAM,UAAS;EAAY,SAAS;CAAgB,CAAA,GACtE,iBAAA,GAAA,kBAAA,IAAA,CAACC,sCAAAA,oBAAD;EAAkC;EAAqB;CAAQ,CAAA,CAC/D,EAAA,CAAA;AAEN"}
@@ -1,6 +1,6 @@
1
1
  import { AnalyticsProps } from "../third-parties/analytics-props.cjs";
2
2
  import { PosthogProvider, useActiveFeatureFlags, useFeatureFlagEnabled, useFeatureFlagPayload, useFeatureFlagResult, useFeatureFlagVariantKey, usePostHog } from "./posthog.cjs";
3
- import { PosthogErrorBoundary, PosthogErrorBoundaryFallbackProps, PosthogErrorBoundaryProps, setupReactErrorHandler } from "./posthog-error-boundary.cjs";
3
+ import { PosthogErrorBoundary, PosthogErrorBoundaryFallbackProps, PosthogErrorBoundaryProps, setupPosthogReactErrorHandler } from "./posthog-error-boundary.cjs";
4
4
  interface Props extends AnalyticsProps {
5
5
  /** The router's current path; a change reports a page view. */
6
6
  pathname: string;
@@ -12,5 +12,5 @@ interface Props extends AnalyticsProps {
12
12
  * current location, e.g. `useLocation()`'s `pathname` and `searchStr` / `search`.
13
13
  */
14
14
  export declare function Analytics({ pathname, search, integrations, facebookAppId, nonce, reportWebVitals }: Props): import("react").JSX.Element;
15
- export { PosthogErrorBoundary, type PosthogErrorBoundaryFallbackProps, type PosthogErrorBoundaryProps, PosthogProvider, setupReactErrorHandler, useActiveFeatureFlags, useFeatureFlagEnabled, useFeatureFlagPayload, useFeatureFlagResult, useFeatureFlagVariantKey, usePostHog };
15
+ export { PosthogErrorBoundary, type PosthogErrorBoundaryFallbackProps, type PosthogErrorBoundaryProps, PosthogProvider, setupPosthogReactErrorHandler, useActiveFeatureFlags, useFeatureFlagEnabled, useFeatureFlagPayload, useFeatureFlagResult, useFeatureFlagVariantKey, usePostHog };
16
16
  //# sourceMappingURL=index.d.cts.map
@@ -1,6 +1,6 @@
1
1
  import { AnalyticsProps } from "../third-parties/analytics-props.mjs";
2
2
  import { PosthogProvider, useActiveFeatureFlags, useFeatureFlagEnabled, useFeatureFlagPayload, useFeatureFlagResult, useFeatureFlagVariantKey, usePostHog } from "./posthog.mjs";
3
- import { PosthogErrorBoundary, PosthogErrorBoundaryFallbackProps, PosthogErrorBoundaryProps, setupReactErrorHandler } from "./posthog-error-boundary.mjs";
3
+ import { PosthogErrorBoundary, PosthogErrorBoundaryFallbackProps, PosthogErrorBoundaryProps, setupPosthogReactErrorHandler } from "./posthog-error-boundary.mjs";
4
4
  interface Props extends AnalyticsProps {
5
5
  /** The router's current path; a change reports a page view. */
6
6
  pathname: string;
@@ -12,5 +12,5 @@ interface Props extends AnalyticsProps {
12
12
  * current location, e.g. `useLocation()`'s `pathname` and `searchStr` / `search`.
13
13
  */
14
14
  export declare function Analytics({ pathname, search, integrations, facebookAppId, nonce, reportWebVitals }: Props): import("react").JSX.Element;
15
- export { PosthogErrorBoundary, type PosthogErrorBoundaryFallbackProps, type PosthogErrorBoundaryProps, PosthogProvider, setupReactErrorHandler, useActiveFeatureFlags, useFeatureFlagEnabled, useFeatureFlagPayload, useFeatureFlagResult, useFeatureFlagVariantKey, usePostHog };
15
+ export { PosthogErrorBoundary, type PosthogErrorBoundaryFallbackProps, type PosthogErrorBoundaryProps, PosthogProvider, setupPosthogReactErrorHandler, useActiveFeatureFlags, useFeatureFlagEnabled, useFeatureFlagPayload, useFeatureFlagResult, useFeatureFlagVariantKey, usePostHog };
16
16
  //# sourceMappingURL=index.d.mts.map
@@ -6,7 +6,7 @@ import { useUETIdSync } from "../hooks/use-uet-id-sync.mjs";
6
6
  import { useWebAnalytics } from "../hooks/use-web-analytics.mjs";
7
7
  import { IntegrationScripts, preconnectIntegrations } from "../third-parties/analytics-props.mjs";
8
8
  import { PosthogProvider, useActiveFeatureFlags, useFeatureFlagEnabled, useFeatureFlagPayload, useFeatureFlagResult, useFeatureFlagVariantKey, usePostHog } from "./posthog.mjs";
9
- import { PosthogErrorBoundary, setupReactErrorHandler } from "./posthog-error-boundary.mjs";
9
+ import { PosthogErrorBoundary, setupPosthogReactErrorHandler } from "./posthog-error-boundary.mjs";
10
10
  import { Fragment, jsx, jsxs } from "react/jsx-runtime";
11
11
  // src/react/index.tsx
12
12
  /**
@@ -39,6 +39,6 @@ function Analytics({ pathname, search, integrations, facebookAppId, nonce, repor
39
39
  nonce
40
40
  })] });
41
41
  }
42
- export { Analytics, PosthogErrorBoundary, PosthogProvider, setupReactErrorHandler, useActiveFeatureFlags, useFeatureFlagEnabled, useFeatureFlagPayload, useFeatureFlagResult, useFeatureFlagVariantKey, usePostHog };
42
+ export { Analytics, PosthogErrorBoundary, PosthogProvider, setupPosthogReactErrorHandler, useActiveFeatureFlags, useFeatureFlagEnabled, useFeatureFlagPayload, useFeatureFlagResult, useFeatureFlagVariantKey, usePostHog };
43
43
 
44
44
  //# sourceMappingURL=index.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":[],"sources":["../../src/react/index.tsx"],"sourcesContent":["import { useOutboundClickAnalytics } from '../hooks/use-outbound-click-analytics';\nimport { useReportWebVitals } from '../hooks/use-report-web-vitals';\nimport { useUETIdSync } from '../hooks/use-uet-id-sync';\nimport { useWebAnalytics } from '../hooks/use-web-analytics';\nimport {\n type AnalyticsProps,\n IntegrationScripts,\n preconnectIntegrations,\n} from '../third-parties/analytics-props';\nimport { uetCustomerIdOf } from '../third-parties/microsoft-uet';\nimport { track } from '../track/index';\n\ninterface Props extends AnalyticsProps {\n /** The router's current path; a change reports a page view. */\n pathname: string;\n /** The router's current query string, with or without the leading `?`. */\n search: string;\n}\n\n/**\n * `<Analytics>` for any React router (TanStack Router, React Router, …): the host passes the\n * current location, e.g. `useLocation()`'s `pathname` and `searchStr` / `search`.\n */\nexport function Analytics({\n pathname,\n search,\n integrations,\n facebookAppId,\n nonce,\n reportWebVitals = true,\n}: Props) {\n useWebAnalytics(pathname, search);\n useOutboundClickAnalytics();\n useUETIdSync(uetCustomerIdOf(integrations));\n preconnectIntegrations(integrations);\n\n useReportWebVitals((metric) => {\n if (!reportWebVitals) return;\n const properties = {\n value: metric.delta,\n metric_id: metric.id,\n metric_value: metric.value,\n metric_delta: metric.delta,\n metric_rating: metric.rating,\n metric_navigation_type: metric.navigationType,\n non_interaction: true, // avoids affecting bounce rate.\n };\n track(metric.name, properties);\n });\n\n return (\n <>\n {facebookAppId && <meta property=\"fb:app_id\" content={facebookAppId} />}\n <IntegrationScripts integrations={integrations} nonce={nonce} />\n </>\n );\n}\n\nexport {\n PosthogProvider,\n useActiveFeatureFlags,\n useFeatureFlagEnabled,\n useFeatureFlagPayload,\n useFeatureFlagResult,\n useFeatureFlagVariantKey,\n usePostHog,\n} from './posthog';\nexport {\n PosthogErrorBoundary,\n type PosthogErrorBoundaryFallbackProps,\n type PosthogErrorBoundaryProps,\n setupReactErrorHandler,\n} from './posthog-error-boundary';\n"],"mappings":";;;;;;;;;;;;;;;AAuBA,SAAgB,UAAU,EACxB,UACA,QACA,cACA,eACA,OACA,kBAAkB,QACV;CACR,gBAAgB,UAAU,MAAM;CAChC,0BAA0B;CAC1B,aAAa,gBAAgB,YAAY,CAAC;CAC1C,uBAAuB,YAAY;CAEnC,oBAAoB,WAAW;EAC7B,IAAI,CAAC,iBAAiB;EACtB,MAAM,aAAa;GACjB,OAAO,OAAO;GACd,WAAW,OAAO;GAClB,cAAc,OAAO;GACrB,cAAc,OAAO;GACrB,eAAe,OAAO;GACtB,wBAAwB,OAAO;GAC/B,iBAAiB;EACnB;EACA,MAAM,OAAO,MAAM,UAAU;CAC/B,CAAC;CAED,OACE,qBAAA,UAAA,EAAA,UAAA,CACG,iBAAiB,oBAAC,QAAD;EAAM,UAAS;EAAY,SAAS;CAAgB,CAAA,GACtE,oBAAC,oBAAD;EAAkC;EAAqB;CAAQ,CAAA,CAC/D,EAAA,CAAA;AAEN"}
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../../src/react/index.tsx"],"sourcesContent":["import { useOutboundClickAnalytics } from '../hooks/use-outbound-click-analytics';\nimport { useReportWebVitals } from '../hooks/use-report-web-vitals';\nimport { useUETIdSync } from '../hooks/use-uet-id-sync';\nimport { useWebAnalytics } from '../hooks/use-web-analytics';\nimport {\n type AnalyticsProps,\n IntegrationScripts,\n preconnectIntegrations,\n} from '../third-parties/analytics-props';\nimport { uetCustomerIdOf } from '../third-parties/microsoft-uet';\nimport { track } from '../track/index';\n\ninterface Props extends AnalyticsProps {\n /** The router's current path; a change reports a page view. */\n pathname: string;\n /** The router's current query string, with or without the leading `?`. */\n search: string;\n}\n\n/**\n * `<Analytics>` for any React router (TanStack Router, React Router, …): the host passes the\n * current location, e.g. `useLocation()`'s `pathname` and `searchStr` / `search`.\n */\nexport function Analytics({\n pathname,\n search,\n integrations,\n facebookAppId,\n nonce,\n reportWebVitals = true,\n}: Props) {\n useWebAnalytics(pathname, search);\n useOutboundClickAnalytics();\n useUETIdSync(uetCustomerIdOf(integrations));\n preconnectIntegrations(integrations);\n\n useReportWebVitals((metric) => {\n if (!reportWebVitals) return;\n const properties = {\n value: metric.delta,\n metric_id: metric.id,\n metric_value: metric.value,\n metric_delta: metric.delta,\n metric_rating: metric.rating,\n metric_navigation_type: metric.navigationType,\n non_interaction: true, // avoids affecting bounce rate.\n };\n track(metric.name, properties);\n });\n\n return (\n <>\n {facebookAppId && <meta property=\"fb:app_id\" content={facebookAppId} />}\n <IntegrationScripts integrations={integrations} nonce={nonce} />\n </>\n );\n}\n\nexport {\n PosthogProvider,\n useActiveFeatureFlags,\n useFeatureFlagEnabled,\n useFeatureFlagPayload,\n useFeatureFlagResult,\n useFeatureFlagVariantKey,\n usePostHog,\n} from './posthog';\nexport {\n PosthogErrorBoundary,\n type PosthogErrorBoundaryFallbackProps,\n type PosthogErrorBoundaryProps,\n setupPosthogReactErrorHandler,\n} from './posthog-error-boundary';\n"],"mappings":";;;;;;;;;;;;;;;AAuBA,SAAgB,UAAU,EACxB,UACA,QACA,cACA,eACA,OACA,kBAAkB,QACV;CACR,gBAAgB,UAAU,MAAM;CAChC,0BAA0B;CAC1B,aAAa,gBAAgB,YAAY,CAAC;CAC1C,uBAAuB,YAAY;CAEnC,oBAAoB,WAAW;EAC7B,IAAI,CAAC,iBAAiB;EACtB,MAAM,aAAa;GACjB,OAAO,OAAO;GACd,WAAW,OAAO;GAClB,cAAc,OAAO;GACrB,cAAc,OAAO;GACrB,eAAe,OAAO;GACtB,wBAAwB,OAAO;GAC/B,iBAAiB;EACnB;EACA,MAAM,OAAO,MAAM,UAAU;CAC/B,CAAC;CAED,OACE,qBAAA,UAAA,EAAA,UAAA,CACG,iBAAiB,oBAAC,QAAD;EAAM,UAAS;EAAY,SAAS;CAAgB,CAAA,GACtE,oBAAC,oBAAD;EAAkC;EAAqB;CAAQ,CAAA,CAC/D,EAAA,CAAA;AAEN"}
@@ -88,32 +88,33 @@ var PosthogErrorBoundary = class extends react.Component {
88
88
  * `client`: a handler for React 19's root options, which report what no `PosthogErrorBoundary`
89
89
  * sees — `onUncaughtError` (no boundary caught it), `onCaughtError` (a framework's boundary did,
90
90
  * e.g. TanStack Router's `errorComponent`) and `onRecoverableError` (a hydration mismatch React
91
- * recovered from). The error goes to PostHog with its component stack; `callback` gets the event
92
- * (`undefined` while only the stub is there), as React's own logging does not run once a handler
93
- * is set.
91
+ * recovered from). The error goes to PostHog with its component stack and is logged with
92
+ * `console.error`, as React's own logging does not run once a handler is set; a `callback` gets the
93
+ * event (`undefined` while only the stub is there) instead of that logging.
94
94
  *
95
95
  * ```tsx
96
96
  * hydrateRoot(document, <StartClient />, {
97
- * onUncaughtError: setupReactErrorHandler(),
98
- * onCaughtError: setupReactErrorHandler(),
99
- * onRecoverableError: setupReactErrorHandler(),
97
+ * onUncaughtError: setupPosthogReactErrorHandler(),
98
+ * onCaughtError: setupPosthogReactErrorHandler(),
99
+ * onRecoverableError: setupPosthogReactErrorHandler(),
100
100
  * });
101
101
  * ```
102
102
  *
103
103
  * Never throws, as `PosthogErrorBoundary`: a failure to report is logged.
104
104
  */
105
- function setupReactErrorHandler(callback) {
105
+ function setupPosthogReactErrorHandler(callback) {
106
106
  return (error, errorInfo) => {
107
107
  let event;
108
108
  try {
109
109
  event = require_third_parties_posthog.getPosthog()?.captureException(withComponentStack(error, errorInfo.componentStack));
110
110
  } catch (e) {
111
- console.error("setupReactErrorHandler: the error was not reported", e);
111
+ console.error("setupPosthogReactErrorHandler: the error was not reported", e);
112
112
  }
113
- callback?.(event, error, errorInfo);
113
+ if (callback) callback(event, error, errorInfo);
114
+ else console.error(error);
114
115
  };
115
116
  }
116
117
  exports.PosthogErrorBoundary = PosthogErrorBoundary;
117
- exports.setupReactErrorHandler = setupReactErrorHandler;
118
+ exports.setupPosthogReactErrorHandler = setupPosthogReactErrorHandler;
118
119
 
119
120
  //# sourceMappingURL=posthog-error-boundary.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"posthog-error-boundary.cjs","names":["Component","getPosthog","isValidElement"],"sources":["../../src/react/posthog-error-boundary.tsx"],"sourcesContent":["import type { CaptureResult, Properties } from '@posthog/types';\nimport {\n Component,\n type ErrorInfo,\n type FunctionComponent,\n type ReactNode,\n isValidElement,\n} from 'react';\nimport { getPosthog } from '../third-parties/posthog';\n\nexport interface PosthogErrorBoundaryFallbackProps {\n error: unknown;\n /** The `$exception` event sent; `undefined` while only the stub is there, which queues it. */\n exceptionEvent: CaptureResult | undefined;\n componentStack: string;\n resetError: () => void;\n}\n\nexport interface PosthogErrorBoundaryProps {\n children?: ReactNode | (() => ReactNode);\n fallback?: ReactNode | FunctionComponent<PosthogErrorBoundaryFallbackProps>;\n additionalProperties?: Properties | ((error: unknown, errorInfo: ErrorInfo) => Properties);\n}\n\ninterface State {\n error: unknown;\n componentStack: string | null;\n exceptionEvent: CaptureResult | undefined;\n}\n\nconst INITIAL_STATE: State = { error: null, componentStack: null, exceptionEvent: undefined };\n\n/**\n * The error as PostHog's own boundary reports it: the React component stack added as a cause, so\n * the issue shows which components it was thrown in.\n */\nfunction withComponentStack(error: unknown, componentStack: string | null | undefined): unknown {\n if (!componentStack) return error;\n const isError = error instanceof Error;\n const stackError = new Error(\n isError ? error.message : `Primitive value captured as exception: ${String(error)}`\n );\n stackError.name = `React ErrorBoundary ${isError ? error.name : 'Error'}`;\n stackError.stack = componentStack;\n if (!isError) return stackError;\n // At the end of the error's cause chain, keeping a last cause that is not an error under it.\n const seen = new WeakSet<Error>();\n let current = error;\n while (!seen.has(current)) {\n seen.add(current);\n if (!(current.cause instanceof Error)) {\n if (current.cause !== undefined) stackError.cause = current.cause;\n current.cause = stackError;\n break;\n }\n current = current.cause;\n }\n return error;\n}\n\n/**\n * `posthog-js/react`'s `PostHogErrorBoundary`, with its props, for the snippet-loaded library: a\n * render error in `children` is sent to PostHog's error tracking (`captureException`, as an\n * `$exception` event tied to the session's replay) and `fallback` renders instead — a\n * component gets the error and `resetError`. An error thrown before the library has loaded is\n * queued on the stub and sent once it has.\n *\n * The boundary itself never throws: a failure to report (no PostHog, an ad blocker that stopped the\n * library, a throwing `additionalProperties`) is logged and the fallback still renders. It\n * catches render errors only, as any error boundary; errors outside React's render (event\n * handlers, unhandled rejections) are the library's exception autocapture's, enabled in the\n * snippet's `config` (`capture_exceptions`).\n */\nexport class PosthogErrorBoundary extends Component<PosthogErrorBoundaryProps, State> {\n override state = INITIAL_STATE;\n\n override componentDidCatch(error: unknown, errorInfo: ErrorInfo) {\n const componentStack = errorInfo.componentStack ?? '';\n let exceptionEvent: CaptureResult | undefined;\n // Reporting must never fail the boundary: an error thrown here would go to the boundary\n // above it, if any — `additionalProperties` throwing, or an error that cannot take a cause.\n try {\n const { additionalProperties } = this.props;\n const properties =\n typeof additionalProperties === 'function'\n ? additionalProperties(error, errorInfo)\n : additionalProperties;\n exceptionEvent = getPosthog()?.captureException(\n withComponentStack(error, componentStack),\n properties\n );\n } catch (e: unknown) {\n console.error('PosthogErrorBoundary: the error was not reported', e);\n }\n this.setState({ error, componentStack, exceptionEvent });\n }\n\n resetError = () => {\n this.setState(INITIAL_STATE);\n };\n\n override render() {\n const { children, fallback } = this.props;\n const { error, componentStack, exceptionEvent } = this.state;\n if (componentStack === null) return typeof children === 'function' ? children() : children;\n\n const element =\n typeof fallback === 'function'\n ? fallback({ error, componentStack, exceptionEvent, resetError: this.resetError })\n : fallback;\n if (isValidElement(element)) return element;\n console.warn('PosthogErrorBoundary: fallback is not a React element; rendering nothing');\n return null;\n }\n}\n\n/**\n * `posthog-js/react`'s `setupReactErrorHandler`, for the snippet-loaded library, so without its\n * `client`: a handler for React 19's root options, which report what no `PosthogErrorBoundary`\n * sees — `onUncaughtError` (no boundary caught it), `onCaughtError` (a framework's boundary did,\n * e.g. TanStack Router's `errorComponent`) and `onRecoverableError` (a hydration mismatch React\n * recovered from). The error goes to PostHog with its component stack; `callback` gets the event\n * (`undefined` while only the stub is there), as React's own logging does not run once a handler\n * is set.\n *\n * ```tsx\n * hydrateRoot(document, <StartClient />, {\n * onUncaughtError: setupReactErrorHandler(),\n * onCaughtError: setupReactErrorHandler(),\n * onRecoverableError: setupReactErrorHandler(),\n * });\n * ```\n *\n * Never throws, as `PosthogErrorBoundary`: a failure to report is logged.\n */\nexport function setupReactErrorHandler(\n callback?: (event: CaptureResult | undefined, error: unknown, errorInfo: ErrorInfo) => void\n): (error: unknown, errorInfo: ErrorInfo) => void {\n return (error, errorInfo) => {\n let event: CaptureResult | undefined;\n try {\n event = getPosthog()?.captureException(withComponentStack(error, errorInfo.componentStack));\n } catch (e: unknown) {\n console.error('setupReactErrorHandler: the error was not reported', e);\n }\n callback?.(event, error, errorInfo);\n };\n}\n"],"mappings":";;;;AA8BA,MAAM,gBAAuB;CAAE,OAAO;CAAM,gBAAgB;CAAM,gBAAgB,KAAA;AAAU;;;;;AAM5F,SAAS,mBAAmB,OAAgB,gBAAoD;CAC9F,IAAI,CAAC,gBAAgB,OAAO;CAC5B,MAAM,UAAU,iBAAiB;CACjC,MAAM,aAAa,IAAI,MACrB,UAAU,MAAM,UAAU,0CAA0C,OAAO,KAAK,GAClF;CACA,WAAW,OAAO,uBAAuB,UAAU,MAAM,OAAO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;;AAqBA,SAAgB,uBACd,UACgD;CAChD,QAAQ,OAAO,cAAc;EAC3B,IAAI;EACJ,IAAI;GACF,QAAQD,8BAAAA,WAAW,CAAC,EAAE,iBAAiB,mBAAmB,OAAO,UAAU,cAAc,CAAC;EAC5F,SAAS,GAAY;GACnB,QAAQ,MAAM,sDAAsD,CAAC;EACvE;EACA,WAAW,OAAO,OAAO,SAAS;CACpC;AACF"}
1
+ {"version":3,"file":"posthog-error-boundary.cjs","names":["Component","getPosthog","isValidElement"],"sources":["../../src/react/posthog-error-boundary.tsx"],"sourcesContent":["import type { CaptureResult, Properties } from '@posthog/types';\nimport {\n Component,\n type ErrorInfo,\n type FunctionComponent,\n type ReactNode,\n isValidElement,\n} from 'react';\nimport { getPosthog } from '../third-parties/posthog';\n\nexport interface PosthogErrorBoundaryFallbackProps {\n error: unknown;\n /** The `$exception` event sent; `undefined` while only the stub is there, which queues it. */\n exceptionEvent: CaptureResult | undefined;\n componentStack: string;\n resetError: () => void;\n}\n\nexport interface PosthogErrorBoundaryProps {\n children?: ReactNode | (() => ReactNode);\n fallback?: ReactNode | FunctionComponent<PosthogErrorBoundaryFallbackProps>;\n additionalProperties?: Properties | ((error: unknown, errorInfo: ErrorInfo) => Properties);\n}\n\ninterface State {\n error: unknown;\n componentStack: string | null;\n exceptionEvent: CaptureResult | undefined;\n}\n\nconst INITIAL_STATE: State = { error: null, componentStack: null, exceptionEvent: undefined };\n\n/**\n * The error as PostHog's own boundary reports it: the React component stack added as a cause, so\n * the issue shows which components it was thrown in.\n */\nfunction withComponentStack(error: unknown, componentStack: string | null | undefined): unknown {\n if (!componentStack) return error;\n const isError = error instanceof Error;\n const stackError = new Error(\n isError ? error.message : `Primitive value captured as exception: ${String(error)}`\n );\n stackError.name = `React ErrorBoundary ${isError ? error.name : 'Error'}`;\n stackError.stack = componentStack;\n if (!isError) return stackError;\n // At the end of the error's cause chain, keeping a last cause that is not an error under it.\n const seen = new WeakSet<Error>();\n let current = error;\n while (!seen.has(current)) {\n seen.add(current);\n if (!(current.cause instanceof Error)) {\n if (current.cause !== undefined) stackError.cause = current.cause;\n current.cause = stackError;\n break;\n }\n current = current.cause;\n }\n return error;\n}\n\n/**\n * `posthog-js/react`'s `PostHogErrorBoundary`, with its props, for the snippet-loaded library: a\n * render error in `children` is sent to PostHog's error tracking (`captureException`, as an\n * `$exception` event tied to the session's replay) and `fallback` renders instead — a\n * component gets the error and `resetError`. An error thrown before the library has loaded is\n * queued on the stub and sent once it has.\n *\n * The boundary itself never throws: a failure to report (no PostHog, an ad blocker that stopped the\n * library, a throwing `additionalProperties`) is logged and the fallback still renders. It\n * catches render errors only, as any error boundary; errors outside React's render (event\n * handlers, unhandled rejections) are the library's exception autocapture's, enabled in the\n * snippet's `config` (`capture_exceptions`).\n */\nexport class PosthogErrorBoundary extends Component<PosthogErrorBoundaryProps, State> {\n override state = INITIAL_STATE;\n\n override componentDidCatch(error: unknown, errorInfo: ErrorInfo) {\n const componentStack = errorInfo.componentStack ?? '';\n let exceptionEvent: CaptureResult | undefined;\n // Reporting must never fail the boundary: an error thrown here would go to the boundary\n // above it, if any — `additionalProperties` throwing, or an error that cannot take a cause.\n try {\n const { additionalProperties } = this.props;\n const properties =\n typeof additionalProperties === 'function'\n ? additionalProperties(error, errorInfo)\n : additionalProperties;\n exceptionEvent = getPosthog()?.captureException(\n withComponentStack(error, componentStack),\n properties\n );\n } catch (e: unknown) {\n console.error('PosthogErrorBoundary: the error was not reported', e);\n }\n this.setState({ error, componentStack, exceptionEvent });\n }\n\n resetError = () => {\n this.setState(INITIAL_STATE);\n };\n\n override render() {\n const { children, fallback } = this.props;\n const { error, componentStack, exceptionEvent } = this.state;\n if (componentStack === null) return typeof children === 'function' ? children() : children;\n\n const element =\n typeof fallback === 'function'\n ? fallback({ error, componentStack, exceptionEvent, resetError: this.resetError })\n : fallback;\n if (isValidElement(element)) return element;\n console.warn('PosthogErrorBoundary: fallback is not a React element; rendering nothing');\n return null;\n }\n}\n\n/**\n * `posthog-js/react`'s `setupReactErrorHandler`, for the snippet-loaded library, so without its\n * `client`: a handler for React 19's root options, which report what no `PosthogErrorBoundary`\n * sees — `onUncaughtError` (no boundary caught it), `onCaughtError` (a framework's boundary did,\n * e.g. TanStack Router's `errorComponent`) and `onRecoverableError` (a hydration mismatch React\n * recovered from). The error goes to PostHog with its component stack and is logged with\n * `console.error`, as React's own logging does not run once a handler is set; a `callback` gets the\n * event (`undefined` while only the stub is there) instead of that logging.\n *\n * ```tsx\n * hydrateRoot(document, <StartClient />, {\n * onUncaughtError: setupPosthogReactErrorHandler(),\n * onCaughtError: setupPosthogReactErrorHandler(),\n * onRecoverableError: setupPosthogReactErrorHandler(),\n * });\n * ```\n *\n * Never throws, as `PosthogErrorBoundary`: a failure to report is logged.\n */\nexport function setupPosthogReactErrorHandler(\n callback?: (event: CaptureResult | undefined, error: unknown, errorInfo: ErrorInfo) => void\n): (error: unknown, errorInfo: ErrorInfo) => void {\n return (error, errorInfo) => {\n let event: CaptureResult | undefined;\n try {\n event = getPosthog()?.captureException(withComponentStack(error, errorInfo.componentStack));\n } catch (e: unknown) {\n console.error('setupPosthogReactErrorHandler: the error was not reported', e);\n }\n if (callback) callback(event, error, errorInfo);\n // React logs these itself only while no handler is set; keep them in the console. Not\n // `reportError`, React's own default for uncaught errors: it dispatches a window `error`,\n // which the library's exception autocapture would send a second time.\n else console.error(error);\n };\n}\n"],"mappings":";;;;AA8BA,MAAM,gBAAuB;CAAE,OAAO;CAAM,gBAAgB;CAAM,gBAAgB,KAAA;AAAU;;;;;AAM5F,SAAS,mBAAmB,OAAgB,gBAAoD;CAC9F,IAAI,CAAC,gBAAgB,OAAO;CAC5B,MAAM,UAAU,iBAAiB;CACjC,MAAM,aAAa,IAAI,MACrB,UAAU,MAAM,UAAU,0CAA0C,OAAO,KAAK,GAClF;CACA,WAAW,OAAO,uBAAuB,UAAU,MAAM,OAAO;CAChE,WAAW,QAAQ;CACnB,IAAI,CAAC,SAAS,OAAO;CAErB,MAAM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IAAI;EACJ,IAAI;GACF,QAAQD,8BAAAA,WAAW,CAAC,EAAE,iBAAiB,mBAAmB,OAAO,UAAU,cAAc,CAAC;EAC5F,SAAS,GAAY;GACnB,QAAQ,MAAM,6DAA6D,CAAC;EAC9E;EACA,IAAI,UAAU,SAAS,OAAO,OAAO,SAAS;OAIzC,QAAQ,MAAM,KAAK;CAC1B;AACF"}
@@ -41,20 +41,20 @@ export declare class PosthogErrorBoundary extends Component<PosthogErrorBoundary
41
41
  * `client`: a handler for React 19's root options, which report what no `PosthogErrorBoundary`
42
42
  * sees — `onUncaughtError` (no boundary caught it), `onCaughtError` (a framework's boundary did,
43
43
  * e.g. TanStack Router's `errorComponent`) and `onRecoverableError` (a hydration mismatch React
44
- * recovered from). The error goes to PostHog with its component stack; `callback` gets the event
45
- * (`undefined` while only the stub is there), as React's own logging does not run once a handler
46
- * is set.
44
+ * recovered from). The error goes to PostHog with its component stack and is logged with
45
+ * `console.error`, as React's own logging does not run once a handler is set; a `callback` gets the
46
+ * event (`undefined` while only the stub is there) instead of that logging.
47
47
  *
48
48
  * ```tsx
49
49
  * hydrateRoot(document, <StartClient />, {
50
- * onUncaughtError: setupReactErrorHandler(),
51
- * onCaughtError: setupReactErrorHandler(),
52
- * onRecoverableError: setupReactErrorHandler(),
50
+ * onUncaughtError: setupPosthogReactErrorHandler(),
51
+ * onCaughtError: setupPosthogReactErrorHandler(),
52
+ * onRecoverableError: setupPosthogReactErrorHandler(),
53
53
  * });
54
54
  * ```
55
55
  *
56
56
  * Never throws, as `PosthogErrorBoundary`: a failure to report is logged.
57
57
  */
58
- export declare function setupReactErrorHandler(callback?: (event: CaptureResult | undefined, error: unknown, errorInfo: ErrorInfo) => void): (error: unknown, errorInfo: ErrorInfo) => void;
58
+ export declare function setupPosthogReactErrorHandler(callback?: (event: CaptureResult | undefined, error: unknown, errorInfo: ErrorInfo) => void): (error: unknown, errorInfo: ErrorInfo) => void;
59
59
  export {};
60
60
  //# sourceMappingURL=posthog-error-boundary.d.cts.map
@@ -1 +1 @@
1
- {"version":3,"file":"posthog-error-boundary.d.cts","names":[],"sources":["../../src/react/posthog-error-boundary.tsx"],"mappings":";;iBAUiB;EACf;;EAEA,gBAAgB;EAChB;EACA;;iBAGe;EACf,WAAW,mBAAmB;EAC9B,WAAW,YAAY,kBAAkB;EACzC,uBAAuB,eAAe,gBAAgB,WAAW,cAAc;;UAGvE;EACR;EACA;EACA,gBAAgB;;;;;;;;;;;;;;;qBA8CL,6BAA6B,UAAU,2BAA2B;EACpE,OAAK;EAEL,kBAAkB,gBAAgB,WAAW;EAqBtD;EAIS,UAAM;;;;;;;;;;;;;;;;;;;;;wBAkCD,uBACd,YAAY,OAAO,2BAA2B,gBAAgB,WAAW,sBACvE,gBAAgB,WAAW"}
1
+ {"version":3,"file":"posthog-error-boundary.d.cts","names":[],"sources":["../../src/react/posthog-error-boundary.tsx"],"mappings":";;iBAUiB;EACf;;EAEA,gBAAgB;EAChB;EACA;;iBAGe;EACf,WAAW,mBAAmB;EAC9B,WAAW,YAAY,kBAAkB;EACzC,uBAAuB,eAAe,gBAAgB,WAAW,cAAc;;UAGvE;EACR;EACA;EACA,gBAAgB;;;;;;;;;;;;;;;qBA8CL,6BAA6B,UAAU,2BAA2B;EACpE,OAAK;EAEL,kBAAkB,gBAAgB,WAAW;EAqBtD;EAIS,UAAM;;;;;;;;;;;;;;;;;;;;;wBAkCD,8BACd,YAAY,OAAO,2BAA2B,gBAAgB,WAAW,sBACvE,gBAAgB,WAAW"}
@@ -41,20 +41,20 @@ export declare class PosthogErrorBoundary extends Component<PosthogErrorBoundary
41
41
  * `client`: a handler for React 19's root options, which report what no `PosthogErrorBoundary`
42
42
  * sees — `onUncaughtError` (no boundary caught it), `onCaughtError` (a framework's boundary did,
43
43
  * e.g. TanStack Router's `errorComponent`) and `onRecoverableError` (a hydration mismatch React
44
- * recovered from). The error goes to PostHog with its component stack; `callback` gets the event
45
- * (`undefined` while only the stub is there), as React's own logging does not run once a handler
46
- * is set.
44
+ * recovered from). The error goes to PostHog with its component stack and is logged with
45
+ * `console.error`, as React's own logging does not run once a handler is set; a `callback` gets the
46
+ * event (`undefined` while only the stub is there) instead of that logging.
47
47
  *
48
48
  * ```tsx
49
49
  * hydrateRoot(document, <StartClient />, {
50
- * onUncaughtError: setupReactErrorHandler(),
51
- * onCaughtError: setupReactErrorHandler(),
52
- * onRecoverableError: setupReactErrorHandler(),
50
+ * onUncaughtError: setupPosthogReactErrorHandler(),
51
+ * onCaughtError: setupPosthogReactErrorHandler(),
52
+ * onRecoverableError: setupPosthogReactErrorHandler(),
53
53
  * });
54
54
  * ```
55
55
  *
56
56
  * Never throws, as `PosthogErrorBoundary`: a failure to report is logged.
57
57
  */
58
- export declare function setupReactErrorHandler(callback?: (event: CaptureResult | undefined, error: unknown, errorInfo: ErrorInfo) => void): (error: unknown, errorInfo: ErrorInfo) => void;
58
+ export declare function setupPosthogReactErrorHandler(callback?: (event: CaptureResult | undefined, error: unknown, errorInfo: ErrorInfo) => void): (error: unknown, errorInfo: ErrorInfo) => void;
59
59
  export {};
60
60
  //# sourceMappingURL=posthog-error-boundary.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"posthog-error-boundary.d.mts","names":[],"sources":["../../src/react/posthog-error-boundary.tsx"],"mappings":";;iBAUiB;EACf;;EAEA,gBAAgB;EAChB;EACA;;iBAGe;EACf,WAAW,mBAAmB;EAC9B,WAAW,YAAY,kBAAkB;EACzC,uBAAuB,eAAe,gBAAgB,WAAW,cAAc;;UAGvE;EACR;EACA;EACA,gBAAgB;;;;;;;;;;;;;;;qBA8CL,6BAA6B,UAAU,2BAA2B;EACpE,OAAK;EAEL,kBAAkB,gBAAgB,WAAW;EAqBtD;EAIS,UAAM;;;;;;;;;;;;;;;;;;;;;wBAkCD,uBACd,YAAY,OAAO,2BAA2B,gBAAgB,WAAW,sBACvE,gBAAgB,WAAW"}
1
+ {"version":3,"file":"posthog-error-boundary.d.mts","names":[],"sources":["../../src/react/posthog-error-boundary.tsx"],"mappings":";;iBAUiB;EACf;;EAEA,gBAAgB;EAChB;EACA;;iBAGe;EACf,WAAW,mBAAmB;EAC9B,WAAW,YAAY,kBAAkB;EACzC,uBAAuB,eAAe,gBAAgB,WAAW,cAAc;;UAGvE;EACR;EACA;EACA,gBAAgB;;;;;;;;;;;;;;;qBA8CL,6BAA6B,UAAU,2BAA2B;EACpE,OAAK;EAEL,kBAAkB,gBAAgB,WAAW;EAqBtD;EAIS,UAAM;;;;;;;;;;;;;;;;;;;;;wBAkCD,8BACd,YAAY,OAAO,2BAA2B,gBAAgB,WAAW,sBACvE,gBAAgB,WAAW"}
@@ -87,31 +87,32 @@ var PosthogErrorBoundary = class extends Component {
87
87
  * `client`: a handler for React 19's root options, which report what no `PosthogErrorBoundary`
88
88
  * sees — `onUncaughtError` (no boundary caught it), `onCaughtError` (a framework's boundary did,
89
89
  * e.g. TanStack Router's `errorComponent`) and `onRecoverableError` (a hydration mismatch React
90
- * recovered from). The error goes to PostHog with its component stack; `callback` gets the event
91
- * (`undefined` while only the stub is there), as React's own logging does not run once a handler
92
- * is set.
90
+ * recovered from). The error goes to PostHog with its component stack and is logged with
91
+ * `console.error`, as React's own logging does not run once a handler is set; a `callback` gets the
92
+ * event (`undefined` while only the stub is there) instead of that logging.
93
93
  *
94
94
  * ```tsx
95
95
  * hydrateRoot(document, <StartClient />, {
96
- * onUncaughtError: setupReactErrorHandler(),
97
- * onCaughtError: setupReactErrorHandler(),
98
- * onRecoverableError: setupReactErrorHandler(),
96
+ * onUncaughtError: setupPosthogReactErrorHandler(),
97
+ * onCaughtError: setupPosthogReactErrorHandler(),
98
+ * onRecoverableError: setupPosthogReactErrorHandler(),
99
99
  * });
100
100
  * ```
101
101
  *
102
102
  * Never throws, as `PosthogErrorBoundary`: a failure to report is logged.
103
103
  */
104
- function setupReactErrorHandler(callback) {
104
+ function setupPosthogReactErrorHandler(callback) {
105
105
  return (error, errorInfo) => {
106
106
  let event;
107
107
  try {
108
108
  event = getPosthog()?.captureException(withComponentStack(error, errorInfo.componentStack));
109
109
  } catch (e) {
110
- console.error("setupReactErrorHandler: the error was not reported", e);
110
+ console.error("setupPosthogReactErrorHandler: the error was not reported", e);
111
111
  }
112
- callback?.(event, error, errorInfo);
112
+ if (callback) callback(event, error, errorInfo);
113
+ else console.error(error);
113
114
  };
114
115
  }
115
- export { PosthogErrorBoundary, setupReactErrorHandler };
116
+ export { PosthogErrorBoundary, setupPosthogReactErrorHandler };
116
117
 
117
118
  //# sourceMappingURL=posthog-error-boundary.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"posthog-error-boundary.mjs","names":[],"sources":["../../src/react/posthog-error-boundary.tsx"],"sourcesContent":["import type { CaptureResult, Properties } from '@posthog/types';\nimport {\n Component,\n type ErrorInfo,\n type FunctionComponent,\n type ReactNode,\n isValidElement,\n} from 'react';\nimport { getPosthog } from '../third-parties/posthog';\n\nexport interface PosthogErrorBoundaryFallbackProps {\n error: unknown;\n /** The `$exception` event sent; `undefined` while only the stub is there, which queues it. */\n exceptionEvent: CaptureResult | undefined;\n componentStack: string;\n resetError: () => void;\n}\n\nexport interface PosthogErrorBoundaryProps {\n children?: ReactNode | (() => ReactNode);\n fallback?: ReactNode | FunctionComponent<PosthogErrorBoundaryFallbackProps>;\n additionalProperties?: Properties | ((error: unknown, errorInfo: ErrorInfo) => Properties);\n}\n\ninterface State {\n error: unknown;\n componentStack: string | null;\n exceptionEvent: CaptureResult | undefined;\n}\n\nconst INITIAL_STATE: State = { error: null, componentStack: null, exceptionEvent: undefined };\n\n/**\n * The error as PostHog's own boundary reports it: the React component stack added as a cause, so\n * the issue shows which components it was thrown in.\n */\nfunction withComponentStack(error: unknown, componentStack: string | null | undefined): unknown {\n if (!componentStack) return error;\n const isError = error instanceof Error;\n const stackError = new Error(\n isError ? error.message : `Primitive value captured as exception: ${String(error)}`\n );\n stackError.name = `React ErrorBoundary ${isError ? error.name : 'Error'}`;\n stackError.stack = componentStack;\n if (!isError) return stackError;\n // At the end of the error's cause chain, keeping a last cause that is not an error under it.\n const seen = new WeakSet<Error>();\n let current = error;\n while (!seen.has(current)) {\n seen.add(current);\n if (!(current.cause instanceof Error)) {\n if (current.cause !== undefined) stackError.cause = current.cause;\n current.cause = stackError;\n break;\n }\n current = current.cause;\n }\n return error;\n}\n\n/**\n * `posthog-js/react`'s `PostHogErrorBoundary`, with its props, for the snippet-loaded library: a\n * render error in `children` is sent to PostHog's error tracking (`captureException`, as an\n * `$exception` event tied to the session's replay) and `fallback` renders instead — a\n * component gets the error and `resetError`. An error thrown before the library has loaded is\n * queued on the stub and sent once it has.\n *\n * The boundary itself never throws: a failure to report (no PostHog, an ad blocker that stopped the\n * library, a throwing `additionalProperties`) is logged and the fallback still renders. It\n * catches render errors only, as any error boundary; errors outside React's render (event\n * handlers, unhandled rejections) are the library's exception autocapture's, enabled in the\n * snippet's `config` (`capture_exceptions`).\n */\nexport class PosthogErrorBoundary extends Component<PosthogErrorBoundaryProps, State> {\n override state = INITIAL_STATE;\n\n override componentDidCatch(error: unknown, errorInfo: ErrorInfo) {\n const componentStack = errorInfo.componentStack ?? '';\n let exceptionEvent: CaptureResult | undefined;\n // Reporting must never fail the boundary: an error thrown here would go to the boundary\n // above it, if any — `additionalProperties` throwing, or an error that cannot take a cause.\n try {\n const { additionalProperties } = this.props;\n const properties =\n typeof additionalProperties === 'function'\n ? additionalProperties(error, errorInfo)\n : additionalProperties;\n exceptionEvent = getPosthog()?.captureException(\n withComponentStack(error, componentStack),\n properties\n );\n } catch (e: unknown) {\n console.error('PosthogErrorBoundary: the error was not reported', e);\n }\n this.setState({ error, componentStack, exceptionEvent });\n }\n\n resetError = () => {\n this.setState(INITIAL_STATE);\n };\n\n override render() {\n const { children, fallback } = this.props;\n const { error, componentStack, exceptionEvent } = this.state;\n if (componentStack === null) return typeof children === 'function' ? children() : children;\n\n const element =\n typeof fallback === 'function'\n ? fallback({ error, componentStack, exceptionEvent, resetError: this.resetError })\n : fallback;\n if (isValidElement(element)) return element;\n console.warn('PosthogErrorBoundary: fallback is not a React element; rendering nothing');\n return null;\n }\n}\n\n/**\n * `posthog-js/react`'s `setupReactErrorHandler`, for the snippet-loaded library, so without its\n * `client`: a handler for React 19's root options, which report what no `PosthogErrorBoundary`\n * sees — `onUncaughtError` (no boundary caught it), `onCaughtError` (a framework's boundary did,\n * e.g. TanStack Router's `errorComponent`) and `onRecoverableError` (a hydration mismatch React\n * recovered from). The error goes to PostHog with its component stack; `callback` gets the event\n * (`undefined` while only the stub is there), as React's own logging does not run once a handler\n * is set.\n *\n * ```tsx\n * hydrateRoot(document, <StartClient />, {\n * onUncaughtError: setupReactErrorHandler(),\n * onCaughtError: setupReactErrorHandler(),\n * onRecoverableError: setupReactErrorHandler(),\n * });\n * ```\n *\n * Never throws, as `PosthogErrorBoundary`: a failure to report is logged.\n */\nexport function setupReactErrorHandler(\n callback?: (event: CaptureResult | undefined, error: unknown, errorInfo: ErrorInfo) => void\n): (error: unknown, errorInfo: ErrorInfo) => void {\n return (error, errorInfo) => {\n let event: CaptureResult | undefined;\n try {\n event = getPosthog()?.captureException(withComponentStack(error, errorInfo.componentStack));\n } catch (e: unknown) {\n console.error('setupReactErrorHandler: the error was not reported', e);\n }\n callback?.(event, error, errorInfo);\n };\n}\n"],"mappings":";;;AA8BA,MAAM,gBAAuB;CAAE,OAAO;CAAM,gBAAgB;CAAM,gBAAgB,KAAA;AAAU;;;;;AAM5F,SAAS,mBAAmB,OAAgB,gBAAoD;CAC9F,IAAI,CAAC,gBAAgB,OAAO;CAC5B,MAAM,UAAU,iBAAiB;CACjC,MAAM,aAAa,IAAI,MACrB,UAAU,MAAM,UAAU,0CAA0C,OAAO,KAAK,GAClF;CACA,WAAW,OAAO,uBAAuB,UAAU,MAAM,OAAO;CAChE,WAAW,QAAQ;CACnB,IAAI,CAAC,SAAS,OAAO;CAErB,MAAM,uBAAO,IAAI,QAAe;CAChC,IAAI,UAAU;CACd,OAAO,CAAC,KAAK,IAAI,OAAO,GAAG;E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,MAAM,sDAAsD,CAAC;EACvE;EACA,WAAW,OAAO,OAAO,SAAS;CACpC;AACF"}
1
+ {"version":3,"file":"posthog-error-boundary.mjs","names":[],"sources":["../../src/react/posthog-error-boundary.tsx"],"sourcesContent":["import type { CaptureResult, Properties } from '@posthog/types';\nimport {\n Component,\n type ErrorInfo,\n type FunctionComponent,\n type ReactNode,\n isValidElement,\n} from 'react';\nimport { getPosthog } from '../third-parties/posthog';\n\nexport interface PosthogErrorBoundaryFallbackProps {\n error: unknown;\n /** The `$exception` event sent; `undefined` while only the stub is there, which queues it. */\n exceptionEvent: CaptureResult | undefined;\n componentStack: string;\n resetError: () => void;\n}\n\nexport interface PosthogErrorBoundaryProps {\n children?: ReactNode | (() => ReactNode);\n fallback?: ReactNode | FunctionComponent<PosthogErrorBoundaryFallbackProps>;\n additionalProperties?: Properties | ((error: unknown, errorInfo: ErrorInfo) => Properties);\n}\n\ninterface State {\n error: unknown;\n componentStack: string | null;\n exceptionEvent: CaptureResult | undefined;\n}\n\nconst INITIAL_STATE: State = { error: null, componentStack: null, exceptionEvent: undefined };\n\n/**\n * The error as PostHog's own boundary reports it: the React component stack added as a cause, so\n * the issue shows which components it was thrown in.\n */\nfunction withComponentStack(error: unknown, componentStack: string | null | undefined): unknown {\n if (!componentStack) return error;\n const isError = error instanceof Error;\n const stackError = new Error(\n isError ? error.message : `Primitive value captured as exception: ${String(error)}`\n );\n stackError.name = `React ErrorBoundary ${isError ? error.name : 'Error'}`;\n stackError.stack = componentStack;\n if (!isError) return stackError;\n // At the end of the error's cause chain, keeping a last cause that is not an error under it.\n const seen = new WeakSet<Error>();\n let current = error;\n while (!seen.has(current)) {\n seen.add(current);\n if (!(current.cause instanceof Error)) {\n if (current.cause !== undefined) stackError.cause = current.cause;\n current.cause = stackError;\n break;\n }\n current = current.cause;\n }\n return error;\n}\n\n/**\n * `posthog-js/react`'s `PostHogErrorBoundary`, with its props, for the snippet-loaded library: a\n * render error in `children` is sent to PostHog's error tracking (`captureException`, as an\n * `$exception` event tied to the session's replay) and `fallback` renders instead — a\n * component gets the error and `resetError`. An error thrown before the library has loaded is\n * queued on the stub and sent once it has.\n *\n * The boundary itself never throws: a failure to report (no PostHog, an ad blocker that stopped the\n * library, a throwing `additionalProperties`) is logged and the fallback still renders. It\n * catches render errors only, as any error boundary; errors outside React's render (event\n * handlers, unhandled rejections) are the library's exception autocapture's, enabled in the\n * snippet's `config` (`capture_exceptions`).\n */\nexport class PosthogErrorBoundary extends Component<PosthogErrorBoundaryProps, State> {\n override state = INITIAL_STATE;\n\n override componentDidCatch(error: unknown, errorInfo: ErrorInfo) {\n const componentStack = errorInfo.componentStack ?? '';\n let exceptionEvent: CaptureResult | undefined;\n // Reporting must never fail the boundary: an error thrown here would go to the boundary\n // above it, if any — `additionalProperties` throwing, or an error that cannot take a cause.\n try {\n const { additionalProperties } = this.props;\n const properties =\n typeof additionalProperties === 'function'\n ? additionalProperties(error, errorInfo)\n : additionalProperties;\n exceptionEvent = getPosthog()?.captureException(\n withComponentStack(error, componentStack),\n properties\n );\n } catch (e: unknown) {\n console.error('PosthogErrorBoundary: the error was not reported', e);\n }\n this.setState({ error, componentStack, exceptionEvent });\n }\n\n resetError = () => {\n this.setState(INITIAL_STATE);\n };\n\n override render() {\n const { children, fallback } = this.props;\n const { error, componentStack, exceptionEvent } = this.state;\n if (componentStack === null) return typeof children === 'function' ? children() : children;\n\n const element =\n typeof fallback === 'function'\n ? fallback({ error, componentStack, exceptionEvent, resetError: this.resetError })\n : fallback;\n if (isValidElement(element)) return element;\n console.warn('PosthogErrorBoundary: fallback is not a React element; rendering nothing');\n return null;\n }\n}\n\n/**\n * `posthog-js/react`'s `setupReactErrorHandler`, for the snippet-loaded library, so without its\n * `client`: a handler for React 19's root options, which report what no `PosthogErrorBoundary`\n * sees — `onUncaughtError` (no boundary caught it), `onCaughtError` (a framework's boundary did,\n * e.g. TanStack Router's `errorComponent`) and `onRecoverableError` (a hydration mismatch React\n * recovered from). The error goes to PostHog with its component stack and is logged with\n * `console.error`, as React's own logging does not run once a handler is set; a `callback` gets the\n * event (`undefined` while only the stub is there) instead of that logging.\n *\n * ```tsx\n * hydrateRoot(document, <StartClient />, {\n * onUncaughtError: setupPosthogReactErrorHandler(),\n * onCaughtError: setupPosthogReactErrorHandler(),\n * onRecoverableError: setupPosthogReactErrorHandler(),\n * });\n * ```\n *\n * Never throws, as `PosthogErrorBoundary`: a failure to report is logged.\n */\nexport function setupPosthogReactErrorHandler(\n callback?: (event: CaptureResult | undefined, error: unknown, errorInfo: ErrorInfo) => void\n): (error: unknown, errorInfo: ErrorInfo) => void {\n return (error, errorInfo) => {\n let event: CaptureResult | undefined;\n try {\n event = getPosthog()?.captureException(withComponentStack(error, errorInfo.componentStack));\n } catch (e: unknown) {\n console.error('setupPosthogReactErrorHandler: the error was not reported', e);\n }\n if (callback) callback(event, error, errorInfo);\n // React logs these itself only while no handler is set; keep them in the console. Not\n // `reportError`, React's own default for uncaught errors: it dispatches a window `error`,\n // which the library's exception autocapture would send a second time.\n else console.error(error);\n };\n}\n"],"mappings":";;;AA8BA,MAAM,gBAAuB;CAAE,OAAO;CAAM,gBAAgB;CAAM,gBAAgB,KAAA;AAAU;;;;;AAM5F,SAAS,mBAAmB,OAAgB,gBAAoD;CAC9F,IAAI,CAAC,gBAAgB,OAAO;CAC5B,MAAM,UAAU,iBAAiB;CACjC,MAAM,aAAa,IAAI,MACrB,UAAU,MAAM,UAAU,0CAA0C,OAAO,KAAK,GAClF;CACA,WAAW,OAAO,uBAAuB,UAAU,MAAM,OAAO;CAChE,WAAW,QAAQ;CACnB,IAAI,CAAC,SAAS,OAAO;CAErB,MAAM,uBAAO,IAAI,QAAe;CAChC,IAAI,UAAU;CACd,OAAO,CAAC,KAAK,IAAI,OAAO,GAAG;EACzB,KAAK,IAAI,OAAO;EAChB,IAAI,EAAE,QAAQ,iBAAiB,QAAQ;GACrC,IAAI,QAAQ,UAAU,KAAA,GAAW,WAAW,QAAQ,QAAQ;GAC5D,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 const require_third_parties_linkedin_insight_tag = require("./linkedin-insight-t
8
8
  const require_third_parties_openai_pixel = require("./openai-pixel.cjs");
9
9
  const require_third_parties_reddit_pixel = require("./reddit-pixel.cjs");
10
10
  exports.CONVERSION_EVENTS = require_third_parties_integration.CONVERSION_EVENTS;
11
+ exports.capturePosthogException = require_third_parties_posthog.capturePosthogException;
11
12
  exports.configureUET = require_third_parties_microsoft_uet.configureUET;
12
13
  exports.getLoadedPosthog = require_third_parties_posthog.getLoadedPosthog;
13
14
  exports.getPosthog = require_third_parties_posthog.getPosthog;
@@ -6,5 +6,5 @@ import { openaiAds, sendOpenAIEvent, setOpenAIUser } from "./openai-pixel.cjs";
6
6
  import { UETConsent, UETEventParams, UETItem, UETPageType, UETPid } from "../track/uetq.cjs";
7
7
  import { MicrosoftAdsIntegration, configureUET, microsoftAds, sendUETEvent, sendUETIdSync, setUETConsent, setUETUser, syncUETVisitor, uetCustomerIdOf } from "./microsoft-uet.cjs";
8
8
  import { googleAnalytics, sendGAEvent, setGAUser } from "./google-analytics.cjs";
9
- import { PostHog, PostHogConfig, getLoadedPosthog, getPosthog, posthogAnalytics, posthogFlagsReady, sendPosthogEvent, setPosthogUser } from "./posthog.cjs";
10
- export { type AdsOptions, CONVERSION_EVENTS, type Integration, type IntegrationScript, type LinkedinConversionConfig, type MicrosoftAdsIntegration, type PostHog, type PostHogConfig, type UETConsent, type UETEventParams, type UETItem, type UETPageType, type UETPid, configureUET, getLoadedPosthog, getPosthog, googleAnalytics, linkedInAds, metaAds, microsoftAds, openaiAds, posthogAnalytics, posthogFlagsReady, redditAds, sendFBEvent, sendGAEvent, sendLinkedinEvent, sendOpenAIEvent, sendPosthogEvent, sendRedditEvent, sendUETEvent, sendUETIdSync, setFBUser, setGAUser, setLinkedinUser, setOpenAIUser, setPosthogUser, setRedditUser, setUETConsent, setUETUser, syncUETVisitor, uetCustomerIdOf };
9
+ import { ErrorPattern, PostHog, PostHogConfig, PosthogErrorTrackingOptions, capturePosthogException, getLoadedPosthog, getPosthog, posthogAnalytics, posthogFlagsReady, sendPosthogEvent, setPosthogUser } from "./posthog.cjs";
10
+ export { type AdsOptions, CONVERSION_EVENTS, type ErrorPattern, type Integration, type IntegrationScript, type LinkedinConversionConfig, type MicrosoftAdsIntegration, type PostHog, type PostHogConfig, type PosthogErrorTrackingOptions, type UETConsent, type UETEventParams, type UETItem, type UETPageType, type UETPid, capturePosthogException, configureUET, getLoadedPosthog, getPosthog, googleAnalytics, linkedInAds, metaAds, microsoftAds, openaiAds, posthogAnalytics, posthogFlagsReady, redditAds, sendFBEvent, sendGAEvent, sendLinkedinEvent, sendOpenAIEvent, sendPosthogEvent, sendRedditEvent, sendUETEvent, sendUETIdSync, setFBUser, setGAUser, setLinkedinUser, setOpenAIUser, setPosthogUser, setRedditUser, setUETConsent, setUETUser, syncUETVisitor, uetCustomerIdOf };
@@ -6,5 +6,5 @@ import { openaiAds, sendOpenAIEvent, setOpenAIUser } from "./openai-pixel.mjs";
6
6
  import { UETConsent, UETEventParams, UETItem, UETPageType, UETPid } from "../track/uetq.mjs";
7
7
  import { MicrosoftAdsIntegration, configureUET, microsoftAds, sendUETEvent, sendUETIdSync, setUETConsent, setUETUser, syncUETVisitor, uetCustomerIdOf } from "./microsoft-uet.mjs";
8
8
  import { googleAnalytics, sendGAEvent, setGAUser } from "./google-analytics.mjs";
9
- import { PostHog, PostHogConfig, getLoadedPosthog, getPosthog, posthogAnalytics, posthogFlagsReady, sendPosthogEvent, setPosthogUser } from "./posthog.mjs";
10
- export { type AdsOptions, CONVERSION_EVENTS, type Integration, type IntegrationScript, type LinkedinConversionConfig, type MicrosoftAdsIntegration, type PostHog, type PostHogConfig, type UETConsent, type UETEventParams, type UETItem, type UETPageType, type UETPid, configureUET, getLoadedPosthog, getPosthog, googleAnalytics, linkedInAds, metaAds, microsoftAds, openaiAds, posthogAnalytics, posthogFlagsReady, redditAds, sendFBEvent, sendGAEvent, sendLinkedinEvent, sendOpenAIEvent, sendPosthogEvent, sendRedditEvent, sendUETEvent, sendUETIdSync, setFBUser, setGAUser, setLinkedinUser, setOpenAIUser, setPosthogUser, setRedditUser, setUETConsent, setUETUser, syncUETVisitor, uetCustomerIdOf };
9
+ import { ErrorPattern, PostHog, PostHogConfig, PosthogErrorTrackingOptions, capturePosthogException, getLoadedPosthog, getPosthog, posthogAnalytics, posthogFlagsReady, sendPosthogEvent, setPosthogUser } from "./posthog.mjs";
10
+ export { type AdsOptions, CONVERSION_EVENTS, type ErrorPattern, type Integration, type IntegrationScript, type LinkedinConversionConfig, type MicrosoftAdsIntegration, type PostHog, type PostHogConfig, type PosthogErrorTrackingOptions, type UETConsent, type UETEventParams, type UETItem, type UETPageType, type UETPid, capturePosthogException, configureUET, getLoadedPosthog, getPosthog, googleAnalytics, linkedInAds, metaAds, microsoftAds, openaiAds, posthogAnalytics, posthogFlagsReady, redditAds, sendFBEvent, sendGAEvent, sendLinkedinEvent, sendOpenAIEvent, sendPosthogEvent, sendRedditEvent, sendUETEvent, sendUETIdSync, setFBUser, setGAUser, setLinkedinUser, setOpenAIUser, setPosthogUser, setRedditUser, setUETConsent, setUETUser, syncUETVisitor, uetCustomerIdOf };
@@ -1,9 +1,9 @@
1
1
  import { CONVERSION_EVENTS } from "./integration.mjs";
2
2
  import { configureUET, microsoftAds, sendUETEvent, sendUETIdSync, setUETConsent, setUETUser, syncUETVisitor, uetCustomerIdOf } from "./microsoft-uet.mjs";
3
- import { getLoadedPosthog, getPosthog, posthogAnalytics, posthogFlagsReady, sendPosthogEvent, setPosthogUser } from "./posthog.mjs";
3
+ import { capturePosthogException, getLoadedPosthog, getPosthog, posthogAnalytics, posthogFlagsReady, sendPosthogEvent, setPosthogUser } from "./posthog.mjs";
4
4
  import { googleAnalytics, sendGAEvent, setGAUser } from "./google-analytics.mjs";
5
5
  import { metaAds, sendFBEvent, setFBUser } from "./meta-pixel.mjs";
6
6
  import { linkedInAds, sendLinkedinEvent, setLinkedinUser } from "./linkedin-insight-tag.mjs";
7
7
  import { openaiAds, sendOpenAIEvent, setOpenAIUser } from "./openai-pixel.mjs";
8
8
  import { redditAds, sendRedditEvent, setRedditUser } from "./reddit-pixel.mjs";
9
- export { CONVERSION_EVENTS, configureUET, getLoadedPosthog, getPosthog, googleAnalytics, linkedInAds, metaAds, microsoftAds, openaiAds, posthogAnalytics, posthogFlagsReady, redditAds, sendFBEvent, sendGAEvent, sendLinkedinEvent, sendOpenAIEvent, sendPosthogEvent, sendRedditEvent, sendUETEvent, sendUETIdSync, setFBUser, setGAUser, setLinkedinUser, setOpenAIUser, setPosthogUser, setRedditUser, setUETConsent, setUETUser, syncUETVisitor, uetCustomerIdOf };
9
+ export { CONVERSION_EVENTS, capturePosthogException, configureUET, getLoadedPosthog, getPosthog, googleAnalytics, linkedInAds, metaAds, microsoftAds, openaiAds, posthogAnalytics, posthogFlagsReady, redditAds, sendFBEvent, sendGAEvent, sendLinkedinEvent, sendOpenAIEvent, sendPosthogEvent, sendRedditEvent, sendUETEvent, sendUETIdSync, setFBUser, setGAUser, setLinkedinUser, setOpenAIUser, setPosthogUser, setRedditUser, setUETConsent, setUETUser, syncUETVisitor, uetCustomerIdOf };
@@ -97,6 +97,60 @@ function setPosthogUser({ user_id, user_data }) {
97
97
  posthog.identify(user_id, { email: require_utils_field.getFirst(user_data?.email) });
98
98
  }
99
99
  /**
100
+ * Sends an error to PostHog's error tracking (`captureException`), as `sendPosthogEvent` does an
101
+ * event: queued on the snippet's stub until the library loads, so it can be called from anywhere
102
+ * at any time — an http client's error hook, a `catch` that recovers but should still be known.
103
+ * Returns the `$exception` event, `undefined` while only the stub is there (or without PostHog).
104
+ *
105
+ * Never throws: reporting an error must not become a second one where it is called. The
106
+ * `errorTracking` filter of `posthogAnalytics` applies, as to every exception.
107
+ */
108
+ function capturePosthogException(error, properties) {
109
+ try {
110
+ return getPosthog()?.captureException(error, properties);
111
+ } catch (e) {
112
+ console.error("capturePosthogException: the error was not reported", e);
113
+ return;
114
+ }
115
+ }
116
+ function serializePatterns(patterns = []) {
117
+ return patterns.map((p) => typeof p === "string" ? p : {
118
+ source: p.source,
119
+ flags: p.flags.replace(/[gy]/g, "")
120
+ });
121
+ }
122
+ /**
123
+ * The snippet's `before_send`, as source: `config` goes to `posthog.init` as JSON, which drops
124
+ * functions, so the filter is written into the inline script instead — in place from the first
125
+ * event, with no window before the app's bundle could install it. ES5, as the rest of the snippet.
126
+ * Called with the rules (`off`, `errors`, `urls`); returns the `before_send` function.
127
+ */
128
+ const EXCEPTION_FILTER = `function(r){
129
+ 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}
130
+ 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}
131
+ var errors=compile(r.errors),urls=compile(r.urls);
132
+ return function(e){
133
+ if(!e||e.event!=="$exception")return e;
134
+ if(r.off)return null;
135
+ var l=(e.properties&&e.properties.$exception_list)||[];
136
+ 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}
137
+ var f=l[0]&&l[0].stacktrace&&l[0].stacktrace.frames,u=f&&f.length?f[f.length-1].filename:"";
138
+ return any(urls,u)?null:e;
139
+ };
140
+ }`;
141
+ /**
142
+ * The origin to preconnect to, or none for a relative URL (a reverse proxy on the site's own
143
+ * origin). `new URL` in a try rather than `URL.canParse`, which Safari before 17 and Chrome before
144
+ * 120 lack: this runs while the app sets up its analytics, where a throw takes the page down.
145
+ */
146
+ function originOf(url) {
147
+ try {
148
+ return [new URL(url).origin];
149
+ } catch {
150
+ return [];
151
+ }
152
+ }
153
+ /**
100
154
  * PostHog: every event, for behavior analysis. Loaded with PostHog's HTML snippet, which defines
101
155
  * a stub `window.posthog` and fetches the library (`array.js`) asynchronously from PostHog's
102
156
  * assets host, so it stays out of the app's bundle; calls made before it loads are queued.
@@ -107,22 +161,39 @@ function setPosthogUser({ user_id, user_data }) {
107
161
  */
108
162
  function posthogAnalytics(options) {
109
163
  const assets = options.config.api_host.replace(".i.posthog.com", "-assets.i.posthog.com");
110
- const config = JSON.stringify(options.config).replace(/</g, "\\u003c");
164
+ const json = (value) => JSON.stringify(value).replace(/</g, "\\u003c");
165
+ const token = JSON.stringify(options.token);
166
+ const { errorTracking } = options;
167
+ let init = `posthog.init(${token}, ${json(options.config)});`;
168
+ if (errorTracking !== void 0) {
169
+ const tracking = typeof errorTracking === "object" ? errorTracking : {};
170
+ const config = {
171
+ ...options.config,
172
+ capture_exceptions: options.config.capture_exceptions ?? (errorTracking && (tracking.autocapture ?? true))
173
+ };
174
+ const rules = {
175
+ off: !errorTracking,
176
+ errors: serializePatterns(tracking.ignoreErrors),
177
+ urls: serializePatterns(tracking.denyUrls)
178
+ };
179
+ init = `!function(){var c=${json(config)};c.before_send=(${EXCEPTION_FILTER})(${json(rules)});posthog.init(${token}, c)}();`;
180
+ }
111
181
  return {
112
182
  type: "analytics",
113
183
  track: sendPosthogEvent,
114
184
  setUser: setPosthogUser,
115
- preconnect: URL.canParse(assets) ? [new URL(assets).origin] : [],
185
+ preconnect: originOf(assets),
116
186
  script: {
117
187
  id: "posthog-snippet",
118
188
  strategy: "beforeInteractive",
119
189
  inline: `
120
- !function(t,e){var o,n,p,r;e.__SV||(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=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",(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||[]);
121
- posthog.init(${JSON.stringify(options.token)}, ${config});
190
+ !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||[]);
191
+ ${init}
122
192
  `
123
193
  }
124
194
  };
125
195
  }
196
+ exports.capturePosthogException = capturePosthogException;
126
197
  exports.getLoadedPosthog = getLoadedPosthog;
127
198
  exports.getPosthog = getPosthog;
128
199
  exports.posthogAnalytics = posthogAnalytics;
@@ -1 +1 @@
1
- {"version":3,"file":"posthog.cjs","names":["getFirst"],"sources":["../../src/third-parties/posthog.ts"],"sourcesContent":["import type { PostHog, PostHogConfig } 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 * 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}): 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), and a `</script>`\n // inside it would end this inline script early. `\\u003c` parses back to the same value.\n const config = JSON.stringify(options.config).replace(/</g, '\\\\u003c');\n return {\n type: 'analytics',\n track: sendPosthogEvent,\n setUser: setPosthogUser,\n preconnect: URL.canParse(assets) ? [new URL(assets).origin] : [],\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.\n strategy: 'beforeInteractive',\n inline: `\n !function(t,e){var o,n,p,r;e.__SV||(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=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\",(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 posthog.init(${JSON.stringify(options.token)}, ${config});\n `,\n },\n };\n}\n"],"mappings":";;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O,SAAS,QAAQ,kBAAkB,uBAAuB;CAGxF,MAAM,SAAS,KAAK,UAAU,QAAQ,MAAM,CAAC,CAAC,QAAQ,MAAM,SAAS;CACrE,OAAO;EACL,MAAM;EACN,OAAO;EACP,SAAS;EACT,YAAY,IAAI,SAAS,MAAM,IAAI,CAAC,IAAI,IAAI,MAAM,CAAC,CAAC,MAAM,IAAI,CAAC;EAC/D,QAAQ;GACN,IAAI;GAIJ,UAAU;GACV,QAAQ;;uBAES,KAAK,UAAU,QAAQ,KAAK,EAAE,IAAI,OAAO;;EAE5D;CACF;AACF"}
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,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,CAAC;CACD,OAAO;AACT;AAEA,MAAM,UAAU;CAAC;CAAO;CAAO;CAAO;CAAO;CAAO;AAAM;AAE1D,SAAgB,iBACd,MACA,YACA;CAIA,IAAI,OAAO,aAAa,aAAa;CACrC,MAAM,UAAU,WAAW;CAC3B,IAAI,CAAC,SAAS;EACZ,QAAQ,KAAK,kCAAkC;EAC/C,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,QAAQ,QAAQ,MAAM,UAAU;AAClC;;;;;;;;;;;AAYA,SAAgB,eAAe,EAAE,SAAS,aAA6C;CACrF,MAAM,UAAU,WAAW;CAC3B,IAAI,CAAC,SAAS;EACZ,QAAQ,KAAK,kCAAkC;EAC/C;CACF;CACA,IAAI,CAAC,S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kB,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,7 +1,7 @@
1
1
  import { EventName, TrackName, TrackProperties } from "../track/types.cjs";
2
2
  import { UpdateVisitorDTO } from "../schema/index.cjs";
3
3
  import { Integration } from "./integration.cjs";
4
- import { PostHog, PostHog as PostHog$1, PostHogConfig, PostHogConfig as PostHogConfig$1 } from "@posthog/types";
4
+ import { CaptureResult, ExceptionAutoCaptureConfig, PostHog, PostHog as PostHog$1, PostHogConfig, PostHogConfig as PostHogConfig$1, Properties } from "@posthog/types";
5
5
  /**
6
6
  * `window.posthog`, for calls that return nothing (`capture`, `identify`, `onFeatureFlags`, …):
7
7
  * the snippet's stub until the library loads, which queues them and replays them in order once it
@@ -51,6 +51,39 @@ export declare function sendPosthogEvent<T extends EventName>(name: TrackName<T>
51
51
  * this page starts anonymous instead of merging into the one who left.
52
52
  */
53
53
  export declare function setPosthogUser({ user_id, user_data }: Omit<UpdateVisitorDTO, 'tags'>): void;
54
+ /**
55
+ * Sends an error to PostHog's error tracking (`captureException`), as `sendPosthogEvent` does an
56
+ * event: queued on the snippet's stub until the library loads, so it can be called from anywhere
57
+ * at any time — an http client's error hook, a `catch` that recovers but should still be known.
58
+ * Returns the `$exception` event, `undefined` while only the stub is there (or without PostHog).
59
+ *
60
+ * Never throws: reporting an error must not become a second one where it is called. The
61
+ * `errorTracking` filter of `posthogAnalytics` applies, as to every exception.
62
+ */
63
+ export declare function capturePosthogException(error: unknown, properties?: Properties): CaptureResult | undefined;
64
+ /** A substring of what it is matched against, or a regular expression tested on it. */
65
+ export type ErrorPattern = string | RegExp;
66
+ export interface PosthogErrorTrackingOptions {
67
+ /**
68
+ * The library's exception autocapture: window errors and unhandled rejections, on by default.
69
+ * The same as `config.capture_exceptions`, which wins when both are set.
70
+ */
71
+ autocapture?: boolean | ExceptionAutoCaptureConfig;
72
+ /**
73
+ * Exceptions not sent, as Sentry's `ignoreErrors`: matched against `Type: message` and the
74
+ * message alone of each error in the chain (`$exception_list`), e.g. `'UET is not defined'` for an
75
+ * ad blocker stubbing a tag. Errors thrown by browser extensions need no entry: PostHog drops them
76
+ * itself (`error_tracking.captureExtensionExceptions`).
77
+ */
78
+ ignoreErrors?: readonly ErrorPattern[];
79
+ /**
80
+ * Exceptions not sent by where they were thrown, as Sentry's `denyUrls`: matched against the
81
+ * file of the error's innermost frame, e.g. `'/gsi/client'` for Google One Tap's own minified
82
+ * errors, whose messages change with every build. An error of yours that only passed through
83
+ * such a script (a callback it called) is still sent.
84
+ */
85
+ denyUrls?: readonly ErrorPattern[];
86
+ }
54
87
  /**
55
88
  * PostHog: every event, for behavior analysis. Loaded with PostHog's HTML snippet, which defines
56
89
  * a stub `window.posthog` and fetches the library (`array.js`) asynchronously from PostHog's
@@ -65,6 +98,15 @@ export declare function posthogAnalytics(options: {
65
98
  config: Partial<PostHogConfig$1> & {
66
99
  api_host: string;
67
100
  };
101
+ /**
102
+ * PostHog's error tracking. `true` or options turn on exception autocapture and filter what is
103
+ * sent (`ignoreErrors`, `denyUrls`); `false` sends no exception at all, autocaptured or
104
+ * reported (`capturePosthogException`, `PosthogErrorBoundary`, `setupPosthogReactErrorHandler`) — for
105
+ * local development, which would otherwise fill the production project's issues. Left out, the
106
+ * library's own `config` decides, as before. Each exception carries the session id, so its issue
107
+ * links to the session's replay.
108
+ */
109
+ errorTracking?: boolean | PosthogErrorTrackingOptions;
68
110
  }): Integration;
69
111
  export type { PostHog, PostHogConfig };
70
112
  //# sourceMappingURL=posthog.d.cts.map
@@ -1 +1 @@
1
- {"version":3,"file":"posthog.d.cts","names":["PostHog","PostHogConfig"],"sources":["../../src/third-parties/posthog.ts"],"mappings":";;;;;;;;;;;;;;wBAkBgB,cAAcA;;;;;;;wBAWd,oBAAoBA;;;;;;;;;;;;;;;;;;;wBAyBpB,kBAAkB,qBAAmB;wBAcrC,iBAAiB,UAAU,WACzC,MAAM,UAAU,IAChB,aAAa,gBAAgB;;;;;;;;;;;wBA4Bf,iBAAiB,SAAS,aAAa,KAAK;;;;;;;;;;wBAsB5C,iBAAiB;EAC/B;EACA,QAAQ,QAAQC;IAAmB;;IACjC"}
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;;;;;;;;;;;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,7 +1,7 @@
1
1
  import { EventName, TrackName, TrackProperties } from "../track/types.mjs";
2
2
  import { UpdateVisitorDTO } from "../schema/index.mjs";
3
3
  import { Integration } from "./integration.mjs";
4
- import { PostHog, PostHog as PostHog$1, PostHogConfig, PostHogConfig as PostHogConfig$1 } from "@posthog/types";
4
+ import { CaptureResult, ExceptionAutoCaptureConfig, PostHog, PostHog as PostHog$1, PostHogConfig, PostHogConfig as PostHogConfig$1, Properties } from "@posthog/types";
5
5
  /**
6
6
  * `window.posthog`, for calls that return nothing (`capture`, `identify`, `onFeatureFlags`, …):
7
7
  * the snippet's stub until the library loads, which queues them and replays them in order once it
@@ -51,6 +51,39 @@ export declare function sendPosthogEvent<T extends EventName>(name: TrackName<T>
51
51
  * this page starts anonymous instead of merging into the one who left.
52
52
  */
53
53
  export declare function setPosthogUser({ user_id, user_data }: Omit<UpdateVisitorDTO, 'tags'>): void;
54
+ /**
55
+ * Sends an error to PostHog's error tracking (`captureException`), as `sendPosthogEvent` does an
56
+ * event: queued on the snippet's stub until the library loads, so it can be called from anywhere
57
+ * at any time — an http client's error hook, a `catch` that recovers but should still be known.
58
+ * Returns the `$exception` event, `undefined` while only the stub is there (or without PostHog).
59
+ *
60
+ * Never throws: reporting an error must not become a second one where it is called. The
61
+ * `errorTracking` filter of `posthogAnalytics` applies, as to every exception.
62
+ */
63
+ export declare function capturePosthogException(error: unknown, properties?: Properties): CaptureResult | undefined;
64
+ /** A substring of what it is matched against, or a regular expression tested on it. */
65
+ export type ErrorPattern = string | RegExp;
66
+ export interface PosthogErrorTrackingOptions {
67
+ /**
68
+ * The library's exception autocapture: window errors and unhandled rejections, on by default.
69
+ * The same as `config.capture_exceptions`, which wins when both are set.
70
+ */
71
+ autocapture?: boolean | ExceptionAutoCaptureConfig;
72
+ /**
73
+ * Exceptions not sent, as Sentry's `ignoreErrors`: matched against `Type: message` and the
74
+ * message alone of each error in the chain (`$exception_list`), e.g. `'UET is not defined'` for an
75
+ * ad blocker stubbing a tag. Errors thrown by browser extensions need no entry: PostHog drops them
76
+ * itself (`error_tracking.captureExtensionExceptions`).
77
+ */
78
+ ignoreErrors?: readonly ErrorPattern[];
79
+ /**
80
+ * Exceptions not sent by where they were thrown, as Sentry's `denyUrls`: matched against the
81
+ * file of the error's innermost frame, e.g. `'/gsi/client'` for Google One Tap's own minified
82
+ * errors, whose messages change with every build. An error of yours that only passed through
83
+ * such a script (a callback it called) is still sent.
84
+ */
85
+ denyUrls?: readonly ErrorPattern[];
86
+ }
54
87
  /**
55
88
  * PostHog: every event, for behavior analysis. Loaded with PostHog's HTML snippet, which defines
56
89
  * a stub `window.posthog` and fetches the library (`array.js`) asynchronously from PostHog's
@@ -65,6 +98,15 @@ export declare function posthogAnalytics(options: {
65
98
  config: Partial<PostHogConfig$1> & {
66
99
  api_host: string;
67
100
  };
101
+ /**
102
+ * PostHog's error tracking. `true` or options turn on exception autocapture and filter what is
103
+ * sent (`ignoreErrors`, `denyUrls`); `false` sends no exception at all, autocaptured or
104
+ * reported (`capturePosthogException`, `PosthogErrorBoundary`, `setupPosthogReactErrorHandler`) — for
105
+ * local development, which would otherwise fill the production project's issues. Left out, the
106
+ * library's own `config` decides, as before. Each exception carries the session id, so its issue
107
+ * links to the session's replay.
108
+ */
109
+ errorTracking?: boolean | PosthogErrorTrackingOptions;
68
110
  }): Integration;
69
111
  export type { PostHog, PostHogConfig };
70
112
  //# sourceMappingURL=posthog.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"posthog.d.mts","names":["PostHog","PostHogConfig"],"sources":["../../src/third-parties/posthog.ts"],"mappings":";;;;;;;;;;;;;;wBAkBgB,cAAcA;;;;;;;wBAWd,oBAAoBA;;;;;;;;;;;;;;;;;;;wBAyBpB,kBAAkB,qBAAmB;wBAcrC,iBAAiB,UAAU,WACzC,MAAM,UAAU,IAChB,aAAa,gBAAgB;;;;;;;;;;;wBA4Bf,iBAAiB,SAAS,aAAa,KAAK;;;;;;;;;;wBAsB5C,iBAAiB;EAC/B;EACA,QAAQ,QAAQC;IAAmB;;IACjC"}
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"}
@@ -96,6 +96,60 @@ function setPosthogUser({ user_id, user_data }) {
96
96
  posthog.identify(user_id, { email: getFirst(user_data?.email) });
97
97
  }
98
98
  /**
99
+ * Sends an error to PostHog's error tracking (`captureException`), as `sendPosthogEvent` does an
100
+ * event: queued on the snippet's stub until the library loads, so it can be called from anywhere
101
+ * at any time — an http client's error hook, a `catch` that recovers but should still be known.
102
+ * Returns the `$exception` event, `undefined` while only the stub is there (or without PostHog).
103
+ *
104
+ * Never throws: reporting an error must not become a second one where it is called. The
105
+ * `errorTracking` filter of `posthogAnalytics` applies, as to every exception.
106
+ */
107
+ function capturePosthogException(error, properties) {
108
+ try {
109
+ return getPosthog()?.captureException(error, properties);
110
+ } catch (e) {
111
+ console.error("capturePosthogException: the error was not reported", e);
112
+ return;
113
+ }
114
+ }
115
+ function serializePatterns(patterns = []) {
116
+ return patterns.map((p) => typeof p === "string" ? p : {
117
+ source: p.source,
118
+ flags: p.flags.replace(/[gy]/g, "")
119
+ });
120
+ }
121
+ /**
122
+ * The snippet's `before_send`, as source: `config` goes to `posthog.init` as JSON, which drops
123
+ * functions, so the filter is written into the inline script instead — in place from the first
124
+ * event, with no window before the app's bundle could install it. ES5, as the rest of the snippet.
125
+ * Called with the rules (`off`, `errors`, `urls`); returns the `before_send` function.
126
+ */
127
+ const EXCEPTION_FILTER = `function(r){
128
+ 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}
129
+ 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}
130
+ var errors=compile(r.errors),urls=compile(r.urls);
131
+ return function(e){
132
+ if(!e||e.event!=="$exception")return e;
133
+ if(r.off)return null;
134
+ var l=(e.properties&&e.properties.$exception_list)||[];
135
+ 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}
136
+ var f=l[0]&&l[0].stacktrace&&l[0].stacktrace.frames,u=f&&f.length?f[f.length-1].filename:"";
137
+ return any(urls,u)?null:e;
138
+ };
139
+ }`;
140
+ /**
141
+ * The origin to preconnect to, or none for a relative URL (a reverse proxy on the site's own
142
+ * origin). `new URL` in a try rather than `URL.canParse`, which Safari before 17 and Chrome before
143
+ * 120 lack: this runs while the app sets up its analytics, where a throw takes the page down.
144
+ */
145
+ function originOf(url) {
146
+ try {
147
+ return [new URL(url).origin];
148
+ } catch {
149
+ return [];
150
+ }
151
+ }
152
+ /**
99
153
  * PostHog: every event, for behavior analysis. Loaded with PostHog's HTML snippet, which defines
100
154
  * a stub `window.posthog` and fetches the library (`array.js`) asynchronously from PostHog's
101
155
  * assets host, so it stays out of the app's bundle; calls made before it loads are queued.
@@ -106,22 +160,38 @@ function setPosthogUser({ user_id, user_data }) {
106
160
  */
107
161
  function posthogAnalytics(options) {
108
162
  const assets = options.config.api_host.replace(".i.posthog.com", "-assets.i.posthog.com");
109
- const config = JSON.stringify(options.config).replace(/</g, "\\u003c");
163
+ const json = (value) => JSON.stringify(value).replace(/</g, "\\u003c");
164
+ const token = JSON.stringify(options.token);
165
+ const { errorTracking } = options;
166
+ let init = `posthog.init(${token}, ${json(options.config)});`;
167
+ if (errorTracking !== void 0) {
168
+ const tracking = typeof errorTracking === "object" ? errorTracking : {};
169
+ const config = {
170
+ ...options.config,
171
+ capture_exceptions: options.config.capture_exceptions ?? (errorTracking && (tracking.autocapture ?? true))
172
+ };
173
+ const rules = {
174
+ off: !errorTracking,
175
+ errors: serializePatterns(tracking.ignoreErrors),
176
+ urls: serializePatterns(tracking.denyUrls)
177
+ };
178
+ init = `!function(){var c=${json(config)};c.before_send=(${EXCEPTION_FILTER})(${json(rules)});posthog.init(${token}, c)}();`;
179
+ }
110
180
  return {
111
181
  type: "analytics",
112
182
  track: sendPosthogEvent,
113
183
  setUser: setPosthogUser,
114
- preconnect: URL.canParse(assets) ? [new URL(assets).origin] : [],
184
+ preconnect: originOf(assets),
115
185
  script: {
116
186
  id: "posthog-snippet",
117
187
  strategy: "beforeInteractive",
118
188
  inline: `
119
- !function(t,e){var o,n,p,r;e.__SV||(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=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",(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||[]);
120
- posthog.init(${JSON.stringify(options.token)}, ${config});
189
+ !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||[]);
190
+ ${init}
121
191
  `
122
192
  }
123
193
  };
124
194
  }
125
- export { getLoadedPosthog, getPosthog, posthogAnalytics, posthogFlagsReady, sendPosthogEvent, setPosthogUser };
195
+ export { capturePosthogException, getLoadedPosthog, getPosthog, posthogAnalytics, posthogFlagsReady, sendPosthogEvent, setPosthogUser };
126
196
 
127
197
  //# sourceMappingURL=posthog.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"posthog.mjs","names":[],"sources":["../../src/third-parties/posthog.ts"],"sourcesContent":["import type { PostHog, PostHogConfig } 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 * 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}): 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), and a `</script>`\n // inside it would end this inline script early. `\\u003c` parses back to the same value.\n const config = JSON.stringify(options.config).replace(/</g, '\\\\u003c');\n return {\n type: 'analytics',\n track: sendPosthogEvent,\n setUser: setPosthogUser,\n preconnect: URL.canParse(assets) ? [new URL(assets).origin] : [],\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.\n strategy: 'beforeInteractive',\n inline: `\n !function(t,e){var o,n,p,r;e.__SV||(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=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\",(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 posthog.init(${JSON.stringify(options.token)}, ${config});\n `,\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;AAkBA,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,CAAC;CACD,OAAO;AACT;AAEA,MAAM,UAAU;CAAC;CAAO;CAAO;CAAO;CAAO;CAAO;AAAM;AAE1D,SAAgB,iBACd,MACA,YACA;CAIA,IAAI,OAAO,aAAa,aAAa;CACrC,MAAM,UAAU,WAAW;CAC3B,IAAI,CAAC,SAAS;EACZ,QAAQ,KAAK,kCAAkC;EAC/C,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,QAAQ,QAAQ,MAAM,UAAU;AAClC;;;;;;;;;;;AAYA,SAAgB,eAAe,EAAE,SAAS,aAA6C;CACrF,MAAM,UAAU,WAAW;CAC3B,IAAI,CAAC,SAAS;EACZ,QAAQ,KAAK,kCAAkC;EAC/C;CACF;CACA,IAAI,CAAC,SAAS;EACZ,QAAQ,MAAM;EACd;CACF;CACA,QAAQ,SAAS,SAAS,EAAE,OAAO,SAAS,WAAW,KAAK,EAAE,CAAC;AACjE;;;;;;;;;;AAWA,SAAgB,iBAAiB,SAGjB;CAGd,MAAM,SAAS,QAAQ,OAAO,SAAS,QAAQ,kBAAkB,uBAAuB;CAGxF,MAAM,SAAS,KAAK,UAAU,QAAQ,MAAM,CAAC,CAAC,QAAQ,MAAM,SAAS;CACrE,OAAO;EACL,MAAM;EACN,OAAO;EACP,SAAS;EACT,YAAY,IAAI,SAAS,MAAM,IAAI,CAAC,IAAI,IAAI,MAAM,CAAC,CAAC,MAAM,IAAI,CAAC;EAC/D,QAAQ;GACN,IAAI;GAIJ,UAAU;GACV,QAAQ;;uBAES,KAAK,UAAU,QAAQ,KAAK,EAAE,IAAI,OAAO;;EAE5D;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 } 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,IAA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