@shware/analytics 16.0.0 → 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 (162) hide show
  1. package/README.md +76 -1
  2. package/dist/native/fbsdk.cjs +1 -2
  3. package/dist/native/fbsdk.cjs.map +1 -1
  4. package/dist/native/fbsdk.d.cts.map +1 -1
  5. package/dist/native/fbsdk.d.mts.map +1 -1
  6. package/dist/native/fbsdk.mjs +3 -4
  7. package/dist/native/fbsdk.mjs.map +1 -1
  8. package/dist/server/conversions-api-error.cjs +20 -0
  9. package/dist/server/conversions-api-error.cjs.map +1 -0
  10. package/dist/server/conversions-api-error.d.cts +17 -0
  11. package/dist/server/conversions-api-error.d.cts.map +1 -0
  12. package/dist/server/conversions-api-error.d.mts +17 -0
  13. package/dist/server/conversions-api-error.d.mts.map +1 -0
  14. package/dist/server/conversions-api-error.mjs +19 -0
  15. package/dist/server/conversions-api-error.mjs.map +1 -0
  16. package/dist/server/google-data-manager.cjs +24 -26
  17. package/dist/server/google-data-manager.cjs.map +1 -1
  18. package/dist/server/google-data-manager.d.cts +13 -5
  19. package/dist/server/google-data-manager.d.cts.map +1 -1
  20. package/dist/server/google-data-manager.d.mts +13 -5
  21. package/dist/server/google-data-manager.d.mts.map +1 -1
  22. package/dist/server/google-data-manager.mjs +24 -27
  23. package/dist/server/google-data-manager.mjs.map +1 -1
  24. package/dist/server/index.cjs +11 -0
  25. package/dist/server/index.d.cts +10 -7
  26. package/dist/server/index.d.mts +10 -7
  27. package/dist/server/index.mjs +9 -7
  28. package/dist/server/linkedin-conversions-api.cjs +29 -23
  29. package/dist/server/linkedin-conversions-api.cjs.map +1 -1
  30. package/dist/server/linkedin-conversions-api.d.cts +7 -2
  31. package/dist/server/linkedin-conversions-api.d.cts.map +1 -1
  32. package/dist/server/linkedin-conversions-api.d.mts +7 -2
  33. package/dist/server/linkedin-conversions-api.d.mts.map +1 -1
  34. package/dist/server/linkedin-conversions-api.mjs +29 -24
  35. package/dist/server/linkedin-conversions-api.mjs.map +1 -1
  36. package/dist/server/meta-capi.cjs +32 -31
  37. package/dist/server/meta-capi.cjs.map +1 -1
  38. package/dist/server/meta-capi.d.cts +12 -3
  39. package/dist/server/meta-capi.d.cts.map +1 -1
  40. package/dist/server/meta-capi.d.mts +12 -3
  41. package/dist/server/meta-capi.d.mts.map +1 -1
  42. package/dist/server/meta-capi.mjs +33 -33
  43. package/dist/server/meta-capi.mjs.map +1 -1
  44. package/dist/server/microsoft-conversions-api.cjs +33 -28
  45. package/dist/server/microsoft-conversions-api.cjs.map +1 -1
  46. package/dist/server/microsoft-conversions-api.d.cts +14 -2
  47. package/dist/server/microsoft-conversions-api.d.cts.map +1 -1
  48. package/dist/server/microsoft-conversions-api.d.mts +14 -2
  49. package/dist/server/microsoft-conversions-api.d.mts.map +1 -1
  50. package/dist/server/microsoft-conversions-api.mjs +33 -29
  51. package/dist/server/microsoft-conversions-api.mjs.map +1 -1
  52. package/dist/server/openai-conversions-api.cjs +20 -18
  53. package/dist/server/openai-conversions-api.cjs.map +1 -1
  54. package/dist/server/openai-conversions-api.d.cts +7 -0
  55. package/dist/server/openai-conversions-api.d.cts.map +1 -1
  56. package/dist/server/openai-conversions-api.d.mts +7 -0
  57. package/dist/server/openai-conversions-api.d.mts.map +1 -1
  58. package/dist/server/openai-conversions-api.mjs +21 -20
  59. package/dist/server/openai-conversions-api.mjs.map +1 -1
  60. package/dist/server/reddit-conversions-api.cjs +20 -18
  61. package/dist/server/reddit-conversions-api.cjs.map +1 -1
  62. package/dist/server/reddit-conversions-api.d.cts +7 -0
  63. package/dist/server/reddit-conversions-api.d.cts.map +1 -1
  64. package/dist/server/reddit-conversions-api.d.mts +7 -0
  65. package/dist/server/reddit-conversions-api.d.mts.map +1 -1
  66. package/dist/server/reddit-conversions-api.mjs +21 -20
  67. package/dist/server/reddit-conversions-api.mjs.map +1 -1
  68. package/dist/server/setup-conversions.cjs +62 -0
  69. package/dist/server/setup-conversions.cjs.map +1 -0
  70. package/dist/server/setup-conversions.d.cts +97 -0
  71. package/dist/server/setup-conversions.d.cts.map +1 -0
  72. package/dist/server/setup-conversions.d.mts +97 -0
  73. package/dist/server/setup-conversions.d.mts.map +1 -0
  74. package/dist/server/setup-conversions.mjs +60 -0
  75. package/dist/server/setup-conversions.mjs.map +1 -0
  76. package/dist/third-parties/index.d.cts +3 -3
  77. package/dist/third-parties/index.d.mts +3 -3
  78. package/dist/third-parties/integration.cjs +13 -6
  79. package/dist/third-parties/integration.cjs.map +1 -1
  80. package/dist/third-parties/integration.d.cts +12 -8
  81. package/dist/third-parties/integration.d.cts.map +1 -1
  82. package/dist/third-parties/integration.d.mts +12 -8
  83. package/dist/third-parties/integration.d.mts.map +1 -1
  84. package/dist/third-parties/integration.mjs +13 -7
  85. package/dist/third-parties/integration.mjs.map +1 -1
  86. package/dist/third-parties/linkedin-insight-tag.cjs +0 -4
  87. package/dist/third-parties/linkedin-insight-tag.cjs.map +1 -1
  88. package/dist/third-parties/linkedin-insight-tag.d.cts +4 -2
  89. package/dist/third-parties/linkedin-insight-tag.d.cts.map +1 -1
  90. package/dist/third-parties/linkedin-insight-tag.d.mts +4 -2
  91. package/dist/third-parties/linkedin-insight-tag.d.mts.map +1 -1
  92. package/dist/third-parties/linkedin-insight-tag.mjs +0 -4
  93. package/dist/third-parties/linkedin-insight-tag.mjs.map +1 -1
  94. package/dist/third-parties/meta-pixel.cjs +1 -3
  95. package/dist/third-parties/meta-pixel.cjs.map +1 -1
  96. package/dist/third-parties/meta-pixel.d.cts +4 -2
  97. package/dist/third-parties/meta-pixel.d.cts.map +1 -1
  98. package/dist/third-parties/meta-pixel.d.mts +4 -2
  99. package/dist/third-parties/meta-pixel.d.mts.map +1 -1
  100. package/dist/third-parties/meta-pixel.mjs +3 -5
  101. package/dist/third-parties/meta-pixel.mjs.map +1 -1
  102. package/dist/third-parties/microsoft-uet.cjs +7 -2
  103. package/dist/third-parties/microsoft-uet.cjs.map +1 -1
  104. package/dist/third-parties/microsoft-uet.d.cts +10 -3
  105. package/dist/third-parties/microsoft-uet.d.cts.map +1 -1
  106. package/dist/third-parties/microsoft-uet.d.mts +10 -3
  107. package/dist/third-parties/microsoft-uet.d.mts.map +1 -1
  108. package/dist/third-parties/microsoft-uet.mjs +8 -4
  109. package/dist/third-parties/microsoft-uet.mjs.map +1 -1
  110. package/dist/third-parties/openai-pixel.cjs +1 -3
  111. package/dist/third-parties/openai-pixel.cjs.map +1 -1
  112. package/dist/third-parties/openai-pixel.d.cts +4 -2
  113. package/dist/third-parties/openai-pixel.d.cts.map +1 -1
  114. package/dist/third-parties/openai-pixel.d.mts +4 -2
  115. package/dist/third-parties/openai-pixel.d.mts.map +1 -1
  116. package/dist/third-parties/openai-pixel.mjs +3 -5
  117. package/dist/third-parties/openai-pixel.mjs.map +1 -1
  118. package/dist/third-parties/reddit-pixel.cjs +1 -3
  119. package/dist/third-parties/reddit-pixel.cjs.map +1 -1
  120. package/dist/third-parties/reddit-pixel.d.cts +4 -2
  121. package/dist/third-parties/reddit-pixel.d.cts.map +1 -1
  122. package/dist/third-parties/reddit-pixel.d.mts +4 -2
  123. package/dist/third-parties/reddit-pixel.d.mts.map +1 -1
  124. package/dist/third-parties/reddit-pixel.mjs +3 -5
  125. package/dist/third-parties/reddit-pixel.mjs.map +1 -1
  126. package/dist/track/fbq.cjs +5 -0
  127. package/dist/track/fbq.cjs.map +1 -1
  128. package/dist/track/fbq.d.cts +2 -0
  129. package/dist/track/fbq.d.cts.map +1 -1
  130. package/dist/track/fbq.d.mts +2 -0
  131. package/dist/track/fbq.d.mts.map +1 -1
  132. package/dist/track/fbq.mjs +5 -1
  133. package/dist/track/fbq.mjs.map +1 -1
  134. package/dist/track/oaiq.cjs +5 -0
  135. package/dist/track/oaiq.cjs.map +1 -1
  136. package/dist/track/oaiq.d.cts +2 -0
  137. package/dist/track/oaiq.d.cts.map +1 -1
  138. package/dist/track/oaiq.d.mts +2 -0
  139. package/dist/track/oaiq.d.mts.map +1 -1
  140. package/dist/track/oaiq.mjs +5 -1
  141. package/dist/track/oaiq.mjs.map +1 -1
  142. package/dist/track/rdt.cjs +5 -0
  143. package/dist/track/rdt.cjs.map +1 -1
  144. package/dist/track/rdt.d.cts +2 -0
  145. package/dist/track/rdt.d.cts.map +1 -1
  146. package/dist/track/rdt.d.mts +2 -0
  147. package/dist/track/rdt.d.mts.map +1 -1
  148. package/dist/track/rdt.mjs +5 -1
  149. package/dist/track/rdt.mjs.map +1 -1
  150. package/package.json +1 -16
  151. package/dist/server/legacy.cjs +0 -3
  152. package/dist/server/legacy.d.cts +0 -2
  153. package/dist/server/legacy.d.mts +0 -2
  154. package/dist/server/legacy.mjs +0 -1
  155. package/dist/server/meta-conversions-api.cjs +0 -205
  156. package/dist/server/meta-conversions-api.cjs.map +0 -1
  157. package/dist/server/meta-conversions-api.d.cts +0 -8
  158. package/dist/server/meta-conversions-api.d.cts.map +0 -1
  159. package/dist/server/meta-conversions-api.d.mts +0 -8
  160. package/dist/server/meta-conversions-api.d.mts.map +0 -1
  161. package/dist/server/meta-conversions-api.mjs +0 -201
  162. package/dist/server/meta-conversions-api.mjs.map +0 -1
package/README.md CHANGED
@@ -33,7 +33,6 @@ modules for `/native`, `react-native-fbsdk-next` for `/native/fbsdk`, and so on)
33
33
  | `@shware/analytics/tanstack` | both | `createClickIdMiddleware` for TanStack Start |
34
34
  | `@shware/analytics/third-parties` | browser | GA4, Meta Pixel, Reddit, LinkedIn, OpenAI and UET trackers and setters |
35
35
  | `@shware/analytics/server` | server | Conversions APIs: Meta, Google Ads, Microsoft, Reddit, LinkedIn, OpenAI |
36
- | `@shware/analytics/server/legacy` | server | The old Meta sender built on `facebook-nodejs-business-sdk` |
37
36
  | `@shware/analytics/attribution` | server | `classifyTouch` and the channel vocabulary for reading sessions |
38
37
  | `@shware/analytics/ads` | server | Pulling spend and performance from Google Ads and Meta |
39
38
 
@@ -261,6 +260,82 @@ The server's conversions API, sending the stored event under the same id, then d
261
260
 
262
261
  Nothing waits for the server: `track` fires the pixels at once and the batch reaches the server within 2 s or by beacon when the page is left, so there is no `trackAsync` (removed in 13.0). A step that must not run before the server has the event does not belong in the client; record it server-side.
263
262
 
263
+ ### Conversions APIs on the server (`setupConversions`)
264
+
265
+ The server's counterpart of `setupAnalytics({ integrations })`, configured on the server alone:
266
+ each ad platform's Conversions API once, sent what its browser integration is sent — the
267
+ platform's standard events and the `customEvents` it lists, nothing else. The options are the
268
+ browser integrations' (`MetaAdsOptions`, …) plus a token; give a platform the same
269
+ `customEvents` on both sides for the tag and the API to report the same events.
270
+
271
+ ```ts
272
+ import {
273
+ linkedinConversions,
274
+ metaConversions,
275
+ redditConversions,
276
+ setupConversions,
277
+ } from '@shware/analytics/server';
278
+
279
+ export const conversions = setupConversions({
280
+ destinations: [
281
+ metaConversions({
282
+ accessToken: env.META_CONVERSIONS_API_ACCESS_TOKEN,
283
+ pixelId: '1234567890',
284
+ customEvents: ['onboarding_completed'],
285
+ }),
286
+ redditConversions({ accessToken: env.REDDIT_CONVERSIONS_API_ACCESS_TOKEN, pixelId: 'a2_xxx' }),
287
+ linkedinConversions({
288
+ accessToken: env.LINKEDIN_CONVERSIONS_API_ACCESS_TOKEN,
289
+ conversions: { sign_up: 7654321, purchase: 7654322 },
290
+ }),
291
+ // a CRM or the host's own workflows: any `{ send(events, data) }`
292
+ { send: (events, data) => sendToCrm(events, data) },
293
+ ],
294
+ // Only for conversions.track(), which is returned only with it; forward needs none of it.
295
+ track: {
296
+ resolveUser: async (userId) => latestSessionOf(userId),
297
+ store: async (event) => (await insertEvents([event])).length > 0,
298
+ },
299
+ });
300
+
301
+ // POST /events, after storing the batch
302
+ ctx.waitUntil(conversions.forward(events, userProvidedData));
303
+
304
+ // a webhook: Stripe's invoice.paid, once the account is credited
305
+ ctx.waitUntil(
306
+ conversions.track({
307
+ id: invoice.id,
308
+ name: 'purchase',
309
+ userId,
310
+ properties: { transaction_id: invoice.id, value: 9.99, currency: 'usd', items: [] },
311
+ createdAt: new Date(invoice.created * 1000).toISOString(),
312
+ })
313
+ );
314
+ ```
315
+
316
+ - `forward(events, data)`: the events a client sent, as stored, to every destination at once.
317
+ - `track(event)`: an event the server reports on its own — a webhook's purchase, renewal or
318
+ refund — with `id` the transaction id. `track.resolveUser(userId)` returns what a client event
319
+ would have carried, from the host's records: the user's latest session's `tags` (cookies, page,
320
+ user agent) with the click ids of the touch the conversion is credited to, that session's
321
+ `visitor_id`, `session_id`, `platform` (which decides website or app) and `environment`, and the
322
+ user's identity as `data`. `track.store` stores the event — in the events table, so the
323
+ server's conversions count wherever the client's do — and says whether it was new: only a new
324
+ one is sent, so a webhook delivered again is not reported twice. That matters: the platforms
325
+ document deduplicating a server event against a browser one, and only Microsoft (on `eventId`)
326
+ and Google Ads (on `transaction_id`) a server event sent twice. A user with no session is
327
+ skipped.
328
+
329
+ Neither throws, so reporting a conversion cannot fail the request it runs in — least of all a
330
+ payment webhook, which its provider would deliver again and again. A failure is logged with the
331
+ ids of the events it lost (`Conversions not sent, events: …`), to be found and sent later: a
332
+ missed conversion costs less than a duplicate one or a failing webhook. The `send…Events`
333
+ functions underneath reject instead (`ConversionsApiError` for an error status, the fetch error
334
+ for a network failure; neither carries a token), for a caller using them directly to handle.
335
+
336
+ List events the server reports itself in `setupAnalytics({ excludeFromIntegrations })` so the
337
+ browser does not send them too.
338
+
264
339
  ### Tracking an occurrence once (`trackOnce`)
265
340
 
266
341
  A payment result page can be reloaded or reopened from history, and a store transaction can be delivered again; each would report the same `purchase` again. `trackOnce` takes the key that identifies the occurrence and tracks it at most once per key:
@@ -44,10 +44,9 @@ function setFBUser({ user_id, user_data }) {
44
44
  * — the app's counterpart of `metaAds`.
45
45
  */
46
46
  function metaAppEvents(options = {}) {
47
- const isStandard = (name) => require_track_fbq.mapFBEvent(name)[0] === "track";
48
47
  return {
49
48
  type: "ads",
50
- track: require_third_parties_integration.adsTracker(sendFBEvent, isStandard, options.customEvents ?? []),
49
+ track: require_third_parties_integration.adsTracker(sendFBEvent, require_third_parties_integration.adEvents(require_track_fbq.isStandardFBEvent, options.customEvents)),
51
50
  setUser: setFBUser
52
51
  };
53
52
  }
@@ -1 +1 @@
1
- {"version":3,"file":"fbsdk.cjs","names":["mapFBEvent","getFirst","adsTracker"],"sources":["../../src/native/fbsdk.ts"],"sourcesContent":["import { AppEventsLogger, type Params } from 'react-native-fbsdk-next';\nimport type { UpdateVisitorDTO } from '../schema/index';\nimport { type AdsOptions, type Integration, adsTracker } from '../third-parties/integration';\nimport { mapFBEvent } from '../track/fbq';\nimport type { EventName, TrackName, TrackProperties } from '../track/types';\nimport { getFirst } from '../utils/field';\n\n/**\n * ref: https://developers.facebook.com/docs/app-events/guides/maximize-in-app-ad-revenue/\n *\n * Synchronous, like `logEvent`: a tracker returns `void | boolean`, which an `async` function's\n * promise would not satisfy. Callers that still `await` it keep compiling.\n */\nexport function sendFBEvent<T extends EventName>(\n name: TrackName<T>,\n properties?: TrackProperties<T>\n) {\n const [_, fbEventName, fbEventProperties] = mapFBEvent(name, properties);\n AppEventsLogger.logEvent(fbEventName, fbEventProperties as Params);\n}\n\n/**\n * Hands the signed-in user to Facebook App Events, as `setFBUser` does the Pixel: the user id\n * (`external_id`) and the advanced matching fields, which the SDK hashes on the device. No user is\n * sign-out (`reset()`): the user id is cleared, but the matching fields may not be.\n *\n * Known gap, kept on purpose: the fields go to the native `setUserData`, which on Android only\n * updates the fields it is given, so the empty ones sent at sign-out leave the previous user's\n * email and phone in place, and later anonymous events (or another user's without an email) can\n * still carry them. `react-native-fbsdk-next` does not expose the native `clearUserData`. Dropping\n * the fields would avoid it, but cost more in ad conversion matching than the gap does.\n */\nexport function setFBUser({ user_id, user_data }: Omit<UpdateVisitorDTO, 'tags'>) {\n AppEventsLogger.setUserID(user_id || null);\n const address = getFirst(user_data?.address);\n AppEventsLogger.setUserData({\n email: getFirst(user_data?.email),\n phone: getFirst(user_data?.phone_number),\n firstName: address?.first_name,\n lastName: address?.last_name,\n city: address?.city,\n state: address?.region,\n zip: address?.postal_code,\n country: address?.country,\n });\n}\n\n/**\n * Facebook App Events: the events `mapFBEvent` maps to a Meta standard event, and `customEvents`\n * — the app's counterpart of `metaAds`.\n */\nexport function metaAppEvents(options: AdsOptions = {}): Integration {\n const isStandard = (name: string) => mapFBEvent(name as TrackName)[0] === 'track';\n return {\n type: 'ads',\n track: adsTracker(sendFBEvent, isStandard, options.customEvents ?? []),\n setUser: setFBUser,\n };\n}\n"],"mappings":";;;;;;;;;;;;AAaA,SAAgB,YACd,MACA,YACA;CACA,MAAM,CAAC,GAAG,aAAa,qBAAqBA,kBAAAA,WAAW,MAAM,UAAU;CACvE,wBAAA,gBAAgB,SAAS,aAAa,iBAA2B;AACnE;;;;;;;;;;;;AAaA,SAAgB,UAAU,EAAE,SAAS,aAA6C;CAChF,wBAAA,gBAAgB,UAAU,WAAW,IAAI;CACzC,MAAM,UAAUC,oBAAAA,SAAS,WAAW,OAAO;CAC3C,wBAAA,gBAAgB,YAAY;EAC1B,OAAOA,oBAAAA,SAAS,WAAW,KAAK;EAChC,OAAOA,oBAAAA,SAAS,WAAW,YAAY;EACvC,WAAW,SAAS;EACpB,UAAU,SAAS;EACnB,MAAM,SAAS;EACf,OAAO,SAAS;EAChB,KAAK,SAAS;EACd,SAAS,SAAS;CACpB,CAAC;AACH;;;;;AAMA,SAAgB,cAAc,UAAsB,CAAC,GAAgB;CACnE,MAAM,cAAc,SAAiBD,kBAAAA,WAAW,IAAiB,CAAC,CAAC,OAAO;CAC1E,OAAO;EACL,MAAM;EACN,OAAOE,kCAAAA,WAAW,aAAa,YAAY,QAAQ,gBAAgB,CAAC,CAAC;EACrE,SAAS;CACX;AACF"}
1
+ {"version":3,"file":"fbsdk.cjs","names":["mapFBEvent","getFirst","adsTracker","adEvents","isStandardFBEvent"],"sources":["../../src/native/fbsdk.ts"],"sourcesContent":["import { AppEventsLogger, type Params } from 'react-native-fbsdk-next';\nimport type { UpdateVisitorDTO } from '../schema/index';\nimport {\n type AdsOptions,\n type Integration,\n adEvents,\n adsTracker,\n} from '../third-parties/integration';\nimport { isStandardFBEvent, mapFBEvent } from '../track/fbq';\nimport type { EventName, TrackName, TrackProperties } from '../track/types';\nimport { getFirst } from '../utils/field';\n\n/**\n * ref: https://developers.facebook.com/docs/app-events/guides/maximize-in-app-ad-revenue/\n *\n * Synchronous, like `logEvent`: a tracker returns `void | boolean`, which an `async` function's\n * promise would not satisfy. Callers that still `await` it keep compiling.\n */\nexport function sendFBEvent<T extends EventName>(\n name: TrackName<T>,\n properties?: TrackProperties<T>\n) {\n const [_, fbEventName, fbEventProperties] = mapFBEvent(name, properties);\n AppEventsLogger.logEvent(fbEventName, fbEventProperties as Params);\n}\n\n/**\n * Hands the signed-in user to Facebook App Events, as `setFBUser` does the Pixel: the user id\n * (`external_id`) and the advanced matching fields, which the SDK hashes on the device. No user is\n * sign-out (`reset()`): the user id is cleared, but the matching fields may not be.\n *\n * Known gap, kept on purpose: the fields go to the native `setUserData`, which on Android only\n * updates the fields it is given, so the empty ones sent at sign-out leave the previous user's\n * email and phone in place, and later anonymous events (or another user's without an email) can\n * still carry them. `react-native-fbsdk-next` does not expose the native `clearUserData`. Dropping\n * the fields would avoid it, but cost more in ad conversion matching than the gap does.\n */\nexport function setFBUser({ user_id, user_data }: Omit<UpdateVisitorDTO, 'tags'>) {\n AppEventsLogger.setUserID(user_id || null);\n const address = getFirst(user_data?.address);\n AppEventsLogger.setUserData({\n email: getFirst(user_data?.email),\n phone: getFirst(user_data?.phone_number),\n firstName: address?.first_name,\n lastName: address?.last_name,\n city: address?.city,\n state: address?.region,\n zip: address?.postal_code,\n country: address?.country,\n });\n}\n\n/**\n * Facebook App Events: the events `mapFBEvent` maps to a Meta standard event, and `customEvents`\n * — the app's counterpart of `metaAds`.\n */\nexport function metaAppEvents(options: AdsOptions = {}): Integration {\n return {\n type: 'ads',\n track: adsTracker(sendFBEvent, adEvents(isStandardFBEvent, options.customEvents)),\n setUser: setFBUser,\n };\n}\n"],"mappings":";;;;;;;;;;;;AAkBA,SAAgB,YACd,MACA,YACA;CACA,MAAM,CAAC,GAAG,aAAa,qBAAqBA,kBAAAA,WAAW,MAAM,UAAU;CACvE,wBAAA,gBAAgB,SAAS,aAAa,iBAA2B;AACnE;;;;;;;;;;;;AAaA,SAAgB,UAAU,EAAE,SAAS,aAA6C;CAChF,wBAAA,gBAAgB,UAAU,WAAW,IAAI;CACzC,MAAM,UAAUC,oBAAAA,SAAS,WAAW,OAAO;CAC3C,wBAAA,gBAAgB,YAAY;EAC1B,OAAOA,oBAAAA,SAAS,WAAW,KAAK;EAChC,OAAOA,oBAAAA,SAAS,WAAW,YAAY;EACvC,WAAW,SAAS;EACpB,UAAU,SAAS;EACnB,MAAM,SAAS;EACf,OAAO,SAAS;EAChB,KAAK,SAAS;EACd,SAAS,SAAS;CACpB,CAAC;AACH;;;;;AAMA,SAAgB,cAAc,UAAsB,CAAC,GAAgB;CACnE,OAAO;EACL,MAAM;EACN,OAAOC,kCAAAA,WAAW,aAAaC,kCAAAA,SAASC,kBAAAA,mBAAmB,QAAQ,YAAY,CAAC;EAChF,SAAS;CACX;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"fbsdk.d.cts","names":[],"sources":["../../src/native/fbsdk.ts"],"mappings":";;;;;;;;;wBAagB,YAAY,UAAU,WACpC,MAAM,UAAU,IAChB,aAAa,gBAAgB;;;;;;;;;;;;wBAiBf,YAAY,SAAS,aAAa,KAAK;;;;;wBAmBvC,cAAc,UAAS,aAAkB"}
1
+ {"version":3,"file":"fbsdk.d.cts","names":[],"sources":["../../src/native/fbsdk.ts"],"mappings":";;;;;;;;;wBAkBgB,YAAY,UAAU,WACpC,MAAM,UAAU,IAChB,aAAa,gBAAgB;;;;;;;;;;;;wBAiBf,YAAY,SAAS,aAAa,KAAK;;;;;wBAmBvC,cAAc,UAAS,aAAkB"}
@@ -1 +1 @@
1
- {"version":3,"file":"fbsdk.d.mts","names":[],"sources":["../../src/native/fbsdk.ts"],"mappings":";;;;;;;;;wBAagB,YAAY,UAAU,WACpC,MAAM,UAAU,IAChB,aAAa,gBAAgB;;;;;;;;;;;;wBAiBf,YAAY,SAAS,aAAa,KAAK;;;;;wBAmBvC,cAAc,UAAS,aAAkB"}
1
+ {"version":3,"file":"fbsdk.d.mts","names":[],"sources":["../../src/native/fbsdk.ts"],"mappings":";;;;;;;;;wBAkBgB,YAAY,UAAU,WACpC,MAAM,UAAU,IAChB,aAAa,gBAAgB;;;;;;;;;;;;wBAiBf,YAAY,SAAS,aAAa,KAAK;;;;;wBAmBvC,cAAc,UAAS,aAAkB"}
@@ -1,6 +1,6 @@
1
1
  import { getFirst } from "../utils/field.mjs";
2
- import { adsTracker } from "../third-parties/integration.mjs";
3
- import { mapFBEvent } from "../track/fbq.mjs";
2
+ import { adEvents, adsTracker } from "../third-parties/integration.mjs";
3
+ import { isStandardFBEvent, mapFBEvent } from "../track/fbq.mjs";
4
4
  import { AppEventsLogger } from "react-native-fbsdk-next";
5
5
  // src/native/fbsdk.ts
6
6
  /**
@@ -43,10 +43,9 @@ function setFBUser({ user_id, user_data }) {
43
43
  * — the app's counterpart of `metaAds`.
44
44
  */
45
45
  function metaAppEvents(options = {}) {
46
- const isStandard = (name) => mapFBEvent(name)[0] === "track";
47
46
  return {
48
47
  type: "ads",
49
- track: adsTracker(sendFBEvent, isStandard, options.customEvents ?? []),
48
+ track: adsTracker(sendFBEvent, adEvents(isStandardFBEvent, options.customEvents)),
50
49
  setUser: setFBUser
51
50
  };
52
51
  }
@@ -1 +1 @@
1
- {"version":3,"file":"fbsdk.mjs","names":[],"sources":["../../src/native/fbsdk.ts"],"sourcesContent":["import { AppEventsLogger, type Params } from 'react-native-fbsdk-next';\nimport type { UpdateVisitorDTO } from '../schema/index';\nimport { type AdsOptions, type Integration, adsTracker } from '../third-parties/integration';\nimport { mapFBEvent } from '../track/fbq';\nimport type { EventName, TrackName, TrackProperties } from '../track/types';\nimport { getFirst } from '../utils/field';\n\n/**\n * ref: https://developers.facebook.com/docs/app-events/guides/maximize-in-app-ad-revenue/\n *\n * Synchronous, like `logEvent`: a tracker returns `void | boolean`, which an `async` function's\n * promise would not satisfy. Callers that still `await` it keep compiling.\n */\nexport function sendFBEvent<T extends EventName>(\n name: TrackName<T>,\n properties?: TrackProperties<T>\n) {\n const [_, fbEventName, fbEventProperties] = mapFBEvent(name, properties);\n AppEventsLogger.logEvent(fbEventName, fbEventProperties as Params);\n}\n\n/**\n * Hands the signed-in user to Facebook App Events, as `setFBUser` does the Pixel: the user id\n * (`external_id`) and the advanced matching fields, which the SDK hashes on the device. No user is\n * sign-out (`reset()`): the user id is cleared, but the matching fields may not be.\n *\n * Known gap, kept on purpose: the fields go to the native `setUserData`, which on Android only\n * updates the fields it is given, so the empty ones sent at sign-out leave the previous user's\n * email and phone in place, and later anonymous events (or another user's without an email) can\n * still carry them. `react-native-fbsdk-next` does not expose the native `clearUserData`. Dropping\n * the fields would avoid it, but cost more in ad conversion matching than the gap does.\n */\nexport function setFBUser({ user_id, user_data }: Omit<UpdateVisitorDTO, 'tags'>) {\n AppEventsLogger.setUserID(user_id || null);\n const address = getFirst(user_data?.address);\n AppEventsLogger.setUserData({\n email: getFirst(user_data?.email),\n phone: getFirst(user_data?.phone_number),\n firstName: address?.first_name,\n lastName: address?.last_name,\n city: address?.city,\n state: address?.region,\n zip: address?.postal_code,\n country: address?.country,\n });\n}\n\n/**\n * Facebook App Events: the events `mapFBEvent` maps to a Meta standard event, and `customEvents`\n * — the app's counterpart of `metaAds`.\n */\nexport function metaAppEvents(options: AdsOptions = {}): Integration {\n const isStandard = (name: string) => mapFBEvent(name as TrackName)[0] === 'track';\n return {\n type: 'ads',\n track: adsTracker(sendFBEvent, isStandard, options.customEvents ?? []),\n setUser: setFBUser,\n };\n}\n"],"mappings":";;;;;;;;;;;AAaA,SAAgB,YACd,MACA,YACA;CACA,MAAM,CAAC,GAAG,aAAa,qBAAqB,WAAW,MAAM,UAAU;CACvE,gBAAgB,SAAS,aAAa,iBAA2B;AACnE;;;;;;;;;;;;AAaA,SAAgB,UAAU,EAAE,SAAS,aAA6C;CAChF,gBAAgB,UAAU,WAAW,IAAI;CACzC,MAAM,UAAU,SAAS,WAAW,OAAO;CAC3C,gBAAgB,YAAY;EAC1B,OAAO,SAAS,WAAW,KAAK;EAChC,OAAO,SAAS,WAAW,YAAY;EACvC,WAAW,SAAS;EACpB,UAAU,SAAS;EACnB,MAAM,SAAS;EACf,OAAO,SAAS;EAChB,KAAK,SAAS;EACd,SAAS,SAAS;CACpB,CAAC;AACH;;;;;AAMA,SAAgB,cAAc,UAAsB,CAAC,GAAgB;CACnE,MAAM,cAAc,SAAiB,WAAW,IAAiB,CAAC,CAAC,OAAO;CAC1E,OAAO;EACL,MAAM;EACN,OAAO,WAAW,aAAa,YAAY,QAAQ,gBAAgB,CAAC,CAAC;EACrE,SAAS;CACX;AACF"}
1
+ {"version":3,"file":"fbsdk.mjs","names":[],"sources":["../../src/native/fbsdk.ts"],"sourcesContent":["import { AppEventsLogger, type Params } from 'react-native-fbsdk-next';\nimport type { UpdateVisitorDTO } from '../schema/index';\nimport {\n type AdsOptions,\n type Integration,\n adEvents,\n adsTracker,\n} from '../third-parties/integration';\nimport { isStandardFBEvent, mapFBEvent } from '../track/fbq';\nimport type { EventName, TrackName, TrackProperties } from '../track/types';\nimport { getFirst } from '../utils/field';\n\n/**\n * ref: https://developers.facebook.com/docs/app-events/guides/maximize-in-app-ad-revenue/\n *\n * Synchronous, like `logEvent`: a tracker returns `void | boolean`, which an `async` function's\n * promise would not satisfy. Callers that still `await` it keep compiling.\n */\nexport function sendFBEvent<T extends EventName>(\n name: TrackName<T>,\n properties?: TrackProperties<T>\n) {\n const [_, fbEventName, fbEventProperties] = mapFBEvent(name, properties);\n AppEventsLogger.logEvent(fbEventName, fbEventProperties as Params);\n}\n\n/**\n * Hands the signed-in user to Facebook App Events, as `setFBUser` does the Pixel: the user id\n * (`external_id`) and the advanced matching fields, which the SDK hashes on the device. No user is\n * sign-out (`reset()`): the user id is cleared, but the matching fields may not be.\n *\n * Known gap, kept on purpose: the fields go to the native `setUserData`, which on Android only\n * updates the fields it is given, so the empty ones sent at sign-out leave the previous user's\n * email and phone in place, and later anonymous events (or another user's without an email) can\n * still carry them. `react-native-fbsdk-next` does not expose the native `clearUserData`. Dropping\n * the fields would avoid it, but cost more in ad conversion matching than the gap does.\n */\nexport function setFBUser({ user_id, user_data }: Omit<UpdateVisitorDTO, 'tags'>) {\n AppEventsLogger.setUserID(user_id || null);\n const address = getFirst(user_data?.address);\n AppEventsLogger.setUserData({\n email: getFirst(user_data?.email),\n phone: getFirst(user_data?.phone_number),\n firstName: address?.first_name,\n lastName: address?.last_name,\n city: address?.city,\n state: address?.region,\n zip: address?.postal_code,\n country: address?.country,\n });\n}\n\n/**\n * Facebook App Events: the events `mapFBEvent` maps to a Meta standard event, and `customEvents`\n * — the app's counterpart of `metaAds`.\n */\nexport function metaAppEvents(options: AdsOptions = {}): Integration {\n return {\n type: 'ads',\n track: adsTracker(sendFBEvent, adEvents(isStandardFBEvent, options.customEvents)),\n setUser: setFBUser,\n };\n}\n"],"mappings":";;;;;;;;;;;AAkBA,SAAgB,YACd,MACA,YACA;CACA,MAAM,CAAC,GAAG,aAAa,qBAAqB,WAAW,MAAM,UAAU;CACvE,gBAAgB,SAAS,aAAa,iBAA2B;AACnE;;;;;;;;;;;;AAaA,SAAgB,UAAU,EAAE,SAAS,aAA6C;CAChF,gBAAgB,UAAU,WAAW,IAAI;CACzC,MAAM,UAAU,SAAS,WAAW,OAAO;CAC3C,gBAAgB,YAAY;EAC1B,OAAO,SAAS,WAAW,KAAK;EAChC,OAAO,SAAS,WAAW,YAAY;EACvC,WAAW,SAAS;EACpB,UAAU,SAAS;EACnB,MAAM,SAAS;EACf,OAAO,SAAS;EAChB,KAAK,SAAS;EACd,SAAS,SAAS;CACpB,CAAC;AACH;;;;;AAMA,SAAgB,cAAc,UAAsB,CAAC,GAAgB;CACnE,OAAO;EACL,MAAM;EACN,OAAO,WAAW,aAAa,SAAS,mBAAmB,QAAQ,YAAY,CAAC;EAChF,SAAS;CACX;AACF"}
@@ -0,0 +1,20 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ // src/server/conversions-api-error.ts
3
+ /**
4
+ * A conversions API that answered with an error status. The senders throw it, after the retries
5
+ * of a transient failure have run out, and leave what to do about it to the caller —
6
+ * `setupConversions` sends to every other destination still, then rejects with all of them. A
7
+ * network failure rejects with the fetch error itself. Neither carries the access token.
8
+ */
9
+ var ConversionsApiError = class extends Error {
10
+ constructor(platform, status, body) {
11
+ super(`Failed to send ${platform} conversions, status: ${status}, body: ${body}`);
12
+ this.platform = platform;
13
+ this.status = status;
14
+ this.body = body;
15
+ this.name = "ConversionsApiError";
16
+ }
17
+ };
18
+ exports.ConversionsApiError = ConversionsApiError;
19
+
20
+ //# sourceMappingURL=conversions-api-error.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"conversions-api-error.cjs","names":[],"sources":["../../src/server/conversions-api-error.ts"],"sourcesContent":["/**\n * A conversions API that answered with an error status. The senders throw it, after the retries\n * of a transient failure have run out, and leave what to do about it to the caller —\n * `setupConversions` sends to every other destination still, then rejects with all of them. A\n * network failure rejects with the fetch error itself. Neither carries the access token.\n */\nexport class ConversionsApiError extends Error {\n override readonly name = 'ConversionsApiError';\n\n constructor(\n readonly platform: 'meta' | 'reddit' | 'openai' | 'linkedin' | 'microsoft' | 'google',\n readonly status: number,\n /** The response body, as the platform explains the rejection. */\n readonly body: string\n ) {\n super(`Failed to send ${platform} conversions, status: ${status}, body: ${body}`);\n }\n}\n"],"mappings":";;;;;;;;AAMA,IAAa,sBAAb,cAAyC,MAAM;CAG7C,YACE,UACA,QAEA,MACA;EACA,MAAM,kBAAkB,SAAS,wBAAwB,OAAO,UAAU,MAAM;EALvE,KAAA,WAAA;EACA,KAAA,SAAA;EAEA,KAAA,OAAA;EANc,KAAA,OAAA;CASzB;AACF"}
@@ -0,0 +1,17 @@
1
+ /**
2
+ * A conversions API that answered with an error status. The senders throw it, after the retries
3
+ * of a transient failure have run out, and leave what to do about it to the caller —
4
+ * `setupConversions` sends to every other destination still, then rejects with all of them. A
5
+ * network failure rejects with the fetch error itself. Neither carries the access token.
6
+ */
7
+ export declare class ConversionsApiError extends Error {
8
+ readonly platform: 'meta' | 'reddit' | 'openai' | 'linkedin' | 'microsoft' | 'google';
9
+ readonly status: number;
10
+ /** The response body, as the platform explains the rejection. */
11
+ readonly body: string;
12
+ readonly name = "ConversionsApiError";
13
+ constructor(platform: 'meta' | 'reddit' | 'openai' | 'linkedin' | 'microsoft' | 'google', status: number,
14
+ /** The response body, as the platform explains the rejection. */
15
+ body: string);
16
+ }
17
+ //# sourceMappingURL=conversions-api-error.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"conversions-api-error.d.cts","names":[],"sources":["../../src/server/conversions-api-error.ts"],"mappings":";;;;;;qBAMa,4BAA4B;WAI5B;WACA;;WAEA;WANO;EAElB,YACW,8EACA;;EAEA"}
@@ -0,0 +1,17 @@
1
+ /**
2
+ * A conversions API that answered with an error status. The senders throw it, after the retries
3
+ * of a transient failure have run out, and leave what to do about it to the caller —
4
+ * `setupConversions` sends to every other destination still, then rejects with all of them. A
5
+ * network failure rejects with the fetch error itself. Neither carries the access token.
6
+ */
7
+ export declare class ConversionsApiError extends Error {
8
+ readonly platform: 'meta' | 'reddit' | 'openai' | 'linkedin' | 'microsoft' | 'google';
9
+ readonly status: number;
10
+ /** The response body, as the platform explains the rejection. */
11
+ readonly body: string;
12
+ readonly name = "ConversionsApiError";
13
+ constructor(platform: 'meta' | 'reddit' | 'openai' | 'linkedin' | 'microsoft' | 'google', status: number,
14
+ /** The response body, as the platform explains the rejection. */
15
+ body: string);
16
+ }
17
+ //# sourceMappingURL=conversions-api-error.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"conversions-api-error.d.mts","names":[],"sources":["../../src/server/conversions-api-error.ts"],"mappings":";;;;;;qBAMa,4BAA4B;WAI5B;WACA;;WAEA;WANO;EAElB,YACW,8EACA;;EAEA"}
@@ -0,0 +1,19 @@
1
+ // src/server/conversions-api-error.ts
2
+ /**
3
+ * A conversions API that answered with an error status. The senders throw it, after the retries
4
+ * of a transient failure have run out, and leave what to do about it to the caller —
5
+ * `setupConversions` sends to every other destination still, then rejects with all of them. A
6
+ * network failure rejects with the fetch error itself. Neither carries the access token.
7
+ */
8
+ var ConversionsApiError = class extends Error {
9
+ constructor(platform, status, body) {
10
+ super(`Failed to send ${platform} conversions, status: ${status}, body: ${body}`);
11
+ this.platform = platform;
12
+ this.status = status;
13
+ this.body = body;
14
+ this.name = "ConversionsApiError";
15
+ }
16
+ };
17
+ export { ConversionsApiError };
18
+
19
+ //# sourceMappingURL=conversions-api-error.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"conversions-api-error.mjs","names":[],"sources":["../../src/server/conversions-api-error.ts"],"sourcesContent":["/**\n * A conversions API that answered with an error status. The senders throw it, after the retries\n * of a transient failure have run out, and leave what to do about it to the caller —\n * `setupConversions` sends to every other destination still, then rejects with all of them. A\n * network failure rejects with the fetch error itself. Neither carries the access token.\n */\nexport class ConversionsApiError extends Error {\n override readonly name = 'ConversionsApiError';\n\n constructor(\n readonly platform: 'meta' | 'reddit' | 'openai' | 'linkedin' | 'microsoft' | 'google',\n readonly status: number,\n /** The response body, as the platform explains the rejection. */\n readonly body: string\n ) {\n super(`Failed to send ${platform} conversions, status: ${status}, body: ${body}`);\n }\n}\n"],"mappings":";;;;;;;AAMA,IAAa,sBAAb,cAAyC,MAAM;CAG7C,YACE,UACA,QAEA,MACA;EACA,MAAM,kBAAkB,SAAS,wBAAwB,OAAO,UAAU,MAAM;EALvE,KAAA,WAAA;EACA,KAAA,SAAA;EAEA,KAAA,OAAA;EANc,KAAA,OAAA;CASzB;AACF"}
@@ -2,6 +2,8 @@ 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_server_action_source = require("./action-source.cjs");
4
4
  const require_server_click_ids = require("./click-ids.cjs");
5
+ const require_server_conversions_api_error = require("./conversions-api-error.cjs");
6
+ const require_server_setup_conversions = require("./setup-conversions.cjs");
5
7
  let _shware_utils = require("@shware/utils");
6
8
  let node_crypto = require("node:crypto");
7
9
  // src/server/google-data-manager.ts
@@ -9,8 +11,8 @@ let node_crypto = require("node:crypto");
9
11
  * Google Ads conversion sender over the Data Manager API (`events:ingest`) — Google's
10
12
  * counterpart to Meta's Conversions API, and the mandated successor to the Google Ads API's
11
13
  * `UploadClickConversions`, which stopped accepting new adopters on 2026-06-15. Same shape as
12
- * the other senders here: a pure per-event builder, a never-throws `sendEvents`, credentials
13
- * in headers and never in a URL or a log line.
14
+ * the other senders here: a pure per-event builder, a `sendEvents` that rejects on failure,
15
+ * credentials in headers and never in a URL or an error.
14
16
  *
15
17
  * Google's recommended deployment is *hybrid* ("boost your tag with additional data sources"):
16
18
  * this upload attaches to the SAME conversion action the gtag tag reports to, matched by
@@ -98,8 +100,9 @@ function getDataManagerEvent(event, config, data = {}, actionType = "webpage") {
98
100
  /** The API takes at most 2000 events per request. */
99
101
  const MAX_EVENTS_PER_REQUEST = 2e3;
100
102
  /**
101
- * Uploads the configured conversions from a batch of events. Never throws: an unusable event
102
- * is skipped and a failed request is logged and swallowed, like every other sender here. The
103
+ * Uploads the configured conversions from a batch of events. An unusable event is skipped; a
104
+ * failed request rejects (a `ConversionsApiError`, or the fetch error), as with every sender here,
105
+ * and sends no further ones. The
103
106
  * Data Manager API has no partial-failure mode — a rejected request costs the whole batch, so
104
107
  * the builder is strict about only emitting events the API can accept. A batch beyond the
105
108
  * 2000-event request cap goes out as sequential requests; the first response is returned.
@@ -134,32 +137,27 @@ async function sendEvents(auth, config, events, data = {}, options = {}) {
134
137
  };
135
138
  if (chunk.some((dmEvent) => dmEvent.userData)) body.encoding = "HEX";
136
139
  if (options.consent) body.consent = options.consent;
137
- try {
138
- const response = await (0, _shware_utils.fetch)(ENDPOINT, {
139
- method: "POST",
140
- retries: 3,
141
- headers: {
142
- "Content-Type": "application/json",
143
- Accept: "application/json",
144
- Authorization: `Bearer ${auth.accessToken}`
145
- },
146
- body: JSON.stringify(body)
147
- });
148
- if (response.ok) {
149
- firstResponse ??= await response.json();
150
- continue;
151
- }
152
- const { status } = response;
153
- const message = await response.text();
154
- console.error(`Failed to send Google Ads conversions, status: ${status}, body: ${message}`);
155
- } catch (error) {
156
- const message = error instanceof Error ? error.message : String(error);
157
- console.error(`Failed to send Google Ads conversions, network error: ${message}`);
158
- }
140
+ const response = await (0, _shware_utils.fetch)(ENDPOINT, {
141
+ method: "POST",
142
+ retries: 3,
143
+ headers: {
144
+ "Content-Type": "application/json",
145
+ Accept: "application/json",
146
+ Authorization: `Bearer ${auth.accessToken}`
147
+ },
148
+ body: JSON.stringify(body)
149
+ });
150
+ if (!response.ok) throw new require_server_conversions_api_error.ConversionsApiError("google", response.status, await response.text());
151
+ firstResponse ??= await response.json();
159
152
  }
160
153
  return firstResponse;
161
154
  }
155
+ /** Google Ads through the Data Manager API: the events in `conversions`, each as its action. */
156
+ function googleAdsConversions(options) {
157
+ return require_server_setup_conversions.conversionDestination((name) => options.conversions[name] !== void 0, (events, data) => sendEvents(options.auth, options.conversions, events, data, options));
158
+ }
162
159
  exports.getDataManagerEvent = getDataManagerEvent;
160
+ exports.googleAdsConversions = googleAdsConversions;
163
161
  exports.normalizeEmail = normalizeEmail;
164
162
  exports.sendEvents = sendEvents;
165
163
 
@@ -1 +1 @@
1
- {"version":3,"file":"google-data-manager.cjs","names":["createHash","resolveActionSource","googleClickIds","IGNORED_EVENTS","fetch"],"sources":["../../src/server/google-data-manager.ts"],"sourcesContent":["/**\n * Google Ads conversion sender over the Data Manager API (`events:ingest`) — Google's\n * counterpart to Meta's Conversions API, and the mandated successor to the Google Ads API's\n * `UploadClickConversions`, which stopped accepting new adopters on 2026-06-15. Same shape as\n * the other senders here: a pure per-event builder, a never-throws `sendEvents`, credentials\n * in headers and never in a URL or a log line.\n *\n * Google's recommended deployment is *hybrid* (\"boost your tag with additional data sources\"):\n * this upload attaches to the SAME conversion action the gtag tag reports to, matched by\n * `transactionId` — a matched pair collapses into one conversion with the server data winning,\n * an unmatched upload is a recovered conversion. Both channels here are fed from the same\n * `track()` call, so the ids agree by construction. `transactionId` is therefore required in\n * that mode; this sender always sends one (the event id when there is no natural order id).\n *\n * Auth is a plain OAuth2 access token with the `datamanager` scope — no Google Ads developer\n * token, no API Center approval. The caller exchanges its stored refresh token for the access\n * token (one POST to oauth2.googleapis.com) and refreshes it however it likes; this module\n * stays out of the OAuth business, exactly as it stays out of Meta's.\n *\n * https://developers.google.com/data-manager/api/reference/rest/v1/events/ingest\n * https://developers.google.com/data-manager/api/devguides/events/google-ads/offline/upgrade/field-mappings\n * https://support.google.com/google-ads/answer/16542291 (hybrid: \"boost your tag with\n * additional data sources\" — the transaction-id matching contract this sender relies on)\n */\nimport { createHash } from 'node:crypto';\nimport { fetch } from '@shware/utils';\nimport { IGNORED_EVENTS } from '../third-parties/ignored-events';\nimport type { TrackEvent, UserProvidedData } from '../track/types';\nimport { resolveActionSource } from './action-source';\nimport { googleClickIds } from './click-ids';\n\nconst ENDPOINT = 'https://datamanager.googleapis.com/v1/events:ingest';\n\n/**\n * Event name → conversion action id, mirroring `LinkedinConversionConfig`: only configured\n * events upload, everything else is skipped silently. In the hybrid setup this is the id of\n * the SAME conversion action the gtag tag reports to.\n */\nexport type GoogleAdsConversionConfig = Record<Lowercase<string>, number | string>;\n\nexport interface GoogleAdsAuth {\n /** OAuth2 access token with the `datamanager` scope. Short-lived; the caller refreshes it. */\n accessToken: string;\n /** The Google Ads account the conversion actions live in. Dashes are tolerated: '123-456-7890'. */\n operatingAccountId: string;\n /** The manager account the OAuth user accesses through, when access is delegated. */\n loginAccountId?: string;\n}\n\n/**\n * EEA/UK/CH consent, applied request-wide. Google drops EEA conversions without granted\n * `adUserData` from bidding, so a host with consent signals should pass them.\n */\nexport interface GoogleAdsConsent {\n adUserData?: 'CONSENT_GRANTED' | 'CONSENT_DENIED' | 'CONSENT_STATUS_UNSPECIFIED';\n adPersonalization?: 'CONSENT_GRANTED' | 'CONSENT_DENIED' | 'CONSENT_STATUS_UNSPECIFIED';\n}\n\n/**\n * The kind of conversion action the events go to, which decides `eventSource`:\n * - `webpage` (default): the action the gtag tag reports to, as in the hybrid deployment this\n * module is built for. Its `eventSource` is optional and, when set, \"must be WEB\" — any other\n * value fails the request, and the request with it. Web events say `WEB`, others say nothing.\n * - `offline`: an action created for uploads (`UPLOAD_CLICKS`), where `eventSource` is required\n * and any value goes: `WEB`, `APP` or `OTHER` from the event's platform.\n * https://developers.google.com/data-manager/api/devguides/events/google-ads/online/send-events\n */\nexport type GoogleAdsActionType = 'webpage' | 'offline';\n\nexport interface GoogleAdsConversionsOptions {\n /** Validates the payload server-side without recording conversions. */\n validateOnly?: boolean;\n consent?: GoogleAdsConsent;\n /** The kind of conversion action `config` points at; `webpage` by default. */\n actionType?: GoogleAdsActionType;\n}\n\n/**\n * Google's email normalization is Meta's minus one wrinkle: for @gmail.com/@googlemail.com the\n * username's dots and everything from '+' on are removed; for every other domain they are kept.\n * All whitespace goes — \"leading, trailing and intermediate\".\n * https://developers.google.com/data-manager/api/devguides/concepts/formatting\n */\nexport function normalizeEmail(input: string): string {\n const email = input.replace(/\\s+/g, '').toLowerCase();\n const at = email.lastIndexOf('@');\n if (at === -1) return email;\n let username = email.slice(0, at);\n const domain = email.slice(at + 1);\n if (domain === 'gmail.com' || domain === 'googlemail.com') {\n username = username.replace(/\\./g, '').split('+', 1)[0] ?? '';\n }\n return `${username}@${domain}`;\n}\n\nconst sha256 = (value: string) => createHash('sha256').update(value).digest('hex');\n\nfunction normalizeCurrency(input: unknown): string {\n if (typeof input !== 'string') return 'USD';\n const currency = input.trim().toUpperCase();\n return /^[A-Z]{3}$/.test(currency) ? currency : 'USD';\n}\n\n/** At most 10 userIdentifiers per event, per the API's hard limit. */\nconst MAX_USER_IDENTIFIERS = 10;\n\n/** Hashes are hex strings, declared by `encoding: 'HEX'` on the request. */\nfunction getUserIdentifiers(data: UserProvidedData): Record<string, string>[] {\n const identifiers: Record<string, string>[] = [];\n const emails = Array.isArray(data.email) ? data.email : data.email ? [data.email] : [];\n for (const email of emails) {\n identifiers.push({ emailAddress: sha256(normalizeEmail(email)) });\n }\n const phones = Array.isArray(data.phone_number)\n ? data.phone_number\n : data.phone_number\n ? [data.phone_number]\n : [];\n for (const phone of phones) {\n // Phones are already E.164 by the schema ('+' then digits); hash after a defensive trim.\n identifiers.push({ phoneNumber: sha256(phone.trim()) });\n }\n return identifiers.slice(0, MAX_USER_IDENTIFIERS);\n}\n\n/** One entry of the `events` array. Field names are the REST (camelCase) spellings. */\nexport interface DataManagerEvent {\n destinationReferences: string[];\n transactionId: string;\n /** RFC 3339 — `created_at` as stored, unlike the legacy API's bespoke format. */\n eventTimestamp: string;\n /** Absent for a non-web event sent to a `webpage` action, which accepts `WEB` only. */\n eventSource?: 'WEB' | 'APP' | 'OTHER';\n conversionValue: number;\n currency: string;\n adIdentifiers?: { gclid?: string; gbraid?: string; wbraid?: string };\n userData?: { userIdentifiers: Record<string, string>[] };\n}\n\n/**\n * Builds one Event, or undefined when no conversion action is configured for the event's name.\n * The gclid goes with the gbraid when there are both — \"we recommend setting both the GCLID and\n * GBRAID\" — and otherwise one click id: gclid, else gbraid, else wbraid (nothing documents a\n * wbraid next to a gclid). https://developers.google.com/google-ads/api/docs/conversions/upload-clicks\n * Unlike\n * the legacy upload, an event with no click id at all is still worth sending when it carries\n * user identifiers — that is the enhanced-conversions match path.\n */\nexport function getDataManagerEvent(\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n event: TrackEvent<any>,\n config: GoogleAdsConversionConfig,\n data: UserProvidedData = {},\n actionType: GoogleAdsActionType = 'webpage'\n): DataManagerEvent | undefined {\n const action = config[event.name as Lowercase<string>];\n if (!action) return undefined;\n\n const source = resolveActionSource(event.platform);\n const dmEvent: DataManagerEvent = {\n destinationReferences: [String(action)],\n // The hybrid-mode match key against the gtag tag's transaction_id: same track() call feeds\n // both channels, so they agree by construction for purchase-shaped events. The event id\n // covers conversions with no natural order id — but the gtag tracker only sends a\n // transaction_id when the properties carry one, so on a HYBRID action a non-purchase event\n // reported by both channels never matches and counts twice. Attach such events to a\n // standalone (API-only) conversion action instead.\n transactionId:\n typeof event.properties?.transaction_id === 'string'\n ? event.properties.transaction_id\n : event.id,\n eventTimestamp: new Date(event.created_at).toISOString(),\n eventSource:\n source === 'web'\n ? 'WEB'\n : actionType === 'webpage'\n ? undefined\n : source === 'app'\n ? 'APP'\n : 'OTHER',\n // Both mandatory, like the LinkedIn sender's defaults: 0 USD is Google's own convention\n // for value-less goals. The API has no partial-failure mode, so a malformed currency would\n // cost the whole batch — anything that isn't a 3-letter code falls back instead.\n conversionValue: typeof event.properties?.value === 'number' ? event.properties.value : 0,\n currency: normalizeCurrency(event.properties?.currency),\n };\n\n const { gclid, gbraid, wbraid } = googleClickIds(event.tags);\n if (gclid) dmEvent.adIdentifiers = gbraid ? { gclid, gbraid } : { gclid };\n else if (gbraid) dmEvent.adIdentifiers = { gbraid };\n else if (wbraid) dmEvent.adIdentifiers = { wbraid };\n\n const userIdentifiers = getUserIdentifiers(data);\n if (userIdentifiers.length > 0) dmEvent.userData = { userIdentifiers };\n\n // With neither a click id nor an identifier Google has nothing to match on; skip.\n if (!dmEvent.adIdentifiers && !dmEvent.userData) return undefined;\n\n return dmEvent;\n}\n\nexport interface DataManagerResponse {\n requestId?: string;\n}\n\n/** The API takes at most 2000 events per request. */\nconst MAX_EVENTS_PER_REQUEST = 2000;\n\n/**\n * Uploads the configured conversions from a batch of events. Never throws: an unusable event\n * is skipped and a failed request is logged and swallowed, like every other sender here. The\n * Data Manager API has no partial-failure mode — a rejected request costs the whole batch, so\n * the builder is strict about only emitting events the API can accept. A batch beyond the\n * 2000-event request cap goes out as sequential requests; the first response is returned.\n */\nexport async function sendEvents(\n auth: GoogleAdsAuth,\n config: GoogleAdsConversionConfig,\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n events: TrackEvent<any>[],\n data: UserProvidedData = {},\n options: GoogleAdsConversionsOptions = {}\n): Promise<DataManagerResponse | undefined> {\n const dmEvents = events\n .filter((event) => !IGNORED_EVENTS.includes(event.name))\n .map((event) => getDataManagerEvent(event, config, data, options.actionType))\n .filter((dmEvent): dmEvent is DataManagerEvent => dmEvent !== undefined);\n if (dmEvents.length === 0) return undefined;\n\n const operatingAccount = {\n accountType: 'GOOGLE_ADS',\n accountId: auth.operatingAccountId.replace(/-/g, ''),\n };\n // One destination per conversion action present in the batch; each event points at its own\n // through destinationReferences, so mixed-action batches go out as one request.\n const loginAccount = auth.loginAccountId\n ? { accountType: 'GOOGLE_ADS', accountId: auth.loginAccountId.replace(/-/g, '') }\n : undefined;\n const actions = Array.from(new Set(dmEvents.flatMap((dmEvent) => dmEvent.destinationReferences)));\n const destinations = actions.map((action) => {\n const destination: Record<string, unknown> = {\n reference: action,\n operatingAccount,\n productDestinationId: action,\n };\n if (loginAccount) destination.loginAccount = loginAccount;\n return destination;\n });\n\n let firstResponse: DataManagerResponse | undefined;\n for (let offset = 0; offset < dmEvents.length; offset += MAX_EVENTS_PER_REQUEST) {\n const chunk = dmEvents.slice(offset, offset + MAX_EVENTS_PER_REQUEST);\n const body: Record<string, unknown> = {\n destinations,\n events: chunk,\n validateOnly: options.validateOnly ?? false,\n };\n if (chunk.some((dmEvent) => dmEvent.userData)) {\n body.encoding = 'HEX';\n }\n if (options.consent) {\n body.consent = options.consent;\n }\n\n try {\n const response = await fetch(ENDPOINT, {\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 ${auth.accessToken}`,\n },\n body: JSON.stringify(body),\n });\n if (response.ok) {\n firstResponse ??= (await response.json()) as DataManagerResponse;\n continue;\n }\n const { status } = response;\n const message = await response.text();\n console.error(`Failed to send Google Ads conversions, status: ${status}, body: ${message}`);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n console.error(`Failed to send Google Ads conversions, network error: ${message}`);\n }\n }\n return firstResponse;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+BA,MAAM,WAAW;;;;;;;AAoDjB,SAAgB,eAAe,OAAuB;CACpD,MAAM,QAAQ,MAAM,QAAQ,QAAQ,EAAE,CAAC,CAAC,YAAY;CACpD,MAAM,KAAK,MAAM,YAAY,GAAG;CAChC,IAAI,OAAO,IAAI,OAAO;CACtB,IAAI,WAAW,MAAM,MAAM,GAAG,EAAE;CAChC,MAAM,SAAS,MAAM,MAAM,KAAK,CAAC;CACjC,IAAI,WAAW,eAAe,WAAW,kBACvC,WAAW,SAAS,QAAQ,OAAO,EAAE,CAAC,CAAC,MAAM,KAAK,CAAC,CAAC,CAAC,MAAM;CAE7D,OAAO,GAAG,SAAS,GAAG;AACxB;AAEA,MAAM,UAAU,WAAA,GAAkBA,YAAAA,WAAAA,CAAW,QAAQ,CAAC,CAAC,OAAO,KAAK,CAAC,CAAC,OAAO,KAAK;AAEjF,SAAS,kBAAkB,OAAwB;CACjD,IAAI,OAAO,UAAU,UAAU,OAAO;CACtC,MAAM,WAAW,MAAM,KAAK,CAAC,CAAC,YAAY;CAC1C,OAAO,aAAa,KAAK,QAAQ,IAAI,WAAW;AAClD;;AAGA,MAAM,uBAAuB;;AAG7B,SAAS,mBAAmB,MAAkD;CAC5E,MAAM,cAAwC,CAAC;CAC/C,MAAM,SAAS,MAAM,QAAQ,KAAK,KAAK,IAAI,KAAK,QAAQ,KAAK,QAAQ,CAAC,KAAK,KAAK,IAAI,CAAC;CACrF,KAAK,MAAM,SAAS,QAClB,YAAY,KAAK,EAAE,cAAc,OAAO,eAAe,KAAK,CAAC,EAAE,CAAC;CAElE,MAAM,SAAS,MAAM,QAAQ,KAAK,YAAY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AM,SAAS,KAAK;IACvC;GACF;GACA,MAAM,EAAE,WAAW;GACnB,MAAM,UAAU,MAAM,SAAS,KAAK;GACpC,QAAQ,MAAM,kDAAkD,OAAO,UAAU,SAAS;EAC5F,SAAS,OAAO;GACd,MAAM,UAAU,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;GACrE,QAAQ,MAAM,yDAAyD,SAAS;EAClF;CACF;CACA,OAAO;AACT"}
1
+ {"version":3,"file":"google-data-manager.cjs","names":["createHash","resolveActionSource","googleClickIds","IGNORED_EVENTS","fetch","ConversionsApiError","conversionDestination"],"sources":["../../src/server/google-data-manager.ts"],"sourcesContent":["/**\n * Google Ads conversion sender over the Data Manager API (`events:ingest`) — Google's\n * counterpart to Meta's Conversions API, and the mandated successor to the Google Ads API's\n * `UploadClickConversions`, which stopped accepting new adopters on 2026-06-15. Same shape as\n * the other senders here: a pure per-event builder, a `sendEvents` that rejects on failure,\n * credentials in headers and never in a URL or an error.\n *\n * Google's recommended deployment is *hybrid* (\"boost your tag with additional data sources\"):\n * this upload attaches to the SAME conversion action the gtag tag reports to, matched by\n * `transactionId` — a matched pair collapses into one conversion with the server data winning,\n * an unmatched upload is a recovered conversion. Both channels here are fed from the same\n * `track()` call, so the ids agree by construction. `transactionId` is therefore required in\n * that mode; this sender always sends one (the event id when there is no natural order id).\n *\n * Auth is a plain OAuth2 access token with the `datamanager` scope — no Google Ads developer\n * token, no API Center approval. The caller exchanges its stored refresh token for the access\n * token (one POST to oauth2.googleapis.com) and refreshes it however it likes; this module\n * stays out of the OAuth business, exactly as it stays out of Meta's.\n *\n * https://developers.google.com/data-manager/api/reference/rest/v1/events/ingest\n * https://developers.google.com/data-manager/api/devguides/events/google-ads/offline/upgrade/field-mappings\n * https://support.google.com/google-ads/answer/16542291 (hybrid: \"boost your tag with\n * additional data sources\" — the transaction-id matching contract this sender relies on)\n */\nimport { createHash } from 'node:crypto';\nimport { fetch } from '@shware/utils';\nimport { IGNORED_EVENTS } from '../third-parties/ignored-events';\nimport type { TrackEvent, TrackName, UserProvidedData } from '../track/types';\nimport { resolveActionSource } from './action-source';\nimport { googleClickIds } from './click-ids';\nimport { ConversionsApiError } from './conversions-api-error';\nimport { type ConversionDestination, conversionDestination } from './setup-conversions';\n\nconst ENDPOINT = 'https://datamanager.googleapis.com/v1/events:ingest';\n\n/**\n * Event name → conversion action id, mirroring `LinkedinConversionConfig`: only configured\n * events upload, everything else is skipped silently. In the hybrid setup this is the id of\n * the SAME conversion action the gtag tag reports to. Keys are the names `track` accepts, so with\n * strict event names a typo or undeclared event is a compile error.\n */\nexport type GoogleAdsConversionConfig = { readonly [K in TrackName]?: number | string };\n\nexport interface GoogleAdsAuth {\n /** OAuth2 access token with the `datamanager` scope. Short-lived; the caller refreshes it. */\n accessToken: string;\n /** The Google Ads account the conversion actions live in. Dashes are tolerated: '123-456-7890'. */\n operatingAccountId: string;\n /** The manager account the OAuth user accesses through, when access is delegated. */\n loginAccountId?: string;\n}\n\n/**\n * EEA/UK/CH consent, applied request-wide. Google drops EEA conversions without granted\n * `adUserData` from bidding, so a host with consent signals should pass them.\n */\nexport interface GoogleAdsConsent {\n adUserData?: 'CONSENT_GRANTED' | 'CONSENT_DENIED' | 'CONSENT_STATUS_UNSPECIFIED';\n adPersonalization?: 'CONSENT_GRANTED' | 'CONSENT_DENIED' | 'CONSENT_STATUS_UNSPECIFIED';\n}\n\n/**\n * The kind of conversion action the events go to, which decides `eventSource`:\n * - `webpage` (default): the action the gtag tag reports to, as in the hybrid deployment this\n * module is built for. Its `eventSource` is optional and, when set, \"must be WEB\" — any other\n * value fails the request, and the request with it. Web events say `WEB`, others say nothing.\n * - `offline`: an action created for uploads (`UPLOAD_CLICKS`), where `eventSource` is required\n * and any value goes: `WEB`, `APP` or `OTHER` from the event's platform.\n * https://developers.google.com/data-manager/api/devguides/events/google-ads/online/send-events\n */\nexport type GoogleAdsActionType = 'webpage' | 'offline';\n\nexport interface GoogleAdsConversionsOptions {\n /** Validates the payload server-side without recording conversions. */\n validateOnly?: boolean;\n consent?: GoogleAdsConsent;\n /** The kind of conversion action `config` points at; `webpage` by default. */\n actionType?: GoogleAdsActionType;\n}\n\n/**\n * Google's email normalization is Meta's minus one wrinkle: for @gmail.com/@googlemail.com the\n * username's dots and everything from '+' on are removed; for every other domain they are kept.\n * All whitespace goes — \"leading, trailing and intermediate\".\n * https://developers.google.com/data-manager/api/devguides/concepts/formatting\n */\nexport function normalizeEmail(input: string): string {\n const email = input.replace(/\\s+/g, '').toLowerCase();\n const at = email.lastIndexOf('@');\n if (at === -1) return email;\n let username = email.slice(0, at);\n const domain = email.slice(at + 1);\n if (domain === 'gmail.com' || domain === 'googlemail.com') {\n username = username.replace(/\\./g, '').split('+', 1)[0] ?? '';\n }\n return `${username}@${domain}`;\n}\n\nconst sha256 = (value: string) => createHash('sha256').update(value).digest('hex');\n\nfunction normalizeCurrency(input: unknown): string {\n if (typeof input !== 'string') return 'USD';\n const currency = input.trim().toUpperCase();\n return /^[A-Z]{3}$/.test(currency) ? currency : 'USD';\n}\n\n/** At most 10 userIdentifiers per event, per the API's hard limit. */\nconst MAX_USER_IDENTIFIERS = 10;\n\n/** Hashes are hex strings, declared by `encoding: 'HEX'` on the request. */\nfunction getUserIdentifiers(data: UserProvidedData): Record<string, string>[] {\n const identifiers: Record<string, string>[] = [];\n const emails = Array.isArray(data.email) ? data.email : data.email ? [data.email] : [];\n for (const email of emails) {\n identifiers.push({ emailAddress: sha256(normalizeEmail(email)) });\n }\n const phones = Array.isArray(data.phone_number)\n ? data.phone_number\n : data.phone_number\n ? [data.phone_number]\n : [];\n for (const phone of phones) {\n // Phones are already E.164 by the schema ('+' then digits); hash after a defensive trim.\n identifiers.push({ phoneNumber: sha256(phone.trim()) });\n }\n return identifiers.slice(0, MAX_USER_IDENTIFIERS);\n}\n\n/** One entry of the `events` array. Field names are the REST (camelCase) spellings. */\nexport interface DataManagerEvent {\n destinationReferences: string[];\n transactionId: string;\n /** RFC 3339 — `created_at` as stored, unlike the legacy API's bespoke format. */\n eventTimestamp: string;\n /** Absent for a non-web event sent to a `webpage` action, which accepts `WEB` only. */\n eventSource?: 'WEB' | 'APP' | 'OTHER';\n conversionValue: number;\n currency: string;\n adIdentifiers?: { gclid?: string; gbraid?: string; wbraid?: string };\n userData?: { userIdentifiers: Record<string, string>[] };\n}\n\n/**\n * Builds one Event, or undefined when no conversion action is configured for the event's name.\n * The gclid goes with the gbraid when there are both — \"we recommend setting both the GCLID and\n * GBRAID\" — and otherwise one click id: gclid, else gbraid, else wbraid (nothing documents a\n * wbraid next to a gclid). https://developers.google.com/google-ads/api/docs/conversions/upload-clicks\n * Unlike\n * the legacy upload, an event with no click id at all is still worth sending when it carries\n * user identifiers — that is the enhanced-conversions match path.\n */\nexport function getDataManagerEvent(\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n event: TrackEvent<any>,\n config: GoogleAdsConversionConfig,\n data: UserProvidedData = {},\n actionType: GoogleAdsActionType = 'webpage'\n): DataManagerEvent | undefined {\n const action = config[event.name as TrackName];\n if (!action) return undefined;\n\n const source = resolveActionSource(event.platform);\n const dmEvent: DataManagerEvent = {\n destinationReferences: [String(action)],\n // The hybrid-mode match key against the gtag tag's transaction_id: same track() call feeds\n // both channels, so they agree by construction for purchase-shaped events. The event id\n // covers conversions with no natural order id — but the gtag tracker only sends a\n // transaction_id when the properties carry one, so on a HYBRID action a non-purchase event\n // reported by both channels never matches and counts twice. Attach such events to a\n // standalone (API-only) conversion action instead.\n transactionId:\n typeof event.properties?.transaction_id === 'string'\n ? event.properties.transaction_id\n : event.id,\n eventTimestamp: new Date(event.created_at).toISOString(),\n eventSource:\n source === 'web'\n ? 'WEB'\n : actionType === 'webpage'\n ? undefined\n : source === 'app'\n ? 'APP'\n : 'OTHER',\n // Both mandatory, like the LinkedIn sender's defaults: 0 USD is Google's own convention\n // for value-less goals. The API has no partial-failure mode, so a malformed currency would\n // cost the whole batch — anything that isn't a 3-letter code falls back instead.\n conversionValue: typeof event.properties?.value === 'number' ? event.properties.value : 0,\n currency: normalizeCurrency(event.properties?.currency),\n };\n\n const { gclid, gbraid, wbraid } = googleClickIds(event.tags);\n if (gclid) dmEvent.adIdentifiers = gbraid ? { gclid, gbraid } : { gclid };\n else if (gbraid) dmEvent.adIdentifiers = { gbraid };\n else if (wbraid) dmEvent.adIdentifiers = { wbraid };\n\n const userIdentifiers = getUserIdentifiers(data);\n if (userIdentifiers.length > 0) dmEvent.userData = { userIdentifiers };\n\n // With neither a click id nor an identifier Google has nothing to match on; skip.\n if (!dmEvent.adIdentifiers && !dmEvent.userData) return undefined;\n\n return dmEvent;\n}\n\nexport interface DataManagerResponse {\n requestId?: string;\n}\n\n/** The API takes at most 2000 events per request. */\nconst MAX_EVENTS_PER_REQUEST = 2000;\n\n/**\n * Uploads the configured conversions from a batch of events. An unusable event is skipped; a\n * failed request rejects (a `ConversionsApiError`, or the fetch error), as with every sender here,\n * and sends no further ones. The\n * Data Manager API has no partial-failure mode — a rejected request costs the whole batch, so\n * the builder is strict about only emitting events the API can accept. A batch beyond the\n * 2000-event request cap goes out as sequential requests; the first response is returned.\n */\nexport async function sendEvents(\n auth: GoogleAdsAuth,\n config: GoogleAdsConversionConfig,\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n events: TrackEvent<any>[],\n data: UserProvidedData = {},\n options: GoogleAdsConversionsOptions = {}\n): Promise<DataManagerResponse | undefined> {\n const dmEvents = events\n .filter((event) => !IGNORED_EVENTS.includes(event.name))\n .map((event) => getDataManagerEvent(event, config, data, options.actionType))\n .filter((dmEvent): dmEvent is DataManagerEvent => dmEvent !== undefined);\n if (dmEvents.length === 0) return undefined;\n\n const operatingAccount = {\n accountType: 'GOOGLE_ADS',\n accountId: auth.operatingAccountId.replace(/-/g, ''),\n };\n // One destination per conversion action present in the batch; each event points at its own\n // through destinationReferences, so mixed-action batches go out as one request.\n const loginAccount = auth.loginAccountId\n ? { accountType: 'GOOGLE_ADS', accountId: auth.loginAccountId.replace(/-/g, '') }\n : undefined;\n const actions = Array.from(new Set(dmEvents.flatMap((dmEvent) => dmEvent.destinationReferences)));\n const destinations = actions.map((action) => {\n const destination: Record<string, unknown> = {\n reference: action,\n operatingAccount,\n productDestinationId: action,\n };\n if (loginAccount) destination.loginAccount = loginAccount;\n return destination;\n });\n\n let firstResponse: DataManagerResponse | undefined;\n for (let offset = 0; offset < dmEvents.length; offset += MAX_EVENTS_PER_REQUEST) {\n const chunk = dmEvents.slice(offset, offset + MAX_EVENTS_PER_REQUEST);\n const body: Record<string, unknown> = {\n destinations,\n events: chunk,\n validateOnly: options.validateOnly ?? false,\n };\n if (chunk.some((dmEvent) => dmEvent.userData)) {\n body.encoding = 'HEX';\n }\n if (options.consent) {\n body.consent = options.consent;\n }\n\n const response = await fetch(ENDPOINT, {\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 ${auth.accessToken}`,\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('google', response.status, await response.text());\n }\n firstResponse ??= (await response.json()) as DataManagerResponse;\n }\n return firstResponse;\n}\n\n/** Google Ads through the Data Manager API: the events in `conversions`, each as its action. */\nexport function googleAdsConversions(\n options: GoogleAdsConversionsOptions & {\n auth: GoogleAdsAuth;\n conversions: GoogleAdsConversionConfig;\n }\n): ConversionDestination {\n return conversionDestination(\n (name) => options.conversions[name as TrackName] !== undefined,\n (events, data) => sendEvents(options.auth, options.conversions, events, data, options)\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiCA,MAAM,WAAW;;;;;;;AAqDjB,SAAgB,eAAe,OAAuB;CACpD,MAAM,QAAQ,MAAM,QAAQ,QAAQ,EAAE,CAAC,CAAC,YAAY;CACpD,MAAM,KAAK,MAAM,YAAY,GAAG;CAChC,IAA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s";
2
+ import { ConversionDestination } from "./setup-conversions.cjs";
2
3
  /**
3
4
  * Event name → conversion action id, mirroring `LinkedinConversionConfig`: only configured
4
5
  * events upload, everything else is skipped silently. In the hybrid setup this is the id of
5
- * the SAME conversion action the gtag tag reports to.
6
+ * the SAME conversion action the gtag tag reports to. Keys are the names `track` accepts, so with
7
+ * strict event names a typo or undeclared event is a compile error.
6
8
  */
7
- export type GoogleAdsConversionConfig = Record<Lowercase<string>, number | string>;
9
+ export type GoogleAdsConversionConfig = { readonly [K in TrackName]?: number | string; };
8
10
  export interface GoogleAdsAuth {
9
11
  /** OAuth2 access token with the `datamanager` scope. Short-lived; the caller refreshes it. */
10
12
  accessToken: string;
@@ -78,11 +80,17 @@ export interface DataManagerResponse {
78
80
  requestId?: string;
79
81
  }
80
82
  /**
81
- * Uploads the configured conversions from a batch of events. Never throws: an unusable event
82
- * is skipped and a failed request is logged and swallowed, like every other sender here. The
83
+ * Uploads the configured conversions from a batch of events. An unusable event is skipped; a
84
+ * failed request rejects (a `ConversionsApiError`, or the fetch error), as with every sender here,
85
+ * and sends no further ones. The
83
86
  * Data Manager API has no partial-failure mode — a rejected request costs the whole batch, so
84
87
  * the builder is strict about only emitting events the API can accept. A batch beyond the
85
88
  * 2000-event request cap goes out as sequential requests; the first response is returned.
86
89
  */
87
90
  export declare function sendEvents(auth: GoogleAdsAuth, config: GoogleAdsConversionConfig, events: TrackEvent<any>[], data?: UserProvidedData, options?: GoogleAdsConversionsOptions): Promise<DataManagerResponse | undefined>;
91
+ /** Google Ads through the Data Manager API: the events in `conversions`, each as its action. */
92
+ export declare function googleAdsConversions(options: GoogleAdsConversionsOptions & {
93
+ auth: GoogleAdsAuth;
94
+ conversions: GoogleAdsConversionConfig;
95
+ }): ConversionDestination;
88
96
  //# sourceMappingURL=google-data-manager.d.cts.map
@@ -1 +1 @@
1
- {"version":3,"file":"google-data-manager.d.cts","names":[],"sources":["../../src/server/google-data-manager.ts"],"mappings":";;;;;;YAsCY,4BAA4B,OAAO;iBAE9B;;EAEf;;EAEA;;EAEA;;;;;;iBAOe;EACf;EACA;;;;;;;;;;;YAYU;iBAEK;;EAEf;EACA,UAAU;;EAEV,aAAa;;;;;;;;wBASC,eAAe;;iBA2Cd;EACf;EACA;;EAEA;;EAEA;EACA;EACA;EACA;IAAkB;IAAgB;IAAiB;;EACnD;IAAa,iBAAiB;;;;;;;;;;;;wBAYhB,oBAEd,OAAO,iBACP,QAAQ,2BACR,OAAM,kBACN,aAAY,sBACX;iBA+Cc;EACf;;;;;;;;;wBAaoB,WACpB,MAAM,eACN,QAAQ,2BAER,QAAQ,mBACR,OAAM,kBACN,UAAS,8BACR,QAAQ"}
1
+ {"version":3,"file":"google-data-manager.d.cts","names":[],"sources":["../../src/server/google-data-manager.ts"],"mappings":";;;;;;;;YAyCY,wCAAwC,KAAK;iBAExC;;EAEf;;EAEA;;EAEA;;;;;;iBAOe;EACf;EACA;;;;;;;;;;;YAYU;iBAEK;;EAEf;EACA,UAAU;;EAEV,aAAa;;;;;;;;wBASC,eAAe;;iBA2Cd;EACf;EACA;;EAEA;;EAEA;EACA;EACA;EACA;IAAkB;IAAgB;IAAiB;;EACnD;IAAa,iBAAiB;;;;;;;;;;;;wBAYhB,oBAEd,OAAO,iBACP,QAAQ,2BACR,OAAM,kBACN,aAAY,sBACX;iBA+Cc;EACf;;;;;;;;;;wBAcoB,WACpB,MAAM,eACN,QAAQ,2BAER,QAAQ,mBACR,OAAM,kBACN,UAAS,8BACR,QAAQ;;wBAgEK,qBACd,SAAS;EACP,MAAM;EACN,aAAa;IAEd"}
@@ -1,10 +1,12 @@
1
- import { TrackEvent, UserProvidedData } from "../track/types.mjs";
1
+ import { TrackEvent, TrackName, UserProvidedData } from "../track/types.mjs";
2
+ import { ConversionDestination } from "./setup-conversions.mjs";
2
3
  /**
3
4
  * Event name → conversion action id, mirroring `LinkedinConversionConfig`: only configured
4
5
  * events upload, everything else is skipped silently. In the hybrid setup this is the id of
5
- * the SAME conversion action the gtag tag reports to.
6
+ * the SAME conversion action the gtag tag reports to. Keys are the names `track` accepts, so with
7
+ * strict event names a typo or undeclared event is a compile error.
6
8
  */
7
- export type GoogleAdsConversionConfig = Record<Lowercase<string>, number | string>;
9
+ export type GoogleAdsConversionConfig = { readonly [K in TrackName]?: number | string; };
8
10
  export interface GoogleAdsAuth {
9
11
  /** OAuth2 access token with the `datamanager` scope. Short-lived; the caller refreshes it. */
10
12
  accessToken: string;
@@ -78,11 +80,17 @@ export interface DataManagerResponse {
78
80
  requestId?: string;
79
81
  }
80
82
  /**
81
- * Uploads the configured conversions from a batch of events. Never throws: an unusable event
82
- * is skipped and a failed request is logged and swallowed, like every other sender here. The
83
+ * Uploads the configured conversions from a batch of events. An unusable event is skipped; a
84
+ * failed request rejects (a `ConversionsApiError`, or the fetch error), as with every sender here,
85
+ * and sends no further ones. The
83
86
  * Data Manager API has no partial-failure mode — a rejected request costs the whole batch, so
84
87
  * the builder is strict about only emitting events the API can accept. A batch beyond the
85
88
  * 2000-event request cap goes out as sequential requests; the first response is returned.
86
89
  */
87
90
  export declare function sendEvents(auth: GoogleAdsAuth, config: GoogleAdsConversionConfig, events: TrackEvent<any>[], data?: UserProvidedData, options?: GoogleAdsConversionsOptions): Promise<DataManagerResponse | undefined>;
91
+ /** Google Ads through the Data Manager API: the events in `conversions`, each as its action. */
92
+ export declare function googleAdsConversions(options: GoogleAdsConversionsOptions & {
93
+ auth: GoogleAdsAuth;
94
+ conversions: GoogleAdsConversionConfig;
95
+ }): ConversionDestination;
88
96
  //# sourceMappingURL=google-data-manager.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"google-data-manager.d.mts","names":[],"sources":["../../src/server/google-data-manager.ts"],"mappings":";;;;;;YAsCY,4BAA4B,OAAO;iBAE9B;;EAEf;;EAEA;;EAEA;;;;;;iBAOe;EACf;EACA;;;;;;;;;;;YAYU;iBAEK;;EAEf;EACA,UAAU;;EAEV,aAAa;;;;;;;;wBASC,eAAe;;iBA2Cd;EACf;EACA;;EAEA;;EAEA;EACA;EACA;EACA;IAAkB;IAAgB;IAAiB;;EACnD;IAAa,iBAAiB;;;;;;;;;;;;wBAYhB,oBAEd,OAAO,iBACP,QAAQ,2BACR,OAAM,kBACN,aAAY,sBACX;iBA+Cc;EACf;;;;;;;;;wBAaoB,WACpB,MAAM,eACN,QAAQ,2BAER,QAAQ,mBACR,OAAM,kBACN,UAAS,8BACR,QAAQ"}
1
+ {"version":3,"file":"google-data-manager.d.mts","names":[],"sources":["../../src/server/google-data-manager.ts"],"mappings":";;;;;;;;YAyCY,wCAAwC,KAAK;iBAExC;;EAEf;;EAEA;;EAEA;;;;;;iBAOe;EACf;EACA;;;;;;;;;;;YAYU;iBAEK;;EAEf;EACA,UAAU;;EAEV,aAAa;;;;;;;;wBASC,eAAe;;iBA2Cd;EACf;EACA;;EAEA;;EAEA;EACA;EACA;EACA;IAAkB;IAAgB;IAAiB;;EACnD;IAAa,iBAAiB;;;;;;;;;;;;wBAYhB,oBAEd,OAAO,iBACP,QAAQ,2BACR,OAAM,kBACN,aAAY,sBACX;iBA+Cc;EACf;;;;;;;;;;wBAcoB,WACpB,MAAM,eACN,QAAQ,2BAER,QAAQ,mBACR,OAAM,kBACN,UAAS,8BACR,QAAQ;;wBAgEK,qBACd,SAAS;EACP,MAAM;EACN,aAAa;IAEd"}
@@ -1,6 +1,8 @@
1
1
  import { IGNORED_EVENTS } from "../third-parties/ignored-events.mjs";
2
2
  import { resolveActionSource } from "./action-source.mjs";
3
3
  import { googleClickIds } from "./click-ids.mjs";
4
+ import { ConversionsApiError } from "./conversions-api-error.mjs";
5
+ import { conversionDestination } from "./setup-conversions.mjs";
4
6
  import { fetch } from "@shware/utils";
5
7
  import { createHash } from "node:crypto";
6
8
  // src/server/google-data-manager.ts
@@ -8,8 +10,8 @@ import { createHash } from "node:crypto";
8
10
  * Google Ads conversion sender over the Data Manager API (`events:ingest`) — Google's
9
11
  * counterpart to Meta's Conversions API, and the mandated successor to the Google Ads API's
10
12
  * `UploadClickConversions`, which stopped accepting new adopters on 2026-06-15. Same shape as
11
- * the other senders here: a pure per-event builder, a never-throws `sendEvents`, credentials
12
- * in headers and never in a URL or a log line.
13
+ * the other senders here: a pure per-event builder, a `sendEvents` that rejects on failure,
14
+ * credentials in headers and never in a URL or an error.
13
15
  *
14
16
  * Google's recommended deployment is *hybrid* ("boost your tag with additional data sources"):
15
17
  * this upload attaches to the SAME conversion action the gtag tag reports to, matched by
@@ -97,8 +99,9 @@ function getDataManagerEvent(event, config, data = {}, actionType = "webpage") {
97
99
  /** The API takes at most 2000 events per request. */
98
100
  const MAX_EVENTS_PER_REQUEST = 2e3;
99
101
  /**
100
- * Uploads the configured conversions from a batch of events. Never throws: an unusable event
101
- * is skipped and a failed request is logged and swallowed, like every other sender here. The
102
+ * Uploads the configured conversions from a batch of events. An unusable event is skipped; a
103
+ * failed request rejects (a `ConversionsApiError`, or the fetch error), as with every sender here,
104
+ * and sends no further ones. The
102
105
  * Data Manager API has no partial-failure mode — a rejected request costs the whole batch, so
103
106
  * the builder is strict about only emitting events the API can accept. A batch beyond the
104
107
  * 2000-event request cap goes out as sequential requests; the first response is returned.
@@ -133,31 +136,25 @@ async function sendEvents(auth, config, events, data = {}, options = {}) {
133
136
  };
134
137
  if (chunk.some((dmEvent) => dmEvent.userData)) body.encoding = "HEX";
135
138
  if (options.consent) body.consent = options.consent;
136
- try {
137
- const response = await fetch(ENDPOINT, {
138
- method: "POST",
139
- retries: 3,
140
- headers: {
141
- "Content-Type": "application/json",
142
- Accept: "application/json",
143
- Authorization: `Bearer ${auth.accessToken}`
144
- },
145
- body: JSON.stringify(body)
146
- });
147
- if (response.ok) {
148
- firstResponse ??= await response.json();
149
- continue;
150
- }
151
- const { status } = response;
152
- const message = await response.text();
153
- console.error(`Failed to send Google Ads conversions, status: ${status}, body: ${message}`);
154
- } catch (error) {
155
- const message = error instanceof Error ? error.message : String(error);
156
- console.error(`Failed to send Google Ads conversions, network error: ${message}`);
157
- }
139
+ const response = await fetch(ENDPOINT, {
140
+ method: "POST",
141
+ retries: 3,
142
+ headers: {
143
+ "Content-Type": "application/json",
144
+ Accept: "application/json",
145
+ Authorization: `Bearer ${auth.accessToken}`
146
+ },
147
+ body: JSON.stringify(body)
148
+ });
149
+ if (!response.ok) throw new ConversionsApiError("google", response.status, await response.text());
150
+ firstResponse ??= await response.json();
158
151
  }
159
152
  return firstResponse;
160
153
  }
161
- export { getDataManagerEvent, normalizeEmail, sendEvents };
154
+ /** Google Ads through the Data Manager API: the events in `conversions`, each as its action. */
155
+ function googleAdsConversions(options) {
156
+ return conversionDestination((name) => options.conversions[name] !== void 0, (events, data) => sendEvents(options.auth, options.conversions, events, data, options));
157
+ }
158
+ export { getDataManagerEvent, googleAdsConversions, normalizeEmail, sendEvents };
162
159
 
163
160
  //# sourceMappingURL=google-data-manager.mjs.map