@shware/analytics 15.0.1 → 16.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +164 -36
- package/dist/native/fbsdk.cjs +44 -1
- package/dist/native/fbsdk.cjs.map +1 -1
- package/dist/native/fbsdk.d.cts +23 -1
- package/dist/native/fbsdk.d.cts.map +1 -1
- package/dist/native/fbsdk.d.mts +23 -1
- package/dist/native/fbsdk.d.mts.map +1 -1
- package/dist/native/fbsdk.mjs +44 -3
- package/dist/native/fbsdk.mjs.map +1 -1
- package/dist/native/firebase.cjs +27 -0
- package/dist/native/firebase.cjs.map +1 -1
- package/dist/native/firebase.d.cts +11 -0
- package/dist/native/firebase.d.cts.map +1 -1
- package/dist/native/firebase.d.mts +11 -0
- package/dist/native/firebase.d.mts.map +1 -1
- package/dist/native/firebase.mjs +27 -2
- package/dist/native/firebase.mjs.map +1 -1
- package/dist/next/index.cjs +10 -123
- package/dist/next/index.cjs.map +1 -1
- package/dist/next/index.d.cts +2 -31
- package/dist/next/index.d.cts.map +1 -1
- package/dist/next/index.d.mts +2 -31
- package/dist/next/index.d.mts.map +1 -1
- package/dist/next/index.mjs +10 -123
- package/dist/next/index.mjs.map +1 -1
- package/dist/react/index.cjs +45 -0
- package/dist/react/index.cjs.map +1 -0
- package/dist/react/index.d.cts +15 -0
- package/dist/react/index.d.cts.map +1 -0
- package/dist/react/index.d.mts +15 -0
- package/dist/react/index.d.mts.map +1 -0
- package/dist/react/index.mjs +43 -0
- package/dist/react/index.mjs.map +1 -0
- package/dist/react/use-feature-flag.cjs +23 -0
- package/dist/react/use-feature-flag.cjs.map +1 -0
- package/dist/react/use-feature-flag.d.cts +10 -0
- package/dist/react/use-feature-flag.d.cts.map +1 -0
- package/dist/react/use-feature-flag.d.mts +10 -0
- package/dist/react/use-feature-flag.d.mts.map +1 -0
- package/dist/react/use-feature-flag.mjs +22 -0
- package/dist/react/use-feature-flag.mjs.map +1 -0
- package/dist/server/conversions-api-error.cjs +20 -0
- package/dist/server/conversions-api-error.cjs.map +1 -0
- package/dist/server/conversions-api-error.d.cts +17 -0
- package/dist/server/conversions-api-error.d.cts.map +1 -0
- package/dist/server/conversions-api-error.d.mts +17 -0
- package/dist/server/conversions-api-error.d.mts.map +1 -0
- package/dist/server/conversions-api-error.mjs +19 -0
- package/dist/server/conversions-api-error.mjs.map +1 -0
- package/dist/server/google-data-manager.cjs +24 -26
- package/dist/server/google-data-manager.cjs.map +1 -1
- package/dist/server/google-data-manager.d.cts +13 -5
- package/dist/server/google-data-manager.d.cts.map +1 -1
- package/dist/server/google-data-manager.d.mts +13 -5
- package/dist/server/google-data-manager.d.mts.map +1 -1
- package/dist/server/google-data-manager.mjs +24 -27
- package/dist/server/google-data-manager.mjs.map +1 -1
- package/dist/server/index.cjs +11 -0
- package/dist/server/index.d.cts +10 -7
- package/dist/server/index.d.mts +10 -7
- package/dist/server/index.mjs +9 -7
- package/dist/server/linkedin-conversions-api.cjs +29 -23
- package/dist/server/linkedin-conversions-api.cjs.map +1 -1
- package/dist/server/linkedin-conversions-api.d.cts +7 -2
- package/dist/server/linkedin-conversions-api.d.cts.map +1 -1
- package/dist/server/linkedin-conversions-api.d.mts +7 -2
- package/dist/server/linkedin-conversions-api.d.mts.map +1 -1
- package/dist/server/linkedin-conversions-api.mjs +29 -24
- package/dist/server/linkedin-conversions-api.mjs.map +1 -1
- package/dist/server/meta-capi.cjs +32 -31
- package/dist/server/meta-capi.cjs.map +1 -1
- package/dist/server/meta-capi.d.cts +12 -3
- package/dist/server/meta-capi.d.cts.map +1 -1
- package/dist/server/meta-capi.d.mts +12 -3
- package/dist/server/meta-capi.d.mts.map +1 -1
- package/dist/server/meta-capi.mjs +33 -33
- package/dist/server/meta-capi.mjs.map +1 -1
- package/dist/server/microsoft-conversions-api.cjs +33 -28
- package/dist/server/microsoft-conversions-api.cjs.map +1 -1
- package/dist/server/microsoft-conversions-api.d.cts +14 -2
- package/dist/server/microsoft-conversions-api.d.cts.map +1 -1
- package/dist/server/microsoft-conversions-api.d.mts +14 -2
- package/dist/server/microsoft-conversions-api.d.mts.map +1 -1
- package/dist/server/microsoft-conversions-api.mjs +33 -29
- package/dist/server/microsoft-conversions-api.mjs.map +1 -1
- package/dist/server/openai-conversions-api.cjs +20 -18
- package/dist/server/openai-conversions-api.cjs.map +1 -1
- package/dist/server/openai-conversions-api.d.cts +7 -0
- package/dist/server/openai-conversions-api.d.cts.map +1 -1
- package/dist/server/openai-conversions-api.d.mts +7 -0
- package/dist/server/openai-conversions-api.d.mts.map +1 -1
- package/dist/server/openai-conversions-api.mjs +21 -20
- package/dist/server/openai-conversions-api.mjs.map +1 -1
- package/dist/server/reddit-conversions-api.cjs +20 -18
- package/dist/server/reddit-conversions-api.cjs.map +1 -1
- package/dist/server/reddit-conversions-api.d.cts +8 -1
- package/dist/server/reddit-conversions-api.d.cts.map +1 -1
- package/dist/server/reddit-conversions-api.d.mts +8 -1
- package/dist/server/reddit-conversions-api.d.mts.map +1 -1
- package/dist/server/reddit-conversions-api.mjs +21 -20
- package/dist/server/reddit-conversions-api.mjs.map +1 -1
- package/dist/server/setup-conversions.cjs +62 -0
- package/dist/server/setup-conversions.cjs.map +1 -0
- package/dist/server/setup-conversions.d.cts +97 -0
- package/dist/server/setup-conversions.d.cts.map +1 -0
- package/dist/server/setup-conversions.d.mts +97 -0
- package/dist/server/setup-conversions.d.mts.map +1 -0
- package/dist/server/setup-conversions.mjs +60 -0
- package/dist/server/setup-conversions.mjs.map +1 -0
- package/dist/setup/index.cjs +4 -4
- package/dist/setup/index.cjs.map +1 -1
- package/dist/setup/index.d.cts +16 -6
- package/dist/setup/index.d.cts.map +1 -1
- package/dist/setup/index.d.mts +16 -6
- package/dist/setup/index.d.mts.map +1 -1
- package/dist/setup/index.mjs +4 -4
- package/dist/setup/index.mjs.map +1 -1
- package/dist/tanstack/index.cjs +0 -2
- package/dist/tanstack/index.d.cts +1 -2
- package/dist/tanstack/index.d.mts +1 -2
- package/dist/tanstack/index.mjs +1 -3
- package/dist/third-parties/analytics-props.cjs +28 -0
- package/dist/third-parties/analytics-props.cjs.map +1 -0
- package/dist/third-parties/analytics-props.d.cts +23 -0
- package/dist/third-parties/analytics-props.d.cts.map +1 -0
- package/dist/third-parties/analytics-props.d.mts +23 -0
- package/dist/third-parties/analytics-props.d.mts.map +1 -0
- package/dist/third-parties/analytics-props.mjs +26 -0
- package/dist/third-parties/analytics-props.mjs.map +1 -0
- package/dist/third-parties/google-analytics.cjs +32 -0
- package/dist/third-parties/google-analytics.cjs.map +1 -1
- package/dist/third-parties/google-analytics.d.cts +11 -1
- package/dist/third-parties/google-analytics.d.cts.map +1 -1
- package/dist/third-parties/google-analytics.d.mts +11 -1
- package/dist/third-parties/google-analytics.d.mts.map +1 -1
- package/dist/third-parties/google-analytics.mjs +32 -1
- package/dist/third-parties/google-analytics.mjs.map +1 -1
- package/dist/third-parties/index.cjs +16 -0
- package/dist/third-parties/index.d.cts +9 -7
- package/dist/third-parties/index.d.mts +9 -7
- package/dist/third-parties/index.mjs +9 -7
- package/dist/third-parties/integration.cjs +46 -0
- package/dist/third-parties/integration.cjs.map +1 -0
- package/dist/third-parties/integration.d.cts +61 -0
- package/dist/third-parties/integration.d.cts.map +1 -0
- package/dist/third-parties/integration.d.mts +61 -0
- package/dist/third-parties/integration.d.mts.map +1 -0
- package/dist/third-parties/integration.mjs +43 -0
- package/dist/third-parties/integration.mjs.map +1 -0
- package/dist/third-parties/linkedin-insight-tag.cjs +29 -0
- package/dist/third-parties/linkedin-insight-tag.cjs.map +1 -1
- package/dist/third-parties/linkedin-insight-tag.d.cts +14 -8
- package/dist/third-parties/linkedin-insight-tag.d.cts.map +1 -1
- package/dist/third-parties/linkedin-insight-tag.d.mts +14 -8
- package/dist/third-parties/linkedin-insight-tag.d.mts.map +1 -1
- package/dist/third-parties/linkedin-insight-tag.mjs +29 -1
- package/dist/third-parties/linkedin-insight-tag.mjs.map +1 -1
- package/dist/third-parties/meta-pixel.cjs +32 -0
- package/dist/third-parties/meta-pixel.cjs.map +1 -1
- package/dist/third-parties/meta-pixel.d.cts +7 -0
- package/dist/third-parties/meta-pixel.d.cts.map +1 -1
- package/dist/third-parties/meta-pixel.d.mts +7 -0
- package/dist/third-parties/meta-pixel.d.mts.map +1 -1
- package/dist/third-parties/meta-pixel.mjs +33 -2
- package/dist/third-parties/meta-pixel.mjs.map +1 -1
- package/dist/third-parties/microsoft-uet.cjs +54 -0
- package/dist/third-parties/microsoft-uet.cjs.map +1 -1
- package/dist/third-parties/microsoft-uet.d.cts +36 -0
- package/dist/third-parties/microsoft-uet.d.cts.map +1 -1
- package/dist/third-parties/microsoft-uet.d.mts +36 -0
- package/dist/third-parties/microsoft-uet.d.mts.map +1 -1
- package/dist/third-parties/microsoft-uet.mjs +52 -1
- package/dist/third-parties/microsoft-uet.mjs.map +1 -1
- package/dist/third-parties/openai-pixel.cjs +29 -0
- package/dist/third-parties/openai-pixel.cjs.map +1 -1
- package/dist/third-parties/openai-pixel.d.cts +7 -0
- package/dist/third-parties/openai-pixel.d.cts.map +1 -1
- package/dist/third-parties/openai-pixel.d.mts +7 -0
- package/dist/third-parties/openai-pixel.d.mts.map +1 -1
- package/dist/third-parties/openai-pixel.mjs +30 -2
- package/dist/third-parties/openai-pixel.mjs.map +1 -1
- package/dist/third-parties/posthog.cjs +97 -4
- package/dist/third-parties/posthog.cjs.map +1 -1
- package/dist/third-parties/posthog.d.cts +56 -1
- package/dist/third-parties/posthog.d.cts.map +1 -1
- package/dist/third-parties/posthog.d.mts +56 -1
- package/dist/third-parties/posthog.d.mts.map +1 -1
- package/dist/third-parties/posthog.mjs +91 -2
- package/dist/third-parties/posthog.mjs.map +1 -1
- package/dist/third-parties/reddit-pixel.cjs +30 -0
- package/dist/third-parties/reddit-pixel.cjs.map +1 -1
- package/dist/third-parties/reddit-pixel.d.cts +7 -0
- package/dist/third-parties/reddit-pixel.d.cts.map +1 -1
- package/dist/third-parties/reddit-pixel.d.mts +7 -0
- package/dist/third-parties/reddit-pixel.d.mts.map +1 -1
- package/dist/third-parties/reddit-pixel.mjs +31 -2
- package/dist/third-parties/reddit-pixel.mjs.map +1 -1
- package/dist/track/fbq.cjs +6 -1
- package/dist/track/fbq.cjs.map +1 -1
- package/dist/track/fbq.d.cts +2 -0
- package/dist/track/fbq.d.cts.map +1 -1
- package/dist/track/fbq.d.mts +2 -0
- package/dist/track/fbq.d.mts.map +1 -1
- package/dist/track/fbq.mjs +6 -2
- package/dist/track/fbq.mjs.map +1 -1
- package/dist/track/index.cjs +7 -7
- package/dist/track/index.cjs.map +1 -1
- package/dist/track/index.d.cts.map +1 -1
- package/dist/track/index.d.mts.map +1 -1
- package/dist/track/index.mjs +7 -7
- package/dist/track/index.mjs.map +1 -1
- package/dist/track/oaiq.cjs +5 -0
- package/dist/track/oaiq.cjs.map +1 -1
- package/dist/track/oaiq.d.cts +2 -0
- package/dist/track/oaiq.d.cts.map +1 -1
- package/dist/track/oaiq.d.mts +2 -0
- package/dist/track/oaiq.d.mts.map +1 -1
- package/dist/track/oaiq.mjs +5 -1
- package/dist/track/oaiq.mjs.map +1 -1
- package/dist/track/rdt.cjs +5 -0
- package/dist/track/rdt.cjs.map +1 -1
- package/dist/track/rdt.d.cts +2 -0
- package/dist/track/rdt.d.cts.map +1 -1
- package/dist/track/rdt.d.mts +2 -0
- package/dist/track/rdt.d.mts.map +1 -1
- package/dist/track/rdt.mjs +5 -1
- package/dist/track/rdt.mjs.map +1 -1
- package/dist/visitor/index.cjs +3 -3
- package/dist/visitor/index.cjs.map +1 -1
- package/dist/visitor/index.mjs +3 -3
- package/dist/visitor/index.mjs.map +1 -1
- package/package.json +11 -39
- package/dist/react-router/index.cjs +0 -160
- package/dist/react-router/index.cjs.map +0 -1
- package/dist/react-router/index.d.cts +0 -22
- package/dist/react-router/index.d.cts.map +0 -1
- package/dist/react-router/index.d.mts +0 -22
- package/dist/react-router/index.d.mts.map +0 -1
- package/dist/react-router/index.mjs +0 -159
- package/dist/react-router/index.mjs.map +0 -1
- package/dist/server/legacy.cjs +0 -3
- package/dist/server/legacy.d.cts +0 -2
- package/dist/server/legacy.d.mts +0 -2
- package/dist/server/legacy.mjs +0 -1
- package/dist/server/meta-conversions-api.cjs +0 -205
- package/dist/server/meta-conversions-api.cjs.map +0 -1
- package/dist/server/meta-conversions-api.d.cts +0 -8
- package/dist/server/meta-conversions-api.d.cts.map +0 -1
- package/dist/server/meta-conversions-api.d.mts +0 -8
- package/dist/server/meta-conversions-api.d.mts.map +0 -1
- package/dist/server/meta-conversions-api.mjs +0 -201
- package/dist/server/meta-conversions-api.mjs.map +0 -1
- package/dist/tanstack/analytics.cjs +0 -184
- package/dist/tanstack/analytics.cjs.map +0 -1
- package/dist/tanstack/analytics.d.cts +0 -33
- package/dist/tanstack/analytics.d.cts.map +0 -1
- package/dist/tanstack/analytics.d.mts +0 -33
- package/dist/tanstack/analytics.d.mts.map +0 -1
- package/dist/tanstack/analytics.mjs +0 -183
- package/dist/tanstack/analytics.mjs.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"openai-pixel.cjs","names":["NON_AD_EVENTS","mapOAIEvent","APP_EVENTS","oaiCustomEventName","getFirst","sha256","normalizeOAIPhone","normalizeOAIName"],"sources":["../../src/third-parties/openai-pixel.ts"],"sourcesContent":["import type { UpdateVisitorDTO } from '../schema/index';\nimport {\n APP_EVENTS,\n NON_AD_EVENTS,\n type OAIQ,\n type OAIQUser,\n mapOAIEvent,\n normalizeOAIName,\n normalizeOAIPhone,\n oaiCustomEventName,\n} from '../track/oaiq';\nimport type { EventName, TrackName, TrackProperties } from '../track/types';\nimport { getFirst } from '../utils/field';\nimport { sha256 } from '../utils/sha256';\n\ndeclare global {\n interface Window {\n /** Undefined until the OpenAI pixel script has loaded. */\n oaiq?: OAIQ['oaiq'];\n }\n}\n\n/** Drop `undefined` fields so the SDK only receives populated values. */\n// oxlint-disable-next-line @typescript-eslint/no-explicit-any\nfunction clean(value: unknown): any {\n return JSON.parse(JSON.stringify(value));\n}\n\n/**\n * Forward an internal track event to the OpenAI measurement pixel.\n * `eventId` is reused as the OpenAI `event_id` so browser events deduplicate against the\n * Conversions API. https://developers.openai.com/ads/measurement-pixel\n */\nexport function sendOpenAIEvent<T extends EventName>(\n name: TrackName<T>,\n properties?: TrackProperties<T>,\n eventId?: string\n) {\n if (typeof window === 'undefined' || !window.oaiq) {\n console.warn('oaiq has not been initialized');\n return false;\n }\n if (NON_AD_EVENTS.includes(name)) return;\n if (window.location.host.includes('127.0.0.1')) return;\n if (window.location.host.includes('localhost')) return;\n\n const { type, data } = mapOAIEvent(name, properties);\n // OpenAI takes the app events from the Conversions API only.\n if (APP_EVENTS.includes(type as never)) return;\n if (type === 'custom') {\n // Named as the Conversions API names it, so the two deduplicate; skipped when it cannot be.\n const custom_event_name = oaiCustomEventName(name);\n if (!custom_event_name) return;\n window.oaiq('measure', 'custom', clean(data), { event_id: eventId, custom_event_name });\n } else {\n window.oaiq('measure', type, clean(data), { event_id: eventId });\n }\n}\n\n/**\n * Re-initialize the pixel with hashed user identity for better conversion matching. Email, phone,\n * external id and names are normalized as OpenAI documents and hashed client-side; geographic\n * fields are sent raw. Hashing is asynchronous, so the `init` call is deferred until the digests\n * resolve.\n */\nexport function setOpenAIUser(pixelId: string) {\n return ({ user_id, user_data }: UpdateVisitorDTO) => {\n if (typeof window === 'undefined' || !window.oaiq) {\n console.warn('oaiq has not been initialized');\n return;\n }\n // Capture the narrowed reference so the deferred `init` closure keeps it non-optional.\n const oaiq = window.oaiq;\n\n const email = getFirst(user_data?.email)?.trim().toLowerCase() || undefined;\n const phone = getFirst(user_data?.phone_number);\n const address = getFirst(user_data?.address);\n\n const base: OAIQUser = {\n country: address?.country?.trim().toUpperCase(),\n city: address?.city?.trim(),\n region: address?.region?.trim(),\n postal_code: address?.postal_code?.trim(),\n };\n\n const init = (hashed: Partial<OAIQUser>) => {\n oaiq('init', { pixelId, user: clean({ ...base, ...hashed }) });\n };\n\n const hash = (value: string | undefined) => (value ? sha256(value) : undefined);\n Promise.all([\n hash(email),\n hash(phone ? normalizeOAIPhone(phone) : undefined),\n hash(user_id?.trim()),\n hash(normalizeOAIName(address?.first_name)),\n hash(normalizeOAIName(address?.last_name)),\n ])\n .then(([email_sha256, phone_number_sha256, external_id_sha256, first, last]) =>\n init({\n email_sha256,\n phone_number_sha256,\n external_id_sha256,\n first_name_sha256: first,\n last_name_sha256: last,\n })\n )\n .catch(() => init({}));\n };\n}\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"openai-pixel.cjs","names":["NON_AD_EVENTS","mapOAIEvent","APP_EVENTS","oaiCustomEventName","getFirst","sha256","normalizeOAIPhone","normalizeOAIName","adsTracker","adEvents","isStandardOAIEvent"],"sources":["../../src/third-parties/openai-pixel.ts"],"sourcesContent":["import type { UpdateVisitorDTO } from '../schema/index';\nimport {\n APP_EVENTS,\n NON_AD_EVENTS,\n type OAIQ,\n type OAIQUser,\n isStandardOAIEvent,\n mapOAIEvent,\n normalizeOAIName,\n normalizeOAIPhone,\n oaiCustomEventName,\n} from '../track/oaiq';\nimport type { EventName, TrackName, TrackProperties } from '../track/types';\nimport { getFirst } from '../utils/field';\nimport { sha256 } from '../utils/sha256';\nimport { type AdsOptions, type Integration, adEvents, adsTracker } from './integration';\n\ndeclare global {\n interface Window {\n /** Undefined until the OpenAI pixel script has loaded. */\n oaiq?: OAIQ['oaiq'];\n }\n}\n\n/** Drop `undefined` fields so the SDK only receives populated values. */\n// oxlint-disable-next-line @typescript-eslint/no-explicit-any\nfunction clean(value: unknown): any {\n return JSON.parse(JSON.stringify(value));\n}\n\n/**\n * Forward an internal track event to the OpenAI measurement pixel.\n * `eventId` is reused as the OpenAI `event_id` so browser events deduplicate against the\n * Conversions API. https://developers.openai.com/ads/measurement-pixel\n */\nexport function sendOpenAIEvent<T extends EventName>(\n name: TrackName<T>,\n properties?: TrackProperties<T>,\n eventId?: string\n) {\n if (typeof window === 'undefined' || !window.oaiq) {\n console.warn('oaiq has not been initialized');\n return false;\n }\n if (NON_AD_EVENTS.includes(name)) return;\n if (window.location.host.includes('127.0.0.1')) return;\n if (window.location.host.includes('localhost')) return;\n\n const { type, data } = mapOAIEvent(name, properties);\n // OpenAI takes the app events from the Conversions API only.\n if (APP_EVENTS.includes(type as never)) return;\n if (type === 'custom') {\n // Named as the Conversions API names it, so the two deduplicate; skipped when it cannot be.\n const custom_event_name = oaiCustomEventName(name);\n if (!custom_event_name) return;\n window.oaiq('measure', 'custom', clean(data), { event_id: eventId, custom_event_name });\n } else {\n window.oaiq('measure', type, clean(data), { event_id: eventId });\n }\n}\n\n/**\n * Re-initialize the pixel with hashed user identity for better conversion matching. Email, phone,\n * external id and names are normalized as OpenAI documents and hashed client-side; geographic\n * fields are sent raw. Hashing is asynchronous, so the `init` call is deferred until the digests\n * resolve.\n */\nexport function setOpenAIUser(pixelId: string) {\n return ({ user_id, user_data }: UpdateVisitorDTO) => {\n if (typeof window === 'undefined' || !window.oaiq) {\n console.warn('oaiq has not been initialized');\n return;\n }\n // Capture the narrowed reference so the deferred `init` closure keeps it non-optional.\n const oaiq = window.oaiq;\n\n const email = getFirst(user_data?.email)?.trim().toLowerCase() || undefined;\n const phone = getFirst(user_data?.phone_number);\n const address = getFirst(user_data?.address);\n\n const base: OAIQUser = {\n country: address?.country?.trim().toUpperCase(),\n city: address?.city?.trim(),\n region: address?.region?.trim(),\n postal_code: address?.postal_code?.trim(),\n };\n\n const init = (hashed: Partial<OAIQUser>) => {\n oaiq('init', { pixelId, user: clean({ ...base, ...hashed }) });\n };\n\n const hash = (value: string | undefined) => (value ? sha256(value) : undefined);\n Promise.all([\n hash(email),\n hash(phone ? normalizeOAIPhone(phone) : undefined),\n hash(user_id?.trim()),\n hash(normalizeOAIName(address?.first_name)),\n hash(normalizeOAIName(address?.last_name)),\n ])\n .then(([email_sha256, phone_number_sha256, external_id_sha256, first, last]) =>\n init({\n email_sha256,\n phone_number_sha256,\n external_id_sha256,\n first_name_sha256: first,\n last_name_sha256: last,\n })\n )\n .catch(() => init({}));\n };\n}\n\n/** OpenAI measurement pixel: the events `mapOAIEvent` maps to a standard event, and `customEvents`. */\n/** OpenAI's configuration, shared by `openaiAds` and `openaiConversions` on the server. */\nexport interface OpenAIAdsOptions extends AdsOptions {\n pixelId: string;\n}\n\nexport function openaiAds(options: OpenAIAdsOptions): Integration {\n return {\n type: 'ads',\n track: adsTracker(sendOpenAIEvent, adEvents(isStandardOAIEvent, options.customEvents)),\n setUser: setOpenAIUser(options.pixelId),\n script: {\n id: 'openai-pixel',\n inline: `\n (function (w, d, s, u) {\n if (w.oaiq) return;\n var q = function () {\n q.q.push(arguments);\n };\n q.q = [];\n w.oaiq = q;\n var js = d.createElement(s);\n js.async = true;\n js.src = u;\n var f = d.getElementsByTagName(s)[0];\n f.parentNode.insertBefore(js, f);\n })(window, document, \"script\", \"https://bzrcdn.openai.com/sdk/oaiq.min.js\");\n oaiq(\"init\", { pixelId: ${JSON.stringify(options.pixelId)} });\n oaiq(\"measure\", \"page_viewed\", { type: \"contents\" });\n `,\n },\n };\n}\n"],"mappings":";;;;;;;AA0BA,SAAS,MAAM,OAAqB;CAClC,OAAO,KAAK,MAAM,KAAK,UAAU,KAAK,CAAC;AACzC;;;;;;AAOA,SAAgB,gBACd,MACA,YACA,SACA;CACA,IAAI,OAAO,WAAW,eAAe,CAAC,OAAO,MAAM;EACjD,QAAQ,KAAK,+BAA+B;EAC5C,OAAO;CACT;CACA,IAAIA,mBAAAA,cAAc,SAAS,IAAI,GAAG;CAClC,IAAI,OAAO,SAAS,KAAK,SAAS,WAAW,GAAG;CAChD,IAAI,OAAO,SAAS,KAAK,SAAS,WAAW,GAAG;CAEhD,MAAM,EAAE,MAAM,SAASC,mBAAAA,YAAY,MAAM,UAAU;CAEnD,IAAIC,mBAAAA,WAAW,SAAS,IAAa,GAAG;CACxC,IAAI,SAAS,UAAU;EAErB,MAAM,oBAAoBC,mBAAAA,mBAAmB,IAAI;EACjD,IAAI,CAAC,mBAAmB;EACxB,OAAO,KAAK,WAAW,UAAU,MAAM,IAAI,GAAG;GAAE,UAAU;GAAS;EAAkB,CAAC;CACxF,OACE,OAAO,KAAK,WAAW,MAAM,MAAM,IAAI,GAAG,EAAE,UAAU,QAAQ,CAAC;AAEnE;;;;;;;AAQA,SAAgB,cAAc,SAAiB;CAC7C,QAAQ,EAAE,SAAS,gBAAkC;EACnD,IAAI,OAAO,WAAW,eAAe,CAAC,OAAO,MAAM;GACjD,QAAQ,KAAK,+BAA+B;GAC5C;EACF;EAEA,MAAM,OAAO,OAAO;EAEpB,MAAM,QAAQC,oBAAAA,SAAS,WAAW,KAAK,CAAC,EAAE,KAAK,CAAC,CAAC,YAAY,KAAK,KAAA;EAClE,MAAM,QAAQA,oBAAAA,SAAS,WAAW,YAAY;EAC9C,MAAM,UAAUA,oBAAAA,SAAS,WAAW,OAAO;EAE3C,MAAM,OAAiB;GACrB,SAAS,SAAS,SAAS,KAAK,CAAC,CAAC,YAAY;GAC9C,MAAM,SAAS,MAAM,KAAK;GAC1B,QAAQ,SAAS,QAAQ,KAAK;GAC9B,aAAa,SAAS,aAAa,KAAK;EAC1C;EAEA,MAAM,QAAQ,WAA8B;GAC1C,KAAK,QAAQ;IAAE;IAAS,MAAM,MAAM;KAAE,GAAG;KAAM,GAAG;IAAO,CAAC;GAAE,CAAC;EAC/D;EAEA,MAAM,QAAQ,UAA+B,QAAQC,qBAAAA,OAAO,KAAK,IAAI,KAAA;EACrE,QAAQ,IAAI;GACV,KAAK,KAAK;GACV,KAAK,QAAQC,mBAAAA,kBAAkB,KAAK,IAAI,KAAA,CAAS;GACjD,KAAK,SAAS,KAAK,CAAC;GACpB,KAAKC,mBAAAA,iBAAiB,SAAS,UAAU,CAAC;GAC1C,KAAKA,mBAAAA,iBAAiB,SAAS,SAAS,CAAC;EAC3C,CAAC,CAAC,CACC,MAAM,CAAC,cAAc,qBAAqB,oBAAoB,OAAO,UACpE,KAAK;GACH;GACA;GACA;GACA,mBAAmB;GACnB,kBAAkB;EACpB,CAAC,CACH,CAAC,CACA,YAAY,KAAK,CAAC,CAAC,CAAC;CACzB;AACF;AAQA,SAAgB,UAAU,SAAwC;CAChE,OAAO;EACL,MAAM;EACN,OAAOC,kCAAAA,WAAW,iBAAiBC,kCAAAA,SAASC,mBAAAA,oBAAoB,QAAQ,YAAY,CAAC;EACrF,SAAS,cAAc,QAAQ,OAAO;EACtC,QAAQ;GACN,IAAI;GACJ,QAAQ;;;;;;;;;;;;;;kCAcoB,KAAK,UAAU,QAAQ,OAAO,EAAE;;;EAG9D;CACF;AACF"}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { EventName, TrackName, TrackProperties } from "../track/types.cjs";
|
|
2
2
|
import { UpdateVisitorDTO } from "../schema/index.cjs";
|
|
3
|
+
import { AdsOptions, Integration } from "./integration.cjs";
|
|
3
4
|
import { OAIQ } from "../track/oaiq.cjs";
|
|
4
5
|
declare global {
|
|
5
6
|
interface Window {
|
|
@@ -20,4 +21,10 @@ export declare function sendOpenAIEvent<T extends EventName>(name: TrackName<T>,
|
|
|
20
21
|
* resolve.
|
|
21
22
|
*/
|
|
22
23
|
export declare function setOpenAIUser(pixelId: string): ({ user_id, user_data }: UpdateVisitorDTO) => void;
|
|
24
|
+
/** OpenAI measurement pixel: the events `mapOAIEvent` maps to a standard event, and `customEvents`. */
|
|
25
|
+
/** OpenAI's configuration, shared by `openaiAds` and `openaiConversions` on the server. */
|
|
26
|
+
export interface OpenAIAdsOptions extends AdsOptions {
|
|
27
|
+
pixelId: string;
|
|
28
|
+
}
|
|
29
|
+
export declare function openaiAds(options: OpenAIAdsOptions): Integration;
|
|
23
30
|
//# sourceMappingURL=openai-pixel.d.cts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"openai-pixel.d.cts","names":[],"sources":["../../src/third-parties/openai-pixel.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"openai-pixel.d.cts","names":[],"sources":["../../src/third-parties/openai-pixel.ts"],"mappings":";;;;QAiBQ;YACI;;IAER,OAAO;;;;;;;;wBAeK,gBAAgB,UAAU,WACxC,MAAM,UAAU,IAChB,aAAa,gBAAgB,IAC7B;;;;;;;wBA6Bc,cAAc,qBAAe,SAAA,aACX;;;iBA8CjB,yBAAyB;EACxC;;wBAGc,UAAU,SAAS,mBAAmB"}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { EventName, TrackName, TrackProperties } from "../track/types.mjs";
|
|
2
2
|
import { UpdateVisitorDTO } from "../schema/index.mjs";
|
|
3
|
+
import { AdsOptions, Integration } from "./integration.mjs";
|
|
3
4
|
import { OAIQ } from "../track/oaiq.mjs";
|
|
4
5
|
declare global {
|
|
5
6
|
interface Window {
|
|
@@ -20,4 +21,10 @@ export declare function sendOpenAIEvent<T extends EventName>(name: TrackName<T>,
|
|
|
20
21
|
* resolve.
|
|
21
22
|
*/
|
|
22
23
|
export declare function setOpenAIUser(pixelId: string): ({ user_id, user_data }: UpdateVisitorDTO) => void;
|
|
24
|
+
/** OpenAI measurement pixel: the events `mapOAIEvent` maps to a standard event, and `customEvents`. */
|
|
25
|
+
/** OpenAI's configuration, shared by `openaiAds` and `openaiConversions` on the server. */
|
|
26
|
+
export interface OpenAIAdsOptions extends AdsOptions {
|
|
27
|
+
pixelId: string;
|
|
28
|
+
}
|
|
29
|
+
export declare function openaiAds(options: OpenAIAdsOptions): Integration;
|
|
23
30
|
//# sourceMappingURL=openai-pixel.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"openai-pixel.d.mts","names":[],"sources":["../../src/third-parties/openai-pixel.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"openai-pixel.d.mts","names":[],"sources":["../../src/third-parties/openai-pixel.ts"],"mappings":";;;;QAiBQ;YACI;;IAER,OAAO;;;;;;;;wBAeK,gBAAgB,UAAU,WACxC,MAAM,UAAU,IAChB,aAAa,gBAAgB,IAC7B;;;;;;;wBA6Bc,cAAc,qBAAe,SAAA,aACX;;;iBA8CjB,yBAAyB;EACxC;;wBAGc,UAAU,SAAS,mBAAmB"}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { getFirst } from "../utils/field.mjs";
|
|
2
2
|
import { sha256 } from "../utils/sha256.mjs";
|
|
3
|
-
import {
|
|
3
|
+
import { adEvents, adsTracker } from "./integration.mjs";
|
|
4
|
+
import { APP_EVENTS, NON_AD_EVENTS, isStandardOAIEvent, mapOAIEvent, normalizeOAIName, normalizeOAIPhone, oaiCustomEventName } from "../track/oaiq.mjs";
|
|
4
5
|
// src/third-parties/openai-pixel.ts
|
|
5
6
|
/** Drop `undefined` fields so the SDK only receives populated values. */
|
|
6
7
|
function clean(value) {
|
|
@@ -77,6 +78,33 @@ function setOpenAIUser(pixelId) {
|
|
|
77
78
|
})).catch(() => init({}));
|
|
78
79
|
};
|
|
79
80
|
}
|
|
80
|
-
|
|
81
|
+
function openaiAds(options) {
|
|
82
|
+
return {
|
|
83
|
+
type: "ads",
|
|
84
|
+
track: adsTracker(sendOpenAIEvent, adEvents(isStandardOAIEvent, options.customEvents)),
|
|
85
|
+
setUser: setOpenAIUser(options.pixelId),
|
|
86
|
+
script: {
|
|
87
|
+
id: "openai-pixel",
|
|
88
|
+
inline: `
|
|
89
|
+
(function (w, d, s, u) {
|
|
90
|
+
if (w.oaiq) return;
|
|
91
|
+
var q = function () {
|
|
92
|
+
q.q.push(arguments);
|
|
93
|
+
};
|
|
94
|
+
q.q = [];
|
|
95
|
+
w.oaiq = q;
|
|
96
|
+
var js = d.createElement(s);
|
|
97
|
+
js.async = true;
|
|
98
|
+
js.src = u;
|
|
99
|
+
var f = d.getElementsByTagName(s)[0];
|
|
100
|
+
f.parentNode.insertBefore(js, f);
|
|
101
|
+
})(window, document, "script", "https://bzrcdn.openai.com/sdk/oaiq.min.js");
|
|
102
|
+
oaiq("init", { pixelId: ${JSON.stringify(options.pixelId)} });
|
|
103
|
+
oaiq("measure", "page_viewed", { type: "contents" });
|
|
104
|
+
`
|
|
105
|
+
}
|
|
106
|
+
};
|
|
107
|
+
}
|
|
108
|
+
export { openaiAds, sendOpenAIEvent, setOpenAIUser };
|
|
81
109
|
|
|
82
110
|
//# sourceMappingURL=openai-pixel.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"openai-pixel.mjs","names":[],"sources":["../../src/third-parties/openai-pixel.ts"],"sourcesContent":["import type { UpdateVisitorDTO } from '../schema/index';\nimport {\n APP_EVENTS,\n NON_AD_EVENTS,\n type OAIQ,\n type OAIQUser,\n mapOAIEvent,\n normalizeOAIName,\n normalizeOAIPhone,\n oaiCustomEventName,\n} from '../track/oaiq';\nimport type { EventName, TrackName, TrackProperties } from '../track/types';\nimport { getFirst } from '../utils/field';\nimport { sha256 } from '../utils/sha256';\n\ndeclare global {\n interface Window {\n /** Undefined until the OpenAI pixel script has loaded. */\n oaiq?: OAIQ['oaiq'];\n }\n}\n\n/** Drop `undefined` fields so the SDK only receives populated values. */\n// oxlint-disable-next-line @typescript-eslint/no-explicit-any\nfunction clean(value: unknown): any {\n return JSON.parse(JSON.stringify(value));\n}\n\n/**\n * Forward an internal track event to the OpenAI measurement pixel.\n * `eventId` is reused as the OpenAI `event_id` so browser events deduplicate against the\n * Conversions API. https://developers.openai.com/ads/measurement-pixel\n */\nexport function sendOpenAIEvent<T extends EventName>(\n name: TrackName<T>,\n properties?: TrackProperties<T>,\n eventId?: string\n) {\n if (typeof window === 'undefined' || !window.oaiq) {\n console.warn('oaiq has not been initialized');\n return false;\n }\n if (NON_AD_EVENTS.includes(name)) return;\n if (window.location.host.includes('127.0.0.1')) return;\n if (window.location.host.includes('localhost')) return;\n\n const { type, data } = mapOAIEvent(name, properties);\n // OpenAI takes the app events from the Conversions API only.\n if (APP_EVENTS.includes(type as never)) return;\n if (type === 'custom') {\n // Named as the Conversions API names it, so the two deduplicate; skipped when it cannot be.\n const custom_event_name = oaiCustomEventName(name);\n if (!custom_event_name) return;\n window.oaiq('measure', 'custom', clean(data), { event_id: eventId, custom_event_name });\n } else {\n window.oaiq('measure', type, clean(data), { event_id: eventId });\n }\n}\n\n/**\n * Re-initialize the pixel with hashed user identity for better conversion matching. Email, phone,\n * external id and names are normalized as OpenAI documents and hashed client-side; geographic\n * fields are sent raw. Hashing is asynchronous, so the `init` call is deferred until the digests\n * resolve.\n */\nexport function setOpenAIUser(pixelId: string) {\n return ({ user_id, user_data }: UpdateVisitorDTO) => {\n if (typeof window === 'undefined' || !window.oaiq) {\n console.warn('oaiq has not been initialized');\n return;\n }\n // Capture the narrowed reference so the deferred `init` closure keeps it non-optional.\n const oaiq = window.oaiq;\n\n const email = getFirst(user_data?.email)?.trim().toLowerCase() || undefined;\n const phone = getFirst(user_data?.phone_number);\n const address = getFirst(user_data?.address);\n\n const base: OAIQUser = {\n country: address?.country?.trim().toUpperCase(),\n city: address?.city?.trim(),\n region: address?.region?.trim(),\n postal_code: address?.postal_code?.trim(),\n };\n\n const init = (hashed: Partial<OAIQUser>) => {\n oaiq('init', { pixelId, user: clean({ ...base, ...hashed }) });\n };\n\n const hash = (value: string | undefined) => (value ? sha256(value) : undefined);\n Promise.all([\n hash(email),\n hash(phone ? normalizeOAIPhone(phone) : undefined),\n hash(user_id?.trim()),\n hash(normalizeOAIName(address?.first_name)),\n hash(normalizeOAIName(address?.last_name)),\n ])\n .then(([email_sha256, phone_number_sha256, external_id_sha256, first, last]) =>\n init({\n email_sha256,\n phone_number_sha256,\n external_id_sha256,\n first_name_sha256: first,\n last_name_sha256: last,\n })\n )\n .catch(() => init({}));\n };\n}\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"openai-pixel.mjs","names":[],"sources":["../../src/third-parties/openai-pixel.ts"],"sourcesContent":["import type { UpdateVisitorDTO } from '../schema/index';\nimport {\n APP_EVENTS,\n NON_AD_EVENTS,\n type OAIQ,\n type OAIQUser,\n isStandardOAIEvent,\n mapOAIEvent,\n normalizeOAIName,\n normalizeOAIPhone,\n oaiCustomEventName,\n} from '../track/oaiq';\nimport type { EventName, TrackName, TrackProperties } from '../track/types';\nimport { getFirst } from '../utils/field';\nimport { sha256 } from '../utils/sha256';\nimport { type AdsOptions, type Integration, adEvents, adsTracker } from './integration';\n\ndeclare global {\n interface Window {\n /** Undefined until the OpenAI pixel script has loaded. */\n oaiq?: OAIQ['oaiq'];\n }\n}\n\n/** Drop `undefined` fields so the SDK only receives populated values. */\n// oxlint-disable-next-line @typescript-eslint/no-explicit-any\nfunction clean(value: unknown): any {\n return JSON.parse(JSON.stringify(value));\n}\n\n/**\n * Forward an internal track event to the OpenAI measurement pixel.\n * `eventId` is reused as the OpenAI `event_id` so browser events deduplicate against the\n * Conversions API. https://developers.openai.com/ads/measurement-pixel\n */\nexport function sendOpenAIEvent<T extends EventName>(\n name: TrackName<T>,\n properties?: TrackProperties<T>,\n eventId?: string\n) {\n if (typeof window === 'undefined' || !window.oaiq) {\n console.warn('oaiq has not been initialized');\n return false;\n }\n if (NON_AD_EVENTS.includes(name)) return;\n if (window.location.host.includes('127.0.0.1')) return;\n if (window.location.host.includes('localhost')) return;\n\n const { type, data } = mapOAIEvent(name, properties);\n // OpenAI takes the app events from the Conversions API only.\n if (APP_EVENTS.includes(type as never)) return;\n if (type === 'custom') {\n // Named as the Conversions API names it, so the two deduplicate; skipped when it cannot be.\n const custom_event_name = oaiCustomEventName(name);\n if (!custom_event_name) return;\n window.oaiq('measure', 'custom', clean(data), { event_id: eventId, custom_event_name });\n } else {\n window.oaiq('measure', type, clean(data), { event_id: eventId });\n }\n}\n\n/**\n * Re-initialize the pixel with hashed user identity for better conversion matching. Email, phone,\n * external id and names are normalized as OpenAI documents and hashed client-side; geographic\n * fields are sent raw. Hashing is asynchronous, so the `init` call is deferred until the digests\n * resolve.\n */\nexport function setOpenAIUser(pixelId: string) {\n return ({ user_id, user_data }: UpdateVisitorDTO) => {\n if (typeof window === 'undefined' || !window.oaiq) {\n console.warn('oaiq has not been initialized');\n return;\n }\n // Capture the narrowed reference so the deferred `init` closure keeps it non-optional.\n const oaiq = window.oaiq;\n\n const email = getFirst(user_data?.email)?.trim().toLowerCase() || undefined;\n const phone = getFirst(user_data?.phone_number);\n const address = getFirst(user_data?.address);\n\n const base: OAIQUser = {\n country: address?.country?.trim().toUpperCase(),\n city: address?.city?.trim(),\n region: address?.region?.trim(),\n postal_code: address?.postal_code?.trim(),\n };\n\n const init = (hashed: Partial<OAIQUser>) => {\n oaiq('init', { pixelId, user: clean({ ...base, ...hashed }) });\n };\n\n const hash = (value: string | undefined) => (value ? sha256(value) : undefined);\n Promise.all([\n hash(email),\n hash(phone ? normalizeOAIPhone(phone) : undefined),\n hash(user_id?.trim()),\n hash(normalizeOAIName(address?.first_name)),\n hash(normalizeOAIName(address?.last_name)),\n ])\n .then(([email_sha256, phone_number_sha256, external_id_sha256, first, last]) =>\n init({\n email_sha256,\n phone_number_sha256,\n external_id_sha256,\n first_name_sha256: first,\n last_name_sha256: last,\n })\n )\n .catch(() => init({}));\n };\n}\n\n/** OpenAI measurement pixel: the events `mapOAIEvent` maps to a standard event, and `customEvents`. */\n/** OpenAI's configuration, shared by `openaiAds` and `openaiConversions` on the server. */\nexport interface OpenAIAdsOptions extends AdsOptions {\n pixelId: string;\n}\n\nexport function openaiAds(options: OpenAIAdsOptions): Integration {\n return {\n type: 'ads',\n track: adsTracker(sendOpenAIEvent, adEvents(isStandardOAIEvent, options.customEvents)),\n setUser: setOpenAIUser(options.pixelId),\n script: {\n id: 'openai-pixel',\n inline: `\n (function (w, d, s, u) {\n if (w.oaiq) return;\n var q = function () {\n q.q.push(arguments);\n };\n q.q = [];\n w.oaiq = q;\n var js = d.createElement(s);\n js.async = true;\n js.src = u;\n var f = d.getElementsByTagName(s)[0];\n f.parentNode.insertBefore(js, f);\n })(window, document, \"script\", \"https://bzrcdn.openai.com/sdk/oaiq.min.js\");\n oaiq(\"init\", { pixelId: ${JSON.stringify(options.pixelId)} });\n oaiq(\"measure\", \"page_viewed\", { type: \"contents\" });\n `,\n },\n };\n}\n"],"mappings":";;;;;;AA0BA,SAAS,MAAM,OAAqB;CAClC,OAAO,KAAK,MAAM,KAAK,UAAU,KAAK,CAAC;AACzC;;;;;;AAOA,SAAgB,gBACd,MACA,YACA,SACA;CACA,IAAI,OAAO,WAAW,eAAe,CAAC,OAAO,MAAM;EACjD,QAAQ,KAAK,+BAA+B;EAC5C,OAAO;CACT;CACA,IAAI,cAAc,SAAS,IAAI,GAAG;CAClC,IAAI,OAAO,SAAS,KAAK,SAAS,WAAW,GAAG;CAChD,IAAI,OAAO,SAAS,KAAK,SAAS,WAAW,GAAG;CAEhD,MAAM,EAAE,MAAM,SAAS,YAAY,MAAM,UAAU;CAEnD,IAAI,WAAW,SAAS,IAAa,GAAG;CACxC,IAAI,SAAS,UAAU;EAErB,MAAM,oBAAoB,mBAAmB,IAAI;EACjD,IAAI,CAAC,mBAAmB;EACxB,OAAO,KAAK,WAAW,UAAU,MAAM,IAAI,GAAG;GAAE,UAAU;GAAS;EAAkB,CAAC;CACxF,OACE,OAAO,KAAK,WAAW,MAAM,MAAM,IAAI,GAAG,EAAE,UAAU,QAAQ,CAAC;AAEnE;;;;;;;AAQA,SAAgB,cAAc,SAAiB;CAC7C,QAAQ,EAAE,SAAS,gBAAkC;EACnD,IAAI,OAAO,WAAW,eAAe,CAAC,OAAO,MAAM;GACjD,QAAQ,KAAK,+BAA+B;GAC5C;EACF;EAEA,MAAM,OAAO,OAAO;EAEpB,MAAM,QAAQ,SAAS,WAAW,KAAK,CAAC,EAAE,KAAK,CAAC,CAAC,YAAY,KAAK,KAAA;EAClE,MAAM,QAAQ,SAAS,WAAW,YAAY;EAC9C,MAAM,UAAU,SAAS,WAAW,OAAO;EAE3C,MAAM,OAAiB;GACrB,SAAS,SAAS,SAAS,KAAK,CAAC,CAAC,YAAY;GAC9C,MAAM,SAAS,MAAM,KAAK;GAC1B,QAAQ,SAAS,QAAQ,KAAK;GAC9B,aAAa,SAAS,aAAa,KAAK;EAC1C;EAEA,MAAM,QAAQ,WAA8B;GAC1C,KAAK,QAAQ;IAAE;IAAS,MAAM,MAAM;KAAE,GAAG;KAAM,GAAG;IAAO,CAAC;GAAE,CAAC;EAC/D;EAEA,MAAM,QAAQ,UAA+B,QAAQ,OAAO,KAAK,IAAI,KAAA;EACrE,QAAQ,IAAI;GACV,KAAK,KAAK;GACV,KAAK,QAAQ,kBAAkB,KAAK,IAAI,KAAA,CAAS;GACjD,KAAK,SAAS,KAAK,CAAC;GACpB,KAAK,iBAAiB,SAAS,UAAU,CAAC;GAC1C,KAAK,iBAAiB,SAAS,SAAS,CAAC;EAC3C,CAAC,CAAC,CACC,MAAM,CAAC,cAAc,qBAAqB,oBAAoB,OAAO,UACpE,KAAK;GACH;GACA;GACA;GACA,mBAAmB;GACnB,kBAAkB;EACpB,CAAC,CACH,CAAC,CACA,YAAY,KAAK,CAAC,CAAC,CAAC;CACzB;AACF;AAQA,SAAgB,UAAU,SAAwC;CAChE,OAAO;EACL,MAAM;EACN,OAAO,WAAW,iBAAiB,SAAS,oBAAoB,QAAQ,YAAY,CAAC;EACrF,SAAS,cAAc,QAAQ,OAAO;EACtC,QAAQ;GACN,IAAI;GACJ,QAAQ;;;;;;;;;;;;;;kCAcoB,KAAK,UAAU,QAAQ,OAAO,EAAE;;;EAG9D;CACF;AACF"}
|
|
@@ -1,7 +1,59 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
2
|
const require_utils_field = require("../utils/field.cjs");
|
|
3
|
-
let posthog_js = require("posthog-js");
|
|
4
3
|
// src/third-parties/posthog.ts
|
|
4
|
+
/**
|
|
5
|
+
* `window.posthog`, for calls that return nothing (`capture`, `identify`, `onFeatureFlags`, …):
|
|
6
|
+
* the snippet's stub until the library loads, which queues them and replays them in order once it
|
|
7
|
+
* has. A method that returns a value returns `undefined` on the stub — use `getLoadedPosthog` for
|
|
8
|
+
* those. `undefined` on the server and before the snippet has run.
|
|
9
|
+
*
|
|
10
|
+
* Read off `window` rather than declared on it, so a host that also has `posthog-js`'s own types
|
|
11
|
+
* does not get two conflicting declarations. Types only: install `posthog-js` (a dev dependency
|
|
12
|
+
* is enough) for them; it is never bundled.
|
|
13
|
+
*/
|
|
14
|
+
function getPosthog() {
|
|
15
|
+
if (typeof document === "undefined") return void 0;
|
|
16
|
+
return window.posthog;
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* The PostHog instance once the library has loaded, for the methods that return a value
|
|
20
|
+
* (`getFeatureFlag`, `isFeatureEnabled`, `get_distinct_id`, …); `undefined` while only the stub is
|
|
21
|
+
* there. To act when flags arrive, subscribe with `getPosthog()?.onFeatureFlags` instead, which
|
|
22
|
+
* the stub queues.
|
|
23
|
+
*/
|
|
24
|
+
function getLoadedPosthog() {
|
|
25
|
+
const posthog = getPosthog();
|
|
26
|
+
return posthog?.__loaded ? posthog : void 0;
|
|
27
|
+
}
|
|
28
|
+
let flagsReady;
|
|
29
|
+
/**
|
|
30
|
+
* Resolves once PostHog has loaded its feature flags — or after `timeoutMs` (3 s by default),
|
|
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:
|
|
34
|
+
*
|
|
35
|
+
* ```tsx
|
|
36
|
+
* function Checkout() {
|
|
37
|
+
* use(browser()); // react-dom: the server renders the <Suspense> fallback instead
|
|
38
|
+
* use(posthogFlagsReady());
|
|
39
|
+
* return useFeatureFlag('new-checkout') === 'test' ? <NewCheckout /> : <OldCheckout />;
|
|
40
|
+
* }
|
|
41
|
+
* ```
|
|
42
|
+
*
|
|
43
|
+
* Waiting shows the fallback until the flags are in, instead of the default then the variant;
|
|
44
|
+
* with server-evaluated flags in `config.bootstrap` it resolves as soon as the library loads.
|
|
45
|
+
* Browser only: it never resolves on the server.
|
|
46
|
+
*/
|
|
47
|
+
function posthogFlagsReady(timeoutMs = 3e3) {
|
|
48
|
+
if (typeof document === "undefined") return new Promise(() => {});
|
|
49
|
+
flagsReady ??= new Promise((resolve) => {
|
|
50
|
+
setTimeout(resolve, timeoutMs);
|
|
51
|
+
const posthog = getPosthog();
|
|
52
|
+
if (!posthog) return;
|
|
53
|
+
posthog.onFeatureFlags(() => resolve());
|
|
54
|
+
});
|
|
55
|
+
return flagsReady;
|
|
56
|
+
}
|
|
5
57
|
const metrics = [
|
|
6
58
|
"CLS",
|
|
7
59
|
"FCP",
|
|
@@ -12,10 +64,15 @@ const metrics = [
|
|
|
12
64
|
];
|
|
13
65
|
function sendPosthogEvent(name, properties) {
|
|
14
66
|
if (typeof document === "undefined") return;
|
|
67
|
+
const posthog = getPosthog();
|
|
68
|
+
if (!posthog) {
|
|
69
|
+
console.warn("posthog has not been initialized");
|
|
70
|
+
return false;
|
|
71
|
+
}
|
|
15
72
|
if (metrics.includes(name)) return;
|
|
16
73
|
if (window.location.host.includes("127.0.0.1")) return;
|
|
17
74
|
if (window.location.host.includes("localhost")) return;
|
|
18
|
-
|
|
75
|
+
posthog.capture(name, properties);
|
|
19
76
|
}
|
|
20
77
|
/**
|
|
21
78
|
* Identifies the visitor to PostHog as the signed-in user, by the user's id — the server's
|
|
@@ -28,12 +85,48 @@ function sendPosthogEvent(name, properties) {
|
|
|
28
85
|
* this page starts anonymous instead of merging into the one who left.
|
|
29
86
|
*/
|
|
30
87
|
function setPosthogUser({ user_id, user_data }) {
|
|
88
|
+
const posthog = getPosthog();
|
|
89
|
+
if (!posthog) {
|
|
90
|
+
console.warn("posthog has not been initialized");
|
|
91
|
+
return;
|
|
92
|
+
}
|
|
31
93
|
if (!user_id) {
|
|
32
|
-
|
|
94
|
+
posthog.reset();
|
|
33
95
|
return;
|
|
34
96
|
}
|
|
35
|
-
|
|
97
|
+
posthog.identify(user_id, { email: require_utils_field.getFirst(user_data?.email) });
|
|
98
|
+
}
|
|
99
|
+
/**
|
|
100
|
+
* PostHog: every event, for behavior analysis. Loaded with PostHog's HTML snippet, which defines
|
|
101
|
+
* a stub `window.posthog` and fetches the library (`array.js`) asynchronously from PostHog's
|
|
102
|
+
* assets host, so it stays out of the app's bundle; calls made before it loads are queued.
|
|
103
|
+
*
|
|
104
|
+
* `config` is serialized into the snippet's `posthog.init` call, so only its JSON survives:
|
|
105
|
+
* `api_host`, `defaults`, `bootstrap` (server-evaluated flags, so an experiment renders its variant
|
|
106
|
+
* without a flicker), and the other plain options — functions such as `loaded` are dropped.
|
|
107
|
+
*/
|
|
108
|
+
function posthogAnalytics(options) {
|
|
109
|
+
const assets = options.config.api_host.replace(".i.posthog.com", "-assets.i.posthog.com");
|
|
110
|
+
const config = JSON.stringify(options.config).replace(/</g, "\\u003c");
|
|
111
|
+
return {
|
|
112
|
+
type: "analytics",
|
|
113
|
+
track: sendPosthogEvent,
|
|
114
|
+
setUser: setPosthogUser,
|
|
115
|
+
preconnect: URL.canParse(assets) ? [new URL(assets).origin] : [],
|
|
116
|
+
script: {
|
|
117
|
+
id: "posthog",
|
|
118
|
+
strategy: "beforeInteractive",
|
|
119
|
+
inline: `
|
|
120
|
+
!function(t,e){var o,n,p,r;e.__SV||(window.posthog=e,e._i=[],e.init=function(i,s,a){function g(t,e){var o=e.split(".");2==o.length&&(t=t[o[0]],e=o[1]),t[e]=function(){t.push([e].concat(Array.prototype.slice.call(arguments,0)))}}(p=t.createElement("script")).type="text/javascript",p.crossOrigin="anonymous",p.async=!0,p.src=s.api_host.replace(".i.posthog.com","-assets.i.posthog.com")+"/static/array.js",(r=t.getElementsByTagName("script")[0]).parentNode.insertBefore(p,r);var u=e;for(void 0!==a?u=e[a]=[]:a="posthog",u.people=u.people||[],Object.defineProperty(u,"toString",{configurable:!0,enumerable:!0,writable:!0,value:function(t){var e="posthog";return"posthog"!==a&&(e+="."+a),t||(e+=" (stub)"),e}}),Object.defineProperty(u.people,"toString",{configurable:!0,enumerable:!0,writable:!0,value:function(){return u.toString(1)+".people (stub)"}}),o="init capture register register_once register_for_session unregister unregister_for_session getFeatureFlag getFeatureFlagResult isFeatureEnabled reloadFeatureFlags updateEarlyAccessFeatureEnrollment getEarlyAccessFeatures on onFeatureFlags onSessionId getSurveys getActiveMatchingSurveys renderSurvey canRenderSurvey getNextSurveyStep identify setPersonProperties group resetGroups setPersonPropertiesForFlags resetPersonPropertiesForFlags setGroupPropertiesForFlags resetGroupPropertiesForFlags reset get_distinct_id getGroups get_session_id get_session_replay_url alias set_config startSessionRecording stopSessionRecording sessionRecordingStarted captureException loadToolbar get_property getSessionProperty createPersonProfile opt_in_capturing opt_out_capturing has_opted_in_capturing has_opted_out_capturing clear_opt_in_out_capturing debug".split(" "),n=0;n<o.length;n++)g(u,o[n]);e._i.push([i,s,a])},e.__SV=1)}(document,window.posthog||[]);
|
|
121
|
+
posthog.init(${JSON.stringify(options.token)}, ${config});
|
|
122
|
+
`
|
|
123
|
+
}
|
|
124
|
+
};
|
|
36
125
|
}
|
|
126
|
+
exports.getLoadedPosthog = getLoadedPosthog;
|
|
127
|
+
exports.getPosthog = getPosthog;
|
|
128
|
+
exports.posthogAnalytics = posthogAnalytics;
|
|
129
|
+
exports.posthogFlagsReady = posthogFlagsReady;
|
|
37
130
|
exports.sendPosthogEvent = sendPosthogEvent;
|
|
38
131
|
exports.setPosthogUser = setPosthogUser;
|
|
39
132
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"posthog.cjs","names":["getFirst"],"sources":["../../src/third-parties/posthog.ts"],"sourcesContent":["import {
|
|
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,6 +1,45 @@
|
|
|
1
1
|
import { EventName, TrackName, TrackProperties } from "../track/types.cjs";
|
|
2
2
|
import { UpdateVisitorDTO } from "../schema/index.cjs";
|
|
3
|
-
|
|
3
|
+
import { Integration } from "./integration.cjs";
|
|
4
|
+
import { PostHog, PostHog as PostHog$1, PostHogConfig, PostHogConfig as PostHogConfig$1 } from "posthog-js";
|
|
5
|
+
/**
|
|
6
|
+
* `window.posthog`, for calls that return nothing (`capture`, `identify`, `onFeatureFlags`, …):
|
|
7
|
+
* the snippet's stub until the library loads, which queues them and replays them in order once it
|
|
8
|
+
* has. A method that returns a value returns `undefined` on the stub — use `getLoadedPosthog` for
|
|
9
|
+
* those. `undefined` on the server and before the snippet has run.
|
|
10
|
+
*
|
|
11
|
+
* Read off `window` rather than declared on it, so a host that also has `posthog-js`'s own types
|
|
12
|
+
* does not get two conflicting declarations. Types only: install `posthog-js` (a dev dependency
|
|
13
|
+
* is enough) for them; it is never bundled.
|
|
14
|
+
*/
|
|
15
|
+
export declare function getPosthog(): PostHog$1 | undefined;
|
|
16
|
+
/**
|
|
17
|
+
* The PostHog instance once the library has loaded, for the methods that return a value
|
|
18
|
+
* (`getFeatureFlag`, `isFeatureEnabled`, `get_distinct_id`, …); `undefined` while only the stub is
|
|
19
|
+
* there. To act when flags arrive, subscribe with `getPosthog()?.onFeatureFlags` instead, which
|
|
20
|
+
* the stub queues.
|
|
21
|
+
*/
|
|
22
|
+
export declare function getLoadedPosthog(): PostHog$1 | undefined;
|
|
23
|
+
/**
|
|
24
|
+
* Resolves once PostHog has loaded its feature flags — or after `timeoutMs` (3 s by default),
|
|
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:
|
|
28
|
+
*
|
|
29
|
+
* ```tsx
|
|
30
|
+
* function Checkout() {
|
|
31
|
+
* use(browser()); // react-dom: the server renders the <Suspense> fallback instead
|
|
32
|
+
* use(posthogFlagsReady());
|
|
33
|
+
* return useFeatureFlag('new-checkout') === 'test' ? <NewCheckout /> : <OldCheckout />;
|
|
34
|
+
* }
|
|
35
|
+
* ```
|
|
36
|
+
*
|
|
37
|
+
* Waiting shows the fallback until the flags are in, instead of the default then the variant;
|
|
38
|
+
* with server-evaluated flags in `config.bootstrap` it resolves as soon as the library loads.
|
|
39
|
+
* Browser only: it never resolves on the server.
|
|
40
|
+
*/
|
|
41
|
+
export declare function posthogFlagsReady(timeoutMs?: number): Promise<void>;
|
|
42
|
+
export declare function sendPosthogEvent<T extends EventName>(name: TrackName<T>, properties?: TrackProperties<T>): false | undefined;
|
|
4
43
|
/**
|
|
5
44
|
* Identifies the visitor to PostHog as the signed-in user, by the user's id — the server's
|
|
6
45
|
* `distinct_id` for the visitor once someone has signed in on it. Only a user: identifying an
|
|
@@ -12,4 +51,20 @@ export declare function sendPosthogEvent<T extends EventName>(name: TrackName<T>
|
|
|
12
51
|
* this page starts anonymous instead of merging into the one who left.
|
|
13
52
|
*/
|
|
14
53
|
export declare function setPosthogUser({ user_id, user_data }: Omit<UpdateVisitorDTO, 'tags'>): void;
|
|
54
|
+
/**
|
|
55
|
+
* PostHog: every event, for behavior analysis. Loaded with PostHog's HTML snippet, which defines
|
|
56
|
+
* a stub `window.posthog` and fetches the library (`array.js`) asynchronously from PostHog's
|
|
57
|
+
* assets host, so it stays out of the app's bundle; calls made before it loads are queued.
|
|
58
|
+
*
|
|
59
|
+
* `config` is serialized into the snippet's `posthog.init` call, so only its JSON survives:
|
|
60
|
+
* `api_host`, `defaults`, `bootstrap` (server-evaluated flags, so an experiment renders its variant
|
|
61
|
+
* without a flicker), and the other plain options — functions such as `loaded` are dropped.
|
|
62
|
+
*/
|
|
63
|
+
export declare function posthogAnalytics(options: {
|
|
64
|
+
token: `phc_${string}`;
|
|
65
|
+
config: Partial<PostHogConfig$1> & {
|
|
66
|
+
api_host: string;
|
|
67
|
+
};
|
|
68
|
+
}): Integration;
|
|
69
|
+
export type { PostHog, PostHogConfig };
|
|
15
70
|
//# sourceMappingURL=posthog.d.cts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"posthog.d.cts","names":[],"sources":["../../src/third-parties/posthog.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"posthog.d.cts","names":["PostHog","PostHogConfig"],"sources":["../../src/third-parties/posthog.ts"],"mappings":";;;;;;;;;;;;;;wBAkBgB,cAAcA;;;;;;;wBAWd,oBAAoBA;;;;;;;;;;;;;;;;;;;wBAyBpB,kBAAkB,qBAAmB;wBAcrC,iBAAiB,UAAU,WACzC,MAAM,UAAU,IAChB,aAAa,gBAAgB;;;;;;;;;;;wBA4Bf,iBAAiB,SAAS,aAAa,KAAK;;;;;;;;;;wBAsB5C,iBAAiB;EAC/B;EACA,QAAQ,QAAQC;IAAmB;;IACjC"}
|
|
@@ -1,6 +1,45 @@
|
|
|
1
1
|
import { EventName, TrackName, TrackProperties } from "../track/types.mjs";
|
|
2
2
|
import { UpdateVisitorDTO } from "../schema/index.mjs";
|
|
3
|
-
|
|
3
|
+
import { Integration } from "./integration.mjs";
|
|
4
|
+
import { PostHog, PostHog as PostHog$1, PostHogConfig, PostHogConfig as PostHogConfig$1 } from "posthog-js";
|
|
5
|
+
/**
|
|
6
|
+
* `window.posthog`, for calls that return nothing (`capture`, `identify`, `onFeatureFlags`, …):
|
|
7
|
+
* the snippet's stub until the library loads, which queues them and replays them in order once it
|
|
8
|
+
* has. A method that returns a value returns `undefined` on the stub — use `getLoadedPosthog` for
|
|
9
|
+
* those. `undefined` on the server and before the snippet has run.
|
|
10
|
+
*
|
|
11
|
+
* Read off `window` rather than declared on it, so a host that also has `posthog-js`'s own types
|
|
12
|
+
* does not get two conflicting declarations. Types only: install `posthog-js` (a dev dependency
|
|
13
|
+
* is enough) for them; it is never bundled.
|
|
14
|
+
*/
|
|
15
|
+
export declare function getPosthog(): PostHog$1 | undefined;
|
|
16
|
+
/**
|
|
17
|
+
* The PostHog instance once the library has loaded, for the methods that return a value
|
|
18
|
+
* (`getFeatureFlag`, `isFeatureEnabled`, `get_distinct_id`, …); `undefined` while only the stub is
|
|
19
|
+
* there. To act when flags arrive, subscribe with `getPosthog()?.onFeatureFlags` instead, which
|
|
20
|
+
* the stub queues.
|
|
21
|
+
*/
|
|
22
|
+
export declare function getLoadedPosthog(): PostHog$1 | undefined;
|
|
23
|
+
/**
|
|
24
|
+
* Resolves once PostHog has loaded its feature flags — or after `timeoutMs` (3 s by default),
|
|
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:
|
|
28
|
+
*
|
|
29
|
+
* ```tsx
|
|
30
|
+
* function Checkout() {
|
|
31
|
+
* use(browser()); // react-dom: the server renders the <Suspense> fallback instead
|
|
32
|
+
* use(posthogFlagsReady());
|
|
33
|
+
* return useFeatureFlag('new-checkout') === 'test' ? <NewCheckout /> : <OldCheckout />;
|
|
34
|
+
* }
|
|
35
|
+
* ```
|
|
36
|
+
*
|
|
37
|
+
* Waiting shows the fallback until the flags are in, instead of the default then the variant;
|
|
38
|
+
* with server-evaluated flags in `config.bootstrap` it resolves as soon as the library loads.
|
|
39
|
+
* Browser only: it never resolves on the server.
|
|
40
|
+
*/
|
|
41
|
+
export declare function posthogFlagsReady(timeoutMs?: number): Promise<void>;
|
|
42
|
+
export declare function sendPosthogEvent<T extends EventName>(name: TrackName<T>, properties?: TrackProperties<T>): false | undefined;
|
|
4
43
|
/**
|
|
5
44
|
* Identifies the visitor to PostHog as the signed-in user, by the user's id — the server's
|
|
6
45
|
* `distinct_id` for the visitor once someone has signed in on it. Only a user: identifying an
|
|
@@ -12,4 +51,20 @@ export declare function sendPosthogEvent<T extends EventName>(name: TrackName<T>
|
|
|
12
51
|
* this page starts anonymous instead of merging into the one who left.
|
|
13
52
|
*/
|
|
14
53
|
export declare function setPosthogUser({ user_id, user_data }: Omit<UpdateVisitorDTO, 'tags'>): void;
|
|
54
|
+
/**
|
|
55
|
+
* PostHog: every event, for behavior analysis. Loaded with PostHog's HTML snippet, which defines
|
|
56
|
+
* a stub `window.posthog` and fetches the library (`array.js`) asynchronously from PostHog's
|
|
57
|
+
* assets host, so it stays out of the app's bundle; calls made before it loads are queued.
|
|
58
|
+
*
|
|
59
|
+
* `config` is serialized into the snippet's `posthog.init` call, so only its JSON survives:
|
|
60
|
+
* `api_host`, `defaults`, `bootstrap` (server-evaluated flags, so an experiment renders its variant
|
|
61
|
+
* without a flicker), and the other plain options — functions such as `loaded` are dropped.
|
|
62
|
+
*/
|
|
63
|
+
export declare function posthogAnalytics(options: {
|
|
64
|
+
token: `phc_${string}`;
|
|
65
|
+
config: Partial<PostHogConfig$1> & {
|
|
66
|
+
api_host: string;
|
|
67
|
+
};
|
|
68
|
+
}): Integration;
|
|
69
|
+
export type { PostHog, PostHogConfig };
|
|
15
70
|
//# sourceMappingURL=posthog.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"posthog.d.mts","names":[],"sources":["../../src/third-parties/posthog.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"posthog.d.mts","names":["PostHog","PostHogConfig"],"sources":["../../src/third-parties/posthog.ts"],"mappings":";;;;;;;;;;;;;;wBAkBgB,cAAcA;;;;;;;wBAWd,oBAAoBA;;;;;;;;;;;;;;;;;;;wBAyBpB,kBAAkB,qBAAmB;wBAcrC,iBAAiB,UAAU,WACzC,MAAM,UAAU,IAChB,aAAa,gBAAgB;;;;;;;;;;;wBA4Bf,iBAAiB,SAAS,aAAa,KAAK;;;;;;;;;;wBAsB5C,iBAAiB;EAC/B;EACA,QAAQ,QAAQC;IAAmB;;IACjC"}
|
|
@@ -1,6 +1,58 @@
|
|
|
1
1
|
import { getFirst } from "../utils/field.mjs";
|
|
2
|
-
import { posthog } from "posthog-js";
|
|
3
2
|
// src/third-parties/posthog.ts
|
|
3
|
+
/**
|
|
4
|
+
* `window.posthog`, for calls that return nothing (`capture`, `identify`, `onFeatureFlags`, …):
|
|
5
|
+
* the snippet's stub until the library loads, which queues them and replays them in order once it
|
|
6
|
+
* has. A method that returns a value returns `undefined` on the stub — use `getLoadedPosthog` for
|
|
7
|
+
* those. `undefined` on the server and before the snippet has run.
|
|
8
|
+
*
|
|
9
|
+
* Read off `window` rather than declared on it, so a host that also has `posthog-js`'s own types
|
|
10
|
+
* does not get two conflicting declarations. Types only: install `posthog-js` (a dev dependency
|
|
11
|
+
* is enough) for them; it is never bundled.
|
|
12
|
+
*/
|
|
13
|
+
function getPosthog() {
|
|
14
|
+
if (typeof document === "undefined") return void 0;
|
|
15
|
+
return window.posthog;
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* The PostHog instance once the library has loaded, for the methods that return a value
|
|
19
|
+
* (`getFeatureFlag`, `isFeatureEnabled`, `get_distinct_id`, …); `undefined` while only the stub is
|
|
20
|
+
* there. To act when flags arrive, subscribe with `getPosthog()?.onFeatureFlags` instead, which
|
|
21
|
+
* the stub queues.
|
|
22
|
+
*/
|
|
23
|
+
function getLoadedPosthog() {
|
|
24
|
+
const posthog = getPosthog();
|
|
25
|
+
return posthog?.__loaded ? posthog : void 0;
|
|
26
|
+
}
|
|
27
|
+
let flagsReady;
|
|
28
|
+
/**
|
|
29
|
+
* Resolves once PostHog has loaded its feature flags — or after `timeoutMs` (3 s by default),
|
|
30
|
+
* since an ad blocker that stops the library would otherwise hold it forever; read the flags
|
|
31
|
+
* after it with `useFeatureFlag` / `getLoadedPosthog`, which are `undefined` in that case. One
|
|
32
|
+
* promise per page, so React's `use()` can suspend on it:
|
|
33
|
+
*
|
|
34
|
+
* ```tsx
|
|
35
|
+
* function Checkout() {
|
|
36
|
+
* use(browser()); // react-dom: the server renders the <Suspense> fallback instead
|
|
37
|
+
* use(posthogFlagsReady());
|
|
38
|
+
* return useFeatureFlag('new-checkout') === 'test' ? <NewCheckout /> : <OldCheckout />;
|
|
39
|
+
* }
|
|
40
|
+
* ```
|
|
41
|
+
*
|
|
42
|
+
* Waiting shows the fallback until the flags are in, instead of the default then the variant;
|
|
43
|
+
* with server-evaluated flags in `config.bootstrap` it resolves as soon as the library loads.
|
|
44
|
+
* Browser only: it never resolves on the server.
|
|
45
|
+
*/
|
|
46
|
+
function posthogFlagsReady(timeoutMs = 3e3) {
|
|
47
|
+
if (typeof document === "undefined") return new Promise(() => {});
|
|
48
|
+
flagsReady ??= new Promise((resolve) => {
|
|
49
|
+
setTimeout(resolve, timeoutMs);
|
|
50
|
+
const posthog = getPosthog();
|
|
51
|
+
if (!posthog) return;
|
|
52
|
+
posthog.onFeatureFlags(() => resolve());
|
|
53
|
+
});
|
|
54
|
+
return flagsReady;
|
|
55
|
+
}
|
|
4
56
|
const metrics = [
|
|
5
57
|
"CLS",
|
|
6
58
|
"FCP",
|
|
@@ -11,6 +63,11 @@ const metrics = [
|
|
|
11
63
|
];
|
|
12
64
|
function sendPosthogEvent(name, properties) {
|
|
13
65
|
if (typeof document === "undefined") return;
|
|
66
|
+
const posthog = getPosthog();
|
|
67
|
+
if (!posthog) {
|
|
68
|
+
console.warn("posthog has not been initialized");
|
|
69
|
+
return false;
|
|
70
|
+
}
|
|
14
71
|
if (metrics.includes(name)) return;
|
|
15
72
|
if (window.location.host.includes("127.0.0.1")) return;
|
|
16
73
|
if (window.location.host.includes("localhost")) return;
|
|
@@ -27,12 +84,44 @@ function sendPosthogEvent(name, properties) {
|
|
|
27
84
|
* this page starts anonymous instead of merging into the one who left.
|
|
28
85
|
*/
|
|
29
86
|
function setPosthogUser({ user_id, user_data }) {
|
|
87
|
+
const posthog = getPosthog();
|
|
88
|
+
if (!posthog) {
|
|
89
|
+
console.warn("posthog has not been initialized");
|
|
90
|
+
return;
|
|
91
|
+
}
|
|
30
92
|
if (!user_id) {
|
|
31
93
|
posthog.reset();
|
|
32
94
|
return;
|
|
33
95
|
}
|
|
34
96
|
posthog.identify(user_id, { email: getFirst(user_data?.email) });
|
|
35
97
|
}
|
|
36
|
-
|
|
98
|
+
/**
|
|
99
|
+
* PostHog: every event, for behavior analysis. Loaded with PostHog's HTML snippet, which defines
|
|
100
|
+
* a stub `window.posthog` and fetches the library (`array.js`) asynchronously from PostHog's
|
|
101
|
+
* assets host, so it stays out of the app's bundle; calls made before it loads are queued.
|
|
102
|
+
*
|
|
103
|
+
* `config` is serialized into the snippet's `posthog.init` call, so only its JSON survives:
|
|
104
|
+
* `api_host`, `defaults`, `bootstrap` (server-evaluated flags, so an experiment renders its variant
|
|
105
|
+
* without a flicker), and the other plain options — functions such as `loaded` are dropped.
|
|
106
|
+
*/
|
|
107
|
+
function posthogAnalytics(options) {
|
|
108
|
+
const assets = options.config.api_host.replace(".i.posthog.com", "-assets.i.posthog.com");
|
|
109
|
+
const config = JSON.stringify(options.config).replace(/</g, "\\u003c");
|
|
110
|
+
return {
|
|
111
|
+
type: "analytics",
|
|
112
|
+
track: sendPosthogEvent,
|
|
113
|
+
setUser: setPosthogUser,
|
|
114
|
+
preconnect: URL.canParse(assets) ? [new URL(assets).origin] : [],
|
|
115
|
+
script: {
|
|
116
|
+
id: "posthog",
|
|
117
|
+
strategy: "beforeInteractive",
|
|
118
|
+
inline: `
|
|
119
|
+
!function(t,e){var o,n,p,r;e.__SV||(window.posthog=e,e._i=[],e.init=function(i,s,a){function g(t,e){var o=e.split(".");2==o.length&&(t=t[o[0]],e=o[1]),t[e]=function(){t.push([e].concat(Array.prototype.slice.call(arguments,0)))}}(p=t.createElement("script")).type="text/javascript",p.crossOrigin="anonymous",p.async=!0,p.src=s.api_host.replace(".i.posthog.com","-assets.i.posthog.com")+"/static/array.js",(r=t.getElementsByTagName("script")[0]).parentNode.insertBefore(p,r);var u=e;for(void 0!==a?u=e[a]=[]:a="posthog",u.people=u.people||[],Object.defineProperty(u,"toString",{configurable:!0,enumerable:!0,writable:!0,value:function(t){var e="posthog";return"posthog"!==a&&(e+="."+a),t||(e+=" (stub)"),e}}),Object.defineProperty(u.people,"toString",{configurable:!0,enumerable:!0,writable:!0,value:function(){return u.toString(1)+".people (stub)"}}),o="init capture register register_once register_for_session unregister unregister_for_session getFeatureFlag getFeatureFlagResult isFeatureEnabled reloadFeatureFlags updateEarlyAccessFeatureEnrollment getEarlyAccessFeatures on onFeatureFlags onSessionId getSurveys getActiveMatchingSurveys renderSurvey canRenderSurvey getNextSurveyStep identify setPersonProperties group resetGroups setPersonPropertiesForFlags resetPersonPropertiesForFlags setGroupPropertiesForFlags resetGroupPropertiesForFlags reset get_distinct_id getGroups get_session_id get_session_replay_url alias set_config startSessionRecording stopSessionRecording sessionRecordingStarted captureException loadToolbar get_property getSessionProperty createPersonProfile opt_in_capturing opt_out_capturing has_opted_in_capturing has_opted_out_capturing clear_opt_in_out_capturing debug".split(" "),n=0;n<o.length;n++)g(u,o[n]);e._i.push([i,s,a])},e.__SV=1)}(document,window.posthog||[]);
|
|
120
|
+
posthog.init(${JSON.stringify(options.token)}, ${config});
|
|
121
|
+
`
|
|
122
|
+
}
|
|
123
|
+
};
|
|
124
|
+
}
|
|
125
|
+
export { getLoadedPosthog, getPosthog, posthogAnalytics, posthogFlagsReady, sendPosthogEvent, setPosthogUser };
|
|
37
126
|
|
|
38
127
|
//# sourceMappingURL=posthog.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"posthog.mjs","names":[],"sources":["../../src/third-parties/posthog.ts"],"sourcesContent":["import {
|
|
1
|
+
{"version":3,"file":"posthog.mjs","names":[],"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,OAAO,SAAS,WAAW,KAAK,EAAE,CAAC;AACjE;;;;;;;;;;AAWA,SAAgB,iBAAiB,SAGjB;CAGd,MAAM,SAAS,QAAQ,OAAO,SAAS,QAAQ,kBAAkB,uBAAuB;CAGxF,MAAM,SAAS,KAAK,UAAU,QAAQ,MAAM,CAAC,CAAC,QAAQ,MAAM,SAAS;CACrE,OAAO;EACL,MAAM;EACN,OAAO;EACP,SAAS;EACT,YAAY,IAAI,SAAS,MAAM,IAAI,CAAC,IAAI,IAAI,MAAM,CAAC,CAAC,MAAM,IAAI,CAAC;EAC/D,QAAQ;GACN,IAAI;GAIJ,UAAU;GACV,QAAQ;;uBAES,KAAK,UAAU,QAAQ,KAAK,EAAE,IAAI,OAAO;;EAE5D;CACF;AACF"}
|