From e625fe80af5ff9ed1de767428b1579f23853805f Mon Sep 17 00:00:00 2001 From: laurentdav <45101601+laurentdav@users.noreply.github.com> Date: Tue, 17 Nov 2026 23:12:36 +0100 Subject: [PATCH 1/2] feat(gravity): new server destination for the Gravity Conversions API Closes #766 Co-Authored-By: Claude Opus 5.5 --- .changeset/gravity-server-destination.md | 9 + package-lock.json | 22 ++ .../server/destinations/gravity/README.md | 64 ++++++ .../destinations/gravity/jest.config.mjs | 5 + .../server/destinations/gravity/package.json | 76 +++++++ .../gravity/src/__tests__/conformance.test.ts | 21 ++ .../gravity/src/__tests__/index.test.ts | 191 ++++++++++++++++ .../src/__tests__/stepExamples.test.ts | 68 ++++++ .../server/destinations/gravity/src/config.ts | 12 ++ .../server/destinations/gravity/src/dev.ts | 2 + .../destinations/gravity/src/examples/env.ts | 36 ++++ .../gravity/src/examples/index.ts | 3 + .../gravity/src/examples/minimal.ts | 10 + .../destinations/gravity/src/examples/step.ts | 175 +++++++++++++++ .../server/destinations/gravity/src/index.ts | 22 ++ .../server/destinations/gravity/src/push.ts | 203 ++++++++++++++++++ .../destinations/gravity/src/schemas/index.ts | 12 ++ .../gravity/src/schemas/mapping.ts | 9 + .../gravity/src/schemas/primitives.ts | 12 ++ .../gravity/src/schemas/settings.ts | 43 ++++ .../destinations/gravity/src/types/index.ts | 109 ++++++++++ .../server/destinations/gravity/tsconfig.json | 8 + .../destinations/gravity/tsup.config.ts | 14 ++ website/docs/destinations/index.mdx | 1 + website/docs/destinations/server/gravity.mdx | 87 ++++++++ website/package.json | 1 + website/sidebars.ts | 5 + 27 files changed, 1220 insertions(+) create mode 100644 .changeset/gravity-server-destination.md create mode 100644 packages/server/destinations/gravity/README.md create mode 100644 packages/server/destinations/gravity/jest.config.mjs create mode 100644 packages/server/destinations/gravity/package.json create mode 100644 packages/server/destinations/gravity/src/__tests__/conformance.test.ts create mode 100644 packages/server/destinations/gravity/src/__tests__/index.test.ts create mode 100644 packages/server/destinations/gravity/src/__tests__/stepExamples.test.ts create mode 100644 packages/server/destinations/gravity/src/config.ts create mode 100644 packages/server/destinations/gravity/src/dev.ts create mode 100644 packages/server/destinations/gravity/src/examples/env.ts create mode 100644 packages/server/destinations/gravity/src/examples/index.ts create mode 100644 packages/server/destinations/gravity/src/examples/minimal.ts create mode 100644 packages/server/destinations/gravity/src/examples/step.ts create mode 100644 packages/server/destinations/gravity/src/index.ts create mode 100644 packages/server/destinations/gravity/src/push.ts create mode 100644 packages/server/destinations/gravity/src/schemas/index.ts create mode 100644 packages/server/destinations/gravity/src/schemas/mapping.ts create mode 100644 packages/server/destinations/gravity/src/schemas/primitives.ts create mode 100644 packages/server/destinations/gravity/src/schemas/settings.ts create mode 100644 packages/server/destinations/gravity/src/types/index.ts create mode 100644 packages/server/destinations/gravity/tsconfig.json create mode 100644 packages/server/destinations/gravity/tsup.config.ts create mode 100644 website/docs/destinations/server/gravity.mdx diff --git a/.changeset/gravity-server-destination.md b/.changeset/gravity-server-destination.md new file mode 100644 index 000000000..65b40710e --- /dev/null +++ b/.changeset/gravity-server-destination.md @@ -0,0 +1,9 @@ +--- +'@walkeros/server-destination-gravity': minor +--- + +New Gravity server destination for the Conversions API of ads in AI assistants. +The mapped event name is the Gravity event (standard or custom); email and phone +are normalised and SHA-256 hashed, the Gravity click parameters are passed +through, and an `error` status inside a 200 answer fails the push. +`test_event_code` validates events without recording them. diff --git a/package-lock.json b/package-lock.json index 97459145a..ec3b5696f 100644 --- a/package-lock.json +++ b/package-lock.json @@ -19841,6 +19841,10 @@ "resolved": "packages/server/destinations/gcp", "link": true }, + "node_modules/@walkeros/server-destination-gravity": { + "resolved": "packages/server/destinations/gravity", + "link": true + }, "node_modules/@walkeros/server-destination-hubspot": { "resolved": "packages/server/destinations/hubspot", "link": true @@ -49446,6 +49450,24 @@ "@walkeros/collector": "4.9.0" } }, + "packages/server/destinations/gravity": { + "name": "@walkeros/server-destination-gravity", + "version": "4.9.0", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/elbwalker" + } + ], + "license": "MIT", + "dependencies": { + "@walkeros/core": "4.9.0", + "@walkeros/server-core": "4.9.0" + }, + "devDependencies": { + "@walkeros/collector": "4.9.0" + } + }, "packages/server/destinations/hubspot": { "name": "@walkeros/server-destination-hubspot", "version": "4.9.0", diff --git a/packages/server/destinations/gravity/README.md b/packages/server/destinations/gravity/README.md new file mode 100644 index 000000000..37d26758b --- /dev/null +++ b/packages/server/destinations/gravity/README.md @@ -0,0 +1,64 @@ +

+ + walkerOS + +

+ +# @walkeros/server-destination-gravity + +Server-side conversions to the [Gravity](https://trygravity.com) Conversions API +(ads in AI assistants), with hashed email and phone, the Gravity click +parameters and deduplication on the walkerOS event id. + +[Documentation](https://www.walkeros.io/docs/destinations/server/gravity) • +[NPM Package](https://www.npmjs.com/package/@walkeros/server-destination-gravity) +• +[Source Code](https://github.com/elbwalker/walkerOS/tree/main/packages/server/destinations/gravity) + +## Installation + +```bash +npm install @walkeros/server-destination-gravity +``` + +## Quick start + +```json +{ + "version": 4, + "flows": { + "default": { + "config": { "platform": "server" }, + "destinations": { + "gravity": { + "package": "@walkeros/server-destination-gravity", + "config": { + "settings": { + "apiKey": "$secret.GRAVITY_API_KEY" + } + } + } + } + } + } +} +``` + +This quick start sets no consent: add `consent: { marketing: true }` to `config` +before you go live, see the docs. + +## Documentation + +Full configuration, mapping, and examples live in the docs: +**https://www.walkeros.io/docs/destinations/server/gravity** + +## Contribute + +Feel free to contribute by submitting an +[issue](https://github.com/elbwalker/walkerOS/issues), starting a +[discussion](https://github.com/elbwalker/walkerOS/discussions), or getting in +[contact](https://calendly.com/elb-alexander/30min). + +## License + +MIT diff --git a/packages/server/destinations/gravity/jest.config.mjs b/packages/server/destinations/gravity/jest.config.mjs new file mode 100644 index 000000000..d1e06ddf6 --- /dev/null +++ b/packages/server/destinations/gravity/jest.config.mjs @@ -0,0 +1,5 @@ +import baseConfig from '@walkeros/config/jest'; + +const config = {}; + +export default { ...baseConfig, ...config }; diff --git a/packages/server/destinations/gravity/package.json b/packages/server/destinations/gravity/package.json new file mode 100644 index 000000000..a3f8d5c44 --- /dev/null +++ b/packages/server/destinations/gravity/package.json @@ -0,0 +1,76 @@ +{ + "name": "@walkeros/server-destination-gravity", + "description": "Gravity (ads in AI assistants) Conversions API server destination for walkerOS", + "version": "4.9.0", + "license": "MIT", + "exports": { + ".": { + "types": "./dist/index.d.ts", + "import": "./dist/index.mjs", + "require": "./dist/index.js" + }, + "./dev": { + "types": "./dist/dev.d.ts", + "import": "./dist/dev.mjs", + "require": "./dist/dev.js" + }, + "./walkerOS.json": "./dist/walkerOS.json", + "./examples": { + "types": "./dist/examples/index.d.ts", + "import": "./dist/examples/index.mjs", + "require": "./dist/examples/index.js" + } + }, + "files": [ + "dist/**", + "CHANGELOG.md" + ], + "scripts": { + "build": "tsup --silent", + "clean": "rm -rf .turbo && rm -rf dist", + "dev": "jest --watchAll --colors", + "typecheck": "tsc --noEmit", + "lint": "eslint \"**/*.ts*\"", + "test": "jest", + "update": "npx npm-check-updates -u && npm update" + }, + "dependencies": { + "@walkeros/core": "4.9.0", + "@walkeros/server-core": "4.9.0" + }, + "devDependencies": { + "@walkeros/collector": "4.9.0" + }, + "repository": { + "url": "git+https://github.com/elbwalker/walkerOS.git", + "directory": "packages/server/destinations/gravity" + }, + "author": "elbwalker ", + "homepage": "https://github.com/elbwalker/walkerOS#readme", + "bugs": { + "url": "https://github.com/elbwalker/walkerOS/issues" + }, + "walkerOS": { + "type": "destination", + "platform": [ + "server" + ], + "docs": "https://www.walkeros.io/docs/destinations/server/gravity" + }, + "keywords": [ + "walkerOS", + "walkerOS-destination", + "destination", + "server", + "gravity", + "ai-ads", + "conversions-api", + "analytics" + ], + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/elbwalker" + } + ] +} diff --git a/packages/server/destinations/gravity/src/__tests__/conformance.test.ts b/packages/server/destinations/gravity/src/__tests__/conformance.test.ts new file mode 100644 index 000000000..17fd885c1 --- /dev/null +++ b/packages/server/destinations/gravity/src/__tests__/conformance.test.ts @@ -0,0 +1,21 @@ +import path from 'path'; +import { conformance } from '@walkeros/collector/dev'; +import { destinationGravity } from '..'; +import { examples, schemas } from '../dev'; + +describe('gravity conformance', () => { + beforeEach(() => { + jest.useRealTimers(); + }); + + it('conforms', async () => { + await conformance('destination', destinationGravity, { + profile: 'http', + examples: examples.step, + schema: schemas.settings, + settings: examples.minimal.settings, + minimal: examples.minimal, + root: path.join(__dirname, '..', '..'), + }); + }); +}); diff --git a/packages/server/destinations/gravity/src/__tests__/index.test.ts b/packages/server/destinations/gravity/src/__tests__/index.test.ts new file mode 100644 index 000000000..69a7705da --- /dev/null +++ b/packages/server/destinations/gravity/src/__tests__/index.test.ts @@ -0,0 +1,191 @@ +import type { Collector, WalkerOS } from '@walkeros/core'; +import type { Settings } from '../types'; +import { + clone, + createIngest, + createMockContext, + createMockLogger, + getEvent, +} from '@walkeros/core'; +import { getHashServer } from '@walkeros/server-core'; +import { destinationGravity as destination } from '..'; +import { examples } from '../dev'; + +describe('Server Destination Gravity', () => { + const apiKey = 's3cr3t'; + const mockSendServer = jest.fn(); + const testEnv = clone(examples.env.push); + testEnv.sendServer = mockSendServer; + + const body = () => JSON.parse(mockSendServer.mock.calls[0][1]); + const conversion = () => body().data[0]; + + function event(props: Partial = {}): WalkerOS.Event { + return { + ...getEvent('order complete', { + id: 'ev-1', + timestamp: 1700000900500, + source: { + type: 'express', + platform: 'server', + url: 'https://shop.example.com/x', + }, + ...props, + }), + name: 'Purchase', + }; + } + + async function push( + walkerEvent: WalkerOS.Event, + data: Record = {}, + settings: Partial = {}, + extra: Record = {}, + ) { + return destination.push( + walkerEvent, + createMockContext({ + config: { settings: { apiKey, ...settings } }, + data, + env: testEnv, + ...extra, + }), + ); + } + + beforeEach(() => { + jest.clearAllMocks(); + mockSendServer.mockResolvedValue({ + data: { results: [{ status: 'success' }] }, + }); + }); + + test('init fails without apiKey', async () => { + await expect( + destination.init({ + config: {}, + collector: {} as Collector.Instance, + env: testEnv, + logger: createMockLogger(), + id: 'test-gravity', + }), + ).rejects.toThrow('Config settings apiKey missing'); + }); + + test('posts to the endpoint with the Bearer key', async () => { + await push(event()); + const [url, , options] = mockSendServer.mock.calls[0]; + expect(url).toBe('https://api.trygravity.com/gateway/events'); + expect(options.headers.Authorization).toBe('Bearer s3cr3t'); + }); + + test('event name, time in seconds, id, source', async () => { + await push(event()); + expect(conversion()).toEqual({ + event_name: 'Purchase', + event_time: 1700000900, + event_id: 'ev-1', + action_source: 'website', + event_source_url: 'https://shop.example.com/x', + user_data: {}, + }); + }); + + test('test_event_code, action_source and url settings', async () => { + await push( + event(), + {}, + { + test_event_code: 'TEST1', + action_source: 'app', + url: 'https://example.com/events', + }, + ); + expect(mockSendServer.mock.calls[0][0]).toBe('https://example.com/events'); + expect(body().test_event_code).toBe('TEST1'); + expect(conversion().action_source).toBe('app'); + }); + + test('email and phone normalised and hashed, digests kept', async () => { + const digest = await getHashServer('x@y.z'); + await push(event(), { + email: [' Jane@Example.com', digest.toUpperCase()], + phone: '+49 (151) 234', + external_id: ['a', 7], + }); + expect(conversion().user_data).toEqual({ + em: [await getHashServer('jane@example.com'), digest], + ph: [await getHashServer('49151234')], + external_id: ['a', '7'], + }); + }); + + test('every Gravity click parameter goes to user_data', async () => { + const clicks = { + grclid: '1', + grcpid: '2', + grpuid: '3', + gradid: '4', + grsig: '5', + graid: '6', + oppref: '7', + }; + await push(event(), clicks); + expect(conversion().user_data).toEqual(clicks); + }); + + test('client IP and user agent from ingest, mapped values win', async () => { + const ingest = { + ...createIngest('test'), + ip: '203.0.113.7', + userAgent: 'Mozilla/5.0 test', + }; + await push(event(), { ip_address: '10.0.0.1' }, {}, { ingest }); + expect(conversion().user_data).toEqual({ + client_ip_address: '10.0.0.1', + client_user_agent: 'Mozilla/5.0 test', + }); + mockSendServer.mockClear(); + await push(event(), {}, { ip: false, userAgent: false }, { ingest }); + expect(conversion().user_data).toEqual({}); + }); + + test('custom_data: currency defaults to USD, order id alone', async () => { + await push(event(), { value: '10.5' }); + expect(conversion().custom_data).toEqual({ value: 10.5, currency: 'USD' }); + mockSendServer.mockClear(); + await push(event(), { order_id: 'O1', currency: 'EUR' }); + expect(conversion().custom_data).toEqual({ order_id: 'O1' }); + }); + + test('client_context passes through', async () => { + await push(event(), { client_context: { page: 'x' } }); + expect(conversion().client_context).toEqual({ page: 'x' }); + }); + + test('invalid value or currency fails without a request', async () => { + await expect(push(event(), { value: -1 })).rejects.toMatchObject({ + code: 'mapping', + retryable: false, + }); + await expect(push(event(), { value: 1, currency: 'euro' })).rejects.toThrow( + '3-letter code', + ); + expect(mockSendServer).not.toHaveBeenCalled(); + }); + + test('an error status in a 200 answer fails the push', async () => { + mockSendServer.mockResolvedValue({ + data: { results: [{ status: 'error', error: 'invalid event' }] }, + }); + await expect(push(event())).rejects.toMatchObject({ + message: 'Gravity rejected the event: invalid event', + retryable: false, + }); + }); + + test('silent rule sends nothing', async () => { + await push(event(), {}, {}, { rule: { silent: true } }); + expect(mockSendServer).not.toHaveBeenCalled(); + }); +}); diff --git a/packages/server/destinations/gravity/src/__tests__/stepExamples.test.ts b/packages/server/destinations/gravity/src/__tests__/stepExamples.test.ts new file mode 100644 index 000000000..f7df7fda3 --- /dev/null +++ b/packages/server/destinations/gravity/src/__tests__/stepExamples.test.ts @@ -0,0 +1,68 @@ +import type { WalkerOS } from '@walkeros/core'; +import { startFlow } from '@walkeros/collector'; +import { clone, isObject } from '@walkeros/core'; +import { examples } from '../dev'; +import { expectSimulationResolves } from '@walkeros/core/dev'; + +type Captured = [callable: string, ...args: unknown[]]; + +/** + * Gravity destination invokes `env.sendServer(url, body, options)` + * exactly once per push. Stateless: no init-time calls to filter. + */ +describe('Step Examples', () => { + const mockSendServer = jest.fn(); + + beforeEach(() => { + jest.clearAllMocks(); + mockSendServer.mockResolvedValue({ + data: { results: [{ status: 'success' }] }, + }); + }); + + // Non-public examples (silent, failures) run in the conformance test. + const published = Object.entries(examples.step).filter( + ([, example]) => example.public !== false, + ); + + it.each(published)('%s', async (_name, example) => { + const event = example.in as WalkerOS.Event; + const mapping = example.mapping; + + const testEnv = clone(examples.env.push); + testEnv.sendServer = mockSendServer; + + const dest = jest.requireActual('../').default; + const { elb } = await startFlow(); + + const mappingConfig = mapping + ? { [event.entity]: { [event.action]: mapping } } + : undefined; + + await elb('walker destination', { + code: { ...dest, env: testEnv }, + config: { + settings: { apiKey: 's3cr3t' }, + mapping: mappingConfig, + }, + }); + + await elb(event); + + const captured: Captured[] = mockSendServer.mock.calls.map( + (args) => ['sendServer', ...args] as Captured, + ); + + expect(captured).toEqual(example.out); + }); +}); + +it('declares simulation paths that resolve', () => + expectSimulationResolves(examples.env)); + +it('gives every example event a timestamp in milliseconds', () => { + for (const example of Object.values(examples.step)) { + const timestamp = isObject(example.in) ? example.in.timestamp : undefined; + expect(timestamp).toBeGreaterThan(1e12); + } +}); diff --git a/packages/server/destinations/gravity/src/config.ts b/packages/server/destinations/gravity/src/config.ts new file mode 100644 index 000000000..86ffab040 --- /dev/null +++ b/packages/server/destinations/gravity/src/config.ts @@ -0,0 +1,12 @@ +import type { Config, Settings, PartialConfig } from './types'; +import { StepError } from '@walkeros/core'; + +export function getConfig(partialConfig: PartialConfig = {}): Config { + const settings: Partial = partialConfig.settings || {}; + const { apiKey } = settings; + + if (!apiKey) + throw new StepError('Config settings apiKey missing', { code: 'config' }); + + return { ...partialConfig, settings: { ...settings, apiKey } }; +} diff --git a/packages/server/destinations/gravity/src/dev.ts b/packages/server/destinations/gravity/src/dev.ts new file mode 100644 index 000000000..706f4127d --- /dev/null +++ b/packages/server/destinations/gravity/src/dev.ts @@ -0,0 +1,2 @@ +export * as schemas from './schemas'; +export * as examples from './examples'; diff --git a/packages/server/destinations/gravity/src/examples/env.ts b/packages/server/destinations/gravity/src/examples/env.ts new file mode 100644 index 000000000..ede02e290 --- /dev/null +++ b/packages/server/destinations/gravity/src/examples/env.ts @@ -0,0 +1,36 @@ +import type { SendDataValue, SendResponse } from '@walkeros/core'; +import type { SendServerOptions } from '@walkeros/server-core'; +import type { Env } from '../types'; + +/** + * Example environment configurations for Gravity Conversions API destination + * + * These environments provide standardized mock structures for testing + * and development without requiring actual HTTP requests. + */ + +type MockSendServer = ( + url: string, + data?: SendDataValue, + options?: SendServerOptions, +) => Promise; + +/** + * Mock sendServer function that simulates successful HTTP responses + */ +const mockSendServer: MockSendServer = async () => { + // Gravity answers 200 with a status per event + return { data: { results: [{ status: 'success' }] } }; +}; + +/** + * Standard mock environment for push operations + * + * Use this for testing Gravity conversion events without making + * actual HTTP requests to Gravity. + */ +export const push: Env = { + sendServer: mockSendServer, +}; + +export const simulation = ['sendServer']; diff --git a/packages/server/destinations/gravity/src/examples/index.ts b/packages/server/destinations/gravity/src/examples/index.ts new file mode 100644 index 000000000..181dfc860 --- /dev/null +++ b/packages/server/destinations/gravity/src/examples/index.ts @@ -0,0 +1,3 @@ +export * as env from './env'; +export * as step from './step'; +export { minimal } from './minimal'; diff --git a/packages/server/destinations/gravity/src/examples/minimal.ts b/packages/server/destinations/gravity/src/examples/minimal.ts new file mode 100644 index 000000000..ac074a437 --- /dev/null +++ b/packages/server/destinations/gravity/src/examples/minimal.ts @@ -0,0 +1,10 @@ +import type { Flow } from '@walkeros/core'; + +/** + * The settings Gravity needs to deliver: the API key, read from the + * environment. + */ +export const minimal: Flow.MinimalExample = { + settings: { apiKey: 's3cr3t' }, + secrets: { apiKey: 'GRAVITY_API_KEY' }, +}; diff --git a/packages/server/destinations/gravity/src/examples/step.ts b/packages/server/destinations/gravity/src/examples/step.ts new file mode 100644 index 000000000..9658c4d5b --- /dev/null +++ b/packages/server/destinations/gravity/src/examples/step.ts @@ -0,0 +1,175 @@ +import type { Flow } from '@walkeros/core'; +import { createEvent, getEvent } from '@walkeros/core'; + +/** + * Gravity Conversions API step examples. + * + * At push time, the destination calls + * `env.sendServer(url, JSON.stringify(body), options)` with + * `body = { test_event_code?, data: [conversion] }`. + * + * The test fixture pins `apiKey = 's3cr3t'` and the default url. + * + * Conversion keys are emitted in this order (insertion order matters for + * `JSON.stringify` string equality): event_name, event_time (seconds), + * event_id, action_source, event_source_url?, user_data, client_context?, + * custom_data?. `email` and `phone` are normalised and SHA-256 hashed into + * `em` and `ph`; Gravity click parameters go to `user_data` as they are. + */ +const URL = 'https://api.trygravity.com/gateway/events'; +const OPTIONS = { + headers: { + Authorization: 'Bearer s3cr3t', + 'Content-Type': 'application/json', + }, +}; + +// sha256('jane@example.com'), sha256('4915123456789') +const EMAIL_SHA256 = + '8c87b489ce35cf2e2f39f80e282cb2e804932a56a213983eeeb428407d43b52d'; +const PHONE_SHA256 = + 'c0f8f0bebbbac96451ee8d8def84a02ae9e34c877775437cb9d458328315afa7'; + +export const purchase: Flow.StepExample = { + title: 'Purchase', + description: + 'A completed order is sent to Gravity as a Purchase with value, currency, order id, the hashed email and the Gravity click id.', + in: getEvent('order complete', { + id: 'ev-1700000900', + timestamp: 1700000900000, + data: { id: 'ORD-300', total: 249.99, currency: 'eur' }, + user: { email: 'Jane@Example.com' }, + globals: { grclid: 'grc_7f3a' }, + source: { + type: 'express', + platform: 'server', + url: 'https://shop.example.com/checkout/complete', + }, + }), + mapping: { + name: 'Purchase', + data: { + map: { + email: 'user.email', + grclid: 'globals.grclid', + value: 'data.total', + currency: 'data.currency', + order_id: 'data.id', + }, + }, + }, + out: [ + [ + 'sendServer', + URL, + JSON.stringify({ + data: [ + { + event_name: 'Purchase', + event_time: 1700000900, + event_id: 'ev-1700000900', + action_source: 'website', + event_source_url: 'https://shop.example.com/checkout/complete', + user_data: { em: [EMAIL_SHA256], grclid: 'grc_7f3a' }, + custom_data: { + value: 249.99, + currency: 'EUR', + order_id: 'ORD-300', + }, + }, + ], + }), + OPTIONS, + ], + ], +}; + +export const lead: Flow.StepExample = { + title: 'Lead', + description: + 'A demo request is sent to Gravity as a Lead with the hashed phone and every Gravity click parameter stored on the landing page.', + in: createEvent({ + name: 'demo request', + id: 'ev-1700000901', + timestamp: 1700000901000, + data: { phone: '+49 151 23456789' }, + globals: { grclid: 'grc_1', grcpid: 'cmp_2', gradid: 'ad_3' }, + }), + mapping: { + name: 'Lead', + data: { + map: { + phone: 'data.phone', + grclid: 'globals.grclid', + grcpid: 'globals.grcpid', + gradid: 'globals.gradid', + }, + }, + }, + out: [ + [ + 'sendServer', + URL, + JSON.stringify({ + data: [ + { + event_name: 'Lead', + event_time: 1700000901, + event_id: 'ev-1700000901', + action_source: 'website', + user_data: { + ph: [PHONE_SHA256], + grclid: 'grc_1', + grcpid: 'cmp_2', + gradid: 'ad_3', + }, + }, + ], + }), + OPTIONS, + ], + ], +}; + +export const custom: Flow.StepExample = { + title: 'Custom event', + description: + 'Any mapped name that is not a Gravity standard event is sent as a custom event with that name.', + in: createEvent({ + name: 'demo booked', + id: 'ev-1700000902', + timestamp: 1700000902000, + data: { user: 'user-42' }, + }), + mapping: { + name: 'demo_booked', + data: { map: { external_id: 'data.user' } }, + }, + out: [ + [ + 'sendServer', + URL, + JSON.stringify({ + data: [ + { + event_name: 'demo_booked', + event_time: 1700000902, + event_id: 'ev-1700000902', + action_source: 'website', + user_data: { external_id: ['user-42'] }, + }, + ], + }), + OPTIONS, + ], + ], +}; + +/** A silent rule sends nothing to Gravity. */ +export const silentRule: Flow.StepExample = { + public: false, + description: 'A rule with silent: true sends no request to Gravity.', + in: getEvent('page view', { timestamp: 1700000990000 }), + mapping: { silent: true }, + out: [], +}; diff --git a/packages/server/destinations/gravity/src/index.ts b/packages/server/destinations/gravity/src/index.ts new file mode 100644 index 000000000..152385989 --- /dev/null +++ b/packages/server/destinations/gravity/src/index.ts @@ -0,0 +1,22 @@ +import type { Destination } from './types'; +import { getConfig } from './config'; +import { push } from './push'; + +// Types +export * as DestinationGravity from './types'; + +export const destinationGravity: Destination = { + type: 'gravity', + + config: {}, + + async init({ config: partialConfig }) { + return getConfig(partialConfig); + }, + + async push(event, context) { + return await push(event, context); + }, +}; + +export default destinationGravity; diff --git a/packages/server/destinations/gravity/src/push.ts b/packages/server/destinations/gravity/src/push.ts new file mode 100644 index 000000000..d102e7dba --- /dev/null +++ b/packages/server/destinations/gravity/src/push.ts @@ -0,0 +1,203 @@ +import type { + ConversionEvent, + CustomData, + PushFn, + RequestBody, + UserData, +} from './types'; +import { CLICK_KEYS } from './types'; +import type { + Collector, + Mapping as WalkerOSMapping, + WalkerOS, +} from '@walkeros/core'; +import { + createMappingRoot, + getMappingValue, + isObject, + StepError, +} from '@walkeros/core'; +import { getHashServer, sendServer } from '@walkeros/server-core'; + +const DEFAULT_URL = 'https://api.trygravity.com/gateway/events'; +const SHA256_HEX = /^[a-f0-9]{64}$/; + +const text = (value: unknown): string | undefined => { + if (typeof value === 'number' && Number.isFinite(value)) return String(value); + return typeof value === 'string' && value.trim() !== '' + ? value.trim() + : undefined; +}; + +function withoutUndefined(value: T): T { + return Object.fromEntries( + Object.entries(value).filter(([, item]) => item !== undefined), + ) as T; +} + +function toList(value: unknown): string[] { + const values = Array.isArray(value) ? value : [value]; + return values.map(text).filter((item): item is string => !!item); +} + +/** Normalised and SHA-256 hashed; an existing SHA-256 hex digest is kept. */ +async function hashList( + value: unknown, + normalize: (value: string) => string, +): Promise { + const hashed = await Promise.all( + toList(value).map(async (item) => { + const digest = item.toLowerCase(); + return SHA256_HEX.test(digest) ? digest : getHashServer(normalize(item)); + }), + ); + const unique = [...new Set(hashed)]; + return unique.length ? unique : undefined; +} + +function inputError(message: string): StepError { + return new StepError(message, { code: 'mapping', retryable: false }); +} + +async function buildEvent( + event: WalkerOS.Event, + data: Record, + actionSource: string, + client: { ip?: string; userAgent?: string }, +): Promise { + const value = + data.value === undefined || data.value === null || data.value === '' + ? undefined + : Number(data.value); + if (value !== undefined && (!Number.isFinite(value) || value < 0)) + throw inputError('Gravity value must be a positive number'); + const currency = text(data.currency)?.toUpperCase(); + if (currency && !/^[A-Z]{3}$/.test(currency)) + throw inputError('Gravity currency must be a 3-letter code'); + + const externalIds = toList(data.external_id); + const clicks = Object.fromEntries( + CLICK_KEYS.map((key) => [key, text(data[key])]), + ); + const userData: UserData = withoutUndefined({ + em: await hashList(data.email, (item) => item.trim().toLowerCase()), + ph: await hashList(data.phone, (item) => item.replace(/\D/g, '')), + external_id: externalIds.length ? externalIds : undefined, + client_ip_address: text(data.ip_address) ?? client.ip, + client_user_agent: text(data.user_agent) ?? client.userAgent, + ...clicks, + }); + + const orderId = text(data.order_id); + const customData: CustomData | undefined = + value !== undefined || orderId + ? withoutUndefined({ + value, + currency: value !== undefined ? (currency ?? 'USD') : undefined, + order_id: orderId, + }) + : undefined; + + return withoutUndefined({ + event_name: event.name, + event_time: Math.floor((Number(event.timestamp) || Date.now()) / 1000), + event_id: String(event.id).slice(0, 128), + action_source: actionSource, + event_source_url: text(data.source_url) ?? text(event.source?.url), + user_data: userData, + client_context: isObject(data.client_context) + ? data.client_context + : undefined, + custom_data: customData, + }); +} + +/** Gravity answers 200 with a status per event: `error` is a rejection. */ +function checkResponse(data: unknown): void { + if (!isObject(data) || !Array.isArray(data.results)) return; + const result: unknown = data.results[0]; + if (isObject(result) && result.status === 'error') + throw new StepError( + `Gravity rejected the event: ${String(result.error ?? '')}`, + { code: 'transport', retryable: false, body: data }, + ); +} + +// A silent rule has no Gravity call of its own: nothing to send. +export const push: PushFn = async function (event, context) { + if (!context.rule?.silent) await send(event, context); +}; + +const send: PushFn = async function ( + event, + { config, data, ingest, env, logger, collector }, +) { + const { + apiKey, + action_source = 'website', + test_event_code, + url = DEFAULT_URL, + ip, + userAgent, + } = config.settings ?? {}; + if (!apiKey) + throw new StepError('Gravity settings missing, init() not run', { + code: 'not-ready', + }); + + const root = createMappingRoot(ingest, event); + const client = { + ip: await resolveClient(ip, DEFAULT_IP, root, collector), + userAgent: await resolveClient( + userAgent, + DEFAULT_USER_AGENT, + root, + collector, + ), + }; + + const conversion = await buildEvent( + event, + isObject(data) ? data : {}, + action_source, + client, + ); + const body: RequestBody = withoutUndefined({ + test_event_code: text(test_event_code), + data: [conversion], + }); + + logger.debug('Calling Gravity Conversions API', { + endpoint: url, + method: 'POST', + eventName: conversion.event_name, + eventId: conversion.event_id, + }); + + const sendServerFn = env?.sendServer || sendServer; + const response = await sendServerFn(url, JSON.stringify(body), { + headers: { + Authorization: `Bearer ${apiKey}`, + 'Content-Type': 'application/json', + }, + }); + checkResponse(response?.data); +}; + +const DEFAULT_IP: WalkerOSMapping.Value = ['ingest.ip', 'event.user.ip']; +const DEFAULT_USER_AGENT: WalkerOSMapping.Value = [ + 'ingest.userAgent', + 'event.user.userAgent', +]; + +/** A client IP or user agent setting resolved to a non-empty string. */ +async function resolveClient( + setting: WalkerOSMapping.Value | false | undefined, + fallback: WalkerOSMapping.Value, + root: WalkerOSMapping.Root, + collector: Collector.Instance, +): Promise { + if (setting === false) return undefined; + const value = await getMappingValue(root, setting ?? fallback, { collector }); + return typeof value === 'string' && value !== '' ? value : undefined; +} diff --git a/packages/server/destinations/gravity/src/schemas/index.ts b/packages/server/destinations/gravity/src/schemas/index.ts new file mode 100644 index 000000000..9dcaf388d --- /dev/null +++ b/packages/server/destinations/gravity/src/schemas/index.ts @@ -0,0 +1,12 @@ +import { zodToSchema } from '@walkeros/core/dev'; +import { SettingsSchema } from './settings'; +import { MappingSchema } from './mapping'; + +export * from './primitives'; + +export { SettingsSchema, type Settings } from './settings'; +export { MappingSchema, type Mapping } from './mapping'; + +// JSON Schema +export const settings = zodToSchema(SettingsSchema); +export const mapping = zodToSchema(MappingSchema); diff --git a/packages/server/destinations/gravity/src/schemas/mapping.ts b/packages/server/destinations/gravity/src/schemas/mapping.ts new file mode 100644 index 000000000..85551dda9 --- /dev/null +++ b/packages/server/destinations/gravity/src/schemas/mapping.ts @@ -0,0 +1,9 @@ +import { z } from '@walkeros/core/dev'; + +/** + * Gravity Conversions API Mapping Schema + * The rule `name` is the Gravity event name; no other rule settings. + */ +export const MappingSchema = z.object({}); + +export type Mapping = z.infer; diff --git a/packages/server/destinations/gravity/src/schemas/primitives.ts b/packages/server/destinations/gravity/src/schemas/primitives.ts new file mode 100644 index 000000000..a602d310e --- /dev/null +++ b/packages/server/destinations/gravity/src/schemas/primitives.ts @@ -0,0 +1,12 @@ +import { z } from '@walkeros/core/dev'; + +/** Gravity standard event names; any other name is a custom event. */ +export const StandardEventSchema = z.enum([ + 'Purchase', + 'Lead', + 'CompleteRegistration', + 'Subscribe', + 'StartTrial', + 'InitiateCheckout', + 'Schedule', +]); diff --git a/packages/server/destinations/gravity/src/schemas/settings.ts b/packages/server/destinations/gravity/src/schemas/settings.ts new file mode 100644 index 000000000..f336cd5f4 --- /dev/null +++ b/packages/server/destinations/gravity/src/schemas/settings.ts @@ -0,0 +1,43 @@ +import { schemas, z } from '@walkeros/core/dev'; + +const InputSchema = z.union([ + schemas.MappingSchemas.ValueSchema, + z.literal(false), +]); + +export const SettingsSchema = z + .object({ + apiKey: z + .string() + .min(1) + .describe( + 'Gravity API key from Settings > Organization (owner or admin), sent as Bearer token (like grv_...)', + ), + action_source: z + .string() + .min(1) + .describe( + 'Where the conversion happened. Default: website (like website)', + ) + .optional(), + test_event_code: z + .string() + .describe( + 'Test event code from Events Manager > Set up tracking: events are validated, not recorded (like TEST123)', + ) + .optional(), + url: z + .string() + .url() + .describe('Endpoint (like https://api.trygravity.com/gateway/events)') + .optional(), + ip: InputSchema.describe( + 'Client IP, sent as user_data.client_ip_address. Resolves against { ingest, event }. Default: ["ingest.ip", "event.user.ip"]. false switches it off. A mapped ip_address wins.', + ).optional(), + userAgent: InputSchema.describe( + 'Client user agent, sent as user_data.client_user_agent. Resolves against { ingest, event }. Default: ["ingest.userAgent", "event.user.userAgent"]. false switches it off. A mapped user_agent wins.', + ).optional(), + }) + .strict(); + +export type Settings = z.infer; diff --git a/packages/server/destinations/gravity/src/types/index.ts b/packages/server/destinations/gravity/src/types/index.ts new file mode 100644 index 000000000..2299f9310 --- /dev/null +++ b/packages/server/destinations/gravity/src/types/index.ts @@ -0,0 +1,109 @@ +import type { + Mapping as WalkerOSMapping, + Destination as CoreDestination, +} from '@walkeros/core'; +import type { DestinationServer, sendServer } from '@walkeros/server-core'; + +export interface Settings { + /** Gravity API key (Settings > Organization), sent as Bearer token */ + apiKey: string; + /** Where the conversion happened. @default 'website' */ + action_source?: ActionSource; + /** Test event code from Events Manager: validated, not recorded */ + test_event_code?: string; + /** Endpoint. @default 'https://api.trygravity.com/gateway/events' */ + url?: string; + /** + * Client IP, sent as user_data.client_ip_address. Resolves against + * { ingest, event }. `false` switches it off. + * @default ['ingest.ip', 'event.user.ip'] + */ + ip?: WalkerOSMapping.Value | false; + /** + * Client user agent, sent as user_data.client_user_agent. Resolves + * against { ingest, event }. `false` switches it off. + * @default ['ingest.userAgent', 'event.user.userAgent'] + */ + userAgent?: WalkerOSMapping.Value | false; +} + +export type InitSettings = Partial; + +export interface Mapping {} + +export interface Env extends DestinationServer.Env { + sendServer?: typeof sendServer; +} + +export type Types = CoreDestination.Types; + +export interface Destination extends DestinationServer.Destination { + init: DestinationServer.InitFn; +} + +export type Config = { + settings: Settings; +} & DestinationServer.Config; + +export type InitFn = DestinationServer.InitFn; +export type PushFn = DestinationServer.PushFn; + +export type PartialConfig = DestinationServer.PartialConfig; + +export type PushEvents = DestinationServer.PushEvents; + +export type Rule = WalkerOSMapping.Rule; +export type Rules = WalkerOSMapping.Rules; + +// Gravity Conversions API types +// https://docs.trygravity.com/advertisers/server-conversions + +/** Where the conversion happened, like `website` (the default) */ +export type ActionSource = string; + +/** Gravity click parameters, stored on the landing page */ +export const CLICK_KEYS = [ + 'grclid', + 'grcpid', + 'grpuid', + 'gradid', + 'grsig', + 'graid', + 'oppref', +] as const; + +export type ClickKey = (typeof CLICK_KEYS)[number]; + +export type UserData = { + em?: string[]; + ph?: string[]; + external_id?: string[]; + client_ip_address?: string; + client_user_agent?: string; +} & Partial>; + +export interface CustomData { + value?: number; + currency?: string; + order_id?: string; +} + +export interface ConversionEvent { + event_name: string; + event_time: number; + event_id: string; + action_source: ActionSource; + event_source_url?: string; + user_data: UserData; + client_context?: Record; + custom_data?: CustomData; +} + +export interface RequestBody { + test_event_code?: string; + data: ConversionEvent[]; +} + +export interface ResponseBody { + results?: { status?: string; error?: string }[]; +} diff --git a/packages/server/destinations/gravity/tsconfig.json b/packages/server/destinations/gravity/tsconfig.json new file mode 100644 index 000000000..b1c75c589 --- /dev/null +++ b/packages/server/destinations/gravity/tsconfig.json @@ -0,0 +1,8 @@ +{ + "extends": "@walkeros/config/tsconfig/node.json", + "compilerOptions": { + "rootDir": "src" + }, + "include": ["src/**/*"], + "exclude": ["node_modules", "dist"] +} diff --git a/packages/server/destinations/gravity/tsup.config.ts b/packages/server/destinations/gravity/tsup.config.ts new file mode 100644 index 000000000..0f100c52d --- /dev/null +++ b/packages/server/destinations/gravity/tsup.config.ts @@ -0,0 +1,14 @@ +import { + defineConfig, + buildModules, + buildExamples, + buildDev, +} from '@walkeros/config/tsup'; + +export default defineConfig([ + buildModules({ + terserOptions: { mangle: false }, + }), + buildExamples(), + buildDev(), +]); diff --git a/website/docs/destinations/index.mdx b/website/docs/destinations/index.mdx index 4351459f1..cb218cf9b 100644 --- a/website/docs/destinations/index.mdx +++ b/website/docs/destinations/index.mdx @@ -100,6 +100,7 @@ destination batches answer `queued` until the flush. | Criteo | - | Criteo Events API | | Customer.io | - | Customer.io | | Google | Google Ads | Google Data Manager API | +| Gravity | - | Gravity Conversions API | | HubSpot | - | HubSpot | | Klaviyo | - | Klaviyo | | LinkedIn | LinkedIn Insight Tag | LinkedIn Conversions API | diff --git a/website/docs/destinations/server/gravity.mdx b/website/docs/destinations/server/gravity.mdx new file mode 100644 index 000000000..0c21e65b4 --- /dev/null +++ b/website/docs/destinations/server/gravity.mdx @@ -0,0 +1,87 @@ +--- +title: Gravity Conversions API +description: "Server-side conversions to Gravity, ads in AI assistants" +path: /docs/destinations/server/gravity +sidebar_position: 8 +package: '@walkeros/server-destination-gravity' +--- +import data from '@walkeros/server-destination-gravity/walkerOS.json'; +import Configuration from '@site/src/components/snippets/_configuration.mdx'; +import Quickstart from '@site/src/components/snippets/_quickstart.mdx'; + +import WhereThisFits from '@site/src/components/snippets/_where-this-fits.mdx'; + +# Gravity Conversions API + + + +Server-side conversions to the [Gravity Conversions API](https://docs.trygravity.com/advertisers/server-conversions), for ads shown in AI assistants. + +Gravity Conversions API is a server destination in the walkerOS flow:} + flowMap={{ + destinations: { default: { label: 'Destination', text: 'Gravity', highlight: true } }, + }} + post={<>Sends one event per request to `POST https://api.trygravity.com/gateway/events` with the API key as Bearer token, using raw HTTP (no SDK). Email and phone are normalised and SHA-256 hashed. Each event carries the walkerOS event id, which Gravity uses with the event name to deduplicate for 48 hours.} +/> + +## Installation + + + + + +## Event name + +The mapped name is sent as `event_name`: a Gravity standard event (`Purchase`, `Lead`, `CompleteRegistration`, `Subscribe`, `StartTrial`, `InitiateCheckout`, `Schedule`, …) or any custom name. + + + +## Mapped data + +| Field | Sent as | +|---|---| +| `email`, `phone` | `user_data.em`, `user_data.ph` (email trimmed and lowercased, phone digits only, then SHA-256; an existing SHA-256 hex digest is kept) | +| `external_id` | `user_data.external_id`, as it is | +| `grclid`, `grcpid`, `grpuid`, `gradid`, `grsig`, `graid`, `oppref` | `user_data`, as they are | +| `ip_address`, `user_agent` | `user_data.client_ip_address`, `user_data.client_user_agent` | +| `client_context` | `client_context` (from the Gravity pixel's `getCAPIData()`) | +| `value`, `currency`, `order_id` | `custom_data` (currency uppercased, `USD` when a value has none) | +| `source_url` | `event_source_url` (default: `event.source.url`) | + +Gravity attributes a conversion through its click parameters: store every one of them on the landing page and send them back with each conversion. + +## Client IP and user agent + +The destination sends the client IP and user agent by default. The `ip` and `userAgent` settings resolve against `{ ingest, event }` and default to `["ingest.ip", "event.user.ip"]` and `["ingest.userAgent", "event.user.userAgent"]` (see the `config.ingest` recipe on the [Express source](/docs/sources/server/express#ingest-metadata)). A mapped `ip_address` or `user_agent` wins. Set either setting to `false` to turn it off. + +## Consent + +The quickstart sets no `config.consent`, so Gravity receives every event, whatever consent the event carries. Add `consent: { marketing: true }` to `config`, next to `settings`, to send only events with marketing consent (see [Gate a destination with consent](/docs/guides/consent#gate-a-destination-with-consent)). + +## Failures + +- Gravity answers HTTP 200 with a status per event: an `error` status fails the push, not retried. +- A negative or non-numeric `value`, or a `currency` that is not a 3-letter code, fails with the code `mapping`, not retried, and nothing is sent. +- A response outside the 2xx range, a network error or no answer within 5 seconds fails with `transport` (with the HTTP status) or `timeout`; 429 and 5xx are retried. +- Without `apiKey` the destination does not start: every push answers `failed` with the code `config`. +- A rule with `silent: true` sends nothing. + +## Testing + +Set `test_event_code` to a code from Events Manager > Set up tracking: Gravity validates the events and does not record them. + +## Links + +- [Gravity server conversions](https://docs.trygravity.com/advertisers/server-conversions) diff --git a/website/package.json b/website/package.json index 9999364b6..a66e4c045 100644 --- a/website/package.json +++ b/website/package.json @@ -36,6 +36,7 @@ "@walkeros/server-destination-datamanager": "^4.9.0", "@walkeros/server-destination-file": "^4.9.0", "@walkeros/server-destination-gcp": "^4.9.0", + "@walkeros/server-destination-gravity": "^4.9.0", "@walkeros/server-destination-hubspot": "^4.9.0", "@walkeros/server-destination-kafka": "^4.9.0", "@walkeros/server-destination-klaviyo": "^4.9.0", diff --git a/website/sidebars.ts b/website/sidebars.ts index 5696f2b85..603a13324 100644 --- a/website/sidebars.ts +++ b/website/sidebars.ts @@ -429,6 +429,11 @@ const sidebars: SidebarsConfig = { id: 'destinations/server/datamanager', className: 'sidebar-badge-server', }, + { + type: 'doc', + id: 'destinations/server/gravity', + className: 'sidebar-badge-server', + }, { type: 'doc', id: 'destinations/server/hubspot', From e7261cca9ab5431f5a0da6cd3c6f7adb52175550 Mon Sep 17 00:00:00 2001 From: laurentdav <45101601+laurentdav@users.noreply.github.com> Date: Tue, 17 Nov 2026 23:22:48 +0100 Subject: [PATCH 2/2] fix(gravity): apply review findings from the sibling OpenAI Ads PR - phone values that normalise to nothing are dropped before hashing - client IP / user agent mappings get the event and the event's consent - docs: no promise of automatic retries Co-Authored-By: Claude Opus 5.5 --- .../gravity/src/__tests__/index.test.ts | 45 +++++++++++++++++++ .../server/destinations/gravity/src/push.ts | 19 ++++++-- website/docs/destinations/server/gravity.mdx | 6 +-- 3 files changed, 63 insertions(+), 7 deletions(-) diff --git a/packages/server/destinations/gravity/src/__tests__/index.test.ts b/packages/server/destinations/gravity/src/__tests__/index.test.ts index 69a7705da..48c1e54df 100644 --- a/packages/server/destinations/gravity/src/__tests__/index.test.ts +++ b/packages/server/destinations/gravity/src/__tests__/index.test.ts @@ -184,6 +184,51 @@ describe('Server Destination Gravity', () => { }); }); + test('a phone without digits is dropped', async () => { + await push(event(), { phone: '()' }); + expect(conversion().user_data).toEqual({}); + }); + + test('client fields follow the event consent, not the collector one', async () => { + const ingest = { ...createIngest('test'), ip: '203.0.113.7' }; + const consented = { key: 'ingest.ip', consent: { marketing: true } }; + await push( + event({ consent: {} }), + {}, + { ip: consented, userAgent: false }, + { ingest, collector: { consent: { marketing: true } } }, + ); + expect(conversion().user_data).toEqual({}); + + mockSendServer.mockClear(); + await push( + event({ consent: { marketing: true } }), + {}, + { ip: consented, userAgent: false }, + { ingest }, + ); + expect(conversion().user_data).toEqual({ + client_ip_address: '203.0.113.7', + }); + }); + + test('client field callbacks receive the event', async () => { + await push( + event({ user: { id: 'u1', userAgent: 'Mozilla/5.0 from event' } }), + {}, + { + ip: false, + userAgent: { + fn: (_: unknown, context: { event?: WalkerOS.DeepPartialEvent }) => + context.event?.user?.userAgent, + }, + }, + ); + expect(conversion().user_data).toEqual({ + client_user_agent: 'Mozilla/5.0 from event', + }); + }); + test('silent rule sends nothing', async () => { await push(event(), {}, {}, { rule: { silent: true } }); expect(mockSendServer).not.toHaveBeenCalled(); diff --git a/packages/server/destinations/gravity/src/push.ts b/packages/server/destinations/gravity/src/push.ts index d102e7dba..d5c0874c6 100644 --- a/packages/server/destinations/gravity/src/push.ts +++ b/packages/server/destinations/gravity/src/push.ts @@ -48,10 +48,13 @@ async function hashList( const hashed = await Promise.all( toList(value).map(async (item) => { const digest = item.toLowerCase(); - return SHA256_HEX.test(digest) ? digest : getHashServer(normalize(item)); + if (SHA256_HEX.test(digest)) return digest; + const normalized = normalize(item); + return normalized ? getHashServer(normalized) : undefined; }), ); - const unique = [...new Set(hashed)]; + // Values that normalise to nothing (a phone without digits) are dropped. + const unique = [...new Set(hashed.filter((item): item is string => !!item))]; return unique.length ? unique : undefined; } @@ -147,12 +150,13 @@ const send: PushFn = async function ( const root = createMappingRoot(ingest, event); const client = { - ip: await resolveClient(ip, DEFAULT_IP, root, collector), + ip: await resolveClient(ip, DEFAULT_IP, root, collector, event), userAgent: await resolveClient( userAgent, DEFAULT_USER_AGENT, root, collector, + event, ), }; @@ -196,8 +200,15 @@ async function resolveClient( fallback: WalkerOSMapping.Value, root: WalkerOSMapping.Root, collector: Collector.Instance, + event: WalkerOS.Event, ): Promise { if (setting === false) return undefined; - const value = await getMappingValue(root, setting ?? fallback, { collector }); + // Callbacks get the event, and the event's own consent (not the + // collector's) gates a consent-scoped mapping. + const value = await getMappingValue(root, setting ?? fallback, { + collector, + event, + consent: event.consent ?? {}, + }); return typeof value === 'string' && value !== '' ? value : undefined; } diff --git a/website/docs/destinations/server/gravity.mdx b/website/docs/destinations/server/gravity.mdx index 0c21e65b4..0a79450f9 100644 --- a/website/docs/destinations/server/gravity.mdx +++ b/website/docs/destinations/server/gravity.mdx @@ -72,9 +72,9 @@ The quickstart sets no `config.consent`, so Gravity receives every event, whatev ## Failures -- Gravity answers HTTP 200 with a status per event: an `error` status fails the push, not retried. -- A negative or non-numeric `value`, or a `currency` that is not a 3-letter code, fails with the code `mapping`, not retried, and nothing is sent. -- A response outside the 2xx range, a network error or no answer within 5 seconds fails with `transport` (with the HTTP status) or `timeout`; 429 and 5xx are retried. +- Gravity answers HTTP 200 with a status per event: an `error` status fails the push, marked not retryable. +- A negative or non-numeric `value`, or a `currency` that is not a 3-letter code, fails with the code `mapping`, marked not retryable, and nothing is sent. +- A response outside the 2xx range, a network error or no answer within 5 seconds fails with `transport` (with the HTTP status) or `timeout`, and the event goes to the dead-letter queue. 429 and 5xx are marked retryable, other 4xx not; nothing resends the event by itself. - Without `apiKey` the destination does not start: every push answers `failed` with the code `config`. - A rule with `silent: true` sends nothing.