@shware/analytics 8.6.0 → 8.7.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/server/linkedin-conversions-api.cjs +28 -6
- package/dist/server/linkedin-conversions-api.cjs.map +1 -1
- package/dist/server/linkedin-conversions-api.d.cts +13 -3
- package/dist/server/linkedin-conversions-api.d.cts.map +1 -1
- package/dist/server/linkedin-conversions-api.d.mts +13 -3
- package/dist/server/linkedin-conversions-api.d.mts.map +1 -1
- package/dist/server/linkedin-conversions-api.mjs +28 -6
- package/dist/server/linkedin-conversions-api.mjs.map +1 -1
- package/package.json +1 -1
|
@@ -6,23 +6,45 @@ let node_crypto = require("node:crypto");
|
|
|
6
6
|
//#region src/server/linkedin-conversions-api.ts
|
|
7
7
|
/**
|
|
8
8
|
* Conversions API Payload Builder: https://www.linkedin.com/developers/payload-builder
|
|
9
|
-
* https://learn.microsoft.com/en-us/linkedin/marketing/conversions/conversions-overview?view=li-lms-
|
|
9
|
+
* https://learn.microsoft.com/en-us/linkedin/marketing/conversions/conversions-overview?view=li-lms-2026-09
|
|
10
10
|
*/
|
|
11
|
+
/**
|
|
12
|
+
* The schema prescribes an exact normalization per field before hashing, and getting it wrong is
|
|
13
|
+
* silent: LinkedIn accepts any 64-char hex digest and simply matches nobody. So these helpers are
|
|
14
|
+
* the difference between attribution and nothing, not between 200 and 400.
|
|
15
|
+
*/
|
|
16
|
+
const sha256 = (value) => (0, node_crypto.createHash)("sha256").update(value).digest("hex");
|
|
17
|
+
/**
|
|
18
|
+
* An email is lower-cased and stripped of whitespace before hashing. Punctuation is left alone —
|
|
19
|
+
* `@` and `.` are the address.
|
|
20
|
+
*/
|
|
21
|
+
const hashEmail = (email) => sha256(email.toLowerCase().replace(/\s/g, ""));
|
|
22
|
+
/**
|
|
23
|
+
* A name is lower-cased and stripped of whitespace *and punctuation* before hashing, so that
|
|
24
|
+
* `O'Brien`, `o brien` and `obrien` all land on the same digest. UTF-8 is what `update` already
|
|
25
|
+
* encodes with.
|
|
26
|
+
*
|
|
27
|
+
* The schema's wording ("lowercase with no spaces or punctuation") leaves room to read the
|
|
28
|
+
* apostrophe either way, so this is checked against its own worked example rather than guessed:
|
|
29
|
+
* the `hashedFirstName` / `hashedLastName` digests it prints are sha256('mary') and
|
|
30
|
+
* sha256('obrien') — Mary O'Brien with the apostrophe removed, not escaped or kept.
|
|
31
|
+
*/
|
|
32
|
+
const hashName = (name) => sha256(name.toLowerCase().replace(/[\s\p{P}]/gu, ""));
|
|
11
33
|
async function sendEvents(accessToken, config, events, data = {}) {
|
|
12
34
|
const eventNames = Object.keys(config);
|
|
13
35
|
const address = require_utils_field.getFirst(data.address);
|
|
14
36
|
const userIds = [];
|
|
15
37
|
const externalIds = data.user_id ? [data.user_id] : void 0;
|
|
16
38
|
const userInfo = address?.first_name && address.last_name ? {
|
|
17
|
-
|
|
18
|
-
|
|
39
|
+
hashedFirstName: hashName(address.first_name),
|
|
40
|
+
hashedLastName: hashName(address.last_name),
|
|
19
41
|
countryCode: address.country
|
|
20
42
|
} : void 0;
|
|
21
43
|
if (data.email) {
|
|
22
44
|
const email = require_utils_field.getFirst(data.email);
|
|
23
45
|
if (email) userIds.push({
|
|
24
46
|
idType: "SHA256_EMAIL",
|
|
25
|
-
idValue: (
|
|
47
|
+
idValue: hashEmail(email)
|
|
26
48
|
});
|
|
27
49
|
}
|
|
28
50
|
const dto = { elements: events.filter((event) => eventNames.includes(event.name) && !require_third_parties_ignored_events.IGNORED_EVENTS.includes(event.name)).map((event) => ({
|
|
@@ -41,7 +63,7 @@ async function sendEvents(accessToken, config, events, data = {}) {
|
|
|
41
63
|
userInfo,
|
|
42
64
|
externalIds
|
|
43
65
|
}
|
|
44
|
-
})) };
|
|
66
|
+
})).filter(({ user }) => user.userIds.length > 0 || !!user.userInfo || !!user.externalIds || !!user.lead) };
|
|
45
67
|
if (dto.elements.length === 0) return;
|
|
46
68
|
try {
|
|
47
69
|
const response = await (0, _shware_utils.fetch)("https://api.linkedin.com/rest/conversionEvents", {
|
|
@@ -49,7 +71,7 @@ async function sendEvents(accessToken, config, events, data = {}) {
|
|
|
49
71
|
headers: {
|
|
50
72
|
Authorization: `Bearer ${accessToken}`,
|
|
51
73
|
"Content-Type": "application/json",
|
|
52
|
-
"LinkedIn-Version": "
|
|
74
|
+
"LinkedIn-Version": "202609",
|
|
53
75
|
"X-Restli-Protocol-Version": "2.0.0",
|
|
54
76
|
"X-RestLi-Method": "BATCH_CREATE"
|
|
55
77
|
},
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"linkedin-conversions-api.cjs","names":["
|
|
1
|
+
{"version":3,"file":"linkedin-conversions-api.cjs","names":["createHash","getFirst","IGNORED_EVENTS","fetch"],"sources":["../../src/server/linkedin-conversions-api.ts"],"sourcesContent":["/**\n * Conversions API Payload Builder: https://www.linkedin.com/developers/payload-builder\n * https://learn.microsoft.com/en-us/linkedin/marketing/conversions/conversions-overview?view=li-lms-2026-09\n */\nimport { createHash } from 'node:crypto';\nimport { fetch } from '@shware/utils';\nimport { IGNORED_EVENTS } from '../third-parties/ignored-events';\nimport type { TrackEvent, UserProvidedData } from '../track/types';\nimport { getFirst } from '../utils/field';\n\n/**\n * The identifier types LinkedIn matches on, as of version 202609. `ORACLE_MOAT_ID` used to be\n * here and is no longer in the schema; the IP and Android ones are.\n */\ntype UserIdType =\n | 'SHA256_EMAIL'\n | 'LINKEDIN_FIRST_PARTY_ADS_TRACKING_UUID'\n | 'ACXIOM_ID'\n | 'PLAINTEXT_IP_ADDRESS'\n | 'SHA256_IP_ADDRESS'\n | 'GOOGLE_AID';\n\nexport interface CreateLinkedinEventDTO {\n /**\n * For any conversion that you want to send through multiple methods, such as Insight Tag and\n * Conversions API, you must create a conversion rule for each data source (browser and server).\n * Then, you can implement a logic to pick up the eventId from the browser and send it with the\n * corresponding event from your server. If we receive an Insight Tag event and a Conversions API\n * event from the same account with the same eventId, we discard the Conversions API event and\n * count only the Insight Tag event in campaign reporting.\n */\n eventId?: string;\n\n /**\n * Replace <id> with the conversion ID extracted when creating the conversion rule\n * (e.g. urn:lla:llaPartnerConversion:<id>).\n */\n conversion: `urn:lla:llaPartnerConversion:${number}`;\n\n /** Epoch timestamp in milliseconds at which the conversion event happened. */\n conversionHappenedAt: number;\n conversionValue: { currencyCode: string; amount: string };\n user: {\n userIds: { idType: UserIdType; idValue: string }[];\n /**\n * Probabilistic matching fields. `hashedFirstName` / `hashedLastName` arrived in 202609 and\n * are what we send; the plaintext `firstName` / `lastName` they replace are still accepted by\n * the API but are not listed here, because sending a name in the clear is not something this\n * client should make easy to reach for.\n */\n userInfo?: {\n hashedFirstName?: string;\n hashedLastName?: string;\n companyName?: string;\n countryCode?: string;\n title?: string;\n };\n\n /**\n * The maximum supported size of the list is 1 at the moment. If the list contains multiple\n * values, only the first value will be used.\n */\n externalIds?: [string, ...string[]];\n\n /**\n * This is generated when users submit the Linkedin Lead-gen form\n * (e.g. urn:li:leadGenFormResponse:<id>).\n */\n lead?: `urn:li:leadGenFormResponse:${string}`;\n };\n}\n\nexport interface CreateMultipleLinkedinEventsDTO {\n elements: CreateLinkedinEventDTO[];\n}\n\n/**\n * The schema prescribes an exact normalization per field before hashing, and getting it wrong is\n * silent: LinkedIn accepts any 64-char hex digest and simply matches nobody. So these helpers are\n * the difference between attribution and nothing, not between 200 and 400.\n */\nconst sha256 = (value: string) => createHash('sha256').update(value).digest('hex');\n\n/**\n * An email is lower-cased and stripped of whitespace before hashing. Punctuation is left alone —\n * `@` and `.` are the address.\n */\nconst hashEmail = (email: string) => sha256(email.toLowerCase().replace(/\\s/g, ''));\n\n/**\n * A name is lower-cased and stripped of whitespace *and punctuation* before hashing, so that\n * `O'Brien`, `o brien` and `obrien` all land on the same digest. UTF-8 is what `update` already\n * encodes with.\n *\n * The schema's wording (\"lowercase with no spaces or punctuation\") leaves room to read the\n * apostrophe either way, so this is checked against its own worked example rather than guessed:\n * the `hashedFirstName` / `hashedLastName` digests it prints are sha256('mary') and\n * sha256('obrien') — Mary O'Brien with the apostrophe removed, not escaped or kept.\n */\nconst hashName = (name: string) => sha256(name.toLowerCase().replace(/[\\s\\p{P}]/gu, ''));\n\nexport type LinkedinConversionConfig = Record<Lowercase<string>, number>;\n\nexport async function sendEvents(\n accessToken: string,\n config: LinkedinConversionConfig,\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n events: TrackEvent<any>[],\n data: UserProvidedData = {}\n) {\n const eventNames = Object.keys(config);\n const address = getFirst(data.address);\n const userIds: { idType: UserIdType; idValue: string }[] = [];\n const externalIds: [string, ...string[]] | undefined = data.user_id ? [data.user_id] : undefined;\n const userInfo =\n address?.first_name && address.last_name\n ? {\n hashedFirstName: hashName(address.first_name),\n hashedLastName: hashName(address.last_name),\n countryCode: address.country,\n }\n : undefined;\n\n if (data.email) {\n const email = getFirst(data.email);\n if (email) userIds.push({ idType: 'SHA256_EMAIL', idValue: hashEmail(email) });\n }\n\n const dto: CreateMultipleLinkedinEventsDTO = {\n elements: events\n .filter((event) => eventNames.includes(event.name) && !IGNORED_EVENTS.includes(event.name))\n .map((event): CreateLinkedinEventDTO => ({\n eventId: event.id,\n conversion: `urn:lla:llaPartnerConversion:${config[event.name]}`,\n conversionHappenedAt: new Date(event.created_at).getTime(),\n conversionValue: {\n currencyCode: event.properties?.currency?.toUpperCase() ?? 'USD',\n amount: event.properties?.value?.toString() ?? '0',\n },\n user: {\n userIds: event.tags.li_fat_id\n ? [\n {\n idType: 'LINKEDIN_FIRST_PARTY_ADS_TRACKING_UUID',\n idValue: event.tags.li_fat_id,\n },\n ...userIds,\n ]\n : userIds,\n userInfo,\n externalIds,\n },\n }))\n // An element carrying no identifier at all fails validation, and LinkedIn fails the whole\n // batch when one element fails — so a single anonymous event would discard every\n // identifiable conversion sent alongside it. Dropped here instead.\n .filter(\n ({ user }) =>\n user.userIds.length > 0 || !!user.userInfo || !!user.externalIds || !!user.lead\n ),\n };\n\n if (dto.elements.length === 0) return;\n try {\n const response = await fetch('https://api.linkedin.com/rest/conversionEvents', {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${accessToken}`,\n 'Content-Type': 'application/json',\n 'LinkedIn-Version': '202609',\n 'X-Restli-Protocol-Version': '2.0.0',\n 'X-RestLi-Method': 'BATCH_CREATE',\n },\n body: JSON.stringify(dto),\n });\n\n if (response.ok) return;\n const { status } = response;\n const message = await response.text();\n console.error(`Failed to send LinkedIn conversion, status: ${status}, body: ${message}`);\n } catch (error) {\n console.error('Failed to send LinkedIn conversion, network error:', error);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;AAiFA,MAAM,UAAU,WAAA,GAAkBA,YAAAA,WAAAA,CAAW,QAAQ,CAAC,CAAC,OAAO,KAAK,CAAC,CAAC,OAAO,KAAK;;;;;AAMjF,MAAM,aAAa,UAAkB,OAAO,MAAM,YAAY,CAAC,CAAC,QAAQ,OAAO,EAAE,CAAC;;;;;;;;;;;AAYlF,MAAM,YAAY,SAAiB,OAAO,KAAK,YAAY,CAAC,CAAC,QAAQ,eAAe,EAAE,CAAC;AAIvF,eAAsB,WACpB,aACA,QAEA,QACA,OAAyB,CAAC,GAC1B;CACA,MAAM,aAAa,OAAO,KAAK,MAAM;CACrC,MAAM,UAAUC,oBAAAA,SAAS,KAAK,OAAO;CACrC,MAAM,UAAqD,CAAC;CAC5D,MAAM,cAAiD,KAAK,UAAU,CAAC,KAAK,OAAO,IAAI,KAAA;CACvF,MAAM,WACJ,SAAS,cAAc,QAAQ,YAC3B;EACE,iBAAiB,SAAS,QAAQ,UAAU;EAC5C,gBAAgB,SAAS,QAAQ,SAAS;EAC1C,aAAa,QAAQ;CACvB,IACA,KAAA;CAEN,IAAI,KAAK,OAAO;EACd,MAAM,QAAQA,oBAAAA,SAAS,KAAK,KAAK;EACjC,IAAI,OAAO,QAAQ,KAAK;GAAE,QAAQ;GAAgB,SAAS,UAAU,KAAK;EAAE,CAAC;CAC/E;CAEA,MAAM,MAAuC,EAC3C,UAAU,OACP,QAAQ,UAAU,WAAW,SAAS,MAAM,IAAI,KAAK,CAACC,qCAAAA,eAAe,SAAS,MAAM,IAAI,CAAC,CAAC,CAC1F,KAAK,WAAmC;EACvC,SAAS,MAAM;EACf,YAAY,gCAAgC,OAAO,MAAM;EACzD,sBAAsB,IAAI,KAAK,MAAM,UAAU,CAAC,CAAC,QAAQ;EACzD,iBAAiB;GACf,cAAc,MAAM,YAAY,UAAU,YAAY,KAAK;GAC3D,QAAQ,MAAM,YAAY,OAAO,SAAS,KAAK;EACjD;EACA,MAAM;GACJ,SAAS,MAAM,KAAK,YAChB,CACE;IACE,QAAQ;IACR,SAAS,MAAM,KAAK;GACtB,GACA,GAAG,OACL,IACA;GACJ;GACA;EACF;CACF,EAAE,CAAC,CAIF,QACE,EAAE,WACD,KAAK,QAAQ,SAAS,KAAK,CAAC,CAAC,KAAK,YAAY,CAAC,CAAC,KAAK,eAAe,CAAC,CAAC,KAAK,IAC/E,EACJ;CAEA,IAAI,IAAI,SAAS,WAAW,GAAG;CAC/B,IAAI;EACF,MAAM,WAAW,OAAA,GAAMC,cAAAA,MAAAA,CAAM,kDAAkD;GAC7E,QAAQ;GACR,SAAS;IACP,eAAe,UAAU;IACzB,gBAAgB;IAChB,oBAAoB;IACpB,6BAA6B;IAC7B,mBAAmB;GACrB;GACA,MAAM,KAAK,UAAU,GAAG;EAC1B,CAAC;EAED,IAAI,SAAS,IAAI;EACjB,MAAM,EAAE,WAAW;EACnB,MAAM,UAAU,MAAM,SAAS,KAAK;EACpC,QAAQ,MAAM,+CAA+C,OAAO,UAAU,SAAS;CACzF,SAAS,OAAO;EACd,QAAQ,MAAM,sDAAsD,KAAK;CAC3E;AACF"}
|
|
@@ -1,6 +1,10 @@
|
|
|
1
1
|
import { TrackEvent, UserProvidedData } from "../track/types.cjs";
|
|
2
2
|
//#region src/server/linkedin-conversions-api.d.ts
|
|
3
|
-
|
|
3
|
+
/**
|
|
4
|
+
* The identifier types LinkedIn matches on, as of version 202609. `ORACLE_MOAT_ID` used to be
|
|
5
|
+
* here and is no longer in the schema; the IP and Android ones are.
|
|
6
|
+
*/
|
|
7
|
+
type UserIdType = 'SHA256_EMAIL' | 'LINKEDIN_FIRST_PARTY_ADS_TRACKING_UUID' | 'ACXIOM_ID' | 'PLAINTEXT_IP_ADDRESS' | 'SHA256_IP_ADDRESS' | 'GOOGLE_AID';
|
|
4
8
|
interface CreateLinkedinEventDTO {
|
|
5
9
|
/**
|
|
6
10
|
* For any conversion that you want to send through multiple methods, such as Insight Tag and
|
|
@@ -27,9 +31,15 @@ interface CreateLinkedinEventDTO {
|
|
|
27
31
|
idType: UserIdType;
|
|
28
32
|
idValue: string;
|
|
29
33
|
}[];
|
|
34
|
+
/**
|
|
35
|
+
* Probabilistic matching fields. `hashedFirstName` / `hashedLastName` arrived in 202609 and
|
|
36
|
+
* are what we send; the plaintext `firstName` / `lastName` they replace are still accepted by
|
|
37
|
+
* the API but are not listed here, because sending a name in the clear is not something this
|
|
38
|
+
* client should make easy to reach for.
|
|
39
|
+
*/
|
|
30
40
|
userInfo?: {
|
|
31
|
-
|
|
32
|
-
|
|
41
|
+
hashedFirstName?: string;
|
|
42
|
+
hashedLastName?: string;
|
|
33
43
|
companyName?: string;
|
|
34
44
|
countryCode?: string;
|
|
35
45
|
title?: string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"linkedin-conversions-api.d.cts","names":[],"sources":["../../src/server/linkedin-conversions-api.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"linkedin-conversions-api.d.cts","names":[],"sources":["../../src/server/linkedin-conversions-api.ts"],"mappings":";;;;;;KAcK;UAQY;;;;;;;;;EASf;;;;;EAMA;;EAGA;EACA;IAAmB;IAAsB;;EACzC;IACE;MAAW,QAAQ;MAAY;;;;;;;;IAO/B;MACE;MACA;MACA;MACA;MACA;;;;;;IAOF;;;;;IAMA;;;UAIa;EACf,UAAU;;KA4BA,2BAA2B,OAAO;iBAExB,WACpB,qBACA,QAAQ,0BAER,QAAQ,mBACR,OAAM,mBAAqB"}
|
|
@@ -1,6 +1,10 @@
|
|
|
1
1
|
import { TrackEvent, UserProvidedData } from "../track/types.mjs";
|
|
2
2
|
//#region src/server/linkedin-conversions-api.d.ts
|
|
3
|
-
|
|
3
|
+
/**
|
|
4
|
+
* The identifier types LinkedIn matches on, as of version 202609. `ORACLE_MOAT_ID` used to be
|
|
5
|
+
* here and is no longer in the schema; the IP and Android ones are.
|
|
6
|
+
*/
|
|
7
|
+
type UserIdType = 'SHA256_EMAIL' | 'LINKEDIN_FIRST_PARTY_ADS_TRACKING_UUID' | 'ACXIOM_ID' | 'PLAINTEXT_IP_ADDRESS' | 'SHA256_IP_ADDRESS' | 'GOOGLE_AID';
|
|
4
8
|
interface CreateLinkedinEventDTO {
|
|
5
9
|
/**
|
|
6
10
|
* For any conversion that you want to send through multiple methods, such as Insight Tag and
|
|
@@ -27,9 +31,15 @@ interface CreateLinkedinEventDTO {
|
|
|
27
31
|
idType: UserIdType;
|
|
28
32
|
idValue: string;
|
|
29
33
|
}[];
|
|
34
|
+
/**
|
|
35
|
+
* Probabilistic matching fields. `hashedFirstName` / `hashedLastName` arrived in 202609 and
|
|
36
|
+
* are what we send; the plaintext `firstName` / `lastName` they replace are still accepted by
|
|
37
|
+
* the API but are not listed here, because sending a name in the clear is not something this
|
|
38
|
+
* client should make easy to reach for.
|
|
39
|
+
*/
|
|
30
40
|
userInfo?: {
|
|
31
|
-
|
|
32
|
-
|
|
41
|
+
hashedFirstName?: string;
|
|
42
|
+
hashedLastName?: string;
|
|
33
43
|
companyName?: string;
|
|
34
44
|
countryCode?: string;
|
|
35
45
|
title?: string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"linkedin-conversions-api.d.mts","names":[],"sources":["../../src/server/linkedin-conversions-api.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"linkedin-conversions-api.d.mts","names":[],"sources":["../../src/server/linkedin-conversions-api.ts"],"mappings":";;;;;;KAcK;UAQY;;;;;;;;;EASf;;;;;EAMA;;EAGA;EACA;IAAmB;IAAsB;;EACzC;IACE;MAAW,QAAQ;MAAY;;;;;;;;IAO/B;MACE;MACA;MACA;MACA;MACA;;;;;;IAOF;;;;;IAMA;;;UAIa;EACf,UAAU;;KA4BA,2BAA2B,OAAO;iBAExB,WACpB,qBACA,QAAQ,0BAER,QAAQ,mBACR,OAAM,mBAAqB"}
|
|
@@ -5,23 +5,45 @@ import { createHash } from "node:crypto";
|
|
|
5
5
|
//#region src/server/linkedin-conversions-api.ts
|
|
6
6
|
/**
|
|
7
7
|
* Conversions API Payload Builder: https://www.linkedin.com/developers/payload-builder
|
|
8
|
-
* https://learn.microsoft.com/en-us/linkedin/marketing/conversions/conversions-overview?view=li-lms-
|
|
8
|
+
* https://learn.microsoft.com/en-us/linkedin/marketing/conversions/conversions-overview?view=li-lms-2026-09
|
|
9
9
|
*/
|
|
10
|
+
/**
|
|
11
|
+
* The schema prescribes an exact normalization per field before hashing, and getting it wrong is
|
|
12
|
+
* silent: LinkedIn accepts any 64-char hex digest and simply matches nobody. So these helpers are
|
|
13
|
+
* the difference between attribution and nothing, not between 200 and 400.
|
|
14
|
+
*/
|
|
15
|
+
const sha256 = (value) => createHash("sha256").update(value).digest("hex");
|
|
16
|
+
/**
|
|
17
|
+
* An email is lower-cased and stripped of whitespace before hashing. Punctuation is left alone —
|
|
18
|
+
* `@` and `.` are the address.
|
|
19
|
+
*/
|
|
20
|
+
const hashEmail = (email) => sha256(email.toLowerCase().replace(/\s/g, ""));
|
|
21
|
+
/**
|
|
22
|
+
* A name is lower-cased and stripped of whitespace *and punctuation* before hashing, so that
|
|
23
|
+
* `O'Brien`, `o brien` and `obrien` all land on the same digest. UTF-8 is what `update` already
|
|
24
|
+
* encodes with.
|
|
25
|
+
*
|
|
26
|
+
* The schema's wording ("lowercase with no spaces or punctuation") leaves room to read the
|
|
27
|
+
* apostrophe either way, so this is checked against its own worked example rather than guessed:
|
|
28
|
+
* the `hashedFirstName` / `hashedLastName` digests it prints are sha256('mary') and
|
|
29
|
+
* sha256('obrien') — Mary O'Brien with the apostrophe removed, not escaped or kept.
|
|
30
|
+
*/
|
|
31
|
+
const hashName = (name) => sha256(name.toLowerCase().replace(/[\s\p{P}]/gu, ""));
|
|
10
32
|
async function sendEvents(accessToken, config, events, data = {}) {
|
|
11
33
|
const eventNames = Object.keys(config);
|
|
12
34
|
const address = getFirst(data.address);
|
|
13
35
|
const userIds = [];
|
|
14
36
|
const externalIds = data.user_id ? [data.user_id] : void 0;
|
|
15
37
|
const userInfo = address?.first_name && address.last_name ? {
|
|
16
|
-
|
|
17
|
-
|
|
38
|
+
hashedFirstName: hashName(address.first_name),
|
|
39
|
+
hashedLastName: hashName(address.last_name),
|
|
18
40
|
countryCode: address.country
|
|
19
41
|
} : void 0;
|
|
20
42
|
if (data.email) {
|
|
21
43
|
const email = getFirst(data.email);
|
|
22
44
|
if (email) userIds.push({
|
|
23
45
|
idType: "SHA256_EMAIL",
|
|
24
|
-
idValue:
|
|
46
|
+
idValue: hashEmail(email)
|
|
25
47
|
});
|
|
26
48
|
}
|
|
27
49
|
const dto = { elements: events.filter((event) => eventNames.includes(event.name) && !IGNORED_EVENTS.includes(event.name)).map((event) => ({
|
|
@@ -40,7 +62,7 @@ async function sendEvents(accessToken, config, events, data = {}) {
|
|
|
40
62
|
userInfo,
|
|
41
63
|
externalIds
|
|
42
64
|
}
|
|
43
|
-
})) };
|
|
65
|
+
})).filter(({ user }) => user.userIds.length > 0 || !!user.userInfo || !!user.externalIds || !!user.lead) };
|
|
44
66
|
if (dto.elements.length === 0) return;
|
|
45
67
|
try {
|
|
46
68
|
const response = await fetch("https://api.linkedin.com/rest/conversionEvents", {
|
|
@@ -48,7 +70,7 @@ async function sendEvents(accessToken, config, events, data = {}) {
|
|
|
48
70
|
headers: {
|
|
49
71
|
Authorization: `Bearer ${accessToken}`,
|
|
50
72
|
"Content-Type": "application/json",
|
|
51
|
-
"LinkedIn-Version": "
|
|
73
|
+
"LinkedIn-Version": "202609",
|
|
52
74
|
"X-Restli-Protocol-Version": "2.0.0",
|
|
53
75
|
"X-RestLi-Method": "BATCH_CREATE"
|
|
54
76
|
},
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"linkedin-conversions-api.mjs","names":[],"sources":["../../src/server/linkedin-conversions-api.ts"],"sourcesContent":["/**\n * Conversions API Payload Builder: https://www.linkedin.com/developers/payload-builder\n * https://learn.microsoft.com/en-us/linkedin/marketing/conversions/conversions-overview?view=li-lms-
|
|
1
|
+
{"version":3,"file":"linkedin-conversions-api.mjs","names":[],"sources":["../../src/server/linkedin-conversions-api.ts"],"sourcesContent":["/**\n * Conversions API Payload Builder: https://www.linkedin.com/developers/payload-builder\n * https://learn.microsoft.com/en-us/linkedin/marketing/conversions/conversions-overview?view=li-lms-2026-09\n */\nimport { createHash } from 'node:crypto';\nimport { fetch } from '@shware/utils';\nimport { IGNORED_EVENTS } from '../third-parties/ignored-events';\nimport type { TrackEvent, UserProvidedData } from '../track/types';\nimport { getFirst } from '../utils/field';\n\n/**\n * The identifier types LinkedIn matches on, as of version 202609. `ORACLE_MOAT_ID` used to be\n * here and is no longer in the schema; the IP and Android ones are.\n */\ntype UserIdType =\n | 'SHA256_EMAIL'\n | 'LINKEDIN_FIRST_PARTY_ADS_TRACKING_UUID'\n | 'ACXIOM_ID'\n | 'PLAINTEXT_IP_ADDRESS'\n | 'SHA256_IP_ADDRESS'\n | 'GOOGLE_AID';\n\nexport interface CreateLinkedinEventDTO {\n /**\n * For any conversion that you want to send through multiple methods, such as Insight Tag and\n * Conversions API, you must create a conversion rule for each data source (browser and server).\n * Then, you can implement a logic to pick up the eventId from the browser and send it with the\n * corresponding event from your server. If we receive an Insight Tag event and a Conversions API\n * event from the same account with the same eventId, we discard the Conversions API event and\n * count only the Insight Tag event in campaign reporting.\n */\n eventId?: string;\n\n /**\n * Replace <id> with the conversion ID extracted when creating the conversion rule\n * (e.g. urn:lla:llaPartnerConversion:<id>).\n */\n conversion: `urn:lla:llaPartnerConversion:${number}`;\n\n /** Epoch timestamp in milliseconds at which the conversion event happened. */\n conversionHappenedAt: number;\n conversionValue: { currencyCode: string; amount: string };\n user: {\n userIds: { idType: UserIdType; idValue: string }[];\n /**\n * Probabilistic matching fields. `hashedFirstName` / `hashedLastName` arrived in 202609 and\n * are what we send; the plaintext `firstName` / `lastName` they replace are still accepted by\n * the API but are not listed here, because sending a name in the clear is not something this\n * client should make easy to reach for.\n */\n userInfo?: {\n hashedFirstName?: string;\n hashedLastName?: string;\n companyName?: string;\n countryCode?: string;\n title?: string;\n };\n\n /**\n * The maximum supported size of the list is 1 at the moment. If the list contains multiple\n * values, only the first value will be used.\n */\n externalIds?: [string, ...string[]];\n\n /**\n * This is generated when users submit the Linkedin Lead-gen form\n * (e.g. urn:li:leadGenFormResponse:<id>).\n */\n lead?: `urn:li:leadGenFormResponse:${string}`;\n };\n}\n\nexport interface CreateMultipleLinkedinEventsDTO {\n elements: CreateLinkedinEventDTO[];\n}\n\n/**\n * The schema prescribes an exact normalization per field before hashing, and getting it wrong is\n * silent: LinkedIn accepts any 64-char hex digest and simply matches nobody. So these helpers are\n * the difference between attribution and nothing, not between 200 and 400.\n */\nconst sha256 = (value: string) => createHash('sha256').update(value).digest('hex');\n\n/**\n * An email is lower-cased and stripped of whitespace before hashing. Punctuation is left alone —\n * `@` and `.` are the address.\n */\nconst hashEmail = (email: string) => sha256(email.toLowerCase().replace(/\\s/g, ''));\n\n/**\n * A name is lower-cased and stripped of whitespace *and punctuation* before hashing, so that\n * `O'Brien`, `o brien` and `obrien` all land on the same digest. UTF-8 is what `update` already\n * encodes with.\n *\n * The schema's wording (\"lowercase with no spaces or punctuation\") leaves room to read the\n * apostrophe either way, so this is checked against its own worked example rather than guessed:\n * the `hashedFirstName` / `hashedLastName` digests it prints are sha256('mary') and\n * sha256('obrien') — Mary O'Brien with the apostrophe removed, not escaped or kept.\n */\nconst hashName = (name: string) => sha256(name.toLowerCase().replace(/[\\s\\p{P}]/gu, ''));\n\nexport type LinkedinConversionConfig = Record<Lowercase<string>, number>;\n\nexport async function sendEvents(\n accessToken: string,\n config: LinkedinConversionConfig,\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n events: TrackEvent<any>[],\n data: UserProvidedData = {}\n) {\n const eventNames = Object.keys(config);\n const address = getFirst(data.address);\n const userIds: { idType: UserIdType; idValue: string }[] = [];\n const externalIds: [string, ...string[]] | undefined = data.user_id ? [data.user_id] : undefined;\n const userInfo =\n address?.first_name && address.last_name\n ? {\n hashedFirstName: hashName(address.first_name),\n hashedLastName: hashName(address.last_name),\n countryCode: address.country,\n }\n : undefined;\n\n if (data.email) {\n const email = getFirst(data.email);\n if (email) userIds.push({ idType: 'SHA256_EMAIL', idValue: hashEmail(email) });\n }\n\n const dto: CreateMultipleLinkedinEventsDTO = {\n elements: events\n .filter((event) => eventNames.includes(event.name) && !IGNORED_EVENTS.includes(event.name))\n .map((event): CreateLinkedinEventDTO => ({\n eventId: event.id,\n conversion: `urn:lla:llaPartnerConversion:${config[event.name]}`,\n conversionHappenedAt: new Date(event.created_at).getTime(),\n conversionValue: {\n currencyCode: event.properties?.currency?.toUpperCase() ?? 'USD',\n amount: event.properties?.value?.toString() ?? '0',\n },\n user: {\n userIds: event.tags.li_fat_id\n ? [\n {\n idType: 'LINKEDIN_FIRST_PARTY_ADS_TRACKING_UUID',\n idValue: event.tags.li_fat_id,\n },\n ...userIds,\n ]\n : userIds,\n userInfo,\n externalIds,\n },\n }))\n // An element carrying no identifier at all fails validation, and LinkedIn fails the whole\n // batch when one element fails — so a single anonymous event would discard every\n // identifiable conversion sent alongside it. Dropped here instead.\n .filter(\n ({ user }) =>\n user.userIds.length > 0 || !!user.userInfo || !!user.externalIds || !!user.lead\n ),\n };\n\n if (dto.elements.length === 0) return;\n try {\n const response = await fetch('https://api.linkedin.com/rest/conversionEvents', {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${accessToken}`,\n 'Content-Type': 'application/json',\n 'LinkedIn-Version': '202609',\n 'X-Restli-Protocol-Version': '2.0.0',\n 'X-RestLi-Method': 'BATCH_CREATE',\n },\n body: JSON.stringify(dto),\n });\n\n if (response.ok) return;\n const { status } = response;\n const message = await response.text();\n console.error(`Failed to send LinkedIn conversion, status: ${status}, body: ${message}`);\n } catch (error) {\n console.error('Failed to send LinkedIn conversion, network error:', error);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;AAiFA,MAAM,UAAU,UAAkB,WAAW,QAAQ,CAAC,CAAC,OAAO,KAAK,CAAC,CAAC,OAAO,KAAK;;;;;AAMjF,MAAM,aAAa,UAAkB,OAAO,MAAM,YAAY,CAAC,CAAC,QAAQ,OAAO,EAAE,CAAC;;;;;;;;;;;AAYlF,MAAM,YAAY,SAAiB,OAAO,KAAK,YAAY,CAAC,CAAC,QAAQ,eAAe,EAAE,CAAC;AAIvF,eAAsB,WACpB,aACA,QAEA,QACA,OAAyB,CAAC,GAC1B;CACA,MAAM,aAAa,OAAO,KAAK,MAAM;CACrC,MAAM,UAAU,SAAS,KAAK,OAAO;CACrC,MAAM,UAAqD,CAAC;CAC5D,MAAM,cAAiD,KAAK,UAAU,CAAC,KAAK,OAAO,IAAI,KAAA;CACvF,MAAM,WACJ,SAAS,cAAc,QAAQ,YAC3B;EACE,iBAAiB,SAAS,QAAQ,UAAU;EAC5C,gBAAgB,SAAS,QAAQ,SAAS;EAC1C,aAAa,QAAQ;CACvB,IACA,KAAA;CAEN,IAAI,KAAK,OAAO;EACd,MAAM,QAAQ,SAAS,KAAK,KAAK;EACjC,IAAI,OAAO,QAAQ,KAAK;GAAE,QAAQ;GAAgB,SAAS,UAAU,KAAK;EAAE,CAAC;CAC/E;CAEA,MAAM,MAAuC,EAC3C,UAAU,OACP,QAAQ,UAAU,WAAW,SAAS,MAAM,IAAI,KAAK,CAAC,eAAe,SAAS,MAAM,IAAI,CAAC,CAAC,CAC1F,KAAK,WAAmC;EACvC,SAAS,MAAM;EACf,YAAY,gCAAgC,OAAO,MAAM;EACzD,sBAAsB,IAAI,KAAK,MAAM,UAAU,CAAC,CAAC,QAAQ;EACzD,iBAAiB;GACf,cAAc,MAAM,YAAY,UAAU,YAAY,KAAK;GAC3D,QAAQ,MAAM,YAAY,OAAO,SAAS,KAAK;EACjD;EACA,MAAM;GACJ,SAAS,MAAM,KAAK,YAChB,CACE;IACE,QAAQ;IACR,SAAS,MAAM,KAAK;GACtB,GACA,GAAG,OACL,IACA;GACJ;GACA;EACF;CACF,EAAE,CAAC,CAIF,QACE,EAAE,WACD,KAAK,QAAQ,SAAS,KAAK,CAAC,CAAC,KAAK,YAAY,CAAC,CAAC,KAAK,eAAe,CAAC,CAAC,KAAK,IAC/E,EACJ;CAEA,IAAI,IAAI,SAAS,WAAW,GAAG;CAC/B,IAAI;EACF,MAAM,WAAW,MAAM,MAAM,kDAAkD;GAC7E,QAAQ;GACR,SAAS;IACP,eAAe,UAAU;IACzB,gBAAgB;IAChB,oBAAoB;IACpB,6BAA6B;IAC7B,mBAAmB;GACrB;GACA,MAAM,KAAK,UAAU,GAAG;EAC1B,CAAC;EAED,IAAI,SAAS,IAAI;EACjB,MAAM,EAAE,WAAW;EACnB,MAAM,UAAU,MAAM,SAAS,KAAK;EACpC,QAAQ,MAAM,+CAA+C,OAAO,UAAU,SAAS;CACzF,SAAS,OAAO;EACd,QAAQ,MAAM,sDAAsD,KAAK;CAC3E;AACF"}
|