@shware/analytics 15.0.1 → 16.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +164 -36
- package/dist/native/fbsdk.cjs +44 -1
- package/dist/native/fbsdk.cjs.map +1 -1
- package/dist/native/fbsdk.d.cts +23 -1
- package/dist/native/fbsdk.d.cts.map +1 -1
- package/dist/native/fbsdk.d.mts +23 -1
- package/dist/native/fbsdk.d.mts.map +1 -1
- package/dist/native/fbsdk.mjs +44 -3
- package/dist/native/fbsdk.mjs.map +1 -1
- package/dist/native/firebase.cjs +27 -0
- package/dist/native/firebase.cjs.map +1 -1
- package/dist/native/firebase.d.cts +11 -0
- package/dist/native/firebase.d.cts.map +1 -1
- package/dist/native/firebase.d.mts +11 -0
- package/dist/native/firebase.d.mts.map +1 -1
- package/dist/native/firebase.mjs +27 -2
- package/dist/native/firebase.mjs.map +1 -1
- package/dist/next/index.cjs +10 -123
- package/dist/next/index.cjs.map +1 -1
- package/dist/next/index.d.cts +2 -31
- package/dist/next/index.d.cts.map +1 -1
- package/dist/next/index.d.mts +2 -31
- package/dist/next/index.d.mts.map +1 -1
- package/dist/next/index.mjs +10 -123
- package/dist/next/index.mjs.map +1 -1
- package/dist/react/index.cjs +45 -0
- package/dist/react/index.cjs.map +1 -0
- package/dist/react/index.d.cts +15 -0
- package/dist/react/index.d.cts.map +1 -0
- package/dist/react/index.d.mts +15 -0
- package/dist/react/index.d.mts.map +1 -0
- package/dist/react/index.mjs +43 -0
- package/dist/react/index.mjs.map +1 -0
- package/dist/react/use-feature-flag.cjs +23 -0
- package/dist/react/use-feature-flag.cjs.map +1 -0
- package/dist/react/use-feature-flag.d.cts +10 -0
- package/dist/react/use-feature-flag.d.cts.map +1 -0
- package/dist/react/use-feature-flag.d.mts +10 -0
- package/dist/react/use-feature-flag.d.mts.map +1 -0
- package/dist/react/use-feature-flag.mjs +22 -0
- package/dist/react/use-feature-flag.mjs.map +1 -0
- package/dist/server/conversions-api-error.cjs +20 -0
- package/dist/server/conversions-api-error.cjs.map +1 -0
- package/dist/server/conversions-api-error.d.cts +17 -0
- package/dist/server/conversions-api-error.d.cts.map +1 -0
- package/dist/server/conversions-api-error.d.mts +17 -0
- package/dist/server/conversions-api-error.d.mts.map +1 -0
- package/dist/server/conversions-api-error.mjs +19 -0
- package/dist/server/conversions-api-error.mjs.map +1 -0
- package/dist/server/google-data-manager.cjs +24 -26
- package/dist/server/google-data-manager.cjs.map +1 -1
- package/dist/server/google-data-manager.d.cts +13 -5
- package/dist/server/google-data-manager.d.cts.map +1 -1
- package/dist/server/google-data-manager.d.mts +13 -5
- package/dist/server/google-data-manager.d.mts.map +1 -1
- package/dist/server/google-data-manager.mjs +24 -27
- package/dist/server/google-data-manager.mjs.map +1 -1
- package/dist/server/index.cjs +11 -0
- package/dist/server/index.d.cts +10 -7
- package/dist/server/index.d.mts +10 -7
- package/dist/server/index.mjs +9 -7
- package/dist/server/linkedin-conversions-api.cjs +29 -23
- package/dist/server/linkedin-conversions-api.cjs.map +1 -1
- package/dist/server/linkedin-conversions-api.d.cts +7 -2
- package/dist/server/linkedin-conversions-api.d.cts.map +1 -1
- package/dist/server/linkedin-conversions-api.d.mts +7 -2
- package/dist/server/linkedin-conversions-api.d.mts.map +1 -1
- package/dist/server/linkedin-conversions-api.mjs +29 -24
- package/dist/server/linkedin-conversions-api.mjs.map +1 -1
- package/dist/server/meta-capi.cjs +32 -31
- package/dist/server/meta-capi.cjs.map +1 -1
- package/dist/server/meta-capi.d.cts +12 -3
- package/dist/server/meta-capi.d.cts.map +1 -1
- package/dist/server/meta-capi.d.mts +12 -3
- package/dist/server/meta-capi.d.mts.map +1 -1
- package/dist/server/meta-capi.mjs +33 -33
- package/dist/server/meta-capi.mjs.map +1 -1
- package/dist/server/microsoft-conversions-api.cjs +33 -28
- package/dist/server/microsoft-conversions-api.cjs.map +1 -1
- package/dist/server/microsoft-conversions-api.d.cts +14 -2
- package/dist/server/microsoft-conversions-api.d.cts.map +1 -1
- package/dist/server/microsoft-conversions-api.d.mts +14 -2
- package/dist/server/microsoft-conversions-api.d.mts.map +1 -1
- package/dist/server/microsoft-conversions-api.mjs +33 -29
- package/dist/server/microsoft-conversions-api.mjs.map +1 -1
- package/dist/server/openai-conversions-api.cjs +20 -18
- package/dist/server/openai-conversions-api.cjs.map +1 -1
- package/dist/server/openai-conversions-api.d.cts +7 -0
- package/dist/server/openai-conversions-api.d.cts.map +1 -1
- package/dist/server/openai-conversions-api.d.mts +7 -0
- package/dist/server/openai-conversions-api.d.mts.map +1 -1
- package/dist/server/openai-conversions-api.mjs +21 -20
- package/dist/server/openai-conversions-api.mjs.map +1 -1
- package/dist/server/reddit-conversions-api.cjs +20 -18
- package/dist/server/reddit-conversions-api.cjs.map +1 -1
- package/dist/server/reddit-conversions-api.d.cts +8 -1
- package/dist/server/reddit-conversions-api.d.cts.map +1 -1
- package/dist/server/reddit-conversions-api.d.mts +8 -1
- package/dist/server/reddit-conversions-api.d.mts.map +1 -1
- package/dist/server/reddit-conversions-api.mjs +21 -20
- package/dist/server/reddit-conversions-api.mjs.map +1 -1
- package/dist/server/setup-conversions.cjs +62 -0
- package/dist/server/setup-conversions.cjs.map +1 -0
- package/dist/server/setup-conversions.d.cts +97 -0
- package/dist/server/setup-conversions.d.cts.map +1 -0
- package/dist/server/setup-conversions.d.mts +97 -0
- package/dist/server/setup-conversions.d.mts.map +1 -0
- package/dist/server/setup-conversions.mjs +60 -0
- package/dist/server/setup-conversions.mjs.map +1 -0
- package/dist/setup/index.cjs +4 -4
- package/dist/setup/index.cjs.map +1 -1
- package/dist/setup/index.d.cts +16 -6
- package/dist/setup/index.d.cts.map +1 -1
- package/dist/setup/index.d.mts +16 -6
- package/dist/setup/index.d.mts.map +1 -1
- package/dist/setup/index.mjs +4 -4
- package/dist/setup/index.mjs.map +1 -1
- package/dist/tanstack/index.cjs +0 -2
- package/dist/tanstack/index.d.cts +1 -2
- package/dist/tanstack/index.d.mts +1 -2
- package/dist/tanstack/index.mjs +1 -3
- package/dist/third-parties/analytics-props.cjs +28 -0
- package/dist/third-parties/analytics-props.cjs.map +1 -0
- package/dist/third-parties/analytics-props.d.cts +23 -0
- package/dist/third-parties/analytics-props.d.cts.map +1 -0
- package/dist/third-parties/analytics-props.d.mts +23 -0
- package/dist/third-parties/analytics-props.d.mts.map +1 -0
- package/dist/third-parties/analytics-props.mjs +26 -0
- package/dist/third-parties/analytics-props.mjs.map +1 -0
- package/dist/third-parties/google-analytics.cjs +32 -0
- package/dist/third-parties/google-analytics.cjs.map +1 -1
- package/dist/third-parties/google-analytics.d.cts +11 -1
- package/dist/third-parties/google-analytics.d.cts.map +1 -1
- package/dist/third-parties/google-analytics.d.mts +11 -1
- package/dist/third-parties/google-analytics.d.mts.map +1 -1
- package/dist/third-parties/google-analytics.mjs +32 -1
- package/dist/third-parties/google-analytics.mjs.map +1 -1
- package/dist/third-parties/index.cjs +16 -0
- package/dist/third-parties/index.d.cts +9 -7
- package/dist/third-parties/index.d.mts +9 -7
- package/dist/third-parties/index.mjs +9 -7
- package/dist/third-parties/integration.cjs +46 -0
- package/dist/third-parties/integration.cjs.map +1 -0
- package/dist/third-parties/integration.d.cts +61 -0
- package/dist/third-parties/integration.d.cts.map +1 -0
- package/dist/third-parties/integration.d.mts +61 -0
- package/dist/third-parties/integration.d.mts.map +1 -0
- package/dist/third-parties/integration.mjs +43 -0
- package/dist/third-parties/integration.mjs.map +1 -0
- package/dist/third-parties/linkedin-insight-tag.cjs +29 -0
- package/dist/third-parties/linkedin-insight-tag.cjs.map +1 -1
- package/dist/third-parties/linkedin-insight-tag.d.cts +14 -8
- package/dist/third-parties/linkedin-insight-tag.d.cts.map +1 -1
- package/dist/third-parties/linkedin-insight-tag.d.mts +14 -8
- package/dist/third-parties/linkedin-insight-tag.d.mts.map +1 -1
- package/dist/third-parties/linkedin-insight-tag.mjs +29 -1
- package/dist/third-parties/linkedin-insight-tag.mjs.map +1 -1
- package/dist/third-parties/meta-pixel.cjs +32 -0
- package/dist/third-parties/meta-pixel.cjs.map +1 -1
- package/dist/third-parties/meta-pixel.d.cts +7 -0
- package/dist/third-parties/meta-pixel.d.cts.map +1 -1
- package/dist/third-parties/meta-pixel.d.mts +7 -0
- package/dist/third-parties/meta-pixel.d.mts.map +1 -1
- package/dist/third-parties/meta-pixel.mjs +33 -2
- package/dist/third-parties/meta-pixel.mjs.map +1 -1
- package/dist/third-parties/microsoft-uet.cjs +54 -0
- package/dist/third-parties/microsoft-uet.cjs.map +1 -1
- package/dist/third-parties/microsoft-uet.d.cts +36 -0
- package/dist/third-parties/microsoft-uet.d.cts.map +1 -1
- package/dist/third-parties/microsoft-uet.d.mts +36 -0
- package/dist/third-parties/microsoft-uet.d.mts.map +1 -1
- package/dist/third-parties/microsoft-uet.mjs +52 -1
- package/dist/third-parties/microsoft-uet.mjs.map +1 -1
- package/dist/third-parties/openai-pixel.cjs +29 -0
- package/dist/third-parties/openai-pixel.cjs.map +1 -1
- package/dist/third-parties/openai-pixel.d.cts +7 -0
- package/dist/third-parties/openai-pixel.d.cts.map +1 -1
- package/dist/third-parties/openai-pixel.d.mts +7 -0
- package/dist/third-parties/openai-pixel.d.mts.map +1 -1
- package/dist/third-parties/openai-pixel.mjs +30 -2
- package/dist/third-parties/openai-pixel.mjs.map +1 -1
- package/dist/third-parties/posthog.cjs +97 -4
- package/dist/third-parties/posthog.cjs.map +1 -1
- package/dist/third-parties/posthog.d.cts +56 -1
- package/dist/third-parties/posthog.d.cts.map +1 -1
- package/dist/third-parties/posthog.d.mts +56 -1
- package/dist/third-parties/posthog.d.mts.map +1 -1
- package/dist/third-parties/posthog.mjs +91 -2
- package/dist/third-parties/posthog.mjs.map +1 -1
- package/dist/third-parties/reddit-pixel.cjs +30 -0
- package/dist/third-parties/reddit-pixel.cjs.map +1 -1
- package/dist/third-parties/reddit-pixel.d.cts +7 -0
- package/dist/third-parties/reddit-pixel.d.cts.map +1 -1
- package/dist/third-parties/reddit-pixel.d.mts +7 -0
- package/dist/third-parties/reddit-pixel.d.mts.map +1 -1
- package/dist/third-parties/reddit-pixel.mjs +31 -2
- package/dist/third-parties/reddit-pixel.mjs.map +1 -1
- package/dist/track/fbq.cjs +6 -1
- package/dist/track/fbq.cjs.map +1 -1
- package/dist/track/fbq.d.cts +2 -0
- package/dist/track/fbq.d.cts.map +1 -1
- package/dist/track/fbq.d.mts +2 -0
- package/dist/track/fbq.d.mts.map +1 -1
- package/dist/track/fbq.mjs +6 -2
- package/dist/track/fbq.mjs.map +1 -1
- package/dist/track/index.cjs +7 -7
- package/dist/track/index.cjs.map +1 -1
- package/dist/track/index.d.cts.map +1 -1
- package/dist/track/index.d.mts.map +1 -1
- package/dist/track/index.mjs +7 -7
- package/dist/track/index.mjs.map +1 -1
- package/dist/track/oaiq.cjs +5 -0
- package/dist/track/oaiq.cjs.map +1 -1
- package/dist/track/oaiq.d.cts +2 -0
- package/dist/track/oaiq.d.cts.map +1 -1
- package/dist/track/oaiq.d.mts +2 -0
- package/dist/track/oaiq.d.mts.map +1 -1
- package/dist/track/oaiq.mjs +5 -1
- package/dist/track/oaiq.mjs.map +1 -1
- package/dist/track/rdt.cjs +5 -0
- package/dist/track/rdt.cjs.map +1 -1
- package/dist/track/rdt.d.cts +2 -0
- package/dist/track/rdt.d.cts.map +1 -1
- package/dist/track/rdt.d.mts +2 -0
- package/dist/track/rdt.d.mts.map +1 -1
- package/dist/track/rdt.mjs +5 -1
- package/dist/track/rdt.mjs.map +1 -1
- package/dist/visitor/index.cjs +3 -3
- package/dist/visitor/index.cjs.map +1 -1
- package/dist/visitor/index.mjs +3 -3
- package/dist/visitor/index.mjs.map +1 -1
- package/package.json +11 -39
- package/dist/react-router/index.cjs +0 -160
- package/dist/react-router/index.cjs.map +0 -1
- package/dist/react-router/index.d.cts +0 -22
- package/dist/react-router/index.d.cts.map +0 -1
- package/dist/react-router/index.d.mts +0 -22
- package/dist/react-router/index.d.mts.map +0 -1
- package/dist/react-router/index.mjs +0 -159
- package/dist/react-router/index.mjs.map +0 -1
- package/dist/server/legacy.cjs +0 -3
- package/dist/server/legacy.d.cts +0 -2
- package/dist/server/legacy.d.mts +0 -2
- package/dist/server/legacy.mjs +0 -1
- package/dist/server/meta-conversions-api.cjs +0 -205
- package/dist/server/meta-conversions-api.cjs.map +0 -1
- package/dist/server/meta-conversions-api.d.cts +0 -8
- package/dist/server/meta-conversions-api.d.cts.map +0 -1
- package/dist/server/meta-conversions-api.d.mts +0 -8
- package/dist/server/meta-conversions-api.d.mts.map +0 -1
- package/dist/server/meta-conversions-api.mjs +0 -201
- package/dist/server/meta-conversions-api.mjs.map +0 -1
- package/dist/tanstack/analytics.cjs +0 -184
- package/dist/tanstack/analytics.cjs.map +0 -1
- package/dist/tanstack/analytics.d.cts +0 -33
- package/dist/tanstack/analytics.d.cts.map +0 -1
- package/dist/tanstack/analytics.d.mts +0 -33
- package/dist/tanstack/analytics.d.mts.map +0 -1
- package/dist/tanstack/analytics.mjs +0 -183
- package/dist/tanstack/analytics.mjs.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"openai-conversions-api.d.mts","names":[],"sources":["../../src/server/openai-conversions-api.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"openai-conversions-api.d.mts","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,8 +1,11 @@
|
|
|
1
1
|
import { IGNORED_EVENTS } from "../third-parties/ignored-events.mjs";
|
|
2
|
+
import { adEvents } from "../third-parties/integration.mjs";
|
|
2
3
|
import { resolveActionSource } from "./action-source.mjs";
|
|
3
4
|
import { openaiOppref } from "./click-ids.mjs";
|
|
5
|
+
import { ConversionsApiError } from "./conversions-api-error.mjs";
|
|
6
|
+
import { conversionDestination } from "./setup-conversions.mjs";
|
|
4
7
|
import { pageLocation } from "./page-location.mjs";
|
|
5
|
-
import { APP_EVENTS, NON_AD_EVENTS, mapOAIEvent, normalizeOAIName, normalizeOAIPhone, oaiCustomEventName } from "../track/oaiq.mjs";
|
|
8
|
+
import { APP_EVENTS, NON_AD_EVENTS, isStandardOAIEvent, mapOAIEvent, normalizeOAIName, normalizeOAIPhone, oaiCustomEventName } from "../track/oaiq.mjs";
|
|
6
9
|
import { fetch } from "@shware/utils";
|
|
7
10
|
import { createHash } from "node:crypto";
|
|
8
11
|
// src/server/openai-conversions-api.ts
|
|
@@ -80,25 +83,23 @@ async function sendEvents(apiKey, pixelId, events, data = {}, validateOnly = fal
|
|
|
80
83
|
}).map((event) => getServerEvent(event, data, actionSource)).filter((event) => event.type !== "custom" || event.custom_event_name !== void 0).filter((event) => !APP_EVENTS.includes(event.type) || event.action_source === "mobile_app")
|
|
81
84
|
};
|
|
82
85
|
if (dto.events.length === 0) return;
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
console.error("Failed to send OpenAI conversion, network error:", error);
|
|
100
|
-
}
|
|
86
|
+
const response = await fetch(`${ENDPOINT}?pid=${pixelId}`, {
|
|
87
|
+
method: "POST",
|
|
88
|
+
retries: 3,
|
|
89
|
+
headers: {
|
|
90
|
+
"Content-Type": "application/json",
|
|
91
|
+
Accept: "application/json",
|
|
92
|
+
Authorization: `Bearer ${apiKey}`
|
|
93
|
+
},
|
|
94
|
+
body: JSON.stringify(dto)
|
|
95
|
+
});
|
|
96
|
+
if (response.ok) return;
|
|
97
|
+
throw new ConversionsApiError("openai", response.status, await response.text());
|
|
98
|
+
}
|
|
99
|
+
/** OpenAI's Conversions API, sent the same events as `openaiAds`. */
|
|
100
|
+
function openaiConversions(options) {
|
|
101
|
+
return conversionDestination(adEvents(isStandardOAIEvent, options.customEvents), (events, data) => sendEvents(options.accessToken, options.pixelId, events, data, options.validateOnly));
|
|
101
102
|
}
|
|
102
|
-
export { getServerEvent, sendEvents };
|
|
103
|
+
export { getServerEvent, openaiConversions, sendEvents };
|
|
103
104
|
|
|
104
105
|
//# sourceMappingURL=openai-conversions-api.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"openai-conversions-api.mjs","names":[],"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,OAAO,WAAW,QAAQ,CAAC,CAAC,OAAO,KAAK,CAAC,CAAC,OAAO,KAAK;AACxD;AAEA,SAAS,gBACP,U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AAW,SAAS,MAAM,IAAa,KAAK,MAAM,kBAAkB,YAClF;CACJ;CAEA,IAAI,IAAI,OAAO,WAAW,GAAG;CAE7B,IAAI;EACF,MAAM,WAAW,MAAM,MAAM,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.mjs","names":[],"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.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AAM,UAAU;GACpD,OAAO,OAAO,oBAAoB,OAAO;EAC3C,CAAC,CAAC,CACD,KAAK,UAAU,eAAe,OAAO,MAAM,YAAY,CAAC,CAAC,CAEzD,QAAQ,UAAU,MAAM,SAAS,YAAY,MAAM,sBAAsB,KAAA,CAAS,CAAC,CAEnF,QACE,UAAU,CAAC,WAAW,SAAS,MAAM,IAAa,KAAK,MAAM,kBAAkB,YAClF;CACJ;CAEA,IAAI,IAAI,OAAO,WAAW,GAAG;CAE7B,MAAM,WAAW,MAAM,MAAM,GAAG,SAAS,OAAO,WAAW;EACzD,QAAQ;EAER,SAAS;EACT,SAAS;GACP,gBAAgB;GAChB,QAAQ;GACR,eAAe,UAAU;EAC3B;EACA,MAAM,KAAK,UAAU,GAAG;CAC1B,CAAC;CAED,IAAI,SAAS,IAAI;CACjB,MAAM,IAAI,oBAAoB,UAAU,SAAS,QAAQ,MAAM,SAAS,KAAK,CAAC;AAChF;;AAGA,SAAgB,kBACd,SACuB;CACvB,OAAO,sBAAsB,SAAS,oBAAoB,QAAQ,YAAY,IAAI,QAAQ,SACxF,WAAW,QAAQ,aAAa,QAAQ,SAAS,QAAQ,MAAM,QAAQ,YAAY,CACrF;AACF"}
|
|
@@ -1,8 +1,11 @@
|
|
|
1
1
|
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_utils_field = require("../utils/field.cjs");
|
|
4
|
+
const require_third_parties_integration = require("../third-parties/integration.cjs");
|
|
4
5
|
const require_server_action_source = require("./action-source.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
|
const require_track_rdt = require("../track/rdt.cjs");
|
|
8
11
|
let _shware_utils = require("@shware/utils");
|
|
@@ -51,26 +54,25 @@ async function sendEvents(accessToken, pixelId, events, data = {}, testId, actio
|
|
|
51
54
|
events: events.filter((event) => !require_third_parties_ignored_events.IGNORED_EVENTS.includes(event.name)).filter((event) => Date.now() - Date.parse(event.created_at) <= MAX_EVENT_AGE_MS).map((event) => getServerEvent(event, data, actionSource))
|
|
52
55
|
} };
|
|
53
56
|
if (dto.data.events.length === 0) return;
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
console.error("Failed to send Reddit conversion, network error:", error);
|
|
71
|
-
}
|
|
57
|
+
const response = await (0, _shware_utils.fetch)(`https://ads-api.reddit.com/api/v3/pixels/${pixelId}/conversion_events`, {
|
|
58
|
+
method: "POST",
|
|
59
|
+
retries: 3,
|
|
60
|
+
headers: {
|
|
61
|
+
"Content-Type": "application/json",
|
|
62
|
+
Accept: "application/json",
|
|
63
|
+
Authorization: `Bearer ${accessToken}`
|
|
64
|
+
},
|
|
65
|
+
body: JSON.stringify(dto)
|
|
66
|
+
});
|
|
67
|
+
if (response.ok) return;
|
|
68
|
+
throw new require_server_conversions_api_error.ConversionsApiError("reddit", response.status, await response.text());
|
|
69
|
+
}
|
|
70
|
+
/** Reddit's Conversions API, sent the same events as `redditAds`. */
|
|
71
|
+
function redditConversions(options) {
|
|
72
|
+
return require_server_setup_conversions.conversionDestination(require_third_parties_integration.adEvents(require_track_rdt.isStandardRDTEvent, options.customEvents), (events, data) => sendEvents(options.accessToken, options.pixelId, events, data, options.testId));
|
|
72
73
|
}
|
|
73
74
|
exports.getServerEvent = getServerEvent;
|
|
75
|
+
exports.redditConversions = redditConversions;
|
|
74
76
|
exports.sendEvents = sendEvents;
|
|
75
77
|
|
|
76
78
|
//# sourceMappingURL=reddit-conversions-api.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"reddit-conversions-api.cjs","names":["mapRDTEvent","resolveActionSource","redditClickId","pageLocation","mapServerStandardEvent","getFirst","redditUuid","IGNORED_EVENTS","fetch"],"sources":["../../src/server/reddit-conversions-api.ts"],"sourcesContent":["import { fetch } from '@shware/utils';\nimport { IGNORED_EVENTS } from '../third-parties/ignored-events';\nimport { type ServerStandardEvent
|
|
1
|
+
{"version":3,"file":"reddit-conversions-api.cjs","names":["mapRDTEvent","resolveActionSource","redditClickId","pageLocation","mapServerStandardEvent","getFirst","redditUuid","IGNORED_EVENTS","fetch","ConversionsApiError","conversionDestination","adEvents","isStandardRDTEvent"],"sources":["../../src/server/reddit-conversions-api.ts"],"sourcesContent":["import { fetch } from '@shware/utils';\nimport { IGNORED_EVENTS } from '../third-parties/ignored-events';\nimport { adEvents } from '../third-parties/integration';\nimport type { RedditAdsOptions } from '../third-parties/reddit-pixel';\nimport {\n type ServerStandardEvent,\n isStandardRDTEvent,\n mapRDTEvent,\n mapServerStandardEvent,\n} from '../track/rdt';\nimport type { TrackEvent, UserProvidedData } from '../track/types';\nimport { getFirst } from '../utils/field';\nimport { type EventActionSource, resolveActionSource } from './action-source';\nimport { redditClickId, redditUuid } from './click-ids';\nimport { ConversionsApiError } from './conversions-api-error';\nimport { pageLocation } from './page-location';\nimport { type ConversionDestination, conversionDestination } from './setup-conversions';\n\n/**\n * https://ads-api.reddit.com/docs/v3/operations/Post%20Conversion%20Events\n * https://business.reddithelp.com/s/article/map-a-catalog-to-a-signal-source\n */\nexport interface RedditEvent {\n /** Match keys: Share user identifiers to match conversions to a Reddit ad engagement. */\n click_id?: string;\n\n /** Unix epoch timestamp in milliseconds, event_at can't be older than seven days. */\n event_at: number;\n\n /**\n * Where the conversion happened. Pixel events are deduplicated only against `WEBSITE` ones.\n * https://business.reddithelp.com/s/article/Conversions-API#measure-impact-across-channels\n */\n action_source: 'WEBSITE' | 'APP' | 'PHYSICAL_STORE' | 'OTHER';\n\n /**\n * The page the event happened on, for `WEBSITE` events: Reddit reads the domain from it, and the\n * click id when `click_id` is missing.\n */\n event_source_url?: string;\n\n type: {\n tracking_type: ServerStandardEvent | 'CUSTOM';\n custom_event_name?: string;\n };\n\n /**\n * Event metadata\n * Share as much additional information about your conversion event as you'd like. If you're\n * using the Conversions API with the pixel, conversion_id is required for deduplication.\n */\n metadata?: {\n conversion_id?: string;\n currency?: string; // ISO 4217 3-letter currency code\n item_count?: number;\n value?: number;\n products?: { id: string; name?: string; category?: string }[];\n };\n\n user?: {\n email?: string;\n external_id?: string;\n ip_address?: string;\n phone_number?: string;\n user_agent?: string;\n\n /** The Identifier for Advertisers (IDFA) of the user's Apple device. */\n idfa?: string;\n\n /** The Android Advertising ID (AAID) of the user's Android device. */\n aaid?: string;\n /**\n * The value from the first-party Pixel _rdt_uuid cookie on your domain. Note that it is in\n * the {timestamp}.{uuid} format. You may use the full value or just the UUID portion.\n * Example: 1684189007728.7c73f2ae-a433-4d7b-9838-f467da98f48e\n */\n uuid?: string;\n\n screen_dimensions?: { width: number; height: number };\n\n /**\n * A structure of data processing options to specify the processing type for the event\n * https://business.reddithelp.com/s/article/Limited-Data-Use\n */\n data_processing_options?: {\n country: string;\n region: string;\n modes: string[] | ['LDU'];\n };\n };\n}\n\nexport interface CreateRedditEventDTO {\n data: { test_id?: string; events: RedditEvent[] };\n}\n\nexport function getServerEvent(\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n event: TrackEvent<any>,\n data: UserProvidedData,\n actionSource?: EventActionSource\n): RedditEvent {\n const { id, name, properties, tags, platform, created_at } = event;\n const [type, params] = mapRDTEvent(name, properties, id);\n // An offline conversion — in store, from a CRM, over the phone — is `OTHER` rather than\n // `PHYSICAL_STORE`, which only one of those is; so is an undeterminable platform.\n const source = resolveActionSource(platform, actionSource);\n\n return {\n click_id: redditClickId(tags),\n event_at: new Date(created_at).getTime(),\n action_source: source === 'web' ? 'WEBSITE' : source === 'app' ? 'APP' : 'OTHER',\n event_source_url: source === 'web' ? pageLocation(tags) : undefined,\n type: {\n tracking_type: type === 'Custom' ? 'CUSTOM' : mapServerStandardEvent(type),\n custom_event_name: type === 'Custom' ? params.customEventName : undefined,\n },\n metadata: {\n conversion_id: id,\n currency:\n 'currency' in params && typeof params.currency === 'string'\n ? params.currency.toUpperCase()\n : undefined,\n item_count:\n 'itemCount' in params && typeof params.itemCount === 'number'\n ? params.itemCount\n : undefined,\n value: 'value' in params && typeof params.value === 'number' ? params.value : undefined,\n products:\n 'products' in params && Array.isArray(params.products) && params.products.length > 0\n ? params.products\n : undefined,\n },\n user: {\n email: getFirst(data.email),\n external_id: data.user_id,\n ip_address: data.ip_address,\n phone_number: getFirst(data.phone_number),\n user_agent: data.user_agent,\n idfa: platform === 'ios' ? tags.advertising_id : undefined,\n aaid: platform === 'android' ? tags.advertising_id : undefined,\n uuid: redditUuid(tags),\n screen_dimensions:\n tags.screen_width && tags.screen_height\n ? { width: tags.screen_width, height: tags.screen_height }\n : undefined,\n },\n };\n}\n\n/** `event_at` \"can't be older than seven days\"; a minute's margin for the trip. */\nconst MAX_EVENT_AGE_MS = 7 * 24 * 60 * 60 * 1000 - 60 * 1000;\n\nexport async function sendEvents(\n accessToken: string,\n pixelId: string,\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n events: TrackEvent<any>[],\n data: UserProvidedData = {},\n testId?: string,\n actionSource?: EventActionSource\n) {\n const dto: CreateRedditEventDTO = {\n data: {\n test_id: testId,\n events: events\n .filter((event) => !IGNORED_EVENTS.includes(event.name))\n .filter((event) => Date.now() - Date.parse(event.created_at) <= MAX_EVENT_AGE_MS)\n .map((event) => getServerEvent(event, data, actionSource)),\n },\n };\n\n if (dto.data.events.length === 0) return;\n\n const response = await fetch(\n `https://ads-api.reddit.com/api/v3/pixels/${pixelId}/conversion_events`,\n {\n method: 'POST',\n // Retried although a POST: the platform deduplicates on the `conversion_id` each event carries.\n retries: 3,\n headers: {\n 'Content-Type': 'application/json',\n Accept: 'application/json',\n Authorization: `Bearer ${accessToken}`,\n },\n body: JSON.stringify(dto),\n }\n );\n if (response.ok) return;\n throw new ConversionsApiError('reddit', response.status, await response.text());\n}\n\n/** Reddit's Conversions API, sent the same events as `redditAds`. */\nexport function redditConversions(\n options: RedditAdsOptions & { accessToken: string; testId?: string }\n): ConversionDestination {\n return conversionDestination(adEvents(isStandardRDTEvent, options.customEvents), (events, data) =>\n sendEvents(options.accessToken, options.pixelId, events, data, options.testId)\n );\n}\n"],"mappings":";;;;;;;;;;;;AAgGA,SAAgB,eAEd,OACA,MACA,cACa;CACb,MAAM,EAAE,IAAI,MAAM,YAAY,MAAM,UAAU,eAAe;CAC7D,MAAM,CAAC,MAAM,UAAUA,kBAAAA,YAAY,MAAM,YAAY,EAAE;CAGvD,MAAM,SAASC,6BAAAA,oBAAoB,UAAU,YAAY;CAEzD,OAAO;EACL,UAAUC,yBAAAA,cAAc,IAAI;EAC5B,UAAU,IAAI,KAAK,UAAU,CAAC,CAAC,QAAQ;EACvC,eAAe,WAAW,QAAQ,YAAY,WAAW,QAAQ,QAAQ;EACzE,kBAAkB,WAAW,QAAQC,6BAAAA,aAAa,IAAI,IAAI,KAAA;EAC1D,MAAM;GACJ,eAAe,SAAS,WAAW,WAAWC,kBAAAA,uBAAuB,IAAI;GACzE,mBAAmB,SAAS,WAAW,OAAO,kBAAkB,KAAA;EAClE;EACA,UAAU;GACR,eAAe;GACf,UACE,cAAc,UAAU,OAAO,OAAO,aAAa,WAC/C,OAAO,SAAS,YAAY,IAC5B,KAAA;GACN,YACE,eAAe,UAAU,OAAO,OAAO,cAAc,WACjD,OAAO,YACP,KAAA;GACN,OAAO,WAAW,UAAU,OAAO,OAAO,UAAU,WAAW,OAAO,QAAQ,KAAA;GAC9E,UACE,cAAc,UAAU,MAAM,QAAQ,OAAO,QAAQ,KAAK,OAAO,SAAS,SAAS,IAC/E,OAAO,WACP,KAAA;EACR;EACA,MAAM;GACJ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,QAAQ,MAAM,CAC/E;AACF"}
|
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import { TrackEvent, UserProvidedData } from "../track/types.cjs";
|
|
2
|
-
import { ServerStandardEvent } from "../track/rdt.cjs";
|
|
3
2
|
import { EventActionSource } from "./action-source.cjs";
|
|
3
|
+
import { ConversionDestination } from "./setup-conversions.cjs";
|
|
4
|
+
import { ServerStandardEvent } from "../track/rdt.cjs";
|
|
5
|
+
import { RedditAdsOptions } from "../third-parties/reddit-pixel.cjs";
|
|
4
6
|
/**
|
|
5
7
|
* https://ads-api.reddit.com/docs/v3/operations/Post%20Conversion%20Events
|
|
6
8
|
* https://business.reddithelp.com/s/article/map-a-catalog-to-a-signal-source
|
|
@@ -79,4 +81,9 @@ export interface CreateRedditEventDTO {
|
|
|
79
81
|
}
|
|
80
82
|
export declare function getServerEvent(event: TrackEvent<any>, data: UserProvidedData, actionSource?: EventActionSource): RedditEvent;
|
|
81
83
|
export declare function sendEvents(accessToken: string, pixelId: string, events: TrackEvent<any>[], data?: UserProvidedData, testId?: string, actionSource?: EventActionSource): Promise<void>;
|
|
84
|
+
/** Reddit's Conversions API, sent the same events as `redditAds`. */
|
|
85
|
+
export declare function redditConversions(options: RedditAdsOptions & {
|
|
86
|
+
accessToken: string;
|
|
87
|
+
testId?: string;
|
|
88
|
+
}): ConversionDestination;
|
|
82
89
|
//# sourceMappingURL=reddit-conversions-api.d.cts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"reddit-conversions-api.d.cts","names":[],"sources":["../../src/server/reddit-conversions-api.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"reddit-conversions-api.d.cts","names":[],"sources":["../../src/server/reddit-conversions-api.ts"],"mappings":";;;;;;;;;iBAsBiB;;EAEf;;EAGA;;;;;EAMA;;;;;EAMA;EAEA;IACE,eAAe;IACf;;;;;;;EAQF;IACE;IACA;IACA;IACA;IACA;MAAa;MAAY;MAAe;;;EAG1C;IACE;IACA;IACA;IACA;IACA;;IAGA;;IAGA;;;;;;IAMA;IAEA;MAAsB;MAAe;;;;;;IAMrC;MACE;MACA;MACA;;;;iBAKW;EACf;IAAQ;IAAkB,QAAQ;;;wBAGpB,eAEd,OAAO,iBACP,MAAM,kBACN,eAAe,oBACd;wBAoDmB,WACpB,qBACA,iBAEA,QAAQ,mBACR,OAAM,kBACN,iBACA,eAAe,oBAAiB;;wBAiClB,kBACd,SAAS;EAAqB;EAAqB;IAClD"}
|
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import { TrackEvent, UserProvidedData } from "../track/types.mjs";
|
|
2
|
-
import { ServerStandardEvent } from "../track/rdt.mjs";
|
|
3
2
|
import { EventActionSource } from "./action-source.mjs";
|
|
3
|
+
import { ConversionDestination } from "./setup-conversions.mjs";
|
|
4
|
+
import { ServerStandardEvent } from "../track/rdt.mjs";
|
|
5
|
+
import { RedditAdsOptions } from "../third-parties/reddit-pixel.mjs";
|
|
4
6
|
/**
|
|
5
7
|
* https://ads-api.reddit.com/docs/v3/operations/Post%20Conversion%20Events
|
|
6
8
|
* https://business.reddithelp.com/s/article/map-a-catalog-to-a-signal-source
|
|
@@ -79,4 +81,9 @@ export interface CreateRedditEventDTO {
|
|
|
79
81
|
}
|
|
80
82
|
export declare function getServerEvent(event: TrackEvent<any>, data: UserProvidedData, actionSource?: EventActionSource): RedditEvent;
|
|
81
83
|
export declare function sendEvents(accessToken: string, pixelId: string, events: TrackEvent<any>[], data?: UserProvidedData, testId?: string, actionSource?: EventActionSource): Promise<void>;
|
|
84
|
+
/** Reddit's Conversions API, sent the same events as `redditAds`. */
|
|
85
|
+
export declare function redditConversions(options: RedditAdsOptions & {
|
|
86
|
+
accessToken: string;
|
|
87
|
+
testId?: string;
|
|
88
|
+
}): ConversionDestination;
|
|
82
89
|
//# sourceMappingURL=reddit-conversions-api.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"reddit-conversions-api.d.mts","names":[],"sources":["../../src/server/reddit-conversions-api.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"reddit-conversions-api.d.mts","names":[],"sources":["../../src/server/reddit-conversions-api.ts"],"mappings":";;;;;;;;;iBAsBiB;;EAEf;;EAGA;;;;;EAMA;;;;;EAMA;EAEA;IACE,eAAe;IACf;;;;;;;EAQF;IACE;IACA;IACA;IACA;IACA;MAAa;MAAY;MAAe;;;EAG1C;IACE;IACA;IACA;IACA;IACA;;IAGA;;IAGA;;;;;;IAMA;IAEA;MAAsB;MAAe;;;;;;IAMrC;MACE;MACA;MACA;;;;iBAKW;EACf;IAAQ;IAAkB,QAAQ;;;wBAGpB,eAEd,OAAO,iBACP,MAAM,kBACN,eAAe,oBACd;wBAoDmB,WACpB,qBACA,iBAEA,QAAQ,mBACR,OAAM,kBACN,iBACA,eAAe,oBAAiB;;wBAiClB,kBACd,SAAS;EAAqB;EAAqB;IAClD"}
|
|
@@ -1,9 +1,12 @@
|
|
|
1
1
|
import { IGNORED_EVENTS } from "../third-parties/ignored-events.mjs";
|
|
2
2
|
import { getFirst } from "../utils/field.mjs";
|
|
3
|
+
import { adEvents } from "../third-parties/integration.mjs";
|
|
3
4
|
import { resolveActionSource } from "./action-source.mjs";
|
|
4
5
|
import { redditClickId, redditUuid } 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
|
-
import { mapRDTEvent, mapServerStandardEvent } from "../track/rdt.mjs";
|
|
9
|
+
import { isStandardRDTEvent, mapRDTEvent, mapServerStandardEvent } from "../track/rdt.mjs";
|
|
7
10
|
import { fetch } from "@shware/utils";
|
|
8
11
|
// src/server/reddit-conversions-api.ts
|
|
9
12
|
function getServerEvent(event, data, actionSource) {
|
|
@@ -50,25 +53,23 @@ async function sendEvents(accessToken, pixelId, events, data = {}, testId, actio
|
|
|
50
53
|
events: events.filter((event) => !IGNORED_EVENTS.includes(event.name)).filter((event) => Date.now() - Date.parse(event.created_at) <= MAX_EVENT_AGE_MS).map((event) => getServerEvent(event, data, actionSource))
|
|
51
54
|
} };
|
|
52
55
|
if (dto.data.events.length === 0) return;
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
console.error("Failed to send Reddit conversion, network error:", error);
|
|
70
|
-
}
|
|
56
|
+
const response = await fetch(`https://ads-api.reddit.com/api/v3/pixels/${pixelId}/conversion_events`, {
|
|
57
|
+
method: "POST",
|
|
58
|
+
retries: 3,
|
|
59
|
+
headers: {
|
|
60
|
+
"Content-Type": "application/json",
|
|
61
|
+
Accept: "application/json",
|
|
62
|
+
Authorization: `Bearer ${accessToken}`
|
|
63
|
+
},
|
|
64
|
+
body: JSON.stringify(dto)
|
|
65
|
+
});
|
|
66
|
+
if (response.ok) return;
|
|
67
|
+
throw new ConversionsApiError("reddit", response.status, await response.text());
|
|
68
|
+
}
|
|
69
|
+
/** Reddit's Conversions API, sent the same events as `redditAds`. */
|
|
70
|
+
function redditConversions(options) {
|
|
71
|
+
return conversionDestination(adEvents(isStandardRDTEvent, options.customEvents), (events, data) => sendEvents(options.accessToken, options.pixelId, events, data, options.testId));
|
|
71
72
|
}
|
|
72
|
-
export { getServerEvent, sendEvents };
|
|
73
|
+
export { getServerEvent, redditConversions, sendEvents };
|
|
73
74
|
|
|
74
75
|
//# sourceMappingURL=reddit-conversions-api.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"reddit-conversions-api.mjs","names":[],"sources":["../../src/server/reddit-conversions-api.ts"],"sourcesContent":["import { fetch } from '@shware/utils';\nimport { IGNORED_EVENTS } from '../third-parties/ignored-events';\nimport { type ServerStandardEvent
|
|
1
|
+
{"version":3,"file":"reddit-conversions-api.mjs","names":[],"sources":["../../src/server/reddit-conversions-api.ts"],"sourcesContent":["import { fetch } from '@shware/utils';\nimport { IGNORED_EVENTS } from '../third-parties/ignored-events';\nimport { adEvents } from '../third-parties/integration';\nimport type { RedditAdsOptions } from '../third-parties/reddit-pixel';\nimport {\n type ServerStandardEvent,\n isStandardRDTEvent,\n mapRDTEvent,\n mapServerStandardEvent,\n} from '../track/rdt';\nimport type { TrackEvent, UserProvidedData } from '../track/types';\nimport { getFirst } from '../utils/field';\nimport { type EventActionSource, resolveActionSource } from './action-source';\nimport { redditClickId, redditUuid } from './click-ids';\nimport { ConversionsApiError } from './conversions-api-error';\nimport { pageLocation } from './page-location';\nimport { type ConversionDestination, conversionDestination } from './setup-conversions';\n\n/**\n * https://ads-api.reddit.com/docs/v3/operations/Post%20Conversion%20Events\n * https://business.reddithelp.com/s/article/map-a-catalog-to-a-signal-source\n */\nexport interface RedditEvent {\n /** Match keys: Share user identifiers to match conversions to a Reddit ad engagement. */\n click_id?: string;\n\n /** Unix epoch timestamp in milliseconds, event_at can't be older than seven days. */\n event_at: number;\n\n /**\n * Where the conversion happened. Pixel events are deduplicated only against `WEBSITE` ones.\n * https://business.reddithelp.com/s/article/Conversions-API#measure-impact-across-channels\n */\n action_source: 'WEBSITE' | 'APP' | 'PHYSICAL_STORE' | 'OTHER';\n\n /**\n * The page the event happened on, for `WEBSITE` events: Reddit reads the domain from it, and the\n * click id when `click_id` is missing.\n */\n event_source_url?: string;\n\n type: {\n tracking_type: ServerStandardEvent | 'CUSTOM';\n custom_event_name?: string;\n };\n\n /**\n * Event metadata\n * Share as much additional information about your conversion event as you'd like. If you're\n * using the Conversions API with the pixel, conversion_id is required for deduplication.\n */\n metadata?: {\n conversion_id?: string;\n currency?: string; // ISO 4217 3-letter currency code\n item_count?: number;\n value?: number;\n products?: { id: string; name?: string; category?: string }[];\n };\n\n user?: {\n email?: string;\n external_id?: string;\n ip_address?: string;\n phone_number?: string;\n user_agent?: string;\n\n /** The Identifier for Advertisers (IDFA) of the user's Apple device. */\n idfa?: string;\n\n /** The Android Advertising ID (AAID) of the user's Android device. */\n aaid?: string;\n /**\n * The value from the first-party Pixel _rdt_uuid cookie on your domain. Note that it is in\n * the {timestamp}.{uuid} format. You may use the full value or just the UUID portion.\n * Example: 1684189007728.7c73f2ae-a433-4d7b-9838-f467da98f48e\n */\n uuid?: string;\n\n screen_dimensions?: { width: number; height: number };\n\n /**\n * A structure of data processing options to specify the processing type for the event\n * https://business.reddithelp.com/s/article/Limited-Data-Use\n */\n data_processing_options?: {\n country: string;\n region: string;\n modes: string[] | ['LDU'];\n };\n };\n}\n\nexport interface CreateRedditEventDTO {\n data: { test_id?: string; events: RedditEvent[] };\n}\n\nexport function getServerEvent(\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n event: TrackEvent<any>,\n data: UserProvidedData,\n actionSource?: EventActionSource\n): RedditEvent {\n const { id, name, properties, tags, platform, created_at } = event;\n const [type, params] = mapRDTEvent(name, properties, id);\n // An offline conversion — in store, from a CRM, over the phone — is `OTHER` rather than\n // `PHYSICAL_STORE`, which only one of those is; so is an undeterminable platform.\n const source = resolveActionSource(platform, actionSource);\n\n return {\n click_id: redditClickId(tags),\n event_at: new Date(created_at).getTime(),\n action_source: source === 'web' ? 'WEBSITE' : source === 'app' ? 'APP' : 'OTHER',\n event_source_url: source === 'web' ? pageLocation(tags) : undefined,\n type: {\n tracking_type: type === 'Custom' ? 'CUSTOM' : mapServerStandardEvent(type),\n custom_event_name: type === 'Custom' ? params.customEventName : undefined,\n },\n metadata: {\n conversion_id: id,\n currency:\n 'currency' in params && typeof params.currency === 'string'\n ? params.currency.toUpperCase()\n : undefined,\n item_count:\n 'itemCount' in params && typeof params.itemCount === 'number'\n ? params.itemCount\n : undefined,\n value: 'value' in params && typeof params.value === 'number' ? params.value : undefined,\n products:\n 'products' in params && Array.isArray(params.products) && params.products.length > 0\n ? params.products\n : undefined,\n },\n user: {\n email: getFirst(data.email),\n external_id: data.user_id,\n ip_address: data.ip_address,\n phone_number: getFirst(data.phone_number),\n user_agent: data.user_agent,\n idfa: platform === 'ios' ? tags.advertising_id : undefined,\n aaid: platform === 'android' ? tags.advertising_id : undefined,\n uuid: redditUuid(tags),\n screen_dimensions:\n tags.screen_width && tags.screen_height\n ? { width: tags.screen_width, height: tags.screen_height }\n : undefined,\n },\n };\n}\n\n/** `event_at` \"can't be older than seven days\"; a minute's margin for the trip. */\nconst MAX_EVENT_AGE_MS = 7 * 24 * 60 * 60 * 1000 - 60 * 1000;\n\nexport async function sendEvents(\n accessToken: string,\n pixelId: string,\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n events: TrackEvent<any>[],\n data: UserProvidedData = {},\n testId?: string,\n actionSource?: EventActionSource\n) {\n const dto: CreateRedditEventDTO = {\n data: {\n test_id: testId,\n events: events\n .filter((event) => !IGNORED_EVENTS.includes(event.name))\n .filter((event) => Date.now() - Date.parse(event.created_at) <= MAX_EVENT_AGE_MS)\n .map((event) => getServerEvent(event, data, actionSource)),\n },\n };\n\n if (dto.data.events.length === 0) return;\n\n const response = await fetch(\n `https://ads-api.reddit.com/api/v3/pixels/${pixelId}/conversion_events`,\n {\n method: 'POST',\n // Retried although a POST: the platform deduplicates on the `conversion_id` each event carries.\n retries: 3,\n headers: {\n 'Content-Type': 'application/json',\n Accept: 'application/json',\n Authorization: `Bearer ${accessToken}`,\n },\n body: JSON.stringify(dto),\n }\n );\n if (response.ok) return;\n throw new ConversionsApiError('reddit', response.status, await response.text());\n}\n\n/** Reddit's Conversions API, sent the same events as `redditAds`. */\nexport function redditConversions(\n options: RedditAdsOptions & { accessToken: string; testId?: string }\n): ConversionDestination {\n return conversionDestination(adEvents(isStandardRDTEvent, options.customEvents), (events, data) =>\n sendEvents(options.accessToken, options.pixelId, events, data, options.testId)\n );\n}\n"],"mappings":";;;;;;;;;;;AAgGA,SAAgB,eAEd,OACA,MACA,cACa;CACb,MAAM,EAAE,IAA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,SAAS;EACT,QAAQ,OACL,QAAQ,UAAU,CAAC,eAAe,SAAS,MAAM,IAAI,CAAC,CAAC,CACvD,QAAQ,UAAU,KAAK,IAAI,IAAI,KAAK,MAAM,MAAM,UAAU,KAAK,gBAAgB,CAAC,CAChF,KAAK,UAAU,eAAe,OAAO,MAAM,YAAY,CAAC;CAC7D,EACF;CAEA,IAAI,IAAI,KAAK,OAAO,WAAW,GAAG;CAElC,MAAM,WAAW,MAAM,MACrB,4CAA4C,QAAQ,qBACpD;EACE,QAAQ;EAER,SAAS;EACT,SAAS;GACP,gBAAgB;GAChB,QAAQ;GACR,eAAe,UAAU;EAC3B;EACA,MAAM,KAAK,UAAU,GAAG;CAC1B,CACF;CACA,IAAI,SAAS,IAAI;CACjB,MAAM,IAAI,oBAAoB,UAAU,SAAS,QAAQ,MAAM,SAAS,KAAK,CAAC;AAChF;;AAGA,SAAgB,kBACd,SACuB;CACvB,OAAO,sBAAsB,SAAS,oBAAoB,QAAQ,YAAY,IAAI,QAAQ,SACxF,WAAW,QAAQ,aAAa,QAAQ,SAAS,QAAQ,MAAM,QAAQ,MAAM,CAC/E;AACF"}
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
+
// src/server/setup-conversions.ts
|
|
3
|
+
/**
|
|
4
|
+
* A destination that sends only the events `accepts` lets through, and makes no request when none
|
|
5
|
+
* is left: what each conversions API's factory (`metaConversions`, …) is built on.
|
|
6
|
+
*/
|
|
7
|
+
function conversionDestination(accepts, send) {
|
|
8
|
+
return { send: async (events, data) => {
|
|
9
|
+
const accepted = events.filter((event) => accepts(event.name));
|
|
10
|
+
if (accepted.length > 0) await send(accepted, data);
|
|
11
|
+
} };
|
|
12
|
+
}
|
|
13
|
+
function setupConversions(options) {
|
|
14
|
+
const { destinations, track: trackOptions } = options;
|
|
15
|
+
async function forward(events, data = {}) {
|
|
16
|
+
if (events.length === 0) return;
|
|
17
|
+
const settled = await Promise.allSettled(destinations.map((d) => Promise.resolve().then(() => d.send(events, data))));
|
|
18
|
+
const ids = events.map((event) => event.id).join(", ");
|
|
19
|
+
settled.forEach((outcome) => {
|
|
20
|
+
if (outcome.status === "rejected") console.error(`Conversions not sent, events: ${ids}`, outcome.reason);
|
|
21
|
+
});
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* Reports a server-only event; resolves with it as sent, or `undefined` when it was not: a
|
|
25
|
+
* user with no session, an event `store` had already stored, or a failure, which is logged.
|
|
26
|
+
*/
|
|
27
|
+
async function track({ resolveUser, store }, input) {
|
|
28
|
+
try {
|
|
29
|
+
const user = await resolveUser(input.userId);
|
|
30
|
+
if (!user) {
|
|
31
|
+
console.warn(`Conversion not reported, event: ${input.id}: no session for ${input.userId}`);
|
|
32
|
+
return;
|
|
33
|
+
}
|
|
34
|
+
const event = {
|
|
35
|
+
id: input.id,
|
|
36
|
+
name: input.name,
|
|
37
|
+
properties: input.properties,
|
|
38
|
+
tags: user.tags,
|
|
39
|
+
visitor_id: user.visitor_id,
|
|
40
|
+
session_id: user.session_id,
|
|
41
|
+
platform: user.platform,
|
|
42
|
+
environment: user.environment,
|
|
43
|
+
created_at: input.createdAt
|
|
44
|
+
};
|
|
45
|
+
if (!await store(event)) return void 0;
|
|
46
|
+
await forward([event], user.data);
|
|
47
|
+
return event;
|
|
48
|
+
} catch (e) {
|
|
49
|
+
console.error(`Conversion not reported, event: ${input.id}`, e);
|
|
50
|
+
return;
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
if (!trackOptions) return { forward };
|
|
54
|
+
return {
|
|
55
|
+
forward,
|
|
56
|
+
track: (input) => track(trackOptions, input)
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
exports.conversionDestination = conversionDestination;
|
|
60
|
+
exports.setupConversions = setupConversions;
|
|
61
|
+
|
|
62
|
+
//# sourceMappingURL=setup-conversions.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"setup-conversions.cjs","names":[],"sources":["../../src/server/setup-conversions.ts"],"sourcesContent":["import type {\n Environment,\n EventName,\n Platform,\n TrackEvent,\n TrackName,\n TrackProperties,\n TrackTags,\n UserProvidedData,\n} from '../track/types';\n\n// oxlint-disable-next-line @typescript-eslint/no-explicit-any\ntype AnyTrackEvent = TrackEvent<any>;\n\n/**\n * Where `setupConversions` sends events: an ad platform's conversions API, from its factory\n * (`metaConversions`, … next to each sender), or anything else the host forwards events to (a\n * CRM, its own workflows).\n *\n * `send` rejects when it fails, as the SDK's senders do: `setupConversions` logs the failure,\n * with the events' ids, and still sends to the others.\n */\nexport interface ConversionDestination {\n readonly send: (events: AnyTrackEvent[], data: UserProvidedData) => Promise<unknown>;\n}\n\n/**\n * A destination that sends only the events `accepts` lets through, and makes no request when none\n * is left: what each conversions API's factory (`metaConversions`, …) is built on.\n */\nexport function conversionDestination(\n accepts: (name: string) => boolean,\n send: (events: AnyTrackEvent[], data: UserProvidedData) => Promise<unknown>\n): ConversionDestination {\n return {\n send: async (events, data) => {\n const accepted = events.filter((event) => accepts(event.name));\n if (accepted.length > 0) await send(accepted, data);\n },\n };\n}\n\n/**\n * Who a server-only event is from, as the host knows them: what the ad platforms match a client\n * event on, read from the host's own records.\n *\n * - `tags`: the user's latest session's tags (their cookies — `_fbp`, `_rdt_uuid`, … — page\n * and user agent), with the click ids of the touch the conversion is attributed to over them.\n * - `visitor_id`, `session_id`, `platform`, `environment`: from that session. `platform` decides\n * each platform's action source (website or app), as for a client event.\n * - `data`: the user's identity (`email`, `user_id`, …), hashed by each sender.\n */\nexport interface ConversionUser {\n tags: TrackTags;\n visitor_id: string;\n session_id: string;\n platform: Platform;\n environment: Environment;\n data: UserProvidedData;\n}\n\n/**\n * An event the server reports on its own, with no client behind it: a webhook's purchase,\n * renewal or refund. `id` is the transaction id: `track.store` keeps a redelivered webhook from\n * being reported twice, and the platforms pair it with a browser event under the same id.\n */\nexport interface ServerEvent<T extends EventName = EventName> {\n id: string;\n name: TrackName<T>;\n /** The user it belongs to, handed to `track.resolveUser`. */\n userId: string;\n properties?: TrackProperties<T>;\n /** When it happened, as an ISO 8601 string. */\n createdAt: string;\n}\n\nexport interface ConversionsOptions {\n destinations: readonly ConversionDestination[];\n /**\n * How `track` completes and stores a server-only event. Without it `setupConversions` returns\n * only `forward`, for a host that only forwards client events.\n */\n track?: {\n /**\n * The user behind the event, read from the host's records (see `ConversionUser`);\n * `undefined` for one the host has no session of, whose event is then dropped.\n */\n resolveUser: (userId: string) => Promise<ConversionUser | undefined>;\n /**\n * Stores the event, e.g. in the events table, returning whether it was new: `track` sends\n * only an event it stored, so a webhook delivered again (its handler failed on something\n * else) is not reported twice — not every platform deduplicates a server event sent twice.\n */\n store: (event: AnyTrackEvent) => Promise<boolean>;\n };\n}\n\n/**\n * The server's counterpart of `setupAnalytics({ integrations })`: every destination configured\n * once, with the same per-platform options as the browser integrations, so the conversions API\n * and the tag report the same events.\n *\n * - `forward(events, data)`: the events a client sent, as stored, on to every destination.\n * - `track(event)`: an event the server reports on its own (a webhook's), completed by\n * `track.resolveUser`, stored with `track.store`, then forwarded.\n *\n * Neither throws, so reporting a conversion can never fail the request it runs in — a payment\n * webhook least of all, which its provider would then deliver again and again. A failure is\n * logged with the ids of the events it lost, for them to be found and sent later: a missed\n * conversion costs less than a duplicate one, or a webhook that keeps failing.\n */\nexport function setupConversions(\n options: ConversionsOptions & { track: NonNullable<ConversionsOptions['track']> }\n): {\n forward: Forward;\n track: Track;\n};\nexport function setupConversions(options: ConversionsOptions): { forward: Forward };\nexport function setupConversions(options: ConversionsOptions) {\n const { destinations, track: trackOptions } = options;\n\n async function forward(events: AnyTrackEvent[], data: UserProvidedData = {}) {\n if (events.length === 0) return;\n // Called inside a promise: a `send` that throws synchronously rejects there instead of\n // stopping the destinations after it.\n const settled = await Promise.allSettled(\n destinations.map((d) => Promise.resolve().then(() => d.send(events, data)))\n );\n const ids = events.map((event) => event.id).join(', ');\n settled.forEach((outcome) => {\n if (outcome.status === 'rejected') {\n console.error(`Conversions not sent, events: ${ids}`, outcome.reason);\n }\n });\n }\n\n /**\n * Reports a server-only event; resolves with it as sent, or `undefined` when it was not: a\n * user with no session, an event `store` had already stored, or a failure, which is logged.\n */\n async function track<T extends EventName>(\n { resolveUser, store }: NonNullable<ConversionsOptions['track']>,\n input: ServerEvent<T>\n ): Promise<TrackEvent<T> | undefined> {\n try {\n const user = await resolveUser(input.userId);\n if (!user) {\n console.warn(`Conversion not reported, event: ${input.id}: no session for ${input.userId}`);\n return undefined;\n }\n const event: TrackEvent<T> = {\n id: input.id,\n name: input.name,\n properties: input.properties,\n tags: user.tags,\n visitor_id: user.visitor_id,\n session_id: user.session_id,\n platform: user.platform,\n environment: user.environment,\n created_at: input.createdAt,\n };\n if (!(await store(event))) return undefined;\n await forward([event], user.data);\n return event;\n } catch (e: unknown) {\n console.error(`Conversion not reported, event: ${input.id}`, e);\n return undefined;\n }\n }\n\n if (!trackOptions) return { forward };\n return { forward, track: (input: ServerEvent) => track(trackOptions, input) };\n}\n\ntype Forward = (events: AnyTrackEvent[], data?: UserProvidedData) => Promise<void>;\ntype Track = <T extends EventName>(input: ServerEvent<T>) => Promise<TrackEvent<T> | undefined>;\n"],"mappings":";;;;;;AA8BA,SAAgB,sBACd,SACA,MACuB;CACvB,OAAO,EACL,MAAM,OAAO,QAAQ,SAAS;EAC5B,MAAM,WAAW,OAAO,QAAQ,UAAU,QAAQ,MAAM,IAAI,CAAC;EAC7D,IAAI,SAAS,SAAS,GAAG,MAAM,KAAK,UAAU,IAAI;CACpD,EACF;AACF;AA8EA,SAAgB,iBAAiB,SAA6B;CAC5D,MAAM,EAAE,cAAc,OAAO,iBAAiB;CAE9C,eAAe,QAAQ,QAAyB,OAAyB,CAAC,GAAG;EAC3E,IAAI,OAAO,WAAW,GAAG;EAGzB,MAAM,UAAU,MAAM,QAAQ,WAC5B,aAAa,KAAK,MAAM,QAAQ,QAAQ,CAAC,CAAC,WAAW,EAAE,KAAK,QAAQ,IAAI,CAAC,CAAC,CAC5E;EACA,MAAM,MAAM,OAAO,KAAK,UAAU,MAAM,EAAE,CAAC,CAAC,KAAK,IAAI;EACrD,QAAQ,SAAS,YAAY;GAC3B,IAAI,QAAQ,WAAW,YACrB,QAAQ,MAAM,iCAAiC,OAAO,QAAQ,MAAM;EAExE,CAAC;CACH;;;;;CAMA,eAAe,MACb,EAAE,aAAa,SACf,OACoC;EACpC,IAAI;GACF,MAAM,OAAO,MAAM,YAAY,MAAM,MAAM;GAC3C,IAAI,CAAC,MAAM;IACT,QAAQ,KAAK,mCAAmC,MAAM,GAAG,mBAAmB,MAAM,QAAQ;IAC1F;GACF;GACA,MAAM,QAAuB;IAC3B,IAAI,MAAM;IACV,MAAM,MAAM;IACZ,YAAY,MAAM;IAClB,MAAM,KAAK;IACX,YAAY,KAAK;IACjB,YAAY,KAAK;IACjB,UAAU,KAAK;IACf,aAAa,KAAK;IAClB,YAAY,MAAM;GACpB;GACA,IAAI,CAAE,MAAM,MAAM,KAAK,GAAI,OAAO,KAAA;GAClC,MAAM,QAAQ,CAAC,KAAK,GAAG,KAAK,IAAI;GAChC,OAAO;EACT,SAAS,GAAY;GACnB,QAAQ,MAAM,mCAAmC,MAAM,MAAM,CAAC;GAC9D;EACF;CACF;CAEA,IAAI,CAAC,cAAc,OAAO,EAAE,QAAQ;CACpC,OAAO;EAAE;EAAS,QAAQ,UAAuB,MAAM,cAAc,KAAK;CAAE;AAC9E"}
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
import { Environment, EventName, Platform, TrackEvent, TrackName, TrackProperties, TrackTags, UserProvidedData } from "../track/types.cjs";
|
|
2
|
+
type AnyTrackEvent = TrackEvent<any>;
|
|
3
|
+
/**
|
|
4
|
+
* Where `setupConversions` sends events: an ad platform's conversions API, from its factory
|
|
5
|
+
* (`metaConversions`, … next to each sender), or anything else the host forwards events to (a
|
|
6
|
+
* CRM, its own workflows).
|
|
7
|
+
*
|
|
8
|
+
* `send` rejects when it fails, as the SDK's senders do: `setupConversions` logs the failure,
|
|
9
|
+
* with the events' ids, and still sends to the others.
|
|
10
|
+
*/
|
|
11
|
+
export interface ConversionDestination {
|
|
12
|
+
readonly send: (events: AnyTrackEvent[], data: UserProvidedData) => Promise<unknown>;
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* A destination that sends only the events `accepts` lets through, and makes no request when none
|
|
16
|
+
* is left: what each conversions API's factory (`metaConversions`, …) is built on.
|
|
17
|
+
*/
|
|
18
|
+
export declare function conversionDestination(accepts: (name: string) => boolean, send: (events: AnyTrackEvent[], data: UserProvidedData) => Promise<unknown>): ConversionDestination;
|
|
19
|
+
/**
|
|
20
|
+
* Who a server-only event is from, as the host knows them: what the ad platforms match a client
|
|
21
|
+
* event on, read from the host's own records.
|
|
22
|
+
*
|
|
23
|
+
* - `tags`: the user's latest session's tags (their cookies — `_fbp`, `_rdt_uuid`, … — page
|
|
24
|
+
* and user agent), with the click ids of the touch the conversion is attributed to over them.
|
|
25
|
+
* - `visitor_id`, `session_id`, `platform`, `environment`: from that session. `platform` decides
|
|
26
|
+
* each platform's action source (website or app), as for a client event.
|
|
27
|
+
* - `data`: the user's identity (`email`, `user_id`, …), hashed by each sender.
|
|
28
|
+
*/
|
|
29
|
+
export interface ConversionUser {
|
|
30
|
+
tags: TrackTags;
|
|
31
|
+
visitor_id: string;
|
|
32
|
+
session_id: string;
|
|
33
|
+
platform: Platform;
|
|
34
|
+
environment: Environment;
|
|
35
|
+
data: UserProvidedData;
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* An event the server reports on its own, with no client behind it: a webhook's purchase,
|
|
39
|
+
* renewal or refund. `id` is the transaction id: `track.store` keeps a redelivered webhook from
|
|
40
|
+
* being reported twice, and the platforms pair it with a browser event under the same id.
|
|
41
|
+
*/
|
|
42
|
+
export interface ServerEvent<T extends EventName = EventName> {
|
|
43
|
+
id: string;
|
|
44
|
+
name: TrackName<T>;
|
|
45
|
+
/** The user it belongs to, handed to `track.resolveUser`. */
|
|
46
|
+
userId: string;
|
|
47
|
+
properties?: TrackProperties<T>;
|
|
48
|
+
/** When it happened, as an ISO 8601 string. */
|
|
49
|
+
createdAt: string;
|
|
50
|
+
}
|
|
51
|
+
export interface ConversionsOptions {
|
|
52
|
+
destinations: readonly ConversionDestination[];
|
|
53
|
+
/**
|
|
54
|
+
* How `track` completes and stores a server-only event. Without it `setupConversions` returns
|
|
55
|
+
* only `forward`, for a host that only forwards client events.
|
|
56
|
+
*/
|
|
57
|
+
track?: {
|
|
58
|
+
/**
|
|
59
|
+
* The user behind the event, read from the host's records (see `ConversionUser`);
|
|
60
|
+
* `undefined` for one the host has no session of, whose event is then dropped.
|
|
61
|
+
*/
|
|
62
|
+
resolveUser: (userId: string) => Promise<ConversionUser | undefined>;
|
|
63
|
+
/**
|
|
64
|
+
* Stores the event, e.g. in the events table, returning whether it was new: `track` sends
|
|
65
|
+
* only an event it stored, so a webhook delivered again (its handler failed on something
|
|
66
|
+
* else) is not reported twice — not every platform deduplicates a server event sent twice.
|
|
67
|
+
*/
|
|
68
|
+
store: (event: AnyTrackEvent) => Promise<boolean>;
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* The server's counterpart of `setupAnalytics({ integrations })`: every destination configured
|
|
73
|
+
* once, with the same per-platform options as the browser integrations, so the conversions API
|
|
74
|
+
* and the tag report the same events.
|
|
75
|
+
*
|
|
76
|
+
* - `forward(events, data)`: the events a client sent, as stored, on to every destination.
|
|
77
|
+
* - `track(event)`: an event the server reports on its own (a webhook's), completed by
|
|
78
|
+
* `track.resolveUser`, stored with `track.store`, then forwarded.
|
|
79
|
+
*
|
|
80
|
+
* Neither throws, so reporting a conversion can never fail the request it runs in — a payment
|
|
81
|
+
* webhook least of all, which its provider would then deliver again and again. A failure is
|
|
82
|
+
* logged with the ids of the events it lost, for them to be found and sent later: a missed
|
|
83
|
+
* conversion costs less than a duplicate one, or a webhook that keeps failing.
|
|
84
|
+
*/
|
|
85
|
+
export declare function setupConversions(options: ConversionsOptions & {
|
|
86
|
+
track: NonNullable<ConversionsOptions['track']>;
|
|
87
|
+
}): {
|
|
88
|
+
forward: Forward;
|
|
89
|
+
track: Track;
|
|
90
|
+
};
|
|
91
|
+
export declare function setupConversions(options: ConversionsOptions): {
|
|
92
|
+
forward: Forward;
|
|
93
|
+
};
|
|
94
|
+
type Forward = (events: AnyTrackEvent[], data?: UserProvidedData) => Promise<void>;
|
|
95
|
+
type Track = <T extends EventName>(input: ServerEvent<T>) => Promise<TrackEvent<T> | undefined>;
|
|
96
|
+
export {};
|
|
97
|
+
//# sourceMappingURL=setup-conversions.d.cts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"setup-conversions.d.cts","names":[],"sources":["../../src/server/setup-conversions.ts"],"mappings":";KAYK,gBAAgB;;;;;;;;;iBAUJ;WACN,OAAO,QAAQ,iBAAiB,MAAM,qBAAqB;;;;;;wBAOtD,sBACd,UAAU,0BACV,OAAO,QAAQ,iBAAiB,MAAM,qBAAqB,mBAC1D;;;;;;;;;;;iBAmBc;EACf,MAAM;EACN;EACA;EACA,UAAU;EACV,aAAa;EACb,MAAM;;;;;;;iBAQS,YAAY,UAAU,YAAY;EACjD;EACA,MAAM,UAAU;;EAEhB;EACA,aAAa,gBAAgB;;EAE7B;;iBAGe;EACf,uBAAuB;;;;;EAKvB;;;;;IAKE,cAAc,mBAAmB,QAAQ;;;;;;IAMzC,QAAQ,OAAO,kBAAkB;;;;;;;;;;;;;;;;;wBAkBrB,iBACd,SAAS;EAAuB,OAAO,YAAY;;EAEnD,SAAS;EACT,OAAO;;wBAEO,iBAAiB,SAAS;EAAuB,SAAS;;KAyDrE,WAAW,QAAQ,iBAAiB,OAAO,qBAAqB;KAChE,SAAS,UAAU,WAAW,OAAO,YAAY,OAAO,QAAQ,WAAW"}
|