@shware/analytics 8.6.0 → 8.7.1
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/dist/track/index.cjs +30 -9
- package/dist/track/index.cjs.map +1 -1
- package/dist/track/index.d.cts.map +1 -1
- package/dist/track/index.d.mts.map +1 -1
- package/dist/track/index.mjs +30 -9
- package/dist/track/index.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,oBAAA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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"}
|
package/dist/track/index.cjs
CHANGED
|
@@ -38,18 +38,38 @@ async function captureTags() {
|
|
|
38
38
|
return require_setup_index.cache.tags ?? {};
|
|
39
39
|
}
|
|
40
40
|
}
|
|
41
|
+
/**
|
|
42
|
+
* The `session_start` a failed batch took down with it, kept for the next batch of the same
|
|
43
|
+
* session. `fetch` has already retried the transient failures by the time a batch fails here;
|
|
44
|
+
* what remains is a batch the server rejected outright — one invalid event fails the whole batch,
|
|
45
|
+
* and `session_start` with it — or a network that stayed down past the retries. Neither is a
|
|
46
|
+
* reason to lose the session's one attribution record, so it goes out again, with the tags and
|
|
47
|
+
* timestamp of the moment the session actually began, under the same session id. Held in memory
|
|
48
|
+
* only: a reload loses it, and with it the session_start — the same as before this existed.
|
|
49
|
+
*/
|
|
50
|
+
let pendingStart;
|
|
41
51
|
async function sendEvents(events) {
|
|
52
|
+
/** The announcement this batch carries, if any, so the catch below can hold it back. */
|
|
53
|
+
let announcement;
|
|
42
54
|
try {
|
|
43
55
|
if (events.length === 0) return;
|
|
44
|
-
const
|
|
45
|
-
const { id: session_id, started } = require_setup_session.getSession().touch(Date.parse(
|
|
46
|
-
if (started)
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
56
|
+
const opening = events[0];
|
|
57
|
+
const { id: session_id, started } = require_setup_session.getSession().touch(Date.parse(opening.timestamp), Date.parse(events[events.length - 1].timestamp));
|
|
58
|
+
if (started || pendingStart?.session_id === session_id) {
|
|
59
|
+
const start = pendingStart?.session_id === session_id ? pendingStart.item : {
|
|
60
|
+
name: "session_start",
|
|
61
|
+
properties: {},
|
|
62
|
+
options: { enableThirdPartyTracking: false },
|
|
63
|
+
tags: opening.tags,
|
|
64
|
+
timestamp: opening.timestamp
|
|
65
|
+
};
|
|
66
|
+
pendingStart = void 0;
|
|
67
|
+
announcement = {
|
|
68
|
+
session_id,
|
|
69
|
+
item: start
|
|
70
|
+
};
|
|
71
|
+
events.unshift(start);
|
|
72
|
+
}
|
|
53
73
|
await getTokenBucket().removeTokens();
|
|
54
74
|
const visitor_id = (await require_visitor_index.getVisitor()).id;
|
|
55
75
|
const dto = await Promise.all(events.map(async (event) => ({
|
|
@@ -93,6 +113,7 @@ async function sendEvents(events) {
|
|
|
93
113
|
}
|
|
94
114
|
} catch (e) {
|
|
95
115
|
if (e instanceof Error) console.log(e.message);
|
|
116
|
+
if (announcement) pendingStart = announcement;
|
|
96
117
|
events.forEach((event) => event.options.onError?.(e));
|
|
97
118
|
}
|
|
98
119
|
}
|
package/dist/track/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["TokenBucket","config","cache","getSession","getVisitor","fetch","IGNORED_EVENTS","keys"],"sources":["../../src/track/index.ts"],"sourcesContent":["import { TokenBucket, fetch } from '@shware/utils';\nimport { keys } from '../constants/storage';\nimport type { CreateTrackEventDTO } from '../schema/index';\nimport { cache, config } from '../setup/index';\nimport { getSession } from '../setup/session';\nimport { IGNORED_EVENTS } from '../third-parties/ignored-events';\nimport { getVisitor } from '../visitor/index';\nimport type { EventName, TrackEventResponse, TrackName, TrackProperties, TrackTags } from './types';\n\nexport interface TrackOptions {\n enableThirdPartyTracking?: boolean;\n onSucceed?: (response?: TrackEventResponse[number]) => void;\n onError?: (error: unknown) => void;\n}\n\nconst defaultOptions: TrackOptions = {};\n\nlet tokenBucket: TokenBucket | undefined;\n\n/**\n * The rate limiter, built on the first send rather than at module scope: its\n * constructor starts a refill `setInterval`, and Cloudflare Workers refuse to\n * set a timer outside a request handler for the same reason they refuse to\n * generate random values there — see `setup/session.ts`.\n */\nfunction getTokenBucket() {\n return (tokenBucket ??= new TokenBucket({ rate: 1, capacity: 20, requested: 2 }));\n}\n\ntype Item = {\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n name: TrackName<any>;\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n properties: TrackProperties<any>;\n tags: Promise<TrackTags>;\n timestamp: string;\n options: TrackOptions;\n};\n\n/**\n * Tags belong to the moment the event happened, not to the moment its batch goes out: a queued\n * event waits up to `delay` ms, and a single page app can navigate in that window, which would\n * stamp every pending event with the URL of the page the user has already left.\n *\n * The promise then sits in the queue with nothing awaiting it, so a failure has to be absorbed\n * here — an unhandled rejection would surface as a global error long before `sendEvents` could\n * catch it. Falling back to the last built tags keeps the event, minus whatever changed since.\n */\nasync function captureTags(): Promise<TrackTags> {\n try {\n return await config.getTags();\n } catch (e: unknown) {\n if (e instanceof Error) console.log(e.message);\n return cache.tags ?? {};\n }\n}\n\nasync function sendEvents(events: Item[]) {\n try {\n if (events.length === 0) return;\n\n // One read-modify-write of the stored session for the whole batch: it answers which session\n // these events belong to and whether this batch is the one that started it. Timed by the\n // events themselves rather than by this moment — a tab frozen in the background can hold a\n // batch for far longer than `delay`, and those events belong to the session they happened in.\n const firstTimestamp = events[0].timestamp;\n const { id: session_id, started } = getSession().touch(\n Date.parse(firstTimestamp),\n Date.parse(events[events.length - 1].timestamp)\n );\n if (started) {\n events.unshift({\n name: 'session_start',\n properties: {},\n options: { enableThirdPartyTracking: false },\n tags: captureTags(),\n // The session began with the event that opened it, not at this moment: a batch held in a\n // frozen tab would otherwise announce its session later than the events inside it.\n timestamp: firstTimestamp,\n });\n }\n\n await getTokenBucket().removeTokens();\n\n const visitor_id = (await getVisitor()).id;\n\n const dto: CreateTrackEventDTO = await Promise.all(\n events.map(async (event) => ({\n name: event.name,\n properties: event.properties,\n tags: await event.tags,\n visitor_id,\n session_id,\n platform: config.platform,\n environment: config.environment,\n timestamp: event.timestamp,\n }))\n );\n\n const response = await fetch(`${config.endpoint}/events`, {\n method: 'POST',\n credentials: 'include',\n // Survive the page being unloaded mid-flight: a batch waits up to `delay` ms, so closing\n // the tab inside that window would otherwise abort the request and lose every event in it.\n // The body stays far under keepalive's 64KB in-flight budget at 100 events per batch.\n keepalive: true,\n headers: await config.getHeaders(),\n body: JSON.stringify(dto),\n });\n\n if (!response.ok) {\n throw new Error(`Failed to send track event: ${response.status} ${await response.text()}`);\n }\n\n const data = (await response.json()) as TrackEventResponse;\n\n let index = 0;\n while (events.length > 0) {\n const event = events.shift();\n if (!event) {\n index++;\n continue;\n }\n const { options, name, properties } = event;\n const eventId = data.at(index)?.id;\n options.onSucceed?.(eventId ? { id: eventId } : undefined);\n index++;\n // An explicit false, not falsiness: a caller passing `{ onSucceed }` replaces the options\n // object wholesale, and leaving the flag out must not silently switch forwarding off.\n if (options.enableThirdPartyTracking === false || IGNORED_EVENTS.includes(name)) {\n continue;\n }\n config.thirdPartyTrackers.forEach((tracker) => {\n try {\n tracker(name, properties, eventId);\n } catch (e: unknown) {\n // A third-party script does not get to take the rest of the batch with it. This loop is\n // still draining `events` with `shift`, so a throw would escape to the catch below and\n // report failure to whatever is left in the queue — for events the server has already\n // accepted, and after the ones ahead of them were told they succeeded.\n if (e instanceof Error) console.log(e.message);\n }\n });\n }\n } catch (e: unknown) {\n if (e instanceof Error) console.log(e.message);\n events.forEach((event) => event.options.onError?.(e));\n }\n}\n\nconst batch = 10;\nconst delay = 2000;\nconst list: Item[] = [];\nlet timer: ReturnType<typeof setTimeout> | null = null;\n\n/**\n * Both paths into a send go through here, so a batch that fills up cancels the timer the\n * previous push armed rather than leaving it to wake up on its own with nothing to send.\n */\nfunction flush() {\n if (timer) {\n clearTimeout(timer);\n timer = null;\n }\n if (list.length === 0) return;\n const copy = [...list];\n list.length = 0;\n void sendEvents(copy);\n}\n\nexport function track<T extends EventName = EventName>(\n name: TrackName<T>,\n properties?: TrackProperties<T>,\n options: TrackOptions = defaultOptions\n) {\n list.push({\n name,\n properties,\n options,\n tags: captureTags(),\n timestamp: new Date().toISOString(),\n });\n if (list.length >= batch) {\n flush();\n return;\n }\n if (timer) clearTimeout(timer);\n timer = setTimeout(flush, delay);\n}\n\nexport async function trackAsync<T extends EventName = EventName>(\n name: TrackName<T>,\n properties?: TrackProperties<T>,\n options: TrackOptions = defaultOptions\n) {\n await sendEvents([\n { name, properties, options, tags: captureTags(), timestamp: new Date().toISOString() },\n ]);\n}\n\nexport function sendBeacon<T extends EventName = EventName>(\n name: TrackName<T>,\n properties?: TrackProperties<T>\n) {\n // The visitor id is persisted, so a returning visitor already has one before `getVisitor` has\n // finished its round trip for this page. Requiring the in-memory copy threw away exactly the\n // events this function exists for: everything a visit accrues before its first batch comes\n // back, which for a short visit is the whole of it.\n const stored = config.storage.getItem(keys.visitor_id);\n const visitor_id = cache.visitor?.id ?? (stored && stored !== 'undefined' ? stored : undefined);\n if (!visitor_id) return;\n\n const dto: CreateTrackEventDTO = [\n {\n name,\n properties,\n // Tags are worth less than the event carrying them: an empty set still reports the\n // engagement, and every field in `tagsSchema` is optional.\n tags: cache.tags ?? {},\n visitor_id,\n session_id: getSession().extend(),\n platform: config.platform,\n environment: config.environment,\n timestamp: new Date().toISOString(),\n },\n ];\n const blob = new Blob([JSON.stringify(dto)], { type: 'application/json' });\n const success = navigator.sendBeacon(`${config.endpoint}/events`, blob);\n if (success) return;\n console.warn('Failed to send beacon', name, properties);\n}\n"],"mappings":";;;;;;;;AAeA,MAAM,iBAA+B,CAAC;AAEtC,IAAI;;;;;;;AAQJ,SAAS,iBAAiB;CACxB,OAAQ,gBAAgB,IAAIA,cAAAA,YAAY;EAAE,MAAM;EAAG,UAAU;EAAI,WAAW;CAAE,CAAC;AACjF;;;;;;;;;;AAqBA,eAAe,cAAkC;CAC/C,IAAI;EACF,OAAO,MAAMC,oBAAAA,OAAO,QAAQ;CAC9B,SAAS,GAAY;EACnB,IAAI,aAAa,OAAO,QAAQ,IAAI,EAAE,OAAO;EAC7C,OAAOC,oBAAAA,MAAM,QAAQ,CAAC;CACxB;AACF;AAEA,eAAe,WAAW,QAAgB;CACxC,IAAI;EACF,IAAI,OAAO,WAAW,GAAG;EAMzB,MAAM,iBAAiB,OAAO,EAAE,CAAC;EACjC,MAAM,EAAE,IAAI,YAAY,YAAYC,sBAAAA,WAAW,CAAC,CAAC,MAC/C,KAAK,MAAM,cAAc,GACzB,KAAK,MAAM,OAAO,OAAO,SAAS,EAAE,CAAC,SAAS,CAChD;EACA,IAAI,SACF,OAAO,QAAQ;GACb,MAAM;GACN,YAAY,CAAC;GACb,SAAS,EAAE,0BAA0B,MAAM;GAC3C,MAAM,YAAY;GAGlB,WAAW;EACb,CAAC;EAGH,MA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AAU,GAAG,CAAC,GAAG,EAAE,MAAM,mBAAmB,CAAC;CAEzE,IADgB,UAAU,WAAW,GAAGA,oBAAAA,OAAO,SAAS,UAAU,IACxD,GAAG;CACb,QAAQ,KAAK,yBAAyB,MAAM,UAAU;AACxD"}
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["TokenBucket","config","cache","getSession","getVisitor","fetch","IGNORED_EVENTS","keys"],"sources":["../../src/track/index.ts"],"sourcesContent":["import { TokenBucket, fetch } from '@shware/utils';\nimport { keys } from '../constants/storage';\nimport type { CreateTrackEventDTO } from '../schema/index';\nimport { cache, config } from '../setup/index';\nimport { getSession } from '../setup/session';\nimport { IGNORED_EVENTS } from '../third-parties/ignored-events';\nimport { getVisitor } from '../visitor/index';\nimport type { EventName, TrackEventResponse, TrackName, TrackProperties, TrackTags } from './types';\n\nexport interface TrackOptions {\n enableThirdPartyTracking?: boolean;\n onSucceed?: (response?: TrackEventResponse[number]) => void;\n onError?: (error: unknown) => void;\n}\n\nconst defaultOptions: TrackOptions = {};\n\nlet tokenBucket: TokenBucket | undefined;\n\n/**\n * The rate limiter, built on the first send rather than at module scope: its\n * constructor starts a refill `setInterval`, and Cloudflare Workers refuse to\n * set a timer outside a request handler for the same reason they refuse to\n * generate random values there — see `setup/session.ts`.\n */\nfunction getTokenBucket() {\n return (tokenBucket ??= new TokenBucket({ rate: 1, capacity: 20, requested: 2 }));\n}\n\ntype Item = {\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n name: TrackName<any>;\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n properties: TrackProperties<any>;\n tags: Promise<TrackTags>;\n timestamp: string;\n options: TrackOptions;\n};\n\n/**\n * Tags belong to the moment the event happened, not to the moment its batch goes out: a queued\n * event waits up to `delay` ms, and a single page app can navigate in that window, which would\n * stamp every pending event with the URL of the page the user has already left.\n *\n * The promise then sits in the queue with nothing awaiting it, so a failure has to be absorbed\n * here — an unhandled rejection would surface as a global error long before `sendEvents` could\n * catch it. Falling back to the last built tags keeps the event, minus whatever changed since.\n */\nasync function captureTags(): Promise<TrackTags> {\n try {\n return await config.getTags();\n } catch (e: unknown) {\n if (e instanceof Error) console.log(e.message);\n return cache.tags ?? {};\n }\n}\n\n/**\n * The `session_start` a failed batch took down with it, kept for the next batch of the same\n * session. `fetch` has already retried the transient failures by the time a batch fails here;\n * what remains is a batch the server rejected outright — one invalid event fails the whole batch,\n * and `session_start` with it — or a network that stayed down past the retries. Neither is a\n * reason to lose the session's one attribution record, so it goes out again, with the tags and\n * timestamp of the moment the session actually began, under the same session id. Held in memory\n * only: a reload loses it, and with it the session_start — the same as before this existed.\n */\nlet pendingStart: { session_id: string; item: Item } | undefined;\n\nasync function sendEvents(events: Item[]) {\n /** The announcement this batch carries, if any, so the catch below can hold it back. */\n let announcement: { session_id: string; item: Item } | undefined;\n try {\n if (events.length === 0) return;\n\n // One read-modify-write of the stored session for the whole batch: it answers which session\n // these events belong to and whether this batch is the one that started it. Timed by the\n // events themselves rather than by this moment — a tab frozen in the background can hold a\n // batch for far longer than `delay`, and those events belong to the session they happened in.\n const opening = events[0];\n const { id: session_id, started } = getSession().touch(\n Date.parse(opening.timestamp),\n Date.parse(events[events.length - 1].timestamp)\n );\n if (started || pendingStart?.session_id === session_id) {\n // `session_start` is derived from the event that opened the session, as GA4 derives it\n // from the hit that did: when that event happened is when the session began, and the page\n // it was captured on is where. Neither is read now — this batch goes out up to `delay` ms\n // later, a batch held in a frozen tab far later still, and a landing page that redirects\n // inside that window would stamp the session's one attribution record with the URL the utm\n // parameters were already stripped from.\n const start: Item =\n pendingStart?.session_id === session_id\n ? pendingStart.item\n : {\n name: 'session_start',\n properties: {},\n options: { enableThirdPartyTracking: false },\n tags: opening.tags,\n timestamp: opening.timestamp,\n };\n pendingStart = undefined;\n announcement = { session_id, item: start };\n events.unshift(start);\n }\n\n await getTokenBucket().removeTokens();\n\n const visitor_id = (await getVisitor()).id;\n\n const dto: CreateTrackEventDTO = await Promise.all(\n events.map(async (event) => ({\n name: event.name,\n properties: event.properties,\n tags: await event.tags,\n visitor_id,\n session_id,\n platform: config.platform,\n environment: config.environment,\n timestamp: event.timestamp,\n }))\n );\n\n const response = await fetch(`${config.endpoint}/events`, {\n method: 'POST',\n credentials: 'include',\n // Survive the page being unloaded mid-flight: a batch waits up to `delay` ms, so closing\n // the tab inside that window would otherwise abort the request and lose every event in it.\n // The body stays far under keepalive's 64KB in-flight budget at 100 events per batch.\n keepalive: true,\n headers: await config.getHeaders(),\n body: JSON.stringify(dto),\n });\n\n if (!response.ok) {\n throw new Error(`Failed to send track event: ${response.status} ${await response.text()}`);\n }\n\n const data = (await response.json()) as TrackEventResponse;\n\n let index = 0;\n while (events.length > 0) {\n const event = events.shift();\n if (!event) {\n index++;\n continue;\n }\n const { options, name, properties } = event;\n const eventId = data.at(index)?.id;\n options.onSucceed?.(eventId ? { id: eventId } : undefined);\n index++;\n // An explicit false, not falsiness: a caller passing `{ onSucceed }` replaces the options\n // object wholesale, and leaving the flag out must not silently switch forwarding off.\n if (options.enableThirdPartyTracking === false || IGNORED_EVENTS.includes(name)) {\n continue;\n }\n config.thirdPartyTrackers.forEach((tracker) => {\n try {\n tracker(name, properties, eventId);\n } catch (e: unknown) {\n // A third-party script does not get to take the rest of the batch with it. This loop is\n // still draining `events` with `shift`, so a throw would escape to the catch below and\n // report failure to whatever is left in the queue — for events the server has already\n // accepted, and after the ones ahead of them were told they succeeded.\n if (e instanceof Error) console.log(e.message);\n }\n });\n }\n } catch (e: unknown) {\n if (e instanceof Error) console.log(e.message);\n // The other events are reported lost and stay lost; `session_start` alone is worth carrying\n // over, because it is the session's only attribution record — a session without one has no\n // channel, and its every later event drops out of an attribution join.\n if (announcement) pendingStart = announcement;\n events.forEach((event) => event.options.onError?.(e));\n }\n}\n\nconst batch = 10;\nconst delay = 2000;\nconst list: Item[] = [];\nlet timer: ReturnType<typeof setTimeout> | null = null;\n\n/**\n * Both paths into a send go through here, so a batch that fills up cancels the timer the\n * previous push armed rather than leaving it to wake up on its own with nothing to send.\n */\nfunction flush() {\n if (timer) {\n clearTimeout(timer);\n timer = null;\n }\n if (list.length === 0) return;\n const copy = [...list];\n list.length = 0;\n void sendEvents(copy);\n}\n\nexport function track<T extends EventName = EventName>(\n name: TrackName<T>,\n properties?: TrackProperties<T>,\n options: TrackOptions = defaultOptions\n) {\n list.push({\n name,\n properties,\n options,\n tags: captureTags(),\n timestamp: new Date().toISOString(),\n });\n if (list.length >= batch) {\n flush();\n return;\n }\n if (timer) clearTimeout(timer);\n timer = setTimeout(flush, delay);\n}\n\nexport async function trackAsync<T extends EventName = EventName>(\n name: TrackName<T>,\n properties?: TrackProperties<T>,\n options: TrackOptions = defaultOptions\n) {\n await sendEvents([\n { name, properties, options, tags: captureTags(), timestamp: new Date().toISOString() },\n ]);\n}\n\nexport function sendBeacon<T extends EventName = EventName>(\n name: TrackName<T>,\n properties?: TrackProperties<T>\n) {\n // The visitor id is persisted, so a returning visitor already has one before `getVisitor` has\n // finished its round trip for this page. Requiring the in-memory copy threw away exactly the\n // events this function exists for: everything a visit accrues before its first batch comes\n // back, which for a short visit is the whole of it.\n const stored = config.storage.getItem(keys.visitor_id);\n const visitor_id = cache.visitor?.id ?? (stored && stored !== 'undefined' ? stored : undefined);\n if (!visitor_id) return;\n\n const dto: CreateTrackEventDTO = [\n {\n name,\n properties,\n // Tags are worth less than the event carrying them: an empty set still reports the\n // engagement, and every field in `tagsSchema` is optional.\n tags: cache.tags ?? {},\n visitor_id,\n session_id: getSession().extend(),\n platform: config.platform,\n environment: config.environment,\n timestamp: new Date().toISOString(),\n },\n ];\n const blob = new Blob([JSON.stringify(dto)], { type: 'application/json' });\n const success = navigator.sendBeacon(`${config.endpoint}/events`, blob);\n if (success) return;\n console.warn('Failed to send beacon', name, properties);\n}\n"],"mappings":";;;;;;;;AAeA,MAAM,iBAA+B,CAAC;AAEtC,IAAI;;;;;;;AAQJ,SAAS,iBAAiB;CACxB,OAAQ,gBAAgB,IAAIA,cAAAA,Y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KAAK;EACR;EACA;EACA;EACA,MAAM,YAAY;EAClB,4BAAW,IAAI,KAAK,EAAA,CAAE,YAAY;CACpC,CAAC;CACD,IAAI,KAAK,UAAU,OAAO;EACxB,MAAM;EACN;CACF;CACA,IAAI,OAAO,aAAa,KAAK;CAC7B,QAAQ,WAAW,OAAO,KAAK;AACjC;AAEA,eAAsB,WACpB,MACA,YACA,UAAwB,gBACxB;CACA,MAAM,WAAW,CACf;EAAE;EAAM;EAAY;EAAS,MAAM,YAAY;EAAG,4BAAW,IAAI,KAAK,EAAA,CAAE,YAAY;CAAE,CACxF,CAAC;AACH;AAEA,SAAgB,WACd,MACA,YACA;CAKA,MAAM,SAASL,oBAAAA,OAAO,QAAQ,QAAQM,0BAAAA,KAAK,UAAU;CACrD,MAAM,aAAaL,oBAAAA,MAAM,SAAS,OAAO,UAAU,WAAW,cAAc,SAAS,KAAA;CACrF,IAAI,CAAC,YAAY;CAEjB,MAAM,MAA2B,CAC/B;EACE;EACA;EAGA,MAAMA,oBAAAA,MAAM,QAAQ,CAAC;EACrB;EACA,YAAYC,sBAAAA,WAAW,CAAC,CAAC,OAAO;EAChC,UAAUF,oBAAAA,OAAO;EACjB,aAAaA,oBAAAA,OAAO;EACpB,4BAAW,IAAI,KAAK,EAAA,CAAE,YAAY;CACpC,CACF;CACA,MAAM,OAAO,IAAI,KAAK,CAAC,KAAK,UAAU,GAAG,CAAC,GAAG,EAAE,MAAM,mBAAmB,CAAC;CAEzE,IADgB,UAAU,WAAW,GAAGA,oBAAAA,OAAO,SAAS,UAAU,IACxD,GAAG;CACb,QAAQ,KAAK,yBAAyB,MAAM,UAAU;AACxD"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.cts","names":[],"sources":["../../src/track/index.ts"],"mappings":";;UASiB;EACf;EACA,aAAa,WAAW;EACxB,WAAW;;
|
|
1
|
+
{"version":3,"file":"index.d.cts","names":[],"sources":["../../src/track/index.ts"],"mappings":";;UASiB;EACf;EACA,aAAa,WAAW;EACxB,WAAW;;iBAyLG,MAAM,UAAU,YAAY,WAC1C,MAAM,UAAU,IAChB,aAAa,gBAAgB,IAC7B,UAAS;iBAiBW,WAAW,UAAU,YAAY,WACrD,MAAM,UAAU,IAChB,aAAa,gBAAgB,IAC7B,UAAS,eAA6B;iBAOxB,WAAW,UAAU,YAAY,WAC/C,MAAM,UAAU,IAChB,aAAa,gBAAgB"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.mts","names":[],"sources":["../../src/track/index.ts"],"mappings":";;UASiB;EACf;EACA,aAAa,WAAW;EACxB,WAAW;;
|
|
1
|
+
{"version":3,"file":"index.d.mts","names":[],"sources":["../../src/track/index.ts"],"mappings":";;UASiB;EACf;EACA,aAAa,WAAW;EACxB,WAAW;;iBAyLG,MAAM,UAAU,YAAY,WAC1C,MAAM,UAAU,IAChB,aAAa,gBAAgB,IAC7B,UAAS;iBAiBW,WAAW,UAAU,YAAY,WACrD,MAAM,UAAU,IAChB,aAAa,gBAAgB,IAC7B,UAAS,eAA6B;iBAOxB,WAAW,UAAU,YAAY,WAC/C,MAAM,UAAU,IAChB,aAAa,gBAAgB"}
|
package/dist/track/index.mjs
CHANGED
|
@@ -37,18 +37,38 @@ async function captureTags() {
|
|
|
37
37
|
return cache.tags ?? {};
|
|
38
38
|
}
|
|
39
39
|
}
|
|
40
|
+
/**
|
|
41
|
+
* The `session_start` a failed batch took down with it, kept for the next batch of the same
|
|
42
|
+
* session. `fetch` has already retried the transient failures by the time a batch fails here;
|
|
43
|
+
* what remains is a batch the server rejected outright — one invalid event fails the whole batch,
|
|
44
|
+
* and `session_start` with it — or a network that stayed down past the retries. Neither is a
|
|
45
|
+
* reason to lose the session's one attribution record, so it goes out again, with the tags and
|
|
46
|
+
* timestamp of the moment the session actually began, under the same session id. Held in memory
|
|
47
|
+
* only: a reload loses it, and with it the session_start — the same as before this existed.
|
|
48
|
+
*/
|
|
49
|
+
let pendingStart;
|
|
40
50
|
async function sendEvents(events) {
|
|
51
|
+
/** The announcement this batch carries, if any, so the catch below can hold it back. */
|
|
52
|
+
let announcement;
|
|
41
53
|
try {
|
|
42
54
|
if (events.length === 0) return;
|
|
43
|
-
const
|
|
44
|
-
const { id: session_id, started } = getSession().touch(Date.parse(
|
|
45
|
-
if (started)
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
55
|
+
const opening = events[0];
|
|
56
|
+
const { id: session_id, started } = getSession().touch(Date.parse(opening.timestamp), Date.parse(events[events.length - 1].timestamp));
|
|
57
|
+
if (started || pendingStart?.session_id === session_id) {
|
|
58
|
+
const start = pendingStart?.session_id === session_id ? pendingStart.item : {
|
|
59
|
+
name: "session_start",
|
|
60
|
+
properties: {},
|
|
61
|
+
options: { enableThirdPartyTracking: false },
|
|
62
|
+
tags: opening.tags,
|
|
63
|
+
timestamp: opening.timestamp
|
|
64
|
+
};
|
|
65
|
+
pendingStart = void 0;
|
|
66
|
+
announcement = {
|
|
67
|
+
session_id,
|
|
68
|
+
item: start
|
|
69
|
+
};
|
|
70
|
+
events.unshift(start);
|
|
71
|
+
}
|
|
52
72
|
await getTokenBucket().removeTokens();
|
|
53
73
|
const visitor_id = (await getVisitor()).id;
|
|
54
74
|
const dto = await Promise.all(events.map(async (event) => ({
|
|
@@ -92,6 +112,7 @@ async function sendEvents(events) {
|
|
|
92
112
|
}
|
|
93
113
|
} catch (e) {
|
|
94
114
|
if (e instanceof Error) console.log(e.message);
|
|
115
|
+
if (announcement) pendingStart = announcement;
|
|
95
116
|
events.forEach((event) => event.options.onError?.(e));
|
|
96
117
|
}
|
|
97
118
|
}
|
package/dist/track/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":[],"sources":["../../src/track/index.ts"],"sourcesContent":["import { TokenBucket, fetch } from '@shware/utils';\nimport { keys } from '../constants/storage';\nimport type { CreateTrackEventDTO } from '../schema/index';\nimport { cache, config } from '../setup/index';\nimport { getSession } from '../setup/session';\nimport { IGNORED_EVENTS } from '../third-parties/ignored-events';\nimport { getVisitor } from '../visitor/index';\nimport type { EventName, TrackEventResponse, TrackName, TrackProperties, TrackTags } from './types';\n\nexport interface TrackOptions {\n enableThirdPartyTracking?: boolean;\n onSucceed?: (response?: TrackEventResponse[number]) => void;\n onError?: (error: unknown) => void;\n}\n\nconst defaultOptions: TrackOptions = {};\n\nlet tokenBucket: TokenBucket | undefined;\n\n/**\n * The rate limiter, built on the first send rather than at module scope: its\n * constructor starts a refill `setInterval`, and Cloudflare Workers refuse to\n * set a timer outside a request handler for the same reason they refuse to\n * generate random values there — see `setup/session.ts`.\n */\nfunction getTokenBucket() {\n return (tokenBucket ??= new TokenBucket({ rate: 1, capacity: 20, requested: 2 }));\n}\n\ntype Item = {\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n name: TrackName<any>;\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n properties: TrackProperties<any>;\n tags: Promise<TrackTags>;\n timestamp: string;\n options: TrackOptions;\n};\n\n/**\n * Tags belong to the moment the event happened, not to the moment its batch goes out: a queued\n * event waits up to `delay` ms, and a single page app can navigate in that window, which would\n * stamp every pending event with the URL of the page the user has already left.\n *\n * The promise then sits in the queue with nothing awaiting it, so a failure has to be absorbed\n * here — an unhandled rejection would surface as a global error long before `sendEvents` could\n * catch it. Falling back to the last built tags keeps the event, minus whatever changed since.\n */\nasync function captureTags(): Promise<TrackTags> {\n try {\n return await config.getTags();\n } catch (e: unknown) {\n if (e instanceof Error) console.log(e.message);\n return cache.tags ?? {};\n }\n}\n\nasync function sendEvents(events: Item[]) {\n try {\n if (events.length === 0) return;\n\n // One read-modify-write of the stored session for the whole batch: it answers which session\n // these events belong to and whether this batch is the one that started it. Timed by the\n // events themselves rather than by this moment — a tab frozen in the background can hold a\n // batch for far longer than `delay`, and those events belong to the session they happened in.\n const firstTimestamp = events[0].timestamp;\n const { id: session_id, started } = getSession().touch(\n Date.parse(firstTimestamp),\n Date.parse(events[events.length - 1].timestamp)\n );\n if (started) {\n events.unshift({\n name: 'session_start',\n properties: {},\n options: { enableThirdPartyTracking: false },\n tags: captureTags(),\n // The session began with the event that opened it, not at this moment: a batch held in a\n // frozen tab would otherwise announce its session later than the events inside it.\n timestamp: firstTimestamp,\n });\n }\n\n await getTokenBucket().removeTokens();\n\n const visitor_id = (await getVisitor()).id;\n\n const dto: CreateTrackEventDTO = await Promise.all(\n events.map(async (event) => ({\n name: event.name,\n properties: event.properties,\n tags: await event.tags,\n visitor_id,\n session_id,\n platform: config.platform,\n environment: config.environment,\n timestamp: event.timestamp,\n }))\n );\n\n const response = await fetch(`${config.endpoint}/events`, {\n method: 'POST',\n credentials: 'include',\n // Survive the page being unloaded mid-flight: a batch waits up to `delay` ms, so closing\n // the tab inside that window would otherwise abort the request and lose every event in it.\n // The body stays far under keepalive's 64KB in-flight budget at 100 events per batch.\n keepalive: true,\n headers: await config.getHeaders(),\n body: JSON.stringify(dto),\n });\n\n if (!response.ok) {\n throw new Error(`Failed to send track event: ${response.status} ${await response.text()}`);\n }\n\n const data = (await response.json()) as TrackEventResponse;\n\n let index = 0;\n while (events.length > 0) {\n const event = events.shift();\n if (!event) {\n index++;\n continue;\n }\n const { options, name, properties } = event;\n const eventId = data.at(index)?.id;\n options.onSucceed?.(eventId ? { id: eventId } : undefined);\n index++;\n // An explicit false, not falsiness: a caller passing `{ onSucceed }` replaces the options\n // object wholesale, and leaving the flag out must not silently switch forwarding off.\n if (options.enableThirdPartyTracking === false || IGNORED_EVENTS.includes(name)) {\n continue;\n }\n config.thirdPartyTrackers.forEach((tracker) => {\n try {\n tracker(name, properties, eventId);\n } catch (e: unknown) {\n // A third-party script does not get to take the rest of the batch with it. This loop is\n // still draining `events` with `shift`, so a throw would escape to the catch below and\n // report failure to whatever is left in the queue — for events the server has already\n // accepted, and after the ones ahead of them were told they succeeded.\n if (e instanceof Error) console.log(e.message);\n }\n });\n }\n } catch (e: unknown) {\n if (e instanceof Error) console.log(e.message);\n events.forEach((event) => event.options.onError?.(e));\n }\n}\n\nconst batch = 10;\nconst delay = 2000;\nconst list: Item[] = [];\nlet timer: ReturnType<typeof setTimeout> | null = null;\n\n/**\n * Both paths into a send go through here, so a batch that fills up cancels the timer the\n * previous push armed rather than leaving it to wake up on its own with nothing to send.\n */\nfunction flush() {\n if (timer) {\n clearTimeout(timer);\n timer = null;\n }\n if (list.length === 0) return;\n const copy = [...list];\n list.length = 0;\n void sendEvents(copy);\n}\n\nexport function track<T extends EventName = EventName>(\n name: TrackName<T>,\n properties?: TrackProperties<T>,\n options: TrackOptions = defaultOptions\n) {\n list.push({\n name,\n properties,\n options,\n tags: captureTags(),\n timestamp: new Date().toISOString(),\n });\n if (list.length >= batch) {\n flush();\n return;\n }\n if (timer) clearTimeout(timer);\n timer = setTimeout(flush, delay);\n}\n\nexport async function trackAsync<T extends EventName = EventName>(\n name: TrackName<T>,\n properties?: TrackProperties<T>,\n options: TrackOptions = defaultOptions\n) {\n await sendEvents([\n { name, properties, options, tags: captureTags(), timestamp: new Date().toISOString() },\n ]);\n}\n\nexport function sendBeacon<T extends EventName = EventName>(\n name: TrackName<T>,\n properties?: TrackProperties<T>\n) {\n // The visitor id is persisted, so a returning visitor already has one before `getVisitor` has\n // finished its round trip for this page. Requiring the in-memory copy threw away exactly the\n // events this function exists for: everything a visit accrues before its first batch comes\n // back, which for a short visit is the whole of it.\n const stored = config.storage.getItem(keys.visitor_id);\n const visitor_id = cache.visitor?.id ?? (stored && stored !== 'undefined' ? stored : undefined);\n if (!visitor_id) return;\n\n const dto: CreateTrackEventDTO = [\n {\n name,\n properties,\n // Tags are worth less than the event carrying them: an empty set still reports the\n // engagement, and every field in `tagsSchema` is optional.\n tags: cache.tags ?? {},\n visitor_id,\n session_id: getSession().extend(),\n platform: config.platform,\n environment: config.environment,\n timestamp: new Date().toISOString(),\n },\n ];\n const blob = new Blob([JSON.stringify(dto)], { type: 'application/json' });\n const success = navigator.sendBeacon(`${config.endpoint}/events`, blob);\n if (success) return;\n console.warn('Failed to send beacon', name, properties);\n}\n"],"mappings":";;;;;;;AAeA,MAAM,iBAA+B,CAAC;AAEtC,IAAI;;;;;;;AAQJ,SAAS,iBAAiB;CACxB,OAAQ,gBAAgB,IAAI,YAAY;EAAE,MAAM;EAAG,UAAU;EAAI,WAAW;CAAE,CAAC;AACjF;;;;;;;;;;AAqBA,eAAe,cAAkC;CAC/C,IAAI;EACF,OAAO,MAAM,OAAO,QAAQ;CAC9B,SAAS,GAAY;EACnB,IAAI,aAAa,OAAO,QAAQ,IAAI,EAAE,OAAO;EAC7C,OAAO,MAAM,QAAQ,CAAC;CACxB;AACF;AAEA,eAAe,WAAW,QAAgB;CACxC,IAAI;EACF,IAAI,OAAO,WAAW,GAAG;EAMzB,MAAM,iBAAiB,OAAO,EAAE,CAAC;EACjC,MAAM,EAAE,IAAI,YAAY,YAAY,WAAW,CAAC,CAAC,MAC/C,KAAK,MAAM,cAAc,GACzB,KAAK,MAAM,OAAO,OAAO,SAAS,EAAE,CAAC,SAAS,CAChD;EACA,IAAI,SACF,OAAO,QAAQ;GACb,MAAM;GACN,YAAY,CAAC;GACb,SAAS,EAAE,0BAA0B,MAAM;GAC3C,MAAM,YAAY;GAGlB,WAAW;EACb,CAAC;EAGH,MAAM,eAAe,CAAC,CAAC,aAAa;EAEpC,MAAM,cAAc,MAAM,WAAW,EAAA,CAAG;EAExC,MAAM,MAA2B,MAAM,QAAQ,IAC7C,OAAO,IAAI,OAAO,WAAW;GAC3B,MAAM,MAAM;GACZ,YAAY,MAAM;GAClB,MAAM,MAAM,MAAM;GAClB;GACA;GACA,UAAU,OAAO;GACjB,aAAa,OAAO;GACpB,WAAW,MAAM;EACnB,EAAE,CACJ;EAEA,MAAM,WAAW,MAAM,MAAM,GAAG,OAAO,SAAS,UAAU;GACxD,QAAQ;GACR,aAAa;GAIb,WAAW;GACX,SAAS,MAAM,OAAO,WAAW;GACjC,MAAM,KAAK,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ACxB,MAAM;EACN;CACF;CACA,IAAI,OAAO,aAAa,KAAK;CAC7B,QAAQ,WAAW,OAAO,KAAK;AACjC;AAEA,eAAsB,WACpB,MACA,YACA,UAAwB,gBACxB;CACA,MAAM,WAAW,CACf;EAAE;EAAM;EAAY;EAAS,MAAM,YAAY;EAAG,4BAAW,IAAI,KAAK,EAAA,CAAE,YAAY;CAAE,CACxF,CAAC;AACH;AAEA,SAAgB,WACd,MACA,YACA;CAKA,MAAM,SAAS,OAAO,QAAQ,QAAQ,KAAK,UAAU;CACrD,MAAM,aAAa,MAAM,SAAS,OAAO,UAAU,WAAW,cAAc,SAAS,KAAA;CACrF,IAAI,CAAC,YAAY;CAEjB,MAAM,MAA2B,CAC/B;EACE;EACA;EAGA,MAAM,MAAM,QAAQ,CAAC;EACrB;EACA,YAAY,WAAW,CAAC,CAAC,OAAO;EAChC,UAAU,OAAO;EACjB,aAAa,OAAO;EACpB,4BAAW,IAAI,KAAK,EAAA,CAAE,YAAY;CACpC,CACF;CACA,MAAM,OAAO,IAAI,KAAK,CAAC,KAAK,UAAU,GAAG,CAAC,GAAG,EAAE,MAAM,mBAAmB,CAAC;CAEzE,IADgB,UAAU,WAAW,GAAG,OAAO,SAAS,UAAU,IACxD,GAAG;CACb,QAAQ,KAAK,yBAAyB,MAAM,UAAU;AACxD"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":[],"sources":["../../src/track/index.ts"],"sourcesContent":["import { TokenBucket, fetch } from '@shware/utils';\nimport { keys } from '../constants/storage';\nimport type { CreateTrackEventDTO } from '../schema/index';\nimport { cache, config } from '../setup/index';\nimport { getSession } from '../setup/session';\nimport { IGNORED_EVENTS } from '../third-parties/ignored-events';\nimport { getVisitor } from '../visitor/index';\nimport type { EventName, TrackEventResponse, TrackName, TrackProperties, TrackTags } from './types';\n\nexport interface TrackOptions {\n enableThirdPartyTracking?: boolean;\n onSucceed?: (response?: TrackEventResponse[number]) => void;\n onError?: (error: unknown) => void;\n}\n\nconst defaultOptions: TrackOptions = {};\n\nlet tokenBucket: TokenBucket | undefined;\n\n/**\n * The rate limiter, built on the first send rather than at module scope: its\n * constructor starts a refill `setInterval`, and Cloudflare Workers refuse to\n * set a timer outside a request handler for the same reason they refuse to\n * generate random values there — see `setup/session.ts`.\n */\nfunction getTokenBucket() {\n return (tokenBucket ??= new TokenBucket({ rate: 1, capacity: 20, requested: 2 }));\n}\n\ntype Item = {\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n name: TrackName<any>;\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n properties: TrackProperties<any>;\n tags: Promise<TrackTags>;\n timestamp: string;\n options: TrackOptions;\n};\n\n/**\n * Tags belong to the moment the event happened, not to the moment its batch goes out: a queued\n * event waits up to `delay` ms, and a single page app can navigate in that window, which would\n * stamp every pending event with the URL of the page the user has already left.\n *\n * The promise then sits in the queue with nothing awaiting it, so a failure has to be absorbed\n * here — an unhandled rejection would surface as a global error long before `sendEvents` could\n * catch it. Falling back to the last built tags keeps the event, minus whatever changed since.\n */\nasync function captureTags(): Promise<TrackTags> {\n try {\n return await config.getTags();\n } catch (e: unknown) {\n if (e instanceof Error) console.log(e.message);\n return cache.tags ?? {};\n }\n}\n\n/**\n * The `session_start` a failed batch took down with it, kept for the next batch of the same\n * session. `fetch` has already retried the transient failures by the time a batch fails here;\n * what remains is a batch the server rejected outright — one invalid event fails the whole batch,\n * and `session_start` with it — or a network that stayed down past the retries. Neither is a\n * reason to lose the session's one attribution record, so it goes out again, with the tags and\n * timestamp of the moment the session actually began, under the same session id. Held in memory\n * only: a reload loses it, and with it the session_start — the same as before this existed.\n */\nlet pendingStart: { session_id: string; item: Item } | undefined;\n\nasync function sendEvents(events: Item[]) {\n /** The announcement this batch carries, if any, so the catch below can hold it back. */\n let announcement: { session_id: string; item: Item } | undefined;\n try {\n if (events.length === 0) return;\n\n // One read-modify-write of the stored session for the whole batch: it answers which session\n // these events belong to and whether this batch is the one that started it. Timed by the\n // events themselves rather than by this moment — a tab frozen in the background can hold a\n // batch for far longer than `delay`, and those events belong to the session they happened in.\n const opening = events[0];\n const { id: session_id, started } = getSession().touch(\n Date.parse(opening.timestamp),\n Date.parse(events[events.length - 1].timestamp)\n );\n if (started || pendingStart?.session_id === session_id) {\n // `session_start` is derived from the event that opened the session, as GA4 derives it\n // from the hit that did: when that event happened is when the session began, and the page\n // it was captured on is where. Neither is read now — this batch goes out up to `delay` ms\n // later, a batch held in a frozen tab far later still, and a landing page that redirects\n // inside that window would stamp the session's one attribution record with the URL the utm\n // parameters were already stripped from.\n const start: Item =\n pendingStart?.session_id === session_id\n ? pendingStart.item\n : {\n name: 'session_start',\n properties: {},\n options: { enableThirdPartyTracking: false },\n tags: opening.tags,\n timestamp: opening.timestamp,\n };\n pendingStart = undefined;\n announcement = { session_id, item: start };\n events.unshift(start);\n }\n\n await getTokenBucket().removeTokens();\n\n const visitor_id = (await getVisitor()).id;\n\n const dto: CreateTrackEventDTO = await Promise.all(\n events.map(async (event) => ({\n name: event.name,\n properties: event.properties,\n tags: await event.tags,\n visitor_id,\n session_id,\n platform: config.platform,\n environment: config.environment,\n timestamp: event.timestamp,\n }))\n );\n\n const response = await fetch(`${config.endpoint}/events`, {\n method: 'POST',\n credentials: 'include',\n // Survive the page being unloaded mid-flight: a batch waits up to `delay` ms, so closing\n // the tab inside that window would otherwise abort the request and lose every event in it.\n // The body stays far under keepalive's 64KB in-flight budget at 100 events per batch.\n keepalive: true,\n headers: await config.getHeaders(),\n body: JSON.stringify(dto),\n });\n\n if (!response.ok) {\n throw new Error(`Failed to send track event: ${response.status} ${await response.text()}`);\n }\n\n const data = (await response.json()) as TrackEventResponse;\n\n let index = 0;\n while (events.length > 0) {\n const event = events.shift();\n if (!event) {\n index++;\n continue;\n }\n const { options, name, properties } = event;\n const eventId = data.at(index)?.id;\n options.onSucceed?.(eventId ? { id: eventId } : undefined);\n index++;\n // An explicit false, not falsiness: a caller passing `{ onSucceed }` replaces the options\n // object wholesale, and leaving the flag out must not silently switch forwarding off.\n if (options.enableThirdPartyTracking === false || IGNORED_EVENTS.includes(name)) {\n continue;\n }\n config.thirdPartyTrackers.forEach((tracker) => {\n try {\n tracker(name, properties, eventId);\n } catch (e: unknown) {\n // A third-party script does not get to take the rest of the batch with it. This loop is\n // still draining `events` with `shift`, so a throw would escape to the catch below and\n // report failure to whatever is left in the queue — for events the server has already\n // accepted, and after the ones ahead of them were told they succeeded.\n if (e instanceof Error) console.log(e.message);\n }\n });\n }\n } catch (e: unknown) {\n if (e instanceof Error) console.log(e.message);\n // The other events are reported lost and stay lost; `session_start` alone is worth carrying\n // over, because it is the session's only attribution record — a session without one has no\n // channel, and its every later event drops out of an attribution join.\n if (announcement) pendingStart = announcement;\n events.forEach((event) => event.options.onError?.(e));\n }\n}\n\nconst batch = 10;\nconst delay = 2000;\nconst list: Item[] = [];\nlet timer: ReturnType<typeof setTimeout> | null = null;\n\n/**\n * Both paths into a send go through here, so a batch that fills up cancels the timer the\n * previous push armed rather than leaving it to wake up on its own with nothing to send.\n */\nfunction flush() {\n if (timer) {\n clearTimeout(timer);\n timer = null;\n }\n if (list.length === 0) return;\n const copy = [...list];\n list.length = 0;\n void sendEvents(copy);\n}\n\nexport function track<T extends EventName = EventName>(\n name: TrackName<T>,\n properties?: TrackProperties<T>,\n options: TrackOptions = defaultOptions\n) {\n list.push({\n name,\n properties,\n options,\n tags: captureTags(),\n timestamp: new Date().toISOString(),\n });\n if (list.length >= batch) {\n flush();\n return;\n }\n if (timer) clearTimeout(timer);\n timer = setTimeout(flush, delay);\n}\n\nexport async function trackAsync<T extends EventName = EventName>(\n name: TrackName<T>,\n properties?: TrackProperties<T>,\n options: TrackOptions = defaultOptions\n) {\n await sendEvents([\n { name, properties, options, tags: captureTags(), timestamp: new Date().toISOString() },\n ]);\n}\n\nexport function sendBeacon<T extends EventName = EventName>(\n name: TrackName<T>,\n properties?: TrackProperties<T>\n) {\n // The visitor id is persisted, so a returning visitor already has one before `getVisitor` has\n // finished its round trip for this page. Requiring the in-memory copy threw away exactly the\n // events this function exists for: everything a visit accrues before its first batch comes\n // back, which for a short visit is the whole of it.\n const stored = config.storage.getItem(keys.visitor_id);\n const visitor_id = cache.visitor?.id ?? (stored && stored !== 'undefined' ? stored : undefined);\n if (!visitor_id) return;\n\n const dto: CreateTrackEventDTO = [\n {\n name,\n properties,\n // Tags are worth less than the event carrying them: an empty set still reports the\n // engagement, and every field in `tagsSchema` is optional.\n tags: cache.tags ?? {},\n visitor_id,\n session_id: getSession().extend(),\n platform: config.platform,\n environment: config.environment,\n timestamp: new Date().toISOString(),\n },\n ];\n const blob = new Blob([JSON.stringify(dto)], { type: 'application/json' });\n const success = navigator.sendBeacon(`${config.endpoint}/events`, blob);\n if (success) return;\n console.warn('Failed to send beacon', name, properties);\n}\n"],"mappings":";;;;;;;AAeA,MAAM,iBAA+B,CAAC;AAEtC,IAAI;;;;;;;AAQJ,SAAS,iBAAiB;CACxB,OAAQ,gBAAgB,IAAI,YAAY;EAAE,MAAM;EAAG,UAAU;EAAI,WAAW;CAAE,CAAC;AACjF;;;;;;;;;;AAqBA,eAAe,cAAkC;CAC/C,IAAI;EACF,OAAO,MAAM,OAAO,QAAQ;CAC9B,SAAS,GAAY;EACnB,IAAI,aAAa,OAAO,QAAQ,IAAI,EAAE,OAAO;EAC7C,OAAO,MAAM,QAAQ,CAAC;CACxB;AACF;;;;;;;;;;AAWA,IAAI;AAEJ,eAAe,WAAW,QAAgB;;CAExC,IAAI;CACJ,IAAI;EACF,IAAI,OAAO,WAAW,GAAG;EAMzB,MAAM,UAAU,OAAO;EACvB,MAAM,EAAE,IAAI,YAAY,YAAY,WAAW,CAAC,CAAC,MAC/C,KAAK,MAAM,QAAQ,SAAS,GAC5B,KAAK,MAAM,OAAO,OAAO,SAAS,EAAE,CAAC,SAAS,CAChD;EACA,IAAI,WAAW,cAAc,eAAe,YAAY;GAOtD,MAAM,QACJ,cAAc,eAAe,aACzB,aAAa,OACb;IACE,MAAM;IACN,YAAY,CAAC;IAC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