@shware/analytics 7.5.0 → 7.6.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/dist/next/index.cjs +1 -1
- package/dist/next/index.mjs +1 -1
- package/dist/react-router/index.cjs +1 -1
- package/dist/react-router/index.mjs +1 -1
- package/dist/schema/index.cjs +7 -0
- package/dist/schema/index.cjs.map +1 -1
- package/dist/schema/index.d.cts +4 -0
- package/dist/schema/index.d.cts.map +1 -1
- package/dist/schema/index.d.mts +4 -0
- package/dist/schema/index.d.mts.map +1 -1
- package/dist/schema/index.mjs +7 -0
- package/dist/schema/index.mjs.map +1 -1
- package/dist/server/index.cjs +3 -0
- package/dist/server/index.d.cts +2 -1
- package/dist/server/index.d.mts +2 -1
- package/dist/server/index.mjs +2 -1
- package/dist/server/meta-capi.cjs +258 -0
- package/dist/server/meta-capi.cjs.map +1 -0
- package/dist/server/meta-capi.d.cts +66 -0
- package/dist/server/meta-capi.d.cts.map +1 -0
- package/dist/server/meta-capi.d.mts +66 -0
- package/dist/server/meta-capi.d.mts.map +1 -0
- package/dist/server/meta-capi.mjs +256 -0
- package/dist/server/meta-capi.mjs.map +1 -0
- package/dist/server/meta-conversions-api.cjs +4 -2
- package/dist/server/meta-conversions-api.cjs.map +1 -1
- package/dist/server/meta-conversions-api.d.cts.map +1 -1
- package/dist/server/meta-conversions-api.d.mts.map +1 -1
- package/dist/server/meta-conversions-api.mjs +4 -2
- package/dist/server/meta-conversions-api.mjs.map +1 -1
- package/dist/server/openai-conversions-api.cjs +2 -1
- package/dist/server/openai-conversions-api.cjs.map +1 -1
- package/dist/server/openai-conversions-api.d.cts.map +1 -1
- package/dist/server/openai-conversions-api.d.mts.map +1 -1
- package/dist/server/openai-conversions-api.mjs +2 -1
- package/dist/server/openai-conversions-api.mjs.map +1 -1
- package/dist/server/page-location.cjs +22 -0
- package/dist/server/page-location.cjs.map +1 -0
- package/dist/server/page-location.d.cts +19 -0
- package/dist/server/page-location.d.cts.map +1 -0
- package/dist/server/page-location.d.mts +19 -0
- package/dist/server/page-location.d.mts.map +1 -0
- package/dist/server/page-location.mjs +21 -0
- package/dist/server/page-location.mjs.map +1 -0
- package/dist/track/types.d.cts +6 -0
- package/dist/track/types.d.cts.map +1 -1
- package/dist/track/types.d.mts +6 -0
- package/dist/track/types.d.mts.map +1 -1
- package/package.json +2 -1
|
@@ -0,0 +1,256 @@
|
|
|
1
|
+
import { IGNORED_EVENTS } from "../third-parties/ignored-events.mjs";
|
|
2
|
+
import { formatFbc } from "../click-id/index.mjs";
|
|
3
|
+
import { resolveActionSource } from "./action-source.mjs";
|
|
4
|
+
import { mapFBEvent } from "../track/fbq.mjs";
|
|
5
|
+
import { pageLocation } from "./page-location.mjs";
|
|
6
|
+
import { fetch } from "@shware/utils";
|
|
7
|
+
import { createHash } from "node:crypto";
|
|
8
|
+
import { PII_DATA_TYPE, ParamBuilder } from "capi-param-builder-nodejs";
|
|
9
|
+
//#region src/server/meta-capi.ts
|
|
10
|
+
/**
|
|
11
|
+
* Meta Conversions API sender built on `capi-param-builder-nodejs` and plain `fetch`, replacing
|
|
12
|
+
* the 31MB `facebook-nodejs-business-sdk` with ~0.5MB of parameter building. `sendMetaEvents`
|
|
13
|
+
* stays exported and untouched; this module is the drop-in successor hosts opt into.
|
|
14
|
+
*
|
|
15
|
+
* The wire payload is byte-identical to what the business SDK's `ServerEvent.normalize()`
|
|
16
|
+
* produces — enforced by a differential test that runs both builders over the same events.
|
|
17
|
+
* Where the two libraries normalize differently (the business SDK keeps punctuation in names,
|
|
18
|
+
* spaces in multi-word last names, accents in cities; the param builder strips them per the
|
|
19
|
+
* current documented rules), this module follows the business SDK so that switching senders
|
|
20
|
+
* cannot change a single hash Meta receives. The param builder is used where the two provably
|
|
21
|
+
* agree — email, phone, gender, country — and its adoption-tracking appendix (`<hash>.<token>`)
|
|
22
|
+
* is stripped for the same reason.
|
|
23
|
+
*
|
|
24
|
+
* Two deliberate behavior differences from the business SDK, both on invalid input only:
|
|
25
|
+
* an invalid field (malformed email, non-ISO country, letters in a phone) is dropped from
|
|
26
|
+
* user_data instead of throwing inside `execute()` and costing the whole batch; an invalid
|
|
27
|
+
* currency is uppercased and forwarded instead of rejected. Valid input is unaffected.
|
|
28
|
+
*
|
|
29
|
+
* https://developers.facebook.com/docs/marketing-api/conversions-api/using-the-api
|
|
30
|
+
* https://developers.facebook.com/docs/marketing-api/conversions-api/parameters/customer-information-parameters
|
|
31
|
+
*/
|
|
32
|
+
/** Matches the Graph API version the pinned business SDK speaks (`FacebookAdsApi.VERSION`). */
|
|
33
|
+
const API_VERSION = "v24.0";
|
|
34
|
+
const USER_ASSIGNED_COUNTRIES = ["xk"];
|
|
35
|
+
function normalizeCountry(input) {
|
|
36
|
+
const country = input?.split(/[-_]/).at(0)?.toLowerCase();
|
|
37
|
+
if (!country) return void 0;
|
|
38
|
+
return USER_ASSIGNED_COUNTRIES.includes(country) ? void 0 : country;
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* Lazy for the same reason as the session and the token bucket (see setup/session.ts):
|
|
42
|
+
* Cloudflare Workers refuse some work in module scope, and nothing here is per-request state.
|
|
43
|
+
*/
|
|
44
|
+
let paramBuilder;
|
|
45
|
+
/**
|
|
46
|
+
* Normalize and hash one PII value through the param builder, stripped to the bare SHA-256 the
|
|
47
|
+
* business SDK sends: the builder appends a `.<language-token>` adoption marker that Meta's
|
|
48
|
+
* endpoint tolerates but the business SDK never produced. Pre-hashed input passes through, as
|
|
49
|
+
* it does in the business SDK.
|
|
50
|
+
*/
|
|
51
|
+
function pii(value, dataType) {
|
|
52
|
+
if (!value) return void 0;
|
|
53
|
+
return (paramBuilder ??= new ParamBuilder()).getNormalizedAndHashedPII(value, dataType)?.split(".").at(0) ?? void 0;
|
|
54
|
+
}
|
|
55
|
+
const SHA256_OR_MD5 = /^[a-f0-9]{64}$|^[a-f0-9]{32}$/;
|
|
56
|
+
/**
|
|
57
|
+
* The business SDK's `normalizeAndHash` for the fields where the param builder normalizes
|
|
58
|
+
* differently (names, city, state, zip): trim + lowercase, pass a pre-hashed value through,
|
|
59
|
+
* apply the field rule, SHA-256. Field rules are copied from `ServerSideUtils` verbatim so the
|
|
60
|
+
* differential test can hold the outputs equal.
|
|
61
|
+
*/
|
|
62
|
+
function hashed(input, rule) {
|
|
63
|
+
if (!input) return void 0;
|
|
64
|
+
const lowered = input.trim().toLowerCase();
|
|
65
|
+
if (!lowered) return void 0;
|
|
66
|
+
if (SHA256_OR_MD5.test(lowered)) return lowered;
|
|
67
|
+
const normalized = rule(lowered);
|
|
68
|
+
if (normalized === void 0) return void 0;
|
|
69
|
+
return createHash("sha256").update(normalized).digest("hex");
|
|
70
|
+
}
|
|
71
|
+
const nameRule = (v) => v;
|
|
72
|
+
const f5Rule = (v) => v.length <= 5 ? v : v.slice(0, 5);
|
|
73
|
+
const cityStateRule = (v) => v.replace(/[0-9\s().-]/g, "");
|
|
74
|
+
const zipRule = (v) => {
|
|
75
|
+
const zip = v.replace(/\s/g, "").split("-", 1)[0];
|
|
76
|
+
return zip.length < 2 ? void 0 : zip;
|
|
77
|
+
};
|
|
78
|
+
/**
|
|
79
|
+
* Every multi-value field is deduplicated after hashing, order preserved — the SDK runs each
|
|
80
|
+
* through `dedupArray` (a Set), `external_id` included.
|
|
81
|
+
*/
|
|
82
|
+
const dedupe = (hashes) => Array.from(new Set(hashes.filter((hash) => hash !== void 0)));
|
|
83
|
+
const list = (hashes) => {
|
|
84
|
+
const deduped = dedupe(hashes);
|
|
85
|
+
return deduped.length > 0 ? deduped : void 0;
|
|
86
|
+
};
|
|
87
|
+
function getUserData(tags, data, eventTimeMs) {
|
|
88
|
+
const userData = {};
|
|
89
|
+
if (data.email) {
|
|
90
|
+
const emails = Array.isArray(data.email) ? data.email : [data.email];
|
|
91
|
+
userData.em = list(emails.map((email) => pii(email, PII_DATA_TYPE.EMAIL)));
|
|
92
|
+
}
|
|
93
|
+
if (data.phone_number) {
|
|
94
|
+
const phones = Array.isArray(data.phone_number) ? data.phone_number : [data.phone_number];
|
|
95
|
+
userData.ph = list(phones.map((phone) => pii(phone, PII_DATA_TYPE.PHONE)));
|
|
96
|
+
}
|
|
97
|
+
if (data.gender === "female" || data.gender === "male") userData.ge = list([pii(data.gender === "female" ? "f" : "m", PII_DATA_TYPE.GENDER)]);
|
|
98
|
+
if (data.address) if (Array.isArray(data.address)) {
|
|
99
|
+
userData.fn = dedupe(data.address.map((a) => hashed(a.first_name, nameRule)));
|
|
100
|
+
userData.ln = dedupe(data.address.map((a) => hashed(a.last_name, nameRule)));
|
|
101
|
+
userData.ct = dedupe(data.address.map((a) => hashed(a.city, cityStateRule)));
|
|
102
|
+
userData.st = dedupe(data.address.map((a) => hashed(a.region, cityStateRule)));
|
|
103
|
+
userData.zp = dedupe(data.address.map((a) => hashed(a.postal_code, zipRule)));
|
|
104
|
+
userData.country = dedupe(data.address.map((a) => pii(normalizeCountry(a.country), PII_DATA_TYPE.COUNTRY)));
|
|
105
|
+
} else {
|
|
106
|
+
userData.fn = list([hashed(data.address.first_name, nameRule)]);
|
|
107
|
+
userData.ln = list([hashed(data.address.last_name, nameRule)]);
|
|
108
|
+
userData.ct = list([hashed(data.address.city, cityStateRule)]);
|
|
109
|
+
userData.st = list([hashed(data.address.region, cityStateRule)]);
|
|
110
|
+
userData.zp = list([hashed(data.address.postal_code, zipRule)]);
|
|
111
|
+
userData.country = list([pii(normalizeCountry(data.address.country), PII_DATA_TYPE.COUNTRY)]);
|
|
112
|
+
userData.f5first = hashed(data.address.first_name?.slice(0, 5), f5Rule);
|
|
113
|
+
userData.f5last = hashed(data.address.last_name?.slice(0, 5), f5Rule);
|
|
114
|
+
}
|
|
115
|
+
if (data.birthday) {
|
|
116
|
+
const { year, month, day } = data.birthday;
|
|
117
|
+
if (/^\d{4}$/.test(year.toString())) userData.doby = createHash("sha256").update(year.toString()).digest("hex");
|
|
118
|
+
if (month >= 1 && month <= 12) userData.dobm = createHash("sha256").update(month.toString().padStart(2, "0")).digest("hex");
|
|
119
|
+
if (day >= 1 && day <= 31) userData.dobd = createHash("sha256").update(day.toString().padStart(2, "0")).digest("hex");
|
|
120
|
+
}
|
|
121
|
+
if (data.user_id && data.user_id.length !== 0) userData.external_id = [data.user_id];
|
|
122
|
+
if (data.ip_address) userData.client_ip_address = data.ip_address;
|
|
123
|
+
if (data.user_agent) userData.client_user_agent = data.user_agent;
|
|
124
|
+
if (data.fb_login_id) userData.fb_login_id = data.fb_login_id;
|
|
125
|
+
if (data.fb_page_id) userData.page_id = data.fb_page_id;
|
|
126
|
+
if (tags.fbc) userData.fbc = tags.fbc;
|
|
127
|
+
else if (tags.fbclid) userData.fbc = formatFbc(tags.fbclid, eventTimeMs);
|
|
128
|
+
if (tags.fbp) userData.fbp = tags.fbp;
|
|
129
|
+
if (tags.advertising_id) userData.madid = tags.advertising_id;
|
|
130
|
+
if (tags.ip_address && typeof tags.ip_address === "string") userData.client_ip_address = tags.ip_address;
|
|
131
|
+
return userData;
|
|
132
|
+
}
|
|
133
|
+
const DELIVERY_CATEGORIES = [
|
|
134
|
+
"in_store",
|
|
135
|
+
"curbside",
|
|
136
|
+
"home_delivery"
|
|
137
|
+
];
|
|
138
|
+
function getCustomData({ name, properties }) {
|
|
139
|
+
const [_, _name, fbEventProperties] = mapFBEvent(name, properties);
|
|
140
|
+
const { value, currency, content_name, content_category, content_ids, contents, content_type, predicted_ltv, num_items, search_string, status, delivery_category, ...custom_properties } = fbEventProperties;
|
|
141
|
+
const customData = {};
|
|
142
|
+
if (value !== void 0 && value !== null && Number.isFinite(Number.parseFloat(String(value)))) customData.value = Number.parseFloat(String(value));
|
|
143
|
+
if (currency) customData.currency = currency.trim().toUpperCase().replace(/[^A-Z]/g, "");
|
|
144
|
+
if (content_name) customData.content_name = content_name;
|
|
145
|
+
if (content_category) customData.content_category = content_category;
|
|
146
|
+
if (content_ids) customData.content_ids = content_ids;
|
|
147
|
+
if (contents) customData.contents = contents.map((c) => {
|
|
148
|
+
const content = {};
|
|
149
|
+
if (c.id) content.id = c.id;
|
|
150
|
+
if (c.quantity) content.quantity = c.quantity;
|
|
151
|
+
if (c.item_price) content.item_price = c.item_price;
|
|
152
|
+
if (c.title) content.title = c.title;
|
|
153
|
+
if (c.description) content.description = c.description;
|
|
154
|
+
if (c.brand) content.brand = c.brand;
|
|
155
|
+
if (c.category) content.category = c.category;
|
|
156
|
+
const delivery = c.delivery_category?.trim().toLowerCase();
|
|
157
|
+
if (delivery && DELIVERY_CATEGORIES.includes(delivery)) content.delivery_category = delivery;
|
|
158
|
+
return content;
|
|
159
|
+
});
|
|
160
|
+
if (content_type) customData.content_type = content_type;
|
|
161
|
+
if (predicted_ltv) customData.predicted_ltv = predicted_ltv;
|
|
162
|
+
if (num_items) customData.num_items = num_items;
|
|
163
|
+
if (search_string) customData.search_string = search_string;
|
|
164
|
+
if (status) customData.status = status.toString();
|
|
165
|
+
const delivery = delivery_category?.trim().toLowerCase();
|
|
166
|
+
if (delivery && DELIVERY_CATEGORIES.includes(delivery)) customData.delivery_category = delivery;
|
|
167
|
+
return {
|
|
168
|
+
...customData,
|
|
169
|
+
...custom_properties
|
|
170
|
+
};
|
|
171
|
+
}
|
|
172
|
+
/**
|
|
173
|
+
* `extinfo` is keyed by field index. The business SDK builds the same object and leaves unset
|
|
174
|
+
* indexes out when it serializes; the documented 16-element array is what the Graph endpoint
|
|
175
|
+
* decodes this into. Indexes: 0 version, 1 package, 2 short version, 3 long version, 4 OS
|
|
176
|
+
* version, 5 device model, 6 locale, 9 screen width, 10 height, 11 density.
|
|
177
|
+
*/
|
|
178
|
+
function getAppData(tags, appPackageName) {
|
|
179
|
+
const extinfo = {};
|
|
180
|
+
if (tags.os_name === "iOS" || tags.os_name === "iPadOS") extinfo[0] = "i2";
|
|
181
|
+
else if (tags.os_name === "Android") extinfo[0] = "a2";
|
|
182
|
+
extinfo[1] = appPackageName;
|
|
183
|
+
const shortVersion = tags.release?.split(".").at(0);
|
|
184
|
+
if (shortVersion) extinfo[2] = shortVersion;
|
|
185
|
+
if (tags.release) extinfo[3] = tags.release;
|
|
186
|
+
if (tags.os_version) extinfo[4] = tags.os_version;
|
|
187
|
+
if (tags.device_model_id) extinfo[5] = tags.device_model_id;
|
|
188
|
+
if (tags.language) extinfo[6] = tags.language;
|
|
189
|
+
if (tags.screen_width) extinfo[9] = tags.screen_width;
|
|
190
|
+
if (tags.screen_height) extinfo[10] = tags.screen_height;
|
|
191
|
+
if (tags.device_pixel_ratio) extinfo[11] = tags.device_pixel_ratio.toString();
|
|
192
|
+
const appData = { extinfo };
|
|
193
|
+
if (tags.advertising_id) appData.advertiser_tracking_enabled = true;
|
|
194
|
+
if (tags.install_referrer) appData.install_referrer = tags.install_referrer;
|
|
195
|
+
return appData;
|
|
196
|
+
}
|
|
197
|
+
/**
|
|
198
|
+
* `action_source` is derived from `event.platform` alone: an OS platform is an app, `web` is a
|
|
199
|
+
* website, and everything else — including a backend-built offline conversion, which should
|
|
200
|
+
* declare `platform: 'unknown'` — lands in Meta's `other`, exactly where the business-SDK
|
|
201
|
+
* sender put an explicit `'offline'` too.
|
|
202
|
+
*/
|
|
203
|
+
function getCapiEvent(event, data, appPackageName) {
|
|
204
|
+
const eventTimeMs = new Date(event.created_at).getTime();
|
|
205
|
+
const [_, eventName] = mapFBEvent(event.name, event.properties);
|
|
206
|
+
const source = resolveActionSource(event.platform);
|
|
207
|
+
const capiEvent = {
|
|
208
|
+
event_name: eventName,
|
|
209
|
+
event_time: Math.round(eventTimeMs / 1e3),
|
|
210
|
+
event_id: event.tags.idempotency_key ?? event.id,
|
|
211
|
+
action_source: source === "app" ? "app" : source === "web" ? "website" : "other",
|
|
212
|
+
user_data: getUserData(event.tags, data, eventTimeMs),
|
|
213
|
+
custom_data: getCustomData(event)
|
|
214
|
+
};
|
|
215
|
+
if (source === "app" && appPackageName) capiEvent.app_data = getAppData(event.tags, appPackageName);
|
|
216
|
+
const eventSourceUrl = pageLocation(event.tags);
|
|
217
|
+
if (eventSourceUrl) capiEvent.event_source_url = eventSourceUrl;
|
|
218
|
+
return capiEvent;
|
|
219
|
+
}
|
|
220
|
+
/**
|
|
221
|
+
* The lightweight counterpart to `sendMetaEvents`: same filtering, same payload, same
|
|
222
|
+
* never-throws contract, minus the 31MB SDK. The token travels in the JSON body, never in the
|
|
223
|
+
* URL, and is never logged.
|
|
224
|
+
*/
|
|
225
|
+
async function sendMetaConversions(accessToken, pixelId, events, data = {}, options = {}) {
|
|
226
|
+
const capiEvents = events.filter((event) => !IGNORED_EVENTS.includes(event.name)).map((event) => getCapiEvent(event, data, options.appPackageName));
|
|
227
|
+
if (capiEvents.length === 0) return void 0;
|
|
228
|
+
const version = options.apiVersion ?? API_VERSION;
|
|
229
|
+
try {
|
|
230
|
+
const response = await fetch(`https://graph.facebook.com/${version}/${pixelId}/events`, {
|
|
231
|
+
method: "POST",
|
|
232
|
+
headers: {
|
|
233
|
+
"Content-Type": "application/json",
|
|
234
|
+
Accept: "application/json"
|
|
235
|
+
},
|
|
236
|
+
body: JSON.stringify({
|
|
237
|
+
data: capiEvents,
|
|
238
|
+
test_event_code: options.testEventCode,
|
|
239
|
+
access_token: accessToken
|
|
240
|
+
})
|
|
241
|
+
});
|
|
242
|
+
if (response.ok) return await response.json();
|
|
243
|
+
const { status } = response;
|
|
244
|
+
const message = await response.text();
|
|
245
|
+
console.error(`Failed to send Meta conversion, status: ${status}, body: ${message}`);
|
|
246
|
+
return;
|
|
247
|
+
} catch (error) {
|
|
248
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
249
|
+
console.error(`Failed to send Meta conversion, network error: ${message}`);
|
|
250
|
+
return;
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
//#endregion
|
|
254
|
+
export { getCapiEvent, sendMetaConversions };
|
|
255
|
+
|
|
256
|
+
//# sourceMappingURL=meta-capi.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"meta-capi.mjs","names":[],"sources":["../../src/server/meta-capi.ts"],"sourcesContent":["/**\n * Meta Conversions API sender built on `capi-param-builder-nodejs` and plain `fetch`, replacing\n * the 31MB `facebook-nodejs-business-sdk` with ~0.5MB of parameter building. `sendMetaEvents`\n * stays exported and untouched; this module is the drop-in successor hosts opt into.\n *\n * The wire payload is byte-identical to what the business SDK's `ServerEvent.normalize()`\n * produces — enforced by a differential test that runs both builders over the same events.\n * Where the two libraries normalize differently (the business SDK keeps punctuation in names,\n * spaces in multi-word last names, accents in cities; the param builder strips them per the\n * current documented rules), this module follows the business SDK so that switching senders\n * cannot change a single hash Meta receives. The param builder is used where the two provably\n * agree — email, phone, gender, country — and its adoption-tracking appendix (`<hash>.<token>`)\n * is stripped for the same reason.\n *\n * Two deliberate behavior differences from the business SDK, both on invalid input only:\n * an invalid field (malformed email, non-ISO country, letters in a phone) is dropped from\n * user_data instead of throwing inside `execute()` and costing the whole batch; an invalid\n * currency is uppercased and forwarded instead of rejected. Valid input is unaffected.\n *\n * https://developers.facebook.com/docs/marketing-api/conversions-api/using-the-api\n * https://developers.facebook.com/docs/marketing-api/conversions-api/parameters/customer-information-parameters\n */\nimport { createHash } from 'node:crypto';\nimport { fetch } from '@shware/utils';\nimport { PII_DATA_TYPE, ParamBuilder } from 'capi-param-builder-nodejs';\nimport { formatFbc } from '../click-id/index';\nimport { IGNORED_EVENTS } from '../third-parties/ignored-events';\nimport { mapFBEvent } from '../track/fbq';\nimport type { TrackEvent, TrackTags, UserProvidedData } from '../track/types';\nimport { resolveActionSource } from './action-source';\nimport { pageLocation } from './page-location';\n\n/** Matches the Graph API version the pinned business SDK speaks (`FacebookAdsApi.VERSION`). */\nconst API_VERSION = 'v24.0';\n\nconst USER_ASSIGNED_COUNTRIES: string[] = ['xk'];\nfunction normalizeCountry(input: string | undefined): string | undefined {\n const country = input?.split(/[-_]/).at(0)?.toLowerCase();\n if (!country) return undefined;\n return USER_ASSIGNED_COUNTRIES.includes(country) ? undefined : country;\n}\n\n/**\n * Lazy for the same reason as the session and the token bucket (see setup/session.ts):\n * Cloudflare Workers refuse some work in module scope, and nothing here is per-request state.\n */\nlet paramBuilder: ParamBuilder | undefined;\n\n/**\n * Normalize and hash one PII value through the param builder, stripped to the bare SHA-256 the\n * business SDK sends: the builder appends a `.<language-token>` adoption marker that Meta's\n * endpoint tolerates but the business SDK never produced. Pre-hashed input passes through, as\n * it does in the business SDK.\n */\nfunction pii(value: string | undefined, dataType: string): string | undefined {\n if (!value) return undefined;\n const built = (paramBuilder ??= new ParamBuilder()).getNormalizedAndHashedPII(value, dataType);\n return built?.split('.').at(0) ?? undefined;\n}\n\nconst SHA256_OR_MD5 = /^[a-f0-9]{64}$|^[a-f0-9]{32}$/;\n\n/**\n * The business SDK's `normalizeAndHash` for the fields where the param builder normalizes\n * differently (names, city, state, zip): trim + lowercase, pass a pre-hashed value through,\n * apply the field rule, SHA-256. Field rules are copied from `ServerSideUtils` verbatim so the\n * differential test can hold the outputs equal.\n */\nfunction hashed(\n input: string | undefined,\n rule: (lowered: string) => string | undefined\n): string | undefined {\n if (!input) return undefined;\n const lowered = input.trim().toLowerCase();\n if (!lowered) return undefined;\n if (SHA256_OR_MD5.test(lowered)) return lowered;\n const normalized = rule(lowered);\n if (normalized === undefined) return undefined;\n return createHash('sha256').update(normalized).digest('hex');\n}\n\nconst nameRule = (v: string) => v;\nconst f5Rule = (v: string) => (v.length <= 5 ? v : v.slice(0, 5));\nconst cityStateRule = (v: string) => v.replace(/[0-9\\s().-]/g, '');\nconst zipRule = (v: string) => {\n const zip = v.replace(/\\s/g, '').split('-', 1)[0];\n return zip.length < 2 ? undefined : zip;\n};\n\n/**\n * Every multi-value field is deduplicated after hashing, order preserved — the SDK runs each\n * through `dedupArray` (a Set), `external_id` included.\n */\nconst dedupe = (hashes: (string | undefined)[]) =>\n Array.from(new Set(hashes.filter((hash): hash is string => hash !== undefined)));\n\nconst list = (hashes: (string | undefined)[]) => {\n const deduped = dedupe(hashes);\n return deduped.length > 0 ? deduped : undefined;\n};\n\ninterface CapiUserData {\n em?: string[];\n ph?: string[];\n ge?: string[];\n fn?: string[];\n ln?: string[];\n ct?: string[];\n st?: string[];\n zp?: string[];\n country?: string[];\n external_id?: string[];\n client_ip_address?: string;\n client_user_agent?: string;\n fbc?: string;\n fbp?: string;\n fb_login_id?: string;\n page_id?: string;\n f5first?: string;\n f5last?: string;\n dobd?: string;\n dobm?: string;\n doby?: string;\n madid?: string;\n}\n\nfunction getUserData(tags: TrackTags, data: UserProvidedData, eventTimeMs: number): CapiUserData {\n const userData: CapiUserData = {};\n\n if (data.email) {\n const emails = Array.isArray(data.email) ? data.email : [data.email];\n userData.em = list(emails.map((email) => pii(email, PII_DATA_TYPE.EMAIL)));\n }\n if (data.phone_number) {\n const phones = Array.isArray(data.phone_number) ? data.phone_number : [data.phone_number];\n userData.ph = list(phones.map((phone) => pii(phone, PII_DATA_TYPE.PHONE)));\n }\n if (data.gender === 'female' || data.gender === 'male') {\n userData.ge = list([pii(data.gender === 'female' ? 'f' : 'm', PII_DATA_TYPE.GENDER)]);\n }\n if (data.address) {\n if (Array.isArray(data.address)) {\n // The SDK sets these lists unconditionally in the multi-address branch, so an all-empty\n // column still goes out as `[]` — kept for byte-equality with the current sender.\n userData.fn = dedupe(data.address.map((a) => hashed(a.first_name, nameRule)));\n userData.ln = dedupe(data.address.map((a) => hashed(a.last_name, nameRule)));\n userData.ct = dedupe(data.address.map((a) => hashed(a.city, cityStateRule)));\n userData.st = dedupe(data.address.map((a) => hashed(a.region, cityStateRule)));\n userData.zp = dedupe(data.address.map((a) => hashed(a.postal_code, zipRule)));\n userData.country = dedupe(\n data.address.map((a) => pii(normalizeCountry(a.country), PII_DATA_TYPE.COUNTRY))\n );\n } else {\n userData.fn = list([hashed(data.address.first_name, nameRule)]);\n userData.ln = list([hashed(data.address.last_name, nameRule)]);\n userData.ct = list([hashed(data.address.city, cityStateRule)]);\n userData.st = list([hashed(data.address.region, cityStateRule)]);\n userData.zp = list([hashed(data.address.postal_code, zipRule)]);\n userData.country = list([pii(normalizeCountry(data.address.country), PII_DATA_TYPE.COUNTRY)]);\n // The 5-character prefixes, exactly as the current sender builds them: sliced first, then\n // normalized. Only the single-address branch sets them, as before.\n userData.f5first = hashed(data.address.first_name?.slice(0, 5), f5Rule);\n userData.f5last = hashed(data.address.last_name?.slice(0, 5), f5Rule);\n }\n }\n if (data.birthday) {\n const { year, month, day } = data.birthday;\n if (/^\\d{4}$/.test(year.toString())) {\n userData.doby = createHash('sha256').update(year.toString()).digest('hex');\n }\n if (month >= 1 && month <= 12) {\n userData.dobm = createHash('sha256').update(month.toString().padStart(2, '0')).digest('hex');\n }\n if (day >= 1 && day <= 31) {\n userData.dobd = createHash('sha256').update(day.toString().padStart(2, '0')).digest('hex');\n }\n }\n if (data.user_id && data.user_id.length !== 0) {\n // Unhashed, as the business SDK sends it. Meta documents hashing as recommended, not\n // required; changing it here would break continuity with every event sent so far.\n userData.external_id = [data.user_id];\n }\n if (data.ip_address) {\n userData.client_ip_address = data.ip_address;\n }\n if (data.user_agent) {\n userData.client_user_agent = data.user_agent;\n }\n if (data.fb_login_id) {\n userData.fb_login_id = data.fb_login_id;\n }\n if (data.fb_page_id) {\n userData.page_id = data.fb_page_id;\n }\n\n if (tags.fbc) {\n userData.fbc = tags.fbc;\n } else if (tags.fbclid) {\n userData.fbc = formatFbc(tags.fbclid, eventTimeMs);\n }\n if (tags.fbp) {\n userData.fbp = tags.fbp;\n }\n if (tags.advertising_id) {\n userData.madid = tags.advertising_id;\n }\n if (tags.ip_address && typeof tags.ip_address === 'string') {\n userData.client_ip_address = tags.ip_address;\n }\n\n return userData;\n}\n\nconst DELIVERY_CATEGORIES = ['in_store', 'curbside', 'home_delivery'];\n\n// oxlint-disable-next-line @typescript-eslint/no-explicit-any\nfunction getCustomData({ name, properties }: TrackEvent<any>): Record<string, unknown> {\n const [_, _name, fbEventProperties] = mapFBEvent(name, properties);\n const {\n value,\n currency,\n content_name,\n content_category,\n content_ids,\n contents,\n content_type,\n predicted_ltv,\n num_items,\n search_string,\n status,\n delivery_category,\n ...custom_properties\n } = fbEventProperties;\n\n const customData: Record<string, unknown> = {};\n // oxlint-disable-next-line typescript/no-unnecessary-condition -- custom event properties may carry `value: null` at runtime despite the declared type\n if (value !== undefined && value !== null && Number.isFinite(Number.parseFloat(String(value)))) {\n customData.value = Number.parseFloat(String(value));\n }\n if (currency) {\n // The business SDK also validates against the ISO 4217 list and throws; here an unknown\n // code is forwarded uppercased rather than costing the batch.\n customData.currency = currency.trim().toUpperCase().replace(/[^A-Z]/g, '');\n }\n if (content_name) customData.content_name = content_name;\n if (content_category) customData.content_category = content_category;\n if (content_ids) customData.content_ids = content_ids;\n if (contents) {\n customData.contents = contents.map((c) => {\n const content: Record<string, unknown> = {};\n if (c.id) content.id = c.id;\n if (c.quantity) content.quantity = c.quantity;\n if (c.item_price) content.item_price = c.item_price;\n if (c.title) content.title = c.title;\n if (c.description) content.description = c.description;\n if (c.brand) content.brand = c.brand;\n if (c.category) content.category = c.category;\n const delivery = c.delivery_category?.trim().toLowerCase();\n if (delivery && DELIVERY_CATEGORIES.includes(delivery)) content.delivery_category = delivery;\n return content;\n });\n }\n if (content_type) customData.content_type = content_type;\n if (predicted_ltv) customData.predicted_ltv = predicted_ltv;\n if (num_items) customData.num_items = num_items;\n if (search_string) customData.search_string = search_string;\n if (status) customData.status = status.toString();\n const delivery = delivery_category?.trim().toLowerCase();\n if (delivery && DELIVERY_CATEGORIES.includes(delivery)) customData.delivery_category = delivery;\n\n return { ...customData, ...custom_properties };\n}\n\n/**\n * `extinfo` is keyed by field index. The business SDK builds the same object and leaves unset\n * indexes out when it serializes; the documented 16-element array is what the Graph endpoint\n * decodes this into. Indexes: 0 version, 1 package, 2 short version, 3 long version, 4 OS\n * version, 5 device model, 6 locale, 9 screen width, 10 height, 11 density.\n */\nfunction getAppData(tags: TrackTags, appPackageName: string): Record<string, unknown> {\n const extinfo: Record<number, string | number> = {};\n if (tags.os_name === 'iOS' || tags.os_name === 'iPadOS') {\n extinfo[0] = 'i2';\n } else if (tags.os_name === 'Android') {\n extinfo[0] = 'a2';\n }\n extinfo[1] = appPackageName;\n const shortVersion = tags.release?.split('.').at(0);\n if (shortVersion) extinfo[2] = shortVersion;\n if (tags.release) extinfo[3] = tags.release;\n if (tags.os_version) extinfo[4] = tags.os_version;\n if (tags.device_model_id) extinfo[5] = tags.device_model_id;\n if (tags.language) extinfo[6] = tags.language;\n if (tags.screen_width) extinfo[9] = tags.screen_width;\n if (tags.screen_height) extinfo[10] = tags.screen_height;\n if (tags.device_pixel_ratio) extinfo[11] = tags.device_pixel_ratio.toString();\n\n const appData: Record<string, unknown> = { extinfo };\n if (tags.advertising_id) appData.advertiser_tracking_enabled = true;\n if (tags.install_referrer) appData.install_referrer = tags.install_referrer;\n return appData;\n}\n\n/** One entry of the `data` array POSTed to `/{pixel_id}/events`. */\nexport interface CapiEvent {\n event_name: string;\n event_time: number;\n event_id: string;\n event_source_url?: string;\n action_source: 'app' | 'website' | 'other';\n user_data: CapiUserData;\n custom_data: Record<string, unknown>;\n app_data?: Record<string, unknown>;\n}\n\n/**\n * `action_source` is derived from `event.platform` alone: an OS platform is an app, `web` is a\n * website, and everything else — including a backend-built offline conversion, which should\n * declare `platform: 'unknown'` — lands in Meta's `other`, exactly where the business-SDK\n * sender put an explicit `'offline'` too.\n */\nexport function getCapiEvent(\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n event: TrackEvent<any>,\n data: UserProvidedData,\n appPackageName?: string\n): CapiEvent {\n const eventTimeMs = new Date(event.created_at).getTime();\n const [_, eventName] = mapFBEvent(event.name, event.properties);\n const source = resolveActionSource(event.platform);\n\n const capiEvent: CapiEvent = {\n event_name: eventName,\n event_time: Math.round(eventTimeMs / 1000),\n event_id: event.tags.idempotency_key ?? event.id,\n // `action_source` is required; an offline conversion and an undeterminable platform both\n // land in Meta's catch-all, exactly as in the business-SDK sender.\n action_source: source === 'app' ? 'app' : source === 'web' ? 'website' : 'other',\n user_data: getUserData(event.tags, data, eventTimeMs),\n custom_data: getCustomData(event),\n };\n if (source === 'app' && appPackageName) {\n capiEvent.app_data = getAppData(event.tags, appPackageName);\n }\n const eventSourceUrl = pageLocation(event.tags);\n if (eventSourceUrl) {\n capiEvent.event_source_url = eventSourceUrl;\n }\n return capiEvent;\n}\n\nexport interface MetaConversionsOptions {\n /** Attaches `app_data`/extinfo to events whose platform resolves to an app. */\n appPackageName?: string;\n /** Routes the batch to Events Manager's Test Events tab instead of production. */\n testEventCode?: string;\n /** Graph API version, e.g. 'v24.0'. */\n apiVersion?: string;\n}\n\nexport interface MetaConversionsResponse {\n events_received?: number;\n messages?: string[];\n fbtrace_id?: string;\n}\n\n/**\n * The lightweight counterpart to `sendMetaEvents`: same filtering, same payload, same\n * never-throws contract, minus the 31MB SDK. The token travels in the JSON body, never in the\n * URL, and is never logged.\n */\nexport async function sendMetaConversions(\n accessToken: string,\n pixelId: string,\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n events: TrackEvent<any>[],\n data: UserProvidedData = {},\n options: MetaConversionsOptions = {}\n): Promise<MetaConversionsResponse | undefined> {\n const capiEvents = events\n .filter((event) => !IGNORED_EVENTS.includes(event.name))\n .map((event) => getCapiEvent(event, data, options.appPackageName));\n if (capiEvents.length === 0) return undefined;\n\n const version = options.apiVersion ?? API_VERSION;\n try {\n const response = await fetch(`https://graph.facebook.com/${version}/${pixelId}/events`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json', Accept: 'application/json' },\n body: JSON.stringify({\n data: capiEvents,\n test_event_code: options.testEventCode,\n access_token: accessToken,\n }),\n });\n if (response.ok) return (await response.json()) as MetaConversionsResponse;\n const { status } = response;\n const message = await response.text();\n console.error(`Failed to send Meta conversion, status: ${status}, body: ${message}`);\n return undefined;\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n console.error(`Failed to send Meta conversion, network error: ${message}`);\n return undefined;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiCA,MAAM,cAAc;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AQ;GACR,SAAS;IAAE,gBAAgB;IAAoB,QAAQ;GAAmB;GAC1E,MAAM,KAAK,UAAU;IACnB,MAAM;IACN,iBAAiB,QAAQ;IACzB,cAAc;GAChB,CAAC;EACH,CAAC;EACD,IAAI,SAAS,IAAI,OAAQ,MAAM,SAAS,KAAK;EAC7C,MAAM,EAAE,WAAW;EACnB,MAAM,UAAU,MAAM,SAAS,KAAK;EACpC,QAAQ,MAAM,2CAA2C,OAAO,UAAU,SAAS;EACnF;CACF,SAAS,OAAO;EACd,MAAM,UAAU,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;EACrE,QAAQ,MAAM,kDAAkD,SAAS;EACzE;CACF;AACF"}
|
|
@@ -1,8 +1,9 @@
|
|
|
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_click_id_index = require("../click-id/index.cjs");
|
|
4
|
-
const require_track_fbq = require("../track/fbq.cjs");
|
|
5
4
|
const require_server_action_source = require("./action-source.cjs");
|
|
5
|
+
const require_track_fbq = require("../track/fbq.cjs");
|
|
6
|
+
const require_server_page_location = require("./page-location.cjs");
|
|
6
7
|
let facebook_nodejs_business_sdk = require("facebook-nodejs-business-sdk");
|
|
7
8
|
//#region src/server/meta-conversions-api.ts
|
|
8
9
|
const USER_ASSIGNED_COUNTRIES = ["xk"];
|
|
@@ -130,7 +131,8 @@ function getServerEvent(event, data, appPackageName, actionSource) {
|
|
|
130
131
|
const appData = getAppData(event.tags, appPackageName);
|
|
131
132
|
serverEvent.setAppData(appData);
|
|
132
133
|
}
|
|
133
|
-
|
|
134
|
+
const eventSourceUrl = require_server_page_location.pageLocation(event.tags);
|
|
135
|
+
if (eventSourceUrl) serverEvent.setEventSourceUrl(eventSourceUrl);
|
|
134
136
|
switch (source) {
|
|
135
137
|
case "app":
|
|
136
138
|
serverEvent.setActionSource("app");
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"meta-conversions-api.cjs","names":["UserData","formatFbc","ExtendedDeviceInfo","AppData","CustomData","mapFBEvent","Content","ServerEvent","resolveActionSource","IGNORED_EVENTS","EventRequest"],"sources":["../../src/server/meta-conversions-api.ts"],"sourcesContent":["import {\n AppData,\n Content,\n CustomData,\n EventRequest,\n ExtendedDeviceInfo,\n ServerEvent,\n UserData,\n} from 'facebook-nodejs-business-sdk';\nimport { formatFbc } from '../click-id/index';\nimport { IGNORED_EVENTS } from '../third-parties/ignored-events';\nimport { mapFBEvent } from '../track/fbq';\nimport type { TrackEvent, TrackTags, UserProvidedData } from '../track/types';\nimport { type EventActionSource, resolveActionSource } from './action-source';\n\nconst USER_ASSIGNED_COUNTRIES: string[] = ['xk'];\nfunction normalizeCountry(input: string | undefined): string | undefined {\n const country = input?.split(/[-_]/).at(0)?.toLowerCase();\n if (!country) return undefined;\n return USER_ASSIGNED_COUNTRIES.includes(country) ? undefined : country;\n}\n\nfunction getUserData(tags: TrackTags, data: UserProvidedData, eventTimeMs: number) {\n const userData = new UserData();\n\n // set user-provided data\n if (data.email) {\n if (Array.isArray(data.email)) {\n userData.setEmails(data.email);\n } else {\n userData.setEmail(data.email);\n }\n }\n if (data.phone_number) {\n if (Array.isArray(data.phone_number)) {\n userData.setPhones(data.phone_number);\n } else {\n userData.setPhone(data.phone_number);\n }\n }\n if (data.gender) {\n if (data.gender === 'female') {\n userData.setGender('f');\n // oxlint-disable-next-line typescript/no-unnecessary-condition -- user-provided data may carry values outside the declared union at runtime\n } else if (data.gender === 'male') {\n userData.setGender('m');\n }\n }\n if (data.address) {\n if (Array.isArray(data.address)) {\n const firstNames = data.address.map((a) => a.first_name).filter(Boolean);\n const lastNames = data.address.map((a) => a.last_name).filter(Boolean);\n const cities = data.address.map((a) => a.city).filter(Boolean);\n const states = data.address.map((a) => a.region).filter(Boolean);\n const postalCodes = data.address.map((a) => a.postal_code).filter(Boolean);\n const countries = data.address.map((a) => normalizeCountry(a.country)).filter(Boolean);\n\n userData.setFirstNames(firstNames as string[]);\n userData.setLastNames(lastNames as string[]);\n userData.setCities(cities as string[]);\n userData.setStates(states as string[]);\n userData.setZips(postalCodes as string[]);\n userData.setCountries(countries as string[]);\n } else {\n if (data.address.first_name) {\n userData.setFirstName(data.address.first_name);\n userData.setF5First(data.address.first_name.slice(0, 5));\n }\n if (data.address.last_name) {\n userData.setLastName(data.address.last_name);\n userData.setF5Last(data.address.last_name.slice(0, 5));\n }\n if (data.address.city) userData.setCity(data.address.city);\n if (data.address.region) userData.setState(data.address.region);\n if (data.address.postal_code) userData.setZip(data.address.postal_code);\n if (data.address.country) {\n const country = normalizeCountry(data.address.country);\n if (country) userData.setCountry(country);\n }\n }\n }\n if (data.birthday) {\n userData.setDoby(data.birthday.year.toString());\n userData.setDobm(data.birthday.month.toString());\n userData.setDobd(data.birthday.day.toString());\n }\n if (data.user_id && data.user_id.length !== 0) {\n userData.setExternalId(data.user_id);\n }\n if (data.ip_address) {\n userData.setClientIpAddress(data.ip_address);\n }\n if (data.user_agent) {\n userData.setClientUserAgent(data.user_agent);\n }\n if (data.fb_login_id) {\n userData.setFbLoginId(data.fb_login_id);\n }\n if (data.fb_page_id) {\n userData.setPageId(data.fb_page_id);\n }\n\n // set tags info\n if (tags.fbc) {\n userData.setFbc(tags.fbc);\n } else if (tags.fbclid) {\n // ref: https://developers.facebook.com/docs/marketing-api/conversions-api/parameters/fbp-and-fbc#2--format-clickid\n // The formatted ClickID value must be of the form `version.subdomainIndex.creationTime.<fbclid>`, where:\n // - version is always this prefix: fb\n // - subdomainIndex is which domain the cookie is defined on ('com' = 0, 'example.com' = 1, 'www.example.com' = 2)\n // - creationTime is the UNIX time since epoch in milliseconds when the _fbc was stored. If you don't save the _fbc cookie, use the timestamp when you first observed or received this fbclid value\n // - <fbclid> is the value for the fbclid query parameter in the page URL.\n\n // \"the timestamp when you first observed or received this fbclid value\" — the event's own\n // time is the closest thing the server has to that, and it does not move when a queued or\n // retried batch finally goes out.\n userData.setFbc(formatFbc(tags.fbclid, eventTimeMs));\n }\n\n if (tags.fbp) {\n userData.setFbp(tags.fbp);\n }\n if (tags.advertising_id) {\n userData.setMadid(tags.advertising_id);\n }\n if (tags.ip_address && typeof tags.ip_address === 'string') {\n userData.setClientIpAddress(tags.ip_address);\n }\n\n return userData;\n}\n\nfunction getAppData(tags: TrackTags, appPackageName: string) {\n const extinfo = new ExtendedDeviceInfo();\n if (tags.os_name) {\n if (tags.os_name === 'iOS' || tags.os_name === 'iPadOS') {\n extinfo.setExtInfoVersion('i2');\n } else if (tags.os_name === 'Android') {\n extinfo.setExtInfoVersion('a2');\n }\n }\n extinfo.setAppPackageName(appPackageName);\n const shortVersion = tags.release?.split('.').at(0);\n if (shortVersion) {\n extinfo.setShortVersion(shortVersion);\n }\n if (tags.release) {\n extinfo.setLongVersion(tags.release);\n }\n if (tags.os_version) {\n extinfo.setOsVersion(tags.os_version);\n }\n if (tags.device_model_id) {\n extinfo.setDeviceModelName(tags.device_model_id);\n }\n if (tags.language) {\n extinfo.setLocale(tags.language);\n }\n if (tags.screen_width) {\n extinfo.setScreenWidth(tags.screen_width);\n }\n if (tags.screen_height) {\n extinfo.setScreenHeight(tags.screen_height);\n }\n if (tags.device_pixel_ratio) {\n extinfo.setScreenDensity(tags.device_pixel_ratio.toString());\n }\n\n const appData = new AppData();\n appData.setExtinfo(extinfo);\n if (tags.install_referrer) {\n appData.setInstallReferrer(tags.install_referrer);\n }\n if (tags.advertising_id) {\n appData.setAdvertiserTrackingEnabled(true);\n }\n if (tags.install_referrer) {\n appData.setInstallReferrer(tags.install_referrer);\n }\n\n return appData;\n}\n\n// oxlint-disable-next-line @typescript-eslint/no-explicit-any\nfunction getCustomData({ name, properties }: TrackEvent<any>) {\n const data = new CustomData();\n const [_, _name, fbEventProperties] = mapFBEvent(name, properties);\n const {\n value,\n currency,\n content_name,\n content_category,\n content_ids,\n contents,\n content_type,\n // order_id,\n predicted_ltv,\n num_items,\n search_string,\n status,\n // item_number,\n delivery_category,\n ...custom_properties\n } = fbEventProperties;\n // oxlint-disable-next-line typescript/no-unnecessary-condition -- custom event properties may carry `value: null` at runtime despite the declared type\n if (value !== undefined && value !== null) data.setValue(value);\n if (currency) data.setCurrency(currency);\n if (content_name) data.setContentName(content_name);\n if (content_category) data.setContentCategory(content_category);\n if (content_ids) data.setContentIds(content_ids);\n if (contents)\n data.setContents(\n contents.map((c) => {\n const result = new Content().setId(c.id).setQuantity(c.quantity);\n if (c.item_price) result.setItemPrice(c.item_price);\n if (c.title) result.setTitle(c.title);\n if (c.description) result.setDescription(c.description);\n if (c.brand) result.setBrand(c.brand);\n if (c.category) result.setCategory(c.category);\n if (c.delivery_category) result.setDeliveryCategory(c.delivery_category);\n return result;\n })\n );\n if (content_type) data.setContentType(content_type);\n // if (order_id) data.setOrderId(order_id);\n if (predicted_ltv) data.setPredictedLtv(predicted_ltv);\n if (num_items) data.setNumItems(num_items);\n if (search_string) data.setSearchString(search_string);\n if (status) data.setStatus(status.toString());\n // if (item_number) data.setItemNumber(item_number);\n if (delivery_category) data.setDeliveryCategory(delivery_category);\n data.setCustomProperties(custom_properties);\n return data;\n}\n\nexport function getServerEvent(\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n event: TrackEvent<any>,\n data: UserProvidedData,\n appPackageName?: string,\n actionSource?: EventActionSource\n) {\n const eventTimeMs = new Date(event.created_at).getTime();\n const userData = getUserData(event.tags, data, eventTimeMs);\n const customData = getCustomData(event);\n const [_, eventName] = mapFBEvent(event.name, event.properties);\n const serverEvent = new ServerEvent()\n .setEventId(event.tags.idempotency_key ?? event.id)\n .setEventName(eventName)\n .setEventTime(Math.round(eventTimeMs / 1000))\n .setUserData(userData)\n .setCustomData(customData);\n\n const source = resolveActionSource(event.platform, actionSource);\n if (source === 'app' && appPackageName) {\n const appData = getAppData(event.tags, appPackageName);\n serverEvent.setAppData(appData);\n }\n if (event.tags.page_location) {\n serverEvent.setEventSourceUrl(event.tags.page_location);\n }\n switch (source) {\n case 'app':\n serverEvent.setActionSource('app');\n break;\n case 'web':\n serverEvent.setActionSource('website');\n break;\n default:\n // `action_source` is required on a server event, so both an offline conversion and an\n // undeterminable platform still have to send something. Meta has no generic offline\n // value: 'physical_store' and 'system_generated' are narrower claims only the caller can\n // make, so everything left lands in Meta's own catch-all.\n serverEvent.setActionSource('other');\n break;\n }\n return serverEvent;\n}\n\n/**\n * The shape `FacebookRequestError` exposes: `status` and `response` are the HTTP status and the\n * parsed error body, and both are null when the request never received a response.\n */\ntype MetaRequestError = { status?: number | null; message?: string; response?: unknown };\n\n/**\n * Meta's SDK rejects on API errors, where every other conversion sender here logs and resolves.\n * Keep the failure inside this module, so one rejected batch cannot fail the caller's request.\n * Never log the error itself: it also carries the access token, in both `url` and `data`.\n */\nfunction logError(error: unknown) {\n const { status, message, response } = (error ?? {}) as MetaRequestError;\n if (typeof status !== 'number') {\n console.error(`Failed to send Meta conversion, network error: ${message ?? String(error)}`);\n return;\n }\n console.error(\n `Failed to send Meta conversion, status: ${status}, body: ${JSON.stringify(response)}`\n );\n}\n\nexport async function sendEvent(\n accessToken: string,\n pixelId: string,\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n event: TrackEvent<any>,\n data: UserProvidedData = {},\n appPackageName?: string,\n actionSource?: EventActionSource\n) {\n if (IGNORED_EVENTS.includes(event.name)) return undefined;\n const request = new EventRequest(accessToken, pixelId);\n const fbEvent = getServerEvent(event, data, appPackageName, actionSource);\n request.setEvents([fbEvent]);\n try {\n return await request.execute();\n } catch (error) {\n logError(error);\n return undefined;\n }\n}\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 appPackageName?: string,\n actionSource?: EventActionSource\n) {\n const fbEvents = events\n .filter((event) => !IGNORED_EVENTS.includes(event.name))\n .map((event) => getServerEvent(event, data, appPackageName, actionSource));\n if (fbEvents.length === 0) return undefined;\n const request = new EventRequest(accessToken, pixelId);\n request.setEvents(fbEvents);\n try {\n return await request.execute();\n } catch (error) {\n logError(error);\n return undefined;\n }\n}\n\nexport async function sendTestEvent(accessToken: string, pixelId: string, testEventCode: string) {\n const extinfo = new ExtendedDeviceInfo()\n .setExtInfoVersion('a2')\n .setAppPackageName('com.some.app')\n .setShortVersion('771')\n .setLongVersion('Version 7.7.1')\n .setOsVersion('10.1.1')\n .setDeviceModelName('OnePlus6')\n .setLocale('en_US')\n .setTimezoneAbbreviation('GMT-1')\n .setCarrier('TMobile')\n .setScreenWidth(1920)\n .setScreenHeight(1080)\n .setScreenDensity('2.00')\n .setCpuCoreCount(2)\n .setTotalDiskSpaceGb(128)\n .setFreeDiskSpaceGb(8)\n .setDeviceTimeZone('USA/New York');\n\n const userData = new UserData().setEmail('test@example.com');\n const appData = new AppData().setExtinfo(extinfo);\n const event = new ServerEvent()\n .setEventId(Math.round(Math.random() * 1000_000).toString())\n .setEventName('TestEvent')\n .setEventTime(Math.round(Date.now() / 1000))\n .setUserData(userData)\n .setAppData(appData)\n .setActionSource('app');\n\n const request = new EventRequest(accessToken, pixelId);\n request.setTestEventCode(testEventCode);\n request.setEvents([event]);\n return request.execute();\n}\n"],"mappings":";;;;;;;AAeA,MAAM,0BAAoC,CAAC,IAAI;AAC/C,SAAS,iBAAiB,OAA+C;CACvE,MAAM,UAAU,OAAO,MAAM,MAAM,CAAC,CAAC,GAAG,CAAC,CAAC,EAAE,YAAY;CACxD,IAAI,CAAC,SAAS,OAAO,KAAA;CACrB,OAAO,wBAAwB,SAAS,OAAO,IAAI,KAAA,IAAY;AACjE;AAEA,SAAS,YAAY,MAAiB,MAAwB,aAAqB;CACjF,MAAM,WAAW,IAAIA,6BAAAA,SAAS;CAG9B,IAAI,KAAK,OACP,IAAI,MAAM,QAAQ,KAAK,KAAK,GAC1B,SAAS,UAAU,KAAK,KAAK;MAE7B,SAAS,SAAS,KAAK,KAAK;CAGhC,IAAI,KAAK,cACP,IAAI,MAA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AO,QAAQ,QAAQ;AACzB"}
|
|
1
|
+
{"version":3,"file":"meta-conversions-api.cjs","names":["UserData","formatFbc","ExtendedDeviceInfo","AppData","CustomData","mapFBEvent","Content","ServerEvent","resolveActionSource","pageLocation","IGNORED_EVENTS","EventRequest"],"sources":["../../src/server/meta-conversions-api.ts"],"sourcesContent":["import {\n AppData,\n Content,\n CustomData,\n EventRequest,\n ExtendedDeviceInfo,\n ServerEvent,\n UserData,\n} from 'facebook-nodejs-business-sdk';\nimport { formatFbc } from '../click-id/index';\nimport { IGNORED_EVENTS } from '../third-parties/ignored-events';\nimport { mapFBEvent } from '../track/fbq';\nimport type { TrackEvent, TrackTags, UserProvidedData } from '../track/types';\nimport { type EventActionSource, resolveActionSource } from './action-source';\nimport { pageLocation } from './page-location';\n\nconst USER_ASSIGNED_COUNTRIES: string[] = ['xk'];\nfunction normalizeCountry(input: string | undefined): string | undefined {\n const country = input?.split(/[-_]/).at(0)?.toLowerCase();\n if (!country) return undefined;\n return USER_ASSIGNED_COUNTRIES.includes(country) ? undefined : country;\n}\n\nfunction getUserData(tags: TrackTags, data: UserProvidedData, eventTimeMs: number) {\n const userData = new UserData();\n\n // set user-provided data\n if (data.email) {\n if (Array.isArray(data.email)) {\n userData.setEmails(data.email);\n } else {\n userData.setEmail(data.email);\n }\n }\n if (data.phone_number) {\n if (Array.isArray(data.phone_number)) {\n userData.setPhones(data.phone_number);\n } else {\n userData.setPhone(data.phone_number);\n }\n }\n if (data.gender) {\n if (data.gender === 'female') {\n userData.setGender('f');\n // oxlint-disable-next-line typescript/no-unnecessary-condition -- user-provided data may carry values outside the declared union at runtime\n } else if (data.gender === 'male') {\n userData.setGender('m');\n }\n }\n if (data.address) {\n if (Array.isArray(data.address)) {\n const firstNames = data.address.map((a) => a.first_name).filter(Boolean);\n const lastNames = data.address.map((a) => a.last_name).filter(Boolean);\n const cities = data.address.map((a) => a.city).filter(Boolean);\n const states = data.address.map((a) => a.region).filter(Boolean);\n const postalCodes = data.address.map((a) => a.postal_code).filter(Boolean);\n const countries = data.address.map((a) => normalizeCountry(a.country)).filter(Boolean);\n\n userData.setFirstNames(firstNames as string[]);\n userData.setLastNames(lastNames as string[]);\n userData.setCities(cities as string[]);\n userData.setStates(states as string[]);\n userData.setZips(postalCodes as string[]);\n userData.setCountries(countries as string[]);\n } else {\n if (data.address.first_name) {\n userData.setFirstName(data.address.first_name);\n userData.setF5First(data.address.first_name.slice(0, 5));\n }\n if (data.address.last_name) {\n userData.setLastName(data.address.last_name);\n userData.setF5Last(data.address.last_name.slice(0, 5));\n }\n if (data.address.city) userData.setCity(data.address.city);\n if (data.address.region) userData.setState(data.address.region);\n if (data.address.postal_code) userData.setZip(data.address.postal_code);\n if (data.address.country) {\n const country = normalizeCountry(data.address.country);\n if (country) userData.setCountry(country);\n }\n }\n }\n if (data.birthday) {\n userData.setDoby(data.birthday.year.toString());\n userData.setDobm(data.birthday.month.toString());\n userData.setDobd(data.birthday.day.toString());\n }\n if (data.user_id && data.user_id.length !== 0) {\n userData.setExternalId(data.user_id);\n }\n if (data.ip_address) {\n userData.setClientIpAddress(data.ip_address);\n }\n if (data.user_agent) {\n userData.setClientUserAgent(data.user_agent);\n }\n if (data.fb_login_id) {\n userData.setFbLoginId(data.fb_login_id);\n }\n if (data.fb_page_id) {\n userData.setPageId(data.fb_page_id);\n }\n\n // set tags info\n if (tags.fbc) {\n userData.setFbc(tags.fbc);\n } else if (tags.fbclid) {\n // ref: https://developers.facebook.com/docs/marketing-api/conversions-api/parameters/fbp-and-fbc#2--format-clickid\n // The formatted ClickID value must be of the form `version.subdomainIndex.creationTime.<fbclid>`, where:\n // - version is always this prefix: fb\n // - subdomainIndex is which domain the cookie is defined on ('com' = 0, 'example.com' = 1, 'www.example.com' = 2)\n // - creationTime is the UNIX time since epoch in milliseconds when the _fbc was stored. If you don't save the _fbc cookie, use the timestamp when you first observed or received this fbclid value\n // - <fbclid> is the value for the fbclid query parameter in the page URL.\n\n // \"the timestamp when you first observed or received this fbclid value\" — the event's own\n // time is the closest thing the server has to that, and it does not move when a queued or\n // retried batch finally goes out.\n userData.setFbc(formatFbc(tags.fbclid, eventTimeMs));\n }\n\n if (tags.fbp) {\n userData.setFbp(tags.fbp);\n }\n if (tags.advertising_id) {\n userData.setMadid(tags.advertising_id);\n }\n if (tags.ip_address && typeof tags.ip_address === 'string') {\n userData.setClientIpAddress(tags.ip_address);\n }\n\n return userData;\n}\n\nfunction getAppData(tags: TrackTags, appPackageName: string) {\n const extinfo = new ExtendedDeviceInfo();\n if (tags.os_name) {\n if (tags.os_name === 'iOS' || tags.os_name === 'iPadOS') {\n extinfo.setExtInfoVersion('i2');\n } else if (tags.os_name === 'Android') {\n extinfo.setExtInfoVersion('a2');\n }\n }\n extinfo.setAppPackageName(appPackageName);\n const shortVersion = tags.release?.split('.').at(0);\n if (shortVersion) {\n extinfo.setShortVersion(shortVersion);\n }\n if (tags.release) {\n extinfo.setLongVersion(tags.release);\n }\n if (tags.os_version) {\n extinfo.setOsVersion(tags.os_version);\n }\n if (tags.device_model_id) {\n extinfo.setDeviceModelName(tags.device_model_id);\n }\n if (tags.language) {\n extinfo.setLocale(tags.language);\n }\n if (tags.screen_width) {\n extinfo.setScreenWidth(tags.screen_width);\n }\n if (tags.screen_height) {\n extinfo.setScreenHeight(tags.screen_height);\n }\n if (tags.device_pixel_ratio) {\n extinfo.setScreenDensity(tags.device_pixel_ratio.toString());\n }\n\n const appData = new AppData();\n appData.setExtinfo(extinfo);\n if (tags.install_referrer) {\n appData.setInstallReferrer(tags.install_referrer);\n }\n if (tags.advertising_id) {\n appData.setAdvertiserTrackingEnabled(true);\n }\n if (tags.install_referrer) {\n appData.setInstallReferrer(tags.install_referrer);\n }\n\n return appData;\n}\n\n// oxlint-disable-next-line @typescript-eslint/no-explicit-any\nfunction getCustomData({ name, properties }: TrackEvent<any>) {\n const data = new CustomData();\n const [_, _name, fbEventProperties] = mapFBEvent(name, properties);\n const {\n value,\n currency,\n content_name,\n content_category,\n content_ids,\n contents,\n content_type,\n // order_id,\n predicted_ltv,\n num_items,\n search_string,\n status,\n // item_number,\n delivery_category,\n ...custom_properties\n } = fbEventProperties;\n // oxlint-disable-next-line typescript/no-unnecessary-condition -- custom event properties may carry `value: null` at runtime despite the declared type\n if (value !== undefined && value !== null) data.setValue(value);\n if (currency) data.setCurrency(currency);\n if (content_name) data.setContentName(content_name);\n if (content_category) data.setContentCategory(content_category);\n if (content_ids) data.setContentIds(content_ids);\n if (contents)\n data.setContents(\n contents.map((c) => {\n const result = new Content().setId(c.id).setQuantity(c.quantity);\n if (c.item_price) result.setItemPrice(c.item_price);\n if (c.title) result.setTitle(c.title);\n if (c.description) result.setDescription(c.description);\n if (c.brand) result.setBrand(c.brand);\n if (c.category) result.setCategory(c.category);\n if (c.delivery_category) result.setDeliveryCategory(c.delivery_category);\n return result;\n })\n );\n if (content_type) data.setContentType(content_type);\n // if (order_id) data.setOrderId(order_id);\n if (predicted_ltv) data.setPredictedLtv(predicted_ltv);\n if (num_items) data.setNumItems(num_items);\n if (search_string) data.setSearchString(search_string);\n if (status) data.setStatus(status.toString());\n // if (item_number) data.setItemNumber(item_number);\n if (delivery_category) data.setDeliveryCategory(delivery_category);\n data.setCustomProperties(custom_properties);\n return data;\n}\n\nexport function getServerEvent(\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n event: TrackEvent<any>,\n data: UserProvidedData,\n appPackageName?: string,\n actionSource?: EventActionSource\n) {\n const eventTimeMs = new Date(event.created_at).getTime();\n const userData = getUserData(event.tags, data, eventTimeMs);\n const customData = getCustomData(event);\n const [_, eventName] = mapFBEvent(event.name, event.properties);\n const serverEvent = new ServerEvent()\n .setEventId(event.tags.idempotency_key ?? event.id)\n .setEventName(eventName)\n .setEventTime(Math.round(eventTimeMs / 1000))\n .setUserData(userData)\n .setCustomData(customData);\n\n const source = resolveActionSource(event.platform, actionSource);\n if (source === 'app' && appPackageName) {\n const appData = getAppData(event.tags, appPackageName);\n serverEvent.setAppData(appData);\n }\n const eventSourceUrl = pageLocation(event.tags);\n if (eventSourceUrl) {\n serverEvent.setEventSourceUrl(eventSourceUrl);\n }\n switch (source) {\n case 'app':\n serverEvent.setActionSource('app');\n break;\n case 'web':\n serverEvent.setActionSource('website');\n break;\n default:\n // `action_source` is required on a server event, so both an offline conversion and an\n // undeterminable platform still have to send something. Meta has no generic offline\n // value: 'physical_store' and 'system_generated' are narrower claims only the caller can\n // make, so everything left lands in Meta's own catch-all.\n serverEvent.setActionSource('other');\n break;\n }\n return serverEvent;\n}\n\n/**\n * The shape `FacebookRequestError` exposes: `status` and `response` are the HTTP status and the\n * parsed error body, and both are null when the request never received a response.\n */\ntype MetaRequestError = { status?: number | null; message?: string; response?: unknown };\n\n/**\n * Meta's SDK rejects on API errors, where every other conversion sender here logs and resolves.\n * Keep the failure inside this module, so one rejected batch cannot fail the caller's request.\n * Never log the error itself: it also carries the access token, in both `url` and `data`.\n */\nfunction logError(error: unknown) {\n const { status, message, response } = (error ?? {}) as MetaRequestError;\n if (typeof status !== 'number') {\n console.error(`Failed to send Meta conversion, network error: ${message ?? String(error)}`);\n return;\n }\n console.error(\n `Failed to send Meta conversion, status: ${status}, body: ${JSON.stringify(response)}`\n );\n}\n\nexport async function sendEvent(\n accessToken: string,\n pixelId: string,\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n event: TrackEvent<any>,\n data: UserProvidedData = {},\n appPackageName?: string,\n actionSource?: EventActionSource\n) {\n if (IGNORED_EVENTS.includes(event.name)) return undefined;\n const request = new EventRequest(accessToken, pixelId);\n const fbEvent = getServerEvent(event, data, appPackageName, actionSource);\n request.setEvents([fbEvent]);\n try {\n return await request.execute();\n } catch (error) {\n logError(error);\n return undefined;\n }\n}\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 appPackageName?: string,\n actionSource?: EventActionSource\n) {\n const fbEvents = events\n .filter((event) => !IGNORED_EVENTS.includes(event.name))\n .map((event) => getServerEvent(event, data, appPackageName, actionSource));\n if (fbEvents.length === 0) return undefined;\n const request = new EventRequest(accessToken, pixelId);\n request.setEvents(fbEvents);\n try {\n return await request.execute();\n } catch (error) {\n logError(error);\n return undefined;\n }\n}\n\nexport async function sendTestEvent(accessToken: string, pixelId: string, testEventCode: string) {\n const extinfo = new ExtendedDeviceInfo()\n .setExtInfoVersion('a2')\n .setAppPackageName('com.some.app')\n .setShortVersion('771')\n .setLongVersion('Version 7.7.1')\n .setOsVersion('10.1.1')\n .setDeviceModelName('OnePlus6')\n .setLocale('en_US')\n .setTimezoneAbbreviation('GMT-1')\n .setCarrier('TMobile')\n .setScreenWidth(1920)\n .setScreenHeight(1080)\n .setScreenDensity('2.00')\n .setCpuCoreCount(2)\n .setTotalDiskSpaceGb(128)\n .setFreeDiskSpaceGb(8)\n .setDeviceTimeZone('USA/New York');\n\n const userData = new UserData().setEmail('test@example.com');\n const appData = new AppData().setExtinfo(extinfo);\n const event = new ServerEvent()\n .setEventId(Math.round(Math.random() * 1000_000).toString())\n .setEventName('TestEvent')\n .setEventTime(Math.round(Date.now() / 1000))\n .setUserData(userData)\n .setAppData(appData)\n .setActionSource('app');\n\n const request = new EventRequest(accessToken, pixelId);\n request.setTestEventCode(testEventCode);\n request.setEvents([event]);\n return request.execute();\n}\n"],"mappings":";;;;;;;;AAgBA,MAAM,0BAAoC,CAAC,IAAI;AAC/C,SAAS,iBAAiB,OAA+C;CACvE,MAAM,UAAU,OAAO,MAAM,MAAM,CAAC,CAAC,GAAG,CAAC,CAAC,EAAE,YAAY;CACxD,IAAI,CAAC,SAAS,OAAO,KAAA;CACrB,OAAO,wBAAwB,SAAS,OAAO,IAAI,KAAA,IAAY;AACjE;AAEA,SAAS,YAAY,MAAiB,MAAwB,aAAqB;CACjF,MAAM,WAAW,IAAIA,6BAAAA,SAAS;CAG9B,IAAI,KAAK,OACP,IAAI,MAAM,QAAQ,KAAK,KAAK,GAC1B,SAA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UAAU,IAAII,6BAAAA,aAAa,aAAa,OAAO;CACrD,QAAQ,iBAAiB,aAAa;CACtC,QAAQ,UAAU,CAAC,KAAK,CAAC;CACzB,OAAO,QAAQ,QAAQ;AACzB"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"meta-conversions-api.d.cts","names":[],"sources":["../../src/server/meta-conversions-api.ts"],"mappings":";;;;
|
|
1
|
+
{"version":3,"file":"meta-conversions-api.d.cts","names":[],"sources":["../../src/server/meta-conversions-api.ts"],"mappings":";;;;iBA4OgB,eAEd,OAAO,iBACP,MAAM,kBACN,yBACA,eAAe,oBAAiB;iBA8DZ,UACpB,qBACA,iBAEA,OAAO,iBACP,OAAM,kBACN,yBACA,eAAe,oBAAiB,+CAAA;iBAcZ,WACpB,qBACA,iBAEA,QAAQ,mBACR,OAAM,kBACN,yBACA,eAAe,oBAAiB,+CAAA;iBAgBZ,cAAc,qBAAqB,iBAAiB,wBAAqB,+CAAA"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"meta-conversions-api.d.mts","names":[],"sources":["../../src/server/meta-conversions-api.ts"],"mappings":";;;;
|
|
1
|
+
{"version":3,"file":"meta-conversions-api.d.mts","names":[],"sources":["../../src/server/meta-conversions-api.ts"],"mappings":";;;;iBA4OgB,eAEd,OAAO,iBACP,MAAM,kBACN,yBACA,eAAe,oBAAiB;iBA8DZ,UACpB,qBACA,iBAEA,OAAO,iBACP,OAAM,kBACN,yBACA,eAAe,oBAAiB,+CAAA;iBAcZ,WACpB,qBACA,iBAEA,QAAQ,mBACR,OAAM,kBACN,yBACA,eAAe,oBAAiB,+CAAA;iBAgBZ,cAAc,qBAAqB,iBAAiB,wBAAqB,+CAAA"}
|
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import { IGNORED_EVENTS } from "../third-parties/ignored-events.mjs";
|
|
2
2
|
import { formatFbc } from "../click-id/index.mjs";
|
|
3
|
-
import { mapFBEvent } from "../track/fbq.mjs";
|
|
4
3
|
import { resolveActionSource } from "./action-source.mjs";
|
|
4
|
+
import { mapFBEvent } from "../track/fbq.mjs";
|
|
5
|
+
import { pageLocation } from "./page-location.mjs";
|
|
5
6
|
import { AppData, Content, CustomData, EventRequest, ExtendedDeviceInfo, ServerEvent, UserData } from "facebook-nodejs-business-sdk";
|
|
6
7
|
//#region src/server/meta-conversions-api.ts
|
|
7
8
|
const USER_ASSIGNED_COUNTRIES = ["xk"];
|
|
@@ -129,7 +130,8 @@ function getServerEvent(event, data, appPackageName, actionSource) {
|
|
|
129
130
|
const appData = getAppData(event.tags, appPackageName);
|
|
130
131
|
serverEvent.setAppData(appData);
|
|
131
132
|
}
|
|
132
|
-
|
|
133
|
+
const eventSourceUrl = pageLocation(event.tags);
|
|
134
|
+
if (eventSourceUrl) serverEvent.setEventSourceUrl(eventSourceUrl);
|
|
133
135
|
switch (source) {
|
|
134
136
|
case "app":
|
|
135
137
|
serverEvent.setActionSource("app");
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"meta-conversions-api.mjs","names":[],"sources":["../../src/server/meta-conversions-api.ts"],"sourcesContent":["import {\n AppData,\n Content,\n CustomData,\n EventRequest,\n ExtendedDeviceInfo,\n ServerEvent,\n UserData,\n} from 'facebook-nodejs-business-sdk';\nimport { formatFbc } from '../click-id/index';\nimport { IGNORED_EVENTS } from '../third-parties/ignored-events';\nimport { mapFBEvent } from '../track/fbq';\nimport type { TrackEvent, TrackTags, UserProvidedData } from '../track/types';\nimport { type EventActionSource, resolveActionSource } from './action-source';\n\nconst USER_ASSIGNED_COUNTRIES: string[] = ['xk'];\nfunction normalizeCountry(input: string | undefined): string | undefined {\n const country = input?.split(/[-_]/).at(0)?.toLowerCase();\n if (!country) return undefined;\n return USER_ASSIGNED_COUNTRIES.includes(country) ? undefined : country;\n}\n\nfunction getUserData(tags: TrackTags, data: UserProvidedData, eventTimeMs: number) {\n const userData = new UserData();\n\n // set user-provided data\n if (data.email) {\n if (Array.isArray(data.email)) {\n userData.setEmails(data.email);\n } else {\n userData.setEmail(data.email);\n }\n }\n if (data.phone_number) {\n if (Array.isArray(data.phone_number)) {\n userData.setPhones(data.phone_number);\n } else {\n userData.setPhone(data.phone_number);\n }\n }\n if (data.gender) {\n if (data.gender === 'female') {\n userData.setGender('f');\n // oxlint-disable-next-line typescript/no-unnecessary-condition -- user-provided data may carry values outside the declared union at runtime\n } else if (data.gender === 'male') {\n userData.setGender('m');\n }\n }\n if (data.address) {\n if (Array.isArray(data.address)) {\n const firstNames = data.address.map((a) => a.first_name).filter(Boolean);\n const lastNames = data.address.map((a) => a.last_name).filter(Boolean);\n const cities = data.address.map((a) => a.city).filter(Boolean);\n const states = data.address.map((a) => a.region).filter(Boolean);\n const postalCodes = data.address.map((a) => a.postal_code).filter(Boolean);\n const countries = data.address.map((a) => normalizeCountry(a.country)).filter(Boolean);\n\n userData.setFirstNames(firstNames as string[]);\n userData.setLastNames(lastNames as string[]);\n userData.setCities(cities as string[]);\n userData.setStates(states as string[]);\n userData.setZips(postalCodes as string[]);\n userData.setCountries(countries as string[]);\n } else {\n if (data.address.first_name) {\n userData.setFirstName(data.address.first_name);\n userData.setF5First(data.address.first_name.slice(0, 5));\n }\n if (data.address.last_name) {\n userData.setLastName(data.address.last_name);\n userData.setF5Last(data.address.last_name.slice(0, 5));\n }\n if (data.address.city) userData.setCity(data.address.city);\n if (data.address.region) userData.setState(data.address.region);\n if (data.address.postal_code) userData.setZip(data.address.postal_code);\n if (data.address.country) {\n const country = normalizeCountry(data.address.country);\n if (country) userData.setCountry(country);\n }\n }\n }\n if (data.birthday) {\n userData.setDoby(data.birthday.year.toString());\n userData.setDobm(data.birthday.month.toString());\n userData.setDobd(data.birthday.day.toString());\n }\n if (data.user_id && data.user_id.length !== 0) {\n userData.setExternalId(data.user_id);\n }\n if (data.ip_address) {\n userData.setClientIpAddress(data.ip_address);\n }\n if (data.user_agent) {\n userData.setClientUserAgent(data.user_agent);\n }\n if (data.fb_login_id) {\n userData.setFbLoginId(data.fb_login_id);\n }\n if (data.fb_page_id) {\n userData.setPageId(data.fb_page_id);\n }\n\n // set tags info\n if (tags.fbc) {\n userData.setFbc(tags.fbc);\n } else if (tags.fbclid) {\n // ref: https://developers.facebook.com/docs/marketing-api/conversions-api/parameters/fbp-and-fbc#2--format-clickid\n // The formatted ClickID value must be of the form `version.subdomainIndex.creationTime.<fbclid>`, where:\n // - version is always this prefix: fb\n // - subdomainIndex is which domain the cookie is defined on ('com' = 0, 'example.com' = 1, 'www.example.com' = 2)\n // - creationTime is the UNIX time since epoch in milliseconds when the _fbc was stored. If you don't save the _fbc cookie, use the timestamp when you first observed or received this fbclid value\n // - <fbclid> is the value for the fbclid query parameter in the page URL.\n\n // \"the timestamp when you first observed or received this fbclid value\" — the event's own\n // time is the closest thing the server has to that, and it does not move when a queued or\n // retried batch finally goes out.\n userData.setFbc(formatFbc(tags.fbclid, eventTimeMs));\n }\n\n if (tags.fbp) {\n userData.setFbp(tags.fbp);\n }\n if (tags.advertising_id) {\n userData.setMadid(tags.advertising_id);\n }\n if (tags.ip_address && typeof tags.ip_address === 'string') {\n userData.setClientIpAddress(tags.ip_address);\n }\n\n return userData;\n}\n\nfunction getAppData(tags: TrackTags, appPackageName: string) {\n const extinfo = new ExtendedDeviceInfo();\n if (tags.os_name) {\n if (tags.os_name === 'iOS' || tags.os_name === 'iPadOS') {\n extinfo.setExtInfoVersion('i2');\n } else if (tags.os_name === 'Android') {\n extinfo.setExtInfoVersion('a2');\n }\n }\n extinfo.setAppPackageName(appPackageName);\n const shortVersion = tags.release?.split('.').at(0);\n if (shortVersion) {\n extinfo.setShortVersion(shortVersion);\n }\n if (tags.release) {\n extinfo.setLongVersion(tags.release);\n }\n if (tags.os_version) {\n extinfo.setOsVersion(tags.os_version);\n }\n if (tags.device_model_id) {\n extinfo.setDeviceModelName(tags.device_model_id);\n }\n if (tags.language) {\n extinfo.setLocale(tags.language);\n }\n if (tags.screen_width) {\n extinfo.setScreenWidth(tags.screen_width);\n }\n if (tags.screen_height) {\n extinfo.setScreenHeight(tags.screen_height);\n }\n if (tags.device_pixel_ratio) {\n extinfo.setScreenDensity(tags.device_pixel_ratio.toString());\n }\n\n const appData = new AppData();\n appData.setExtinfo(extinfo);\n if (tags.install_referrer) {\n appData.setInstallReferrer(tags.install_referrer);\n }\n if (tags.advertising_id) {\n appData.setAdvertiserTrackingEnabled(true);\n }\n if (tags.install_referrer) {\n appData.setInstallReferrer(tags.install_referrer);\n }\n\n return appData;\n}\n\n// oxlint-disable-next-line @typescript-eslint/no-explicit-any\nfunction getCustomData({ name, properties }: TrackEvent<any>) {\n const data = new CustomData();\n const [_, _name, fbEventProperties] = mapFBEvent(name, properties);\n const {\n value,\n currency,\n content_name,\n content_category,\n content_ids,\n contents,\n content_type,\n // order_id,\n predicted_ltv,\n num_items,\n search_string,\n status,\n // item_number,\n delivery_category,\n ...custom_properties\n } = fbEventProperties;\n // oxlint-disable-next-line typescript/no-unnecessary-condition -- custom event properties may carry `value: null` at runtime despite the declared type\n if (value !== undefined && value !== null) data.setValue(value);\n if (currency) data.setCurrency(currency);\n if (content_name) data.setContentName(content_name);\n if (content_category) data.setContentCategory(content_category);\n if (content_ids) data.setContentIds(content_ids);\n if (contents)\n data.setContents(\n contents.map((c) => {\n const result = new Content().setId(c.id).setQuantity(c.quantity);\n if (c.item_price) result.setItemPrice(c.item_price);\n if (c.title) result.setTitle(c.title);\n if (c.description) result.setDescription(c.description);\n if (c.brand) result.setBrand(c.brand);\n if (c.category) result.setCategory(c.category);\n if (c.delivery_category) result.setDeliveryCategory(c.delivery_category);\n return result;\n })\n );\n if (content_type) data.setContentType(content_type);\n // if (order_id) data.setOrderId(order_id);\n if (predicted_ltv) data.setPredictedLtv(predicted_ltv);\n if (num_items) data.setNumItems(num_items);\n if (search_string) data.setSearchString(search_string);\n if (status) data.setStatus(status.toString());\n // if (item_number) data.setItemNumber(item_number);\n if (delivery_category) data.setDeliveryCategory(delivery_category);\n data.setCustomProperties(custom_properties);\n return data;\n}\n\nexport function getServerEvent(\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n event: TrackEvent<any>,\n data: UserProvidedData,\n appPackageName?: string,\n actionSource?: EventActionSource\n) {\n const eventTimeMs = new Date(event.created_at).getTime();\n const userData = getUserData(event.tags, data, eventTimeMs);\n const customData = getCustomData(event);\n const [_, eventName] = mapFBEvent(event.name, event.properties);\n const serverEvent = new ServerEvent()\n .setEventId(event.tags.idempotency_key ?? event.id)\n .setEventName(eventName)\n .setEventTime(Math.round(eventTimeMs / 1000))\n .setUserData(userData)\n .setCustomData(customData);\n\n const source = resolveActionSource(event.platform, actionSource);\n if (source === 'app' && appPackageName) {\n const appData = getAppData(event.tags, appPackageName);\n serverEvent.setAppData(appData);\n }\n if (event.tags.page_location) {\n serverEvent.setEventSourceUrl(event.tags.page_location);\n }\n switch (source) {\n case 'app':\n serverEvent.setActionSource('app');\n break;\n case 'web':\n serverEvent.setActionSource('website');\n break;\n default:\n // `action_source` is required on a server event, so both an offline conversion and an\n // undeterminable platform still have to send something. Meta has no generic offline\n // value: 'physical_store' and 'system_generated' are narrower claims only the caller can\n // make, so everything left lands in Meta's own catch-all.\n serverEvent.setActionSource('other');\n break;\n }\n return serverEvent;\n}\n\n/**\n * The shape `FacebookRequestError` exposes: `status` and `response` are the HTTP status and the\n * parsed error body, and both are null when the request never received a response.\n */\ntype MetaRequestError = { status?: number | null; message?: string; response?: unknown };\n\n/**\n * Meta's SDK rejects on API errors, where every other conversion sender here logs and resolves.\n * Keep the failure inside this module, so one rejected batch cannot fail the caller's request.\n * Never log the error itself: it also carries the access token, in both `url` and `data`.\n */\nfunction logError(error: unknown) {\n const { status, message, response } = (error ?? {}) as MetaRequestError;\n if (typeof status !== 'number') {\n console.error(`Failed to send Meta conversion, network error: ${message ?? String(error)}`);\n return;\n }\n console.error(\n `Failed to send Meta conversion, status: ${status}, body: ${JSON.stringify(response)}`\n );\n}\n\nexport async function sendEvent(\n accessToken: string,\n pixelId: string,\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n event: TrackEvent<any>,\n data: UserProvidedData = {},\n appPackageName?: string,\n actionSource?: EventActionSource\n) {\n if (IGNORED_EVENTS.includes(event.name)) return undefined;\n const request = new EventRequest(accessToken, pixelId);\n const fbEvent = getServerEvent(event, data, appPackageName, actionSource);\n request.setEvents([fbEvent]);\n try {\n return await request.execute();\n } catch (error) {\n logError(error);\n return undefined;\n }\n}\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 appPackageName?: string,\n actionSource?: EventActionSource\n) {\n const fbEvents = events\n .filter((event) => !IGNORED_EVENTS.includes(event.name))\n .map((event) => getServerEvent(event, data, appPackageName, actionSource));\n if (fbEvents.length === 0) return undefined;\n const request = new EventRequest(accessToken, pixelId);\n request.setEvents(fbEvents);\n try {\n return await request.execute();\n } catch (error) {\n logError(error);\n return undefined;\n }\n}\n\nexport async function sendTestEvent(accessToken: string, pixelId: string, testEventCode: string) {\n const extinfo = new ExtendedDeviceInfo()\n .setExtInfoVersion('a2')\n .setAppPackageName('com.some.app')\n .setShortVersion('771')\n .setLongVersion('Version 7.7.1')\n .setOsVersion('10.1.1')\n .setDeviceModelName('OnePlus6')\n .setLocale('en_US')\n .setTimezoneAbbreviation('GMT-1')\n .setCarrier('TMobile')\n .setScreenWidth(1920)\n .setScreenHeight(1080)\n .setScreenDensity('2.00')\n .setCpuCoreCount(2)\n .setTotalDiskSpaceGb(128)\n .setFreeDiskSpaceGb(8)\n .setDeviceTimeZone('USA/New York');\n\n const userData = new UserData().setEmail('test@example.com');\n const appData = new AppData().setExtinfo(extinfo);\n const event = new ServerEvent()\n .setEventId(Math.round(Math.random() * 1000_000).toString())\n .setEventName('TestEvent')\n .setEventTime(Math.round(Date.now() / 1000))\n .setUserData(userData)\n .setAppData(appData)\n .setActionSource('app');\n\n const request = new EventRequest(accessToken, pixelId);\n request.setTestE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W,KAAK,MAAM,KAAK,OAAO,IAAI,GAAQ,CAAC,CAAC,SAAS,CAAC,CAAC,CAC3D,aAAa,WAAW,CAAC,CACzB,aAAa,KAAK,MAAM,KAAK,IAAI,IAAI,GAAI,CAAC,CAAC,CAC3C,YAAY,QAAQ,CAAC,CACrB,WAAW,OAAO,CAAC,CACnB,gBAAgB,KAAK;CAExB,MAAM,UAAU,IAAI,aAAa,aAAa,OAAO;CACrD,QAAQ,iBAAiB,aAAa;CACtC,QAAQ,UAAU,CAAC,KAAK,CAAC;CACzB,OAAO,QAAQ,QAAQ;AACzB"}
|
|
1
|
+
{"version":3,"file":"meta-conversions-api.mjs","names":[],"sources":["../../src/server/meta-conversions-api.ts"],"sourcesContent":["import {\n AppData,\n Content,\n CustomData,\n EventRequest,\n ExtendedDeviceInfo,\n ServerEvent,\n UserData,\n} from 'facebook-nodejs-business-sdk';\nimport { formatFbc } from '../click-id/index';\nimport { IGNORED_EVENTS } from '../third-parties/ignored-events';\nimport { mapFBEvent } from '../track/fbq';\nimport type { TrackEvent, TrackTags, UserProvidedData } from '../track/types';\nimport { type EventActionSource, resolveActionSource } from './action-source';\nimport { pageLocation } from './page-location';\n\nconst USER_ASSIGNED_COUNTRIES: string[] = ['xk'];\nfunction normalizeCountry(input: string | undefined): string | undefined {\n const country = input?.split(/[-_]/).at(0)?.toLowerCase();\n if (!country) return undefined;\n return USER_ASSIGNED_COUNTRIES.includes(country) ? undefined : country;\n}\n\nfunction getUserData(tags: TrackTags, data: UserProvidedData, eventTimeMs: number) {\n const userData = new UserData();\n\n // set user-provided data\n if (data.email) {\n if (Array.isArray(data.email)) {\n userData.setEmails(data.email);\n } else {\n userData.setEmail(data.email);\n }\n }\n if (data.phone_number) {\n if (Array.isArray(data.phone_number)) {\n userData.setPhones(data.phone_number);\n } else {\n userData.setPhone(data.phone_number);\n }\n }\n if (data.gender) {\n if (data.gender === 'female') {\n userData.setGender('f');\n // oxlint-disable-next-line typescript/no-unnecessary-condition -- user-provided data may carry values outside the declared union at runtime\n } else if (data.gender === 'male') {\n userData.setGender('m');\n }\n }\n if (data.address) {\n if (Array.isArray(data.address)) {\n const firstNames = data.address.map((a) => a.first_name).filter(Boolean);\n const lastNames = data.address.map((a) => a.last_name).filter(Boolean);\n const cities = data.address.map((a) => a.city).filter(Boolean);\n const states = data.address.map((a) => a.region).filter(Boolean);\n const postalCodes = data.address.map((a) => a.postal_code).filter(Boolean);\n const countries = data.address.map((a) => normalizeCountry(a.country)).filter(Boolean);\n\n userData.setFirstNames(firstNames as string[]);\n userData.setLastNames(lastNames as string[]);\n userData.setCities(cities as string[]);\n userData.setStates(states as string[]);\n userData.setZips(postalCodes as string[]);\n userData.setCountries(countries as string[]);\n } else {\n if (data.address.first_name) {\n userData.setFirstName(data.address.first_name);\n userData.setF5First(data.address.first_name.slice(0, 5));\n }\n if (data.address.last_name) {\n userData.setLastName(data.address.last_name);\n userData.setF5Last(data.address.last_name.slice(0, 5));\n }\n if (data.address.city) userData.setCity(data.address.city);\n if (data.address.region) userData.setState(data.address.region);\n if (data.address.postal_code) userData.setZip(data.address.postal_code);\n if (data.address.country) {\n const country = normalizeCountry(data.address.country);\n if (country) userData.setCountry(country);\n }\n }\n }\n if (data.birthday) {\n userData.setDoby(data.birthday.year.toString());\n userData.setDobm(data.birthday.month.toString());\n userData.setDobd(data.birthday.day.toString());\n }\n if (data.user_id && data.user_id.length !== 0) {\n userData.setExternalId(data.user_id);\n }\n if (data.ip_address) {\n userData.setClientIpAddress(data.ip_address);\n }\n if (data.user_agent) {\n userData.setClientUserAgent(data.user_agent);\n }\n if (data.fb_login_id) {\n userData.setFbLoginId(data.fb_login_id);\n }\n if (data.fb_page_id) {\n userData.setPageId(data.fb_page_id);\n }\n\n // set tags info\n if (tags.fbc) {\n userData.setFbc(tags.fbc);\n } else if (tags.fbclid) {\n // ref: https://developers.facebook.com/docs/marketing-api/conversions-api/parameters/fbp-and-fbc#2--format-clickid\n // The formatted ClickID value must be of the form `version.subdomainIndex.creationTime.<fbclid>`, where:\n // - version is always this prefix: fb\n // - subdomainIndex is which domain the cookie is defined on ('com' = 0, 'example.com' = 1, 'www.example.com' = 2)\n // - creationTime is the UNIX time since epoch in milliseconds when the _fbc was stored. If you don't save the _fbc cookie, use the timestamp when you first observed or received this fbclid value\n // - <fbclid> is the value for the fbclid query parameter in the page URL.\n\n // \"the timestamp when you first observed or received this fbclid value\" — the event's own\n // time is the closest thing the server has to that, and it does not move when a queued or\n // retried batch finally goes out.\n userData.setFbc(formatFbc(tags.fbclid, eventTimeMs));\n }\n\n if (tags.fbp) {\n userData.setFbp(tags.fbp);\n }\n if (tags.advertising_id) {\n userData.setMadid(tags.advertising_id);\n }\n if (tags.ip_address && typeof tags.ip_address === 'string') {\n userData.setClientIpAddress(tags.ip_address);\n }\n\n return userData;\n}\n\nfunction getAppData(tags: TrackTags, appPackageName: string) {\n const extinfo = new ExtendedDeviceInfo();\n if (tags.os_name) {\n if (tags.os_name === 'iOS' || tags.os_name === 'iPadOS') {\n extinfo.setExtInfoVersion('i2');\n } else if (tags.os_name === 'Android') {\n extinfo.setExtInfoVersion('a2');\n }\n }\n extinfo.setAppPackageName(appPackageName);\n const shortVersion = tags.release?.split('.').at(0);\n if (shortVersion) {\n extinfo.setShortVersion(shortVersion);\n }\n if (tags.release) {\n extinfo.setLongVersion(tags.release);\n }\n if (tags.os_version) {\n extinfo.setOsVersion(tags.os_version);\n }\n if (tags.device_model_id) {\n extinfo.setDeviceModelName(tags.device_model_id);\n }\n if (tags.language) {\n extinfo.setLocale(tags.language);\n }\n if (tags.screen_width) {\n extinfo.setScreenWidth(tags.screen_width);\n }\n if (tags.screen_height) {\n extinfo.setScreenHeight(tags.screen_height);\n }\n if (tags.device_pixel_ratio) {\n extinfo.setScreenDensity(tags.device_pixel_ratio.toString());\n }\n\n const appData = new AppData();\n appData.setExtinfo(extinfo);\n if (tags.install_referrer) {\n appData.setInstallReferrer(tags.install_referrer);\n }\n if (tags.advertising_id) {\n appData.setAdvertiserTrackingEnabled(true);\n }\n if (tags.install_referrer) {\n appData.setInstallReferrer(tags.install_referrer);\n }\n\n return appData;\n}\n\n// oxlint-disable-next-line @typescript-eslint/no-explicit-any\nfunction getCustomData({ name, properties }: TrackEvent<any>) {\n const data = new CustomData();\n const [_, _name, fbEventProperties] = mapFBEvent(name, properties);\n const {\n value,\n currency,\n content_name,\n content_category,\n content_ids,\n contents,\n content_type,\n // order_id,\n predicted_ltv,\n num_items,\n search_string,\n status,\n // item_number,\n delivery_category,\n ...custom_properties\n } = fbEventProperties;\n // oxlint-disable-next-line typescript/no-unnecessary-condition -- custom event properties may carry `value: null` at runtime despite the declared type\n if (value !== undefined && value !== null) data.setValue(value);\n if (currency) data.setCurrency(currency);\n if (content_name) data.setContentName(content_name);\n if (content_category) data.setContentCategory(content_category);\n if (content_ids) data.setContentIds(content_ids);\n if (contents)\n data.setContents(\n contents.map((c) => {\n const result = new Content().setId(c.id).setQuantity(c.quantity);\n if (c.item_price) result.setItemPrice(c.item_price);\n if (c.title) result.setTitle(c.title);\n if (c.description) result.setDescription(c.description);\n if (c.brand) result.setBrand(c.brand);\n if (c.category) result.setCategory(c.category);\n if (c.delivery_category) result.setDeliveryCategory(c.delivery_category);\n return result;\n })\n );\n if (content_type) data.setContentType(content_type);\n // if (order_id) data.setOrderId(order_id);\n if (predicted_ltv) data.setPredictedLtv(predicted_ltv);\n if (num_items) data.setNumItems(num_items);\n if (search_string) data.setSearchString(search_string);\n if (status) data.setStatus(status.toString());\n // if (item_number) data.setItemNumber(item_number);\n if (delivery_category) data.setDeliveryCategory(delivery_category);\n data.setCustomProperties(custom_properties);\n return data;\n}\n\nexport function getServerEvent(\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n event: TrackEvent<any>,\n data: UserProvidedData,\n appPackageName?: string,\n actionSource?: EventActionSource\n) {\n const eventTimeMs = new Date(event.created_at).getTime();\n const userData = getUserData(event.tags, data, eventTimeMs);\n const customData = getCustomData(event);\n const [_, eventName] = mapFBEvent(event.name, event.properties);\n const serverEvent = new ServerEvent()\n .setEventId(event.tags.idempotency_key ?? event.id)\n .setEventName(eventName)\n .setEventTime(Math.round(eventTimeMs / 1000))\n .setUserData(userData)\n .setCustomData(customData);\n\n const source = resolveActionSource(event.platform, actionSource);\n if (source === 'app' && appPackageName) {\n const appData = getAppData(event.tags, appPackageName);\n serverEvent.setAppData(appData);\n }\n const eventSourceUrl = pageLocation(event.tags);\n if (eventSourceUrl) {\n serverEvent.setEventSourceUrl(eventSourceUrl);\n }\n switch (source) {\n case 'app':\n serverEvent.setActionSource('app');\n break;\n case 'web':\n serverEvent.setActionSource('website');\n break;\n default:\n // `action_source` is required on a server event, so both an offline conversion and an\n // undeterminable platform still have to send something. Meta has no generic offline\n // value: 'physical_store' and 'system_generated' are narrower claims only the caller can\n // make, so everything left lands in Meta's own catch-all.\n serverEvent.setActionSource('other');\n break;\n }\n return serverEvent;\n}\n\n/**\n * The shape `FacebookRequestError` exposes: `status` and `response` are the HTTP status and the\n * parsed error body, and both are null when the request never received a response.\n */\ntype MetaRequestError = { status?: number | null; message?: string; response?: unknown };\n\n/**\n * Meta's SDK rejects on API errors, where every other conversion sender here logs and resolves.\n * Keep the failure inside this module, so one rejected batch cannot fail the caller's request.\n * Never log the error itself: it also carries the access token, in both `url` and `data`.\n */\nfunction logError(error: unknown) {\n const { status, message, response } = (error ?? {}) as MetaRequestError;\n if (typeof status !== 'number') {\n console.error(`Failed to send Meta conversion, network error: ${message ?? String(error)}`);\n return;\n }\n console.error(\n `Failed to send Meta conversion, status: ${status}, body: ${JSON.stringify(response)}`\n );\n}\n\nexport async function sendEvent(\n accessToken: string,\n pixelId: string,\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n event: TrackEvent<any>,\n data: UserProvidedData = {},\n appPackageName?: string,\n actionSource?: EventActionSource\n) {\n if (IGNORED_EVENTS.includes(event.name)) return undefined;\n const request = new EventRequest(accessToken, pixelId);\n const fbEvent = getServerEvent(event, data, appPackageName, actionSource);\n request.setEvents([fbEvent]);\n try {\n return await request.execute();\n } catch (error) {\n logError(error);\n return undefined;\n }\n}\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 appPackageName?: string,\n actionSource?: EventActionSource\n) {\n const fbEvents = events\n .filter((event) => !IGNORED_EVENTS.includes(event.name))\n .map((event) => getServerEvent(event, data, appPackageName, actionSource));\n if (fbEvents.length === 0) return undefined;\n const request = new EventRequest(accessToken, pixelId);\n request.setEvents(fbEvents);\n try {\n return await request.execute();\n } catch (error) {\n logError(error);\n return undefined;\n }\n}\n\nexport async function sendTestEvent(accessToken: string, pixelId: string, testEventCode: string) {\n const extinfo = new ExtendedDeviceInfo()\n .setExtInfoVersion('a2')\n .setAppPackageName('com.some.app')\n .setShortVersion('771')\n .setLongVersion('Version 7.7.1')\n .setOsVersion('10.1.1')\n .setDeviceModelName('OnePlus6')\n .setLocale('en_US')\n .setTimezoneAbbreviation('GMT-1')\n .setCarrier('TMobile')\n .setScreenWidth(1920)\n .setScreenHeight(1080)\n .setScreenDensity('2.00')\n .setCpuCoreCount(2)\n .setTotalDiskSpaceGb(128)\n .setFreeDiskSpaceGb(8)\n .setDeviceTimeZone('USA/New York');\n\n const userData = new UserData().setEmail('test@example.com');\n const appData = new AppData().setExtinfo(extinfo);\n const event = new ServerEvent()\n .setEventId(Math.round(Math.random() * 1000_000).toString())\n .setEventName('TestEvent')\n .setEventTime(Math.round(Date.now() / 1000))\n .setUserData(userData)\n .setAppData(appData)\n .setActionSource('app');\n\n const request = new EventRequest(accessToken, pixelId);\n request.setTestEventCode(testEventCode);\n request.setEvents([event]);\n return request.execute();\n}\n"],"mappings":";;;;;;;AAgBA,MAAM,0BAAoC,CAAC,IAAI;AAC/C,SAAS,iBAAiB,OAA+C;CACvE,MAAM,UAAU,OAAO,MAAM,MAAM,CAAC,CAAC,GAAG,CAAC,CAAC,EAAE,YA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CAAC,CACrB,WAAW,OAAO,CAAC,CACnB,gBAAgB,KAAK;CAExB,MAAM,UAAU,IAAI,aAAa,aAAa,OAAO;CACrD,QAAQ,iBAAiB,aAAa;CACtC,QAAQ,UAAU,CAAC,KAAK,CAAC;CACzB,OAAO,QAAQ,QAAQ;AACzB"}
|
|
@@ -1,6 +1,7 @@
|
|
|
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_server_action_source = require("./action-source.cjs");
|
|
4
|
+
const require_server_page_location = require("./page-location.cjs");
|
|
4
5
|
const require_utils_field = require("../utils/field.cjs");
|
|
5
6
|
const require_track_oaiq = require("../track/oaiq.cjs");
|
|
6
7
|
let _shware_utils = require("@shware/utils");
|
|
@@ -44,7 +45,7 @@ function getServerEvent(event, data, actionSource) {
|
|
|
44
45
|
type,
|
|
45
46
|
custom_event_name: type === "custom" ? event.name : void 0,
|
|
46
47
|
timestamp_ms: new Date(event.created_at).getTime(),
|
|
47
|
-
source_url: event.tags
|
|
48
|
+
source_url: require_server_page_location.pageLocation(event.tags),
|
|
48
49
|
action_source: mapActionSource(event.platform, actionSource),
|
|
49
50
|
user: getUser(data),
|
|
50
51
|
data: eventData
|