@shware/analytics 16.1.0 → 16.2.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.
Files changed (50) hide show
  1. package/README.md +14 -4
  2. package/dist/react/index.cjs +11 -2
  3. package/dist/react/index.cjs.map +1 -1
  4. package/dist/react/index.d.cts +3 -2
  5. package/dist/react/index.d.cts.map +1 -1
  6. package/dist/react/index.d.mts +3 -2
  7. package/dist/react/index.d.mts.map +1 -1
  8. package/dist/react/index.mjs +3 -2
  9. package/dist/react/index.mjs.map +1 -1
  10. package/dist/react/posthog-error-boundary.cjs +119 -0
  11. package/dist/react/posthog-error-boundary.cjs.map +1 -0
  12. package/dist/react/posthog-error-boundary.d.cts +60 -0
  13. package/dist/react/posthog-error-boundary.d.cts.map +1 -0
  14. package/dist/react/posthog-error-boundary.d.mts +60 -0
  15. package/dist/react/posthog-error-boundary.d.mts.map +1 -0
  16. package/dist/react/posthog-error-boundary.mjs +117 -0
  17. package/dist/react/posthog-error-boundary.mjs.map +1 -0
  18. package/dist/react/posthog.cjs +97 -0
  19. package/dist/react/posthog.cjs.map +1 -0
  20. package/dist/react/posthog.d.cts +41 -0
  21. package/dist/react/posthog.d.cts.map +1 -0
  22. package/dist/react/posthog.d.mts +41 -0
  23. package/dist/react/posthog.d.mts.map +1 -0
  24. package/dist/react/posthog.mjs +90 -0
  25. package/dist/react/posthog.mjs.map +1 -0
  26. package/dist/third-parties/google-analytics.cjs +1 -1
  27. package/dist/third-parties/google-analytics.cjs.map +1 -1
  28. package/dist/third-parties/google-analytics.mjs +1 -1
  29. package/dist/third-parties/google-analytics.mjs.map +1 -1
  30. package/dist/third-parties/integration.cjs.map +1 -1
  31. package/dist/third-parties/integration.d.cts +5 -1
  32. package/dist/third-parties/integration.d.cts.map +1 -1
  33. package/dist/third-parties/integration.d.mts +5 -1
  34. package/dist/third-parties/integration.d.mts.map +1 -1
  35. package/dist/third-parties/integration.mjs.map +1 -1
  36. package/dist/third-parties/posthog.cjs +4 -4
  37. package/dist/third-parties/posthog.cjs.map +1 -1
  38. package/dist/third-parties/posthog.d.cts +3 -3
  39. package/dist/third-parties/posthog.d.mts +3 -3
  40. package/dist/third-parties/posthog.mjs +4 -4
  41. package/dist/third-parties/posthog.mjs.map +1 -1
  42. package/package.json +1 -1
  43. package/dist/react/use-feature-flag.cjs +0 -23
  44. package/dist/react/use-feature-flag.cjs.map +0 -1
  45. package/dist/react/use-feature-flag.d.cts +0 -10
  46. package/dist/react/use-feature-flag.d.cts.map +0 -1
  47. package/dist/react/use-feature-flag.d.mts +0 -10
  48. package/dist/react/use-feature-flag.d.mts.map +0 -1
  49. package/dist/react/use-feature-flag.mjs +0 -22
  50. package/dist/react/use-feature-flag.mjs.map +0 -1
@@ -0,0 +1,97 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ const require_third_parties_posthog = require("../third-parties/posthog.cjs");
3
+ let react = require("react");
4
+ // src/react/posthog.ts
5
+ const noop = () => {};
6
+ const Bootstrap = (0, react.createContext)(void 0);
7
+ /**
8
+ * The counterpart of `posthog-js/react`'s `PostHogProvider`, for the snippet-loaded library. It
9
+ * does not initialize PostHog — `posthogAnalytics` does — only carries what the hooks need from
10
+ * the server: the request's server-evaluated flags, the same object as the snippet's
11
+ * `config.bootstrap`, for the flag hooks to render with on the server, through hydration and until
12
+ * the library has loaded its flags — an experiment's variant renders at once, with no flicker and
13
+ * no hydration mismatch. Wrap the app in it, e.g. in the root route.
14
+ */
15
+ function PosthogProvider({ bootstrap, children }) {
16
+ return (0, react.createElement)(Bootstrap.Provider, { value: bootstrap }, children);
17
+ }
18
+ /** Subscribes to flag (re)loads; on the stub the subscription is queued and has no unsubscribe. */
19
+ function subscribe(onChange) {
20
+ return require_third_parties_posthog.getPosthog()?.onFeatureFlags(onChange) ?? noop;
21
+ }
22
+ /**
23
+ * What `read` returns once the library has loaded its flags, and `bootstrapped` until then and on
24
+ * the server, re-read when flags reload. The value is kept while its JSON is unchanged, as
25
+ * `useSyncExternalStore` needs: PostHog builds a new result or payload object on every read.
26
+ */
27
+ function useFlags(read, bootstrapped) {
28
+ const cache = (0, react.useRef)(void 0);
29
+ const stable = (value) => {
30
+ const json = JSON.stringify(value);
31
+ if (!cache.current || cache.current.json !== json) cache.current = {
32
+ json,
33
+ value
34
+ };
35
+ return cache.current.value;
36
+ };
37
+ return (0, react.useSyncExternalStore)(subscribe, () => {
38
+ const posthog = require_third_parties_posthog.getLoadedPosthog();
39
+ return stable(posthog?.featureFlags.hasLoadedFlags ? read(posthog) : bootstrapped);
40
+ }, () => stable(bootstrapped));
41
+ }
42
+ /** A flag's value: `true`/`false`, a multivariate flag's variant, or `undefined` until loaded. */
43
+ function useFeatureFlagVariantKey(flag) {
44
+ const bootstrapped = (0, react.use)(Bootstrap)?.featureFlags?.[flag];
45
+ return useFlags((posthog) => posthog.getFeatureFlag(flag), bootstrapped);
46
+ }
47
+ function useFeatureFlagEnabled(flag, defaultValue) {
48
+ const value = (0, react.use)(Bootstrap)?.featureFlags?.[flag];
49
+ return useFlags((posthog) => posthog.isFeatureEnabled(flag), value === void 0 ? void 0 : !!value) ?? defaultValue;
50
+ }
51
+ /** A flag's payload, read without recording an exposure. */
52
+ function useFeatureFlagPayload(flag) {
53
+ const bootstrapped = (0, react.use)(Bootstrap)?.featureFlagPayloads?.[flag];
54
+ return useFlags((posthog) => posthog.getFeatureFlagResult(flag, { send_event: false })?.payload, bootstrapped);
55
+ }
56
+ /** A flag's value, variant and payload together; `undefined` while it is unknown. */
57
+ function useFeatureFlagResult(flag) {
58
+ const bootstrap = (0, react.use)(Bootstrap);
59
+ const value = bootstrap?.featureFlags?.[flag];
60
+ return useFlags((posthog) => posthog.getFeatureFlagResult(flag), value === void 0 ? void 0 : {
61
+ key: flag,
62
+ enabled: typeof value === "string" ? true : value,
63
+ variant: typeof value === "string" ? value : void 0,
64
+ payload: bootstrap?.featureFlagPayloads?.[flag]
65
+ });
66
+ }
67
+ /**
68
+ * The keys of the flags: only those that are on while bootstrapped, every flag the library has
69
+ * once loaded — as `posthog-js/react`'s does.
70
+ */
71
+ function useActiveFeatureFlags() {
72
+ const flags = (0, react.use)(Bootstrap)?.featureFlags ?? {};
73
+ return useFlags((posthog) => posthog.featureFlags.getFlags(), Object.keys(flags).filter((key) => flags[key]));
74
+ }
75
+ /**
76
+ * `window.posthog`, as `posthog-js/react`'s `usePostHog`: the snippet's stub until the library
77
+ * loads — which queues the calls returning nothing (`capture`, `identify`, …) — then the library,
78
+ * re-rendering when it replaces the stub; `undefined` on the server. Use the value of the latest
79
+ * render rather than one kept from before (e.g. in a ref): calls on a stub kept past the load are
80
+ * lost. A method that returns a value returns `undefined` on the stub; read flags with the hooks.
81
+ *
82
+ * The re-render comes from the flags loading, as the library answers the stub's queued
83
+ * `onFeatureFlags`: with feature flags disabled it stays on the stub until something else
84
+ * re-renders.
85
+ */
86
+ function usePostHog() {
87
+ return (0, react.useSyncExternalStore)(subscribe, require_third_parties_posthog.getPosthog, () => void 0);
88
+ }
89
+ exports.PosthogProvider = PosthogProvider;
90
+ exports.useActiveFeatureFlags = useActiveFeatureFlags;
91
+ exports.useFeatureFlagEnabled = useFeatureFlagEnabled;
92
+ exports.useFeatureFlagPayload = useFeatureFlagPayload;
93
+ exports.useFeatureFlagResult = useFeatureFlagResult;
94
+ exports.useFeatureFlagVariantKey = useFeatureFlagVariantKey;
95
+ exports.usePostHog = usePostHog;
96
+
97
+ //# sourceMappingURL=posthog.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"posthog.cjs","names":["createContext","createElement","getPosthog","useRef","useSyncExternalStore","getLoadedPosthog","use"],"sources":["../../src/react/posthog.ts"],"sourcesContent":["import type { BootstrapConfig, FeatureFlagResult, JsonType, PostHog } from 'posthog-js';\nimport {\n type ReactNode,\n createContext,\n createElement,\n use,\n useRef,\n useSyncExternalStore,\n} from 'react';\nimport { getLoadedPosthog, getPosthog } from '../third-parties/posthog';\n\nconst noop = () => {};\n\nconst Bootstrap = createContext<BootstrapConfig | undefined>(undefined);\n\n/**\n * The counterpart of `posthog-js/react`'s `PostHogProvider`, for the snippet-loaded library. It\n * does not initialize PostHog — `posthogAnalytics` does — only carries what the hooks need from\n * the server: the request's server-evaluated flags, the same object as the snippet's\n * `config.bootstrap`, for the flag hooks to render with on the server, through hydration and until\n * the library has loaded its flags — an experiment's variant renders at once, with no flicker and\n * no hydration mismatch. Wrap the app in it, e.g. in the root route.\n */\nexport function PosthogProvider({\n bootstrap,\n children,\n}: {\n bootstrap: BootstrapConfig | undefined;\n children: ReactNode;\n}) {\n return createElement(Bootstrap.Provider, { value: bootstrap }, children);\n}\n\n/** Subscribes to flag (re)loads; on the stub the subscription is queued and has no unsubscribe. */\nfunction subscribe(onChange: () => void): () => void {\n const unsubscribe: (() => void) | undefined = getPosthog()?.onFeatureFlags(onChange);\n return unsubscribe ?? noop;\n}\n\n/**\n * What `read` returns once the library has loaded its flags, and `bootstrapped` until then and on\n * the server, re-read when flags reload. The value is kept while its JSON is unchanged, as\n * `useSyncExternalStore` needs: PostHog builds a new result or payload object on every read.\n */\nfunction useFlags<T>(read: (posthog: PostHog) => T, bootstrapped: T): T {\n const cache = useRef<{ json: string | undefined; value: T }>(undefined);\n const stable = (value: T) => {\n // Typed wider: `JSON.stringify(undefined)` is `undefined`, whatever its type says.\n const json: string | undefined = JSON.stringify(value);\n if (!cache.current || cache.current.json !== json) cache.current = { json, value };\n return cache.current.value;\n };\n return useSyncExternalStore(\n subscribe,\n () => {\n const posthog = getLoadedPosthog();\n // As `posthog-js/react`: the bootstrap until the flags request has answered, not only until\n // the library has loaded, so no flag is read (and no exposure recorded) before then.\n return stable(posthog?.featureFlags.hasLoadedFlags ? read(posthog) : bootstrapped);\n },\n () => stable(bootstrapped)\n );\n}\n\n/*\n * The hooks of `posthog-js/react`, with its names and signatures, for the snippet-loaded library.\n *\n * Under a `<PosthogProvider>` each is the server's value until the library has loaded its\n * flags, on the server too. Without one it is `undefined` on the server and through hydration, so\n * the default renders first and the variant once flags arrive; to wait for them instead, call\n * `use(browser())` and `use(posthogFlagsReady())` above it, under a `<Suspense>`.\n *\n * Reading a flag records the exposure (`$feature_flag_called`) once the flags have loaded, as\n * PostHog's do — except the payload's — not while only a bootstrapped value is shown.\n */\n\n/** A flag's value: `true`/`false`, a multivariate flag's variant, or `undefined` until loaded. */\nexport function useFeatureFlagVariantKey(flag: string): string | boolean | undefined {\n const bootstrapped = use(Bootstrap)?.featureFlags?.[flag];\n return useFlags((posthog) => posthog.getFeatureFlag(flag), bootstrapped);\n}\n\n/** Whether a flag is on (a variant counts as on); `defaultValue` while it is unknown. */\nexport function useFeatureFlagEnabled(flag: string): boolean | undefined;\nexport function useFeatureFlagEnabled(flag: string, defaultValue: boolean): boolean;\nexport function useFeatureFlagEnabled(flag: string, defaultValue?: boolean) {\n const value = use(Bootstrap)?.featureFlags?.[flag];\n const bootstrapped = value === undefined ? undefined : !!value;\n return useFlags((posthog) => posthog.isFeatureEnabled(flag), bootstrapped) ?? defaultValue;\n}\n\n/** A flag's payload, read without recording an exposure. */\nexport function useFeatureFlagPayload(flag: string): JsonType {\n const bootstrapped = use(Bootstrap)?.featureFlagPayloads?.[flag];\n return useFlags(\n (posthog) => posthog.getFeatureFlagResult(flag, { send_event: false })?.payload,\n bootstrapped\n );\n}\n\n/** A flag's value, variant and payload together; `undefined` while it is unknown. */\nexport function useFeatureFlagResult(flag: string): FeatureFlagResult | undefined {\n const bootstrap = use(Bootstrap);\n const value = bootstrap?.featureFlags?.[flag];\n const bootstrapped: FeatureFlagResult | undefined =\n value === undefined\n ? undefined\n : {\n key: flag,\n enabled: typeof value === 'string' ? true : value,\n variant: typeof value === 'string' ? value : undefined,\n payload: bootstrap?.featureFlagPayloads?.[flag],\n };\n return useFlags((posthog) => posthog.getFeatureFlagResult(flag), bootstrapped);\n}\n\n/**\n * The keys of the flags: only those that are on while bootstrapped, every flag the library has\n * once loaded — as `posthog-js/react`'s does.\n */\nexport function useActiveFeatureFlags(): string[] {\n const flags = use(Bootstrap)?.featureFlags ?? {};\n const bootstrapped = Object.keys(flags).filter((key) => flags[key]);\n return useFlags((posthog) => posthog.featureFlags.getFlags(), bootstrapped);\n}\n\n/**\n * `window.posthog`, as `posthog-js/react`'s `usePostHog`: the snippet's stub until the library\n * loads — which queues the calls returning nothing (`capture`, `identify`, …) — then the library,\n * re-rendering when it replaces the stub; `undefined` on the server. Use the value of the latest\n * render rather than one kept from before (e.g. in a ref): calls on a stub kept past the load are\n * lost. A method that returns a value returns `undefined` on the stub; read flags with the hooks.\n *\n * The re-render comes from the flags loading, as the library answers the stub's queued\n * `onFeatureFlags`: with feature flags disabled it stays on the stub until something else\n * re-renders.\n */\nexport function usePostHog(): PostHog | undefined {\n return useSyncExternalStore(subscribe, getPosthog, () => undefined);\n}\n"],"mappings":";;;;AAWA,MAAM,aAAa,CAAC;AAEpB,MAAM,aAAA,GAAYA,MAAAA,cAAAA,CAA2C,KAAA,CAAS;;;;;;;;;AAUtE,SAAgB,gBAAgB,EAC9B,WACA,YAIC;CACD,QAAA,GAAOC,MAAAA,cAAAA,CAAc,UAAU,UAAU,EAAE,OAAO,UAAU,GAAG,QAAQ;AACzE;;AAGA,SAAS,UAAU,UAAkC;CAEnD,OAD8CC,8BAAAA,WAAW,CAAC,EAAE,eAAe,QAAQ,KAC7D;AACxB;;;;;;AAOA,SAAS,SAAY,MAA+B,cAAoB;CACtE,MAAM,SAAA,GAAQC,MAAAA,OAAAA,CAA+C,KAAA,CAAS;CACtE,MAAM,UAAU,UAAa;EAE3B,MAAM,OAA2B,KAAK,UAAU,KAAK;EACrD,IAAI,CAAC,MAAM,WAAW,MAAM,QAAQ,SAAS,MAAM,MAAM,UAAU;GAAE;GAAM;EAAM;EACjF,OAAO,MAAM,QAAQ;CACvB;CACA,QAAA,GAAOC,MAAAA,qBAAAA,CACL,iBACM;EACJ,MAAM,UAAUC,8BAAAA,iBAAiB;EAGjC,OAAO,OAAO,SAAS,aAAa,iBAAiB,KAAK,OAAO,IAAI,YAAY;CACnF,SACM,OAAO,YAAY,CAC3B;AACF;;AAeA,SAAgB,yBAAyB,MAA4C;CACnF,MAAM,gBAAA,GAAeC,MAAAA,IAAAA,CAAI,SAAS,CAAC,EAAE,eAAe;CACpD,OAAO,UAAU,YAAY,QAAQ,eAAe,IAAI,GAAG,YAAY;AACzE;AAKA,SAAgB,sBAAsB,MAAc,cAAwB;CAC1E,MAAM,SAAA,GAAQA,MAAAA,IAAAA,CAAI,SAAS,CAAC,EAAE,eAAe;CAE7C,OAAO,UAAU,YAAY,QAAQ,iBAAiB,IAAI,GADrC,UAAU,KAAA,IAAY,KAAA,IAAY,CAAC,CAAC,KACgB,KAAK;AAChF;;AAGA,SAAgB,sBAAsB,MAAwB;CAC5D,MAAM,gBAAA,GAAeA,MAAAA,IAAAA,CAAI,SAAS,CAAC,EAAE,sBAAsB;CAC3D,OAAO,UACJ,YAAY,QAAQ,qBAAqB,MAAM,EAAE,YAAY,MAAM,CAAC,CAAC,EAAE,SACxE,YACF;AACF;;AAGA,SAAgB,qBAAqB,MAA6C;CAChF,MAAM,aAAA,GAAYA,MAAAA,IAAAA,CAAI,SAAS;CAC/B,MAAM,QAAQ,WAAW,eAAe;CAUxC,OAAO,UAAU,YAAY,QAAQ,qBAAqB,IAAI,GAR5D,UAAU,KAAA,IACN,KAAA,IACA;EACE,KAAK;EACL,SAAS,OAAO,UAAU,WAAW,OAAO;EAC5C,SAAS,OAAO,UAAU,WAAW,QAAQ,KAAA;EAC7C,SAAS,WAAW,sBAAsB;CAC5C,CACuE;AAC/E;;;;;AAMA,SAAgB,wBAAkC;CAChD,MAAM,SAAA,GAAQA,MAAAA,IAAAA,CAAI,SAAS,CAAC,EAAE,gBAAgB,CAAC;CAE/C,OAAO,UAAU,YAAY,QAAQ,aAAa,SAAS,GADtC,OAAO,KAAK,KAAK,CAAC,CAAC,QAAQ,QAAQ,MAAM,IACW,CAAC;AAC5E;;;;;;;;;;;;AAaA,SAAgB,aAAkC;CAChD,QAAA,GAAOF,MAAAA,qBAAAA,CAAqB,WAAWF,8BAAAA,kBAAkB,KAAA,CAAS;AACpE"}
@@ -0,0 +1,41 @@
1
+ import { ReactNode } from "react";
2
+ import { BootstrapConfig, FeatureFlagResult, JsonType, PostHog } from "posthog-js";
3
+ /**
4
+ * The counterpart of `posthog-js/react`'s `PostHogProvider`, for the snippet-loaded library. It
5
+ * does not initialize PostHog — `posthogAnalytics` does — only carries what the hooks need from
6
+ * the server: the request's server-evaluated flags, the same object as the snippet's
7
+ * `config.bootstrap`, for the flag hooks to render with on the server, through hydration and until
8
+ * the library has loaded its flags — an experiment's variant renders at once, with no flicker and
9
+ * no hydration mismatch. Wrap the app in it, e.g. in the root route.
10
+ */
11
+ export declare function PosthogProvider({ bootstrap, children }: {
12
+ bootstrap: BootstrapConfig | undefined;
13
+ children: ReactNode;
14
+ }): import("react").FunctionComponentElement<import("react").ProviderProps<BootstrapConfig | undefined>>;
15
+ /** A flag's value: `true`/`false`, a multivariate flag's variant, or `undefined` until loaded. */
16
+ export declare function useFeatureFlagVariantKey(flag: string): string | boolean | undefined;
17
+ /** Whether a flag is on (a variant counts as on); `defaultValue` while it is unknown. */
18
+ export declare function useFeatureFlagEnabled(flag: string): boolean | undefined;
19
+ export declare function useFeatureFlagEnabled(flag: string, defaultValue: boolean): boolean;
20
+ /** A flag's payload, read without recording an exposure. */
21
+ export declare function useFeatureFlagPayload(flag: string): JsonType;
22
+ /** A flag's value, variant and payload together; `undefined` while it is unknown. */
23
+ export declare function useFeatureFlagResult(flag: string): FeatureFlagResult | undefined;
24
+ /**
25
+ * The keys of the flags: only those that are on while bootstrapped, every flag the library has
26
+ * once loaded — as `posthog-js/react`'s does.
27
+ */
28
+ export declare function useActiveFeatureFlags(): string[];
29
+ /**
30
+ * `window.posthog`, as `posthog-js/react`'s `usePostHog`: the snippet's stub until the library
31
+ * loads — which queues the calls returning nothing (`capture`, `identify`, …) — then the library,
32
+ * re-rendering when it replaces the stub; `undefined` on the server. Use the value of the latest
33
+ * render rather than one kept from before (e.g. in a ref): calls on a stub kept past the load are
34
+ * lost. A method that returns a value returns `undefined` on the stub; read flags with the hooks.
35
+ *
36
+ * The re-render comes from the flags loading, as the library answers the stub's queued
37
+ * `onFeatureFlags`: with feature flags disabled it stays on the stub until something else
38
+ * re-renders.
39
+ */
40
+ export declare function usePostHog(): PostHog | undefined;
41
+ //# sourceMappingURL=posthog.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"posthog.d.cts","names":[],"sources":["../../src/react/posthog.ts"],"mappings":";;;;;;;;;;wBAuBgB,kBACd,WACA;EAEA,WAAW;EACX,UAAU;oBACX,yCAAA,cAAA;;wBAgDe,yBAAyB;;wBAMzB,sBAAsB;wBACtB,sBAAsB,cAAc;;wBAQpC,sBAAsB,eAAe;;wBASrC,qBAAqB,eAAe;;;;;wBAmBpC;;;;;;;;;;;;wBAiBA,cAAc"}
@@ -0,0 +1,41 @@
1
+ import { ReactNode } from "react";
2
+ import { BootstrapConfig, FeatureFlagResult, JsonType, PostHog } from "posthog-js";
3
+ /**
4
+ * The counterpart of `posthog-js/react`'s `PostHogProvider`, for the snippet-loaded library. It
5
+ * does not initialize PostHog — `posthogAnalytics` does — only carries what the hooks need from
6
+ * the server: the request's server-evaluated flags, the same object as the snippet's
7
+ * `config.bootstrap`, for the flag hooks to render with on the server, through hydration and until
8
+ * the library has loaded its flags — an experiment's variant renders at once, with no flicker and
9
+ * no hydration mismatch. Wrap the app in it, e.g. in the root route.
10
+ */
11
+ export declare function PosthogProvider({ bootstrap, children }: {
12
+ bootstrap: BootstrapConfig | undefined;
13
+ children: ReactNode;
14
+ }): import("react").FunctionComponentElement<import("react").ProviderProps<BootstrapConfig | undefined>>;
15
+ /** A flag's value: `true`/`false`, a multivariate flag's variant, or `undefined` until loaded. */
16
+ export declare function useFeatureFlagVariantKey(flag: string): string | boolean | undefined;
17
+ /** Whether a flag is on (a variant counts as on); `defaultValue` while it is unknown. */
18
+ export declare function useFeatureFlagEnabled(flag: string): boolean | undefined;
19
+ export declare function useFeatureFlagEnabled(flag: string, defaultValue: boolean): boolean;
20
+ /** A flag's payload, read without recording an exposure. */
21
+ export declare function useFeatureFlagPayload(flag: string): JsonType;
22
+ /** A flag's value, variant and payload together; `undefined` while it is unknown. */
23
+ export declare function useFeatureFlagResult(flag: string): FeatureFlagResult | undefined;
24
+ /**
25
+ * The keys of the flags: only those that are on while bootstrapped, every flag the library has
26
+ * once loaded — as `posthog-js/react`'s does.
27
+ */
28
+ export declare function useActiveFeatureFlags(): string[];
29
+ /**
30
+ * `window.posthog`, as `posthog-js/react`'s `usePostHog`: the snippet's stub until the library
31
+ * loads — which queues the calls returning nothing (`capture`, `identify`, …) — then the library,
32
+ * re-rendering when it replaces the stub; `undefined` on the server. Use the value of the latest
33
+ * render rather than one kept from before (e.g. in a ref): calls on a stub kept past the load are
34
+ * lost. A method that returns a value returns `undefined` on the stub; read flags with the hooks.
35
+ *
36
+ * The re-render comes from the flags loading, as the library answers the stub's queued
37
+ * `onFeatureFlags`: with feature flags disabled it stays on the stub until something else
38
+ * re-renders.
39
+ */
40
+ export declare function usePostHog(): PostHog | undefined;
41
+ //# sourceMappingURL=posthog.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"posthog.d.mts","names":[],"sources":["../../src/react/posthog.ts"],"mappings":";;;;;;;;;;wBAuBgB,kBACd,WACA;EAEA,WAAW;EACX,UAAU;oBACX,yCAAA,cAAA;;wBAgDe,yBAAyB;;wBAMzB,sBAAsB;wBACtB,sBAAsB,cAAc;;wBAQpC,sBAAsB,eAAe;;wBASrC,qBAAqB,eAAe;;;;;wBAmBpC;;;;;;;;;;;;wBAiBA,cAAc"}
@@ -0,0 +1,90 @@
1
+ import { getLoadedPosthog, getPosthog } from "../third-parties/posthog.mjs";
2
+ import { createContext, createElement, use, useRef, useSyncExternalStore } from "react";
3
+ // src/react/posthog.ts
4
+ const noop = () => {};
5
+ const Bootstrap = createContext(void 0);
6
+ /**
7
+ * The counterpart of `posthog-js/react`'s `PostHogProvider`, for the snippet-loaded library. It
8
+ * does not initialize PostHog — `posthogAnalytics` does — only carries what the hooks need from
9
+ * the server: the request's server-evaluated flags, the same object as the snippet's
10
+ * `config.bootstrap`, for the flag hooks to render with on the server, through hydration and until
11
+ * the library has loaded its flags — an experiment's variant renders at once, with no flicker and
12
+ * no hydration mismatch. Wrap the app in it, e.g. in the root route.
13
+ */
14
+ function PosthogProvider({ bootstrap, children }) {
15
+ return createElement(Bootstrap.Provider, { value: bootstrap }, children);
16
+ }
17
+ /** Subscribes to flag (re)loads; on the stub the subscription is queued and has no unsubscribe. */
18
+ function subscribe(onChange) {
19
+ return getPosthog()?.onFeatureFlags(onChange) ?? noop;
20
+ }
21
+ /**
22
+ * What `read` returns once the library has loaded its flags, and `bootstrapped` until then and on
23
+ * the server, re-read when flags reload. The value is kept while its JSON is unchanged, as
24
+ * `useSyncExternalStore` needs: PostHog builds a new result or payload object on every read.
25
+ */
26
+ function useFlags(read, bootstrapped) {
27
+ const cache = useRef(void 0);
28
+ const stable = (value) => {
29
+ const json = JSON.stringify(value);
30
+ if (!cache.current || cache.current.json !== json) cache.current = {
31
+ json,
32
+ value
33
+ };
34
+ return cache.current.value;
35
+ };
36
+ return useSyncExternalStore(subscribe, () => {
37
+ const posthog = getLoadedPosthog();
38
+ return stable(posthog?.featureFlags.hasLoadedFlags ? read(posthog) : bootstrapped);
39
+ }, () => stable(bootstrapped));
40
+ }
41
+ /** A flag's value: `true`/`false`, a multivariate flag's variant, or `undefined` until loaded. */
42
+ function useFeatureFlagVariantKey(flag) {
43
+ const bootstrapped = use(Bootstrap)?.featureFlags?.[flag];
44
+ return useFlags((posthog) => posthog.getFeatureFlag(flag), bootstrapped);
45
+ }
46
+ function useFeatureFlagEnabled(flag, defaultValue) {
47
+ const value = use(Bootstrap)?.featureFlags?.[flag];
48
+ return useFlags((posthog) => posthog.isFeatureEnabled(flag), value === void 0 ? void 0 : !!value) ?? defaultValue;
49
+ }
50
+ /** A flag's payload, read without recording an exposure. */
51
+ function useFeatureFlagPayload(flag) {
52
+ const bootstrapped = use(Bootstrap)?.featureFlagPayloads?.[flag];
53
+ return useFlags((posthog) => posthog.getFeatureFlagResult(flag, { send_event: false })?.payload, bootstrapped);
54
+ }
55
+ /** A flag's value, variant and payload together; `undefined` while it is unknown. */
56
+ function useFeatureFlagResult(flag) {
57
+ const bootstrap = use(Bootstrap);
58
+ const value = bootstrap?.featureFlags?.[flag];
59
+ return useFlags((posthog) => posthog.getFeatureFlagResult(flag), value === void 0 ? void 0 : {
60
+ key: flag,
61
+ enabled: typeof value === "string" ? true : value,
62
+ variant: typeof value === "string" ? value : void 0,
63
+ payload: bootstrap?.featureFlagPayloads?.[flag]
64
+ });
65
+ }
66
+ /**
67
+ * The keys of the flags: only those that are on while bootstrapped, every flag the library has
68
+ * once loaded — as `posthog-js/react`'s does.
69
+ */
70
+ function useActiveFeatureFlags() {
71
+ const flags = use(Bootstrap)?.featureFlags ?? {};
72
+ return useFlags((posthog) => posthog.featureFlags.getFlags(), Object.keys(flags).filter((key) => flags[key]));
73
+ }
74
+ /**
75
+ * `window.posthog`, as `posthog-js/react`'s `usePostHog`: the snippet's stub until the library
76
+ * loads — which queues the calls returning nothing (`capture`, `identify`, …) — then the library,
77
+ * re-rendering when it replaces the stub; `undefined` on the server. Use the value of the latest
78
+ * render rather than one kept from before (e.g. in a ref): calls on a stub kept past the load are
79
+ * lost. A method that returns a value returns `undefined` on the stub; read flags with the hooks.
80
+ *
81
+ * The re-render comes from the flags loading, as the library answers the stub's queued
82
+ * `onFeatureFlags`: with feature flags disabled it stays on the stub until something else
83
+ * re-renders.
84
+ */
85
+ function usePostHog() {
86
+ return useSyncExternalStore(subscribe, getPosthog, () => void 0);
87
+ }
88
+ export { PosthogProvider, useActiveFeatureFlags, useFeatureFlagEnabled, useFeatureFlagPayload, useFeatureFlagResult, useFeatureFlagVariantKey, usePostHog };
89
+
90
+ //# sourceMappingURL=posthog.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"posthog.mjs","names":[],"sources":["../../src/react/posthog.ts"],"sourcesContent":["import type { BootstrapConfig, FeatureFlagResult, JsonType, PostHog } from 'posthog-js';\nimport {\n type ReactNode,\n createContext,\n createElement,\n use,\n useRef,\n useSyncExternalStore,\n} from 'react';\nimport { getLoadedPosthog, getPosthog } from '../third-parties/posthog';\n\nconst noop = () => {};\n\nconst Bootstrap = createContext<BootstrapConfig | undefined>(undefined);\n\n/**\n * The counterpart of `posthog-js/react`'s `PostHogProvider`, for the snippet-loaded library. It\n * does not initialize PostHog — `posthogAnalytics` does — only carries what the hooks need from\n * the server: the request's server-evaluated flags, the same object as the snippet's\n * `config.bootstrap`, for the flag hooks to render with on the server, through hydration and until\n * the library has loaded its flags — an experiment's variant renders at once, with no flicker and\n * no hydration mismatch. Wrap the app in it, e.g. in the root route.\n */\nexport function PosthogProvider({\n bootstrap,\n children,\n}: {\n bootstrap: BootstrapConfig | undefined;\n children: ReactNode;\n}) {\n return createElement(Bootstrap.Provider, { value: bootstrap }, children);\n}\n\n/** Subscribes to flag (re)loads; on the stub the subscription is queued and has no unsubscribe. */\nfunction subscribe(onChange: () => void): () => void {\n const unsubscribe: (() => void) | undefined = getPosthog()?.onFeatureFlags(onChange);\n return unsubscribe ?? noop;\n}\n\n/**\n * What `read` returns once the library has loaded its flags, and `bootstrapped` until then and on\n * the server, re-read when flags reload. The value is kept while its JSON is unchanged, as\n * `useSyncExternalStore` needs: PostHog builds a new result or payload object on every read.\n */\nfunction useFlags<T>(read: (posthog: PostHog) => T, bootstrapped: T): T {\n const cache = useRef<{ json: string | undefined; value: T }>(undefined);\n const stable = (value: T) => {\n // Typed wider: `JSON.stringify(undefined)` is `undefined`, whatever its type says.\n const json: string | undefined = JSON.stringify(value);\n if (!cache.current || cache.current.json !== json) cache.current = { json, value };\n return cache.current.value;\n };\n return useSyncExternalStore(\n subscribe,\n () => {\n const posthog = getLoadedPosthog();\n // As `posthog-js/react`: the bootstrap until the flags request has answered, not only until\n // the library has loaded, so no flag is read (and no exposure recorded) before then.\n return stable(posthog?.featureFlags.hasLoadedFlags ? read(posthog) : bootstrapped);\n },\n () => stable(bootstrapped)\n );\n}\n\n/*\n * The hooks of `posthog-js/react`, with its names and signatures, for the snippet-loaded library.\n *\n * Under a `<PosthogProvider>` each is the server's value until the library has loaded its\n * flags, on the server too. Without one it is `undefined` on the server and through hydration, so\n * the default renders first and the variant once flags arrive; to wait for them instead, call\n * `use(browser())` and `use(posthogFlagsReady())` above it, under a `<Suspense>`.\n *\n * Reading a flag records the exposure (`$feature_flag_called`) once the flags have loaded, as\n * PostHog's do — except the payload's — not while only a bootstrapped value is shown.\n */\n\n/** A flag's value: `true`/`false`, a multivariate flag's variant, or `undefined` until loaded. */\nexport function useFeatureFlagVariantKey(flag: string): string | boolean | undefined {\n const bootstrapped = use(Bootstrap)?.featureFlags?.[flag];\n return useFlags((posthog) => posthog.getFeatureFlag(flag), bootstrapped);\n}\n\n/** Whether a flag is on (a variant counts as on); `defaultValue` while it is unknown. */\nexport function useFeatureFlagEnabled(flag: string): boolean | undefined;\nexport function useFeatureFlagEnabled(flag: string, defaultValue: boolean): boolean;\nexport function useFeatureFlagEnabled(flag: string, defaultValue?: boolean) {\n const value = use(Bootstrap)?.featureFlags?.[flag];\n const bootstrapped = value === undefined ? undefined : !!value;\n return useFlags((posthog) => posthog.isFeatureEnabled(flag), bootstrapped) ?? defaultValue;\n}\n\n/** A flag's payload, read without recording an exposure. */\nexport function useFeatureFlagPayload(flag: string): JsonType {\n const bootstrapped = use(Bootstrap)?.featureFlagPayloads?.[flag];\n return useFlags(\n (posthog) => posthog.getFeatureFlagResult(flag, { send_event: false })?.payload,\n bootstrapped\n );\n}\n\n/** A flag's value, variant and payload together; `undefined` while it is unknown. */\nexport function useFeatureFlagResult(flag: string): FeatureFlagResult | undefined {\n const bootstrap = use(Bootstrap);\n const value = bootstrap?.featureFlags?.[flag];\n const bootstrapped: FeatureFlagResult | undefined =\n value === undefined\n ? undefined\n : {\n key: flag,\n enabled: typeof value === 'string' ? true : value,\n variant: typeof value === 'string' ? value : undefined,\n payload: bootstrap?.featureFlagPayloads?.[flag],\n };\n return useFlags((posthog) => posthog.getFeatureFlagResult(flag), bootstrapped);\n}\n\n/**\n * The keys of the flags: only those that are on while bootstrapped, every flag the library has\n * once loaded — as `posthog-js/react`'s does.\n */\nexport function useActiveFeatureFlags(): string[] {\n const flags = use(Bootstrap)?.featureFlags ?? {};\n const bootstrapped = Object.keys(flags).filter((key) => flags[key]);\n return useFlags((posthog) => posthog.featureFlags.getFlags(), bootstrapped);\n}\n\n/**\n * `window.posthog`, as `posthog-js/react`'s `usePostHog`: the snippet's stub until the library\n * loads — which queues the calls returning nothing (`capture`, `identify`, …) — then the library,\n * re-rendering when it replaces the stub; `undefined` on the server. Use the value of the latest\n * render rather than one kept from before (e.g. in a ref): calls on a stub kept past the load are\n * lost. A method that returns a value returns `undefined` on the stub; read flags with the hooks.\n *\n * The re-render comes from the flags loading, as the library answers the stub's queued\n * `onFeatureFlags`: with feature flags disabled it stays on the stub until something else\n * re-renders.\n */\nexport function usePostHog(): PostHog | undefined {\n return useSyncExternalStore(subscribe, getPosthog, () => undefined);\n}\n"],"mappings":";;;AAWA,MAAM,aAAa,CAAC;AAEpB,MAAM,YAAY,cAA2C,KAAA,CAAS;;;;;;;;;AAUtE,SAAgB,gBAAgB,EAC9B,WACA,YAIC;CACD,OAAO,cAAc,UAAU,UAAU,EAAE,OAAO,UAAU,GAAG,QAAQ;AACzE;;AAGA,SAAS,UAAU,UAAkC;CAEnD,OAD8C,WAAW,CAAC,EAAE,eAAe,QAAQ,KAC7D;AACxB;;;;;;AAOA,SAAS,SAAY,MAA+B,cAAoB;CACtE,MAAM,QAAQ,OAA+C,KAAA,CAAS;CACtE,MAAM,UAAU,UAAa;EAE3B,MAAM,OAA2B,KAAK,UAAU,KAAK;EACrD,IAAI,CAAC,MAAM,WAAW,MAAM,QAAQ,SAAS,MAAM,MAAM,UAAU;GAAE;GAAM;EAAM;EACjF,OAAO,MAAM,QAAQ;CACvB;CACA,OAAO,qBACL,iBACM;EACJ,MAAM,UAAU,iBAAiB;EAGjC,OAAO,OAAO,SAAS,aAAa,iBAAiB,KAAK,OAAO,IAAI,YAAY;CACnF,SACM,OAAO,YAAY,CAC3B;AACF;;AAeA,SAAgB,yBAAyB,MAA4C;CACnF,MAAM,eAAe,IAAI,SAAS,CAAC,EAAE,eAAe;CACpD,OAAO,UAAU,YAAY,QAAQ,eAAe,IAAI,GAAG,YAAY;AACzE;AAKA,SAAgB,sBAAsB,MAAc,cAAwB;CAC1E,MAAM,QAAQ,IAAI,SAAS,CAAC,EAAE,eAAe;CAE7C,OAAO,UAAU,YAAY,QAAQ,iBAAiB,IAAI,GADrC,UAAU,KAAA,IAAY,KAAA,IAAY,CAAC,CAAC,KACgB,KAAK;AAChF;;AAGA,SAAgB,sBAAsB,MAAwB;CAC5D,MAAM,eAAe,IAAI,SAAS,CAAC,EAAE,sBAAsB;CAC3D,OAAO,UACJ,YAAY,QAAQ,qBAAqB,MAAM,EAAE,YAAY,MAAM,CAAC,CAAC,EAAE,SACxE,YACF;AACF;;AAGA,SAAgB,qBAAqB,MAA6C;CAChF,MAAM,YAAY,IAAI,SAAS;CAC/B,MAAM,QAAQ,WAAW,eAAe;CAUxC,OAAO,UAAU,YAAY,QAAQ,qBAAqB,IAAI,GAR5D,UAAU,KAAA,IACN,KAAA,IACA;EACE,KAAK;EACL,SAAS,OAAO,UAAU,WAAW,OAAO;EAC5C,SAAS,OAAO,UAAU,WAAW,QAAQ,KAAA;EAC7C,SAAS,WAAW,sBAAsB;CAC5C,CACuE;AAC/E;;;;;AAMA,SAAgB,wBAAkC;CAChD,MAAM,QAAQ,IAAI,SAAS,CAAC,EAAE,gBAAgB,CAAC;CAE/C,OAAO,UAAU,YAAY,QAAQ,aAAa,SAAS,GADtC,OAAO,KAAK,KAAK,CAAC,CAAC,QAAQ,QAAQ,MAAM,IACW,CAAC;AAC5E;;;;;;;;;;;;AAaA,SAAgB,aAAkC;CAChD,OAAO,qBAAqB,WAAW,kBAAkB,KAAA,CAAS;AACpE"}
@@ -26,7 +26,7 @@ function googleAnalytics(options) {
26
26
  track: sendGAEvent,
27
27
  setUser: setGAUser,
28
28
  script: {
29
- id: "gtag",
29
+ id: "google-analytics",
30
30
  inline: `
31
31
  window.dataLayer = window.dataLayer || [];
32
32
  function gtag(){dataLayer.push(arguments);}
@@ -1 +1 @@
1
- {"version":3,"file":"google-analytics.cjs","names":[],"sources":["../../src/third-parties/google-analytics.ts"],"sourcesContent":["import type { UpdateVisitorDTO } from '../schema/index';\nimport type { GaId, Gtag } from '../track/gtag';\nimport type { EventName, TrackName, TrackProperties } from '../track/types';\nimport type { Integration } from './integration';\n\ndeclare global {\n interface Window {\n /** Undefined until the Google tag (gtag.js) script has loaded. */\n gtag?: Gtag['gtag'];\n }\n}\n\nexport function sendGAEvent<T extends EventName>(\n name: TrackName<T>,\n properties?: TrackProperties<T>\n) {\n if (typeof window === 'undefined' || !window.gtag) {\n console.warn('GA has not been initialized');\n return false;\n }\n window.gtag('event', name, properties);\n}\n\nexport function setGAUser({ user_id, user_data }: UpdateVisitorDTO) {\n if (typeof window === 'undefined' || !window.gtag) {\n console.warn('GA has not been initialized');\n return;\n }\n // No user is sign-out (`reset()`): GA keeps a set user_id for every later event on the page, so\n // it is cleared explicitly.\n window.gtag('set', 'user_id', user_id || null);\n if (user_data) window.gtag('set', 'user_data', user_data);\n}\n\n/**\n * Google Analytics 4 (gtag.js): every event, for behavior analysis. `src` serves gtag.js from\n * another path (a first-party proxy); `debug` turns on GA4's DebugView for this page.\n */\nexport function googleAnalytics(options: { id: GaId; src?: string; debug?: boolean }): Integration {\n const src = options.src ?? `https://www.googletagmanager.com/gtag/js?id=${options.id}`;\n return {\n type: 'analytics',\n track: sendGAEvent,\n setUser: setGAUser,\n script: {\n id: 'gtag',\n inline: `\n window.dataLayer = window.dataLayer || [];\n function gtag(){dataLayer.push(arguments);}\n gtag('js', new Date());\n gtag('config', ${JSON.stringify(options.id)}${options.debug ? ', { debug_mode: true }' : ''});\n (function (d, s, u) {\n var j = d.createElement(s);\n j.async = true;\n // A script added here does not inherit the nonce: hand it this one's, or a CSP that\n // allows scripts by nonce (without 'strict-dynamic') blocks gtag.js.\n j.nonce = d.currentScript && d.currentScript.nonce;\n j.src = u;\n var f = d.getElementsByTagName(s)[0];\n f.parentNode.insertBefore(j, f);\n })(document, 'script', ${JSON.stringify(src)});\n `,\n },\n };\n}\n"],"mappings":";;AAYA,SAAgB,YACd,MACA,YACA;CACA,IAAI,OAAO,WAAW,eAAe,CAAC,OAAO,MAAM;EACjD,QAAQ,KAAK,6BAA6B;EAC1C,OAAO;CACT;CACA,OAAO,KAAK,SAAS,MAAM,UAAU;AACvC;AAEA,SAAgB,UAAU,EAAE,SAAS,aAA+B;CAClE,IAAI,OAAO,WAAW,eAAe,CAAC,OAAO,MAAM;EACjD,QAAQ,KAAK,6BAA6B;EAC1C;CACF;CAGA,OAAO,KAAK,OAAO,WAAW,WAAW,IAAI;CAC7C,IAAI,WAAW,OAAO,KAAK,OAAO,aAAa,SAAS;AAC1D;;;;;AAMA,SAAgB,gBAAgB,SAAmE;CACjG,MAAM,MAAM,QAAQ,OAAO,+CAA+C,QAAQ;CAClF,OAAO;EACL,MAAM;EACN,OAAO;EACP,SAAS;EACT,QAAQ;GACN,IAAI;GACJ,QAAQ;;;;yBAIW,KAAK,UAAU,QAAQ,EAAE,IAAI,QAAQ,QAAQ,2BAA2B,GAAG;;;;;;;;;;iCAUnE,KAAK,UAAU,GAAG,EAAE;;EAEjD;CACF;AACF"}
1
+ {"version":3,"file":"google-analytics.cjs","names":[],"sources":["../../src/third-parties/google-analytics.ts"],"sourcesContent":["import type { UpdateVisitorDTO } from '../schema/index';\nimport type { GaId, Gtag } from '../track/gtag';\nimport type { EventName, TrackName, TrackProperties } from '../track/types';\nimport type { Integration } from './integration';\n\ndeclare global {\n interface Window {\n /** Undefined until the Google tag (gtag.js) script has loaded. */\n gtag?: Gtag['gtag'];\n }\n}\n\nexport function sendGAEvent<T extends EventName>(\n name: TrackName<T>,\n properties?: TrackProperties<T>\n) {\n if (typeof window === 'undefined' || !window.gtag) {\n console.warn('GA has not been initialized');\n return false;\n }\n window.gtag('event', name, properties);\n}\n\nexport function setGAUser({ user_id, user_data }: UpdateVisitorDTO) {\n if (typeof window === 'undefined' || !window.gtag) {\n console.warn('GA has not been initialized');\n return;\n }\n // No user is sign-out (`reset()`): GA keeps a set user_id for every later event on the page, so\n // it is cleared explicitly.\n window.gtag('set', 'user_id', user_id || null);\n if (user_data) window.gtag('set', 'user_data', user_data);\n}\n\n/**\n * Google Analytics 4 (gtag.js): every event, for behavior analysis. `src` serves gtag.js from\n * another path (a first-party proxy); `debug` turns on GA4's DebugView for this page.\n */\nexport function googleAnalytics(options: { id: GaId; src?: string; debug?: boolean }): Integration {\n const src = options.src ?? `https://www.googletagmanager.com/gtag/js?id=${options.id}`;\n return {\n type: 'analytics',\n track: sendGAEvent,\n setUser: setGAUser,\n script: {\n id: 'google-analytics',\n inline: `\n window.dataLayer = window.dataLayer || [];\n function gtag(){dataLayer.push(arguments);}\n gtag('js', new Date());\n gtag('config', ${JSON.stringify(options.id)}${options.debug ? ', { debug_mode: true }' : ''});\n (function (d, s, u) {\n var j = d.createElement(s);\n j.async = true;\n // A script added here does not inherit the nonce: hand it this one's, or a CSP that\n // allows scripts by nonce (without 'strict-dynamic') blocks gtag.js.\n j.nonce = d.currentScript && d.currentScript.nonce;\n j.src = u;\n var f = d.getElementsByTagName(s)[0];\n f.parentNode.insertBefore(j, f);\n })(document, 'script', ${JSON.stringify(src)});\n `,\n },\n };\n}\n"],"mappings":";;AAYA,SAAgB,YACd,MACA,YACA;CACA,IAAI,OAAO,WAAW,eAAe,CAAC,OAAO,MAAM;EACjD,QAAQ,KAAK,6BAA6B;EAC1C,OAAO;CACT;CACA,OAAO,KAAK,SAAS,MAAM,UAAU;AACvC;AAEA,SAAgB,UAAU,EAAE,SAAS,aAA+B;CAClE,IAAI,OAAO,WAAW,eAAe,CAAC,OAAO,MAAM;EACjD,QAAQ,KAAK,6BAA6B;EAC1C;CACF;CAGA,OAAO,KAAK,OAAO,WAAW,WAAW,IAAI;CAC7C,IAAI,WAAW,OAAO,KAAK,OAAO,aAAa,SAAS;AAC1D;;;;;AAMA,SAAgB,gBAAgB,SAAmE;CACjG,MAAM,MAAM,QAAQ,OAAO,+CAA+C,QAAQ;CAClF,OAAO;EACL,MAAM;EACN,OAAO;EACP,SAAS;EACT,QAAQ;GACN,IAAI;GACJ,QAAQ;;;;yBAIW,KAAK,UAAU,QAAQ,EAAE,IAAI,QAAQ,QAAQ,2BAA2B,GAAG;;;;;;;;;;iCAUnE,KAAK,UAAU,GAAG,EAAE;;EAEjD;CACF;AACF"}
@@ -25,7 +25,7 @@ function googleAnalytics(options) {
25
25
  track: sendGAEvent,
26
26
  setUser: setGAUser,
27
27
  script: {
28
- id: "gtag",
28
+ id: "google-analytics",
29
29
  inline: `
30
30
  window.dataLayer = window.dataLayer || [];
31
31
  function gtag(){dataLayer.push(arguments);}
@@ -1 +1 @@
1
- {"version":3,"file":"google-analytics.mjs","names":[],"sources":["../../src/third-parties/google-analytics.ts"],"sourcesContent":["import type { UpdateVisitorDTO } from '../schema/index';\nimport type { GaId, Gtag } from '../track/gtag';\nimport type { EventName, TrackName, TrackProperties } from '../track/types';\nimport type { Integration } from './integration';\n\ndeclare global {\n interface Window {\n /** Undefined until the Google tag (gtag.js) script has loaded. */\n gtag?: Gtag['gtag'];\n }\n}\n\nexport function sendGAEvent<T extends EventName>(\n name: TrackName<T>,\n properties?: TrackProperties<T>\n) {\n if (typeof window === 'undefined' || !window.gtag) {\n console.warn('GA has not been initialized');\n return false;\n }\n window.gtag('event', name, properties);\n}\n\nexport function setGAUser({ user_id, user_data }: UpdateVisitorDTO) {\n if (typeof window === 'undefined' || !window.gtag) {\n console.warn('GA has not been initialized');\n return;\n }\n // No user is sign-out (`reset()`): GA keeps a set user_id for every later event on the page, so\n // it is cleared explicitly.\n window.gtag('set', 'user_id', user_id || null);\n if (user_data) window.gtag('set', 'user_data', user_data);\n}\n\n/**\n * Google Analytics 4 (gtag.js): every event, for behavior analysis. `src` serves gtag.js from\n * another path (a first-party proxy); `debug` turns on GA4's DebugView for this page.\n */\nexport function googleAnalytics(options: { id: GaId; src?: string; debug?: boolean }): Integration {\n const src = options.src ?? `https://www.googletagmanager.com/gtag/js?id=${options.id}`;\n return {\n type: 'analytics',\n track: sendGAEvent,\n setUser: setGAUser,\n script: {\n id: 'gtag',\n inline: `\n window.dataLayer = window.dataLayer || [];\n function gtag(){dataLayer.push(arguments);}\n gtag('js', new Date());\n gtag('config', ${JSON.stringify(options.id)}${options.debug ? ', { debug_mode: true }' : ''});\n (function (d, s, u) {\n var j = d.createElement(s);\n j.async = true;\n // A script added here does not inherit the nonce: hand it this one's, or a CSP that\n // allows scripts by nonce (without 'strict-dynamic') blocks gtag.js.\n j.nonce = d.currentScript && d.currentScript.nonce;\n j.src = u;\n var f = d.getElementsByTagName(s)[0];\n f.parentNode.insertBefore(j, f);\n })(document, 'script', ${JSON.stringify(src)});\n `,\n },\n };\n}\n"],"mappings":";AAYA,SAAgB,YACd,MACA,YACA;CACA,IAAI,OAAO,WAAW,eAAe,CAAC,OAAO,MAAM;EACjD,QAAQ,KAAK,6BAA6B;EAC1C,OAAO;CACT;CACA,OAAO,KAAK,SAAS,MAAM,UAAU;AACvC;AAEA,SAAgB,UAAU,EAAE,SAAS,aAA+B;CAClE,IAAI,OAAO,WAAW,eAAe,CAAC,OAAO,MAAM;EACjD,QAAQ,KAAK,6BAA6B;EAC1C;CACF;CAGA,OAAO,KAAK,OAAO,WAAW,WAAW,IAAI;CAC7C,IAAI,WAAW,OAAO,KAAK,OAAO,aAAa,SAAS;AAC1D;;;;;AAMA,SAAgB,gBAAgB,SAAmE;CACjG,MAAM,MAAM,QAAQ,OAAO,+CAA+C,QAAQ;CAClF,OAAO;EACL,MAAM;EACN,OAAO;EACP,SAAS;EACT,QAAQ;GACN,IAAI;GACJ,QAAQ;;;;yBAIW,KAAK,UAAU,QAAQ,EAAE,IAAI,QAAQ,QAAQ,2BAA2B,GAAG;;;;;;;;;;iCAUnE,KAAK,UAAU,GAAG,EAAE;;EAEjD;CACF;AACF"}
1
+ {"version":3,"file":"google-analytics.mjs","names":[],"sources":["../../src/third-parties/google-analytics.ts"],"sourcesContent":["import type { UpdateVisitorDTO } from '../schema/index';\nimport type { GaId, Gtag } from '../track/gtag';\nimport type { EventName, TrackName, TrackProperties } from '../track/types';\nimport type { Integration } from './integration';\n\ndeclare global {\n interface Window {\n /** Undefined until the Google tag (gtag.js) script has loaded. */\n gtag?: Gtag['gtag'];\n }\n}\n\nexport function sendGAEvent<T extends EventName>(\n name: TrackName<T>,\n properties?: TrackProperties<T>\n) {\n if (typeof window === 'undefined' || !window.gtag) {\n console.warn('GA has not been initialized');\n return false;\n }\n window.gtag('event', name, properties);\n}\n\nexport function setGAUser({ user_id, user_data }: UpdateVisitorDTO) {\n if (typeof window === 'undefined' || !window.gtag) {\n console.warn('GA has not been initialized');\n return;\n }\n // No user is sign-out (`reset()`): GA keeps a set user_id for every later event on the page, so\n // it is cleared explicitly.\n window.gtag('set', 'user_id', user_id || null);\n if (user_data) window.gtag('set', 'user_data', user_data);\n}\n\n/**\n * Google Analytics 4 (gtag.js): every event, for behavior analysis. `src` serves gtag.js from\n * another path (a first-party proxy); `debug` turns on GA4's DebugView for this page.\n */\nexport function googleAnalytics(options: { id: GaId; src?: string; debug?: boolean }): Integration {\n const src = options.src ?? `https://www.googletagmanager.com/gtag/js?id=${options.id}`;\n return {\n type: 'analytics',\n track: sendGAEvent,\n setUser: setGAUser,\n script: {\n id: 'google-analytics',\n inline: `\n window.dataLayer = window.dataLayer || [];\n function gtag(){dataLayer.push(arguments);}\n gtag('js', new Date());\n gtag('config', ${JSON.stringify(options.id)}${options.debug ? ', { debug_mode: true }' : ''});\n (function (d, s, u) {\n var j = d.createElement(s);\n j.async = true;\n // A script added here does not inherit the nonce: hand it this one's, or a CSP that\n // allows scripts by nonce (without 'strict-dynamic') blocks gtag.js.\n j.nonce = d.currentScript && d.currentScript.nonce;\n j.src = u;\n var f = d.getElementsByTagName(s)[0];\n f.parentNode.insertBefore(j, f);\n })(document, 'script', ${JSON.stringify(src)});\n `,\n },\n };\n}\n"],"mappings":";AAYA,SAAgB,YACd,MACA,YACA;CACA,IAAI,OAAO,WAAW,eAAe,CAAC,OAAO,MAAM;EACjD,QAAQ,KAAK,6BAA6B;EAC1C,OAAO;CACT;CACA,OAAO,KAAK,SAAS,MAAM,UAAU;AACvC;AAEA,SAAgB,UAAU,EAAE,SAAS,aAA+B;CAClE,IAAI,OAAO,WAAW,eAAe,CAAC,OAAO,MAAM;EACjD,QAAQ,KAAK,6BAA6B;EAC1C;CACF;CAGA,OAAO,KAAK,OAAO,WAAW,WAAW,IAAI;CAC7C,IAAI,WAAW,OAAO,KAAK,OAAO,aAAa,SAAS;AAC1D;;;;;AAMA,SAAgB,gBAAgB,SAAmE;CACjG,MAAM,MAAM,QAAQ,OAAO,+CAA+C,QAAQ;CAClF,OAAO;EACL,MAAM;EACN,OAAO;EACP,SAAS;EACT,QAAQ;GACN,IAAI;GACJ,QAAQ;;;;yBAIW,KAAK,UAAU,QAAQ,EAAE,IAAI,QAAQ,QAAQ,2BAA2B,GAAG;;;;;;;;;;iCAUnE,KAAK,UAAU,GAAG,EAAE;;EAEjD;CACF;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"integration.cjs","names":[],"sources":["../../src/third-parties/integration.ts"],"sourcesContent":["import type { EventName, ThirdPartyTracker, TrackName } from '../track/types';\nimport type { ThirdPartyUserSetter } from '../visitor/types';\n\n/**\n * The one script an integration puts on the page, rendered by `<Analytics integrations>`\n * (react, next) with the request's `nonce`: an inline snippet that loads the\n * vendor's own script from its host, as every vendor's official snippet does.\n */\nexport interface IntegrationScript {\n /** The element id; also its React key, and how a test or a CSP report finds it. */\n readonly id: string;\n readonly inline: string;\n /** `next/script`'s loading strategy, `afterInteractive` by default; the other frameworks ignore it. */\n readonly strategy?: 'beforeInteractive' | 'afterInteractive' | 'lazyOnload';\n}\n\n/**\n * One third party, configured in one place: how events reach it, how it learns the signed-in\n * user, and the script it needs. Built by the factories in `@shware/analytics/third-parties`\n * (`googleAnalytics`, `metaAds`, …) and handed to both `setupAnalytics({ integrations })` and\n * `<Analytics integrations>`. A host can write its own for a platform the SDK does not cover.\n *\n * `type` says what the platform is for. An `analytics` integration (GA4, PostHog) receives every\n * event, for behavior analysis. An `ads` integration receives only what helps an ad platform\n * optimize and build audiences — the conversion events it maps to its own standard events, plus\n * the custom events it was explicitly given — and filters in its own `track`.\n */\nexport interface Integration {\n readonly type: 'analytics' | 'ads';\n readonly track: ThirdPartyTracker;\n readonly setUser?: ThirdPartyUserSetter;\n readonly script?: IntegrationScript;\n /**\n * Origins `<Analytics>` preconnects to (`react-dom`'s `preconnect`), so the connection is up\n * before the script asks for something there — e.g. where a snippet loads its library from.\n */\n readonly preconnect?: readonly string[];\n}\n\n/**\n * The GA4 recommended events that are conversions or close to one, for an ad platform with no\n * standard events of its own to map to (Microsoft UET), so it is not sent the whole product.\n */\nexport const CONVERSION_EVENTS = [\n 'sign_up',\n 'login',\n 'generate_lead',\n 'view_item',\n 'add_to_cart',\n 'add_to_wishlist',\n 'begin_checkout',\n 'add_payment_info',\n 'purchase',\n 'subscribe',\n 'trial_begin',\n 'search',\n 'schedule',\n 'submit_application',\n 'contact',\n] as const satisfies readonly EventName[];\n\nexport interface AdsOptions {\n /**\n * Custom events this platform receives besides the conversions it maps to its standard\n * events, e.g. one used as an optimization goal or for an audience. Everything else is not\n * sent to it. The names `track` accepts, so with strict event names a typo is a compile error.\n */\n customEvents?: readonly TrackName[];\n}\n\n/**\n * Which events an ad platform receives: what `isStandard` accepts — the events its mapper turns\n * into one of its standard events — and the custom events the host listed. Everything else in the\n * product (feature use, clicks, onboarding steps) is behavior analysis, which is GA4's and\n * PostHog's job, and only noise to an ad platform's optimization. The same rule picks what the\n * browser tag and the platform's conversions API send (`@shware/analytics/server`), so the two\n * report the same events.\n */\nexport function adEvents(\n isStandard: (name: string) => boolean,\n customEvents: readonly string[] = []\n): (name: string) => boolean {\n return (name) => isStandard(name) || customEvents.includes(name);\n}\n\n/** An ad tracker that sends only the events `accepts` lets through (`adEvents`). */\nexport function adsTracker(\n send: ThirdPartyTracker,\n accepts: (name: string) => boolean\n): ThirdPartyTracker {\n return (name, properties, eventId) => {\n if (!accepts(name)) return;\n return send(name, properties, eventId);\n };\n}\n"],"mappings":";;;;;;AA2CA,MAAa,oBAAoB;CAC/B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;;;;;;;;AAmBA,SAAgB,SACd,YACA,eAAkC,CAAC,GACR;CAC3B,QAAQ,SAAS,WAAW,IAAI,KAAK,aAAa,SAAS,IAAI;AACjE;;AAGA,SAAgB,WACd,MACA,SACmB;CACnB,QAAQ,MAAM,YAAY,YAAY;EACpC,IAAI,CAAC,QAAQ,IAAI,GAAG;EACpB,OAAO,KAAK,MAAM,YAAY,OAAO;CACvC;AACF"}
1
+ {"version":3,"file":"integration.cjs","names":[],"sources":["../../src/third-parties/integration.ts"],"sourcesContent":["import type { EventName, ThirdPartyTracker, TrackName } from '../track/types';\nimport type { ThirdPartyUserSetter } from '../visitor/types';\n\n/**\n * The one script an integration puts on the page, rendered by `<Analytics integrations>`\n * (react, next) with the request's `nonce`: an inline snippet that loads the\n * vendor's own script from its host, as every vendor's official snippet does.\n */\nexport interface IntegrationScript {\n /**\n * The element id; also its React key, and how a test or a CSP report finds it. Never a global's\n * name: an element's id is readable as `window[id]` until a script defines it, so an id like\n * `posthog` hands the snippet's `window.posthog || []` the <script> element. Keep a hyphen in it.\n */\n readonly id: string;\n readonly inline: string;\n /** `next/script`'s loading strategy, `afterInteractive` by default; the other frameworks ignore it. */\n readonly strategy?: 'beforeInteractive' | 'afterInteractive' | 'lazyOnload';\n}\n\n/**\n * One third party, configured in one place: how events reach it, how it learns the signed-in\n * user, and the script it needs. Built by the factories in `@shware/analytics/third-parties`\n * (`googleAnalytics`, `metaAds`, …) and handed to both `setupAnalytics({ integrations })` and\n * `<Analytics integrations>`. A host can write its own for a platform the SDK does not cover.\n *\n * `type` says what the platform is for. An `analytics` integration (GA4, PostHog) receives every\n * event, for behavior analysis. An `ads` integration receives only what helps an ad platform\n * optimize and build audiences — the conversion events it maps to its own standard events, plus\n * the custom events it was explicitly given — and filters in its own `track`.\n */\nexport interface Integration {\n readonly type: 'analytics' | 'ads';\n readonly track: ThirdPartyTracker;\n readonly setUser?: ThirdPartyUserSetter;\n readonly script?: IntegrationScript;\n /**\n * Origins `<Analytics>` preconnects to (`react-dom`'s `preconnect`), so the connection is up\n * before the script asks for something there — e.g. where a snippet loads its library from.\n */\n readonly preconnect?: readonly string[];\n}\n\n/**\n * The GA4 recommended events that are conversions or close to one, for an ad platform with no\n * standard events of its own to map to (Microsoft UET), so it is not sent the whole product.\n */\nexport const CONVERSION_EVENTS = [\n 'sign_up',\n 'login',\n 'generate_lead',\n 'view_item',\n 'add_to_cart',\n 'add_to_wishlist',\n 'begin_checkout',\n 'add_payment_info',\n 'purchase',\n 'subscribe',\n 'trial_begin',\n 'search',\n 'schedule',\n 'submit_application',\n 'contact',\n] as const satisfies readonly EventName[];\n\nexport interface AdsOptions {\n /**\n * Custom events this platform receives besides the conversions it maps to its standard\n * events, e.g. one used as an optimization goal or for an audience. Everything else is not\n * sent to it. The names `track` accepts, so with strict event names a typo is a compile error.\n */\n customEvents?: readonly TrackName[];\n}\n\n/**\n * Which events an ad platform receives: what `isStandard` accepts — the events its mapper turns\n * into one of its standard events — and the custom events the host listed. Everything else in the\n * product (feature use, clicks, onboarding steps) is behavior analysis, which is GA4's and\n * PostHog's job, and only noise to an ad platform's optimization. The same rule picks what the\n * browser tag and the platform's conversions API send (`@shware/analytics/server`), so the two\n * report the same events.\n */\nexport function adEvents(\n isStandard: (name: string) => boolean,\n customEvents: readonly string[] = []\n): (name: string) => boolean {\n return (name) => isStandard(name) || customEvents.includes(name);\n}\n\n/** An ad tracker that sends only the events `accepts` lets through (`adEvents`). */\nexport function adsTracker(\n send: ThirdPartyTracker,\n accepts: (name: string) => boolean\n): ThirdPartyTracker {\n return (name, properties, eventId) => {\n if (!accepts(name)) return;\n return send(name, properties, eventId);\n };\n}\n"],"mappings":";;;;;;AA+CA,MAAa,oBAAoB;CAC/B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;;;;;;;;AAmBA,SAAgB,SACd,YACA,eAAkC,CAAC,GACR;CAC3B,QAAQ,SAAS,WAAW,IAAI,KAAK,aAAa,SAAS,IAAI;AACjE;;AAGA,SAAgB,WACd,MACA,SACmB;CACnB,QAAQ,MAAM,YAAY,YAAY;EACpC,IAAI,CAAC,QAAQ,IAAI,GAAG;EACpB,OAAO,KAAK,MAAM,YAAY,OAAO;CACvC;AACF"}
@@ -6,7 +6,11 @@ import { ThirdPartyUserSetter } from "../visitor/types.cjs";
6
6
  * vendor's own script from its host, as every vendor's official snippet does.
7
7
  */
8
8
  export interface IntegrationScript {
9
- /** The element id; also its React key, and how a test or a CSP report finds it. */
9
+ /**
10
+ * The element id; also its React key, and how a test or a CSP report finds it. Never a global's
11
+ * name: an element's id is readable as `window[id]` until a script defines it, so an id like
12
+ * `posthog` hands the snippet's `window.posthog || []` the <script> element. Keep a hyphen in it.
13
+ */
10
14
  readonly id: string;
11
15
  readonly inline: string;
12
16
  /** `next/script`'s loading strategy, `afterInteractive` by default; the other frameworks ignore it. */
@@ -1 +1 @@
1
- {"version":3,"file":"integration.d.cts","names":[],"sources":["../../src/third-parties/integration.ts"],"mappings":";;;;;;;iBAQiB;;WAEN;WACA;;WAEA;;;;;;;;;;;;;iBAcM;WACN;WACA,OAAO;WACP,UAAU;WACV,SAAS;;;;;WAKT;;;;;;qBAOE;iBAkBI;;;;;;EAMf,wBAAwB;;;;;;;;;;wBAWV,SACd,aAAa,0BACb,oCACE;;wBAKY,WACd,MAAM,mBACN,UAAU,2BACT"}
1
+ {"version":3,"file":"integration.d.cts","names":[],"sources":["../../src/third-parties/integration.ts"],"mappings":";;;;;;;iBAQiB;;;;;;WAMN;WACA;;WAEA;;;;;;;;;;;;;iBAcM;WACN;WACA,OAAO;WACP,UAAU;WACV,SAAS;;;;;WAKT;;;;;;qBAOE;iBAkBI;;;;;;EAMf,wBAAwB;;;;;;;;;;wBAWV,SACd,aAAa,0BACb,oCACE;;wBAKY,WACd,MAAM,mBACN,UAAU,2BACT"}
@@ -6,7 +6,11 @@ import { ThirdPartyUserSetter } from "../visitor/types.mjs";
6
6
  * vendor's own script from its host, as every vendor's official snippet does.
7
7
  */
8
8
  export interface IntegrationScript {
9
- /** The element id; also its React key, and how a test or a CSP report finds it. */
9
+ /**
10
+ * The element id; also its React key, and how a test or a CSP report finds it. Never a global's
11
+ * name: an element's id is readable as `window[id]` until a script defines it, so an id like
12
+ * `posthog` hands the snippet's `window.posthog || []` the <script> element. Keep a hyphen in it.
13
+ */
10
14
  readonly id: string;
11
15
  readonly inline: string;
12
16
  /** `next/script`'s loading strategy, `afterInteractive` by default; the other frameworks ignore it. */
@@ -1 +1 @@
1
- {"version":3,"file":"integration.d.mts","names":[],"sources":["../../src/third-parties/integration.ts"],"mappings":";;;;;;;iBAQiB;;WAEN;WACA;;WAEA;;;;;;;;;;;;;iBAcM;WACN;WACA,OAAO;WACP,UAAU;WACV,SAAS;;;;;WAKT;;;;;;qBAOE;iBAkBI;;;;;;EAMf,wBAAwB;;;;;;;;;;wBAWV,SACd,aAAa,0BACb,oCACE;;wBAKY,WACd,MAAM,mBACN,UAAU,2BACT"}
1
+ {"version":3,"file":"integration.d.mts","names":[],"sources":["../../src/third-parties/integration.ts"],"mappings":";;;;;;;iBAQiB;;;;;;WAMN;WACA;;WAEA;;;;;;;;;;;;;iBAcM;WACN;WACA,OAAO;WACP,UAAU;WACV,SAAS;;;;;WAKT;;;;;;qBAOE;iBAkBI;;;;;;EAMf,wBAAwB;;;;;;;;;;wBAWV,SACd,aAAa,0BACb,oCACE;;wBAKY,WACd,MAAM,mBACN,UAAU,2BACT"}
@@ -1 +1 @@
1
- {"version":3,"file":"integration.mjs","names":[],"sources":["../../src/third-parties/integration.ts"],"sourcesContent":["import type { EventName, ThirdPartyTracker, TrackName } from '../track/types';\nimport type { ThirdPartyUserSetter } from '../visitor/types';\n\n/**\n * The one script an integration puts on the page, rendered by `<Analytics integrations>`\n * (react, next) with the request's `nonce`: an inline snippet that loads the\n * vendor's own script from its host, as every vendor's official snippet does.\n */\nexport interface IntegrationScript {\n /** The element id; also its React key, and how a test or a CSP report finds it. */\n readonly id: string;\n readonly inline: string;\n /** `next/script`'s loading strategy, `afterInteractive` by default; the other frameworks ignore it. */\n readonly strategy?: 'beforeInteractive' | 'afterInteractive' | 'lazyOnload';\n}\n\n/**\n * One third party, configured in one place: how events reach it, how it learns the signed-in\n * user, and the script it needs. Built by the factories in `@shware/analytics/third-parties`\n * (`googleAnalytics`, `metaAds`, …) and handed to both `setupAnalytics({ integrations })` and\n * `<Analytics integrations>`. A host can write its own for a platform the SDK does not cover.\n *\n * `type` says what the platform is for. An `analytics` integration (GA4, PostHog) receives every\n * event, for behavior analysis. An `ads` integration receives only what helps an ad platform\n * optimize and build audiences — the conversion events it maps to its own standard events, plus\n * the custom events it was explicitly given — and filters in its own `track`.\n */\nexport interface Integration {\n readonly type: 'analytics' | 'ads';\n readonly track: ThirdPartyTracker;\n readonly setUser?: ThirdPartyUserSetter;\n readonly script?: IntegrationScript;\n /**\n * Origins `<Analytics>` preconnects to (`react-dom`'s `preconnect`), so the connection is up\n * before the script asks for something there — e.g. where a snippet loads its library from.\n */\n readonly preconnect?: readonly string[];\n}\n\n/**\n * The GA4 recommended events that are conversions or close to one, for an ad platform with no\n * standard events of its own to map to (Microsoft UET), so it is not sent the whole product.\n */\nexport const CONVERSION_EVENTS = [\n 'sign_up',\n 'login',\n 'generate_lead',\n 'view_item',\n 'add_to_cart',\n 'add_to_wishlist',\n 'begin_checkout',\n 'add_payment_info',\n 'purchase',\n 'subscribe',\n 'trial_begin',\n 'search',\n 'schedule',\n 'submit_application',\n 'contact',\n] as const satisfies readonly EventName[];\n\nexport interface AdsOptions {\n /**\n * Custom events this platform receives besides the conversions it maps to its standard\n * events, e.g. one used as an optimization goal or for an audience. Everything else is not\n * sent to it. The names `track` accepts, so with strict event names a typo is a compile error.\n */\n customEvents?: readonly TrackName[];\n}\n\n/**\n * Which events an ad platform receives: what `isStandard` accepts — the events its mapper turns\n * into one of its standard events — and the custom events the host listed. Everything else in the\n * product (feature use, clicks, onboarding steps) is behavior analysis, which is GA4's and\n * PostHog's job, and only noise to an ad platform's optimization. The same rule picks what the\n * browser tag and the platform's conversions API send (`@shware/analytics/server`), so the two\n * report the same events.\n */\nexport function adEvents(\n isStandard: (name: string) => boolean,\n customEvents: readonly string[] = []\n): (name: string) => boolean {\n return (name) => isStandard(name) || customEvents.includes(name);\n}\n\n/** An ad tracker that sends only the events `accepts` lets through (`adEvents`). */\nexport function adsTracker(\n send: ThirdPartyTracker,\n accepts: (name: string) => boolean\n): ThirdPartyTracker {\n return (name, properties, eventId) => {\n if (!accepts(name)) return;\n return send(name, properties, eventId);\n };\n}\n"],"mappings":";;;;;AA2CA,MAAa,oBAAoB;CAC/B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;;;;;;;;AAmBA,SAAgB,SACd,YACA,eAAkC,CAAC,GACR;CAC3B,QAAQ,SAAS,WAAW,IAAI,KAAK,aAAa,SAAS,IAAI;AACjE;;AAGA,SAAgB,WACd,MACA,SACmB;CACnB,QAAQ,MAAM,YAAY,YAAY;EACpC,IAAI,CAAC,QAAQ,IAAI,GAAG;EACpB,OAAO,KAAK,MAAM,YAAY,OAAO;CACvC;AACF"}
1
+ {"version":3,"file":"integration.mjs","names":[],"sources":["../../src/third-parties/integration.ts"],"sourcesContent":["import type { EventName, ThirdPartyTracker, TrackName } from '../track/types';\nimport type { ThirdPartyUserSetter } from '../visitor/types';\n\n/**\n * The one script an integration puts on the page, rendered by `<Analytics integrations>`\n * (react, next) with the request's `nonce`: an inline snippet that loads the\n * vendor's own script from its host, as every vendor's official snippet does.\n */\nexport interface IntegrationScript {\n /**\n * The element id; also its React key, and how a test or a CSP report finds it. Never a global's\n * name: an element's id is readable as `window[id]` until a script defines it, so an id like\n * `posthog` hands the snippet's `window.posthog || []` the <script> element. Keep a hyphen in it.\n */\n readonly id: string;\n readonly inline: string;\n /** `next/script`'s loading strategy, `afterInteractive` by default; the other frameworks ignore it. */\n readonly strategy?: 'beforeInteractive' | 'afterInteractive' | 'lazyOnload';\n}\n\n/**\n * One third party, configured in one place: how events reach it, how it learns the signed-in\n * user, and the script it needs. Built by the factories in `@shware/analytics/third-parties`\n * (`googleAnalytics`, `metaAds`, …) and handed to both `setupAnalytics({ integrations })` and\n * `<Analytics integrations>`. A host can write its own for a platform the SDK does not cover.\n *\n * `type` says what the platform is for. An `analytics` integration (GA4, PostHog) receives every\n * event, for behavior analysis. An `ads` integration receives only what helps an ad platform\n * optimize and build audiences — the conversion events it maps to its own standard events, plus\n * the custom events it was explicitly given — and filters in its own `track`.\n */\nexport interface Integration {\n readonly type: 'analytics' | 'ads';\n readonly track: ThirdPartyTracker;\n readonly setUser?: ThirdPartyUserSetter;\n readonly script?: IntegrationScript;\n /**\n * Origins `<Analytics>` preconnects to (`react-dom`'s `preconnect`), so the connection is up\n * before the script asks for something there — e.g. where a snippet loads its library from.\n */\n readonly preconnect?: readonly string[];\n}\n\n/**\n * The GA4 recommended events that are conversions or close to one, for an ad platform with no\n * standard events of its own to map to (Microsoft UET), so it is not sent the whole product.\n */\nexport const CONVERSION_EVENTS = [\n 'sign_up',\n 'login',\n 'generate_lead',\n 'view_item',\n 'add_to_cart',\n 'add_to_wishlist',\n 'begin_checkout',\n 'add_payment_info',\n 'purchase',\n 'subscribe',\n 'trial_begin',\n 'search',\n 'schedule',\n 'submit_application',\n 'contact',\n] as const satisfies readonly EventName[];\n\nexport interface AdsOptions {\n /**\n * Custom events this platform receives besides the conversions it maps to its standard\n * events, e.g. one used as an optimization goal or for an audience. Everything else is not\n * sent to it. The names `track` accepts, so with strict event names a typo is a compile error.\n */\n customEvents?: readonly TrackName[];\n}\n\n/**\n * Which events an ad platform receives: what `isStandard` accepts — the events its mapper turns\n * into one of its standard events — and the custom events the host listed. Everything else in the\n * product (feature use, clicks, onboarding steps) is behavior analysis, which is GA4's and\n * PostHog's job, and only noise to an ad platform's optimization. The same rule picks what the\n * browser tag and the platform's conversions API send (`@shware/analytics/server`), so the two\n * report the same events.\n */\nexport function adEvents(\n isStandard: (name: string) => boolean,\n customEvents: readonly string[] = []\n): (name: string) => boolean {\n return (name) => isStandard(name) || customEvents.includes(name);\n}\n\n/** An ad tracker that sends only the events `accepts` lets through (`adEvents`). */\nexport function adsTracker(\n send: ThirdPartyTracker,\n accepts: (name: string) => boolean\n): ThirdPartyTracker {\n return (name, properties, eventId) => {\n if (!accepts(name)) return;\n return send(name, properties, eventId);\n };\n}\n"],"mappings":";;;;;AA+CA,MAAa,oBAAoB;CAC/B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;;;;;;;;AAmBA,SAAgB,SACd,YACA,eAAkC,CAAC,GACR;CAC3B,QAAQ,SAAS,WAAW,IAAI,KAAK,aAAa,SAAS,IAAI;AACjE;;AAGA,SAAgB,WACd,MACA,SACmB;CACnB,QAAQ,MAAM,YAAY,YAAY;EACpC,IAAI,CAAC,QAAQ,IAAI,GAAG;EACpB,OAAO,KAAK,MAAM,YAAY,OAAO;CACvC;AACF"}
@@ -29,14 +29,14 @@ let flagsReady;
29
29
  /**
30
30
  * Resolves once PostHog has loaded its feature flags — or after `timeoutMs` (3 s by default),
31
31
  * since an ad blocker that stops the library would otherwise hold it forever; read the flags
32
- * after it with `useFeatureFlag` / `getLoadedPosthog`, which are `undefined` in that case. One
33
- * promise per page, so React's `use()` can suspend on it:
32
+ * after it with `useFeatureFlagVariantKey` / `getLoadedPosthog`, which are `undefined` in that
33
+ * case. One promise per page, so React's `use()` can suspend on it:
34
34
  *
35
35
  * ```tsx
36
36
  * function Checkout() {
37
37
  * use(browser()); // react-dom: the server renders the <Suspense> fallback instead
38
38
  * use(posthogFlagsReady());
39
- * return useFeatureFlag('new-checkout') === 'test' ? <NewCheckout /> : <OldCheckout />;
39
+ * return useFeatureFlagVariantKey('new-checkout') === 'test' ? <NewCheckout /> : <OldCheckout />;
40
40
  * }
41
41
  * ```
42
42
  *
@@ -114,7 +114,7 @@ function posthogAnalytics(options) {
114
114
  setUser: setPosthogUser,
115
115
  preconnect: URL.canParse(assets) ? [new URL(assets).origin] : [],
116
116
  script: {
117
- id: "posthog",
117
+ id: "posthog-snippet",
118
118
  strategy: "beforeInteractive",
119
119
  inline: `
120
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||[]);
@@ -1 +1 @@
1
- {"version":3,"file":"posthog.cjs","names":["getFirst"],"sources":["../../src/third-parties/posthog.ts"],"sourcesContent":["import type { PostHog, PostHogConfig } from 'posthog-js';\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-js';\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. Types only: install `posthog-js` (a dev dependency\n * is enough) for them; it is never bundled.\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 `useFeatureFlag` / `getLoadedPosthog`, which are `undefined` in that case. One\n * 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 useFeatureFlag('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',\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,OAAOA,oBAAAA,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.cjs","names":["getFirst"],"sources":["../../src/third-parties/posthog.ts"],"sourcesContent":["import type { PostHog, PostHogConfig } from 'posthog-js';\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-js';\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. Types only: install `posthog-js` (a dev dependency\n * is enough) for them; it is never bundled.\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,OAAOA,oBAAAA,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"}
@@ -23,14 +23,14 @@ export declare function getLoadedPosthog(): PostHog$1 | undefined;
23
23
  /**
24
24
  * Resolves once PostHog has loaded its feature flags — or after `timeoutMs` (3 s by default),
25
25
  * since an ad blocker that stops the library would otherwise hold it forever; read the flags
26
- * after it with `useFeatureFlag` / `getLoadedPosthog`, which are `undefined` in that case. One
27
- * promise per page, so React's `use()` can suspend on it:
26
+ * after it with `useFeatureFlagVariantKey` / `getLoadedPosthog`, which are `undefined` in that
27
+ * case. One promise per page, so React's `use()` can suspend on it:
28
28
  *
29
29
  * ```tsx
30
30
  * function Checkout() {
31
31
  * use(browser()); // react-dom: the server renders the <Suspense> fallback instead
32
32
  * use(posthogFlagsReady());
33
- * return useFeatureFlag('new-checkout') === 'test' ? <NewCheckout /> : <OldCheckout />;
33
+ * return useFeatureFlagVariantKey('new-checkout') === 'test' ? <NewCheckout /> : <OldCheckout />;
34
34
  * }
35
35
  * ```
36
36
  *
@@ -23,14 +23,14 @@ export declare function getLoadedPosthog(): PostHog$1 | undefined;
23
23
  /**
24
24
  * Resolves once PostHog has loaded its feature flags — or after `timeoutMs` (3 s by default),
25
25
  * since an ad blocker that stops the library would otherwise hold it forever; read the flags
26
- * after it with `useFeatureFlag` / `getLoadedPosthog`, which are `undefined` in that case. One
27
- * promise per page, so React's `use()` can suspend on it:
26
+ * after it with `useFeatureFlagVariantKey` / `getLoadedPosthog`, which are `undefined` in that
27
+ * case. One promise per page, so React's `use()` can suspend on it:
28
28
  *
29
29
  * ```tsx
30
30
  * function Checkout() {
31
31
  * use(browser()); // react-dom: the server renders the <Suspense> fallback instead
32
32
  * use(posthogFlagsReady());
33
- * return useFeatureFlag('new-checkout') === 'test' ? <NewCheckout /> : <OldCheckout />;
33
+ * return useFeatureFlagVariantKey('new-checkout') === 'test' ? <NewCheckout /> : <OldCheckout />;
34
34
  * }
35
35
  * ```
36
36
  *