@shware/analytics 16.0.0 → 16.2.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.
Files changed (200) hide show
  1. package/README.md +90 -5
  2. package/dist/native/fbsdk.cjs +1 -2
  3. package/dist/native/fbsdk.cjs.map +1 -1
  4. package/dist/native/fbsdk.d.cts.map +1 -1
  5. package/dist/native/fbsdk.d.mts.map +1 -1
  6. package/dist/native/fbsdk.mjs +3 -4
  7. package/dist/native/fbsdk.mjs.map +1 -1
  8. package/dist/react/index.cjs +11 -2
  9. package/dist/react/index.cjs.map +1 -1
  10. package/dist/react/index.d.cts +3 -2
  11. package/dist/react/index.d.cts.map +1 -1
  12. package/dist/react/index.d.mts +3 -2
  13. package/dist/react/index.d.mts.map +1 -1
  14. package/dist/react/index.mjs +3 -2
  15. package/dist/react/index.mjs.map +1 -1
  16. package/dist/react/posthog-error-boundary.cjs +119 -0
  17. package/dist/react/posthog-error-boundary.cjs.map +1 -0
  18. package/dist/react/posthog-error-boundary.d.cts +60 -0
  19. package/dist/react/posthog-error-boundary.d.cts.map +1 -0
  20. package/dist/react/posthog-error-boundary.d.mts +60 -0
  21. package/dist/react/posthog-error-boundary.d.mts.map +1 -0
  22. package/dist/react/posthog-error-boundary.mjs +117 -0
  23. package/dist/react/posthog-error-boundary.mjs.map +1 -0
  24. package/dist/react/posthog.cjs +97 -0
  25. package/dist/react/posthog.cjs.map +1 -0
  26. package/dist/react/posthog.d.cts +41 -0
  27. package/dist/react/posthog.d.cts.map +1 -0
  28. package/dist/react/posthog.d.mts +41 -0
  29. package/dist/react/posthog.d.mts.map +1 -0
  30. package/dist/react/posthog.mjs +90 -0
  31. package/dist/react/posthog.mjs.map +1 -0
  32. package/dist/server/conversions-api-error.cjs +20 -0
  33. package/dist/server/conversions-api-error.cjs.map +1 -0
  34. package/dist/server/conversions-api-error.d.cts +17 -0
  35. package/dist/server/conversions-api-error.d.cts.map +1 -0
  36. package/dist/server/conversions-api-error.d.mts +17 -0
  37. package/dist/server/conversions-api-error.d.mts.map +1 -0
  38. package/dist/server/conversions-api-error.mjs +19 -0
  39. package/dist/server/conversions-api-error.mjs.map +1 -0
  40. package/dist/server/google-data-manager.cjs +24 -26
  41. package/dist/server/google-data-manager.cjs.map +1 -1
  42. package/dist/server/google-data-manager.d.cts +13 -5
  43. package/dist/server/google-data-manager.d.cts.map +1 -1
  44. package/dist/server/google-data-manager.d.mts +13 -5
  45. package/dist/server/google-data-manager.d.mts.map +1 -1
  46. package/dist/server/google-data-manager.mjs +24 -27
  47. package/dist/server/google-data-manager.mjs.map +1 -1
  48. package/dist/server/index.cjs +11 -0
  49. package/dist/server/index.d.cts +10 -7
  50. package/dist/server/index.d.mts +10 -7
  51. package/dist/server/index.mjs +9 -7
  52. package/dist/server/linkedin-conversions-api.cjs +29 -23
  53. package/dist/server/linkedin-conversions-api.cjs.map +1 -1
  54. package/dist/server/linkedin-conversions-api.d.cts +7 -2
  55. package/dist/server/linkedin-conversions-api.d.cts.map +1 -1
  56. package/dist/server/linkedin-conversions-api.d.mts +7 -2
  57. package/dist/server/linkedin-conversions-api.d.mts.map +1 -1
  58. package/dist/server/linkedin-conversions-api.mjs +29 -24
  59. package/dist/server/linkedin-conversions-api.mjs.map +1 -1
  60. package/dist/server/meta-capi.cjs +32 -31
  61. package/dist/server/meta-capi.cjs.map +1 -1
  62. package/dist/server/meta-capi.d.cts +12 -3
  63. package/dist/server/meta-capi.d.cts.map +1 -1
  64. package/dist/server/meta-capi.d.mts +12 -3
  65. package/dist/server/meta-capi.d.mts.map +1 -1
  66. package/dist/server/meta-capi.mjs +33 -33
  67. package/dist/server/meta-capi.mjs.map +1 -1
  68. package/dist/server/microsoft-conversions-api.cjs +33 -28
  69. package/dist/server/microsoft-conversions-api.cjs.map +1 -1
  70. package/dist/server/microsoft-conversions-api.d.cts +14 -2
  71. package/dist/server/microsoft-conversions-api.d.cts.map +1 -1
  72. package/dist/server/microsoft-conversions-api.d.mts +14 -2
  73. package/dist/server/microsoft-conversions-api.d.mts.map +1 -1
  74. package/dist/server/microsoft-conversions-api.mjs +33 -29
  75. package/dist/server/microsoft-conversions-api.mjs.map +1 -1
  76. package/dist/server/openai-conversions-api.cjs +20 -18
  77. package/dist/server/openai-conversions-api.cjs.map +1 -1
  78. package/dist/server/openai-conversions-api.d.cts +7 -0
  79. package/dist/server/openai-conversions-api.d.cts.map +1 -1
  80. package/dist/server/openai-conversions-api.d.mts +7 -0
  81. package/dist/server/openai-conversions-api.d.mts.map +1 -1
  82. package/dist/server/openai-conversions-api.mjs +21 -20
  83. package/dist/server/openai-conversions-api.mjs.map +1 -1
  84. package/dist/server/reddit-conversions-api.cjs +20 -18
  85. package/dist/server/reddit-conversions-api.cjs.map +1 -1
  86. package/dist/server/reddit-conversions-api.d.cts +7 -0
  87. package/dist/server/reddit-conversions-api.d.cts.map +1 -1
  88. package/dist/server/reddit-conversions-api.d.mts +7 -0
  89. package/dist/server/reddit-conversions-api.d.mts.map +1 -1
  90. package/dist/server/reddit-conversions-api.mjs +21 -20
  91. package/dist/server/reddit-conversions-api.mjs.map +1 -1
  92. package/dist/server/setup-conversions.cjs +62 -0
  93. package/dist/server/setup-conversions.cjs.map +1 -0
  94. package/dist/server/setup-conversions.d.cts +97 -0
  95. package/dist/server/setup-conversions.d.cts.map +1 -0
  96. package/dist/server/setup-conversions.d.mts +97 -0
  97. package/dist/server/setup-conversions.d.mts.map +1 -0
  98. package/dist/server/setup-conversions.mjs +60 -0
  99. package/dist/server/setup-conversions.mjs.map +1 -0
  100. package/dist/third-parties/index.d.cts +3 -3
  101. package/dist/third-parties/index.d.mts +3 -3
  102. package/dist/third-parties/integration.cjs +13 -6
  103. package/dist/third-parties/integration.cjs.map +1 -1
  104. package/dist/third-parties/integration.d.cts +12 -8
  105. package/dist/third-parties/integration.d.cts.map +1 -1
  106. package/dist/third-parties/integration.d.mts +12 -8
  107. package/dist/third-parties/integration.d.mts.map +1 -1
  108. package/dist/third-parties/integration.mjs +13 -7
  109. package/dist/third-parties/integration.mjs.map +1 -1
  110. package/dist/third-parties/linkedin-insight-tag.cjs +0 -4
  111. package/dist/third-parties/linkedin-insight-tag.cjs.map +1 -1
  112. package/dist/third-parties/linkedin-insight-tag.d.cts +4 -2
  113. package/dist/third-parties/linkedin-insight-tag.d.cts.map +1 -1
  114. package/dist/third-parties/linkedin-insight-tag.d.mts +4 -2
  115. package/dist/third-parties/linkedin-insight-tag.d.mts.map +1 -1
  116. package/dist/third-parties/linkedin-insight-tag.mjs +0 -4
  117. package/dist/third-parties/linkedin-insight-tag.mjs.map +1 -1
  118. package/dist/third-parties/meta-pixel.cjs +1 -3
  119. package/dist/third-parties/meta-pixel.cjs.map +1 -1
  120. package/dist/third-parties/meta-pixel.d.cts +4 -2
  121. package/dist/third-parties/meta-pixel.d.cts.map +1 -1
  122. package/dist/third-parties/meta-pixel.d.mts +4 -2
  123. package/dist/third-parties/meta-pixel.d.mts.map +1 -1
  124. package/dist/third-parties/meta-pixel.mjs +3 -5
  125. package/dist/third-parties/meta-pixel.mjs.map +1 -1
  126. package/dist/third-parties/microsoft-uet.cjs +7 -2
  127. package/dist/third-parties/microsoft-uet.cjs.map +1 -1
  128. package/dist/third-parties/microsoft-uet.d.cts +10 -3
  129. package/dist/third-parties/microsoft-uet.d.cts.map +1 -1
  130. package/dist/third-parties/microsoft-uet.d.mts +10 -3
  131. package/dist/third-parties/microsoft-uet.d.mts.map +1 -1
  132. package/dist/third-parties/microsoft-uet.mjs +8 -4
  133. package/dist/third-parties/microsoft-uet.mjs.map +1 -1
  134. package/dist/third-parties/openai-pixel.cjs +1 -3
  135. package/dist/third-parties/openai-pixel.cjs.map +1 -1
  136. package/dist/third-parties/openai-pixel.d.cts +4 -2
  137. package/dist/third-parties/openai-pixel.d.cts.map +1 -1
  138. package/dist/third-parties/openai-pixel.d.mts +4 -2
  139. package/dist/third-parties/openai-pixel.d.mts.map +1 -1
  140. package/dist/third-parties/openai-pixel.mjs +3 -5
  141. package/dist/third-parties/openai-pixel.mjs.map +1 -1
  142. package/dist/third-parties/posthog.cjs +3 -3
  143. package/dist/third-parties/posthog.cjs.map +1 -1
  144. package/dist/third-parties/posthog.d.cts +3 -3
  145. package/dist/third-parties/posthog.d.mts +3 -3
  146. package/dist/third-parties/posthog.mjs +3 -3
  147. package/dist/third-parties/posthog.mjs.map +1 -1
  148. package/dist/third-parties/reddit-pixel.cjs +1 -3
  149. package/dist/third-parties/reddit-pixel.cjs.map +1 -1
  150. package/dist/third-parties/reddit-pixel.d.cts +4 -2
  151. package/dist/third-parties/reddit-pixel.d.cts.map +1 -1
  152. package/dist/third-parties/reddit-pixel.d.mts +4 -2
  153. package/dist/third-parties/reddit-pixel.d.mts.map +1 -1
  154. package/dist/third-parties/reddit-pixel.mjs +3 -5
  155. package/dist/third-parties/reddit-pixel.mjs.map +1 -1
  156. package/dist/track/fbq.cjs +5 -0
  157. package/dist/track/fbq.cjs.map +1 -1
  158. package/dist/track/fbq.d.cts +2 -0
  159. package/dist/track/fbq.d.cts.map +1 -1
  160. package/dist/track/fbq.d.mts +2 -0
  161. package/dist/track/fbq.d.mts.map +1 -1
  162. package/dist/track/fbq.mjs +5 -1
  163. package/dist/track/fbq.mjs.map +1 -1
  164. package/dist/track/oaiq.cjs +5 -0
  165. package/dist/track/oaiq.cjs.map +1 -1
  166. package/dist/track/oaiq.d.cts +2 -0
  167. package/dist/track/oaiq.d.cts.map +1 -1
  168. package/dist/track/oaiq.d.mts +2 -0
  169. package/dist/track/oaiq.d.mts.map +1 -1
  170. package/dist/track/oaiq.mjs +5 -1
  171. package/dist/track/oaiq.mjs.map +1 -1
  172. package/dist/track/rdt.cjs +5 -0
  173. package/dist/track/rdt.cjs.map +1 -1
  174. package/dist/track/rdt.d.cts +2 -0
  175. package/dist/track/rdt.d.cts.map +1 -1
  176. package/dist/track/rdt.d.mts +2 -0
  177. package/dist/track/rdt.d.mts.map +1 -1
  178. package/dist/track/rdt.mjs +5 -1
  179. package/dist/track/rdt.mjs.map +1 -1
  180. package/package.json +1 -16
  181. package/dist/react/use-feature-flag.cjs +0 -23
  182. package/dist/react/use-feature-flag.cjs.map +0 -1
  183. package/dist/react/use-feature-flag.d.cts +0 -10
  184. package/dist/react/use-feature-flag.d.cts.map +0 -1
  185. package/dist/react/use-feature-flag.d.mts +0 -10
  186. package/dist/react/use-feature-flag.d.mts.map +0 -1
  187. package/dist/react/use-feature-flag.mjs +0 -22
  188. package/dist/react/use-feature-flag.mjs.map +0 -1
  189. package/dist/server/legacy.cjs +0 -3
  190. package/dist/server/legacy.d.cts +0 -2
  191. package/dist/server/legacy.d.mts +0 -2
  192. package/dist/server/legacy.mjs +0 -1
  193. package/dist/server/meta-conversions-api.cjs +0 -205
  194. package/dist/server/meta-conversions-api.cjs.map +0 -1
  195. package/dist/server/meta-conversions-api.d.cts +0 -8
  196. package/dist/server/meta-conversions-api.d.cts.map +0 -1
  197. package/dist/server/meta-conversions-api.d.mts +0 -8
  198. package/dist/server/meta-conversions-api.d.mts.map +0 -1
  199. package/dist/server/meta-conversions-api.mjs +0 -201
  200. package/dist/server/meta-conversions-api.mjs.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"reddit-conversions-api.mjs","names":[],"sources":["../../src/server/reddit-conversions-api.ts"],"sourcesContent":["import { fetch } from '@shware/utils';\nimport { IGNORED_EVENTS } from '../third-parties/ignored-events';\nimport { type ServerStandardEvent, mapRDTEvent, mapServerStandardEvent } from '../track/rdt';\nimport type { TrackEvent, UserProvidedData } from '../track/types';\nimport { getFirst } from '../utils/field';\nimport { type EventActionSource, resolveActionSource } from './action-source';\nimport { redditClickId, redditUuid } from './click-ids';\nimport { pageLocation } from './page-location';\n\n/**\n * https://ads-api.reddit.com/docs/v3/operations/Post%20Conversion%20Events\n * https://business.reddithelp.com/s/article/map-a-catalog-to-a-signal-source\n */\nexport interface RedditEvent {\n /** Match keys: Share user identifiers to match conversions to a Reddit ad engagement. */\n click_id?: string;\n\n /** Unix epoch timestamp in milliseconds, event_at can't be older than seven days. */\n event_at: number;\n\n /**\n * Where the conversion happened. Pixel events are deduplicated only against `WEBSITE` ones.\n * https://business.reddithelp.com/s/article/Conversions-API#measure-impact-across-channels\n */\n action_source: 'WEBSITE' | 'APP' | 'PHYSICAL_STORE' | 'OTHER';\n\n /**\n * The page the event happened on, for `WEBSITE` events: Reddit reads the domain from it, and the\n * click id when `click_id` is missing.\n */\n event_source_url?: string;\n\n type: {\n tracking_type: ServerStandardEvent | 'CUSTOM';\n custom_event_name?: string;\n };\n\n /**\n * Event metadata\n * Share as much additional information about your conversion event as you'd like. If you're\n * using the Conversions API with the pixel, conversion_id is required for deduplication.\n */\n metadata?: {\n conversion_id?: string;\n currency?: string; // ISO 4217 3-letter currency code\n item_count?: number;\n value?: number;\n products?: { id: string; name?: string; category?: string }[];\n };\n\n user?: {\n email?: string;\n external_id?: string;\n ip_address?: string;\n phone_number?: string;\n user_agent?: string;\n\n /** The Identifier for Advertisers (IDFA) of the user's Apple device. */\n idfa?: string;\n\n /** The Android Advertising ID (AAID) of the user's Android device. */\n aaid?: string;\n /**\n * The value from the first-party Pixel _rdt_uuid cookie on your domain. Note that it is in\n * the {timestamp}.{uuid} format. You may use the full value or just the UUID portion.\n * Example: 1684189007728.7c73f2ae-a433-4d7b-9838-f467da98f48e\n */\n uuid?: string;\n\n screen_dimensions?: { width: number; height: number };\n\n /**\n * A structure of data processing options to specify the processing type for the event\n * https://business.reddithelp.com/s/article/Limited-Data-Use\n */\n data_processing_options?: {\n country: string;\n region: string;\n modes: string[] | ['LDU'];\n };\n };\n}\n\nexport interface CreateRedditEventDTO {\n data: { test_id?: string; events: RedditEvent[] };\n}\n\nexport function getServerEvent(\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n event: TrackEvent<any>,\n data: UserProvidedData,\n actionSource?: EventActionSource\n): RedditEvent {\n const { id, name, properties, tags, platform, created_at } = event;\n const [type, params] = mapRDTEvent(name, properties, id);\n // An offline conversion — in store, from a CRM, over the phone — is `OTHER` rather than\n // `PHYSICAL_STORE`, which only one of those is; so is an undeterminable platform.\n const source = resolveActionSource(platform, actionSource);\n\n return {\n click_id: redditClickId(tags),\n event_at: new Date(created_at).getTime(),\n action_source: source === 'web' ? 'WEBSITE' : source === 'app' ? 'APP' : 'OTHER',\n event_source_url: source === 'web' ? pageLocation(tags) : undefined,\n type: {\n tracking_type: type === 'Custom' ? 'CUSTOM' : mapServerStandardEvent(type),\n custom_event_name: type === 'Custom' ? params.customEventName : undefined,\n },\n metadata: {\n conversion_id: id,\n currency:\n 'currency' in params && typeof params.currency === 'string'\n ? params.currency.toUpperCase()\n : undefined,\n item_count:\n 'itemCount' in params && typeof params.itemCount === 'number'\n ? params.itemCount\n : undefined,\n value: 'value' in params && typeof params.value === 'number' ? params.value : undefined,\n products:\n 'products' in params && Array.isArray(params.products) && params.products.length > 0\n ? params.products\n : undefined,\n },\n user: {\n email: getFirst(data.email),\n external_id: data.user_id,\n ip_address: data.ip_address,\n phone_number: getFirst(data.phone_number),\n user_agent: data.user_agent,\n idfa: platform === 'ios' ? tags.advertising_id : undefined,\n aaid: platform === 'android' ? tags.advertising_id : undefined,\n uuid: redditUuid(tags),\n screen_dimensions:\n tags.screen_width && tags.screen_height\n ? { width: tags.screen_width, height: tags.screen_height }\n : undefined,\n },\n };\n}\n\n/** `event_at` \"can't be older than seven days\"; a minute's margin for the trip. */\nconst MAX_EVENT_AGE_MS = 7 * 24 * 60 * 60 * 1000 - 60 * 1000;\n\nexport async function sendEvents(\n accessToken: string,\n pixelId: string,\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n events: TrackEvent<any>[],\n data: UserProvidedData = {},\n testId?: string,\n actionSource?: EventActionSource\n) {\n const dto: CreateRedditEventDTO = {\n data: {\n test_id: testId,\n events: events\n .filter((event) => !IGNORED_EVENTS.includes(event.name))\n .filter((event) => Date.now() - Date.parse(event.created_at) <= MAX_EVENT_AGE_MS)\n .map((event) => getServerEvent(event, data, actionSource)),\n },\n };\n\n if (dto.data.events.length === 0) return;\n\n try {\n const response = await fetch(\n `https://ads-api.reddit.com/api/v3/pixels/${pixelId}/conversion_events`,\n {\n method: 'POST',\n // Retried although a POST: the platform deduplicates on the `conversion_id` each event carries.\n retries: 3,\n headers: {\n 'Content-Type': 'application/json',\n Accept: 'application/json',\n Authorization: `Bearer ${accessToken}`,\n },\n body: JSON.stringify(dto),\n }\n );\n if (response.ok) return;\n const { status } = response;\n const message = await response.text();\n console.error(`Failed to send Reddit conversion, status: ${status}, body: ${message}`);\n } catch (error) {\n console.error('Failed to send Reddit conversion, network error:', error);\n }\n}\n"],"mappings":";;;;;;;;AAuFA,SAAgB,eAEd,OACA,MACA,cACa;CACb,MAAM,EAAE,IAAI,MAAM,YAAY,MAAM,UAAU,eAAe;CAC7D,MAAM,CAAC,MAAM,UAAU,YAAY,MAAM,YAAY,EAAE;CAGvD,MAAM,SAAS,oBAAoB,UAAU,YAAY;CAEzD,OAAO;EACL,UAAU,cAAc,IAAI;EAC5B,UAAU,IAAI,KAAK,UAAU,CAAC,CAAC,QAAQ;EACvC,eAAe,WAAW,QAAQ,YAAY,WAAW,QAAQ,QAAQ;EACzE,kBAAkB,WAAW,QAAQ,aAAa,IAAI,IAAI,KAAA;EAC1D,MAAM;GACJ,eAAe,SAAS,WAAW,WAAW,uBAAuB,IAAI;GACzE,mBAAmB,SAAS,WAAW,OAAO,kBAAkB,KAAA;EAClE;EACA,UAAU;GACR,eAAe;GACf,UACE,cAAc,UAAU,OAAO,OAAO,aAAa,WAC/C,OAAO,SAAS,YAAY,IAC5B,KAAA;GACN,YACE,eAAe,UAAU,OAAO,OAAO,cAAc,WACjD,OAAO,YACP,KAAA;GACN,OAAO,WAAW,UAAU,OAAO,OAAO,UAAU,WAAW,OAAO,QAAQ,KAAA;GAC9E,UACE,cAAc,UAAU,MAAM,QAAQ,OAAO,QAAQ,KAAK,OAAO,SAAS,SAAS,IAC/E,OAAO,WACP,KAAA;EACR;EACA,MAAM;GACJ,OAAO,SAAS,KAAK,KAAK;GAC1B,aAAa,KAAK;GAClB,YAAY,KAAK;GACjB,cAAc,SAAS,KAAK,YAAY;GACxC,YAAY,KAAK;GACjB,MAAM,aAAa,QAAQ,KAAK,iBAAiB,KAAA;GACjD,MAAM,aAAa,YAAY,KAAK,iBAAiB,KAAA;GACrD,MAAM,WAAW,IAAI;GACrB,mBACE,KAAK,gBAAgB,KAAK,gBACtB;IAAE,OAAO,KAAK;IAAc,QAAQ,KAAK;GAAc,IACvD,KAAA;EACR;CACF;AACF;;AAGA,MAAM,mBAAmB;AAEzB,eAAsB,WACpB,aACA,SAEA,QACA,OAAyB,CAAC,GAC1B,QACA,cACA;CACA,MAAM,MAA4B,EAChC,MAAM;EACJ,SAAS;EACT,QAAQ,OACL,QAAQ,UAAU,CAAC,eAAe,SAAS,MAAM,IAAI,CAAC,CAAC,CACvD,QAAQ,UAAU,KAAK,IAAI,IAAI,KAAK,MAAM,MAAM,UAAU,KAAK,gBAAgB,CAAC,CAChF,KAAK,UAAU,eAAe,OAAO,MAAM,YAAY,CAAC;CAC7D,EACF;CAEA,IAAI,IAAI,KAAK,OAAO,WAAW,GAAG;CAElC,IAAI;EACF,MAAM,WAAW,MAAM,MACrB,4CAA4C,QAAQ,qBACpD;GACE,QAAQ;GAER,SAAS;GACT,SAAS;IACP,gBAAgB;IAChB,QAAQ;IACR,eAAe,UAAU;GAC3B;GACA,MAAM,KAAK,UAAU,GAAG;EAC1B,CACF;EACA,IAAI,SAAS,IAAI;EACjB,MAAM,EAAE,WAAW;EACnB,MAAM,UAAU,MAAM,SAAS,KAAK;EACpC,QAAQ,MAAM,6CAA6C,OAAO,UAAU,SAAS;CACvF,SAAS,OAAO;EACd,QAAQ,MAAM,oDAAoD,KAAK;CACzE;AACF"}
1
+ {"version":3,"file":"reddit-conversions-api.mjs","names":[],"sources":["../../src/server/reddit-conversions-api.ts"],"sourcesContent":["import { fetch } from '@shware/utils';\nimport { IGNORED_EVENTS } from '../third-parties/ignored-events';\nimport { adEvents } from '../third-parties/integration';\nimport type { RedditAdsOptions } from '../third-parties/reddit-pixel';\nimport {\n type ServerStandardEvent,\n isStandardRDTEvent,\n mapRDTEvent,\n mapServerStandardEvent,\n} from '../track/rdt';\nimport type { TrackEvent, UserProvidedData } from '../track/types';\nimport { getFirst } from '../utils/field';\nimport { type EventActionSource, resolveActionSource } from './action-source';\nimport { redditClickId, redditUuid } from './click-ids';\nimport { ConversionsApiError } from './conversions-api-error';\nimport { pageLocation } from './page-location';\nimport { type ConversionDestination, conversionDestination } from './setup-conversions';\n\n/**\n * https://ads-api.reddit.com/docs/v3/operations/Post%20Conversion%20Events\n * https://business.reddithelp.com/s/article/map-a-catalog-to-a-signal-source\n */\nexport interface RedditEvent {\n /** Match keys: Share user identifiers to match conversions to a Reddit ad engagement. */\n click_id?: string;\n\n /** Unix epoch timestamp in milliseconds, event_at can't be older than seven days. */\n event_at: number;\n\n /**\n * Where the conversion happened. Pixel events are deduplicated only against `WEBSITE` ones.\n * https://business.reddithelp.com/s/article/Conversions-API#measure-impact-across-channels\n */\n action_source: 'WEBSITE' | 'APP' | 'PHYSICAL_STORE' | 'OTHER';\n\n /**\n * The page the event happened on, for `WEBSITE` events: Reddit reads the domain from it, and the\n * click id when `click_id` is missing.\n */\n event_source_url?: string;\n\n type: {\n tracking_type: ServerStandardEvent | 'CUSTOM';\n custom_event_name?: string;\n };\n\n /**\n * Event metadata\n * Share as much additional information about your conversion event as you'd like. If you're\n * using the Conversions API with the pixel, conversion_id is required for deduplication.\n */\n metadata?: {\n conversion_id?: string;\n currency?: string; // ISO 4217 3-letter currency code\n item_count?: number;\n value?: number;\n products?: { id: string; name?: string; category?: string }[];\n };\n\n user?: {\n email?: string;\n external_id?: string;\n ip_address?: string;\n phone_number?: string;\n user_agent?: string;\n\n /** The Identifier for Advertisers (IDFA) of the user's Apple device. */\n idfa?: string;\n\n /** The Android Advertising ID (AAID) of the user's Android device. */\n aaid?: string;\n /**\n * The value from the first-party Pixel _rdt_uuid cookie on your domain. Note that it is in\n * the {timestamp}.{uuid} format. You may use the full value or just the UUID portion.\n * Example: 1684189007728.7c73f2ae-a433-4d7b-9838-f467da98f48e\n */\n uuid?: string;\n\n screen_dimensions?: { width: number; height: number };\n\n /**\n * A structure of data processing options to specify the processing type for the event\n * https://business.reddithelp.com/s/article/Limited-Data-Use\n */\n data_processing_options?: {\n country: string;\n region: string;\n modes: string[] | ['LDU'];\n };\n };\n}\n\nexport interface CreateRedditEventDTO {\n data: { test_id?: string; events: RedditEvent[] };\n}\n\nexport function getServerEvent(\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n event: TrackEvent<any>,\n data: UserProvidedData,\n actionSource?: EventActionSource\n): RedditEvent {\n const { id, name, properties, tags, platform, created_at } = event;\n const [type, params] = mapRDTEvent(name, properties, id);\n // An offline conversion — in store, from a CRM, over the phone — is `OTHER` rather than\n // `PHYSICAL_STORE`, which only one of those is; so is an undeterminable platform.\n const source = resolveActionSource(platform, actionSource);\n\n return {\n click_id: redditClickId(tags),\n event_at: new Date(created_at).getTime(),\n action_source: source === 'web' ? 'WEBSITE' : source === 'app' ? 'APP' : 'OTHER',\n event_source_url: source === 'web' ? pageLocation(tags) : undefined,\n type: {\n tracking_type: type === 'Custom' ? 'CUSTOM' : mapServerStandardEvent(type),\n custom_event_name: type === 'Custom' ? params.customEventName : undefined,\n },\n metadata: {\n conversion_id: id,\n currency:\n 'currency' in params && typeof params.currency === 'string'\n ? params.currency.toUpperCase()\n : undefined,\n item_count:\n 'itemCount' in params && typeof params.itemCount === 'number'\n ? params.itemCount\n : undefined,\n value: 'value' in params && typeof params.value === 'number' ? params.value : undefined,\n products:\n 'products' in params && Array.isArray(params.products) && params.products.length > 0\n ? params.products\n : undefined,\n },\n user: {\n email: getFirst(data.email),\n external_id: data.user_id,\n ip_address: data.ip_address,\n phone_number: getFirst(data.phone_number),\n user_agent: data.user_agent,\n idfa: platform === 'ios' ? tags.advertising_id : undefined,\n aaid: platform === 'android' ? tags.advertising_id : undefined,\n uuid: redditUuid(tags),\n screen_dimensions:\n tags.screen_width && tags.screen_height\n ? { width: tags.screen_width, height: tags.screen_height }\n : undefined,\n },\n };\n}\n\n/** `event_at` \"can't be older than seven days\"; a minute's margin for the trip. */\nconst MAX_EVENT_AGE_MS = 7 * 24 * 60 * 60 * 1000 - 60 * 1000;\n\nexport async function sendEvents(\n accessToken: string,\n pixelId: string,\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n events: TrackEvent<any>[],\n data: UserProvidedData = {},\n testId?: string,\n actionSource?: EventActionSource\n) {\n const dto: CreateRedditEventDTO = {\n data: {\n test_id: testId,\n events: events\n .filter((event) => !IGNORED_EVENTS.includes(event.name))\n .filter((event) => Date.now() - Date.parse(event.created_at) <= MAX_EVENT_AGE_MS)\n .map((event) => getServerEvent(event, data, actionSource)),\n },\n };\n\n if (dto.data.events.length === 0) return;\n\n const response = await fetch(\n `https://ads-api.reddit.com/api/v3/pixels/${pixelId}/conversion_events`,\n {\n method: 'POST',\n // Retried although a POST: the platform deduplicates on the `conversion_id` each event carries.\n retries: 3,\n headers: {\n 'Content-Type': 'application/json',\n Accept: 'application/json',\n Authorization: `Bearer ${accessToken}`,\n },\n body: JSON.stringify(dto),\n }\n );\n if (response.ok) return;\n throw new ConversionsApiError('reddit', response.status, await response.text());\n}\n\n/** Reddit's Conversions API, sent the same events as `redditAds`. */\nexport function redditConversions(\n options: RedditAdsOptions & { accessToken: string; testId?: string }\n): ConversionDestination {\n return conversionDestination(adEvents(isStandardRDTEvent, options.customEvents), (events, data) =>\n sendEvents(options.accessToken, options.pixelId, events, data, options.testId)\n );\n}\n"],"mappings":";;;;;;;;;;;AAgGA,SAAgB,eAEd,OACA,MACA,cACa;CACb,MAAM,EAAE,IAAI,MAAM,YAAY,MAAM,UAAU,eAAe;CAC7D,MAAM,CAAC,MAAM,UAAU,YAAY,MAAM,YAAY,EAAE;CAGvD,MAAM,SAAS,oBAAoB,UAAU,YAAY;CAEzD,OAAO;EACL,UAAU,cAAc,IAAI;EAC5B,UAAU,IAAI,KAAK,UAAU,CAAC,CAAC,QAAQ;EACvC,eAAe,WAAW,QAAQ,YAAY,WAAW,QAAQ,QAAQ;EACzE,kBAAkB,WAAW,QAAQ,aAAa,IAAI,IAAI,KAAA;EAC1D,MAAM;GACJ,eAAe,SAAS,WAAW,WAAW,uBAAuB,IAAI;GACzE,mBAAmB,SAAS,WAAW,OAAO,kBAAkB,KAAA;EAClE;EACA,UAAU;GACR,eAAe;GACf,UACE,cAAc,UAAU,OAAO,OAAO,aAAa,WAC/C,OAAO,SAAS,YAAY,IAC5B,KAAA;GACN,YACE,eAAe,UAAU,OAAO,OAAO,cAAc,WACjD,OAAO,YACP,KAAA;GACN,OAAO,WAAW,UAAU,OAAO,OAAO,UAAU,WAAW,OAAO,QAAQ,KAAA;GAC9E,UACE,cAAc,UAAU,MAAM,QAAQ,OAAO,QAAQ,KAAK,OAAO,SAAS,SAAS,IAC/E,OAAO,WACP,KAAA;EACR;EACA,MAAM;GACJ,OAAO,SAAS,KAAK,KAAK;GAC1B,aAAa,KAAK;GAClB,YAAY,KAAK;GACjB,cAAc,SAAS,KAAK,YAAY;GACxC,YAAY,KAAK;GACjB,MAAM,aAAa,QAAQ,KAAK,iBAAiB,KAAA;GACjD,MAAM,aAAa,YAAY,KAAK,iBAAiB,KAAA;GACrD,MAAM,WAAW,IAAI;GACrB,mBACE,KAAK,gBAAgB,KAAK,gBACtB;IAAE,OAAO,KAAK;IAAc,QAAQ,KAAK;GAAc,IACvD,KAAA;EACR;CACF;AACF;;AAGA,MAAM,mBAAmB;AAEzB,eAAsB,WACpB,aACA,SAEA,QACA,OAAyB,CAAC,GAC1B,QACA,cACA;CACA,MAAM,MAA4B,EAChC,MAAM;EACJ,SAAS;EACT,QAAQ,OACL,QAAQ,UAAU,CAAC,eAAe,SAAS,MAAM,IAAI,CAAC,CAAC,CACvD,QAAQ,UAAU,KAAK,IAAI,IAAI,KAAK,MAAM,MAAM,UAAU,KAAK,gBAAgB,CAAC,CAChF,KAAK,UAAU,eAAe,OAAO,MAAM,YAAY,CAAC;CAC7D,EACF;CAEA,IAAI,IAAI,KAAK,OAAO,WAAW,GAAG;CAElC,MAAM,WAAW,MAAM,MACrB,4CAA4C,QAAQ,qBACpD;EACE,QAAQ;EAER,SAAS;EACT,SAAS;GACP,gBAAgB;GAChB,QAAQ;GACR,eAAe,UAAU;EAC3B;EACA,MAAM,KAAK,UAAU,GAAG;CAC1B,CACF;CACA,IAAI,SAAS,IAAI;CACjB,MAAM,IAAI,oBAAoB,UAAU,SAAS,QAAQ,MAAM,SAAS,KAAK,CAAC;AAChF;;AAGA,SAAgB,kBACd,SACuB;CACvB,OAAO,sBAAsB,SAAS,oBAAoB,QAAQ,YAAY,IAAI,QAAQ,SACxF,WAAW,QAAQ,aAAa,QAAQ,SAAS,QAAQ,MAAM,QAAQ,MAAM,CAC/E;AACF"}
@@ -0,0 +1,62 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ // src/server/setup-conversions.ts
3
+ /**
4
+ * A destination that sends only the events `accepts` lets through, and makes no request when none
5
+ * is left: what each conversions API's factory (`metaConversions`, …) is built on.
6
+ */
7
+ function conversionDestination(accepts, send) {
8
+ return { send: async (events, data) => {
9
+ const accepted = events.filter((event) => accepts(event.name));
10
+ if (accepted.length > 0) await send(accepted, data);
11
+ } };
12
+ }
13
+ function setupConversions(options) {
14
+ const { destinations, track: trackOptions } = options;
15
+ async function forward(events, data = {}) {
16
+ if (events.length === 0) return;
17
+ const settled = await Promise.allSettled(destinations.map((d) => Promise.resolve().then(() => d.send(events, data))));
18
+ const ids = events.map((event) => event.id).join(", ");
19
+ settled.forEach((outcome) => {
20
+ if (outcome.status === "rejected") console.error(`Conversions not sent, events: ${ids}`, outcome.reason);
21
+ });
22
+ }
23
+ /**
24
+ * Reports a server-only event; resolves with it as sent, or `undefined` when it was not: a
25
+ * user with no session, an event `store` had already stored, or a failure, which is logged.
26
+ */
27
+ async function track({ resolveUser, store }, input) {
28
+ try {
29
+ const user = await resolveUser(input.userId);
30
+ if (!user) {
31
+ console.warn(`Conversion not reported, event: ${input.id}: no session for ${input.userId}`);
32
+ return;
33
+ }
34
+ const event = {
35
+ id: input.id,
36
+ name: input.name,
37
+ properties: input.properties,
38
+ tags: user.tags,
39
+ visitor_id: user.visitor_id,
40
+ session_id: user.session_id,
41
+ platform: user.platform,
42
+ environment: user.environment,
43
+ created_at: input.createdAt
44
+ };
45
+ if (!await store(event)) return void 0;
46
+ await forward([event], user.data);
47
+ return event;
48
+ } catch (e) {
49
+ console.error(`Conversion not reported, event: ${input.id}`, e);
50
+ return;
51
+ }
52
+ }
53
+ if (!trackOptions) return { forward };
54
+ return {
55
+ forward,
56
+ track: (input) => track(trackOptions, input)
57
+ };
58
+ }
59
+ exports.conversionDestination = conversionDestination;
60
+ exports.setupConversions = setupConversions;
61
+
62
+ //# sourceMappingURL=setup-conversions.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"setup-conversions.cjs","names":[],"sources":["../../src/server/setup-conversions.ts"],"sourcesContent":["import type {\n Environment,\n EventName,\n Platform,\n TrackEvent,\n TrackName,\n TrackProperties,\n TrackTags,\n UserProvidedData,\n} from '../track/types';\n\n// oxlint-disable-next-line @typescript-eslint/no-explicit-any\ntype AnyTrackEvent = TrackEvent<any>;\n\n/**\n * Where `setupConversions` sends events: an ad platform's conversions API, from its factory\n * (`metaConversions`, … next to each sender), or anything else the host forwards events to (a\n * CRM, its own workflows).\n *\n * `send` rejects when it fails, as the SDK's senders do: `setupConversions` logs the failure,\n * with the events' ids, and still sends to the others.\n */\nexport interface ConversionDestination {\n readonly send: (events: AnyTrackEvent[], data: UserProvidedData) => Promise<unknown>;\n}\n\n/**\n * A destination that sends only the events `accepts` lets through, and makes no request when none\n * is left: what each conversions API's factory (`metaConversions`, …) is built on.\n */\nexport function conversionDestination(\n accepts: (name: string) => boolean,\n send: (events: AnyTrackEvent[], data: UserProvidedData) => Promise<unknown>\n): ConversionDestination {\n return {\n send: async (events, data) => {\n const accepted = events.filter((event) => accepts(event.name));\n if (accepted.length > 0) await send(accepted, data);\n },\n };\n}\n\n/**\n * Who a server-only event is from, as the host knows them: what the ad platforms match a client\n * event on, read from the host's own records.\n *\n * - `tags`: the user's latest session's tags (their cookies — `_fbp`, `_rdt_uuid`, … — page\n * and user agent), with the click ids of the touch the conversion is attributed to over them.\n * - `visitor_id`, `session_id`, `platform`, `environment`: from that session. `platform` decides\n * each platform's action source (website or app), as for a client event.\n * - `data`: the user's identity (`email`, `user_id`, …), hashed by each sender.\n */\nexport interface ConversionUser {\n tags: TrackTags;\n visitor_id: string;\n session_id: string;\n platform: Platform;\n environment: Environment;\n data: UserProvidedData;\n}\n\n/**\n * An event the server reports on its own, with no client behind it: a webhook's purchase,\n * renewal or refund. `id` is the transaction id: `track.store` keeps a redelivered webhook from\n * being reported twice, and the platforms pair it with a browser event under the same id.\n */\nexport interface ServerEvent<T extends EventName = EventName> {\n id: string;\n name: TrackName<T>;\n /** The user it belongs to, handed to `track.resolveUser`. */\n userId: string;\n properties?: TrackProperties<T>;\n /** When it happened, as an ISO 8601 string. */\n createdAt: string;\n}\n\nexport interface ConversionsOptions {\n destinations: readonly ConversionDestination[];\n /**\n * How `track` completes and stores a server-only event. Without it `setupConversions` returns\n * only `forward`, for a host that only forwards client events.\n */\n track?: {\n /**\n * The user behind the event, read from the host's records (see `ConversionUser`);\n * `undefined` for one the host has no session of, whose event is then dropped.\n */\n resolveUser: (userId: string) => Promise<ConversionUser | undefined>;\n /**\n * Stores the event, e.g. in the events table, returning whether it was new: `track` sends\n * only an event it stored, so a webhook delivered again (its handler failed on something\n * else) is not reported twice — not every platform deduplicates a server event sent twice.\n */\n store: (event: AnyTrackEvent) => Promise<boolean>;\n };\n}\n\n/**\n * The server's counterpart of `setupAnalytics({ integrations })`: every destination configured\n * once, with the same per-platform options as the browser integrations, so the conversions API\n * and the tag report the same events.\n *\n * - `forward(events, data)`: the events a client sent, as stored, on to every destination.\n * - `track(event)`: an event the server reports on its own (a webhook's), completed by\n * `track.resolveUser`, stored with `track.store`, then forwarded.\n *\n * Neither throws, so reporting a conversion can never fail the request it runs in — a payment\n * webhook least of all, which its provider would then deliver again and again. A failure is\n * logged with the ids of the events it lost, for them to be found and sent later: a missed\n * conversion costs less than a duplicate one, or a webhook that keeps failing.\n */\nexport function setupConversions(\n options: ConversionsOptions & { track: NonNullable<ConversionsOptions['track']> }\n): {\n forward: Forward;\n track: Track;\n};\nexport function setupConversions(options: ConversionsOptions): { forward: Forward };\nexport function setupConversions(options: ConversionsOptions) {\n const { destinations, track: trackOptions } = options;\n\n async function forward(events: AnyTrackEvent[], data: UserProvidedData = {}) {\n if (events.length === 0) return;\n // Called inside a promise: a `send` that throws synchronously rejects there instead of\n // stopping the destinations after it.\n const settled = await Promise.allSettled(\n destinations.map((d) => Promise.resolve().then(() => d.send(events, data)))\n );\n const ids = events.map((event) => event.id).join(', ');\n settled.forEach((outcome) => {\n if (outcome.status === 'rejected') {\n console.error(`Conversions not sent, events: ${ids}`, outcome.reason);\n }\n });\n }\n\n /**\n * Reports a server-only event; resolves with it as sent, or `undefined` when it was not: a\n * user with no session, an event `store` had already stored, or a failure, which is logged.\n */\n async function track<T extends EventName>(\n { resolveUser, store }: NonNullable<ConversionsOptions['track']>,\n input: ServerEvent<T>\n ): Promise<TrackEvent<T> | undefined> {\n try {\n const user = await resolveUser(input.userId);\n if (!user) {\n console.warn(`Conversion not reported, event: ${input.id}: no session for ${input.userId}`);\n return undefined;\n }\n const event: TrackEvent<T> = {\n id: input.id,\n name: input.name,\n properties: input.properties,\n tags: user.tags,\n visitor_id: user.visitor_id,\n session_id: user.session_id,\n platform: user.platform,\n environment: user.environment,\n created_at: input.createdAt,\n };\n if (!(await store(event))) return undefined;\n await forward([event], user.data);\n return event;\n } catch (e: unknown) {\n console.error(`Conversion not reported, event: ${input.id}`, e);\n return undefined;\n }\n }\n\n if (!trackOptions) return { forward };\n return { forward, track: (input: ServerEvent) => track(trackOptions, input) };\n}\n\ntype Forward = (events: AnyTrackEvent[], data?: UserProvidedData) => Promise<void>;\ntype Track = <T extends EventName>(input: ServerEvent<T>) => Promise<TrackEvent<T> | undefined>;\n"],"mappings":";;;;;;AA8BA,SAAgB,sBACd,SACA,MACuB;CACvB,OAAO,EACL,MAAM,OAAO,QAAQ,SAAS;EAC5B,MAAM,WAAW,OAAO,QAAQ,UAAU,QAAQ,MAAM,IAAI,CAAC;EAC7D,IAAI,SAAS,SAAS,GAAG,MAAM,KAAK,UAAU,IAAI;CACpD,EACF;AACF;AA8EA,SAAgB,iBAAiB,SAA6B;CAC5D,MAAM,EAAE,cAAc,OAAO,iBAAiB;CAE9C,eAAe,QAAQ,QAAyB,OAAyB,CAAC,GAAG;EAC3E,IAAI,OAAO,WAAW,GAAG;EAGzB,MAAM,UAAU,MAAM,QAAQ,WAC5B,aAAa,KAAK,MAAM,QAAQ,QAAQ,CAAC,CAAC,WAAW,EAAE,KAAK,QAAQ,IAAI,CAAC,CAAC,CAC5E;EACA,MAAM,MAAM,OAAO,KAAK,UAAU,MAAM,EAAE,CAAC,CAAC,KAAK,IAAI;EACrD,QAAQ,SAAS,YAAY;GAC3B,IAAI,QAAQ,WAAW,YACrB,QAAQ,MAAM,iCAAiC,OAAO,QAAQ,MAAM;EAExE,CAAC;CACH;;;;;CAMA,eAAe,MACb,EAAE,aAAa,SACf,OACoC;EACpC,IAAI;GACF,MAAM,OAAO,MAAM,YAAY,MAAM,MAAM;GAC3C,IAAI,CAAC,MAAM;IACT,QAAQ,KAAK,mCAAmC,MAAM,GAAG,mBAAmB,MAAM,QAAQ;IAC1F;GACF;GACA,MAAM,QAAuB;IAC3B,IAAI,MAAM;IACV,MAAM,MAAM;IACZ,YAAY,MAAM;IAClB,MAAM,KAAK;IACX,YAAY,KAAK;IACjB,YAAY,KAAK;IACjB,UAAU,KAAK;IACf,aAAa,KAAK;IAClB,YAAY,MAAM;GACpB;GACA,IAAI,CAAE,MAAM,MAAM,KAAK,GAAI,OAAO,KAAA;GAClC,MAAM,QAAQ,CAAC,KAAK,GAAG,KAAK,IAAI;GAChC,OAAO;EACT,SAAS,GAAY;GACnB,QAAQ,MAAM,mCAAmC,MAAM,MAAM,CAAC;GAC9D;EACF;CACF;CAEA,IAAI,CAAC,cAAc,OAAO,EAAE,QAAQ;CACpC,OAAO;EAAE;EAAS,QAAQ,UAAuB,MAAM,cAAc,KAAK;CAAE;AAC9E"}
@@ -0,0 +1,97 @@
1
+ import { Environment, EventName, Platform, TrackEvent, TrackName, TrackProperties, TrackTags, UserProvidedData } from "../track/types.cjs";
2
+ type AnyTrackEvent = TrackEvent<any>;
3
+ /**
4
+ * Where `setupConversions` sends events: an ad platform's conversions API, from its factory
5
+ * (`metaConversions`, … next to each sender), or anything else the host forwards events to (a
6
+ * CRM, its own workflows).
7
+ *
8
+ * `send` rejects when it fails, as the SDK's senders do: `setupConversions` logs the failure,
9
+ * with the events' ids, and still sends to the others.
10
+ */
11
+ export interface ConversionDestination {
12
+ readonly send: (events: AnyTrackEvent[], data: UserProvidedData) => Promise<unknown>;
13
+ }
14
+ /**
15
+ * A destination that sends only the events `accepts` lets through, and makes no request when none
16
+ * is left: what each conversions API's factory (`metaConversions`, …) is built on.
17
+ */
18
+ export declare function conversionDestination(accepts: (name: string) => boolean, send: (events: AnyTrackEvent[], data: UserProvidedData) => Promise<unknown>): ConversionDestination;
19
+ /**
20
+ * Who a server-only event is from, as the host knows them: what the ad platforms match a client
21
+ * event on, read from the host's own records.
22
+ *
23
+ * - `tags`: the user's latest session's tags (their cookies — `_fbp`, `_rdt_uuid`, … — page
24
+ * and user agent), with the click ids of the touch the conversion is attributed to over them.
25
+ * - `visitor_id`, `session_id`, `platform`, `environment`: from that session. `platform` decides
26
+ * each platform's action source (website or app), as for a client event.
27
+ * - `data`: the user's identity (`email`, `user_id`, …), hashed by each sender.
28
+ */
29
+ export interface ConversionUser {
30
+ tags: TrackTags;
31
+ visitor_id: string;
32
+ session_id: string;
33
+ platform: Platform;
34
+ environment: Environment;
35
+ data: UserProvidedData;
36
+ }
37
+ /**
38
+ * An event the server reports on its own, with no client behind it: a webhook's purchase,
39
+ * renewal or refund. `id` is the transaction id: `track.store` keeps a redelivered webhook from
40
+ * being reported twice, and the platforms pair it with a browser event under the same id.
41
+ */
42
+ export interface ServerEvent<T extends EventName = EventName> {
43
+ id: string;
44
+ name: TrackName<T>;
45
+ /** The user it belongs to, handed to `track.resolveUser`. */
46
+ userId: string;
47
+ properties?: TrackProperties<T>;
48
+ /** When it happened, as an ISO 8601 string. */
49
+ createdAt: string;
50
+ }
51
+ export interface ConversionsOptions {
52
+ destinations: readonly ConversionDestination[];
53
+ /**
54
+ * How `track` completes and stores a server-only event. Without it `setupConversions` returns
55
+ * only `forward`, for a host that only forwards client events.
56
+ */
57
+ track?: {
58
+ /**
59
+ * The user behind the event, read from the host's records (see `ConversionUser`);
60
+ * `undefined` for one the host has no session of, whose event is then dropped.
61
+ */
62
+ resolveUser: (userId: string) => Promise<ConversionUser | undefined>;
63
+ /**
64
+ * Stores the event, e.g. in the events table, returning whether it was new: `track` sends
65
+ * only an event it stored, so a webhook delivered again (its handler failed on something
66
+ * else) is not reported twice — not every platform deduplicates a server event sent twice.
67
+ */
68
+ store: (event: AnyTrackEvent) => Promise<boolean>;
69
+ };
70
+ }
71
+ /**
72
+ * The server's counterpart of `setupAnalytics({ integrations })`: every destination configured
73
+ * once, with the same per-platform options as the browser integrations, so the conversions API
74
+ * and the tag report the same events.
75
+ *
76
+ * - `forward(events, data)`: the events a client sent, as stored, on to every destination.
77
+ * - `track(event)`: an event the server reports on its own (a webhook's), completed by
78
+ * `track.resolveUser`, stored with `track.store`, then forwarded.
79
+ *
80
+ * Neither throws, so reporting a conversion can never fail the request it runs in — a payment
81
+ * webhook least of all, which its provider would then deliver again and again. A failure is
82
+ * logged with the ids of the events it lost, for them to be found and sent later: a missed
83
+ * conversion costs less than a duplicate one, or a webhook that keeps failing.
84
+ */
85
+ export declare function setupConversions(options: ConversionsOptions & {
86
+ track: NonNullable<ConversionsOptions['track']>;
87
+ }): {
88
+ forward: Forward;
89
+ track: Track;
90
+ };
91
+ export declare function setupConversions(options: ConversionsOptions): {
92
+ forward: Forward;
93
+ };
94
+ type Forward = (events: AnyTrackEvent[], data?: UserProvidedData) => Promise<void>;
95
+ type Track = <T extends EventName>(input: ServerEvent<T>) => Promise<TrackEvent<T> | undefined>;
96
+ export {};
97
+ //# sourceMappingURL=setup-conversions.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"setup-conversions.d.cts","names":[],"sources":["../../src/server/setup-conversions.ts"],"mappings":";KAYK,gBAAgB;;;;;;;;;iBAUJ;WACN,OAAO,QAAQ,iBAAiB,MAAM,qBAAqB;;;;;;wBAOtD,sBACd,UAAU,0BACV,OAAO,QAAQ,iBAAiB,MAAM,qBAAqB,mBAC1D;;;;;;;;;;;iBAmBc;EACf,MAAM;EACN;EACA;EACA,UAAU;EACV,aAAa;EACb,MAAM;;;;;;;iBAQS,YAAY,UAAU,YAAY;EACjD;EACA,MAAM,UAAU;;EAEhB;EACA,aAAa,gBAAgB;;EAE7B;;iBAGe;EACf,uBAAuB;;;;;EAKvB;;;;;IAKE,cAAc,mBAAmB,QAAQ;;;;;;IAMzC,QAAQ,OAAO,kBAAkB;;;;;;;;;;;;;;;;;wBAkBrB,iBACd,SAAS;EAAuB,OAAO,YAAY;;EAEnD,SAAS;EACT,OAAO;;wBAEO,iBAAiB,SAAS;EAAuB,SAAS;;KAyDrE,WAAW,QAAQ,iBAAiB,OAAO,qBAAqB;KAChE,SAAS,UAAU,WAAW,OAAO,YAAY,OAAO,QAAQ,WAAW"}
@@ -0,0 +1,97 @@
1
+ import { Environment, EventName, Platform, TrackEvent, TrackName, TrackProperties, TrackTags, UserProvidedData } from "../track/types.mjs";
2
+ type AnyTrackEvent = TrackEvent<any>;
3
+ /**
4
+ * Where `setupConversions` sends events: an ad platform's conversions API, from its factory
5
+ * (`metaConversions`, … next to each sender), or anything else the host forwards events to (a
6
+ * CRM, its own workflows).
7
+ *
8
+ * `send` rejects when it fails, as the SDK's senders do: `setupConversions` logs the failure,
9
+ * with the events' ids, and still sends to the others.
10
+ */
11
+ export interface ConversionDestination {
12
+ readonly send: (events: AnyTrackEvent[], data: UserProvidedData) => Promise<unknown>;
13
+ }
14
+ /**
15
+ * A destination that sends only the events `accepts` lets through, and makes no request when none
16
+ * is left: what each conversions API's factory (`metaConversions`, …) is built on.
17
+ */
18
+ export declare function conversionDestination(accepts: (name: string) => boolean, send: (events: AnyTrackEvent[], data: UserProvidedData) => Promise<unknown>): ConversionDestination;
19
+ /**
20
+ * Who a server-only event is from, as the host knows them: what the ad platforms match a client
21
+ * event on, read from the host's own records.
22
+ *
23
+ * - `tags`: the user's latest session's tags (their cookies — `_fbp`, `_rdt_uuid`, … — page
24
+ * and user agent), with the click ids of the touch the conversion is attributed to over them.
25
+ * - `visitor_id`, `session_id`, `platform`, `environment`: from that session. `platform` decides
26
+ * each platform's action source (website or app), as for a client event.
27
+ * - `data`: the user's identity (`email`, `user_id`, …), hashed by each sender.
28
+ */
29
+ export interface ConversionUser {
30
+ tags: TrackTags;
31
+ visitor_id: string;
32
+ session_id: string;
33
+ platform: Platform;
34
+ environment: Environment;
35
+ data: UserProvidedData;
36
+ }
37
+ /**
38
+ * An event the server reports on its own, with no client behind it: a webhook's purchase,
39
+ * renewal or refund. `id` is the transaction id: `track.store` keeps a redelivered webhook from
40
+ * being reported twice, and the platforms pair it with a browser event under the same id.
41
+ */
42
+ export interface ServerEvent<T extends EventName = EventName> {
43
+ id: string;
44
+ name: TrackName<T>;
45
+ /** The user it belongs to, handed to `track.resolveUser`. */
46
+ userId: string;
47
+ properties?: TrackProperties<T>;
48
+ /** When it happened, as an ISO 8601 string. */
49
+ createdAt: string;
50
+ }
51
+ export interface ConversionsOptions {
52
+ destinations: readonly ConversionDestination[];
53
+ /**
54
+ * How `track` completes and stores a server-only event. Without it `setupConversions` returns
55
+ * only `forward`, for a host that only forwards client events.
56
+ */
57
+ track?: {
58
+ /**
59
+ * The user behind the event, read from the host's records (see `ConversionUser`);
60
+ * `undefined` for one the host has no session of, whose event is then dropped.
61
+ */
62
+ resolveUser: (userId: string) => Promise<ConversionUser | undefined>;
63
+ /**
64
+ * Stores the event, e.g. in the events table, returning whether it was new: `track` sends
65
+ * only an event it stored, so a webhook delivered again (its handler failed on something
66
+ * else) is not reported twice — not every platform deduplicates a server event sent twice.
67
+ */
68
+ store: (event: AnyTrackEvent) => Promise<boolean>;
69
+ };
70
+ }
71
+ /**
72
+ * The server's counterpart of `setupAnalytics({ integrations })`: every destination configured
73
+ * once, with the same per-platform options as the browser integrations, so the conversions API
74
+ * and the tag report the same events.
75
+ *
76
+ * - `forward(events, data)`: the events a client sent, as stored, on to every destination.
77
+ * - `track(event)`: an event the server reports on its own (a webhook's), completed by
78
+ * `track.resolveUser`, stored with `track.store`, then forwarded.
79
+ *
80
+ * Neither throws, so reporting a conversion can never fail the request it runs in — a payment
81
+ * webhook least of all, which its provider would then deliver again and again. A failure is
82
+ * logged with the ids of the events it lost, for them to be found and sent later: a missed
83
+ * conversion costs less than a duplicate one, or a webhook that keeps failing.
84
+ */
85
+ export declare function setupConversions(options: ConversionsOptions & {
86
+ track: NonNullable<ConversionsOptions['track']>;
87
+ }): {
88
+ forward: Forward;
89
+ track: Track;
90
+ };
91
+ export declare function setupConversions(options: ConversionsOptions): {
92
+ forward: Forward;
93
+ };
94
+ type Forward = (events: AnyTrackEvent[], data?: UserProvidedData) => Promise<void>;
95
+ type Track = <T extends EventName>(input: ServerEvent<T>) => Promise<TrackEvent<T> | undefined>;
96
+ export {};
97
+ //# sourceMappingURL=setup-conversions.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"setup-conversions.d.mts","names":[],"sources":["../../src/server/setup-conversions.ts"],"mappings":";KAYK,gBAAgB;;;;;;;;;iBAUJ;WACN,OAAO,QAAQ,iBAAiB,MAAM,qBAAqB;;;;;;wBAOtD,sBACd,UAAU,0BACV,OAAO,QAAQ,iBAAiB,MAAM,qBAAqB,mBAC1D;;;;;;;;;;;iBAmBc;EACf,MAAM;EACN;EACA;EACA,UAAU;EACV,aAAa;EACb,MAAM;;;;;;;iBAQS,YAAY,UAAU,YAAY;EACjD;EACA,MAAM,UAAU;;EAEhB;EACA,aAAa,gBAAgB;;EAE7B;;iBAGe;EACf,uBAAuB;;;;;EAKvB;;;;;IAKE,cAAc,mBAAmB,QAAQ;;;;;;IAMzC,QAAQ,OAAO,kBAAkB;;;;;;;;;;;;;;;;;wBAkBrB,iBACd,SAAS;EAAuB,OAAO,YAAY;;EAEnD,SAAS;EACT,OAAO;;wBAEO,iBAAiB,SAAS;EAAuB,SAAS;;KAyDrE,WAAW,QAAQ,iBAAiB,OAAO,qBAAqB;KAChE,SAAS,UAAU,WAAW,OAAO,YAAY,OAAO,QAAQ,WAAW"}
@@ -0,0 +1,60 @@
1
+ // src/server/setup-conversions.ts
2
+ /**
3
+ * A destination that sends only the events `accepts` lets through, and makes no request when none
4
+ * is left: what each conversions API's factory (`metaConversions`, …) is built on.
5
+ */
6
+ function conversionDestination(accepts, send) {
7
+ return { send: async (events, data) => {
8
+ const accepted = events.filter((event) => accepts(event.name));
9
+ if (accepted.length > 0) await send(accepted, data);
10
+ } };
11
+ }
12
+ function setupConversions(options) {
13
+ const { destinations, track: trackOptions } = options;
14
+ async function forward(events, data = {}) {
15
+ if (events.length === 0) return;
16
+ const settled = await Promise.allSettled(destinations.map((d) => Promise.resolve().then(() => d.send(events, data))));
17
+ const ids = events.map((event) => event.id).join(", ");
18
+ settled.forEach((outcome) => {
19
+ if (outcome.status === "rejected") console.error(`Conversions not sent, events: ${ids}`, outcome.reason);
20
+ });
21
+ }
22
+ /**
23
+ * Reports a server-only event; resolves with it as sent, or `undefined` when it was not: a
24
+ * user with no session, an event `store` had already stored, or a failure, which is logged.
25
+ */
26
+ async function track({ resolveUser, store }, input) {
27
+ try {
28
+ const user = await resolveUser(input.userId);
29
+ if (!user) {
30
+ console.warn(`Conversion not reported, event: ${input.id}: no session for ${input.userId}`);
31
+ return;
32
+ }
33
+ const event = {
34
+ id: input.id,
35
+ name: input.name,
36
+ properties: input.properties,
37
+ tags: user.tags,
38
+ visitor_id: user.visitor_id,
39
+ session_id: user.session_id,
40
+ platform: user.platform,
41
+ environment: user.environment,
42
+ created_at: input.createdAt
43
+ };
44
+ if (!await store(event)) return void 0;
45
+ await forward([event], user.data);
46
+ return event;
47
+ } catch (e) {
48
+ console.error(`Conversion not reported, event: ${input.id}`, e);
49
+ return;
50
+ }
51
+ }
52
+ if (!trackOptions) return { forward };
53
+ return {
54
+ forward,
55
+ track: (input) => track(trackOptions, input)
56
+ };
57
+ }
58
+ export { conversionDestination, setupConversions };
59
+
60
+ //# sourceMappingURL=setup-conversions.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"setup-conversions.mjs","names":[],"sources":["../../src/server/setup-conversions.ts"],"sourcesContent":["import type {\n Environment,\n EventName,\n Platform,\n TrackEvent,\n TrackName,\n TrackProperties,\n TrackTags,\n UserProvidedData,\n} from '../track/types';\n\n// oxlint-disable-next-line @typescript-eslint/no-explicit-any\ntype AnyTrackEvent = TrackEvent<any>;\n\n/**\n * Where `setupConversions` sends events: an ad platform's conversions API, from its factory\n * (`metaConversions`, … next to each sender), or anything else the host forwards events to (a\n * CRM, its own workflows).\n *\n * `send` rejects when it fails, as the SDK's senders do: `setupConversions` logs the failure,\n * with the events' ids, and still sends to the others.\n */\nexport interface ConversionDestination {\n readonly send: (events: AnyTrackEvent[], data: UserProvidedData) => Promise<unknown>;\n}\n\n/**\n * A destination that sends only the events `accepts` lets through, and makes no request when none\n * is left: what each conversions API's factory (`metaConversions`, …) is built on.\n */\nexport function conversionDestination(\n accepts: (name: string) => boolean,\n send: (events: AnyTrackEvent[], data: UserProvidedData) => Promise<unknown>\n): ConversionDestination {\n return {\n send: async (events, data) => {\n const accepted = events.filter((event) => accepts(event.name));\n if (accepted.length > 0) await send(accepted, data);\n },\n };\n}\n\n/**\n * Who a server-only event is from, as the host knows them: what the ad platforms match a client\n * event on, read from the host's own records.\n *\n * - `tags`: the user's latest session's tags (their cookies — `_fbp`, `_rdt_uuid`, … — page\n * and user agent), with the click ids of the touch the conversion is attributed to over them.\n * - `visitor_id`, `session_id`, `platform`, `environment`: from that session. `platform` decides\n * each platform's action source (website or app), as for a client event.\n * - `data`: the user's identity (`email`, `user_id`, …), hashed by each sender.\n */\nexport interface ConversionUser {\n tags: TrackTags;\n visitor_id: string;\n session_id: string;\n platform: Platform;\n environment: Environment;\n data: UserProvidedData;\n}\n\n/**\n * An event the server reports on its own, with no client behind it: a webhook's purchase,\n * renewal or refund. `id` is the transaction id: `track.store` keeps a redelivered webhook from\n * being reported twice, and the platforms pair it with a browser event under the same id.\n */\nexport interface ServerEvent<T extends EventName = EventName> {\n id: string;\n name: TrackName<T>;\n /** The user it belongs to, handed to `track.resolveUser`. */\n userId: string;\n properties?: TrackProperties<T>;\n /** When it happened, as an ISO 8601 string. */\n createdAt: string;\n}\n\nexport interface ConversionsOptions {\n destinations: readonly ConversionDestination[];\n /**\n * How `track` completes and stores a server-only event. Without it `setupConversions` returns\n * only `forward`, for a host that only forwards client events.\n */\n track?: {\n /**\n * The user behind the event, read from the host's records (see `ConversionUser`);\n * `undefined` for one the host has no session of, whose event is then dropped.\n */\n resolveUser: (userId: string) => Promise<ConversionUser | undefined>;\n /**\n * Stores the event, e.g. in the events table, returning whether it was new: `track` sends\n * only an event it stored, so a webhook delivered again (its handler failed on something\n * else) is not reported twice — not every platform deduplicates a server event sent twice.\n */\n store: (event: AnyTrackEvent) => Promise<boolean>;\n };\n}\n\n/**\n * The server's counterpart of `setupAnalytics({ integrations })`: every destination configured\n * once, with the same per-platform options as the browser integrations, so the conversions API\n * and the tag report the same events.\n *\n * - `forward(events, data)`: the events a client sent, as stored, on to every destination.\n * - `track(event)`: an event the server reports on its own (a webhook's), completed by\n * `track.resolveUser`, stored with `track.store`, then forwarded.\n *\n * Neither throws, so reporting a conversion can never fail the request it runs in — a payment\n * webhook least of all, which its provider would then deliver again and again. A failure is\n * logged with the ids of the events it lost, for them to be found and sent later: a missed\n * conversion costs less than a duplicate one, or a webhook that keeps failing.\n */\nexport function setupConversions(\n options: ConversionsOptions & { track: NonNullable<ConversionsOptions['track']> }\n): {\n forward: Forward;\n track: Track;\n};\nexport function setupConversions(options: ConversionsOptions): { forward: Forward };\nexport function setupConversions(options: ConversionsOptions) {\n const { destinations, track: trackOptions } = options;\n\n async function forward(events: AnyTrackEvent[], data: UserProvidedData = {}) {\n if (events.length === 0) return;\n // Called inside a promise: a `send` that throws synchronously rejects there instead of\n // stopping the destinations after it.\n const settled = await Promise.allSettled(\n destinations.map((d) => Promise.resolve().then(() => d.send(events, data)))\n );\n const ids = events.map((event) => event.id).join(', ');\n settled.forEach((outcome) => {\n if (outcome.status === 'rejected') {\n console.error(`Conversions not sent, events: ${ids}`, outcome.reason);\n }\n });\n }\n\n /**\n * Reports a server-only event; resolves with it as sent, or `undefined` when it was not: a\n * user with no session, an event `store` had already stored, or a failure, which is logged.\n */\n async function track<T extends EventName>(\n { resolveUser, store }: NonNullable<ConversionsOptions['track']>,\n input: ServerEvent<T>\n ): Promise<TrackEvent<T> | undefined> {\n try {\n const user = await resolveUser(input.userId);\n if (!user) {\n console.warn(`Conversion not reported, event: ${input.id}: no session for ${input.userId}`);\n return undefined;\n }\n const event: TrackEvent<T> = {\n id: input.id,\n name: input.name,\n properties: input.properties,\n tags: user.tags,\n visitor_id: user.visitor_id,\n session_id: user.session_id,\n platform: user.platform,\n environment: user.environment,\n created_at: input.createdAt,\n };\n if (!(await store(event))) return undefined;\n await forward([event], user.data);\n return event;\n } catch (e: unknown) {\n console.error(`Conversion not reported, event: ${input.id}`, e);\n return undefined;\n }\n }\n\n if (!trackOptions) return { forward };\n return { forward, track: (input: ServerEvent) => track(trackOptions, input) };\n}\n\ntype Forward = (events: AnyTrackEvent[], data?: UserProvidedData) => Promise<void>;\ntype Track = <T extends EventName>(input: ServerEvent<T>) => Promise<TrackEvent<T> | undefined>;\n"],"mappings":";;;;;AA8BA,SAAgB,sBACd,SACA,MACuB;CACvB,OAAO,EACL,MAAM,OAAO,QAAQ,SAAS;EAC5B,MAAM,WAAW,OAAO,QAAQ,UAAU,QAAQ,MAAM,IAAI,CAAC;EAC7D,IAAI,SAAS,SAAS,GAAG,MAAM,KAAK,UAAU,IAAI;CACpD,EACF;AACF;AA8EA,SAAgB,iBAAiB,SAA6B;CAC5D,MAAM,EAAE,cAAc,OAAO,iBAAiB;CAE9C,eAAe,QAAQ,QAAyB,OAAyB,CAAC,GAAG;EAC3E,IAAI,OAAO,WAAW,GAAG;EAGzB,MAAM,UAAU,MAAM,QAAQ,WAC5B,aAAa,KAAK,MAAM,QAAQ,QAAQ,CAAC,CAAC,WAAW,EAAE,KAAK,QAAQ,IAAI,CAAC,CAAC,CAC5E;EACA,MAAM,MAAM,OAAO,KAAK,UAAU,MAAM,EAAE,CAAC,CAAC,KAAK,IAAI;EACrD,QAAQ,SAAS,YAAY;GAC3B,IAAI,QAAQ,WAAW,YACrB,QAAQ,MAAM,iCAAiC,OAAO,QAAQ,MAAM;EAExE,CAAC;CACH;;;;;CAMA,eAAe,MACb,EAAE,aAAa,SACf,OACoC;EACpC,IAAI;GACF,MAAM,OAAO,MAAM,YAAY,MAAM,MAAM;GAC3C,IAAI,CAAC,MAAM;IACT,QAAQ,KAAK,mCAAmC,MAAM,GAAG,mBAAmB,MAAM,QAAQ;IAC1F;GACF;GACA,MAAM,QAAuB;IAC3B,IAAI,MAAM;IACV,MAAM,MAAM;IACZ,YAAY,MAAM;IAClB,MAAM,KAAK;IACX,YAAY,KAAK;IACjB,YAAY,KAAK;IACjB,UAAU,KAAK;IACf,aAAa,KAAK;IAClB,YAAY,MAAM;GACpB;GACA,IAAI,CAAE,MAAM,MAAM,KAAK,GAAI,OAAO,KAAA;GAClC,MAAM,QAAQ,CAAC,KAAK,GAAG,KAAK,IAAI;GAChC,OAAO;EACT,SAAS,GAAY;GACnB,QAAQ,MAAM,mCAAmC,MAAM,MAAM,CAAC;GAC9D;EACF;CACF;CAEA,IAAI,CAAC,cAAc,OAAO,EAAE,QAAQ;CACpC,OAAO;EAAE;EAAS,QAAQ,UAAuB,MAAM,cAAc,KAAK;CAAE;AAC9E"}
@@ -1,10 +1,10 @@
1
1
  import { AdsOptions, CONVERSION_EVENTS, Integration, IntegrationScript } from "./integration.cjs";
2
- import { googleAnalytics, sendGAEvent, setGAUser } from "./google-analytics.cjs";
3
2
  import { metaAds, sendFBEvent, setFBUser } from "./meta-pixel.cjs";
3
+ import { redditAds, sendRedditEvent, setRedditUser } from "./reddit-pixel.cjs";
4
4
  import { LinkedinConversionConfig, linkedInAds, sendLinkedinEvent, setLinkedinUser } from "./linkedin-insight-tag.cjs";
5
- import { PostHog, PostHogConfig, getLoadedPosthog, getPosthog, posthogAnalytics, posthogFlagsReady, sendPosthogEvent, setPosthogUser } from "./posthog.cjs";
6
5
  import { openaiAds, sendOpenAIEvent, setOpenAIUser } from "./openai-pixel.cjs";
7
- import { redditAds, sendRedditEvent, setRedditUser } from "./reddit-pixel.cjs";
8
6
  import { UETConsent, UETEventParams, UETItem, UETPageType, UETPid } from "../track/uetq.cjs";
9
7
  import { MicrosoftAdsIntegration, configureUET, microsoftAds, sendUETEvent, sendUETIdSync, setUETConsent, setUETUser, syncUETVisitor, uetCustomerIdOf } from "./microsoft-uet.cjs";
8
+ import { googleAnalytics, sendGAEvent, setGAUser } from "./google-analytics.cjs";
9
+ import { PostHog, PostHogConfig, getLoadedPosthog, getPosthog, posthogAnalytics, posthogFlagsReady, sendPosthogEvent, setPosthogUser } from "./posthog.cjs";
10
10
  export { type AdsOptions, CONVERSION_EVENTS, type Integration, type IntegrationScript, type LinkedinConversionConfig, type MicrosoftAdsIntegration, type PostHog, type PostHogConfig, type UETConsent, type UETEventParams, type UETItem, type UETPageType, type UETPid, configureUET, getLoadedPosthog, getPosthog, googleAnalytics, linkedInAds, metaAds, microsoftAds, openaiAds, posthogAnalytics, posthogFlagsReady, redditAds, sendFBEvent, sendGAEvent, sendLinkedinEvent, sendOpenAIEvent, sendPosthogEvent, sendRedditEvent, sendUETEvent, sendUETIdSync, setFBUser, setGAUser, setLinkedinUser, setOpenAIUser, setPosthogUser, setRedditUser, setUETConsent, setUETUser, syncUETVisitor, uetCustomerIdOf };
@@ -1,10 +1,10 @@
1
1
  import { AdsOptions, CONVERSION_EVENTS, Integration, IntegrationScript } from "./integration.mjs";
2
- import { googleAnalytics, sendGAEvent, setGAUser } from "./google-analytics.mjs";
3
2
  import { metaAds, sendFBEvent, setFBUser } from "./meta-pixel.mjs";
3
+ import { redditAds, sendRedditEvent, setRedditUser } from "./reddit-pixel.mjs";
4
4
  import { LinkedinConversionConfig, linkedInAds, sendLinkedinEvent, setLinkedinUser } from "./linkedin-insight-tag.mjs";
5
- import { PostHog, PostHogConfig, getLoadedPosthog, getPosthog, posthogAnalytics, posthogFlagsReady, sendPosthogEvent, setPosthogUser } from "./posthog.mjs";
6
5
  import { openaiAds, sendOpenAIEvent, setOpenAIUser } from "./openai-pixel.mjs";
7
- import { redditAds, sendRedditEvent, setRedditUser } from "./reddit-pixel.mjs";
8
6
  import { UETConsent, UETEventParams, UETItem, UETPageType, UETPid } from "../track/uetq.mjs";
9
7
  import { MicrosoftAdsIntegration, configureUET, microsoftAds, sendUETEvent, sendUETIdSync, setUETConsent, setUETUser, syncUETVisitor, uetCustomerIdOf } from "./microsoft-uet.mjs";
8
+ import { googleAnalytics, sendGAEvent, setGAUser } from "./google-analytics.mjs";
9
+ import { PostHog, PostHogConfig, getLoadedPosthog, getPosthog, posthogAnalytics, posthogFlagsReady, sendPosthogEvent, setPosthogUser } from "./posthog.mjs";
10
10
  export { type AdsOptions, CONVERSION_EVENTS, type Integration, type IntegrationScript, type LinkedinConversionConfig, type MicrosoftAdsIntegration, type PostHog, type PostHogConfig, type UETConsent, type UETEventParams, type UETItem, type UETPageType, type UETPid, configureUET, getLoadedPosthog, getPosthog, googleAnalytics, linkedInAds, metaAds, microsoftAds, openaiAds, posthogAnalytics, posthogFlagsReady, redditAds, sendFBEvent, sendGAEvent, sendLinkedinEvent, sendOpenAIEvent, sendPosthogEvent, sendRedditEvent, sendUETEvent, sendUETIdSync, setFBUser, setGAUser, setLinkedinUser, setOpenAIUser, setPosthogUser, setRedditUser, setUETConsent, setUETUser, syncUETVisitor, uetCustomerIdOf };
@@ -22,18 +22,25 @@ const CONVERSION_EVENTS = [
22
22
  "contact"
23
23
  ];
24
24
  /**
25
- * An ad tracker that sends only what `isStandard` accepts — the events the platform's mapper
26
- * turns into one of its standard events — and the custom events the host listed. Everything
27
- * else in the product (feature use, clicks, onboarding steps) is behavior analysis, which is
28
- * GA4's and PostHog's job, and only noise to an ad platform's optimization.
25
+ * Which events an ad platform receives: what `isStandard` accepts — the events its mapper turns
26
+ * into one of its standard events — and the custom events the host listed. Everything else in the
27
+ * product (feature use, clicks, onboarding steps) is behavior analysis, which is GA4's and
28
+ * PostHog's job, and only noise to an ad platform's optimization. The same rule picks what the
29
+ * browser tag and the platform's conversions API send (`@shware/analytics/server`), so the two
30
+ * report the same events.
29
31
  */
30
- function adsTracker(send, isStandard, customEvents) {
32
+ function adEvents(isStandard, customEvents = []) {
33
+ return (name) => isStandard(name) || customEvents.includes(name);
34
+ }
35
+ /** An ad tracker that sends only the events `accepts` lets through (`adEvents`). */
36
+ function adsTracker(send, accepts) {
31
37
  return (name, properties, eventId) => {
32
- if (!isStandard(name) && !customEvents.includes(name)) return;
38
+ if (!accepts(name)) return;
33
39
  return send(name, properties, eventId);
34
40
  };
35
41
  }
36
42
  exports.CONVERSION_EVENTS = CONVERSION_EVENTS;
43
+ exports.adEvents = adEvents;
37
44
  exports.adsTracker = adsTracker;
38
45
 
39
46
  //# sourceMappingURL=integration.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"integration.cjs","names":[],"sources":["../../src/third-parties/integration.ts"],"sourcesContent":["import type { EventName, ThirdPartyTracker } 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.\n */\n customEvents?: readonly EventName[];\n}\n\n/**\n * An ad tracker that sends only what `isStandard` accepts — the events the platform's mapper\n * turns into one of its standard events — and the custom events the host listed. Everything\n * else in the product (feature use, clicks, onboarding steps) is behavior analysis, which is\n * GA4's and PostHog's job, and only noise to an ad platform's optimization.\n */\nexport function adsTracker(\n send: ThirdPartyTracker,\n isStandard: (name: string) => boolean,\n customEvents: readonly string[]\n): ThirdPartyTracker {\n return (name, properties, eventId) => {\n if (!isStandard(name) && !customEvents.includes(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;;;;;;;AAiBA,SAAgB,WACd,MACA,YACA,cACmB;CACnB,QAAQ,MAAM,YAAY,YAAY;EACpC,IAAI,CAAC,WAAW,IAAI,KAAK,CAAC,aAAa,SAAS,IAAI,GAAG;EACvD,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 /** 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,4 +1,4 @@
1
- import { EventName, ThirdPartyTracker } from "../track/types.cjs";
1
+ import { ThirdPartyTracker, TrackName } from "../track/types.cjs";
2
2
  import { ThirdPartyUserSetter } from "../visitor/types.cjs";
3
3
  /**
4
4
  * The one script an integration puts on the page, rendered by `<Analytics integrations>`
@@ -43,15 +43,19 @@ export interface AdsOptions {
43
43
  /**
44
44
  * Custom events this platform receives besides the conversions it maps to its standard
45
45
  * events, e.g. one used as an optimization goal or for an audience. Everything else is not
46
- * sent to it.
46
+ * sent to it. The names `track` accepts, so with strict event names a typo is a compile error.
47
47
  */
48
- customEvents?: readonly EventName[];
48
+ customEvents?: readonly TrackName[];
49
49
  }
50
50
  /**
51
- * An ad tracker that sends only what `isStandard` accepts — the events the platform's mapper
52
- * turns into one of its standard events — and the custom events the host listed. Everything
53
- * else in the product (feature use, clicks, onboarding steps) is behavior analysis, which is
54
- * GA4's and PostHog's job, and only noise to an ad platform's optimization.
51
+ * Which events an ad platform receives: what `isStandard` accepts — the events its mapper turns
52
+ * into one of its standard events — and the custom events the host listed. Everything else in the
53
+ * product (feature use, clicks, onboarding steps) is behavior analysis, which is GA4's and
54
+ * PostHog's job, and only noise to an ad platform's optimization. The same rule picks what the
55
+ * browser tag and the platform's conversions API send (`@shware/analytics/server`), so the two
56
+ * report the same events.
55
57
  */
56
- export declare function adsTracker(send: ThirdPartyTracker, isStandard: (name: string) => boolean, customEvents: readonly string[]): ThirdPartyTracker;
58
+ export declare function adEvents(isStandard: (name: string) => boolean, customEvents?: readonly string[]): (name: string) => boolean;
59
+ /** An ad tracker that sends only the events `accepts` lets through (`adEvents`). */
60
+ export declare function adsTracker(send: ThirdPartyTracker, accepts: (name: string) => boolean): ThirdPartyTracker;
57
61
  //# sourceMappingURL=integration.d.cts.map
@@ -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;;;;;;;;wBASV,WACd,MAAM,mBACN,aAAa,0BACb,kCACC"}
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,4 +1,4 @@
1
- import { EventName, ThirdPartyTracker } from "../track/types.mjs";
1
+ import { ThirdPartyTracker, TrackName } from "../track/types.mjs";
2
2
  import { ThirdPartyUserSetter } from "../visitor/types.mjs";
3
3
  /**
4
4
  * The one script an integration puts on the page, rendered by `<Analytics integrations>`
@@ -43,15 +43,19 @@ export interface AdsOptions {
43
43
  /**
44
44
  * Custom events this platform receives besides the conversions it maps to its standard
45
45
  * events, e.g. one used as an optimization goal or for an audience. Everything else is not
46
- * sent to it.
46
+ * sent to it. The names `track` accepts, so with strict event names a typo is a compile error.
47
47
  */
48
- customEvents?: readonly EventName[];
48
+ customEvents?: readonly TrackName[];
49
49
  }
50
50
  /**
51
- * An ad tracker that sends only what `isStandard` accepts — the events the platform's mapper
52
- * turns into one of its standard events — and the custom events the host listed. Everything
53
- * else in the product (feature use, clicks, onboarding steps) is behavior analysis, which is
54
- * GA4's and PostHog's job, and only noise to an ad platform's optimization.
51
+ * Which events an ad platform receives: what `isStandard` accepts — the events its mapper turns
52
+ * into one of its standard events — and the custom events the host listed. Everything else in the
53
+ * product (feature use, clicks, onboarding steps) is behavior analysis, which is GA4's and
54
+ * PostHog's job, and only noise to an ad platform's optimization. The same rule picks what the
55
+ * browser tag and the platform's conversions API send (`@shware/analytics/server`), so the two
56
+ * report the same events.
55
57
  */
56
- export declare function adsTracker(send: ThirdPartyTracker, isStandard: (name: string) => boolean, customEvents: readonly string[]): ThirdPartyTracker;
58
+ export declare function adEvents(isStandard: (name: string) => boolean, customEvents?: readonly string[]): (name: string) => boolean;
59
+ /** An ad tracker that sends only the events `accepts` lets through (`adEvents`). */
60
+ export declare function adsTracker(send: ThirdPartyTracker, accepts: (name: string) => boolean): ThirdPartyTracker;
57
61
  //# sourceMappingURL=integration.d.mts.map
@@ -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;;;;;;;;wBASV,WACd,MAAM,mBACN,aAAa,0BACb,kCACC"}
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"}
@@ -21,17 +21,23 @@ const CONVERSION_EVENTS = [
21
21
  "contact"
22
22
  ];
23
23
  /**
24
- * An ad tracker that sends only what `isStandard` accepts — the events the platform's mapper
25
- * turns into one of its standard events — and the custom events the host listed. Everything
26
- * else in the product (feature use, clicks, onboarding steps) is behavior analysis, which is
27
- * GA4's and PostHog's job, and only noise to an ad platform's optimization.
24
+ * Which events an ad platform receives: what `isStandard` accepts — the events its mapper turns
25
+ * into one of its standard events — and the custom events the host listed. Everything else in the
26
+ * product (feature use, clicks, onboarding steps) is behavior analysis, which is GA4's and
27
+ * PostHog's job, and only noise to an ad platform's optimization. The same rule picks what the
28
+ * browser tag and the platform's conversions API send (`@shware/analytics/server`), so the two
29
+ * report the same events.
28
30
  */
29
- function adsTracker(send, isStandard, customEvents) {
31
+ function adEvents(isStandard, customEvents = []) {
32
+ return (name) => isStandard(name) || customEvents.includes(name);
33
+ }
34
+ /** An ad tracker that sends only the events `accepts` lets through (`adEvents`). */
35
+ function adsTracker(send, accepts) {
30
36
  return (name, properties, eventId) => {
31
- if (!isStandard(name) && !customEvents.includes(name)) return;
37
+ if (!accepts(name)) return;
32
38
  return send(name, properties, eventId);
33
39
  };
34
40
  }
35
- export { CONVERSION_EVENTS, adsTracker };
41
+ export { CONVERSION_EVENTS, adEvents, adsTracker };
36
42
 
37
43
  //# sourceMappingURL=integration.mjs.map