@shware/analytics 16.0.0 → 16.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +76 -1
- package/dist/native/fbsdk.cjs +1 -2
- package/dist/native/fbsdk.cjs.map +1 -1
- package/dist/native/fbsdk.d.cts.map +1 -1
- package/dist/native/fbsdk.d.mts.map +1 -1
- package/dist/native/fbsdk.mjs +3 -4
- package/dist/native/fbsdk.mjs.map +1 -1
- package/dist/server/conversions-api-error.cjs +20 -0
- package/dist/server/conversions-api-error.cjs.map +1 -0
- package/dist/server/conversions-api-error.d.cts +17 -0
- package/dist/server/conversions-api-error.d.cts.map +1 -0
- package/dist/server/conversions-api-error.d.mts +17 -0
- package/dist/server/conversions-api-error.d.mts.map +1 -0
- package/dist/server/conversions-api-error.mjs +19 -0
- package/dist/server/conversions-api-error.mjs.map +1 -0
- package/dist/server/google-data-manager.cjs +24 -26
- package/dist/server/google-data-manager.cjs.map +1 -1
- package/dist/server/google-data-manager.d.cts +13 -5
- package/dist/server/google-data-manager.d.cts.map +1 -1
- package/dist/server/google-data-manager.d.mts +13 -5
- package/dist/server/google-data-manager.d.mts.map +1 -1
- package/dist/server/google-data-manager.mjs +24 -27
- package/dist/server/google-data-manager.mjs.map +1 -1
- package/dist/server/index.cjs +11 -0
- package/dist/server/index.d.cts +10 -7
- package/dist/server/index.d.mts +10 -7
- package/dist/server/index.mjs +9 -7
- package/dist/server/linkedin-conversions-api.cjs +29 -23
- package/dist/server/linkedin-conversions-api.cjs.map +1 -1
- package/dist/server/linkedin-conversions-api.d.cts +7 -2
- package/dist/server/linkedin-conversions-api.d.cts.map +1 -1
- package/dist/server/linkedin-conversions-api.d.mts +7 -2
- package/dist/server/linkedin-conversions-api.d.mts.map +1 -1
- package/dist/server/linkedin-conversions-api.mjs +29 -24
- package/dist/server/linkedin-conversions-api.mjs.map +1 -1
- package/dist/server/meta-capi.cjs +32 -31
- package/dist/server/meta-capi.cjs.map +1 -1
- package/dist/server/meta-capi.d.cts +12 -3
- package/dist/server/meta-capi.d.cts.map +1 -1
- package/dist/server/meta-capi.d.mts +12 -3
- package/dist/server/meta-capi.d.mts.map +1 -1
- package/dist/server/meta-capi.mjs +33 -33
- package/dist/server/meta-capi.mjs.map +1 -1
- package/dist/server/microsoft-conversions-api.cjs +33 -28
- package/dist/server/microsoft-conversions-api.cjs.map +1 -1
- package/dist/server/microsoft-conversions-api.d.cts +14 -2
- package/dist/server/microsoft-conversions-api.d.cts.map +1 -1
- package/dist/server/microsoft-conversions-api.d.mts +14 -2
- package/dist/server/microsoft-conversions-api.d.mts.map +1 -1
- package/dist/server/microsoft-conversions-api.mjs +33 -29
- package/dist/server/microsoft-conversions-api.mjs.map +1 -1
- package/dist/server/openai-conversions-api.cjs +20 -18
- package/dist/server/openai-conversions-api.cjs.map +1 -1
- package/dist/server/openai-conversions-api.d.cts +7 -0
- package/dist/server/openai-conversions-api.d.cts.map +1 -1
- package/dist/server/openai-conversions-api.d.mts +7 -0
- package/dist/server/openai-conversions-api.d.mts.map +1 -1
- package/dist/server/openai-conversions-api.mjs +21 -20
- package/dist/server/openai-conversions-api.mjs.map +1 -1
- package/dist/server/reddit-conversions-api.cjs +20 -18
- package/dist/server/reddit-conversions-api.cjs.map +1 -1
- package/dist/server/reddit-conversions-api.d.cts +7 -0
- package/dist/server/reddit-conversions-api.d.cts.map +1 -1
- package/dist/server/reddit-conversions-api.d.mts +7 -0
- package/dist/server/reddit-conversions-api.d.mts.map +1 -1
- package/dist/server/reddit-conversions-api.mjs +21 -20
- package/dist/server/reddit-conversions-api.mjs.map +1 -1
- package/dist/server/setup-conversions.cjs +62 -0
- package/dist/server/setup-conversions.cjs.map +1 -0
- package/dist/server/setup-conversions.d.cts +97 -0
- package/dist/server/setup-conversions.d.cts.map +1 -0
- package/dist/server/setup-conversions.d.mts +97 -0
- package/dist/server/setup-conversions.d.mts.map +1 -0
- package/dist/server/setup-conversions.mjs +60 -0
- package/dist/server/setup-conversions.mjs.map +1 -0
- package/dist/third-parties/index.d.cts +3 -3
- package/dist/third-parties/index.d.mts +3 -3
- package/dist/third-parties/integration.cjs +13 -6
- package/dist/third-parties/integration.cjs.map +1 -1
- package/dist/third-parties/integration.d.cts +12 -8
- package/dist/third-parties/integration.d.cts.map +1 -1
- package/dist/third-parties/integration.d.mts +12 -8
- package/dist/third-parties/integration.d.mts.map +1 -1
- package/dist/third-parties/integration.mjs +13 -7
- package/dist/third-parties/integration.mjs.map +1 -1
- package/dist/third-parties/linkedin-insight-tag.cjs +0 -4
- package/dist/third-parties/linkedin-insight-tag.cjs.map +1 -1
- package/dist/third-parties/linkedin-insight-tag.d.cts +4 -2
- package/dist/third-parties/linkedin-insight-tag.d.cts.map +1 -1
- package/dist/third-parties/linkedin-insight-tag.d.mts +4 -2
- package/dist/third-parties/linkedin-insight-tag.d.mts.map +1 -1
- package/dist/third-parties/linkedin-insight-tag.mjs +0 -4
- package/dist/third-parties/linkedin-insight-tag.mjs.map +1 -1
- package/dist/third-parties/meta-pixel.cjs +1 -3
- package/dist/third-parties/meta-pixel.cjs.map +1 -1
- package/dist/third-parties/meta-pixel.d.cts +4 -2
- package/dist/third-parties/meta-pixel.d.cts.map +1 -1
- package/dist/third-parties/meta-pixel.d.mts +4 -2
- package/dist/third-parties/meta-pixel.d.mts.map +1 -1
- package/dist/third-parties/meta-pixel.mjs +3 -5
- package/dist/third-parties/meta-pixel.mjs.map +1 -1
- package/dist/third-parties/microsoft-uet.cjs +7 -2
- package/dist/third-parties/microsoft-uet.cjs.map +1 -1
- package/dist/third-parties/microsoft-uet.d.cts +10 -3
- package/dist/third-parties/microsoft-uet.d.cts.map +1 -1
- package/dist/third-parties/microsoft-uet.d.mts +10 -3
- package/dist/third-parties/microsoft-uet.d.mts.map +1 -1
- package/dist/third-parties/microsoft-uet.mjs +8 -4
- package/dist/third-parties/microsoft-uet.mjs.map +1 -1
- package/dist/third-parties/openai-pixel.cjs +1 -3
- package/dist/third-parties/openai-pixel.cjs.map +1 -1
- package/dist/third-parties/openai-pixel.d.cts +4 -2
- package/dist/third-parties/openai-pixel.d.cts.map +1 -1
- package/dist/third-parties/openai-pixel.d.mts +4 -2
- package/dist/third-parties/openai-pixel.d.mts.map +1 -1
- package/dist/third-parties/openai-pixel.mjs +3 -5
- package/dist/third-parties/openai-pixel.mjs.map +1 -1
- package/dist/third-parties/reddit-pixel.cjs +1 -3
- package/dist/third-parties/reddit-pixel.cjs.map +1 -1
- package/dist/third-parties/reddit-pixel.d.cts +4 -2
- package/dist/third-parties/reddit-pixel.d.cts.map +1 -1
- package/dist/third-parties/reddit-pixel.d.mts +4 -2
- package/dist/third-parties/reddit-pixel.d.mts.map +1 -1
- package/dist/third-parties/reddit-pixel.mjs +3 -5
- package/dist/third-parties/reddit-pixel.mjs.map +1 -1
- package/dist/track/fbq.cjs +5 -0
- package/dist/track/fbq.cjs.map +1 -1
- package/dist/track/fbq.d.cts +2 -0
- package/dist/track/fbq.d.cts.map +1 -1
- package/dist/track/fbq.d.mts +2 -0
- package/dist/track/fbq.d.mts.map +1 -1
- package/dist/track/fbq.mjs +5 -1
- package/dist/track/fbq.mjs.map +1 -1
- package/dist/track/oaiq.cjs +5 -0
- package/dist/track/oaiq.cjs.map +1 -1
- package/dist/track/oaiq.d.cts +2 -0
- package/dist/track/oaiq.d.cts.map +1 -1
- package/dist/track/oaiq.d.mts +2 -0
- package/dist/track/oaiq.d.mts.map +1 -1
- package/dist/track/oaiq.mjs +5 -1
- package/dist/track/oaiq.mjs.map +1 -1
- package/dist/track/rdt.cjs +5 -0
- package/dist/track/rdt.cjs.map +1 -1
- package/dist/track/rdt.d.cts +2 -0
- package/dist/track/rdt.d.cts.map +1 -1
- package/dist/track/rdt.d.mts +2 -0
- package/dist/track/rdt.d.mts.map +1 -1
- package/dist/track/rdt.mjs +5 -1
- package/dist/track/rdt.mjs.map +1 -1
- package/package.json +1 -16
- package/dist/server/legacy.cjs +0 -3
- package/dist/server/legacy.d.cts +0 -2
- package/dist/server/legacy.d.mts +0 -2
- package/dist/server/legacy.mjs +0 -1
- package/dist/server/meta-conversions-api.cjs +0 -205
- package/dist/server/meta-conversions-api.cjs.map +0 -1
- package/dist/server/meta-conversions-api.d.cts +0 -8
- package/dist/server/meta-conversions-api.d.cts.map +0 -1
- package/dist/server/meta-conversions-api.d.mts +0 -8
- package/dist/server/meta-conversions-api.d.mts.map +0 -1
- package/dist/server/meta-conversions-api.mjs +0 -201
- package/dist/server/meta-conversions-api.mjs.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"google-data-manager.mjs","names":[],"sources":["../../src/server/google-data-manager.ts"],"sourcesContent":["/**\n * Google Ads conversion sender over the Data Manager API (`events:ingest`) — Google's\n * counterpart to Meta's Conversions API, and the mandated successor to the Google Ads API's\n * `UploadClickConversions`, which stopped accepting new adopters on 2026-06-15. Same shape as\n * the other senders here: a pure per-event builder, a never-throws `sendEvents`, credentials\n * in headers and never in a URL or a log line.\n *\n * Google's recommended deployment is *hybrid* (\"boost your tag with additional data sources\"):\n * this upload attaches to the SAME conversion action the gtag tag reports to, matched by\n * `transactionId` — a matched pair collapses into one conversion with the server data winning,\n * an unmatched upload is a recovered conversion. Both channels here are fed from the same\n * `track()` call, so the ids agree by construction. `transactionId` is therefore required in\n * that mode; this sender always sends one (the event id when there is no natural order id).\n *\n * Auth is a plain OAuth2 access token with the `datamanager` scope — no Google Ads developer\n * token, no API Center approval. The caller exchanges its stored refresh token for the access\n * token (one POST to oauth2.googleapis.com) and refreshes it however it likes; this module\n * stays out of the OAuth business, exactly as it stays out of Meta's.\n *\n * https://developers.google.com/data-manager/api/reference/rest/v1/events/ingest\n * https://developers.google.com/data-manager/api/devguides/events/google-ads/offline/upgrade/field-mappings\n * https://support.google.com/google-ads/answer/16542291 (hybrid: \"boost your tag with\n * additional data sources\" — the transaction-id matching contract this sender relies on)\n */\nimport { createHash } from 'node:crypto';\nimport { fetch } from '@shware/utils';\nimport { IGNORED_EVENTS } from '../third-parties/ignored-events';\nimport type { TrackEvent, UserProvidedData } from '../track/types';\nimport { resolveActionSource } from './action-source';\nimport { googleClickIds } from './click-ids';\n\nconst ENDPOINT = 'https://datamanager.googleapis.com/v1/events:ingest';\n\n/**\n * Event name → conversion action id, mirroring `LinkedinConversionConfig`: only configured\n * events upload, everything else is skipped silently. In the hybrid setup this is the id of\n * the SAME conversion action the gtag tag reports to.\n */\nexport type GoogleAdsConversionConfig = Record<Lowercase<string>, number | string>;\n\nexport interface GoogleAdsAuth {\n /** OAuth2 access token with the `datamanager` scope. Short-lived; the caller refreshes it. */\n accessToken: string;\n /** The Google Ads account the conversion actions live in. Dashes are tolerated: '123-456-7890'. */\n operatingAccountId: string;\n /** The manager account the OAuth user accesses through, when access is delegated. */\n loginAccountId?: string;\n}\n\n/**\n * EEA/UK/CH consent, applied request-wide. Google drops EEA conversions without granted\n * `adUserData` from bidding, so a host with consent signals should pass them.\n */\nexport interface GoogleAdsConsent {\n adUserData?: 'CONSENT_GRANTED' | 'CONSENT_DENIED' | 'CONSENT_STATUS_UNSPECIFIED';\n adPersonalization?: 'CONSENT_GRANTED' | 'CONSENT_DENIED' | 'CONSENT_STATUS_UNSPECIFIED';\n}\n\n/**\n * The kind of conversion action the events go to, which decides `eventSource`:\n * - `webpage` (default): the action the gtag tag reports to, as in the hybrid deployment this\n * module is built for. Its `eventSource` is optional and, when set, \"must be WEB\" — any other\n * value fails the request, and the request with it. Web events say `WEB`, others say nothing.\n * - `offline`: an action created for uploads (`UPLOAD_CLICKS`), where `eventSource` is required\n * and any value goes: `WEB`, `APP` or `OTHER` from the event's platform.\n * https://developers.google.com/data-manager/api/devguides/events/google-ads/online/send-events\n */\nexport type GoogleAdsActionType = 'webpage' | 'offline';\n\nexport interface GoogleAdsConversionsOptions {\n /** Validates the payload server-side without recording conversions. */\n validateOnly?: boolean;\n consent?: GoogleAdsConsent;\n /** The kind of conversion action `config` points at; `webpage` by default. */\n actionType?: GoogleAdsActionType;\n}\n\n/**\n * Google's email normalization is Meta's minus one wrinkle: for @gmail.com/@googlemail.com the\n * username's dots and everything from '+' on are removed; for every other domain they are kept.\n * All whitespace goes — \"leading, trailing and intermediate\".\n * https://developers.google.com/data-manager/api/devguides/concepts/formatting\n */\nexport function normalizeEmail(input: string): string {\n const email = input.replace(/\\s+/g, '').toLowerCase();\n const at = email.lastIndexOf('@');\n if (at === -1) return email;\n let username = email.slice(0, at);\n const domain = email.slice(at + 1);\n if (domain === 'gmail.com' || domain === 'googlemail.com') {\n username = username.replace(/\\./g, '').split('+', 1)[0] ?? '';\n }\n return `${username}@${domain}`;\n}\n\nconst sha256 = (value: string) => createHash('sha256').update(value).digest('hex');\n\nfunction normalizeCurrency(input: unknown): string {\n if (typeof input !== 'string') return 'USD';\n const currency = input.trim().toUpperCase();\n return /^[A-Z]{3}$/.test(currency) ? currency : 'USD';\n}\n\n/** At most 10 userIdentifiers per event, per the API's hard limit. */\nconst MAX_USER_IDENTIFIERS = 10;\n\n/** Hashes are hex strings, declared by `encoding: 'HEX'` on the request. */\nfunction getUserIdentifiers(data: UserProvidedData): Record<string, string>[] {\n const identifiers: Record<string, string>[] = [];\n const emails = Array.isArray(data.email) ? data.email : data.email ? [data.email] : [];\n for (const email of emails) {\n identifiers.push({ emailAddress: sha256(normalizeEmail(email)) });\n }\n const phones = Array.isArray(data.phone_number)\n ? data.phone_number\n : data.phone_number\n ? [data.phone_number]\n : [];\n for (const phone of phones) {\n // Phones are already E.164 by the schema ('+' then digits); hash after a defensive trim.\n identifiers.push({ phoneNumber: sha256(phone.trim()) });\n }\n return identifiers.slice(0, MAX_USER_IDENTIFIERS);\n}\n\n/** One entry of the `events` array. Field names are the REST (camelCase) spellings. */\nexport interface DataManagerEvent {\n destinationReferences: string[];\n transactionId: string;\n /** RFC 3339 — `created_at` as stored, unlike the legacy API's bespoke format. */\n eventTimestamp: string;\n /** Absent for a non-web event sent to a `webpage` action, which accepts `WEB` only. */\n eventSource?: 'WEB' | 'APP' | 'OTHER';\n conversionValue: number;\n currency: string;\n adIdentifiers?: { gclid?: string; gbraid?: string; wbraid?: string };\n userData?: { userIdentifiers: Record<string, string>[] };\n}\n\n/**\n * Builds one Event, or undefined when no conversion action is configured for the event's name.\n * The gclid goes with the gbraid when there are both — \"we recommend setting both the GCLID and\n * GBRAID\" — and otherwise one click id: gclid, else gbraid, else wbraid (nothing documents a\n * wbraid next to a gclid). https://developers.google.com/google-ads/api/docs/conversions/upload-clicks\n * Unlike\n * the legacy upload, an event with no click id at all is still worth sending when it carries\n * user identifiers — that is the enhanced-conversions match path.\n */\nexport function getDataManagerEvent(\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n event: TrackEvent<any>,\n config: GoogleAdsConversionConfig,\n data: UserProvidedData = {},\n actionType: GoogleAdsActionType = 'webpage'\n): DataManagerEvent | undefined {\n const action = config[event.name as Lowercase<string>];\n if (!action) return undefined;\n\n const source = resolveActionSource(event.platform);\n const dmEvent: DataManagerEvent = {\n destinationReferences: [String(action)],\n // The hybrid-mode match key against the gtag tag's transaction_id: same track() call feeds\n // both channels, so they agree by construction for purchase-shaped events. The event id\n // covers conversions with no natural order id — but the gtag tracker only sends a\n // transaction_id when the properties carry one, so on a HYBRID action a non-purchase event\n // reported by both channels never matches and counts twice. Attach such events to a\n // standalone (API-only) conversion action instead.\n transactionId:\n typeof event.properties?.transaction_id === 'string'\n ? event.properties.transaction_id\n : event.id,\n eventTimestamp: new Date(event.created_at).toISOString(),\n eventSource:\n source === 'web'\n ? 'WEB'\n : actionType === 'webpage'\n ? undefined\n : source === 'app'\n ? 'APP'\n : 'OTHER',\n // Both mandatory, like the LinkedIn sender's defaults: 0 USD is Google's own convention\n // for value-less goals. The API has no partial-failure mode, so a malformed currency would\n // cost the whole batch — anything that isn't a 3-letter code falls back instead.\n conversionValue: typeof event.properties?.value === 'number' ? event.properties.value : 0,\n currency: normalizeCurrency(event.properties?.currency),\n };\n\n const { gclid, gbraid, wbraid } = googleClickIds(event.tags);\n if (gclid) dmEvent.adIdentifiers = gbraid ? { gclid, gbraid } : { gclid };\n else if (gbraid) dmEvent.adIdentifiers = { gbraid };\n else if (wbraid) dmEvent.adIdentifiers = { wbraid };\n\n const userIdentifiers = getUserIdentifiers(data);\n if (userIdentifiers.length > 0) dmEvent.userData = { userIdentifiers };\n\n // With neither a click id nor an identifier Google has nothing to match on; skip.\n if (!dmEvent.adIdentifiers && !dmEvent.userData) return undefined;\n\n return dmEvent;\n}\n\nexport interface DataManagerResponse {\n requestId?: string;\n}\n\n/** The API takes at most 2000 events per request. */\nconst MAX_EVENTS_PER_REQUEST = 2000;\n\n/**\n * Uploads the configured conversions from a batch of events. Never throws: an unusable event\n * is skipped and a failed request is logged and swallowed, like every other sender here. The\n * Data Manager API has no partial-failure mode — a rejected request costs the whole batch, so\n * the builder is strict about only emitting events the API can accept. A batch beyond the\n * 2000-event request cap goes out as sequential requests; the first response is returned.\n */\nexport async function sendEvents(\n auth: GoogleAdsAuth,\n config: GoogleAdsConversionConfig,\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n events: TrackEvent<any>[],\n data: UserProvidedData = {},\n options: GoogleAdsConversionsOptions = {}\n): Promise<DataManagerResponse | undefined> {\n const dmEvents = events\n .filter((event) => !IGNORED_EVENTS.includes(event.name))\n .map((event) => getDataManagerEvent(event, config, data, options.actionType))\n .filter((dmEvent): dmEvent is DataManagerEvent => dmEvent !== undefined);\n if (dmEvents.length === 0) return undefined;\n\n const operatingAccount = {\n accountType: 'GOOGLE_ADS',\n accountId: auth.operatingAccountId.replace(/-/g, ''),\n };\n // One destination per conversion action present in the batch; each event points at its own\n // through destinationReferences, so mixed-action batches go out as one request.\n const loginAccount = auth.loginAccountId\n ? { accountType: 'GOOGLE_ADS', accountId: auth.loginAccountId.replace(/-/g, '') }\n : undefined;\n const actions = Array.from(new Set(dmEvents.flatMap((dmEvent) => dmEvent.destinationReferences)));\n const destinations = actions.map((action) => {\n const destination: Record<string, unknown> = {\n reference: action,\n operatingAccount,\n productDestinationId: action,\n };\n if (loginAccount) destination.loginAccount = loginAccount;\n return destination;\n });\n\n let firstResponse: DataManagerResponse | undefined;\n for (let offset = 0; offset < dmEvents.length; offset += MAX_EVENTS_PER_REQUEST) {\n const chunk = dmEvents.slice(offset, offset + MAX_EVENTS_PER_REQUEST);\n const body: Record<string, unknown> = {\n destinations,\n events: chunk,\n validateOnly: options.validateOnly ?? false,\n };\n if (chunk.some((dmEvent) => dmEvent.userData)) {\n body.encoding = 'HEX';\n }\n if (options.consent) {\n body.consent = options.consent;\n }\n\n try {\n const response = await fetch(ENDPOINT, {\n method: 'POST',\n // Retried although a POST: the platform deduplicates on the `event id` each event carries.\n retries: 3,\n headers: {\n 'Content-Type': 'application/json',\n Accept: 'application/json',\n Authorization: `Bearer ${auth.accessToken}`,\n },\n body: JSON.stringify(body),\n });\n if (response.ok) {\n firstResponse ??= (await response.json()) as DataManagerResponse;\n continue;\n }\n const { status } = response;\n const message = await response.text();\n console.error(`Failed to send Google Ads conversions, status: ${status}, body: ${message}`);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n console.error(`Failed to send Google Ads conversions, network error: ${message}`);\n }\n }\n return firstResponse;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+BA,MAAM,WAAW;;;;;;;AAoDjB,SAAgB,eAAe,OAAuB;CACpD,MAAM,QAAQ,MAAM,QAAQ,QAAQ,EAAE,CAAC,CAAC,YAAY;CACpD,MAAM,KAAK,MAAM,YAAY,GAAG;CAChC,IAAI,OAAO,IAAI,OAAO;CACtB,IAAI,WAAW,MAAM,MAAM,GAAG,EAAE;CAChC,MAAM,SAAS,MAAM,MAAM,KAAK,CAAC;CACjC,IAAI,WAAW,eAAe,WAAW,kBACvC,WAAW,SAAS,QAAQ,OAAO,EAAE,CAAC,CAAC,MAAM,KAAK,CAAC,CAAC,CAAC,MAAM;CAE7D,OAAO,GAAG,SAAS,GAAG;AACxB;AAEA,MAAM,UAAU,UAAkB,WAAW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,GAAG,SAAS,SAAS,QAAQ,UAAU,wBAAwB;EAC/E,MAAM,QAAQ,SAAS,MAAM,QAAQ,SAAS,sBAAsB;EACpE,MAAM,OAAgC;GACpC;GACA,QAAQ;GACR,cAAc,QAAQ,gBAAgB;EACxC;EACA,IAAI,MAAM,MAAM,YAAY,QAAQ,QAAQ,GAC1C,KAAK,WAAW;EAElB,IAAI,QAAQ,SACV,KAAK,UAAU,QAAQ;EAGzB,IAAI;GACF,MAAM,WAAW,MAAM,MAAM,UAAU;IACrC,QAAQ;IAER,SAAS;IACT,SAAS;KACP,gBAAgB;KAChB,QAAQ;KACR,eAAe,UAAU,KAAK;IAChC;IACA,MAAM,KAAK,UAAU,IAAI;GAC3B,CAAC;GACD,IAAI,SAAS,IAAI;IACf,kBAAmB,MAAM,SAAS,KAAK;IACvC;GACF;GACA,MAAM,EAAE,WAAW;GACnB,MAAM,UAAU,MAAM,SAAS,KAAK;GACpC,QAAQ,MAAM,kDAAkD,OAAO,UAAU,SAAS;EAC5F,SAAS,OAAO;GACd,MAAM,UAAU,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;GACrE,QAAQ,MAAM,yDAAyD,SAAS;EAClF;CACF;CACA,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"google-data-manager.mjs","names":[],"sources":["../../src/server/google-data-manager.ts"],"sourcesContent":["/**\n * Google Ads conversion sender over the Data Manager API (`events:ingest`) — Google's\n * counterpart to Meta's Conversions API, and the mandated successor to the Google Ads API's\n * `UploadClickConversions`, which stopped accepting new adopters on 2026-06-15. Same shape as\n * the other senders here: a pure per-event builder, a `sendEvents` that rejects on failure,\n * credentials in headers and never in a URL or an error.\n *\n * Google's recommended deployment is *hybrid* (\"boost your tag with additional data sources\"):\n * this upload attaches to the SAME conversion action the gtag tag reports to, matched by\n * `transactionId` — a matched pair collapses into one conversion with the server data winning,\n * an unmatched upload is a recovered conversion. Both channels here are fed from the same\n * `track()` call, so the ids agree by construction. `transactionId` is therefore required in\n * that mode; this sender always sends one (the event id when there is no natural order id).\n *\n * Auth is a plain OAuth2 access token with the `datamanager` scope — no Google Ads developer\n * token, no API Center approval. The caller exchanges its stored refresh token for the access\n * token (one POST to oauth2.googleapis.com) and refreshes it however it likes; this module\n * stays out of the OAuth business, exactly as it stays out of Meta's.\n *\n * https://developers.google.com/data-manager/api/reference/rest/v1/events/ingest\n * https://developers.google.com/data-manager/api/devguides/events/google-ads/offline/upgrade/field-mappings\n * https://support.google.com/google-ads/answer/16542291 (hybrid: \"boost your tag with\n * additional data sources\" — the transaction-id matching contract this sender relies on)\n */\nimport { createHash } from 'node:crypto';\nimport { fetch } from '@shware/utils';\nimport { IGNORED_EVENTS } from '../third-parties/ignored-events';\nimport type { TrackEvent, TrackName, UserProvidedData } from '../track/types';\nimport { resolveActionSource } from './action-source';\nimport { googleClickIds } from './click-ids';\nimport { ConversionsApiError } from './conversions-api-error';\nimport { type ConversionDestination, conversionDestination } from './setup-conversions';\n\nconst ENDPOINT = 'https://datamanager.googleapis.com/v1/events:ingest';\n\n/**\n * Event name → conversion action id, mirroring `LinkedinConversionConfig`: only configured\n * events upload, everything else is skipped silently. In the hybrid setup this is the id of\n * the SAME conversion action the gtag tag reports to. Keys are the names `track` accepts, so with\n * strict event names a typo or undeclared event is a compile error.\n */\nexport type GoogleAdsConversionConfig = { readonly [K in TrackName]?: number | string };\n\nexport interface GoogleAdsAuth {\n /** OAuth2 access token with the `datamanager` scope. Short-lived; the caller refreshes it. */\n accessToken: string;\n /** The Google Ads account the conversion actions live in. Dashes are tolerated: '123-456-7890'. */\n operatingAccountId: string;\n /** The manager account the OAuth user accesses through, when access is delegated. */\n loginAccountId?: string;\n}\n\n/**\n * EEA/UK/CH consent, applied request-wide. Google drops EEA conversions without granted\n * `adUserData` from bidding, so a host with consent signals should pass them.\n */\nexport interface GoogleAdsConsent {\n adUserData?: 'CONSENT_GRANTED' | 'CONSENT_DENIED' | 'CONSENT_STATUS_UNSPECIFIED';\n adPersonalization?: 'CONSENT_GRANTED' | 'CONSENT_DENIED' | 'CONSENT_STATUS_UNSPECIFIED';\n}\n\n/**\n * The kind of conversion action the events go to, which decides `eventSource`:\n * - `webpage` (default): the action the gtag tag reports to, as in the hybrid deployment this\n * module is built for. Its `eventSource` is optional and, when set, \"must be WEB\" — any other\n * value fails the request, and the request with it. Web events say `WEB`, others say nothing.\n * - `offline`: an action created for uploads (`UPLOAD_CLICKS`), where `eventSource` is required\n * and any value goes: `WEB`, `APP` or `OTHER` from the event's platform.\n * https://developers.google.com/data-manager/api/devguides/events/google-ads/online/send-events\n */\nexport type GoogleAdsActionType = 'webpage' | 'offline';\n\nexport interface GoogleAdsConversionsOptions {\n /** Validates the payload server-side without recording conversions. */\n validateOnly?: boolean;\n consent?: GoogleAdsConsent;\n /** The kind of conversion action `config` points at; `webpage` by default. */\n actionType?: GoogleAdsActionType;\n}\n\n/**\n * Google's email normalization is Meta's minus one wrinkle: for @gmail.com/@googlemail.com the\n * username's dots and everything from '+' on are removed; for every other domain they are kept.\n * All whitespace goes — \"leading, trailing and intermediate\".\n * https://developers.google.com/data-manager/api/devguides/concepts/formatting\n */\nexport function normalizeEmail(input: string): string {\n const email = input.replace(/\\s+/g, '').toLowerCase();\n const at = email.lastIndexOf('@');\n if (at === -1) return email;\n let username = email.slice(0, at);\n const domain = email.slice(at + 1);\n if (domain === 'gmail.com' || domain === 'googlemail.com') {\n username = username.replace(/\\./g, '').split('+', 1)[0] ?? '';\n }\n return `${username}@${domain}`;\n}\n\nconst sha256 = (value: string) => createHash('sha256').update(value).digest('hex');\n\nfunction normalizeCurrency(input: unknown): string {\n if (typeof input !== 'string') return 'USD';\n const currency = input.trim().toUpperCase();\n return /^[A-Z]{3}$/.test(currency) ? currency : 'USD';\n}\n\n/** At most 10 userIdentifiers per event, per the API's hard limit. */\nconst MAX_USER_IDENTIFIERS = 10;\n\n/** Hashes are hex strings, declared by `encoding: 'HEX'` on the request. */\nfunction getUserIdentifiers(data: UserProvidedData): Record<string, string>[] {\n const identifiers: Record<string, string>[] = [];\n const emails = Array.isArray(data.email) ? data.email : data.email ? [data.email] : [];\n for (const email of emails) {\n identifiers.push({ emailAddress: sha256(normalizeEmail(email)) });\n }\n const phones = Array.isArray(data.phone_number)\n ? data.phone_number\n : data.phone_number\n ? [data.phone_number]\n : [];\n for (const phone of phones) {\n // Phones are already E.164 by the schema ('+' then digits); hash after a defensive trim.\n identifiers.push({ phoneNumber: sha256(phone.trim()) });\n }\n return identifiers.slice(0, MAX_USER_IDENTIFIERS);\n}\n\n/** One entry of the `events` array. Field names are the REST (camelCase) spellings. */\nexport interface DataManagerEvent {\n destinationReferences: string[];\n transactionId: string;\n /** RFC 3339 — `created_at` as stored, unlike the legacy API's bespoke format. */\n eventTimestamp: string;\n /** Absent for a non-web event sent to a `webpage` action, which accepts `WEB` only. */\n eventSource?: 'WEB' | 'APP' | 'OTHER';\n conversionValue: number;\n currency: string;\n adIdentifiers?: { gclid?: string; gbraid?: string; wbraid?: string };\n userData?: { userIdentifiers: Record<string, string>[] };\n}\n\n/**\n * Builds one Event, or undefined when no conversion action is configured for the event's name.\n * The gclid goes with the gbraid when there are both — \"we recommend setting both the GCLID and\n * GBRAID\" — and otherwise one click id: gclid, else gbraid, else wbraid (nothing documents a\n * wbraid next to a gclid). https://developers.google.com/google-ads/api/docs/conversions/upload-clicks\n * Unlike\n * the legacy upload, an event with no click id at all is still worth sending when it carries\n * user identifiers — that is the enhanced-conversions match path.\n */\nexport function getDataManagerEvent(\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n event: TrackEvent<any>,\n config: GoogleAdsConversionConfig,\n data: UserProvidedData = {},\n actionType: GoogleAdsActionType = 'webpage'\n): DataManagerEvent | undefined {\n const action = config[event.name as TrackName];\n if (!action) return undefined;\n\n const source = resolveActionSource(event.platform);\n const dmEvent: DataManagerEvent = {\n destinationReferences: [String(action)],\n // The hybrid-mode match key against the gtag tag's transaction_id: same track() call feeds\n // both channels, so they agree by construction for purchase-shaped events. The event id\n // covers conversions with no natural order id — but the gtag tracker only sends a\n // transaction_id when the properties carry one, so on a HYBRID action a non-purchase event\n // reported by both channels never matches and counts twice. Attach such events to a\n // standalone (API-only) conversion action instead.\n transactionId:\n typeof event.properties?.transaction_id === 'string'\n ? event.properties.transaction_id\n : event.id,\n eventTimestamp: new Date(event.created_at).toISOString(),\n eventSource:\n source === 'web'\n ? 'WEB'\n : actionType === 'webpage'\n ? undefined\n : source === 'app'\n ? 'APP'\n : 'OTHER',\n // Both mandatory, like the LinkedIn sender's defaults: 0 USD is Google's own convention\n // for value-less goals. The API has no partial-failure mode, so a malformed currency would\n // cost the whole batch — anything that isn't a 3-letter code falls back instead.\n conversionValue: typeof event.properties?.value === 'number' ? event.properties.value : 0,\n currency: normalizeCurrency(event.properties?.currency),\n };\n\n const { gclid, gbraid, wbraid } = googleClickIds(event.tags);\n if (gclid) dmEvent.adIdentifiers = gbraid ? { gclid, gbraid } : { gclid };\n else if (gbraid) dmEvent.adIdentifiers = { gbraid };\n else if (wbraid) dmEvent.adIdentifiers = { wbraid };\n\n const userIdentifiers = getUserIdentifiers(data);\n if (userIdentifiers.length > 0) dmEvent.userData = { userIdentifiers };\n\n // With neither a click id nor an identifier Google has nothing to match on; skip.\n if (!dmEvent.adIdentifiers && !dmEvent.userData) return undefined;\n\n return dmEvent;\n}\n\nexport interface DataManagerResponse {\n requestId?: string;\n}\n\n/** The API takes at most 2000 events per request. */\nconst MAX_EVENTS_PER_REQUEST = 2000;\n\n/**\n * Uploads the configured conversions from a batch of events. An unusable event is skipped; a\n * failed request rejects (a `ConversionsApiError`, or the fetch error), as with every sender here,\n * and sends no further ones. The\n * Data Manager API has no partial-failure mode — a rejected request costs the whole batch, so\n * the builder is strict about only emitting events the API can accept. A batch beyond the\n * 2000-event request cap goes out as sequential requests; the first response is returned.\n */\nexport async function sendEvents(\n auth: GoogleAdsAuth,\n config: GoogleAdsConversionConfig,\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n events: TrackEvent<any>[],\n data: UserProvidedData = {},\n options: GoogleAdsConversionsOptions = {}\n): Promise<DataManagerResponse | undefined> {\n const dmEvents = events\n .filter((event) => !IGNORED_EVENTS.includes(event.name))\n .map((event) => getDataManagerEvent(event, config, data, options.actionType))\n .filter((dmEvent): dmEvent is DataManagerEvent => dmEvent !== undefined);\n if (dmEvents.length === 0) return undefined;\n\n const operatingAccount = {\n accountType: 'GOOGLE_ADS',\n accountId: auth.operatingAccountId.replace(/-/g, ''),\n };\n // One destination per conversion action present in the batch; each event points at its own\n // through destinationReferences, so mixed-action batches go out as one request.\n const loginAccount = auth.loginAccountId\n ? { accountType: 'GOOGLE_ADS', accountId: auth.loginAccountId.replace(/-/g, '') }\n : undefined;\n const actions = Array.from(new Set(dmEvents.flatMap((dmEvent) => dmEvent.destinationReferences)));\n const destinations = actions.map((action) => {\n const destination: Record<string, unknown> = {\n reference: action,\n operatingAccount,\n productDestinationId: action,\n };\n if (loginAccount) destination.loginAccount = loginAccount;\n return destination;\n });\n\n let firstResponse: DataManagerResponse | undefined;\n for (let offset = 0; offset < dmEvents.length; offset += MAX_EVENTS_PER_REQUEST) {\n const chunk = dmEvents.slice(offset, offset + MAX_EVENTS_PER_REQUEST);\n const body: Record<string, unknown> = {\n destinations,\n events: chunk,\n validateOnly: options.validateOnly ?? false,\n };\n if (chunk.some((dmEvent) => dmEvent.userData)) {\n body.encoding = 'HEX';\n }\n if (options.consent) {\n body.consent = options.consent;\n }\n\n const response = await fetch(ENDPOINT, {\n method: 'POST',\n // Retried although a POST: the platform deduplicates on the `event id` each event carries.\n retries: 3,\n headers: {\n 'Content-Type': 'application/json',\n Accept: 'application/json',\n Authorization: `Bearer ${auth.accessToken}`,\n },\n body: JSON.stringify(body),\n });\n // The first failed request ends the batch: sending it again sends every request again, and\n // the platform deduplicates the ones that had gone through.\n if (!response.ok) {\n throw new ConversionsApiError('google', response.status, await response.text());\n }\n firstResponse ??= (await response.json()) as DataManagerResponse;\n }\n return firstResponse;\n}\n\n/** Google Ads through the Data Manager API: the events in `conversions`, each as its action. */\nexport function googleAdsConversions(\n options: GoogleAdsConversionsOptions & {\n auth: GoogleAdsAuth;\n conversions: GoogleAdsConversionConfig;\n }\n): ConversionDestination {\n return conversionDestination(\n (name) => options.conversions[name as TrackName] !== undefined,\n (events, data) => sendEvents(options.auth, options.conversions, events, data, options)\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiCA,MAAM,WAAW;;;;;;;AAqDjB,SAAgB,eAAe,OAAuB;CACpD,MAAM,QAAQ,MAAM,QAAQ,QAAQ,EAAE,CAAC,CAAC,YAAY;CACpD,MAAM,KAAK,MAAM,YAAY,GAAG;CAChC,IAAI,OAAO,IAAI,OAAO;CACtB,IAAI,WAAW,MAAM,MAAM,GAAG,EAAE;CAChC,MAAM,SAAS,MAAM,MAAM,KAAK,CAAC;CACjC,IAAI,WAAW,eAAe,WAAW,kBACvC,WAAW,SAAS,QAAQ,OAAO,EAAE,CAAC,CAAC,MAAM,KAAK,CAAC,CAAC,CAAC,MAAM;CAE7D,OAAO,GAAG,SAAS,GAAG;AACxB;AAEA,MAAM,UAAU,UAAkB,WAAW,QAAQ,CAAC,CAAC,OAAO,KAAK,CAAC,CAAC,OAAO,KAAK;AAEjF,SAAS,kBAAkB,OAAwB;CACjD,IAAI,OAAO,UAAU,UAAU,OAAO;CACtC,MAAM,WAAW,MAAM,KAAK,CAAC,CAAC,YAAY;CAC1C,OAAO,aAAa,KAAK,QAAQ,IAAI,WAAW;AAClD;;AAGA,MAAM,uBAAuB;;AAG7B,SAAS,mBAAmB,MAAkD;CAC5E,MAAM,cAAwC,CAAC;CAC/C,MAAM,SAAS,MAAM,QAAQ,KAAK,KAAK,IAAI,KAAK,QAAQ,KAAK,QAAQ,CAAC,KAAK,KAAK,IAAI,CAAC;CACrF,KAAK,MAAM,SAAS,QAClB,YAAY,KAAK,EAAE,cAAc,OAAO,eAAe,KAAK,CAAC,EAAE,CAAC;CAElE,MAAM,S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,MAAM,SAAS,KAAK,CAAC;EAEhF,kBAAmB,MAAM,SAAS,KAAK;CACzC;CACA,OAAO;AACT;;AAGA,SAAgB,qBACd,SAIuB;CACvB,OAAO,uBACJ,SAAS,QAAQ,YAAY,UAAuB,KAAA,IACpD,QAAQ,SAAS,WAAW,QAAQ,MAAM,QAAQ,aAAa,QAAQ,MAAM,OAAO,CACvF;AACF"}
|
package/dist/server/index.cjs
CHANGED
|
@@ -1,16 +1,20 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
2
|
const require_click_id_index = require("../click-id/index.cjs");
|
|
3
|
+
const require_server_conversions_api_error = require("./conversions-api-error.cjs");
|
|
4
|
+
const require_server_setup_conversions = require("./setup-conversions.cjs");
|
|
3
5
|
const require_server_google_data_manager = require("./google-data-manager.cjs");
|
|
4
6
|
const require_server_meta_capi = require("./meta-capi.cjs");
|
|
5
7
|
const require_server_reddit_conversions_api = require("./reddit-conversions-api.cjs");
|
|
6
8
|
const require_server_linkedin_conversions_api = require("./linkedin-conversions-api.cjs");
|
|
7
9
|
const require_server_openai_conversions_api = require("./openai-conversions-api.cjs");
|
|
8
10
|
const require_server_microsoft_conversions_api = require("./microsoft-conversions-api.cjs");
|
|
11
|
+
exports.ConversionsApiError = require_server_conversions_api_error.ConversionsApiError;
|
|
9
12
|
exports.FBC_COOKIE = require_click_id_index.FBC_COOKIE;
|
|
10
13
|
exports.GCL_AW_COOKIE = require_click_id_index.GCL_AW_COOKIE;
|
|
11
14
|
exports.GCL_GB_COOKIE = require_click_id_index.GCL_GB_COOKIE;
|
|
12
15
|
exports.RDT_CID_COOKIE = require_click_id_index.RDT_CID_COOKIE;
|
|
13
16
|
exports.UET_MSCLKID_COOKIE = require_click_id_index.UET_MSCLKID_COOKIE;
|
|
17
|
+
exports.conversionDestination = require_server_setup_conversions.conversionDestination;
|
|
14
18
|
exports.formatFbc = require_click_id_index.formatFbc;
|
|
15
19
|
exports.formatGcl = require_click_id_index.formatGcl;
|
|
16
20
|
exports.formatMsclkid = require_click_id_index.formatMsclkid;
|
|
@@ -18,11 +22,17 @@ exports.formatUetMsclkid = require_click_id_index.formatUetMsclkid;
|
|
|
18
22
|
exports.getCapiEvent = require_server_meta_capi.getCapiEvent;
|
|
19
23
|
exports.getDataManagerEvent = require_server_google_data_manager.getDataManagerEvent;
|
|
20
24
|
exports.getMicrosoftEvent = require_server_microsoft_conversions_api.getServerEvent;
|
|
25
|
+
exports.googleAdsConversions = require_server_google_data_manager.googleAdsConversions;
|
|
26
|
+
exports.linkedinConversions = require_server_linkedin_conversions_api.linkedinConversions;
|
|
27
|
+
exports.metaConversions = require_server_meta_capi.metaConversions;
|
|
28
|
+
exports.microsoftConversions = require_server_microsoft_conversions_api.microsoftConversions;
|
|
21
29
|
exports.normalizeEmail = require_server_google_data_manager.normalizeEmail;
|
|
22
30
|
exports.normalizeMicrosoftEmail = require_server_microsoft_conversions_api.normalizeEmail;
|
|
31
|
+
exports.openaiConversions = require_server_openai_conversions_api.openaiConversions;
|
|
23
32
|
exports.parseFbc = require_click_id_index.parseFbc;
|
|
24
33
|
exports.parseGcl = require_click_id_index.parseGcl;
|
|
25
34
|
exports.parseUetMsclkid = require_click_id_index.parseUetMsclkid;
|
|
35
|
+
exports.redditConversions = require_server_reddit_conversions_api.redditConversions;
|
|
26
36
|
exports.resolveClickIdCookies = require_click_id_index.resolveClickIdCookies;
|
|
27
37
|
exports.sendGoogleAdsEvents = require_server_google_data_manager.sendEvents;
|
|
28
38
|
exports.sendLinkedinEvents = require_server_linkedin_conversions_api.sendEvents;
|
|
@@ -30,4 +40,5 @@ exports.sendMetaEvents = require_server_meta_capi.sendEvents;
|
|
|
30
40
|
exports.sendMicrosoftEvents = require_server_microsoft_conversions_api.sendEvents;
|
|
31
41
|
exports.sendOpenAIEvents = require_server_openai_conversions_api.sendEvents;
|
|
32
42
|
exports.sendRedditEvents = require_server_reddit_conversions_api.sendEvents;
|
|
43
|
+
exports.setupConversions = require_server_setup_conversions.setupConversions;
|
|
33
44
|
exports.toSetCookieHeaders = require_click_id_index.toSetCookieHeaders;
|
package/dist/server/index.d.cts
CHANGED
|
@@ -1,9 +1,12 @@
|
|
|
1
1
|
import { FBC_COOKIE, GCL_AW_COOKIE, GCL_GB_COOKIE, ParsedFbc, ParsedGcl, RDT_CID_COOKIE, ResolveClickIdCookiesInput, ResolveClickIdCookiesResult, UET_MSCLKID_COOKIE, formatFbc, formatGcl, formatMsclkid, formatUetMsclkid, parseFbc, parseGcl, parseUetMsclkid, resolveClickIdCookies, toSetCookieHeaders } from "../click-id/index.cjs";
|
|
2
2
|
import { EventActionSource } from "./action-source.cjs";
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
6
|
-
import {
|
|
7
|
-
import { sendEvents as sendEvents$
|
|
8
|
-
import {
|
|
9
|
-
|
|
3
|
+
import { ConversionsApiError } from "./conversions-api-error.cjs";
|
|
4
|
+
import { ConversionDestination, ConversionUser, ConversionsOptions, ServerEvent, conversionDestination, setupConversions } from "./setup-conversions.cjs";
|
|
5
|
+
import { DataManagerEvent, DataManagerResponse, GoogleAdsActionType, GoogleAdsAuth, GoogleAdsConsent, GoogleAdsConversionConfig, GoogleAdsConversionsOptions, getDataManagerEvent, googleAdsConversions, normalizeEmail, sendEvents } from "./google-data-manager.cjs";
|
|
6
|
+
import { CapiEvent, MetaConversionsOptions, MetaConversionsResponse, getCapiEvent, metaConversions, sendEvents as sendEvents$2 } from "./meta-capi.cjs";
|
|
7
|
+
import { redditConversions, sendEvents as sendEvents$5 } from "./reddit-conversions-api.cjs";
|
|
8
|
+
import { LinkedinConversionConfig } from "../third-parties/linkedin-insight-tag.cjs";
|
|
9
|
+
import { linkedinConversions, sendEvents as sendEvents$1 } from "./linkedin-conversions-api.cjs";
|
|
10
|
+
import { openaiConversions, sendEvents as sendEvents$4 } from "./openai-conversions-api.cjs";
|
|
11
|
+
import { MicrosoftConversionsOptions, MicrosoftConversionsResponse, MicrosoftCustomData, MicrosoftEvent, MicrosoftEventOptions, MicrosoftUserData, MicrosoftValidationDetail, getServerEvent, microsoftConversions, normalizeEmail as normalizeEmail$1, sendEvents as sendEvents$3 } from "./microsoft-conversions-api.cjs";
|
|
12
|
+
export { type CapiEvent, type ConversionDestination, type ConversionUser, ConversionsApiError, type ConversionsOptions, type DataManagerEvent, type DataManagerResponse, type EventActionSource, FBC_COOKIE, GCL_AW_COOKIE, GCL_GB_COOKIE, type GoogleAdsActionType, type GoogleAdsAuth, type GoogleAdsConsent, type GoogleAdsConversionConfig, type GoogleAdsConversionsOptions, type LinkedinConversionConfig, type MetaConversionsOptions, type MetaConversionsResponse, type MicrosoftConversionsOptions, type MicrosoftConversionsResponse, type MicrosoftCustomData, type MicrosoftEvent, type MicrosoftEventOptions, type MicrosoftUserData, type MicrosoftValidationDetail, type ParsedFbc, type ParsedGcl, RDT_CID_COOKIE, type ResolveClickIdCookiesInput, type ResolveClickIdCookiesResult, type ServerEvent, UET_MSCLKID_COOKIE, conversionDestination, formatFbc, formatGcl, formatMsclkid, formatUetMsclkid, getCapiEvent, getDataManagerEvent, getServerEvent as getMicrosoftEvent, googleAdsConversions, linkedinConversions, metaConversions, microsoftConversions, normalizeEmail, normalizeEmail$1 as normalizeMicrosoftEmail, openaiConversions, parseFbc, parseGcl, parseUetMsclkid, redditConversions, resolveClickIdCookies, sendEvents as sendGoogleAdsEvents, sendEvents$1 as sendLinkedinEvents, sendEvents$2 as sendMetaEvents, sendEvents$3 as sendMicrosoftEvents, sendEvents$4 as sendOpenAIEvents, sendEvents$5 as sendRedditEvents, setupConversions, toSetCookieHeaders };
|
package/dist/server/index.d.mts
CHANGED
|
@@ -1,9 +1,12 @@
|
|
|
1
1
|
import { FBC_COOKIE, GCL_AW_COOKIE, GCL_GB_COOKIE, ParsedFbc, ParsedGcl, RDT_CID_COOKIE, ResolveClickIdCookiesInput, ResolveClickIdCookiesResult, UET_MSCLKID_COOKIE, formatFbc, formatGcl, formatMsclkid, formatUetMsclkid, parseFbc, parseGcl, parseUetMsclkid, resolveClickIdCookies, toSetCookieHeaders } from "../click-id/index.mjs";
|
|
2
2
|
import { EventActionSource } from "./action-source.mjs";
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
6
|
-
import {
|
|
7
|
-
import { sendEvents as sendEvents$
|
|
8
|
-
import {
|
|
9
|
-
|
|
3
|
+
import { ConversionsApiError } from "./conversions-api-error.mjs";
|
|
4
|
+
import { ConversionDestination, ConversionUser, ConversionsOptions, ServerEvent, conversionDestination, setupConversions } from "./setup-conversions.mjs";
|
|
5
|
+
import { DataManagerEvent, DataManagerResponse, GoogleAdsActionType, GoogleAdsAuth, GoogleAdsConsent, GoogleAdsConversionConfig, GoogleAdsConversionsOptions, getDataManagerEvent, googleAdsConversions, normalizeEmail, sendEvents } from "./google-data-manager.mjs";
|
|
6
|
+
import { CapiEvent, MetaConversionsOptions, MetaConversionsResponse, getCapiEvent, metaConversions, sendEvents as sendEvents$2 } from "./meta-capi.mjs";
|
|
7
|
+
import { redditConversions, sendEvents as sendEvents$5 } from "./reddit-conversions-api.mjs";
|
|
8
|
+
import { LinkedinConversionConfig } from "../third-parties/linkedin-insight-tag.mjs";
|
|
9
|
+
import { linkedinConversions, sendEvents as sendEvents$1 } from "./linkedin-conversions-api.mjs";
|
|
10
|
+
import { openaiConversions, sendEvents as sendEvents$4 } from "./openai-conversions-api.mjs";
|
|
11
|
+
import { MicrosoftConversionsOptions, MicrosoftConversionsResponse, MicrosoftCustomData, MicrosoftEvent, MicrosoftEventOptions, MicrosoftUserData, MicrosoftValidationDetail, getServerEvent, microsoftConversions, normalizeEmail as normalizeEmail$1, sendEvents as sendEvents$3 } from "./microsoft-conversions-api.mjs";
|
|
12
|
+
export { type CapiEvent, type ConversionDestination, type ConversionUser, ConversionsApiError, type ConversionsOptions, type DataManagerEvent, type DataManagerResponse, type EventActionSource, FBC_COOKIE, GCL_AW_COOKIE, GCL_GB_COOKIE, type GoogleAdsActionType, type GoogleAdsAuth, type GoogleAdsConsent, type GoogleAdsConversionConfig, type GoogleAdsConversionsOptions, type LinkedinConversionConfig, type MetaConversionsOptions, type MetaConversionsResponse, type MicrosoftConversionsOptions, type MicrosoftConversionsResponse, type MicrosoftCustomData, type MicrosoftEvent, type MicrosoftEventOptions, type MicrosoftUserData, type MicrosoftValidationDetail, type ParsedFbc, type ParsedGcl, RDT_CID_COOKIE, type ResolveClickIdCookiesInput, type ResolveClickIdCookiesResult, type ServerEvent, UET_MSCLKID_COOKIE, conversionDestination, formatFbc, formatGcl, formatMsclkid, formatUetMsclkid, getCapiEvent, getDataManagerEvent, getServerEvent as getMicrosoftEvent, googleAdsConversions, linkedinConversions, metaConversions, microsoftConversions, normalizeEmail, normalizeEmail$1 as normalizeMicrosoftEmail, openaiConversions, parseFbc, parseGcl, parseUetMsclkid, redditConversions, resolveClickIdCookies, sendEvents as sendGoogleAdsEvents, sendEvents$1 as sendLinkedinEvents, sendEvents$2 as sendMetaEvents, sendEvents$3 as sendMicrosoftEvents, sendEvents$4 as sendOpenAIEvents, sendEvents$5 as sendRedditEvents, setupConversions, toSetCookieHeaders };
|
package/dist/server/index.mjs
CHANGED
|
@@ -1,8 +1,10 @@
|
|
|
1
1
|
import { FBC_COOKIE, GCL_AW_COOKIE, GCL_GB_COOKIE, RDT_CID_COOKIE, UET_MSCLKID_COOKIE, formatFbc, formatGcl, formatMsclkid, formatUetMsclkid, parseFbc, parseGcl, parseUetMsclkid, resolveClickIdCookies, toSetCookieHeaders } from "../click-id/index.mjs";
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
5
|
-
import { sendEvents as sendEvents$
|
|
6
|
-
import { sendEvents as sendEvents$
|
|
7
|
-
import {
|
|
8
|
-
|
|
2
|
+
import { ConversionsApiError } from "./conversions-api-error.mjs";
|
|
3
|
+
import { conversionDestination, setupConversions } from "./setup-conversions.mjs";
|
|
4
|
+
import { getDataManagerEvent, googleAdsConversions, normalizeEmail, sendEvents } from "./google-data-manager.mjs";
|
|
5
|
+
import { getCapiEvent, metaConversions, sendEvents as sendEvents$2 } from "./meta-capi.mjs";
|
|
6
|
+
import { redditConversions, sendEvents as sendEvents$5 } from "./reddit-conversions-api.mjs";
|
|
7
|
+
import { linkedinConversions, sendEvents as sendEvents$1 } from "./linkedin-conversions-api.mjs";
|
|
8
|
+
import { openaiConversions, sendEvents as sendEvents$4 } from "./openai-conversions-api.mjs";
|
|
9
|
+
import { getServerEvent, microsoftConversions, normalizeEmail as normalizeEmail$1, sendEvents as sendEvents$3 } from "./microsoft-conversions-api.mjs";
|
|
10
|
+
export { ConversionsApiError, FBC_COOKIE, GCL_AW_COOKIE, GCL_GB_COOKIE, RDT_CID_COOKIE, UET_MSCLKID_COOKIE, conversionDestination, formatFbc, formatGcl, formatMsclkid, formatUetMsclkid, getCapiEvent, getDataManagerEvent, getServerEvent as getMicrosoftEvent, googleAdsConversions, linkedinConversions, metaConversions, microsoftConversions, normalizeEmail, normalizeEmail$1 as normalizeMicrosoftEmail, openaiConversions, parseFbc, parseGcl, parseUetMsclkid, redditConversions, resolveClickIdCookies, sendEvents as sendGoogleAdsEvents, sendEvents$1 as sendLinkedinEvents, sendEvents$2 as sendMetaEvents, sendEvents$3 as sendMicrosoftEvents, sendEvents$4 as sendOpenAIEvents, sendEvents$5 as sendRedditEvents, setupConversions, toSetCookieHeaders };
|
|
@@ -2,6 +2,8 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
|
2
2
|
const require_third_parties_ignored_events = require("../third-parties/ignored-events.cjs");
|
|
3
3
|
const require_utils_field = require("../utils/field.cjs");
|
|
4
4
|
const require_server_click_ids = require("./click-ids.cjs");
|
|
5
|
+
const require_server_conversions_api_error = require("./conversions-api-error.cjs");
|
|
6
|
+
const require_server_setup_conversions = require("./setup-conversions.cjs");
|
|
5
7
|
let _shware_utils = require("@shware/utils");
|
|
6
8
|
let node_crypto = require("node:crypto");
|
|
7
9
|
let node_net = require("node:net");
|
|
@@ -38,7 +40,6 @@ const hashName = (name) => sha256(name.toLowerCase().replace(/[\s\p{P}]/gu, ""))
|
|
|
38
40
|
*/
|
|
39
41
|
const MAX_EVENT_AGE_MS = 777594e4;
|
|
40
42
|
async function sendEvents(accessToken, config, events, data = {}) {
|
|
41
|
-
const eventNames = Object.keys(config);
|
|
42
43
|
const address = require_utils_field.getFirst(data.address);
|
|
43
44
|
const userIds = [];
|
|
44
45
|
const externalIds = data.user_id ? [data.user_id] : void 0;
|
|
@@ -71,9 +72,15 @@ async function sendEvents(accessToken, config, events, data = {}) {
|
|
|
71
72
|
});
|
|
72
73
|
return ids;
|
|
73
74
|
};
|
|
74
|
-
const dto = { elements: events.filter((event) =>
|
|
75
|
+
const dto = { elements: events.filter((event) => !require_third_parties_ignored_events.IGNORED_EVENTS.includes(event.name)).filter((event) => Date.now() - Date.parse(event.created_at) <= MAX_EVENT_AGE_MS).flatMap((event) => {
|
|
76
|
+
const conversionId = config[event.name];
|
|
77
|
+
return conversionId === void 0 ? [] : [{
|
|
78
|
+
event,
|
|
79
|
+
conversionId
|
|
80
|
+
}];
|
|
81
|
+
}).map(({ event, conversionId }) => ({
|
|
75
82
|
eventId: event.id,
|
|
76
|
-
conversion: `urn:lla:llaPartnerConversion:${
|
|
83
|
+
conversion: `urn:lla:llaPartnerConversion:${conversionId}`,
|
|
77
84
|
conversionHappenedAt: new Date(event.created_at).getTime(),
|
|
78
85
|
conversionValue: {
|
|
79
86
|
currencyCode: event.properties?.currency?.toUpperCase() ?? "USD",
|
|
@@ -86,27 +93,26 @@ async function sendEvents(accessToken, config, events, data = {}) {
|
|
|
86
93
|
}
|
|
87
94
|
})).filter(({ user }) => user.userIds.length > 0 || !!user.userInfo || !!user.externalIds || !!user.lead) };
|
|
88
95
|
if (dto.elements.length === 0) return;
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
console.error("Failed to send LinkedIn conversion, network error:", error);
|
|
108
|
-
}
|
|
96
|
+
const response = await (0, _shware_utils.fetch)("https://api.linkedin.com/rest/conversionEvents", {
|
|
97
|
+
method: "POST",
|
|
98
|
+
retries: 3,
|
|
99
|
+
headers: {
|
|
100
|
+
Authorization: `Bearer ${accessToken}`,
|
|
101
|
+
"Content-Type": "application/json",
|
|
102
|
+
"LinkedIn-Version": "202609",
|
|
103
|
+
"X-Restli-Protocol-Version": "2.0.0",
|
|
104
|
+
"X-RestLi-Method": "BATCH_CREATE"
|
|
105
|
+
},
|
|
106
|
+
body: JSON.stringify(dto)
|
|
107
|
+
});
|
|
108
|
+
if (response.ok) return;
|
|
109
|
+
throw new require_server_conversions_api_error.ConversionsApiError("linkedin", response.status, await response.text());
|
|
110
|
+
}
|
|
111
|
+
/** LinkedIn's Conversions API, sent the events in `conversions`, as `linkedInAds` is. */
|
|
112
|
+
function linkedinConversions(options) {
|
|
113
|
+
return require_server_setup_conversions.conversionDestination((name) => options.conversions[name] !== void 0, (events, data) => sendEvents(options.accessToken, options.conversions, events, data));
|
|
109
114
|
}
|
|
115
|
+
exports.linkedinConversions = linkedinConversions;
|
|
110
116
|
exports.sendEvents = sendEvents;
|
|
111
117
|
|
|
112
118
|
//# sourceMappingURL=linkedin-conversions-api.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"linkedin-conversions-api.cjs","names":["createHash","getFirst","isIPv4","linkedinFatId","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 { isIPv4 } from 'node:net';\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';\nimport { linkedinFatId } from './click-ids';\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\n/**\n * `conversionHappenedAt` must be \"within the past 90 days\", and one invalid record makes \"all\n * records fail\"; such an event is left out, with a minute's margin for the trip.\n */\nconst MAX_EVENT_AGE_MS = 90 * 24 * 60 * 60 * 1000 - 60 * 1000;\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 // LinkedIn takes the IP as is (it salts and hashes it itself), IPv4 only.\n // https://learn.microsoft.com/en-us/linkedin/marketing/integrations/ads-reporting/conversions-api\n if (data.ip_address && isIPv4(data.ip_address)) {\n userIds.push({ idType: 'PLAINTEXT_IP_ADDRESS', idValue: data.ip_address });\n }\n\n // The identifiers each event carries itself: the click id, and the Android advertising id.\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n const eventIds = (event: TrackEvent<any>): { idType: UserIdType; idValue: string }[] => {\n const ids: { idType: UserIdType; idValue: string }[] = [];\n const fatId = linkedinFatId(event.tags);\n if (fatId) ids.push({ idType: 'LINKEDIN_FIRST_PARTY_ADS_TRACKING_UUID', idValue: fatId });\n if (event.platform === 'android' && event.tags.advertising_id) {\n ids.push({ idType: 'GOOGLE_AID', idValue: event.tags.advertising_id });\n }\n return ids;\n };\n\n const dto: CreateMultipleLinkedinEventsDTO = {\n elements: events\n .filter((event) => eventNames.includes(event.name) && !IGNORED_EVENTS.includes(event.name))\n .filter((event) => Date.now() - Date.parse(event.created_at) <= MAX_EVENT_AGE_MS)\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: [...eventIds(event), ...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 // Retried although a POST: the platform deduplicates on the `eventId` each event carries.\n retries: 3,\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":";;;;;;;;;;;;;;;;;AAmFA,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;;;;;AAQvF,MAAM,mBAAmB;AAEzB,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,KAA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C,cAAAA,MAAAA,CAAM,kDAAkD;GAC7E,QAAQ;GAER,SAAS;GACT,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
|
+
{"version":3,"file":"linkedin-conversions-api.cjs","names":["createHash","getFirst","isIPv4","linkedinFatId","IGNORED_EVENTS","fetch","ConversionsApiError","conversionDestination"],"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 { isIPv4 } from 'node:net';\nimport { fetch } from '@shware/utils';\nimport { IGNORED_EVENTS } from '../third-parties/ignored-events';\nimport type {\n LinkedInAdsOptions,\n LinkedinConversionConfig,\n} from '../third-parties/linkedin-insight-tag';\nimport type { TrackEvent, TrackName, UserProvidedData } from '../track/types';\nimport { getFirst } from '../utils/field';\nimport { linkedinFatId } from './click-ids';\nimport { ConversionsApiError } from './conversions-api-error';\nimport { type ConversionDestination, conversionDestination } from './setup-conversions';\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\n/** The same event name → conversion id map `linkedInAds` takes in the browser. */\nexport type { LinkedinConversionConfig } from '../third-parties/linkedin-insight-tag';\n\n/**\n * `conversionHappenedAt` must be \"within the past 90 days\", and one invalid record makes \"all\n * records fail\"; such an event is left out, with a minute's margin for the trip.\n */\nconst MAX_EVENT_AGE_MS = 90 * 24 * 60 * 60 * 1000 - 60 * 1000;\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 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 // LinkedIn takes the IP as is (it salts and hashes it itself), IPv4 only.\n // https://learn.microsoft.com/en-us/linkedin/marketing/integrations/ads-reporting/conversions-api\n if (data.ip_address && isIPv4(data.ip_address)) {\n userIds.push({ idType: 'PLAINTEXT_IP_ADDRESS', idValue: data.ip_address });\n }\n\n // The identifiers each event carries itself: the click id, and the Android advertising id.\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n const eventIds = (event: TrackEvent<any>): { idType: UserIdType; idValue: string }[] => {\n const ids: { idType: UserIdType; idValue: string }[] = [];\n const fatId = linkedinFatId(event.tags);\n if (fatId) ids.push({ idType: 'LINKEDIN_FIRST_PARTY_ADS_TRACKING_UUID', idValue: fatId });\n if (event.platform === 'android' && event.tags.advertising_id) {\n ids.push({ idType: 'GOOGLE_AID', idValue: event.tags.advertising_id });\n }\n return ids;\n };\n\n const dto: CreateMultipleLinkedinEventsDTO = {\n elements: events\n .filter((event) => !IGNORED_EVENTS.includes(event.name))\n .filter((event) => Date.now() - Date.parse(event.created_at) <= MAX_EVENT_AGE_MS)\n .flatMap((event) => {\n const conversionId = config[event.name as TrackName];\n return conversionId === undefined ? [] : [{ event, conversionId }];\n })\n .map(({ event, conversionId }): CreateLinkedinEventDTO => ({\n eventId: event.id,\n conversion: `urn:lla:llaPartnerConversion:${conversionId}`,\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: [...eventIds(event), ...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 const response = await fetch('https://api.linkedin.com/rest/conversionEvents', {\n method: 'POST',\n // Retried although a POST: the platform deduplicates on the `eventId` each event carries.\n retries: 3,\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 throw new ConversionsApiError('linkedin', response.status, await response.text());\n}\n\n/** LinkedIn's Conversions API, sent the events in `conversions`, as `linkedInAds` is. */\nexport function linkedinConversions(\n options: Pick<LinkedInAdsOptions, 'conversions'> & { accessToken: string }\n): ConversionDestination {\n return conversionDestination(\n (name) => options.conversions[name as TrackName] !== undefined,\n (events, data) => sendEvents(options.accessToken, options.conversions, events, data)\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAyFA,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;;;;;AASvF,MAAM,mBAAmB;AAEzB,eAAsB,WACpB,aACA,QAEA,QACA,OAAyB,CAAC,GAC1B;CACA,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;CAIA,IAAI,KAAK,eAAA,GAAcC,SAAAA,OAAAA,CAAO,KAAK,UAAU,GAC3C,QAAQ,KAAK;EAAE,QAAQ;EAAwB,SAAS,KAAK;CAAW,CAAC;CAK3E,MAAM,YAAY,UAAsE;EACtF,MAAM,MAAiD,CAAC;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B;EACrB;EACA,MAAM,KAAK,UAAU,GAAG;CAC1B,CAAC;CAED,IAAI,SAAS,IAAI;CACjB,MAAM,IAAIC,qCAAAA,oBAAoB,YAAY,SAAS,QAAQ,MAAM,SAAS,KAAK,CAAC;AAClF;;AAGA,SAAgB,oBACd,SACuB;CACvB,OAAOC,iCAAAA,uBACJ,SAAS,QAAQ,YAAY,UAAuB,KAAA,IACpD,QAAQ,SAAS,WAAW,QAAQ,aAAa,QAAQ,aAAa,QAAQ,IAAI,CACrF;AACF"}
|
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
import { TrackEvent, UserProvidedData } from "../track/types.cjs";
|
|
2
|
+
import { ConversionDestination } from "./setup-conversions.cjs";
|
|
3
|
+
import { LinkedInAdsOptions, LinkedinConversionConfig } from "../third-parties/linkedin-insight-tag.cjs";
|
|
2
4
|
/**
|
|
3
5
|
* The identifier types LinkedIn matches on, as of version 202609. `ORACLE_MOAT_ID` used to be
|
|
4
6
|
* here and is no longer in the schema; the IP and Android ones are.
|
|
@@ -58,7 +60,10 @@ export interface CreateLinkedinEventDTO {
|
|
|
58
60
|
export interface CreateMultipleLinkedinEventsDTO {
|
|
59
61
|
elements: CreateLinkedinEventDTO[];
|
|
60
62
|
}
|
|
61
|
-
export type LinkedinConversionConfig = Record<Lowercase<string>, number>;
|
|
62
63
|
export declare function sendEvents(accessToken: string, config: LinkedinConversionConfig, events: TrackEvent<any>[], data?: UserProvidedData): Promise<void>;
|
|
63
|
-
|
|
64
|
+
/** LinkedIn's Conversions API, sent the events in `conversions`, as `linkedInAds` is. */
|
|
65
|
+
export declare function linkedinConversions(options: Pick<LinkedInAdsOptions, 'conversions'> & {
|
|
66
|
+
accessToken: string;
|
|
67
|
+
}): ConversionDestination;
|
|
68
|
+
export type { LinkedinConversionConfig };
|
|
64
69
|
//# sourceMappingURL=linkedin-conversions-api.d.cts.map
|
|
@@ -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":";;;;;;;KAsBK;iBAQY;;;;;;;;;EASf;;;;;EAMA;;EAGA;EACA;IAAmB;IAAsB;;EACzC;IACE;MAAW,QAAQ;MAAY;;;;;;;;IAO/B;MACE;MACA;MACA;MACA;MACA;;;;;;IAOF;;;;;IAMA;;;iBAIa;EACf,UAAU;;wBAqCU,WACpB,qBACA,QAAQ,0BAER,QAAQ,mBACR,OAAM,mBAAqB;;wBAwFb,oBACd,SAAS,KAAK;EAAuC;IACpD"}
|
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
import { TrackEvent, UserProvidedData } from "../track/types.mjs";
|
|
2
|
+
import { ConversionDestination } from "./setup-conversions.mjs";
|
|
3
|
+
import { LinkedInAdsOptions, LinkedinConversionConfig } from "../third-parties/linkedin-insight-tag.mjs";
|
|
2
4
|
/**
|
|
3
5
|
* The identifier types LinkedIn matches on, as of version 202609. `ORACLE_MOAT_ID` used to be
|
|
4
6
|
* here and is no longer in the schema; the IP and Android ones are.
|
|
@@ -58,7 +60,10 @@ export interface CreateLinkedinEventDTO {
|
|
|
58
60
|
export interface CreateMultipleLinkedinEventsDTO {
|
|
59
61
|
elements: CreateLinkedinEventDTO[];
|
|
60
62
|
}
|
|
61
|
-
export type LinkedinConversionConfig = Record<Lowercase<string>, number>;
|
|
62
63
|
export declare function sendEvents(accessToken: string, config: LinkedinConversionConfig, events: TrackEvent<any>[], data?: UserProvidedData): Promise<void>;
|
|
63
|
-
|
|
64
|
+
/** LinkedIn's Conversions API, sent the events in `conversions`, as `linkedInAds` is. */
|
|
65
|
+
export declare function linkedinConversions(options: Pick<LinkedInAdsOptions, 'conversions'> & {
|
|
66
|
+
accessToken: string;
|
|
67
|
+
}): ConversionDestination;
|
|
68
|
+
export type { LinkedinConversionConfig };
|
|
64
69
|
//# sourceMappingURL=linkedin-conversions-api.d.mts.map
|
|
@@ -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":";;;;;;;KAsBK;iBAQY;;;;;;;;;EASf;;;;;EAMA;;EAGA;EACA;IAAmB;IAAsB;;EACzC;IACE;MAAW,QAAQ;MAAY;;;;;;;;IAO/B;MACE;MACA;MACA;MACA;MACA;;;;;;IAOF;;;;;IAMA;;;iBAIa;EACf,UAAU;;wBAqCU,WACpB,qBACA,QAAQ,0BAER,QAAQ,mBACR,OAAM,mBAAqB;;wBAwFb,oBACd,SAAS,KAAK;EAAuC;IACpD"}
|
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import { IGNORED_EVENTS } from "../third-parties/ignored-events.mjs";
|
|
2
2
|
import { getFirst } from "../utils/field.mjs";
|
|
3
3
|
import { linkedinFatId } from "./click-ids.mjs";
|
|
4
|
+
import { ConversionsApiError } from "./conversions-api-error.mjs";
|
|
5
|
+
import { conversionDestination } from "./setup-conversions.mjs";
|
|
4
6
|
import { fetch } from "@shware/utils";
|
|
5
7
|
import { createHash } from "node:crypto";
|
|
6
8
|
import { isIPv4 } from "node:net";
|
|
@@ -37,7 +39,6 @@ const hashName = (name) => sha256(name.toLowerCase().replace(/[\s\p{P}]/gu, ""))
|
|
|
37
39
|
*/
|
|
38
40
|
const MAX_EVENT_AGE_MS = 777594e4;
|
|
39
41
|
async function sendEvents(accessToken, config, events, data = {}) {
|
|
40
|
-
const eventNames = Object.keys(config);
|
|
41
42
|
const address = getFirst(data.address);
|
|
42
43
|
const userIds = [];
|
|
43
44
|
const externalIds = data.user_id ? [data.user_id] : void 0;
|
|
@@ -70,9 +71,15 @@ async function sendEvents(accessToken, config, events, data = {}) {
|
|
|
70
71
|
});
|
|
71
72
|
return ids;
|
|
72
73
|
};
|
|
73
|
-
const dto = { elements: events.filter((event) =>
|
|
74
|
+
const dto = { elements: events.filter((event) => !IGNORED_EVENTS.includes(event.name)).filter((event) => Date.now() - Date.parse(event.created_at) <= MAX_EVENT_AGE_MS).flatMap((event) => {
|
|
75
|
+
const conversionId = config[event.name];
|
|
76
|
+
return conversionId === void 0 ? [] : [{
|
|
77
|
+
event,
|
|
78
|
+
conversionId
|
|
79
|
+
}];
|
|
80
|
+
}).map(({ event, conversionId }) => ({
|
|
74
81
|
eventId: event.id,
|
|
75
|
-
conversion: `urn:lla:llaPartnerConversion:${
|
|
82
|
+
conversion: `urn:lla:llaPartnerConversion:${conversionId}`,
|
|
76
83
|
conversionHappenedAt: new Date(event.created_at).getTime(),
|
|
77
84
|
conversionValue: {
|
|
78
85
|
currencyCode: event.properties?.currency?.toUpperCase() ?? "USD",
|
|
@@ -85,27 +92,25 @@ async function sendEvents(accessToken, config, events, data = {}) {
|
|
|
85
92
|
}
|
|
86
93
|
})).filter(({ user }) => user.userIds.length > 0 || !!user.userInfo || !!user.externalIds || !!user.lead) };
|
|
87
94
|
if (dto.elements.length === 0) return;
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
console.error("Failed to send LinkedIn conversion, network error:", error);
|
|
107
|
-
}
|
|
95
|
+
const response = await fetch("https://api.linkedin.com/rest/conversionEvents", {
|
|
96
|
+
method: "POST",
|
|
97
|
+
retries: 3,
|
|
98
|
+
headers: {
|
|
99
|
+
Authorization: `Bearer ${accessToken}`,
|
|
100
|
+
"Content-Type": "application/json",
|
|
101
|
+
"LinkedIn-Version": "202609",
|
|
102
|
+
"X-Restli-Protocol-Version": "2.0.0",
|
|
103
|
+
"X-RestLi-Method": "BATCH_CREATE"
|
|
104
|
+
},
|
|
105
|
+
body: JSON.stringify(dto)
|
|
106
|
+
});
|
|
107
|
+
if (response.ok) return;
|
|
108
|
+
throw new ConversionsApiError("linkedin", response.status, await response.text());
|
|
109
|
+
}
|
|
110
|
+
/** LinkedIn's Conversions API, sent the events in `conversions`, as `linkedInAds` is. */
|
|
111
|
+
function linkedinConversions(options) {
|
|
112
|
+
return conversionDestination((name) => options.conversions[name] !== void 0, (events, data) => sendEvents(options.accessToken, options.conversions, events, data));
|
|
108
113
|
}
|
|
109
|
-
export { sendEvents };
|
|
114
|
+
export { linkedinConversions, sendEvents };
|
|
110
115
|
|
|
111
116
|
//# sourceMappingURL=linkedin-conversions-api.mjs.map
|
|
@@ -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-2026-09\n */\nimport { createHash } from 'node:crypto';\nimport { isIPv4 } from 'node:net';\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';\nimport { linkedinFatId } from './click-ids';\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\n/**\n * `conversionHappenedAt` must be \"within the past 90 days\", and one invalid record makes \"all\n * records fail\"; such an event is left out, with a minute's margin for the trip.\n */\nconst MAX_EVENT_AGE_MS = 90 * 24 * 60 * 60 * 1000 - 60 * 1000;\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 // LinkedIn takes the IP as is (it salts and hashes it itself), IPv4 only.\n // https://learn.microsoft.com/en-us/linkedin/marketing/integrations/ads-reporting/conversions-api\n if (data.ip_address && isIPv4(data.ip_address)) {\n userIds.push({ idType: 'PLAINTEXT_IP_ADDRESS', idValue: data.ip_address });\n }\n\n // The identifiers each event carries itself: the click id, and the Android advertising id.\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n const eventIds = (event: TrackEvent<any>): { idType: UserIdType; idValue: string }[] => {\n const ids: { idType: UserIdType; idValue: string }[] = [];\n const fatId = linkedinFatId(event.tags);\n if (fatId) ids.push({ idType: 'LINKEDIN_FIRST_PARTY_ADS_TRACKING_UUID', idValue: fatId });\n if (event.platform === 'android' && event.tags.advertising_id) {\n ids.push({ idType: 'GOOGLE_AID', idValue: event.tags.advertising_id });\n }\n return ids;\n };\n\n const dto: CreateMultipleLinkedinEventsDTO = {\n elements: events\n .filter((event) => eventNames.includes(event.name) && !IGNORED_EVENTS.includes(event.name))\n .filter((event) => Date.now() - Date.parse(event.created_at) <= MAX_EVENT_AGE_MS)\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: [...eventIds(event), ...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 // Retried although a POST: the platform deduplicates on the `eventId` each event carries.\n retries: 3,\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":";;;;;;;;;;;;;;;;AAmFA,MAAM,UAAU,UAAkB,WAAW,QAAQ,CAAC,CAAC,OAAO,KAAK,CAAC,CAAC,OA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AI,CAAC,CAAC,CAC1F,QAAQ,UAAU,KAAK,IAAI,IAAI,KAAK,MAAM,MAAM,UAAU,KAAK,gBAAgB,CAAC,CAChF,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,CAAC,GAAG,SAAS,KAAK,GAAG,GAAG,OAAO;GACxC;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;GAER,SAAS;GACT,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
|
+
{"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 { isIPv4 } from 'node:net';\nimport { fetch } from '@shware/utils';\nimport { IGNORED_EVENTS } from '../third-parties/ignored-events';\nimport type {\n LinkedInAdsOptions,\n LinkedinConversionConfig,\n} from '../third-parties/linkedin-insight-tag';\nimport type { TrackEvent, TrackName, UserProvidedData } from '../track/types';\nimport { getFirst } from '../utils/field';\nimport { linkedinFatId } from './click-ids';\nimport { ConversionsApiError } from './conversions-api-error';\nimport { type ConversionDestination, conversionDestination } from './setup-conversions';\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\n/** The same event name → conversion id map `linkedInAds` takes in the browser. */\nexport type { LinkedinConversionConfig } from '../third-parties/linkedin-insight-tag';\n\n/**\n * `conversionHappenedAt` must be \"within the past 90 days\", and one invalid record makes \"all\n * records fail\"; such an event is left out, with a minute's margin for the trip.\n */\nconst MAX_EVENT_AGE_MS = 90 * 24 * 60 * 60 * 1000 - 60 * 1000;\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 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 // LinkedIn takes the IP as is (it salts and hashes it itself), IPv4 only.\n // https://learn.microsoft.com/en-us/linkedin/marketing/integrations/ads-reporting/conversions-api\n if (data.ip_address && isIPv4(data.ip_address)) {\n userIds.push({ idType: 'PLAINTEXT_IP_ADDRESS', idValue: data.ip_address });\n }\n\n // The identifiers each event carries itself: the click id, and the Android advertising id.\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n const eventIds = (event: TrackEvent<any>): { idType: UserIdType; idValue: string }[] => {\n const ids: { idType: UserIdType; idValue: string }[] = [];\n const fatId = linkedinFatId(event.tags);\n if (fatId) ids.push({ idType: 'LINKEDIN_FIRST_PARTY_ADS_TRACKING_UUID', idValue: fatId });\n if (event.platform === 'android' && event.tags.advertising_id) {\n ids.push({ idType: 'GOOGLE_AID', idValue: event.tags.advertising_id });\n }\n return ids;\n };\n\n const dto: CreateMultipleLinkedinEventsDTO = {\n elements: events\n .filter((event) => !IGNORED_EVENTS.includes(event.name))\n .filter((event) => Date.now() - Date.parse(event.created_at) <= MAX_EVENT_AGE_MS)\n .flatMap((event) => {\n const conversionId = config[event.name as TrackName];\n return conversionId === undefined ? [] : [{ event, conversionId }];\n })\n .map(({ event, conversionId }): CreateLinkedinEventDTO => ({\n eventId: event.id,\n conversion: `urn:lla:llaPartnerConversion:${conversionId}`,\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: [...eventIds(event), ...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 const response = await fetch('https://api.linkedin.com/rest/conversionEvents', {\n method: 'POST',\n // Retried although a POST: the platform deduplicates on the `eventId` each event carries.\n retries: 3,\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 throw new ConversionsApiError('linkedin', response.status, await response.text());\n}\n\n/** LinkedIn's Conversions API, sent the events in `conversions`, as `linkedInAds` is. */\nexport function linkedinConversions(\n options: Pick<LinkedInAdsOptions, 'conversions'> & { accessToken: string }\n): ConversionDestination {\n return conversionDestination(\n (name) => options.conversions[name as TrackName] !== undefined,\n (events, data) => sendEvents(options.accessToken, options.conversions, events, data)\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAyFA,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;;;;;AASvF,MAAM,mBAAmB;AAEzB,eAAsB,WACpB,aACA,QAEA,QACA,OAAyB,CAAC,GAC1B;CACA,MAAM,UAAU,SAAS,KAAK,OAAO;CACrC,MAAM,UAAqD,CAAC;CAC5D,MAAM,cAAiD,KAAK,UAAU,CAAC,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