@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.
Files changed (260) hide show
  1. package/README.md +164 -36
  2. package/dist/native/fbsdk.cjs +44 -1
  3. package/dist/native/fbsdk.cjs.map +1 -1
  4. package/dist/native/fbsdk.d.cts +23 -1
  5. package/dist/native/fbsdk.d.cts.map +1 -1
  6. package/dist/native/fbsdk.d.mts +23 -1
  7. package/dist/native/fbsdk.d.mts.map +1 -1
  8. package/dist/native/fbsdk.mjs +44 -3
  9. package/dist/native/fbsdk.mjs.map +1 -1
  10. package/dist/native/firebase.cjs +27 -0
  11. package/dist/native/firebase.cjs.map +1 -1
  12. package/dist/native/firebase.d.cts +11 -0
  13. package/dist/native/firebase.d.cts.map +1 -1
  14. package/dist/native/firebase.d.mts +11 -0
  15. package/dist/native/firebase.d.mts.map +1 -1
  16. package/dist/native/firebase.mjs +27 -2
  17. package/dist/native/firebase.mjs.map +1 -1
  18. package/dist/next/index.cjs +10 -123
  19. package/dist/next/index.cjs.map +1 -1
  20. package/dist/next/index.d.cts +2 -31
  21. package/dist/next/index.d.cts.map +1 -1
  22. package/dist/next/index.d.mts +2 -31
  23. package/dist/next/index.d.mts.map +1 -1
  24. package/dist/next/index.mjs +10 -123
  25. package/dist/next/index.mjs.map +1 -1
  26. package/dist/react/index.cjs +45 -0
  27. package/dist/react/index.cjs.map +1 -0
  28. package/dist/react/index.d.cts +15 -0
  29. package/dist/react/index.d.cts.map +1 -0
  30. package/dist/react/index.d.mts +15 -0
  31. package/dist/react/index.d.mts.map +1 -0
  32. package/dist/react/index.mjs +43 -0
  33. package/dist/react/index.mjs.map +1 -0
  34. package/dist/react/use-feature-flag.cjs +23 -0
  35. package/dist/react/use-feature-flag.cjs.map +1 -0
  36. package/dist/react/use-feature-flag.d.cts +10 -0
  37. package/dist/react/use-feature-flag.d.cts.map +1 -0
  38. package/dist/react/use-feature-flag.d.mts +10 -0
  39. package/dist/react/use-feature-flag.d.mts.map +1 -0
  40. package/dist/react/use-feature-flag.mjs +22 -0
  41. package/dist/react/use-feature-flag.mjs.map +1 -0
  42. package/dist/server/conversions-api-error.cjs +20 -0
  43. package/dist/server/conversions-api-error.cjs.map +1 -0
  44. package/dist/server/conversions-api-error.d.cts +17 -0
  45. package/dist/server/conversions-api-error.d.cts.map +1 -0
  46. package/dist/server/conversions-api-error.d.mts +17 -0
  47. package/dist/server/conversions-api-error.d.mts.map +1 -0
  48. package/dist/server/conversions-api-error.mjs +19 -0
  49. package/dist/server/conversions-api-error.mjs.map +1 -0
  50. package/dist/server/google-data-manager.cjs +24 -26
  51. package/dist/server/google-data-manager.cjs.map +1 -1
  52. package/dist/server/google-data-manager.d.cts +13 -5
  53. package/dist/server/google-data-manager.d.cts.map +1 -1
  54. package/dist/server/google-data-manager.d.mts +13 -5
  55. package/dist/server/google-data-manager.d.mts.map +1 -1
  56. package/dist/server/google-data-manager.mjs +24 -27
  57. package/dist/server/google-data-manager.mjs.map +1 -1
  58. package/dist/server/index.cjs +11 -0
  59. package/dist/server/index.d.cts +10 -7
  60. package/dist/server/index.d.mts +10 -7
  61. package/dist/server/index.mjs +9 -7
  62. package/dist/server/linkedin-conversions-api.cjs +29 -23
  63. package/dist/server/linkedin-conversions-api.cjs.map +1 -1
  64. package/dist/server/linkedin-conversions-api.d.cts +7 -2
  65. package/dist/server/linkedin-conversions-api.d.cts.map +1 -1
  66. package/dist/server/linkedin-conversions-api.d.mts +7 -2
  67. package/dist/server/linkedin-conversions-api.d.mts.map +1 -1
  68. package/dist/server/linkedin-conversions-api.mjs +29 -24
  69. package/dist/server/linkedin-conversions-api.mjs.map +1 -1
  70. package/dist/server/meta-capi.cjs +32 -31
  71. package/dist/server/meta-capi.cjs.map +1 -1
  72. package/dist/server/meta-capi.d.cts +12 -3
  73. package/dist/server/meta-capi.d.cts.map +1 -1
  74. package/dist/server/meta-capi.d.mts +12 -3
  75. package/dist/server/meta-capi.d.mts.map +1 -1
  76. package/dist/server/meta-capi.mjs +33 -33
  77. package/dist/server/meta-capi.mjs.map +1 -1
  78. package/dist/server/microsoft-conversions-api.cjs +33 -28
  79. package/dist/server/microsoft-conversions-api.cjs.map +1 -1
  80. package/dist/server/microsoft-conversions-api.d.cts +14 -2
  81. package/dist/server/microsoft-conversions-api.d.cts.map +1 -1
  82. package/dist/server/microsoft-conversions-api.d.mts +14 -2
  83. package/dist/server/microsoft-conversions-api.d.mts.map +1 -1
  84. package/dist/server/microsoft-conversions-api.mjs +33 -29
  85. package/dist/server/microsoft-conversions-api.mjs.map +1 -1
  86. package/dist/server/openai-conversions-api.cjs +20 -18
  87. package/dist/server/openai-conversions-api.cjs.map +1 -1
  88. package/dist/server/openai-conversions-api.d.cts +7 -0
  89. package/dist/server/openai-conversions-api.d.cts.map +1 -1
  90. package/dist/server/openai-conversions-api.d.mts +7 -0
  91. package/dist/server/openai-conversions-api.d.mts.map +1 -1
  92. package/dist/server/openai-conversions-api.mjs +21 -20
  93. package/dist/server/openai-conversions-api.mjs.map +1 -1
  94. package/dist/server/reddit-conversions-api.cjs +20 -18
  95. package/dist/server/reddit-conversions-api.cjs.map +1 -1
  96. package/dist/server/reddit-conversions-api.d.cts +8 -1
  97. package/dist/server/reddit-conversions-api.d.cts.map +1 -1
  98. package/dist/server/reddit-conversions-api.d.mts +8 -1
  99. package/dist/server/reddit-conversions-api.d.mts.map +1 -1
  100. package/dist/server/reddit-conversions-api.mjs +21 -20
  101. package/dist/server/reddit-conversions-api.mjs.map +1 -1
  102. package/dist/server/setup-conversions.cjs +62 -0
  103. package/dist/server/setup-conversions.cjs.map +1 -0
  104. package/dist/server/setup-conversions.d.cts +97 -0
  105. package/dist/server/setup-conversions.d.cts.map +1 -0
  106. package/dist/server/setup-conversions.d.mts +97 -0
  107. package/dist/server/setup-conversions.d.mts.map +1 -0
  108. package/dist/server/setup-conversions.mjs +60 -0
  109. package/dist/server/setup-conversions.mjs.map +1 -0
  110. package/dist/setup/index.cjs +4 -4
  111. package/dist/setup/index.cjs.map +1 -1
  112. package/dist/setup/index.d.cts +16 -6
  113. package/dist/setup/index.d.cts.map +1 -1
  114. package/dist/setup/index.d.mts +16 -6
  115. package/dist/setup/index.d.mts.map +1 -1
  116. package/dist/setup/index.mjs +4 -4
  117. package/dist/setup/index.mjs.map +1 -1
  118. package/dist/tanstack/index.cjs +0 -2
  119. package/dist/tanstack/index.d.cts +1 -2
  120. package/dist/tanstack/index.d.mts +1 -2
  121. package/dist/tanstack/index.mjs +1 -3
  122. package/dist/third-parties/analytics-props.cjs +28 -0
  123. package/dist/third-parties/analytics-props.cjs.map +1 -0
  124. package/dist/third-parties/analytics-props.d.cts +23 -0
  125. package/dist/third-parties/analytics-props.d.cts.map +1 -0
  126. package/dist/third-parties/analytics-props.d.mts +23 -0
  127. package/dist/third-parties/analytics-props.d.mts.map +1 -0
  128. package/dist/third-parties/analytics-props.mjs +26 -0
  129. package/dist/third-parties/analytics-props.mjs.map +1 -0
  130. package/dist/third-parties/google-analytics.cjs +32 -0
  131. package/dist/third-parties/google-analytics.cjs.map +1 -1
  132. package/dist/third-parties/google-analytics.d.cts +11 -1
  133. package/dist/third-parties/google-analytics.d.cts.map +1 -1
  134. package/dist/third-parties/google-analytics.d.mts +11 -1
  135. package/dist/third-parties/google-analytics.d.mts.map +1 -1
  136. package/dist/third-parties/google-analytics.mjs +32 -1
  137. package/dist/third-parties/google-analytics.mjs.map +1 -1
  138. package/dist/third-parties/index.cjs +16 -0
  139. package/dist/third-parties/index.d.cts +9 -7
  140. package/dist/third-parties/index.d.mts +9 -7
  141. package/dist/third-parties/index.mjs +9 -7
  142. package/dist/third-parties/integration.cjs +46 -0
  143. package/dist/third-parties/integration.cjs.map +1 -0
  144. package/dist/third-parties/integration.d.cts +61 -0
  145. package/dist/third-parties/integration.d.cts.map +1 -0
  146. package/dist/third-parties/integration.d.mts +61 -0
  147. package/dist/third-parties/integration.d.mts.map +1 -0
  148. package/dist/third-parties/integration.mjs +43 -0
  149. package/dist/third-parties/integration.mjs.map +1 -0
  150. package/dist/third-parties/linkedin-insight-tag.cjs +29 -0
  151. package/dist/third-parties/linkedin-insight-tag.cjs.map +1 -1
  152. package/dist/third-parties/linkedin-insight-tag.d.cts +14 -8
  153. package/dist/third-parties/linkedin-insight-tag.d.cts.map +1 -1
  154. package/dist/third-parties/linkedin-insight-tag.d.mts +14 -8
  155. package/dist/third-parties/linkedin-insight-tag.d.mts.map +1 -1
  156. package/dist/third-parties/linkedin-insight-tag.mjs +29 -1
  157. package/dist/third-parties/linkedin-insight-tag.mjs.map +1 -1
  158. package/dist/third-parties/meta-pixel.cjs +32 -0
  159. package/dist/third-parties/meta-pixel.cjs.map +1 -1
  160. package/dist/third-parties/meta-pixel.d.cts +7 -0
  161. package/dist/third-parties/meta-pixel.d.cts.map +1 -1
  162. package/dist/third-parties/meta-pixel.d.mts +7 -0
  163. package/dist/third-parties/meta-pixel.d.mts.map +1 -1
  164. package/dist/third-parties/meta-pixel.mjs +33 -2
  165. package/dist/third-parties/meta-pixel.mjs.map +1 -1
  166. package/dist/third-parties/microsoft-uet.cjs +54 -0
  167. package/dist/third-parties/microsoft-uet.cjs.map +1 -1
  168. package/dist/third-parties/microsoft-uet.d.cts +36 -0
  169. package/dist/third-parties/microsoft-uet.d.cts.map +1 -1
  170. package/dist/third-parties/microsoft-uet.d.mts +36 -0
  171. package/dist/third-parties/microsoft-uet.d.mts.map +1 -1
  172. package/dist/third-parties/microsoft-uet.mjs +52 -1
  173. package/dist/third-parties/microsoft-uet.mjs.map +1 -1
  174. package/dist/third-parties/openai-pixel.cjs +29 -0
  175. package/dist/third-parties/openai-pixel.cjs.map +1 -1
  176. package/dist/third-parties/openai-pixel.d.cts +7 -0
  177. package/dist/third-parties/openai-pixel.d.cts.map +1 -1
  178. package/dist/third-parties/openai-pixel.d.mts +7 -0
  179. package/dist/third-parties/openai-pixel.d.mts.map +1 -1
  180. package/dist/third-parties/openai-pixel.mjs +30 -2
  181. package/dist/third-parties/openai-pixel.mjs.map +1 -1
  182. package/dist/third-parties/posthog.cjs +97 -4
  183. package/dist/third-parties/posthog.cjs.map +1 -1
  184. package/dist/third-parties/posthog.d.cts +56 -1
  185. package/dist/third-parties/posthog.d.cts.map +1 -1
  186. package/dist/third-parties/posthog.d.mts +56 -1
  187. package/dist/third-parties/posthog.d.mts.map +1 -1
  188. package/dist/third-parties/posthog.mjs +91 -2
  189. package/dist/third-parties/posthog.mjs.map +1 -1
  190. package/dist/third-parties/reddit-pixel.cjs +30 -0
  191. package/dist/third-parties/reddit-pixel.cjs.map +1 -1
  192. package/dist/third-parties/reddit-pixel.d.cts +7 -0
  193. package/dist/third-parties/reddit-pixel.d.cts.map +1 -1
  194. package/dist/third-parties/reddit-pixel.d.mts +7 -0
  195. package/dist/third-parties/reddit-pixel.d.mts.map +1 -1
  196. package/dist/third-parties/reddit-pixel.mjs +31 -2
  197. package/dist/third-parties/reddit-pixel.mjs.map +1 -1
  198. package/dist/track/fbq.cjs +6 -1
  199. package/dist/track/fbq.cjs.map +1 -1
  200. package/dist/track/fbq.d.cts +2 -0
  201. package/dist/track/fbq.d.cts.map +1 -1
  202. package/dist/track/fbq.d.mts +2 -0
  203. package/dist/track/fbq.d.mts.map +1 -1
  204. package/dist/track/fbq.mjs +6 -2
  205. package/dist/track/fbq.mjs.map +1 -1
  206. package/dist/track/index.cjs +7 -7
  207. package/dist/track/index.cjs.map +1 -1
  208. package/dist/track/index.d.cts.map +1 -1
  209. package/dist/track/index.d.mts.map +1 -1
  210. package/dist/track/index.mjs +7 -7
  211. package/dist/track/index.mjs.map +1 -1
  212. package/dist/track/oaiq.cjs +5 -0
  213. package/dist/track/oaiq.cjs.map +1 -1
  214. package/dist/track/oaiq.d.cts +2 -0
  215. package/dist/track/oaiq.d.cts.map +1 -1
  216. package/dist/track/oaiq.d.mts +2 -0
  217. package/dist/track/oaiq.d.mts.map +1 -1
  218. package/dist/track/oaiq.mjs +5 -1
  219. package/dist/track/oaiq.mjs.map +1 -1
  220. package/dist/track/rdt.cjs +5 -0
  221. package/dist/track/rdt.cjs.map +1 -1
  222. package/dist/track/rdt.d.cts +2 -0
  223. package/dist/track/rdt.d.cts.map +1 -1
  224. package/dist/track/rdt.d.mts +2 -0
  225. package/dist/track/rdt.d.mts.map +1 -1
  226. package/dist/track/rdt.mjs +5 -1
  227. package/dist/track/rdt.mjs.map +1 -1
  228. package/dist/visitor/index.cjs +3 -3
  229. package/dist/visitor/index.cjs.map +1 -1
  230. package/dist/visitor/index.mjs +3 -3
  231. package/dist/visitor/index.mjs.map +1 -1
  232. package/package.json +11 -39
  233. package/dist/react-router/index.cjs +0 -160
  234. package/dist/react-router/index.cjs.map +0 -1
  235. package/dist/react-router/index.d.cts +0 -22
  236. package/dist/react-router/index.d.cts.map +0 -1
  237. package/dist/react-router/index.d.mts +0 -22
  238. package/dist/react-router/index.d.mts.map +0 -1
  239. package/dist/react-router/index.mjs +0 -159
  240. package/dist/react-router/index.mjs.map +0 -1
  241. package/dist/server/legacy.cjs +0 -3
  242. package/dist/server/legacy.d.cts +0 -2
  243. package/dist/server/legacy.d.mts +0 -2
  244. package/dist/server/legacy.mjs +0 -1
  245. package/dist/server/meta-conversions-api.cjs +0 -205
  246. package/dist/server/meta-conversions-api.cjs.map +0 -1
  247. package/dist/server/meta-conversions-api.d.cts +0 -8
  248. package/dist/server/meta-conversions-api.d.cts.map +0 -1
  249. package/dist/server/meta-conversions-api.d.mts +0 -8
  250. package/dist/server/meta-conversions-api.d.mts.map +0 -1
  251. package/dist/server/meta-conversions-api.mjs +0 -201
  252. package/dist/server/meta-conversions-api.mjs.map +0 -1
  253. package/dist/tanstack/analytics.cjs +0 -184
  254. package/dist/tanstack/analytics.cjs.map +0 -1
  255. package/dist/tanstack/analytics.d.cts +0 -33
  256. package/dist/tanstack/analytics.d.cts.map +0 -1
  257. package/dist/tanstack/analytics.d.mts +0 -33
  258. package/dist/tanstack/analytics.d.mts.map +0 -1
  259. package/dist/tanstack/analytics.mjs +0 -183
  260. package/dist/tanstack/analytics.mjs.map +0 -1
@@ -2,15 +2,18 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
2
  const require_third_parties_ignored_events = require("../third-parties/ignored-events.cjs");
3
3
  const require_click_id_index = require("../click-id/index.cjs");
4
4
  const require_track_uetq = require("../track/uetq.cjs");
5
+ const require_third_parties_microsoft_uet = require("../third-parties/microsoft-uet.cjs");
5
6
  const require_server_click_ids = require("./click-ids.cjs");
7
+ const require_server_conversions_api_error = require("./conversions-api-error.cjs");
8
+ const require_server_setup_conversions = require("./setup-conversions.cjs");
6
9
  const require_server_page_location = require("./page-location.cjs");
7
10
  let _shware_utils = require("@shware/utils");
8
11
  let node_crypto = require("node:crypto");
9
12
  // src/server/microsoft-conversions-api.ts
10
13
  /**
11
14
  * Microsoft Advertising Conversions API (CAPI) sender — the server-side counterpart of the UET
12
- * tag, in the same shape as the other senders here: a pure per-event builder, a never-throws
13
- * `sendEvents`, the token in a header and never in a URL or a log line.
15
+ * tag, in the same shape as the other senders here: a pure per-event builder, a `sendEvents`
16
+ * that rejects on failure, the token in a header and never in a URL or an error.
14
17
  *
15
18
  * Microsoft's recommended deployment is hybrid: keep the UET JavaScript on the page and send the
16
19
  * same conversions here too, deduplicated by (`tagId`, `eventName`, `eventId`). Both channels in
@@ -124,8 +127,9 @@ function compact(value) {
124
127
  const MAX_EVENT_AGE_MS = 60474e4;
125
128
  /**
126
129
  * Send events to `POST /v1/{tagId}/events`. Batches above the API's 1,000-event limit are split
127
- * into consecutive requests; one response is returned per request made. Never throws: an HTTP
128
- * or network failure is logged (without the token) and yields no response for that request.
130
+ * into consecutive requests; one response is returned per request made. The first failed request
131
+ * rejects — a `ConversionsApiError`, or the fetch error, neither carrying the token — and sends
132
+ * no further ones.
129
133
  */
130
134
  async function sendEvents(token, tagId, events, data = {}, options = {}) {
131
135
  const { consent, pageLoads = false, dataProvider, continueOnValidationError = true } = options;
@@ -141,34 +145,35 @@ async function sendEvents(token, tagId, events, data = {}, options = {}) {
141
145
  continueOnValidationError,
142
146
  dataProvider
143
147
  });
144
- try {
145
- const response = await (0, _shware_utils.fetch)(`${ENDPOINT}/${tagId}/events`, {
146
- method: "POST",
147
- retries: 3,
148
- headers: {
149
- "Content-Type": "application/json",
150
- Accept: "application/json",
151
- Authorization: `Bearer ${token}`
152
- },
153
- body: JSON.stringify(body)
154
- });
155
- if (response.ok) {
156
- const result = await response.json();
157
- if (result.error?.details?.length) console.warn(`Microsoft conversion accepted with validation issues: ${JSON.stringify(result.error.details)}`);
158
- responses.push(result);
159
- continue;
160
- }
161
- const { status } = response;
162
- const message = await response.text();
163
- console.error(`Failed to send Microsoft conversion, status: ${status}, body: ${message}`);
164
- } catch (error) {
165
- const message = error instanceof Error ? error.message : String(error);
166
- console.error(`Failed to send Microsoft conversion, network error: ${message}`);
167
- }
148
+ const response = await (0, _shware_utils.fetch)(`${ENDPOINT}/${tagId}/events`, {
149
+ method: "POST",
150
+ retries: 3,
151
+ headers: {
152
+ "Content-Type": "application/json",
153
+ Accept: "application/json",
154
+ Authorization: `Bearer ${token}`
155
+ },
156
+ body: JSON.stringify(body)
157
+ });
158
+ if (!response.ok) throw new require_server_conversions_api_error.ConversionsApiError("microsoft", response.status, await response.text());
159
+ const result = await response.json();
160
+ if (result.error?.details?.length) console.warn(`Microsoft conversion accepted with validation issues: ${JSON.stringify(result.error.details)}`);
161
+ responses.push(result);
168
162
  }
169
163
  return responses;
170
164
  }
165
+ /**
166
+ * Microsoft's Conversions API, sent the same events as `microsoftAds` (`events`, the GA4
167
+ * conversion events by default, and `customEvents`) — and `page_view` too with `pageLoads`, for
168
+ * a site with no UET tag on the page. `consent` is the API's batch-level consent here, not the
169
+ * tag's consent mode default.
170
+ */
171
+ function microsoftConversions(options) {
172
+ const accepts = require_third_parties_microsoft_uet.uetEvents(options);
173
+ return require_server_setup_conversions.conversionDestination((name) => accepts(name) || options.pageLoads === true && name === "page_view", (events, data) => sendEvents(options.accessToken, options.tagId, events, data, options));
174
+ }
171
175
  exports.getServerEvent = getServerEvent;
176
+ exports.microsoftConversions = microsoftConversions;
172
177
  exports.normalizeEmail = normalizeEmail;
173
178
  exports.sendEvents = sendEvents;
174
179
 
@@ -1 +1 @@
1
- {"version":3,"file":"microsoft-conversions-api.cjs","names":["createHash","microsoftMsclkid","formatMsclkid","mapUETEvent","pageLocation","IGNORED_EVENTS","chunk","fetch"],"sources":["../../src/server/microsoft-conversions-api.ts"],"sourcesContent":["/**\n * Microsoft Advertising Conversions API (CAPI) sender — the server-side counterpart of the UET\n * tag, in the same shape as the other senders here: a pure per-event builder, a never-throws\n * `sendEvents`, the token in a header and never in a URL or a log line.\n *\n * Microsoft's recommended deployment is hybrid: keep the UET JavaScript on the page and send the\n * same conversions here too, deduplicated by (`tagId`, `eventName`, `eventId`). Both channels in\n * this SDK are fed from the same `track()` call — the browser sends the internal name as the UET\n * action with the event id as `event_id`, and this builder sends the same name as `eventName`\n * with the same id — so the pair agrees by construction.\n *\n * The token comes from the UET tag's \"Use Conversions API\" setup step, or from the Campaign\n * Management API's `UetTagAuthKey/Query`. Access is provisioned per customer account: an account\n * whose tag setup has no \"Use Conversions API\" option has to ask Microsoft Advertising support.\n *\n * https://learn.microsoft.com/en-us/advertising/guides/uet-conversion-api-integration\n */\nimport { createHash } from 'node:crypto';\nimport { chunk, fetch } from '@shware/utils';\nimport { formatMsclkid } from '../click-id/index';\nimport { IGNORED_EVENTS } from '../third-parties/ignored-events';\nimport type { TrackEvent, UserProvidedData } from '../track/types';\nimport { mapUETEvent } from '../track/uetq';\nimport { microsoftMsclkid } from './click-ids';\nimport { pageLocation } from './page-location';\n\nconst ENDPOINT = 'https://capi.uet.microsoft.com/v1';\n\n/** The API's hard limit per request. */\nconst MAX_EVENTS_PER_REQUEST = 1000;\n\nconst SHA256 = /^[a-f0-9]{64}$/;\n\nconst sha256 = (value: string) => createHash('sha256').update(value).digest('hex');\n\n/**\n * Microsoft's email normalization: trim, drop the dots and any `+alias` from the user part —\n * for EVERY domain, unlike Google's gmail-only rule — lowercase, SHA-256. A value that is\n * already a SHA-256 hex digest passes through.\n * https://learn.microsoft.com/en-us/advertising/guides/uet-conversion-api-integration#hashed-identifiers\n */\nexport function normalizeEmail(input: string): string {\n const email = input.trim().toLowerCase();\n const at = email.lastIndexOf('@');\n if (at === -1) return email;\n const user = email.slice(0, at).replace(/\\./g, '').split('+', 1)[0] ?? '';\n return `${user}@${email.slice(at + 1)}`;\n}\n\nfunction hashEmail(input: string | undefined): string | undefined {\n const value = input?.trim().toLowerCase();\n if (!value) return undefined;\n return SHA256.test(value) ? value : sha256(normalizeEmail(value));\n}\n\n/**\n * Phones are E.164 by the schema (`+` then 11–15 digits, the range bat.js validates too); the\n * separators bat.js tolerates are stripped, and anything else is dropped rather than guessed —\n * a number with no country code hashed under an assumed one can never match.\n */\nfunction hashPhone(input: string | undefined): string | undefined {\n const value = input?.trim().toLowerCase();\n if (!value) return undefined;\n if (SHA256.test(value)) return value;\n const phone = value.replace(/[-() \\t]/g, '');\n return /^\\+\\d{11,15}$/.test(phone) ? sha256(phone) : undefined;\n}\n\nexport interface MicrosoftUserData {\n /** Microsoft click id, as a dashed UUID. */\n msclkid?: string;\n /** SHA-256 of the normalized email. */\n em?: string;\n /** SHA-256 of the E.164 phone number. */\n ph?: string;\n /** The SDK visitor id — what the client-side ID Sync pixel (`sendUETIdSync`) sends as `VID`. */\n anonymousId?: string;\n /** SHA-256 of the signed-in user id — what `sendUETIdSync` sends as `UID`. */\n externalId?: string;\n clientUserAgent?: string;\n clientIpAddress?: string;\n idfa?: string;\n gaid?: string;\n}\n\nexport interface MicrosoftItem {\n id?: string;\n name?: string;\n price?: number;\n quantity?: number;\n}\n\nexport interface MicrosoftCustomData {\n eventCategory?: string;\n eventLabel?: string;\n eventValue?: number;\n searchTerm?: string;\n transactionId?: string;\n value?: number;\n currency?: string;\n items?: MicrosoftItem[];\n itemIds?: string[];\n pageType?: string;\n ecommTotalValue?: number;\n ecommCategory?: string;\n}\n\n/** One entry of the `data` array POSTed to `/v1/{tagId}/events`. */\nexport interface MicrosoftEvent {\n eventType: 'custom' | 'pageLoad';\n eventId: string;\n /** The UET action; absent on `pageLoad` events. */\n eventName?: string;\n /** UNIX seconds, UTC; the API rejects anything older than 7 days. */\n eventTime: number;\n eventSourceUrl?: string;\n /** Links a `custom` event to its `pageLoad` event; a v4 UUID (the SDK's `page_load_id` tag). */\n pageLoadId?: string;\n referrerUrl?: string;\n pageTitle?: string;\n /** `G` granted, `D` denied. Absent means granted. */\n adStorageConsent?: 'G' | 'D';\n userData: MicrosoftUserData;\n customData?: MicrosoftCustomData;\n}\n\nexport interface MicrosoftConversionsOptions {\n /**\n * EEA/UK/CH consent for the whole batch. `denied` events are accepted but used for nothing —\n * no attribution, no audiences. Absent means granted, which is also the API's default.\n */\n consent?: 'granted' | 'denied';\n /**\n * Also send `page_view` events, as CAPI `pageLoad` events, and link every custom event to the\n * page load it happened on (`pageLoadId`, from the `page_load_id` tag). Off by default because\n * the UET JavaScript already reports every page load and the two would double-count\n * destination-URL goals; turn it on for a CAPI-only site with no tag on the page. Off, no\n * `pageLoadId` is sent either: it would point at a page load Microsoft only saw from the tag,\n * under the tag's own id.\n *\n * Not yet modelled: the revenue-only custom event a `pageLoad` needs for a destination goal\n * with variable revenue.\n */\n pageLoads?: boolean;\n /** Identifies a third-party sender in Microsoft's monitoring; leave unset for a first-party build. */\n dataProvider?: string;\n /**\n * Process the valid events of a batch and report the invalid ones, instead of the API's default\n * all-or-nothing rejection. On by default — one malformed event should cost itself, not the\n * batch it travelled with.\n */\n continueOnValidationError?: boolean;\n}\n\nexport interface MicrosoftValidationDetail {\n index?: number;\n propertyName?: string;\n attemptedValue?: unknown;\n errorMessage?: string;\n errorCode?: string;\n isWarning?: boolean;\n}\n\nexport interface MicrosoftConversionsResponse {\n eventsReceived?: number;\n error?: { code?: string; message?: string; details?: MicrosoftValidationDetail[] };\n}\n\nfunction getUserData(\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n event: TrackEvent<any>,\n data: UserProvidedData\n): MicrosoftUserData {\n const { tags, platform, visitor_id } = event;\n const email = Array.isArray(data.email) ? data.email[0] : data.email;\n const phone = Array.isArray(data.phone_number) ? data.phone_number[0] : data.phone_number;\n const msclkid = microsoftMsclkid(tags);\n\n return {\n msclkid: msclkid ? formatMsclkid(msclkid) : undefined,\n em: hashEmail(email),\n ph: hashPhone(phone),\n // Microsoft requires this to equal the `VID` of the client-side ID Sync pixel; both sides use\n // the SDK visitor id, which every event carries and the client can always read.\n anonymousId: visitor_id || undefined,\n // Microsoft asks for an anonymized id and never a real one. SHA-256, the same digest\n // `sendUETIdSync` applies client-side, so `externalId` and the pixel's `UID` agree too.\n externalId: data.user_id ? sha256(data.user_id) : undefined,\n clientUserAgent: data.user_agent,\n clientIpAddress:\n typeof tags.ip_address === 'string' && tags.ip_address ? tags.ip_address : data.ip_address,\n idfa: platform === 'ios' ? tags.advertising_id : undefined,\n gaid: platform === 'android' ? tags.advertising_id : undefined,\n };\n}\n\n// oxlint-disable-next-line @typescript-eslint/no-explicit-any\nfunction getCustomData(event: TrackEvent<any>): MicrosoftCustomData | undefined {\n const [, params] = mapUETEvent(event.name, event.properties);\n const customData: MicrosoftCustomData = {\n eventCategory: params.event_category,\n eventLabel: params.event_label,\n eventValue: params.event_value,\n searchTerm: params.search_term,\n transactionId: params.transaction_id,\n value: params.revenue_value,\n currency: params.currency,\n items: params.items?.map(({ id, name, price, quantity }) => ({ id, name, price, quantity })),\n itemIds: Array.isArray(params.ecomm_prodid)\n ? params.ecomm_prodid\n : params.ecomm_prodid\n ? [params.ecomm_prodid]\n : undefined,\n pageType: params.ecomm_pagetype,\n ecommTotalValue: params.ecomm_totalvalue,\n ecommCategory: params.ecomm_category,\n };\n return Object.values(customData).some((value) => value !== undefined) ? customData : undefined;\n}\n\n/**\n * Build one CAPI event. `page_view` becomes a `pageLoad` event (the caller decides whether to\n * send those, see `MicrosoftConversionsOptions.pageLoads`); everything else is a `custom` event\n * named after the track event, which is also the UET action the browser sent.\n */\nexport type MicrosoftEventOptions = Pick<MicrosoftConversionsOptions, 'consent' | 'pageLoads'>;\n\nexport function getServerEvent(\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n event: TrackEvent<any>,\n data: UserProvidedData = {},\n /** Options, or — the 8.3.0 signature, still accepted — the bare consent value. */\n options: MicrosoftEventOptions | MicrosoftEventOptions['consent'] = {}\n): MicrosoftEvent {\n const { consent, pageLoads = false } =\n typeof options === 'string' ? { consent: options } : options;\n const { id, name, tags, created_at } = event;\n const isPageLoad = name === 'page_view';\n\n return {\n eventType: isPageLoad ? 'pageLoad' : 'custom',\n eventId: tags.idempotency_key ?? id,\n eventName: isPageLoad ? undefined : name,\n eventTime: Math.round(new Date(created_at).getTime() / 1000),\n eventSourceUrl: pageLocation(tags),\n pageLoadId: pageLoads ? tags.page_load_id : undefined,\n referrerUrl: tags.page_referrer,\n pageTitle: tags.page_title,\n adStorageConsent: consent === 'granted' ? 'G' : consent === 'denied' ? 'D' : undefined,\n userData: getUserData(event, data),\n customData: isPageLoad ? undefined : getCustomData(event),\n };\n}\n\n/** Strip undefined fields so the wire payload carries only what was set. */\nfunction compact<T>(value: T): T {\n return JSON.parse(JSON.stringify(value)) as T;\n}\n\n/** `eventTime` must be \"within the last 7 days\"; a minute's margin for the trip. */\nconst MAX_EVENT_AGE_MS = 7 * 24 * 60 * 60 * 1000 - 60 * 1000;\n\n/**\n * Send events to `POST /v1/{tagId}/events`. Batches above the API's 1,000-event limit are split\n * into consecutive requests; one response is returned per request made. Never throws: an HTTP\n * or network failure is logged (without the token) and yields no response for that request.\n */\nexport async function sendEvents(\n token: string,\n tagId: string | number,\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n events: TrackEvent<any>[],\n data: UserProvidedData = {},\n options: MicrosoftConversionsOptions = {}\n): Promise<MicrosoftConversionsResponse[]> {\n const { consent, pageLoads = false, dataProvider, continueOnValidationError = true } = options;\n\n const capiEvents = events\n .filter(\n (event) => (pageLoads && event.name === 'page_view') || !IGNORED_EVENTS.includes(event.name)\n )\n .filter((event) => Date.now() - Date.parse(event.created_at) <= MAX_EVENT_AGE_MS)\n .map((event) => getServerEvent(event, data, { consent, pageLoads }))\n // A pageLoad without a URL is rejected by the API, and a page-less event has nothing to say.\n .filter((event) => event.eventType !== 'pageLoad' || event.eventSourceUrl);\n if (capiEvents.length === 0) return [];\n\n const responses: MicrosoftConversionsResponse[] = [];\n for (const batch of chunk(capiEvents, MAX_EVENTS_PER_REQUEST)) {\n const body = compact({ data: batch, continueOnValidationError, dataProvider });\n try {\n const response = await fetch(`${ENDPOINT}/${tagId}/events`, {\n method: 'POST',\n // Retried although a POST: the platform deduplicates on the `eventId` each event carries.\n retries: 3,\n headers: {\n 'Content-Type': 'application/json',\n Accept: 'application/json',\n Authorization: `Bearer ${token}`,\n },\n body: JSON.stringify(body),\n });\n if (response.ok) {\n const result = (await response.json()) as MicrosoftConversionsResponse;\n // A 200 can still carry field-level warnings (the field was removed) and, with\n // `continueOnValidationError`, skipped events. Surface them: silent partial data loss is\n // the one failure mode the caller cannot see from the status code.\n if (result.error?.details?.length) {\n console.warn(\n `Microsoft conversion accepted with validation issues: ${JSON.stringify(result.error.details)}`\n );\n }\n responses.push(result);\n continue;\n }\n const { status } = response;\n const message = await response.text();\n console.error(`Failed to send Microsoft conversion, status: ${status}, body: ${message}`);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n console.error(`Failed to send Microsoft conversion, network error: ${message}`);\n }\n }\n return responses;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AA0BA,MAAM,WAAW;;AAGjB,MAAM,yBAAyB;AAE/B,MAAM,SAAS;AAEf,MAAM,UAAU,WAAA,GAAkBA,YAAAA,WAAAA,CAAW,QAAQ,CAAC,CAAC,OAAO,KAAK,CAAC,CAAC,OAAO,KAAK;;;;;;;AAQjF,SAAgB,eAAe,OAAuB;CACpD,MAAM,QAAQ,MAAM,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AC9F;IAEF,UAAU,KAAK,MAAM;IACrB;GACF;GACA,MAAM,EAAE,WAAW;GACnB,MAAM,UAAU,MAAM,SAAS,KAAK;GACpC,QAAQ,MAAM,gDAAgD,OAAO,UAAU,SAAS;EAC1F,SAAS,OAAO;GACd,MAAM,UAAU,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;GACrE,QAAQ,MAAM,uDAAuD,SAAS;EAChF;CACF;CACA,OAAO;AACT"}
1
+ {"version":3,"file":"microsoft-conversions-api.cjs","names":["createHash","microsoftMsclkid","formatMsclkid","mapUETEvent","pageLocation","IGNORED_EVENTS","chunk","fetch","ConversionsApiError","uetEvents","conversionDestination"],"sources":["../../src/server/microsoft-conversions-api.ts"],"sourcesContent":["/**\n * Microsoft Advertising Conversions API (CAPI) sender — the server-side counterpart of the UET\n * tag, in the same shape as the other senders here: a pure per-event builder, a `sendEvents`\n * that rejects on failure, the token in a header and never in a URL or an error.\n *\n * Microsoft's recommended deployment is hybrid: keep the UET JavaScript on the page and send the\n * same conversions here too, deduplicated by (`tagId`, `eventName`, `eventId`). Both channels in\n * this SDK are fed from the same `track()` call — the browser sends the internal name as the UET\n * action with the event id as `event_id`, and this builder sends the same name as `eventName`\n * with the same id — so the pair agrees by construction.\n *\n * The token comes from the UET tag's \"Use Conversions API\" setup step, or from the Campaign\n * Management API's `UetTagAuthKey/Query`. Access is provisioned per customer account: an account\n * whose tag setup has no \"Use Conversions API\" option has to ask Microsoft Advertising support.\n *\n * https://learn.microsoft.com/en-us/advertising/guides/uet-conversion-api-integration\n */\nimport { createHash } from 'node:crypto';\nimport { chunk, fetch } from '@shware/utils';\nimport { formatMsclkid } from '../click-id/index';\nimport { IGNORED_EVENTS } from '../third-parties/ignored-events';\nimport { type MicrosoftAdsOptions, uetEvents } from '../third-parties/microsoft-uet';\nimport type { TrackEvent, UserProvidedData } from '../track/types';\nimport { mapUETEvent } from '../track/uetq';\nimport { microsoftMsclkid } from './click-ids';\nimport { ConversionsApiError } from './conversions-api-error';\nimport { pageLocation } from './page-location';\nimport { type ConversionDestination, conversionDestination } from './setup-conversions';\n\nconst ENDPOINT = 'https://capi.uet.microsoft.com/v1';\n\n/** The API's hard limit per request. */\nconst MAX_EVENTS_PER_REQUEST = 1000;\n\nconst SHA256 = /^[a-f0-9]{64}$/;\n\nconst sha256 = (value: string) => createHash('sha256').update(value).digest('hex');\n\n/**\n * Microsoft's email normalization: trim, drop the dots and any `+alias` from the user part —\n * for EVERY domain, unlike Google's gmail-only rule — lowercase, SHA-256. A value that is\n * already a SHA-256 hex digest passes through.\n * https://learn.microsoft.com/en-us/advertising/guides/uet-conversion-api-integration#hashed-identifiers\n */\nexport function normalizeEmail(input: string): string {\n const email = input.trim().toLowerCase();\n const at = email.lastIndexOf('@');\n if (at === -1) return email;\n const user = email.slice(0, at).replace(/\\./g, '').split('+', 1)[0] ?? '';\n return `${user}@${email.slice(at + 1)}`;\n}\n\nfunction hashEmail(input: string | undefined): string | undefined {\n const value = input?.trim().toLowerCase();\n if (!value) return undefined;\n return SHA256.test(value) ? value : sha256(normalizeEmail(value));\n}\n\n/**\n * Phones are E.164 by the schema (`+` then 11–15 digits, the range bat.js validates too); the\n * separators bat.js tolerates are stripped, and anything else is dropped rather than guessed —\n * a number with no country code hashed under an assumed one can never match.\n */\nfunction hashPhone(input: string | undefined): string | undefined {\n const value = input?.trim().toLowerCase();\n if (!value) return undefined;\n if (SHA256.test(value)) return value;\n const phone = value.replace(/[-() \\t]/g, '');\n return /^\\+\\d{11,15}$/.test(phone) ? sha256(phone) : undefined;\n}\n\nexport interface MicrosoftUserData {\n /** Microsoft click id, as a dashed UUID. */\n msclkid?: string;\n /** SHA-256 of the normalized email. */\n em?: string;\n /** SHA-256 of the E.164 phone number. */\n ph?: string;\n /** The SDK visitor id — what the client-side ID Sync pixel (`sendUETIdSync`) sends as `VID`. */\n anonymousId?: string;\n /** SHA-256 of the signed-in user id — what `sendUETIdSync` sends as `UID`. */\n externalId?: string;\n clientUserAgent?: string;\n clientIpAddress?: string;\n idfa?: string;\n gaid?: string;\n}\n\nexport interface MicrosoftItem {\n id?: string;\n name?: string;\n price?: number;\n quantity?: number;\n}\n\nexport interface MicrosoftCustomData {\n eventCategory?: string;\n eventLabel?: string;\n eventValue?: number;\n searchTerm?: string;\n transactionId?: string;\n value?: number;\n currency?: string;\n items?: MicrosoftItem[];\n itemIds?: string[];\n pageType?: string;\n ecommTotalValue?: number;\n ecommCategory?: string;\n}\n\n/** One entry of the `data` array POSTed to `/v1/{tagId}/events`. */\nexport interface MicrosoftEvent {\n eventType: 'custom' | 'pageLoad';\n eventId: string;\n /** The UET action; absent on `pageLoad` events. */\n eventName?: string;\n /** UNIX seconds, UTC; the API rejects anything older than 7 days. */\n eventTime: number;\n eventSourceUrl?: string;\n /** Links a `custom` event to its `pageLoad` event; a v4 UUID (the SDK's `page_load_id` tag). */\n pageLoadId?: string;\n referrerUrl?: string;\n pageTitle?: string;\n /** `G` granted, `D` denied. Absent means granted. */\n adStorageConsent?: 'G' | 'D';\n userData: MicrosoftUserData;\n customData?: MicrosoftCustomData;\n}\n\nexport interface MicrosoftConversionsOptions {\n /**\n * EEA/UK/CH consent for the whole batch. `denied` events are accepted but used for nothing —\n * no attribution, no audiences. Absent means granted, which is also the API's default.\n */\n consent?: 'granted' | 'denied';\n /**\n * Also send `page_view` events, as CAPI `pageLoad` events, and link every custom event to the\n * page load it happened on (`pageLoadId`, from the `page_load_id` tag). Off by default because\n * the UET JavaScript already reports every page load and the two would double-count\n * destination-URL goals; turn it on for a CAPI-only site with no tag on the page. Off, no\n * `pageLoadId` is sent either: it would point at a page load Microsoft only saw from the tag,\n * under the tag's own id.\n *\n * Not yet modelled: the revenue-only custom event a `pageLoad` needs for a destination goal\n * with variable revenue.\n */\n pageLoads?: boolean;\n /** Identifies a third-party sender in Microsoft's monitoring; leave unset for a first-party build. */\n dataProvider?: string;\n /**\n * Process the valid events of a batch and report the invalid ones, instead of the API's default\n * all-or-nothing rejection. On by default — one malformed event should cost itself, not the\n * batch it travelled with.\n */\n continueOnValidationError?: boolean;\n}\n\nexport interface MicrosoftValidationDetail {\n index?: number;\n propertyName?: string;\n attemptedValue?: unknown;\n errorMessage?: string;\n errorCode?: string;\n isWarning?: boolean;\n}\n\nexport interface MicrosoftConversionsResponse {\n eventsReceived?: number;\n error?: { code?: string; message?: string; details?: MicrosoftValidationDetail[] };\n}\n\nfunction getUserData(\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n event: TrackEvent<any>,\n data: UserProvidedData\n): MicrosoftUserData {\n const { tags, platform, visitor_id } = event;\n const email = Array.isArray(data.email) ? data.email[0] : data.email;\n const phone = Array.isArray(data.phone_number) ? data.phone_number[0] : data.phone_number;\n const msclkid = microsoftMsclkid(tags);\n\n return {\n msclkid: msclkid ? formatMsclkid(msclkid) : undefined,\n em: hashEmail(email),\n ph: hashPhone(phone),\n // Microsoft requires this to equal the `VID` of the client-side ID Sync pixel; both sides use\n // the SDK visitor id, which every event carries and the client can always read.\n anonymousId: visitor_id || undefined,\n // Microsoft asks for an anonymized id and never a real one. SHA-256, the same digest\n // `sendUETIdSync` applies client-side, so `externalId` and the pixel's `UID` agree too.\n externalId: data.user_id ? sha256(data.user_id) : undefined,\n clientUserAgent: data.user_agent,\n clientIpAddress:\n typeof tags.ip_address === 'string' && tags.ip_address ? tags.ip_address : data.ip_address,\n idfa: platform === 'ios' ? tags.advertising_id : undefined,\n gaid: platform === 'android' ? tags.advertising_id : undefined,\n };\n}\n\n// oxlint-disable-next-line @typescript-eslint/no-explicit-any\nfunction getCustomData(event: TrackEvent<any>): MicrosoftCustomData | undefined {\n const [, params] = mapUETEvent(event.name, event.properties);\n const customData: MicrosoftCustomData = {\n eventCategory: params.event_category,\n eventLabel: params.event_label,\n eventValue: params.event_value,\n searchTerm: params.search_term,\n transactionId: params.transaction_id,\n value: params.revenue_value,\n currency: params.currency,\n items: params.items?.map(({ id, name, price, quantity }) => ({ id, name, price, quantity })),\n itemIds: Array.isArray(params.ecomm_prodid)\n ? params.ecomm_prodid\n : params.ecomm_prodid\n ? [params.ecomm_prodid]\n : undefined,\n pageType: params.ecomm_pagetype,\n ecommTotalValue: params.ecomm_totalvalue,\n ecommCategory: params.ecomm_category,\n };\n return Object.values(customData).some((value) => value !== undefined) ? customData : undefined;\n}\n\n/**\n * Build one CAPI event. `page_view` becomes a `pageLoad` event (the caller decides whether to\n * send those, see `MicrosoftConversionsOptions.pageLoads`); everything else is a `custom` event\n * named after the track event, which is also the UET action the browser sent.\n */\nexport type MicrosoftEventOptions = Pick<MicrosoftConversionsOptions, 'consent' | 'pageLoads'>;\n\nexport function getServerEvent(\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n event: TrackEvent<any>,\n data: UserProvidedData = {},\n /** Options, or — the 8.3.0 signature, still accepted — the bare consent value. */\n options: MicrosoftEventOptions | MicrosoftEventOptions['consent'] = {}\n): MicrosoftEvent {\n const { consent, pageLoads = false } =\n typeof options === 'string' ? { consent: options } : options;\n const { id, name, tags, created_at } = event;\n const isPageLoad = name === 'page_view';\n\n return {\n eventType: isPageLoad ? 'pageLoad' : 'custom',\n eventId: tags.idempotency_key ?? id,\n eventName: isPageLoad ? undefined : name,\n eventTime: Math.round(new Date(created_at).getTime() / 1000),\n eventSourceUrl: pageLocation(tags),\n pageLoadId: pageLoads ? tags.page_load_id : undefined,\n referrerUrl: tags.page_referrer,\n pageTitle: tags.page_title,\n adStorageConsent: consent === 'granted' ? 'G' : consent === 'denied' ? 'D' : undefined,\n userData: getUserData(event, data),\n customData: isPageLoad ? undefined : getCustomData(event),\n };\n}\n\n/** Strip undefined fields so the wire payload carries only what was set. */\nfunction compact<T>(value: T): T {\n return JSON.parse(JSON.stringify(value)) as T;\n}\n\n/** `eventTime` must be \"within the last 7 days\"; a minute's margin for the trip. */\nconst MAX_EVENT_AGE_MS = 7 * 24 * 60 * 60 * 1000 - 60 * 1000;\n\n/**\n * Send events to `POST /v1/{tagId}/events`. Batches above the API's 1,000-event limit are split\n * into consecutive requests; one response is returned per request made. The first failed request\n * rejects — a `ConversionsApiError`, or the fetch error, neither carrying the token — and sends\n * no further ones.\n */\nexport async function sendEvents(\n token: string,\n tagId: string | number,\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n events: TrackEvent<any>[],\n data: UserProvidedData = {},\n options: MicrosoftConversionsOptions = {}\n): Promise<MicrosoftConversionsResponse[]> {\n const { consent, pageLoads = false, dataProvider, continueOnValidationError = true } = options;\n\n const capiEvents = events\n .filter(\n (event) => (pageLoads && event.name === 'page_view') || !IGNORED_EVENTS.includes(event.name)\n )\n .filter((event) => Date.now() - Date.parse(event.created_at) <= MAX_EVENT_AGE_MS)\n .map((event) => getServerEvent(event, data, { consent, pageLoads }))\n // A pageLoad without a URL is rejected by the API, and a page-less event has nothing to say.\n .filter((event) => event.eventType !== 'pageLoad' || event.eventSourceUrl);\n if (capiEvents.length === 0) return [];\n\n const responses: MicrosoftConversionsResponse[] = [];\n for (const batch of chunk(capiEvents, MAX_EVENTS_PER_REQUEST)) {\n const body = compact({ data: batch, continueOnValidationError, dataProvider });\n const response = await fetch(`${ENDPOINT}/${tagId}/events`, {\n method: 'POST',\n // Retried although a POST: the platform deduplicates on the `eventId` each event carries.\n retries: 3,\n headers: {\n 'Content-Type': 'application/json',\n Accept: 'application/json',\n Authorization: `Bearer ${token}`,\n },\n body: JSON.stringify(body),\n });\n // The first failed request ends the batch: sending it again sends every request again, and\n // the platform deduplicates the ones that had gone through.\n if (!response.ok) {\n throw new ConversionsApiError('microsoft', response.status, await response.text());\n }\n const result = (await response.json()) as MicrosoftConversionsResponse;\n // A 200 can still carry field-level warnings (the field was removed) and, with\n // `continueOnValidationError`, skipped events. Surface them: silent partial data loss is the\n // one failure mode the caller cannot see from the status code.\n if (result.error?.details?.length) {\n console.warn(\n `Microsoft conversion accepted with validation issues: ${JSON.stringify(result.error.details)}`\n );\n }\n responses.push(result);\n }\n return responses;\n}\n\n/**\n * Microsoft's Conversions API, sent the same events as `microsoftAds` (`events`, the GA4\n * conversion events by default, and `customEvents`) — and `page_view` too with `pageLoads`, for\n * a site with no UET tag on the page. `consent` is the API's batch-level consent here, not the\n * tag's consent mode default.\n */\nexport function microsoftConversions(\n options: Omit<MicrosoftAdsOptions, 'consent' | 'customerId'> &\n MicrosoftConversionsOptions & { accessToken: string }\n): ConversionDestination {\n const accepts = uetEvents(options);\n return conversionDestination(\n (name) => accepts(name) || (options.pageLoads === true && name === 'page_view'),\n (events, data) => sendEvents(options.accessToken, options.tagId, events, data, options)\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6BA,MAAM,WAAW;;AAGjB,MAAM,yBAAyB;AAE/B,MAAM,SAAS;AAEf,MAAM,UAAU,WAAA,GAAkBA,YAAAA,WAAAA,CAAW,QAAQ,CAAC,CAAC,OAAO,KAAK,CAAC,CAAC,OAAO,KAAK;;;;;;;AAQjF,SAAgB,eAAe,OAAuB;CACpD,MAAM,QAAQ,MAAM,KAAK,CAAC,CAAC,YAAY;CACvC,MAAM,KAAK,MAAM,YAAY,GAAG;CAChC,IAAI,OAAO,IAAI,OAAO;CAEtB,OAAO,GADM,MAAM,MAAM,GAAG,EAAE,CAAC,CAAC,QAAQ,OAAO,EAAE,CAAC,CAAC,MAAM,KAAK,CAAC,CAAC,CAAC,MAAM,GACxD,GAAG,MAAM,MAAM,KAAK,CAAC;AACtC;AAEA,SAAS,UAAU,OAA+C;CAChE,MAAM,QAAQ,OAAO,KAAK,CAAC,CAAC,YAAY;CACxC,IAAI,CAAC,OAAO,OAAO,KAAA;CACnB,OAAO,OAAO,KAAK,KAAK,IAAI,QAAQ,OAAO,eAAe,KAAK,CAAC;AAClE;;;;;;AAOA,SAAS,UAAU,OAA+C;CAChE,MAAM,QAAQ,OAAO,KAAK,CAAC,CAAC,YAAY;CACxC,IAAI,CAAC,OAAO,OAAO,KAAA;CACnB,IAAI,OAAO,KAAK,KAAK,GAAG,OAAO;CAC/B,MAAM,QAAQ,MAAM,QAAQ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U,MAAM,cAAc,cAAc,MAAM,cAAc;CAC3E,IAAI,WAAW,WAAW,GAAG,OAAO,CAAC;CAErC,MAAM,YAA4C,CAAC;CACnD,KAAK,MAAM,UAAA,GAASC,cAAAA,MAAAA,CAAM,YAAY,sBAAsB,GAAG;EAC7D,MAAM,OAAO,QAAQ;GAAE,MAAM;GAAO;GAA2B;EAAa,CAAC;EAC7E,MAAM,WAAW,OAAA,GAAMC,cAAAA,MAAAA,CAAM,GAAG,SAAS,GAAG,MAAM,UAAU;GAC1D,QAAQ;GAER,SAAS;GACT,SAAS;IACP,gBAAgB;IAChB,QAAQ;IACR,eAAe,UAAU;GAC3B;GACA,MAAM,KAAK,UAAU,IAAI;EAC3B,CAAC;EAGD,IAAI,CAAC,SAAS,IACZ,MAAM,IAAIC,qCAAAA,oBAAoB,aAAa,SAAS,QAAQ,MAAM,SAAS,KAAK,CAAC;EAEnF,MAAM,SAAU,MAAM,SAAS,KAAK;EAIpC,IAAI,OAAO,OAAO,SAAS,QACzB,QAAQ,KACN,yDAAyD,KAAK,UAAU,OAAO,MAAM,OAAO,GAC9F;EAEF,UAAU,KAAK,MAAM;CACvB;CACA,OAAO;AACT;;;;;;;AAQA,SAAgB,qBACd,SAEuB;CACvB,MAAM,UAAUC,oCAAAA,UAAU,OAAO;CACjC,OAAOC,iCAAAA,uBACJ,SAAS,QAAQ,IAAI,KAAM,QAAQ,cAAc,QAAQ,SAAS,cAClE,QAAQ,SAAS,WAAW,QAAQ,aAAa,QAAQ,OAAO,QAAQ,MAAM,OAAO,CACxF;AACF"}
@@ -1,4 +1,6 @@
1
1
  import { TrackEvent, UserProvidedData } from "../track/types.cjs";
2
+ import { ConversionDestination } from "./setup-conversions.cjs";
3
+ import { MicrosoftAdsOptions } from "../third-parties/microsoft-uet.cjs";
2
4
  /**
3
5
  * Microsoft's email normalization: trim, drop the dots and any `+alias` from the user part —
4
6
  * for EVERY domain, unlike Google's gmail-only rule — lowercase, SHA-256. A value that is
@@ -114,8 +116,18 @@ export declare function getServerEvent(event: TrackEvent<any>, data?: UserProvid
114
116
  options?: MicrosoftEventOptions | MicrosoftEventOptions['consent']): MicrosoftEvent;
115
117
  /**
116
118
  * Send events to `POST /v1/{tagId}/events`. Batches above the API's 1,000-event limit are split
117
- * into consecutive requests; one response is returned per request made. Never throws: an HTTP
118
- * or network failure is logged (without the token) and yields no response for that request.
119
+ * into consecutive requests; one response is returned per request made. The first failed request
120
+ * rejects — a `ConversionsApiError`, or the fetch error, neither carrying the token — and sends
121
+ * no further ones.
119
122
  */
120
123
  export declare function sendEvents(token: string, tagId: string | number, events: TrackEvent<any>[], data?: UserProvidedData, options?: MicrosoftConversionsOptions): Promise<MicrosoftConversionsResponse[]>;
124
+ /**
125
+ * Microsoft's Conversions API, sent the same events as `microsoftAds` (`events`, the GA4
126
+ * conversion events by default, and `customEvents`) — and `page_view` too with `pageLoads`, for
127
+ * a site with no UET tag on the page. `consent` is the API's batch-level consent here, not the
128
+ * tag's consent mode default.
129
+ */
130
+ export declare function microsoftConversions(options: Omit<MicrosoftAdsOptions, 'consent' | 'customerId'> & MicrosoftConversionsOptions & {
131
+ accessToken: string;
132
+ }): ConversionDestination;
121
133
  //# sourceMappingURL=microsoft-conversions-api.d.cts.map
@@ -1 +1 @@
1
- {"version":3,"file":"microsoft-conversions-api.d.cts","names":[],"sources":["../../src/server/microsoft-conversions-api.ts"],"mappings":";;;;;;;wBAyCgB,eAAe;iBA2Bd;;EAEf;;EAEA;;EAEA;;EAEA;;EAEA;EACA;EACA;EACA;EACA;;iBAGe;EACf;EACA;EACA;EACA;;iBAGe;EACf;EACA;EACA;EACA;EACA;EACA;EACA;EACA,QAAQ;EACR;EACA;EACA;EACA;;;iBAIe;EACf;EACA;;EAEA;;EAEA;EACA;;EAEA;EACA;EACA;;EAEA;EACA,UAAU;EACV,aAAa;;iBAGE;;;;;EAKf;;;;;;;;;;;;EAYA;;EAEA;;;;;;EAMA;;iBAGe;EACf;EACA;EACA;EACA;EACA;EACA;;iBAGe;EACf;EACA;IAAU;IAAe;IAAkB,UAAU;;;;;;;;YA4D3C,wBAAwB,KAAK;wBAEzB,eAEd,OAAO,iBACP,OAAM;;AAEN,UAAS,wBAAwB,mCAChC;;;;;;wBAkCmB,WACpB,eACA,wBAEA,QAAQ,mBACR,OAAM,kBACN,UAAS,8BACR,QAAQ"}
1
+ {"version":3,"file":"microsoft-conversions-api.d.cts","names":[],"sources":["../../src/server/microsoft-conversions-api.ts"],"mappings":";;;;;;;;;wBA4CgB,eAAe;iBA2Bd;;EAEf;;EAEA;;EAEA;;EAEA;;EAEA;EACA;EACA;EACA;EACA;;iBAGe;EACf;EACA;EACA;EACA;;iBAGe;EACf;EACA;EACA;EACA;EACA;EACA;EACA;EACA,QAAQ;EACR;EACA;EACA;EACA;;;iBAIe;EACf;EACA;;EAEA;;EAEA;EACA;;EAEA;EACA;EACA;;EAEA;EACA,UAAU;EACV,aAAa;;iBAGE;;;;;EAKf;;;;;;;;;;;;EAYA;;EAEA;;;;;;EAMA;;iBAGe;EACf;EACA;EACA;EACA;EACA;EACA;;iBAGe;EACf;EACA;IAAU;IAAe;IAAkB,UAAU;;;;;;;;YA4D3C,wBAAwB,KAAK;wBAEzB,eAEd,OAAO,iBACP,OAAM;;AAEN,UAAS,wBAAwB,mCAChC;;;;;;;wBAmCmB,WACpB,eACA,wBAEA,QAAQ,mBACR,OAAM,kBACN,UAAS,8BACR,QAAQ;;;;;;;wBAoDK,qBACd,SAAS,KAAK,iDACZ;EAAgC;IACjC"}
@@ -1,4 +1,6 @@
1
1
  import { TrackEvent, UserProvidedData } from "../track/types.mjs";
2
+ import { ConversionDestination } from "./setup-conversions.mjs";
3
+ import { MicrosoftAdsOptions } from "../third-parties/microsoft-uet.mjs";
2
4
  /**
3
5
  * Microsoft's email normalization: trim, drop the dots and any `+alias` from the user part —
4
6
  * for EVERY domain, unlike Google's gmail-only rule — lowercase, SHA-256. A value that is
@@ -114,8 +116,18 @@ export declare function getServerEvent(event: TrackEvent<any>, data?: UserProvid
114
116
  options?: MicrosoftEventOptions | MicrosoftEventOptions['consent']): MicrosoftEvent;
115
117
  /**
116
118
  * Send events to `POST /v1/{tagId}/events`. Batches above the API's 1,000-event limit are split
117
- * into consecutive requests; one response is returned per request made. Never throws: an HTTP
118
- * or network failure is logged (without the token) and yields no response for that request.
119
+ * into consecutive requests; one response is returned per request made. The first failed request
120
+ * rejects — a `ConversionsApiError`, or the fetch error, neither carrying the token — and sends
121
+ * no further ones.
119
122
  */
120
123
  export declare function sendEvents(token: string, tagId: string | number, events: TrackEvent<any>[], data?: UserProvidedData, options?: MicrosoftConversionsOptions): Promise<MicrosoftConversionsResponse[]>;
124
+ /**
125
+ * Microsoft's Conversions API, sent the same events as `microsoftAds` (`events`, the GA4
126
+ * conversion events by default, and `customEvents`) — and `page_view` too with `pageLoads`, for
127
+ * a site with no UET tag on the page. `consent` is the API's batch-level consent here, not the
128
+ * tag's consent mode default.
129
+ */
130
+ export declare function microsoftConversions(options: Omit<MicrosoftAdsOptions, 'consent' | 'customerId'> & MicrosoftConversionsOptions & {
131
+ accessToken: string;
132
+ }): ConversionDestination;
121
133
  //# sourceMappingURL=microsoft-conversions-api.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"microsoft-conversions-api.d.mts","names":[],"sources":["../../src/server/microsoft-conversions-api.ts"],"mappings":";;;;;;;wBAyCgB,eAAe;iBA2Bd;;EAEf;;EAEA;;EAEA;;EAEA;;EAEA;EACA;EACA;EACA;EACA;;iBAGe;EACf;EACA;EACA;EACA;;iBAGe;EACf;EACA;EACA;EACA;EACA;EACA;EACA;EACA,QAAQ;EACR;EACA;EACA;EACA;;;iBAIe;EACf;EACA;;EAEA;;EAEA;EACA;;EAEA;EACA;EACA;;EAEA;EACA,UAAU;EACV,aAAa;;iBAGE;;;;;EAKf;;;;;;;;;;;;EAYA;;EAEA;;;;;;EAMA;;iBAGe;EACf;EACA;EACA;EACA;EACA;EACA;;iBAGe;EACf;EACA;IAAU;IAAe;IAAkB,UAAU;;;;;;;;YA4D3C,wBAAwB,KAAK;wBAEzB,eAEd,OAAO,iBACP,OAAM;;AAEN,UAAS,wBAAwB,mCAChC;;;;;;wBAkCmB,WACpB,eACA,wBAEA,QAAQ,mBACR,OAAM,kBACN,UAAS,8BACR,QAAQ"}
1
+ {"version":3,"file":"microsoft-conversions-api.d.mts","names":[],"sources":["../../src/server/microsoft-conversions-api.ts"],"mappings":";;;;;;;;;wBA4CgB,eAAe;iBA2Bd;;EAEf;;EAEA;;EAEA;;EAEA;;EAEA;EACA;EACA;EACA;EACA;;iBAGe;EACf;EACA;EACA;EACA;;iBAGe;EACf;EACA;EACA;EACA;EACA;EACA;EACA;EACA,QAAQ;EACR;EACA;EACA;EACA;;;iBAIe;EACf;EACA;;EAEA;;EAEA;EACA;;EAEA;EACA;EACA;;EAEA;EACA,UAAU;EACV,aAAa;;iBAGE;;;;;EAKf;;;;;;;;;;;;EAYA;;EAEA;;;;;;EAMA;;iBAGe;EACf;EACA;EACA;EACA;EACA;EACA;;iBAGe;EACf;EACA;IAAU;IAAe;IAAkB,UAAU;;;;;;;;YA4D3C,wBAAwB,KAAK;wBAEzB,eAEd,OAAO,iBACP,OAAM;;AAEN,UAAS,wBAAwB,mCAChC;;;;;;;wBAmCmB,WACpB,eACA,wBAEA,QAAQ,mBACR,OAAM,kBACN,UAAS,8BACR,QAAQ;;;;;;;wBAoDK,qBACd,SAAS,KAAK,iDACZ;EAAgC;IACjC"}
@@ -1,15 +1,18 @@
1
1
  import { IGNORED_EVENTS } from "../third-parties/ignored-events.mjs";
2
2
  import { formatMsclkid } from "../click-id/index.mjs";
3
3
  import { mapUETEvent } from "../track/uetq.mjs";
4
+ import { uetEvents } from "../third-parties/microsoft-uet.mjs";
4
5
  import { microsoftMsclkid } from "./click-ids.mjs";
6
+ import { ConversionsApiError } from "./conversions-api-error.mjs";
7
+ import { conversionDestination } from "./setup-conversions.mjs";
5
8
  import { pageLocation } from "./page-location.mjs";
6
9
  import { chunk, fetch } from "@shware/utils";
7
10
  import { createHash } from "node:crypto";
8
11
  // src/server/microsoft-conversions-api.ts
9
12
  /**
10
13
  * Microsoft Advertising Conversions API (CAPI) sender — the server-side counterpart of the UET
11
- * tag, in the same shape as the other senders here: a pure per-event builder, a never-throws
12
- * `sendEvents`, the token in a header and never in a URL or a log line.
14
+ * tag, in the same shape as the other senders here: a pure per-event builder, a `sendEvents`
15
+ * that rejects on failure, the token in a header and never in a URL or an error.
13
16
  *
14
17
  * Microsoft's recommended deployment is hybrid: keep the UET JavaScript on the page and send the
15
18
  * same conversions here too, deduplicated by (`tagId`, `eventName`, `eventId`). Both channels in
@@ -123,8 +126,9 @@ function compact(value) {
123
126
  const MAX_EVENT_AGE_MS = 60474e4;
124
127
  /**
125
128
  * Send events to `POST /v1/{tagId}/events`. Batches above the API's 1,000-event limit are split
126
- * into consecutive requests; one response is returned per request made. Never throws: an HTTP
127
- * or network failure is logged (without the token) and yields no response for that request.
129
+ * into consecutive requests; one response is returned per request made. The first failed request
130
+ * rejects — a `ConversionsApiError`, or the fetch error, neither carrying the token — and sends
131
+ * no further ones.
128
132
  */
129
133
  async function sendEvents(token, tagId, events, data = {}, options = {}) {
130
134
  const { consent, pageLoads = false, dataProvider, continueOnValidationError = true } = options;
@@ -140,33 +144,33 @@ async function sendEvents(token, tagId, events, data = {}, options = {}) {
140
144
  continueOnValidationError,
141
145
  dataProvider
142
146
  });
143
- try {
144
- const response = await fetch(`${ENDPOINT}/${tagId}/events`, {
145
- method: "POST",
146
- retries: 3,
147
- headers: {
148
- "Content-Type": "application/json",
149
- Accept: "application/json",
150
- Authorization: `Bearer ${token}`
151
- },
152
- body: JSON.stringify(body)
153
- });
154
- if (response.ok) {
155
- const result = await response.json();
156
- if (result.error?.details?.length) console.warn(`Microsoft conversion accepted with validation issues: ${JSON.stringify(result.error.details)}`);
157
- responses.push(result);
158
- continue;
159
- }
160
- const { status } = response;
161
- const message = await response.text();
162
- console.error(`Failed to send Microsoft conversion, status: ${status}, body: ${message}`);
163
- } catch (error) {
164
- const message = error instanceof Error ? error.message : String(error);
165
- console.error(`Failed to send Microsoft conversion, network error: ${message}`);
166
- }
147
+ const response = await fetch(`${ENDPOINT}/${tagId}/events`, {
148
+ method: "POST",
149
+ retries: 3,
150
+ headers: {
151
+ "Content-Type": "application/json",
152
+ Accept: "application/json",
153
+ Authorization: `Bearer ${token}`
154
+ },
155
+ body: JSON.stringify(body)
156
+ });
157
+ if (!response.ok) throw new ConversionsApiError("microsoft", response.status, await response.text());
158
+ const result = await response.json();
159
+ if (result.error?.details?.length) console.warn(`Microsoft conversion accepted with validation issues: ${JSON.stringify(result.error.details)}`);
160
+ responses.push(result);
167
161
  }
168
162
  return responses;
169
163
  }
170
- export { getServerEvent, normalizeEmail, sendEvents };
164
+ /**
165
+ * Microsoft's Conversions API, sent the same events as `microsoftAds` (`events`, the GA4
166
+ * conversion events by default, and `customEvents`) — and `page_view` too with `pageLoads`, for
167
+ * a site with no UET tag on the page. `consent` is the API's batch-level consent here, not the
168
+ * tag's consent mode default.
169
+ */
170
+ function microsoftConversions(options) {
171
+ const accepts = uetEvents(options);
172
+ return conversionDestination((name) => accepts(name) || options.pageLoads === true && name === "page_view", (events, data) => sendEvents(options.accessToken, options.tagId, events, data, options));
173
+ }
174
+ export { getServerEvent, microsoftConversions, normalizeEmail, sendEvents };
171
175
 
172
176
  //# sourceMappingURL=microsoft-conversions-api.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"microsoft-conversions-api.mjs","names":[],"sources":["../../src/server/microsoft-conversions-api.ts"],"sourcesContent":["/**\n * Microsoft Advertising Conversions API (CAPI) sender — the server-side counterpart of the UET\n * tag, in the same shape as the other senders here: a pure per-event builder, a never-throws\n * `sendEvents`, the token in a header and never in a URL or a log line.\n *\n * Microsoft's recommended deployment is hybrid: keep the UET JavaScript on the page and send the\n * same conversions here too, deduplicated by (`tagId`, `eventName`, `eventId`). Both channels in\n * this SDK are fed from the same `track()` call — the browser sends the internal name as the UET\n * action with the event id as `event_id`, and this builder sends the same name as `eventName`\n * with the same id — so the pair agrees by construction.\n *\n * The token comes from the UET tag's \"Use Conversions API\" setup step, or from the Campaign\n * Management API's `UetTagAuthKey/Query`. Access is provisioned per customer account: an account\n * whose tag setup has no \"Use Conversions API\" option has to ask Microsoft Advertising support.\n *\n * https://learn.microsoft.com/en-us/advertising/guides/uet-conversion-api-integration\n */\nimport { createHash } from 'node:crypto';\nimport { chunk, fetch } from '@shware/utils';\nimport { formatMsclkid } from '../click-id/index';\nimport { IGNORED_EVENTS } from '../third-parties/ignored-events';\nimport type { TrackEvent, UserProvidedData } from '../track/types';\nimport { mapUETEvent } from '../track/uetq';\nimport { microsoftMsclkid } from './click-ids';\nimport { pageLocation } from './page-location';\n\nconst ENDPOINT = 'https://capi.uet.microsoft.com/v1';\n\n/** The API's hard limit per request. */\nconst MAX_EVENTS_PER_REQUEST = 1000;\n\nconst SHA256 = /^[a-f0-9]{64}$/;\n\nconst sha256 = (value: string) => createHash('sha256').update(value).digest('hex');\n\n/**\n * Microsoft's email normalization: trim, drop the dots and any `+alias` from the user part —\n * for EVERY domain, unlike Google's gmail-only rule — lowercase, SHA-256. A value that is\n * already a SHA-256 hex digest passes through.\n * https://learn.microsoft.com/en-us/advertising/guides/uet-conversion-api-integration#hashed-identifiers\n */\nexport function normalizeEmail(input: string): string {\n const email = input.trim().toLowerCase();\n const at = email.lastIndexOf('@');\n if (at === -1) return email;\n const user = email.slice(0, at).replace(/\\./g, '').split('+', 1)[0] ?? '';\n return `${user}@${email.slice(at + 1)}`;\n}\n\nfunction hashEmail(input: string | undefined): string | undefined {\n const value = input?.trim().toLowerCase();\n if (!value) return undefined;\n return SHA256.test(value) ? value : sha256(normalizeEmail(value));\n}\n\n/**\n * Phones are E.164 by the schema (`+` then 11–15 digits, the range bat.js validates too); the\n * separators bat.js tolerates are stripped, and anything else is dropped rather than guessed —\n * a number with no country code hashed under an assumed one can never match.\n */\nfunction hashPhone(input: string | undefined): string | undefined {\n const value = input?.trim().toLowerCase();\n if (!value) return undefined;\n if (SHA256.test(value)) return value;\n const phone = value.replace(/[-() \\t]/g, '');\n return /^\\+\\d{11,15}$/.test(phone) ? sha256(phone) : undefined;\n}\n\nexport interface MicrosoftUserData {\n /** Microsoft click id, as a dashed UUID. */\n msclkid?: string;\n /** SHA-256 of the normalized email. */\n em?: string;\n /** SHA-256 of the E.164 phone number. */\n ph?: string;\n /** The SDK visitor id — what the client-side ID Sync pixel (`sendUETIdSync`) sends as `VID`. */\n anonymousId?: string;\n /** SHA-256 of the signed-in user id — what `sendUETIdSync` sends as `UID`. */\n externalId?: string;\n clientUserAgent?: string;\n clientIpAddress?: string;\n idfa?: string;\n gaid?: string;\n}\n\nexport interface MicrosoftItem {\n id?: string;\n name?: string;\n price?: number;\n quantity?: number;\n}\n\nexport interface MicrosoftCustomData {\n eventCategory?: string;\n eventLabel?: string;\n eventValue?: number;\n searchTerm?: string;\n transactionId?: string;\n value?: number;\n currency?: string;\n items?: MicrosoftItem[];\n itemIds?: string[];\n pageType?: string;\n ecommTotalValue?: number;\n ecommCategory?: string;\n}\n\n/** One entry of the `data` array POSTed to `/v1/{tagId}/events`. */\nexport interface MicrosoftEvent {\n eventType: 'custom' | 'pageLoad';\n eventId: string;\n /** The UET action; absent on `pageLoad` events. */\n eventName?: string;\n /** UNIX seconds, UTC; the API rejects anything older than 7 days. */\n eventTime: number;\n eventSourceUrl?: string;\n /** Links a `custom` event to its `pageLoad` event; a v4 UUID (the SDK's `page_load_id` tag). */\n pageLoadId?: string;\n referrerUrl?: string;\n pageTitle?: string;\n /** `G` granted, `D` denied. Absent means granted. */\n adStorageConsent?: 'G' | 'D';\n userData: MicrosoftUserData;\n customData?: MicrosoftCustomData;\n}\n\nexport interface MicrosoftConversionsOptions {\n /**\n * EEA/UK/CH consent for the whole batch. `denied` events are accepted but used for nothing —\n * no attribution, no audiences. Absent means granted, which is also the API's default.\n */\n consent?: 'granted' | 'denied';\n /**\n * Also send `page_view` events, as CAPI `pageLoad` events, and link every custom event to the\n * page load it happened on (`pageLoadId`, from the `page_load_id` tag). Off by default because\n * the UET JavaScript already reports every page load and the two would double-count\n * destination-URL goals; turn it on for a CAPI-only site with no tag on the page. Off, no\n * `pageLoadId` is sent either: it would point at a page load Microsoft only saw from the tag,\n * under the tag's own id.\n *\n * Not yet modelled: the revenue-only custom event a `pageLoad` needs for a destination goal\n * with variable revenue.\n */\n pageLoads?: boolean;\n /** Identifies a third-party sender in Microsoft's monitoring; leave unset for a first-party build. */\n dataProvider?: string;\n /**\n * Process the valid events of a batch and report the invalid ones, instead of the API's default\n * all-or-nothing rejection. On by default — one malformed event should cost itself, not the\n * batch it travelled with.\n */\n continueOnValidationError?: boolean;\n}\n\nexport interface MicrosoftValidationDetail {\n index?: number;\n propertyName?: string;\n attemptedValue?: unknown;\n errorMessage?: string;\n errorCode?: string;\n isWarning?: boolean;\n}\n\nexport interface MicrosoftConversionsResponse {\n eventsReceived?: number;\n error?: { code?: string; message?: string; details?: MicrosoftValidationDetail[] };\n}\n\nfunction getUserData(\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n event: TrackEvent<any>,\n data: UserProvidedData\n): MicrosoftUserData {\n const { tags, platform, visitor_id } = event;\n const email = Array.isArray(data.email) ? data.email[0] : data.email;\n const phone = Array.isArray(data.phone_number) ? data.phone_number[0] : data.phone_number;\n const msclkid = microsoftMsclkid(tags);\n\n return {\n msclkid: msclkid ? formatMsclkid(msclkid) : undefined,\n em: hashEmail(email),\n ph: hashPhone(phone),\n // Microsoft requires this to equal the `VID` of the client-side ID Sync pixel; both sides use\n // the SDK visitor id, which every event carries and the client can always read.\n anonymousId: visitor_id || undefined,\n // Microsoft asks for an anonymized id and never a real one. SHA-256, the same digest\n // `sendUETIdSync` applies client-side, so `externalId` and the pixel's `UID` agree too.\n externalId: data.user_id ? sha256(data.user_id) : undefined,\n clientUserAgent: data.user_agent,\n clientIpAddress:\n typeof tags.ip_address === 'string' && tags.ip_address ? tags.ip_address : data.ip_address,\n idfa: platform === 'ios' ? tags.advertising_id : undefined,\n gaid: platform === 'android' ? tags.advertising_id : undefined,\n };\n}\n\n// oxlint-disable-next-line @typescript-eslint/no-explicit-any\nfunction getCustomData(event: TrackEvent<any>): MicrosoftCustomData | undefined {\n const [, params] = mapUETEvent(event.name, event.properties);\n const customData: MicrosoftCustomData = {\n eventCategory: params.event_category,\n eventLabel: params.event_label,\n eventValue: params.event_value,\n searchTerm: params.search_term,\n transactionId: params.transaction_id,\n value: params.revenue_value,\n currency: params.currency,\n items: params.items?.map(({ id, name, price, quantity }) => ({ id, name, price, quantity })),\n itemIds: Array.isArray(params.ecomm_prodid)\n ? params.ecomm_prodid\n : params.ecomm_prodid\n ? [params.ecomm_prodid]\n : undefined,\n pageType: params.ecomm_pagetype,\n ecommTotalValue: params.ecomm_totalvalue,\n ecommCategory: params.ecomm_category,\n };\n return Object.values(customData).some((value) => value !== undefined) ? customData : undefined;\n}\n\n/**\n * Build one CAPI event. `page_view` becomes a `pageLoad` event (the caller decides whether to\n * send those, see `MicrosoftConversionsOptions.pageLoads`); everything else is a `custom` event\n * named after the track event, which is also the UET action the browser sent.\n */\nexport type MicrosoftEventOptions = Pick<MicrosoftConversionsOptions, 'consent' | 'pageLoads'>;\n\nexport function getServerEvent(\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n event: TrackEvent<any>,\n data: UserProvidedData = {},\n /** Options, or — the 8.3.0 signature, still accepted — the bare consent value. */\n options: MicrosoftEventOptions | MicrosoftEventOptions['consent'] = {}\n): MicrosoftEvent {\n const { consent, pageLoads = false } =\n typeof options === 'string' ? { consent: options } : options;\n const { id, name, tags, created_at } = event;\n const isPageLoad = name === 'page_view';\n\n return {\n eventType: isPageLoad ? 'pageLoad' : 'custom',\n eventId: tags.idempotency_key ?? id,\n eventName: isPageLoad ? undefined : name,\n eventTime: Math.round(new Date(created_at).getTime() / 1000),\n eventSourceUrl: pageLocation(tags),\n pageLoadId: pageLoads ? tags.page_load_id : undefined,\n referrerUrl: tags.page_referrer,\n pageTitle: tags.page_title,\n adStorageConsent: consent === 'granted' ? 'G' : consent === 'denied' ? 'D' : undefined,\n userData: getUserData(event, data),\n customData: isPageLoad ? undefined : getCustomData(event),\n };\n}\n\n/** Strip undefined fields so the wire payload carries only what was set. */\nfunction compact<T>(value: T): T {\n return JSON.parse(JSON.stringify(value)) as T;\n}\n\n/** `eventTime` must be \"within the last 7 days\"; a minute's margin for the trip. */\nconst MAX_EVENT_AGE_MS = 7 * 24 * 60 * 60 * 1000 - 60 * 1000;\n\n/**\n * Send events to `POST /v1/{tagId}/events`. Batches above the API's 1,000-event limit are split\n * into consecutive requests; one response is returned per request made. Never throws: an HTTP\n * or network failure is logged (without the token) and yields no response for that request.\n */\nexport async function sendEvents(\n token: string,\n tagId: string | number,\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n events: TrackEvent<any>[],\n data: UserProvidedData = {},\n options: MicrosoftConversionsOptions = {}\n): Promise<MicrosoftConversionsResponse[]> {\n const { consent, pageLoads = false, dataProvider, continueOnValidationError = true } = options;\n\n const capiEvents = events\n .filter(\n (event) => (pageLoads && event.name === 'page_view') || !IGNORED_EVENTS.includes(event.name)\n )\n .filter((event) => Date.now() - Date.parse(event.created_at) <= MAX_EVENT_AGE_MS)\n .map((event) => getServerEvent(event, data, { consent, pageLoads }))\n // A pageLoad without a URL is rejected by the API, and a page-less event has nothing to say.\n .filter((event) => event.eventType !== 'pageLoad' || event.eventSourceUrl);\n if (capiEvents.length === 0) return [];\n\n const responses: MicrosoftConversionsResponse[] = [];\n for (const batch of chunk(capiEvents, MAX_EVENTS_PER_REQUEST)) {\n const body = compact({ data: batch, continueOnValidationError, dataProvider });\n try {\n const response = await fetch(`${ENDPOINT}/${tagId}/events`, {\n method: 'POST',\n // Retried although a POST: the platform deduplicates on the `eventId` each event carries.\n retries: 3,\n headers: {\n 'Content-Type': 'application/json',\n Accept: 'application/json',\n Authorization: `Bearer ${token}`,\n },\n body: JSON.stringify(body),\n });\n if (response.ok) {\n const result = (await response.json()) as MicrosoftConversionsResponse;\n // A 200 can still carry field-level warnings (the field was removed) and, with\n // `continueOnValidationError`, skipped events. Surface them: silent partial data loss is\n // the one failure mode the caller cannot see from the status code.\n if (result.error?.details?.length) {\n console.warn(\n `Microsoft conversion accepted with validation issues: ${JSON.stringify(result.error.details)}`\n );\n }\n responses.push(result);\n continue;\n }\n const { status } = response;\n const message = await response.text();\n console.error(`Failed to send Microsoft conversion, status: ${status}, body: ${message}`);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n console.error(`Failed to send Microsoft conversion, network error: ${message}`);\n }\n }\n return responses;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AA0BA,MAAM,WAAW;;AAGjB,MAAM,yBAAyB;AAE/B,MAAM,SAAS;AAEf,MAAM,UAAU,UAAkB,WAAW,QAAQ,CAAC,CAAC,OAAO,KAAK,CAAC,CAAC,OAAO,KAAK;;;;;;;AAQjF,SAAgB,eAAe,OAAuB;CACpD,MAAM,QAAQ,MAAM,KAAK,CAAC,CAAC,YAAY;CACvC,MAAM,KAAK,MAAM,YAAY,GAAG;CAChC,IAAI,OAAO,IAAI,OAAO;CAEtB,OAAO,GADM,MAAM,MAAM,GAAG,EAAE,CAAC,CAAC,QAAQ,OAAO,EAAE,CAAC,CAAC,MAAM,KAAK,CAAC,CAAC,CAAC,MAAM,GACxD,GAAG,MAAM,MAAM,KAAK,CAAC;AACtC;AAEA,SAAS,UAAU,OAA+C;CAChE,MAAM,QAAQ,OAAO,KAAK,CAAC,CAAC,YAAY;CACxC,IAAI,CAAC,OAAO,OAAO,KAAA;CACnB,OAAO,OAAO,KAAK,KAAK,IAAI,QAAQ,OAAO,eAAe,KAAK,CAAC;AAClE;;;;;;AAOA,SAAS,UAAU,OAA+C;CAChE,MAAM,QAAQ,OAAO,KAAK,CAAC,CAAC,YAAY;CACxC,IAAI,CAAC,OAAO,OAAO,KAAA;CACnB,IAAI,OAAO,KAAK,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AU,MAAM,cAAc,cAAc,MAAM,cAAc;CAC3E,IAAI,WAAW,WAAW,GAAG,OAAO,CAAC;CAErC,MAAM,YAA4C,CAAC;CACnD,KAAK,MAAM,SAAS,MAAM,YAAY,sBAAsB,GAAG;EAC7D,MAAM,OAAO,QAAQ;GAAE,MAAM;GAAO;GAA2B;EAAa,CAAC;EAC7E,IAAI;GACF,MAAM,WAAW,MAAM,MAAM,GAAG,SAAS,GAAG,MAAM,UAAU;IAC1D,QAAQ;IAER,SAAS;IACT,SAAS;KACP,gBAAgB;KAChB,QAAQ;KACR,eAAe,UAAU;IAC3B;IACA,MAAM,KAAK,UAAU,IAAI;GAC3B,CAAC;GACD,IAAI,SAAS,IAAI;IACf,MAAM,SAAU,MAAM,SAAS,KAAK;IAIpC,IAAI,OAAO,OAAO,SAAS,QACzB,QAAQ,KACN,yDAAyD,KAAK,UAAU,OAAO,MAAM,OAAO,GAC9F;IAEF,UAAU,KAAK,MAAM;IACrB;GACF;GACA,MAAM,EAAE,WAAW;GACnB,MAAM,UAAU,MAAM,SAAS,KAAK;GACpC,QAAQ,MAAM,gDAAgD,OAAO,UAAU,SAAS;EAC1F,SAAS,OAAO;GACd,MAAM,UAAU,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;GACrE,QAAQ,MAAM,uDAAuD,SAAS;EAChF;CACF;CACA,OAAO;AACT"}
1
+ {"version":3,"file":"microsoft-conversions-api.mjs","names":[],"sources":["../../src/server/microsoft-conversions-api.ts"],"sourcesContent":["/**\n * Microsoft Advertising Conversions API (CAPI) sender — the server-side counterpart of the UET\n * tag, in the same shape as the other senders here: a pure per-event builder, a `sendEvents`\n * that rejects on failure, the token in a header and never in a URL or an error.\n *\n * Microsoft's recommended deployment is hybrid: keep the UET JavaScript on the page and send the\n * same conversions here too, deduplicated by (`tagId`, `eventName`, `eventId`). Both channels in\n * this SDK are fed from the same `track()` call — the browser sends the internal name as the UET\n * action with the event id as `event_id`, and this builder sends the same name as `eventName`\n * with the same id — so the pair agrees by construction.\n *\n * The token comes from the UET tag's \"Use Conversions API\" setup step, or from the Campaign\n * Management API's `UetTagAuthKey/Query`. Access is provisioned per customer account: an account\n * whose tag setup has no \"Use Conversions API\" option has to ask Microsoft Advertising support.\n *\n * https://learn.microsoft.com/en-us/advertising/guides/uet-conversion-api-integration\n */\nimport { createHash } from 'node:crypto';\nimport { chunk, fetch } from '@shware/utils';\nimport { formatMsclkid } from '../click-id/index';\nimport { IGNORED_EVENTS } from '../third-parties/ignored-events';\nimport { type MicrosoftAdsOptions, uetEvents } from '../third-parties/microsoft-uet';\nimport type { TrackEvent, UserProvidedData } from '../track/types';\nimport { mapUETEvent } from '../track/uetq';\nimport { microsoftMsclkid } from './click-ids';\nimport { ConversionsApiError } from './conversions-api-error';\nimport { pageLocation } from './page-location';\nimport { type ConversionDestination, conversionDestination } from './setup-conversions';\n\nconst ENDPOINT = 'https://capi.uet.microsoft.com/v1';\n\n/** The API's hard limit per request. */\nconst MAX_EVENTS_PER_REQUEST = 1000;\n\nconst SHA256 = /^[a-f0-9]{64}$/;\n\nconst sha256 = (value: string) => createHash('sha256').update(value).digest('hex');\n\n/**\n * Microsoft's email normalization: trim, drop the dots and any `+alias` from the user part —\n * for EVERY domain, unlike Google's gmail-only rule — lowercase, SHA-256. A value that is\n * already a SHA-256 hex digest passes through.\n * https://learn.microsoft.com/en-us/advertising/guides/uet-conversion-api-integration#hashed-identifiers\n */\nexport function normalizeEmail(input: string): string {\n const email = input.trim().toLowerCase();\n const at = email.lastIndexOf('@');\n if (at === -1) return email;\n const user = email.slice(0, at).replace(/\\./g, '').split('+', 1)[0] ?? '';\n return `${user}@${email.slice(at + 1)}`;\n}\n\nfunction hashEmail(input: string | undefined): string | undefined {\n const value = input?.trim().toLowerCase();\n if (!value) return undefined;\n return SHA256.test(value) ? value : sha256(normalizeEmail(value));\n}\n\n/**\n * Phones are E.164 by the schema (`+` then 11–15 digits, the range bat.js validates too); the\n * separators bat.js tolerates are stripped, and anything else is dropped rather than guessed —\n * a number with no country code hashed under an assumed one can never match.\n */\nfunction hashPhone(input: string | undefined): string | undefined {\n const value = input?.trim().toLowerCase();\n if (!value) return undefined;\n if (SHA256.test(value)) return value;\n const phone = value.replace(/[-() \\t]/g, '');\n return /^\\+\\d{11,15}$/.test(phone) ? sha256(phone) : undefined;\n}\n\nexport interface MicrosoftUserData {\n /** Microsoft click id, as a dashed UUID. */\n msclkid?: string;\n /** SHA-256 of the normalized email. */\n em?: string;\n /** SHA-256 of the E.164 phone number. */\n ph?: string;\n /** The SDK visitor id — what the client-side ID Sync pixel (`sendUETIdSync`) sends as `VID`. */\n anonymousId?: string;\n /** SHA-256 of the signed-in user id — what `sendUETIdSync` sends as `UID`. */\n externalId?: string;\n clientUserAgent?: string;\n clientIpAddress?: string;\n idfa?: string;\n gaid?: string;\n}\n\nexport interface MicrosoftItem {\n id?: string;\n name?: string;\n price?: number;\n quantity?: number;\n}\n\nexport interface MicrosoftCustomData {\n eventCategory?: string;\n eventLabel?: string;\n eventValue?: number;\n searchTerm?: string;\n transactionId?: string;\n value?: number;\n currency?: string;\n items?: MicrosoftItem[];\n itemIds?: string[];\n pageType?: string;\n ecommTotalValue?: number;\n ecommCategory?: string;\n}\n\n/** One entry of the `data` array POSTed to `/v1/{tagId}/events`. */\nexport interface MicrosoftEvent {\n eventType: 'custom' | 'pageLoad';\n eventId: string;\n /** The UET action; absent on `pageLoad` events. */\n eventName?: string;\n /** UNIX seconds, UTC; the API rejects anything older than 7 days. */\n eventTime: number;\n eventSourceUrl?: string;\n /** Links a `custom` event to its `pageLoad` event; a v4 UUID (the SDK's `page_load_id` tag). */\n pageLoadId?: string;\n referrerUrl?: string;\n pageTitle?: string;\n /** `G` granted, `D` denied. Absent means granted. */\n adStorageConsent?: 'G' | 'D';\n userData: MicrosoftUserData;\n customData?: MicrosoftCustomData;\n}\n\nexport interface MicrosoftConversionsOptions {\n /**\n * EEA/UK/CH consent for the whole batch. `denied` events are accepted but used for nothing —\n * no attribution, no audiences. Absent means granted, which is also the API's default.\n */\n consent?: 'granted' | 'denied';\n /**\n * Also send `page_view` events, as CAPI `pageLoad` events, and link every custom event to the\n * page load it happened on (`pageLoadId`, from the `page_load_id` tag). Off by default because\n * the UET JavaScript already reports every page load and the two would double-count\n * destination-URL goals; turn it on for a CAPI-only site with no tag on the page. Off, no\n * `pageLoadId` is sent either: it would point at a page load Microsoft only saw from the tag,\n * under the tag's own id.\n *\n * Not yet modelled: the revenue-only custom event a `pageLoad` needs for a destination goal\n * with variable revenue.\n */\n pageLoads?: boolean;\n /** Identifies a third-party sender in Microsoft's monitoring; leave unset for a first-party build. */\n dataProvider?: string;\n /**\n * Process the valid events of a batch and report the invalid ones, instead of the API's default\n * all-or-nothing rejection. On by default — one malformed event should cost itself, not the\n * batch it travelled with.\n */\n continueOnValidationError?: boolean;\n}\n\nexport interface MicrosoftValidationDetail {\n index?: number;\n propertyName?: string;\n attemptedValue?: unknown;\n errorMessage?: string;\n errorCode?: string;\n isWarning?: boolean;\n}\n\nexport interface MicrosoftConversionsResponse {\n eventsReceived?: number;\n error?: { code?: string; message?: string; details?: MicrosoftValidationDetail[] };\n}\n\nfunction getUserData(\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n event: TrackEvent<any>,\n data: UserProvidedData\n): MicrosoftUserData {\n const { tags, platform, visitor_id } = event;\n const email = Array.isArray(data.email) ? data.email[0] : data.email;\n const phone = Array.isArray(data.phone_number) ? data.phone_number[0] : data.phone_number;\n const msclkid = microsoftMsclkid(tags);\n\n return {\n msclkid: msclkid ? formatMsclkid(msclkid) : undefined,\n em: hashEmail(email),\n ph: hashPhone(phone),\n // Microsoft requires this to equal the `VID` of the client-side ID Sync pixel; both sides use\n // the SDK visitor id, which every event carries and the client can always read.\n anonymousId: visitor_id || undefined,\n // Microsoft asks for an anonymized id and never a real one. SHA-256, the same digest\n // `sendUETIdSync` applies client-side, so `externalId` and the pixel's `UID` agree too.\n externalId: data.user_id ? sha256(data.user_id) : undefined,\n clientUserAgent: data.user_agent,\n clientIpAddress:\n typeof tags.ip_address === 'string' && tags.ip_address ? tags.ip_address : data.ip_address,\n idfa: platform === 'ios' ? tags.advertising_id : undefined,\n gaid: platform === 'android' ? tags.advertising_id : undefined,\n };\n}\n\n// oxlint-disable-next-line @typescript-eslint/no-explicit-any\nfunction getCustomData(event: TrackEvent<any>): MicrosoftCustomData | undefined {\n const [, params] = mapUETEvent(event.name, event.properties);\n const customData: MicrosoftCustomData = {\n eventCategory: params.event_category,\n eventLabel: params.event_label,\n eventValue: params.event_value,\n searchTerm: params.search_term,\n transactionId: params.transaction_id,\n value: params.revenue_value,\n currency: params.currency,\n items: params.items?.map(({ id, name, price, quantity }) => ({ id, name, price, quantity })),\n itemIds: Array.isArray(params.ecomm_prodid)\n ? params.ecomm_prodid\n : params.ecomm_prodid\n ? [params.ecomm_prodid]\n : undefined,\n pageType: params.ecomm_pagetype,\n ecommTotalValue: params.ecomm_totalvalue,\n ecommCategory: params.ecomm_category,\n };\n return Object.values(customData).some((value) => value !== undefined) ? customData : undefined;\n}\n\n/**\n * Build one CAPI event. `page_view` becomes a `pageLoad` event (the caller decides whether to\n * send those, see `MicrosoftConversionsOptions.pageLoads`); everything else is a `custom` event\n * named after the track event, which is also the UET action the browser sent.\n */\nexport type MicrosoftEventOptions = Pick<MicrosoftConversionsOptions, 'consent' | 'pageLoads'>;\n\nexport function getServerEvent(\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n event: TrackEvent<any>,\n data: UserProvidedData = {},\n /** Options, or — the 8.3.0 signature, still accepted — the bare consent value. */\n options: MicrosoftEventOptions | MicrosoftEventOptions['consent'] = {}\n): MicrosoftEvent {\n const { consent, pageLoads = false } =\n typeof options === 'string' ? { consent: options } : options;\n const { id, name, tags, created_at } = event;\n const isPageLoad = name === 'page_view';\n\n return {\n eventType: isPageLoad ? 'pageLoad' : 'custom',\n eventId: tags.idempotency_key ?? id,\n eventName: isPageLoad ? undefined : name,\n eventTime: Math.round(new Date(created_at).getTime() / 1000),\n eventSourceUrl: pageLocation(tags),\n pageLoadId: pageLoads ? tags.page_load_id : undefined,\n referrerUrl: tags.page_referrer,\n pageTitle: tags.page_title,\n adStorageConsent: consent === 'granted' ? 'G' : consent === 'denied' ? 'D' : undefined,\n userData: getUserData(event, data),\n customData: isPageLoad ? undefined : getCustomData(event),\n };\n}\n\n/** Strip undefined fields so the wire payload carries only what was set. */\nfunction compact<T>(value: T): T {\n return JSON.parse(JSON.stringify(value)) as T;\n}\n\n/** `eventTime` must be \"within the last 7 days\"; a minute's margin for the trip. */\nconst MAX_EVENT_AGE_MS = 7 * 24 * 60 * 60 * 1000 - 60 * 1000;\n\n/**\n * Send events to `POST /v1/{tagId}/events`. Batches above the API's 1,000-event limit are split\n * into consecutive requests; one response is returned per request made. The first failed request\n * rejects — a `ConversionsApiError`, or the fetch error, neither carrying the token — and sends\n * no further ones.\n */\nexport async function sendEvents(\n token: string,\n tagId: string | number,\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n events: TrackEvent<any>[],\n data: UserProvidedData = {},\n options: MicrosoftConversionsOptions = {}\n): Promise<MicrosoftConversionsResponse[]> {\n const { consent, pageLoads = false, dataProvider, continueOnValidationError = true } = options;\n\n const capiEvents = events\n .filter(\n (event) => (pageLoads && event.name === 'page_view') || !IGNORED_EVENTS.includes(event.name)\n )\n .filter((event) => Date.now() - Date.parse(event.created_at) <= MAX_EVENT_AGE_MS)\n .map((event) => getServerEvent(event, data, { consent, pageLoads }))\n // A pageLoad without a URL is rejected by the API, and a page-less event has nothing to say.\n .filter((event) => event.eventType !== 'pageLoad' || event.eventSourceUrl);\n if (capiEvents.length === 0) return [];\n\n const responses: MicrosoftConversionsResponse[] = [];\n for (const batch of chunk(capiEvents, MAX_EVENTS_PER_REQUEST)) {\n const body = compact({ data: batch, continueOnValidationError, dataProvider });\n const response = await fetch(`${ENDPOINT}/${tagId}/events`, {\n method: 'POST',\n // Retried although a POST: the platform deduplicates on the `eventId` each event carries.\n retries: 3,\n headers: {\n 'Content-Type': 'application/json',\n Accept: 'application/json',\n Authorization: `Bearer ${token}`,\n },\n body: JSON.stringify(body),\n });\n // The first failed request ends the batch: sending it again sends every request again, and\n // the platform deduplicates the ones that had gone through.\n if (!response.ok) {\n throw new ConversionsApiError('microsoft', response.status, await response.text());\n }\n const result = (await response.json()) as MicrosoftConversionsResponse;\n // A 200 can still carry field-level warnings (the field was removed) and, with\n // `continueOnValidationError`, skipped events. Surface them: silent partial data loss is the\n // one failure mode the caller cannot see from the status code.\n if (result.error?.details?.length) {\n console.warn(\n `Microsoft conversion accepted with validation issues: ${JSON.stringify(result.error.details)}`\n );\n }\n responses.push(result);\n }\n return responses;\n}\n\n/**\n * Microsoft's Conversions API, sent the same events as `microsoftAds` (`events`, the GA4\n * conversion events by default, and `customEvents`) — and `page_view` too with `pageLoads`, for\n * a site with no UET tag on the page. `consent` is the API's batch-level consent here, not the\n * tag's consent mode default.\n */\nexport function microsoftConversions(\n options: Omit<MicrosoftAdsOptions, 'consent' | 'customerId'> &\n MicrosoftConversionsOptions & { accessToken: string }\n): ConversionDestination {\n const accepts = uetEvents(options);\n return conversionDestination(\n (name) => accepts(name) || (options.pageLoads === true && name === 'page_view'),\n (events, data) => sendEvents(options.accessToken, options.tagId, events, data, options)\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6BA,MAAM,WAAW;;AAGjB,MAAM,yBAAyB;AAE/B,MAAM,SAAS;AAEf,MAAM,UAAU,UAAkB,WAAW,QAAQ,CAAC,CAAC,OAAO,KAAK,CAAC,CAAC,OAAO,KAAK;;;;;;;AAQjF,SAAgB,eAAe,OAAuB;CACpD,MAAM,QAAQ,MAAM,KAAK,CAAC,CAAC,YAAY;CACvC,MAAM,KAAK,MAAM,YAAY,GAAG;CAChC,IAAI,OAAO,IAAI,OAAO;CAEtB,OAAO,GADM,MAAM,MAAM,GAAG,EAAE,CAAC,CAAC,QAAQ,OAAO,EAAE,CAAC,CAAC,MAAM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WAAW,QAAQ,aAAa,QAAQ,OAAO,QAAQ,MAAM,OAAO,CACxF;AACF"}
@@ -1,7 +1,10 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
2
  const require_third_parties_ignored_events = require("../third-parties/ignored-events.cjs");
3
+ const require_third_parties_integration = require("../third-parties/integration.cjs");
3
4
  const require_server_action_source = require("./action-source.cjs");
4
5
  const require_server_click_ids = require("./click-ids.cjs");
6
+ const require_server_conversions_api_error = require("./conversions-api-error.cjs");
7
+ const require_server_setup_conversions = require("./setup-conversions.cjs");
5
8
  const require_server_page_location = require("./page-location.cjs");
6
9
  const require_track_oaiq = require("../track/oaiq.cjs");
7
10
  let _shware_utils = require("@shware/utils");
@@ -81,26 +84,25 @@ async function sendEvents(apiKey, pixelId, events, data = {}, validateOnly = fal
81
84
  }).map((event) => getServerEvent(event, data, actionSource)).filter((event) => event.type !== "custom" || event.custom_event_name !== void 0).filter((event) => !require_track_oaiq.APP_EVENTS.includes(event.type) || event.action_source === "mobile_app")
82
85
  };
83
86
  if (dto.events.length === 0) return;
84
- try {
85
- const response = await (0, _shware_utils.fetch)(`${ENDPOINT}?pid=${pixelId}`, {
86
- method: "POST",
87
- retries: 3,
88
- headers: {
89
- "Content-Type": "application/json",
90
- Accept: "application/json",
91
- Authorization: `Bearer ${apiKey}`
92
- },
93
- body: JSON.stringify(dto)
94
- });
95
- if (response.ok) return;
96
- const { status } = response;
97
- const message = await response.text();
98
- console.error(`Failed to send OpenAI conversion, status: ${status}, body: ${message}`);
99
- } catch (error) {
100
- console.error("Failed to send OpenAI conversion, network error:", error);
101
- }
87
+ const response = await (0, _shware_utils.fetch)(`${ENDPOINT}?pid=${pixelId}`, {
88
+ method: "POST",
89
+ retries: 3,
90
+ headers: {
91
+ "Content-Type": "application/json",
92
+ Accept: "application/json",
93
+ Authorization: `Bearer ${apiKey}`
94
+ },
95
+ body: JSON.stringify(dto)
96
+ });
97
+ if (response.ok) return;
98
+ throw new require_server_conversions_api_error.ConversionsApiError("openai", response.status, await response.text());
99
+ }
100
+ /** OpenAI's Conversions API, sent the same events as `openaiAds`. */
101
+ function openaiConversions(options) {
102
+ return require_server_setup_conversions.conversionDestination(require_third_parties_integration.adEvents(require_track_oaiq.isStandardOAIEvent, options.customEvents), (events, data) => sendEvents(options.accessToken, options.pixelId, events, data, options.validateOnly));
102
103
  }
103
104
  exports.getServerEvent = getServerEvent;
105
+ exports.openaiConversions = openaiConversions;
104
106
  exports.sendEvents = sendEvents;
105
107
 
106
108
  //# sourceMappingURL=openai-conversions-api.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"openai-conversions-api.cjs","names":["createHash","resolveActionSource","normalizeOAIPhone","normalizeOAIName","mapOAIEvent","oaiCustomEventName","pageLocation","openaiOppref","IGNORED_EVENTS","NON_AD_EVENTS","APP_EVENTS","fetch"],"sources":["../../src/server/openai-conversions-api.ts"],"sourcesContent":["/**\n * OpenAI Conversions API\n * https://developers.openai.com/ads/conversions-api\n * https://developers.openai.com/ads/supported-events\n */\nimport { createHash } from 'node:crypto';\nimport { fetch } from '@shware/utils';\nimport { IGNORED_EVENTS } from '../third-parties/ignored-events';\nimport {\n APP_EVENTS,\n type EventData,\n NON_AD_EVENTS,\n mapOAIEvent,\n normalizeOAIName,\n normalizeOAIPhone,\n oaiCustomEventName,\n} from '../track/oaiq';\nimport type { Platform, TrackEvent, UserProvidedData } from '../track/types';\nimport { type EventActionSource, resolveActionSource } from './action-source';\nimport { openaiOppref } from './click-ids';\nimport { pageLocation } from './page-location';\n\nconst ENDPOINT = 'https://bzr.openai.com/v1/events';\n\ntype ActionSource =\n | 'web'\n | 'mobile_app'\n | 'offline'\n | 'physical_store'\n | 'phone_call'\n | 'email'\n | 'other';\n\n/**\n * Conversion-matching fields, all optional. Identifiers are normalized, then sent as lowercase\n * 64-char SHA-256 hex strings; geographic values are raw. Of each list the API uses the first\n * three valid, unique values.\n * ref: https://developers.openai.com/ads/conversions-api#send-user-data\n */\nexport interface OpenAIUser {\n /** The pixel's `__obref` cookie, unhashed; ties the server event to the pixel's browser. */\n obref?: string;\n emails_sha256?: string[];\n /** 8–15 digits with the country code, no leading `+` or zeroes. */\n phone_numbers_sha256?: string[];\n external_ids_sha256?: string[];\n first_names_sha256?: string[];\n last_names_sha256?: string[];\n regions?: string[];\n postal_codes?: string[];\n cities?: string[];\n /** Two-letter ISO 3166-1 country codes (e.g. \"US\"). */\n countries?: string[];\n /** Android GAID only; IDFA is not supported. */\n android_advertising_id?: string;\n ip_address?: string;\n user_agent?: string;\n}\n\nexport interface OpenAIEvent {\n /** Unique event id; combined with `type` for deduplication against pixel events. */\n id: string;\n /** Standard event name or `custom`. */\n type: string;\n /** Required when `type` is `custom`. */\n custom_event_name?: string;\n /** Event timestamp in ms; must be within 7 days and no more than 10 minutes in the future. */\n timestamp_ms: number;\n /** Required for `action_source: \"web\"`. */\n source_url?: string;\n action_source?: ActionSource;\n /** OpenAI-provided privacy-preserving identifier. */\n oppref?: string;\n /** When true, opts the event out of personalization. */\n opt_out?: boolean;\n user?: OpenAIUser;\n data: EventData;\n}\n\nexport interface CreateOpenAIEventsDTO {\n /** When true, validates the events without persisting them. */\n validate_only?: boolean;\n events: OpenAIEvent[];\n}\n\nfunction sha256(value: string): string {\n return createHash('sha256').update(value).digest('hex');\n}\n\nfunction mapActionSource(\n platform: Platform,\n actionSource?: EventActionSource\n): ActionSource | undefined {\n switch (resolveActionSource(platform, actionSource)) {\n case 'web':\n return 'web';\n case 'app':\n return 'mobile_app';\n case 'offline':\n return 'offline';\n default:\n return undefined;\n }\n}\n\nfunction list<T>(field: T | T[] | undefined): T[] {\n if (!field) return [];\n return Array.isArray(field) ? field : [field];\n}\n\n/** The distinct non-empty values, or undefined when there are none. */\nfunction values(items: (string | undefined)[]): string[] | undefined {\n const result = [...new Set(items.filter((item): item is string => !!item))];\n return result.length > 0 ? result : undefined;\n}\n\nfunction getUser(\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n event: TrackEvent<any>,\n data: UserProvidedData\n): OpenAIUser | undefined {\n const hashed = (items: (string | undefined)[]) => values(items)?.map(sha256);\n const addresses = list(data.address);\n\n const user: OpenAIUser = {\n obref: event.tags.__obref,\n emails_sha256: hashed(list(data.email).map((email) => email.trim().toLowerCase())),\n phone_numbers_sha256: hashed(list(data.phone_number).map(normalizeOAIPhone)),\n external_ids_sha256: hashed([data.user_id?.trim()]),\n first_names_sha256: hashed(addresses.map((a) => normalizeOAIName(a.first_name))),\n last_names_sha256: hashed(addresses.map((a) => normalizeOAIName(a.last_name))),\n regions: values(addresses.map((a) => a.region?.trim())),\n postal_codes: values(addresses.map((a) => a.postal_code?.trim())),\n cities: values(addresses.map((a) => a.city?.trim())),\n countries: values(addresses.map((a) => a.country?.trim().toUpperCase())),\n android_advertising_id:\n event.platform === 'android' ? event.tags.advertising_id || undefined : undefined,\n ip_address: data.ip_address,\n user_agent: data.user_agent,\n };\n\n return Object.values(user).some((value) => value !== undefined) ? user : undefined;\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): OpenAIEvent {\n const { type, data: eventData } = mapOAIEvent(event.name, event.properties);\n\n return {\n id: event.tags.idempotency_key ?? event.id,\n type,\n // For custom events the track name, made valid (`oaiCustomEventName`); the browser pixel\n // names it the same way, so the two deduplicate. Standard events omit it.\n custom_event_name: type === 'custom' ? oaiCustomEventName(event.name) : undefined,\n timestamp_ms: new Date(event.created_at).getTime(),\n source_url: pageLocation(event.tags),\n // The click id OpenAI appends to an ad's landing URL; what ties the conversion to the click.\n oppref: openaiOppref(event.tags),\n action_source: mapActionSource(event.platform, actionSource),\n user: getUser(event, data),\n data: eventData,\n };\n}\n\n/**\n * `timestamp_ms` \"must be within the last 7 days and no more than 10 minutes in the future\", or\n * the request fails; such an event is left out, with a minute's margin for the trip.\n */\nconst MAX_EVENT_AGE_MS = 7 * 24 * 60 * 60 * 1000 - 60 * 1000;\nconst MAX_EVENT_AHEAD_MS = 10 * 60 * 1000;\n\nexport async function sendEvents(\n apiKey: string,\n pixelId: string,\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n events: TrackEvent<any>[],\n data: UserProvidedData = {},\n validateOnly = false,\n actionSource?: EventActionSource\n) {\n const dto: CreateOpenAIEventsDTO = {\n validate_only: validateOnly,\n events: events\n // `first_open` is the install: left out of what GA collects itself, not of what OpenAI takes.\n .filter((event) => event.name === 'first_open' || !IGNORED_EVENTS.includes(event.name))\n .filter((event) => !NON_AD_EVENTS.includes(event.name))\n .filter((event) => {\n const age = Date.now() - Date.parse(event.created_at);\n return age <= MAX_EVENT_AGE_MS && age >= -MAX_EVENT_AHEAD_MS;\n })\n .map((event) => getServerEvent(event, data, actionSource))\n // A custom event whose name cannot be made valid would fail the whole request.\n .filter((event) => event.type !== 'custom' || event.custom_event_name !== undefined)\n // The app events count only from an app: OpenAI takes them with `mobile_app` alone.\n .filter(\n (event) => !APP_EVENTS.includes(event.type as never) || event.action_source === 'mobile_app'\n ),\n };\n\n if (dto.events.length === 0) return;\n\n try {\n const response = await fetch(`${ENDPOINT}?pid=${pixelId}`, {\n method: 'POST',\n // Retried although a POST: the platform deduplicates on the `event_id` each event carries.\n retries: 3,\n headers: {\n 'Content-Type': 'application/json',\n Accept: 'application/json',\n Authorization: `Bearer ${apiKey}`,\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 OpenAI conversion, status: ${status}, body: ${message}`);\n } catch (error) {\n console.error('Failed to send OpenAI conversion, network error:', error);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;AAsBA,MAAM,WAAW;AA+DjB,SAAS,OAAO,OAAuB;CACrC,QAAA,GAAOA,YAAAA,WAAAA,CAAW,QAAQ,CAAC,CAAC,OAAO,KAAK,CAAC,CAAC,OAAO,KAAK;AACxD;AAEA,SAAS,gBACP,UACA,cAC0B;CAC1B,QAAQC,6BAA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AY,MAAM,sBAAsB,KAAA,CAAS,CAAC,CAEnF,QACE,UAAU,CAACC,mBAAAA,WAAW,SAAS,MAAM,IAAa,KAAK,MAAM,kBAAkB,YAClF;CACJ;CAEA,IAAI,IAAI,OAAO,WAAW,GAAG;CAE7B,IAAI;EACF,MAAM,WAAW,OAAA,GAAMC,cAAAA,MAAAA,CAAM,GAAG,SAAS,OAAO,WAAW;GACzD,QAAQ;GAER,SAAS;GACT,SAAS;IACP,gBAAgB;IAChB,QAAQ;IACR,eAAe,UAAU;GAC3B;GACA,MAAM,KAAK,UAAU,GAAG;EAC1B,CAAC;EAED,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":"openai-conversions-api.cjs","names":["createHash","resolveActionSource","normalizeOAIPhone","normalizeOAIName","mapOAIEvent","oaiCustomEventName","pageLocation","openaiOppref","IGNORED_EVENTS","NON_AD_EVENTS","APP_EVENTS","fetch","ConversionsApiError","conversionDestination","adEvents","isStandardOAIEvent"],"sources":["../../src/server/openai-conversions-api.ts"],"sourcesContent":["/**\n * OpenAI Conversions API\n * https://developers.openai.com/ads/conversions-api\n * https://developers.openai.com/ads/supported-events\n */\nimport { createHash } from 'node:crypto';\nimport { fetch } from '@shware/utils';\nimport { IGNORED_EVENTS } from '../third-parties/ignored-events';\nimport { adEvents } from '../third-parties/integration';\nimport type { OpenAIAdsOptions } from '../third-parties/openai-pixel';\nimport {\n APP_EVENTS,\n type EventData,\n NON_AD_EVENTS,\n isStandardOAIEvent,\n mapOAIEvent,\n normalizeOAIName,\n normalizeOAIPhone,\n oaiCustomEventName,\n} from '../track/oaiq';\nimport type { Platform, TrackEvent, UserProvidedData } from '../track/types';\nimport { type EventActionSource, resolveActionSource } from './action-source';\nimport { openaiOppref } from './click-ids';\nimport { ConversionsApiError } from './conversions-api-error';\nimport { pageLocation } from './page-location';\nimport { type ConversionDestination, conversionDestination } from './setup-conversions';\n\nconst ENDPOINT = 'https://bzr.openai.com/v1/events';\n\ntype ActionSource =\n | 'web'\n | 'mobile_app'\n | 'offline'\n | 'physical_store'\n | 'phone_call'\n | 'email'\n | 'other';\n\n/**\n * Conversion-matching fields, all optional. Identifiers are normalized, then sent as lowercase\n * 64-char SHA-256 hex strings; geographic values are raw. Of each list the API uses the first\n * three valid, unique values.\n * ref: https://developers.openai.com/ads/conversions-api#send-user-data\n */\nexport interface OpenAIUser {\n /** The pixel's `__obref` cookie, unhashed; ties the server event to the pixel's browser. */\n obref?: string;\n emails_sha256?: string[];\n /** 8–15 digits with the country code, no leading `+` or zeroes. */\n phone_numbers_sha256?: string[];\n external_ids_sha256?: string[];\n first_names_sha256?: string[];\n last_names_sha256?: string[];\n regions?: string[];\n postal_codes?: string[];\n cities?: string[];\n /** Two-letter ISO 3166-1 country codes (e.g. \"US\"). */\n countries?: string[];\n /** Android GAID only; IDFA is not supported. */\n android_advertising_id?: string;\n ip_address?: string;\n user_agent?: string;\n}\n\nexport interface OpenAIEvent {\n /** Unique event id; combined with `type` for deduplication against pixel events. */\n id: string;\n /** Standard event name or `custom`. */\n type: string;\n /** Required when `type` is `custom`. */\n custom_event_name?: string;\n /** Event timestamp in ms; must be within 7 days and no more than 10 minutes in the future. */\n timestamp_ms: number;\n /** Required for `action_source: \"web\"`. */\n source_url?: string;\n action_source?: ActionSource;\n /** OpenAI-provided privacy-preserving identifier. */\n oppref?: string;\n /** When true, opts the event out of personalization. */\n opt_out?: boolean;\n user?: OpenAIUser;\n data: EventData;\n}\n\nexport interface CreateOpenAIEventsDTO {\n /** When true, validates the events without persisting them. */\n validate_only?: boolean;\n events: OpenAIEvent[];\n}\n\nfunction sha256(value: string): string {\n return createHash('sha256').update(value).digest('hex');\n}\n\nfunction mapActionSource(\n platform: Platform,\n actionSource?: EventActionSource\n): ActionSource | undefined {\n switch (resolveActionSource(platform, actionSource)) {\n case 'web':\n return 'web';\n case 'app':\n return 'mobile_app';\n case 'offline':\n return 'offline';\n default:\n return undefined;\n }\n}\n\nfunction list<T>(field: T | T[] | undefined): T[] {\n if (!field) return [];\n return Array.isArray(field) ? field : [field];\n}\n\n/** The distinct non-empty values, or undefined when there are none. */\nfunction values(items: (string | undefined)[]): string[] | undefined {\n const result = [...new Set(items.filter((item): item is string => !!item))];\n return result.length > 0 ? result : undefined;\n}\n\nfunction getUser(\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n event: TrackEvent<any>,\n data: UserProvidedData\n): OpenAIUser | undefined {\n const hashed = (items: (string | undefined)[]) => values(items)?.map(sha256);\n const addresses = list(data.address);\n\n const user: OpenAIUser = {\n obref: event.tags.__obref,\n emails_sha256: hashed(list(data.email).map((email) => email.trim().toLowerCase())),\n phone_numbers_sha256: hashed(list(data.phone_number).map(normalizeOAIPhone)),\n external_ids_sha256: hashed([data.user_id?.trim()]),\n first_names_sha256: hashed(addresses.map((a) => normalizeOAIName(a.first_name))),\n last_names_sha256: hashed(addresses.map((a) => normalizeOAIName(a.last_name))),\n regions: values(addresses.map((a) => a.region?.trim())),\n postal_codes: values(addresses.map((a) => a.postal_code?.trim())),\n cities: values(addresses.map((a) => a.city?.trim())),\n countries: values(addresses.map((a) => a.country?.trim().toUpperCase())),\n android_advertising_id:\n event.platform === 'android' ? event.tags.advertising_id || undefined : undefined,\n ip_address: data.ip_address,\n user_agent: data.user_agent,\n };\n\n return Object.values(user).some((value) => value !== undefined) ? user : undefined;\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): OpenAIEvent {\n const { type, data: eventData } = mapOAIEvent(event.name, event.properties);\n\n return {\n id: event.tags.idempotency_key ?? event.id,\n type,\n // For custom events the track name, made valid (`oaiCustomEventName`); the browser pixel\n // names it the same way, so the two deduplicate. Standard events omit it.\n custom_event_name: type === 'custom' ? oaiCustomEventName(event.name) : undefined,\n timestamp_ms: new Date(event.created_at).getTime(),\n source_url: pageLocation(event.tags),\n // The click id OpenAI appends to an ad's landing URL; what ties the conversion to the click.\n oppref: openaiOppref(event.tags),\n action_source: mapActionSource(event.platform, actionSource),\n user: getUser(event, data),\n data: eventData,\n };\n}\n\n/**\n * `timestamp_ms` \"must be within the last 7 days and no more than 10 minutes in the future\", or\n * the request fails; such an event is left out, with a minute's margin for the trip.\n */\nconst MAX_EVENT_AGE_MS = 7 * 24 * 60 * 60 * 1000 - 60 * 1000;\nconst MAX_EVENT_AHEAD_MS = 10 * 60 * 1000;\n\nexport async function sendEvents(\n apiKey: string,\n pixelId: string,\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n events: TrackEvent<any>[],\n data: UserProvidedData = {},\n validateOnly = false,\n actionSource?: EventActionSource\n) {\n const dto: CreateOpenAIEventsDTO = {\n validate_only: validateOnly,\n events: events\n // `first_open` is the install: left out of what GA collects itself, not of what OpenAI takes.\n .filter((event) => event.name === 'first_open' || !IGNORED_EVENTS.includes(event.name))\n .filter((event) => !NON_AD_EVENTS.includes(event.name))\n .filter((event) => {\n const age = Date.now() - Date.parse(event.created_at);\n return age <= MAX_EVENT_AGE_MS && age >= -MAX_EVENT_AHEAD_MS;\n })\n .map((event) => getServerEvent(event, data, actionSource))\n // A custom event whose name cannot be made valid would fail the whole request.\n .filter((event) => event.type !== 'custom' || event.custom_event_name !== undefined)\n // The app events count only from an app: OpenAI takes them with `mobile_app` alone.\n .filter(\n (event) => !APP_EVENTS.includes(event.type as never) || event.action_source === 'mobile_app'\n ),\n };\n\n if (dto.events.length === 0) return;\n\n const response = await fetch(`${ENDPOINT}?pid=${pixelId}`, {\n method: 'POST',\n // Retried although a POST: the platform deduplicates on the `event_id` each event carries.\n retries: 3,\n headers: {\n 'Content-Type': 'application/json',\n Accept: 'application/json',\n Authorization: `Bearer ${apiKey}`,\n },\n body: JSON.stringify(dto),\n });\n\n if (response.ok) return;\n throw new ConversionsApiError('openai', response.status, await response.text());\n}\n\n/** OpenAI's Conversions API, sent the same events as `openaiAds`. */\nexport function openaiConversions(\n options: OpenAIAdsOptions & { accessToken: string; validateOnly?: boolean }\n): ConversionDestination {\n return conversionDestination(adEvents(isStandardOAIEvent, options.customEvents), (events, data) =>\n sendEvents(options.accessToken, options.pixelId, events, data, options.validateOnly)\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AA2BA,MAAM,WAAW;AA+DjB,SAAS,OAAO,OAAuB;CACrC,QAAA,GAAOA,YAAAA,WAAAA,CAAW,QAAQ,CAAC,CAAC,OAAO,KAAK,CAAC,CAAC,OAAO,KAAK;AACxD;AAEA,SAAS,gBACP,UACA,cAC0B;CAC1B,QAAQC,6BAAAA,oBAAoB,UAAU,YAAY,GAAlD;EACE,KAAK,OACH,OAAO;EACT,KAAK,OACH,OAAO;EACT,KAAK,WACH,OAAO;EACT,SACE;CACJ;AACF;AAEA,SAAS,KAAQ,OAAiC;CAChD,IAAI,CAAC,OAAO,OAAO,CAAC;CACpB,OAAO,MAAM,QAAQ,KAAK,IAAI,QAAQ,CAAC,KAAK;AAC9C;;AAGA,SAAS,OAAO,OAAqD;CACnE,MAAM,SAAS,CAAC,GAAG,IAAI,IAAI,MAAM,QAAQ,SAAyB,CAAC,CAAC,IAAI,CAAC,CAAC;CAC1E,OAAO,OAAO,SAAS,IAAI,SAAS,KAAA;AACtC;AAEA,SAAS,QAEP,OACA,MACwB;CACxB,MAAM,UAAU,UAAkC,OAAO,KAAK,CAAC,EAAE,IAAI,MAAM;CAC3E,MAAM,YAAY,KAAK,KAAK,OAAO;CAEnC,MAAM,OAAmB;EACvB,OAAO,MAAM,KAAK;EAClB,eAAe,OAAO,KAAK,KAAK,KAAK,CAAC,CAAC,KAAK,UAAU,MAAM,KAAK,CAAC,CAAC,YAAY,CAAC,CAAC;EACjF,sBAAsB,OAAO,KAAK,KAAK,YAAY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js";
2
2
  import { EventActionSource } from "./action-source.cjs";
3
+ import { ConversionDestination } from "./setup-conversions.cjs";
3
4
  import { EventData } from "../track/oaiq.cjs";
5
+ import { OpenAIAdsOptions } from "../third-parties/openai-pixel.cjs";
4
6
  type ActionSource = 'web' | 'mobile_app' | 'offline' | 'physical_store' | 'phone_call' | 'email' | 'other';
5
7
  /**
6
8
  * Conversion-matching fields, all optional. Identifiers are normalized, then sent as lowercase
@@ -53,5 +55,10 @@ export interface CreateOpenAIEventsDTO {
53
55
  }
54
56
  export declare function getServerEvent(event: TrackEvent<any>, data: UserProvidedData, actionSource?: EventActionSource): OpenAIEvent;
55
57
  export declare function sendEvents(apiKey: string, pixelId: string, events: TrackEvent<any>[], data?: UserProvidedData, validateOnly?: boolean, actionSource?: EventActionSource): Promise<void>;
58
+ /** OpenAI's Conversions API, sent the same events as `openaiAds`. */
59
+ export declare function openaiConversions(options: OpenAIAdsOptions & {
60
+ accessToken: string;
61
+ validateOnly?: boolean;
62
+ }): ConversionDestination;
56
63
  export {};
57
64
  //# sourceMappingURL=openai-conversions-api.d.cts.map
@@ -1 +1 @@
1
- {"version":3,"file":"openai-conversions-api.d.cts","names":[],"sources":["../../src/server/openai-conversions-api.ts"],"mappings":";;;KAwBK;;;;;;;iBAeY;;EAEf;EACA;;EAEA;EACA;EACA;EACA;EACA;EACA;EACA;;EAEA;;EAEA;EACA;EACA;;iBAGe;;EAEf;;EAEA;;EAEA;;EAEA;;EAEA;EACA,gBAAgB;;EAEhB;;EAEA;EACA,OAAO;EACP,MAAM;;iBAGS;;EAEf;EACA,QAAQ;;wBA8DM,eAEd,OAAO,iBACP,MAAM,kBACN,eAAe,oBACd;wBA0BmB,WACpB,gBACA,iBAEA,QAAQ,mBACR,OAAM,kBACN,wBACA,eAAe,oBAAiB"}
1
+ {"version":3,"file":"openai-conversions-api.d.cts","names":[],"sources":["../../src/server/openai-conversions-api.ts"],"mappings":";;;;;KA6BK;;;;;;;iBAeY;;EAEf;EACA;;EAEA;EACA;EACA;EACA;EACA;EACA;EACA;;EAEA;;EAEA;EACA;EACA;;iBAGe;;EAEf;;EAEA;;EAEA;;EAEA;;EAEA;EACA,gBAAgB;;EAEhB;;EAEA;EACA,OAAO;EACP,MAAM;;iBAGS;;EAEf;EACA,QAAQ;;wBA8DM,eAEd,OAAO,iBACP,MAAM,kBACN,eAAe,oBACd;wBA0BmB,WACpB,gBACA,iBAEA,QAAQ,mBACR,OAAM,kBACN,wBACA,eAAe,oBAAiB;;wBAwClB,kBACd,SAAS;EAAqB;EAAqB;IAClD"}
@@ -1,6 +1,8 @@
1
1
  import { TrackEvent, UserProvidedData } from "../track/types.mjs";
2
2
  import { EventActionSource } from "./action-source.mjs";
3
+ import { ConversionDestination } from "./setup-conversions.mjs";
3
4
  import { EventData } from "../track/oaiq.mjs";
5
+ import { OpenAIAdsOptions } from "../third-parties/openai-pixel.mjs";
4
6
  type ActionSource = 'web' | 'mobile_app' | 'offline' | 'physical_store' | 'phone_call' | 'email' | 'other';
5
7
  /**
6
8
  * Conversion-matching fields, all optional. Identifiers are normalized, then sent as lowercase
@@ -53,5 +55,10 @@ export interface CreateOpenAIEventsDTO {
53
55
  }
54
56
  export declare function getServerEvent(event: TrackEvent<any>, data: UserProvidedData, actionSource?: EventActionSource): OpenAIEvent;
55
57
  export declare function sendEvents(apiKey: string, pixelId: string, events: TrackEvent<any>[], data?: UserProvidedData, validateOnly?: boolean, actionSource?: EventActionSource): Promise<void>;
58
+ /** OpenAI's Conversions API, sent the same events as `openaiAds`. */
59
+ export declare function openaiConversions(options: OpenAIAdsOptions & {
60
+ accessToken: string;
61
+ validateOnly?: boolean;
62
+ }): ConversionDestination;
56
63
  export {};
57
64
  //# sourceMappingURL=openai-conversions-api.d.mts.map