diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml new file mode 100644 index 0000000..7017fea --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.yml @@ -0,0 +1,46 @@ +name: Bug report +description: Report a problem with the DATALYR Node SDK. +labels: [bug] +body: + - type: textarea + id: what-happened + attributes: + label: What happened + description: Describe the problem. Include the error message if there is one. + validations: + required: true + - type: textarea + id: expected + attributes: + label: What you expected + validations: + required: true + - type: textarea + id: steps + attributes: + label: Steps to reproduce + description: Give the smallest code sample that shows the problem. Remove API keys and personal data. + render: javascript + validations: + required: true + - type: input + id: sdk-version + attributes: + label: SDK version + placeholder: "1.3.4" + validations: + required: true + - type: input + id: environment + attributes: + label: Environment + description: Node version, operating system and hosting platform. + placeholder: "Node 22, Linux, AWS Lambda" + validations: + required: true + - type: textarea + id: logs + attributes: + label: Debug logs + description: Set `debug: true` and paste the output. Remove API keys and personal data. + render: text diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml new file mode 100644 index 0000000..9fc8d68 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -0,0 +1,8 @@ +blank_issues_enabled: false +contact_links: + - name: Documentation + url: https://docs.datalyr.com/sdk-reference/node + about: Read the Node SDK reference. + - name: DATALYR + url: https://datalyr.com + about: Ask other questions about DATALYR. diff --git a/.github/ISSUE_TEMPLATE/feature_request.yml b/.github/ISSUE_TEMPLATE/feature_request.yml new file mode 100644 index 0000000..c9a130d --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature_request.yml @@ -0,0 +1,23 @@ +name: Feature request +description: Suggest a change to the DATALYR Node SDK. +labels: [enhancement] +body: + - type: textarea + id: problem + attributes: + label: Problem + description: Describe what you want to do and what stops you now. + validations: + required: true + - type: textarea + id: proposal + attributes: + label: Proposed solution + description: Describe the change you want. + validations: + required: true + - type: textarea + id: alternatives + attributes: + label: Alternatives + description: Describe any workarounds you use now. diff --git a/.github/assets/banner-dark.png b/.github/assets/banner-dark.png new file mode 100644 index 0000000..5c3afd0 Binary files /dev/null and b/.github/assets/banner-dark.png differ diff --git a/.github/assets/banner-light.png b/.github/assets/banner-light.png new file mode 100644 index 0000000..6a4f580 Binary files /dev/null and b/.github/assets/banner-light.png differ diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md new file mode 100644 index 0000000..ffe448c --- /dev/null +++ b/.github/pull_request_template.md @@ -0,0 +1,13 @@ +## What changed + + + +## How you tested it + + + +## Checklist + +- [ ] `npm run build` and `npm test` pass. +- [ ] Public API changes are in `CHANGELOG.md` under `[Unreleased]`. +- [ ] No API keys, customer data or personal data are in the change. diff --git a/CHANGELOG.md b/CHANGELOG.md index f90a31a..bc33294 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -24,7 +24,7 @@ All notable changes to this project will be documented in this file. ## [1.3.3] - 2026-09-03 ### Added -- `externalIds` on `track()` options (person contract §6): `{ namespace: id }` declared identities, e.g. `{ stripe: 'cus_123' }`, sent top-level on the envelope. Ingest classifies them as declared namespaces so they join the customer journey; undeclared namespaces are reported as unjoined rather than minting a person. +- `externalIds` on `track()` options: `{ namespace: id }` declared identities, e.g. `{ stripe: 'cus_123' }`, sent top-level on the envelope. Ingest classifies them as declared namespaces so they join the customer journey; undeclared namespaces are reported as unjoined rather than minting a person. ### Fixed - The `SDK_VERSION` sent in `context.library.version` and the `User-Agent` was stuck at `1.3.1` through the 1.3.2 release; it now matches the package version. @@ -32,7 +32,7 @@ All notable changes to this project will be documented in this file. ## [1.3.2] - 2026-07-25 ### Changed -- **NODE-01: `engines.node` raised to `>=18.0.0`.** The SDK calls global `fetch` and +- **`engines.node` raised to `>=18.0.0`.** The SDK calls global `fetch` and `AbortController`; Node 16 and earlier provide neither and the SDK fails at the first send. `engines` nonetheless declared `>=14.17.0`, so npm installed it silently on runtimes that cannot run it and the failure surfaced at the first event instead of at @@ -49,9 +49,9 @@ All notable changes to this project will be documented in this file. ## [1.3.1] - 2026-07-12 ### Added -- **A3-25: `schema_version` envelope stamp.** Every event's context now carries +- **`schema_version` envelope stamp.** Every event's context now carries `schema_version: 1`, the first canonical envelope version shared across the SDK fleet, - so the ingest contract layer can key on one version marker. + so the server can key on one version marker. - **`eventId` on `TrackOptions` (webhook idempotency).** The ingest server de-duplicates on the event id (6h window), but `track()` always minted a fresh UUID — so at-least-once webhook redeliveries (Stripe, Shopify, …) were counted as new events, double-counting @@ -72,26 +72,26 @@ All notable changes to this project will be documented in this file. exceptions are swallowed and can never crash the SDK. ### Fixed -- **`close()` hung the process up to `closeTimeout` (~30s) after resolving (TR-09).** The +- **`close()` hung the process up to `closeTimeout` (~30s) after resolving.** The drain loop's `Promise.race` budget/pause timers were never cleared, so a won race left a live timer pinning the event loop — reintroducing the exact exit-hang the 1.3.0 unref work fixed. Timers are now canceled when their race settles (proven: process exits ~4ms after `close()` instead of ~8s). -- **`await flush()` did not guarantee a drain (TR-25).** If a flush was already in flight it +- **`await flush()` did not guarantee a drain.** If a flush was already in flight it returned that promise, which had snapshotted the queue **before** later events — so the serverless `track(); track(); await flush()` pattern stranded the second event. `flush()` now loops until the queue empties (or a pass delivers nothing against a down endpoint). -- **Invalid args threw out of a fire-and-forget promise (9.D.4).** `track({event:''})`, +- **Invalid args threw out of a fire-and-forget promise.** `track({event:''})`, `identify()`/`alias()`/`group()` with a missing required id used to `throw`, which — for an un-awaited call — surfaced as an `ERR_UNHANDLED_REJECTION` and crashed the host (exit 1). They now warn-and-drop (`onDrop('validation_error')`) and resolve. -- **A wrong API key black-holed everything silently (9.D.8).** A permanent 4xx (≠ 408/429) +- **A wrong API key black-holed everything silently.** A permanent 4xx (≠ 408/429) was re-queued and retried ~10 flush cycles per event before a generic drop. It is now dropped immediately (no retry/requeue), and `401`/`403` logs a one-time authentication failure. `408`/`429` are now correctly treated as **transient** (retried), not permanent. -- **`track()` after `close()` was silently dropped (9.D.3).** It now logs one loud error and +- **`track()` after `close()` was silently dropped.** It now logs one loud error and fires `onDrop('closed')`; `close()` is idempotent under repeat/concurrent calls. -- **Over-long `eventId` (B-4).** A pathological caller id became a pathological server Redis +- **Over-long `eventId`.** A pathological caller id became a pathological server-side key; ids over 256 chars are now collapsed to a deterministic hash (redeliveries of the same id still dedup). - **`page(userId, name)` left `page_url` blank server-side** — the pageview now falls back to diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..14b701b --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,25 @@ +# Contributing + +Thank you for helping to improve the DATALYR Node SDK. + +## Run the checks + +The CI workflow runs these commands on Node 22 and 24. Run them before you open a pull request. + +```bash +npm ci +npm run build +npm test +``` + +## Pull requests + +- Keep each pull request to one change. +- Add or update tests for a change in behavior. +- Add an entry to `CHANGELOG.md` under `[Unreleased]` for a change that users can see. +- Do not change the version number. The maintainers do this at release. +- Remove API keys, customer data and personal data from code, tests and logs. + +## Report a problem + +Use the [issue templates](https://github.com/datalyr/api/issues/new/choose). For a security problem, see [SECURITY.md](SECURITY.md). diff --git a/LICENSE b/LICENSE index f1b490a..d0718ae 100644 --- a/LICENSE +++ b/LICENSE @@ -1,6 +1,6 @@ MIT License -Copyright (c) 2024 Datalyr +Copyright (c) 2024-2026 DATALYR Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/README.md b/README.md index 8894b47..1eeef87 100644 --- a/README.md +++ b/README.md @@ -1,622 +1,85 @@ -# @datalyr/api + + + DATALYR Node SDK + -Server-side analytics and attribution SDK for Node.js. Track events, identify users, and -preserve attribution data from your backend. +

+ npm + CI + License: MIT + Docs +

-Version 1.3.1. Full reference: [Node.js SDK](https://docs.datalyr.com/sdk-reference/node). +# DATALYR Node SDK -## Requirements +Send events and revenue from your server to DATALYR and see which channel, campaign and ad drove every conversion. -| Item | Value | -| --- | --- | -| Package | `@datalyr/api` | -| Version | `1.3.1` | -| Runtime Node version | 18 or later | -| Runtime dependencies | None | -| Module formats | CommonJS and ESM | -| TypeScript types | Included | +- **Server-side truth.** Signups, purchases and webhooks are recorded where they happen, so ad blockers cannot hide them. +- **One customer, every touch.** Server events join the same person your website and app track. +- **No double counting.** Pass a webhook's own event ID and redeliveries count once. +- **Safe in production.** The SDK never throws on a bad event, retries failed sends and drains its queue on shutdown. -> **Run this SDK on Node 18 or later.** It calls global `fetch` and `AbortController`. -> Node 16 and earlier do not provide either, and the SDK fails at the first send. -> `engines.node` declares `>=18.0.0` as of **1.3.2**, so npm now warns you before you -> install it on a runtime that cannot run it. Published versions up to and including -> **1.3.1 declare `>=14.17.0` and install silently on Node 14–16**, where they fail at -> the first send rather than at install time. +## Install -## Installation +The SDK needs Node 18 or later. ```bash npm install @datalyr/api ``` +Find your server API key in DATALYR under **Settings → API**. The key starts with `dk_`. + ## Quick start ```javascript import { Datalyr } from '@datalyr/api'; -const datalyr = new Datalyr({ - apiKey: process.env.DATALYR_API_KEY, - debug: true, -}); +const datalyr = new Datalyr({ apiKey: process.env.DATALYR_API_KEY }); -// Track an event +// Track an action await datalyr.track({ event: 'signup_completed', userId: 'user_123', properties: { plan: 'pro' }, }); -// Identify a user +// Attach traits to your user await datalyr.identify('user_123', { email: 'user@example.com' }); -// Drain the queue at process shutdown -await datalyr.close(); -``` - -The constructor throws `Error('Datalyr API key is required')` when `apiKey` is missing. -That is the only throw in the SDK. Every other method resolves, including on invalid -input. A key that does not begin with `dk_` logs a warning and continues. - -The SDK reads no environment variable. Pass the key yourself. - -## Authentication - -| Header | Value | -| --- | --- | -| `X-API-Key` | Your write key from **Settings → API** | -| `Content-Type` | `application/json` | -| `User-Agent` | `@datalyr/api/1.3.1` | - -The SDK sends no workspace ID. The key alone selects the workspace. - -## Configuration - -The constructor accepts a `DatalyrConfig` object or an API key string. - -> **Use the object form when you want failure callbacks.** The string shorthand -> `new Datalyr('dk_...')` never assigns `onError` or `onDrop`, so delivery failures are -> invisible to your code. - -```javascript -const datalyr = new Datalyr({ - apiKey: process.env.DATALYR_API_KEY, - host: 'https://ingest.datalyr.com/track', - flushAt: 20, - flushInterval: 10000, - debug: false, - timeout: 10000, - retryLimit: 3, - maxQueueSize: 1000, - closeTimeout: 30000, - onError: (event, error) => console.error(event.event, error), - onDrop: (events, reason) => console.error(reason, events.length), -}); - -// String shorthand — every default applies, no failure callbacks -const datalyr = new Datalyr('dk_your_api_key'); -``` - -Every numeric option is clamped. A value outside its range becomes the nearest bound. - -| Option | Type | Default | Unit | Range | -| --- | --- | --- | --- | --- | -| `apiKey` | `string` | Required. Throws when missing. | — | — | -| `host` | `string` | `'https://ingest.datalyr.com/track'` | URL | — | -| `flushAt` | `number` | `20` | events | 1–100 | -| `flushInterval` | `number` | `10000` | milliseconds | 1000–3600000 | -| `timeout` | `number` | `10000` | milliseconds | 1000–60000 | -| `retryLimit` | `number` | `3` | retries | 0–10 | -| `maxQueueSize` | `number` | `1000` | events | 100–10000 | -| `closeTimeout` | `number` | `30000` | milliseconds | 1000–120000 | -| `debug` | `boolean` | `false` | — | — | -| `onError` | `(event: TrackEvent, error: Error) => void` | Unset | — | — | -| `onDrop` | `(events: TrackEvent[], reason: DropReason) => void` | Unset | — | — | - -`host` carries its own `/track` path. An override must include a full path. - -Every option above is read by the SDK. None is dead. - -## Complete method list - -| Method | Signature | -| --- | --- | -| `constructor` | `(config: DatalyrConfig \| string)` | -| `track` | `(options: TrackOptions) => Promise` | -| `track` | `(userId: string \| null, event: string, properties?: any) => Promise` — legacy form | -| `identify` | `(userId: string, traits?: any, anonymousId?: string) => Promise` | -| `alias` | `(newUserId: string, previousId?: string, anonymousId?: string) => Promise` | -| `page` | `(userId: string, name?: string, properties?: any, anonymousId?: string) => Promise` | -| `group` | `(userId: string, groupId: string, traits?: any, anonymousId?: string) => Promise` | -| `trackPurchase` | `(userId: string \| null, purchase: PurchaseProperties, opts?: { anonymousId?: string; eventId?: string; timestamp?: string \| Date \| number }) => Promise` | -| `flush` | `() => Promise` | -| `close` | `() => Promise` | -| `getAnonymousId` | `() => string` | - -## Identity - -> **Pass `userId`, `anonymousId`, or both on every call.** With neither, the SDK mints a -> fresh `anon_` for that one call. Every such call becomes a separate person with no -> journey. The SDK logs one warning the first time this happens. - -This SDK runs in a multi-user process, so it keeps no shared anonymous ID. Take the -anonymous ID from the browser: call `datalyr.getVisitorId()` in the Web SDK, send the -value to your server, and pass it back as `anonymousId`. - -```javascript -await datalyr.track({ - event: 'purchase', - userId: 'user_123', - anonymousId: session.visitorId, - properties: { value: 99.99, currency: 'USD' }, -}); - -await datalyr.identify('user_123', { email: 'user@example.com' }, session.visitorId); -``` - -`identify`, `alias`, `page`, and `group` all accept `anonymousId` as their last argument. - -### getAnonymousId() - -```javascript -const anonId = datalyr.getAnonymousId(); // 'anon_3d5cf66d-203f-4009-8bb0-f3714da152a4' -``` - -> **`getAnonymousId()` generates a new `anon_` on every call and stores nothing.** -> It is not a getter and it is not stable per instance. Never call it to look up an -> existing person. Persist the value in your own per-user store, then pass it back as -> `anonymousId`. - -## Track an event - -`track()` has two call signatures. - -```javascript -// Object form (TrackOptions) -await datalyr.track({ - event: 'purchase', // Required - userId: 'user_123', // Optional - anonymousId: 'anon_from_browser', // Optional - eventId: 'evt_1Nxxxxx', // Optional — idempotency key - timestamp: 1751373296, // Optional — ISO string, Date, or epoch - properties: { - value: 99.99, - currency: 'USD', - }, -}); - -// Legacy form -await datalyr.track('user_123', 'purchase', { value: 99.99, currency: 'USD' }); - -// Pass null as userId for an event with no known user -await datalyr.track(null, 'page_loaded', { url: '/pricing' }); -``` - -An empty or non-string event name logs a warning, calls `onDrop` with -`validation_error`, and resolves. It never throws. - -### What goes on the wire - -The SDK posts one event object per request. There is no envelope and no `events` array. - -```json -{ - "userId": "user_123", - "anonymousId": "anon_9f2c1b40-1c2e-4d55-9a0b-6a4f7f1d2e33", - "eventId": "evt_1Nxxxxx", - "event": "purchase", - "properties": { - "value": 99.99, - "currency": "USD", - "anonymous_id": "anon_9f2c1b40-1c2e-4d55-9a0b-6a4f7f1d2e33" - }, - "context": { - "library": "@datalyr/api", - "version": "1.3.1", - "source": "api", - "schema_version": 1 - }, - "timestamp": "2026-07-25T12:00:00.000Z" -} -``` - -| Wire field | Value | -| --- | --- | -| `userId` | Your ID. camelCase. | -| `anonymousId` | The browser `visitor_id`. camelCase. | -| `properties.anonymous_id` | The same value, in snake_case. The SDK adds it to every event. | -| `context` | Always these four keys. A `context` you pass is overwritten. | -| `timestamp` | Your event time normalized to ISO 8601, or the enqueue time. | - -This SDK sends no `distinct_id` and no `session_id`. It has no session concept. - -### eventId — idempotent delivery - -Stripe, Shopify, and every other webhook source deliver at-least-once. Without an -`eventId`, each `track()` call generates a fresh UUID, so a redelivery counts as a new -event and double-counts revenue. - -Pass the source system's event ID as `eventId`. The ingest server de-duplicates on that -key for **7 days** by default. - -```javascript -await datalyr.track({ - event: 'purchase', - userId: session.client_reference_id, - eventId: stripeEvent.id, // same ID on redelivery → counted once - timestamp: stripeEvent.created, // when it happened, not when the retry arrived - properties: { value: session.amount_total / 100, currency: session.currency }, -}); -``` - -`eventId` must be a non-empty string. Any other value is ignored, and the SDK uses a -random UUID with a debug-mode warning. An `eventId` over 256 characters becomes its first -191 characters, a hyphen, and a SHA-256 hex digest of the original. That collapse is -deterministic, so redeliveries still dedupe. - -### timestamp - -`timestamp` accepts an ISO 8601 string, a `Date`, or a number. A number below `1e12` is -read as epoch **seconds**. Stripe's `event.created` is seconds. A larger number is read as -milliseconds. An omitted or invalid value falls back to the current time. - -Pass `timestamp` on delayed webhook replays so the event lands on the day it happened. - -## Events the SDK sends for you - -These event names are reserved. Never send one through `track()` yourself. - -| Method | Wire event name | -| --- | --- | -| `identify()` | `$identify` | -| `alias()` | `$alias` | -| `page()` | `$pageview` | -| `group()` | `$group` | -| `trackPurchase()` | `purchase` | - -### identify() - -```javascript -await datalyr.identify('user_123', { - email: 'user@example.com', - name: 'Jane Doe', - plan: 'premium', -}, session.visitorId); -``` - -Traits are sent flat inside `properties`. - -### page() - -```javascript -await datalyr.page('user_123', 'Pricing', { - url: 'https://example.com/pricing', - referrer: 'https://google.com', -}, session.visitorId); -``` - -Ingest derives `page_url` from `properties.url` only. When you pass no `url`, the SDK -copies `name` into `url` so the pageview stays addressable. Pass a real URL. - -### alias() - -```javascript -// Link a new ID to a fresh anonymous ID -await datalyr.alias('new_user_456'); - -// Link a new ID to a known previous ID -await datalyr.alias('new_user_456', 'old_user_123', session.visitorId); -``` - -When you omit `previousId`, the SDK uses the resolved anonymous ID for that call. +// Record a conversion with its value +await datalyr.trackPurchase('user_123', { value: 49.0, currency: 'USD' }); -### group() - -```javascript -await datalyr.group('user_123', 'company_456', { - name: 'Acme Corp', - industry: 'Technology', - employees: 50, -}, session.visitorId); -``` - -> **Do not use `group()` for B2B account rollups.** It records a plain `$group` event. -> Datalyr builds no account or group association from it. The method exists for API -> compatibility only. - -### trackPurchase() - -`trackPurchase()` stamps the canonical `value` field and uppercases `currency`, which -defaults to `USD`. `opts` forwards `anonymousId`, `eventId`, and `timestamp`. - -```javascript -await datalyr.trackPurchase('user_123', - { value: 49.99, currency: 'usd', plan: 'pro' }, - { eventId: stripeEvent.id, timestamp: stripeEvent.created, anonymousId: session.visitorId }); -``` - -`PurchaseProperties` requires a finite `value: number`. A `NaN`, an `Infinity`, or a -non-number logs a warning, calls `onDrop` with `validation_error`, and sends nothing. - -> **Put the amount in `value` when you use plain `track()` for revenue.** The ingest -> revenue pipeline reads `value ?? revenue ?? amount`, in that order. An amount under any -> other key is counted as \$0. - -## Flush and shut down - -```javascript -await datalyr.flush(); // between invocations of a reused instance -await datalyr.close(); // once, at process shutdown -``` - -### flush() - -`flush()` drains the whole queue and resolves once every event is sent, or once a pass -delivers nothing against a down endpoint. It loops, so events enqueued during a flush are -also sent. When a drain is already running, `flush()` awaits that drain instead of -starting a second one. That includes a drain started by reaching `flushAt`, even though -the queue is already empty by then. Before 1.3.4, `flush()` returned at once in that case -with the sends still in flight. - -Use `flush()` in serverless handlers, where the instance can freeze the moment you return. - -```javascript -// AWS Lambda / Cloud Functions — flush per invocation, never close() -export async function handler(event) { - await datalyr.track({ event: 'api_call', userId: event.userId }); - await datalyr.flush(); - return { ok: true }; -} -``` - -### close() - -`close()` stops the flush timer, then drains the queue, and waits for any send already in -flight, until both are done or `closeTimeout` expires. It is terminal and idempotent: -repeat and concurrent calls share one drain. - -> **Call `close()` only at process shutdown.** A `track()` call after `close()` is dropped -> with reason `closed`, and the SDK logs one loud error. - -```javascript -process.on('SIGTERM', async () => { - await datalyr.close(); - process.exit(0); -}); -``` - -Events still queued when the budget expires go to `onDrop(events, 'close_timeout')`. A -send still running at that moment keeps going in the background, so its result arrives -after `close()` has returned: it is delivered, or `onDrop` fires for it then -(`close_timeout` for a retryable failure, `permanent_client_error` for a 4xx). - -The SDK also registers a `beforeExit` hook that calls `flush()` best-effort. That hook -does not replace `await close()`. - -## Delivery hooks - -Pass `onError` and `onDrop` in the config to see delivery problems. - -```javascript -const datalyr = new Datalyr({ - apiKey: process.env.DATALYR_API_KEY, - onError: (event, error) => log.warn('datalyr send failed', { event: event.event, error }), - onDrop: (events, reason) => deadLetter.saveAll(events, reason), -}); -``` - -`onError` fires on every send failure, before any retry, requeue, or drop decision. -`onDrop` fires when events are dropped permanently. - -| `reason` | Cause | -| --- | --- | -| `validation_error` | A missing event name, `userId`, `newUserId`, or `groupId`, or a non-finite purchase `value` | -| `queue_overflow` | The queue reached `maxQueueSize`. The oldest event was evicted. | -| `permanent_client_error` | A `4xx` other than `408` or `429` | -| `max_flush_attempts` | 10 failed flush cycles for one event | -| `close_timeout` | `close()` ran out of time | -| `closed` | `track()` ran after `close()` | - -An exception thrown inside your hook is swallowed. A hook can never crash the SDK. - -## Delivery, retries, and limits - -The SDK never batches. It sends one HTTP request per event, with up to 10 requests in -flight at once. - -| Limit | Value | -| --- | --- | -| Auto-flush trigger | `flushAt` queued events, default 20 | -| Flush timer | `flushInterval`, default 10,000 ms | -| HTTP concurrency | 10 requests in parallel, one event each | -| Requests per event | One | -| Retries per send | `retryLimit`, default 3 | -| Retry backoff | `min(2^n × 1000, 10000)` ms, multiplied by `0.5 + random()/2` | -| Request timeout | `timeout`, default 10,000 ms, through `AbortController` | -| Queue | `maxQueueSize`, default 1000. The oldest event is dropped first. | -| Failed flush cycles per event | 10, then the event is dropped | -| Drain passes per flush | 12 | -| `close()` budget | `closeTimeout`, default 30,000 ms | -| `eventId` length | 256 characters | -| Server-side dedupe window | 7 days | - -### How failed requests behave - -| Response | Behavior | -| --- | --- | -| `2xx` | Success. | -| `408`, `429`, any `5xx` | Retried with jittered exponential backoff, up to `retryLimit`. | -| `401`, `403` | Dropped. The SDK logs an authentication failure once. | -| Other `4xx` | Dropped immediately. Never retried. | -| Network, DNS, TLS, abort | Retried like a `5xx`. | - -An event that exhausts its retries returns to the front of the queue. After 10 failed -flush cycles the SDK drops it, so one bad event cannot block the queue. - -## Attribution preservation - -Pass the browser's `visitor_id` as `anonymousId` to link a server-side event to the web -session that produced it. - -```javascript -await datalyr.track({ - event: 'purchase', - userId: 'user_123', - anonymousId: req.body.visitor_id, // from datalyr.getVisitorId() in the Web SDK - properties: { value: 99.99, currency: 'USD' }, -}); -``` - -The link carries the UTM parameters, click IDs, referrer, landing page, and journey the -Web SDK captured. The Web SDK captures these 15 click IDs: `fbclid`, `gclid`, `gbraid`, -`wbraid`, `ttclid`, `msclkid`, `twclid`, `li_fat_id`, `sclid`, `dclid`, `epik`, -`rdt_cid`, `obclid`, `irclid`, `ko_click_id`. - -## Framework examples - -### Express - -```javascript -import express from 'express'; -import { Datalyr } from '@datalyr/api'; - -const app = express(); -const datalyr = new Datalyr({ apiKey: process.env.DATALYR_API_KEY }); - -app.post('/api/purchase', async (req, res) => { - const { items, visitor_id } = req.body; - - await datalyr.track({ - event: 'purchase', - userId: req.user?.id, - anonymousId: visitor_id, - properties: { - value: calculateTotal(items), - currency: 'USD', - item_count: items.length, - }, - }); - - res.json({ success: true }); -}); - -process.on('SIGTERM', async () => { - await datalyr.close(); - process.exit(0); -}); -``` - -### Stripe webhooks - -Stripe delivers webhooks at-least-once. Pass `event.id` as `eventId` so redeliveries -dedupe. Pass `event.created` as `timestamp` so replays land on the right day. - -```javascript -import express from 'express'; -import Stripe from 'stripe'; -import { Datalyr } from '@datalyr/api'; - -const app = express(); -const datalyr = new Datalyr({ apiKey: process.env.DATALYR_API_KEY }); -const stripe = new Stripe(process.env.STRIPE_SECRET_KEY); - -app.post('/webhooks/stripe', async (req, res) => { - const sig = req.headers['stripe-signature']; - const event = stripe.webhooks.constructEvent(req.body, sig, process.env.STRIPE_WEBHOOK_SECRET); - - switch (event.type) { - case 'checkout.session.completed': { - const session = event.data.object; - await datalyr.track({ - event: 'purchase', - userId: session.client_reference_id, - anonymousId: session.metadata?.visitor_id, - eventId: event.id, - timestamp: event.created, - properties: { - value: session.amount_total / 100, - currency: session.currency, - stripe_session_id: session.id, - }, - }); - break; - } - - case 'customer.subscription.created': { - const subscription = event.data.object; - await datalyr.track({ - event: 'subscription_started', - userId: subscription.metadata.userId, - anonymousId: subscription.metadata.visitor_id, - eventId: event.id, - timestamp: event.created, - properties: { - plan: subscription.items.data[0].price.nickname, - value: subscription.items.data[0].price.unit_amount / 100, - currency: subscription.currency, - interval: subscription.items.data[0].price.recurring.interval, - }, - }); - break; - } - } - - res.json({ received: true }); -}); +// Before the process exits, send all queued events +await datalyr.close(); ``` -`session.metadata.visitor_id` comes from `datalyr.getStripeMetadata()` in the Web SDK. - -## TypeScript +Keep the API key on your server. Do not put it in browser or app code. -Type definitions ship with the package. +## Check it works -```typescript -import { Datalyr, DatalyrConfig, TrackOptions, TrackEvent } from '@datalyr/api'; +1. Run the quick start with your API key. +2. In DATALYR, open **Events**. +3. Confirm that a `signup_completed` event arrives within 30 seconds. -const config: DatalyrConfig = { - apiKey: process.env.DATALYR_API_KEY!, - debug: true, -}; - -const datalyr = new Datalyr(config); - -const options: TrackOptions = { - event: 'purchase', - userId: 'user_123', - anonymousId: 'anon_from_browser', - eventId: 'evt_1Nxxxxx', - timestamp: '2026-07-01T12:00:00Z', - properties: { - value: 99.99, - currency: 'USD', - }, -}; - -await datalyr.track(options); -``` +If no event arrives, add `debug: true` to the constructor. Then read the process logs. -## Verify the install +## Set up with an AI agent -1. Send one event with a `userId` you recognize. -2. Open **Events** in Datalyr. -3. Confirm the event arrives within 30 seconds. +Your AI agent can install the SDK for you. Connect the agent to the DATALYR MCP server at `https://mcp.datalyr.com/mcp`. Then ask it to install server-side tracking. See [DATALYR MCP](https://docs.datalyr.com/datalyr-mcp). -When nothing arrives, add an `onDrop` callback and log the reason. +## Documentation -## Troubleshooting +- [Node SDK reference](https://docs.datalyr.com/sdk-reference/node): every method, option and event +- [Examples](examples/): Express, Stripe webhooks and a basic script +- [Changelog](CHANGELOG.md) +- Other SDKs: [Web](https://github.com/datalyr/web) · [React Native](https://github.com/datalyr/react-native) · [iOS (Swift)](https://github.com/datalyr/swift) -| Symptom | Cause | Fix | -| --- | --- | --- | -| No events, `onDrop` reports `permanent_client_error` | Wrong API key, or a malformed payload | Confirm the key starts with `dk_` and matches **Settings → API** | -| No events, no `onDrop` call | The process exited before the queue drained | Call `await datalyr.flush()` before returning, or `await datalyr.close()` at shutdown | -| `onDrop` reports `closed` | `track()` ran after `close()` | Use `flush()` per invocation. Reserve `close()` for shutdown. | -| `onDrop` reports `queue_overflow` | Production volume exceeds `maxQueueSize` | Raise `maxQueueSize`, or lower `flushAt` to flush sooner | -| Revenue reports \$0 | The amount is not in `value` | Use `trackPurchase()`, or put the amount in `properties.value` | -| Every server event is a separate person | Calls carry neither `userId` nor `anonymousId` | Pass the browser `visitor_id` as `anonymousId` | -| `fetch is not defined` at send time | Node 16 or earlier | Upgrade to Node 18 or later | +## Support -Set `debug: true` to log every send and every error to the console. +- Bugs and feature requests: [open an issue](https://github.com/datalyr/api/issues/new/choose) +- Security reports: see [SECURITY.md](SECURITY.md) +- Other questions: [datalyr.com](https://datalyr.com) ## License -MIT +MIT. See [LICENSE](LICENSE). diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000..010e689 --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,17 @@ +# Security policy + +## Report a vulnerability + +Do not open a public issue for a security problem. + +Report it privately through GitHub: + +1. Open the [Security tab](https://github.com/datalyr/api/security) of this repository. +2. Select **Report a vulnerability**. +3. Describe the problem, the affected versions and the steps to reproduce it. + +We reply to the report in the advisory. We publish a fix and an advisory when the problem is resolved. + +## Supported versions + +We fix security problems in the latest published version of `@datalyr/api`. diff --git a/examples/README.md b/examples/README.md new file mode 100644 index 0000000..3c20c65 --- /dev/null +++ b/examples/README.md @@ -0,0 +1,23 @@ +# Examples + +Runnable examples for the DATALYR Node SDK. Each one reads your API key from `DATALYR_API_KEY`. + +| File | Shows | +| --- | --- | +| [basic.js](basic.js) | Track, identify, record a purchase and close the client | +| [express.js](express.js) | Track requests and signups in an Express app; close on shutdown | +| [stripe-webhook.js](stripe-webhook.js) | Record Stripe payments with `eventId` and `timestamp`, so redeliveries count once | + +Install the SDK and the example's own dependencies first: + +```bash +npm install @datalyr/api express stripe +``` + +Then run an example: + +```bash +DATALYR_API_KEY=dk_your_api_key node examples/basic.js +``` + +See the [Node SDK reference](https://docs.datalyr.com/sdk-reference/node) for every method and option. diff --git a/examples/basic.js b/examples/basic.js index 19e9106..e71f8fd 100644 --- a/examples/basic.js +++ b/examples/basic.js @@ -1,39 +1,39 @@ -// Basic example for @datalyr/api SDK +// Basic example for the DATALYR Node SDK (@datalyr/api) const { Datalyr } = require('@datalyr/api'); async function main() { - // Initialize with your API key - const datalyr = new Datalyr('dk_your_api_key_here'); + // Initialize with your server API key + const datalyr = new Datalyr({ apiKey: process.env.DATALYR_API_KEY || 'dk_your_api_key_here' }); try { - // Track a simple event - await datalyr.track('user_123', 'Button Clicked', { - button_name: 'Sign Up', - page: 'Homepage' + // Track an event + await datalyr.track({ + event: 'button_clicked', + userId: 'user_123', + properties: { button_name: 'sign_up', page: 'homepage' } }); // Identify a user await datalyr.identify('user_123', { email: 'user@example.com', - name: 'John Doe', + name: 'Jane Doe', plan: 'free' }); - // Track a purchase - await datalyr.track('user_123', 'Purchase Completed', { - amount: 49.99, + // Record a purchase with its value + await datalyr.trackPurchase('user_123', { + value: 49.99, currency: 'USD', items: ['Product A', 'Product B'] }); - // Flush events and close - await datalyr.flush(); + // Send queued events and stop the client before exit await datalyr.close(); - - console.log('Events sent successfully!'); + + console.log('Events sent.'); } catch (error) { console.error('Error:', error); } } -main(); \ No newline at end of file +main(); diff --git a/examples/express.js b/examples/express.js index 3f0b8fd..e44833c 100644 --- a/examples/express.js +++ b/examples/express.js @@ -1,11 +1,11 @@ -// Express.js integration example for @datalyr/api SDK +// Express integration example for the DATALYR Node SDK (@datalyr/api) const express = require('express'); const { Datalyr } = require('@datalyr/api'); const app = express(); app.use(express.json()); -// Initialize Datalyr SDK +// Initialize the DATALYR SDK const datalyr = new Datalyr({ apiKey: process.env.DATALYR_API_KEY || 'dk_your_api_key_here', debug: true @@ -14,16 +14,16 @@ const datalyr = new Datalyr({ // Middleware to track API requests app.use(async (req, res, next) => { // Track API request - await datalyr.track( - req.user?.id || null, - 'API Request', - { + await datalyr.track({ + event: 'api_request', + userId: req.user?.id, + properties: { method: req.method, path: req.path, ip: req.ip, userAgent: req.headers['user-agent'] } - ); + }); next(); }); @@ -33,9 +33,10 @@ app.post('/api/signup', async (req, res) => { const userId = `user_${Date.now()}`; // Track signup event - await datalyr.track(userId, 'User Signed Up', { - email, - source: 'api' + await datalyr.track({ + event: 'signup_completed', + userId, + properties: { email, source: 'api' } }); // Identify the new user @@ -52,12 +53,11 @@ app.post('/api/signup', async (req, res) => { app.post('/api/purchase', async (req, res) => { const { userId, amount, products } = req.body; - // Track purchase event - await datalyr.track(userId, 'Purchase Completed', { - amount, + // Record the purchase with its value + await datalyr.trackPurchase(userId, { + value: amount, currency: 'USD', - products, - timestamp: new Date().toISOString() + products }); res.json({ success: true }); diff --git a/examples/stripe-webhook.js b/examples/stripe-webhook.js index b3b4aa2..a46b191 100644 --- a/examples/stripe-webhook.js +++ b/examples/stripe-webhook.js @@ -1,9 +1,9 @@ -// Stripe webhook integration example for @datalyr/api SDK +// Stripe webhook integration example for the DATALYR Node SDK (@datalyr/api) // // IDEMPOTENT REDELIVERY: Stripe delivers webhooks at-least-once — the same event can // arrive multiple times (retries, replays from the dashboard). Always pass the Stripe -// event id as `eventId`: Datalyr's ingest de-duplicates on it (6h window), so a -// redelivered Purchase is counted ONCE instead of double-counting revenue. +// event id as `eventId`: DATALYR de-duplicates on it (6h window), so a +// redelivered purchase is counted once instead of double-counting revenue. // Also pass `timestamp: event.created` (epoch seconds) so delayed replays land on the // day the event actually happened, not the day the retry arrived. const express = require('express'); @@ -62,7 +62,7 @@ app.post('/webhooks/stripe', // Track subscription start await datalyr.track({ userId: subscription.metadata?.userId || subscription.customer, - event: 'Subscription Started', + event: 'subscription_started', eventId: event.id, timestamp: event.created, properties: { @@ -91,7 +91,7 @@ app.post('/webhooks/stripe', // Track cancellation await datalyr.track({ userId: canceledSub.metadata?.userId || canceledSub.customer, - event: 'Subscription Canceled', + event: 'subscription_canceled', eventId: event.id, timestamp: event.created, properties: { @@ -117,7 +117,7 @@ app.post('/webhooks/stripe', // Track failed payment await datalyr.track({ userId: invoice.metadata?.userId || invoice.customer, - event: 'Payment Failed', + event: 'payment_failed', eventId: event.id, timestamp: event.created, properties: { diff --git a/package.json b/package.json index cb6ae58..00a61f3 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "@datalyr/api", "version": "1.3.4", - "description": "Datalyr API SDK for server-side tracking", + "description": "DATALYR Node SDK for server-side event, identity and revenue tracking", "main": "dist/index.js", "module": "dist/index.mjs", "types": "dist/index.d.ts", @@ -26,7 +26,7 @@ ], "author": "Datalyr", "license": "MIT", - "homepage": "https://datalyr.com", + "homepage": "https://docs.datalyr.com/sdk-reference/node", "repository": { "type": "git", "url": "https://github.com/datalyr/api.git" diff --git a/src/index.ts b/src/index.ts index dad4725..698105c 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,13 +1,13 @@ import { randomUUID, createHash } from 'node:crypto'; -/** Why an event was dropped, passed to the onDrop hook (9.D.7). */ +/** Why an event was dropped, passed to the onDrop hook. */ export type DropReason = - | 'validation_error' // track/identify/alias/group called with invalid args (9.D.4) - | 'queue_overflow' // maxQueueSize reached; oldest evicted (NODE-5) - | 'permanent_client_error' // non-retryable 4xx (≠408/429), e.g. 401/403/400 (9.D.8) - | 'max_flush_attempts' // transient failures exceeded MAX_FLUSH_ATTEMPTS cycles (NODE-8) - | 'close_timeout' // still queued when close()'s closeTimeout budget expired (NODE-1) - | 'closed'; // track() called after close() (9.D.3) + | 'validation_error' // track/identify/alias/group called with invalid args + | 'queue_overflow' // maxQueueSize reached; oldest evicted + | 'permanent_client_error' // non-retryable 4xx (≠408/429), e.g. 401/403/400 + | 'max_flush_attempts' // transient failures exceeded MAX_FLUSH_ATTEMPTS cycles + | 'close_timeout' // still queued when close()'s closeTimeout budget expired + | 'closed'; // track() called after close() export interface DatalyrConfig { apiKey: string; @@ -22,10 +22,10 @@ export interface DatalyrConfig { * Must be >= worst-case retry time (sendEvent backoff is up to ~7s for 3 retries), * or close() drops events still mid-retry. */ closeTimeout?: number; - /** 9.D.7: called for every send failure (before any retry/requeue/drop decision), so you + /** called for every send failure (before any retry/requeue/drop decision), so you * can log/alert on delivery problems. Never throws into the SDK — exceptions are swallowed. */ onError?: (event: TrackEvent, error: Error) => void; - /** 9.D.7: called whenever event(s) are permanently dropped, with the reason. Covers ALL + /** called whenever event(s) are permanently dropped, with the reason. Covers ALL * drop paths (overflow, permanent 4xx, max-attempts, post-close, validation). Never * throws into the SDK — exceptions are swallowed. Use this to persist to your own DLQ. */ onDrop?: (events: TrackEvent[], reason: DropReason) => void; @@ -57,7 +57,7 @@ export interface TrackOptions { * `event.created`). Defaults to now. Invalid values are ignored (defaults to now) — * pass this on delayed webhook replays so the event lands on the right day. */ timestamp?: string | Date | number; - /** Declared external identity namespaces (Datalyr person contract §6): + /** Declared external identity namespaces: * `{ namespace: id }`, e.g. `{ stripe: 'cus_123', crm: 'acct_9' }`. Use this for * ANY identifier that is not the same userId your client-side identify() uses — * internal database ids, provider customer ids, private namespaces. Declared ids @@ -68,7 +68,7 @@ export interface TrackOptions { externalIds?: Record; } -/** 9.D.6: the revenue payload for trackPurchase(). `value` is required and must be a finite +/** The revenue payload for trackPurchase(). `value` is required and must be a finite * number (the server reads value ?? revenue ?? amount — value is the canonical field). */ export interface PurchaseProperties { value: number; @@ -76,7 +76,7 @@ export interface PurchaseProperties { [key: string]: any; } -// NODE-13: use node:crypto randomUUID unconditionally (GA since Node 14.17). The old +// use node:crypto randomUUID unconditionally (GA since Node 14.17). The old // global-`crypto` guard fell back to a weak Math.random id on Node <19, and eventId is // the SERVER dedup key — a collision there is silent data loss. function generateEventId(): string { @@ -84,7 +84,7 @@ function generateEventId(): string { } // A FRESH anonymous id, generated PER CALL — never a shared instance value. This is the -// fix for NODE-6: a single long-lived server process tracking many distinct end-users +// a single long-lived server process tracking many distinct end-users // must not stamp them all with one anonymous_id (which the ingest identity-resolution // then cross-links into one merged identity, leaking traits across users). function generateAnonymousId(): string { @@ -93,14 +93,14 @@ function generateAnonymousId(): string { const SDK_VERSION = '1.3.4'; // keep in sync with package.json -// NODE-8: max FAILED flush-cycles before an event is dropped (DLQ-lite). Separate from — +// max FAILED flush-cycles before an event is dropped (DLQ-lite). Separate from — // and more generous than — retryLimit (the per-send retry count): a brief outage spans a // few flush cycles before recovering, so this must be high enough to survive that, while // still preventing a permanently-failing "poison" event from cycling at the queue front // forever. const MAX_FLUSH_ATTEMPTS = 10; -// B-4: cap the caller-supplied eventId. Longer ids become pathological Redis keys server-side; +// cap the caller-supplied eventId. Longer ids become pathological Redis keys server-side; // overflow is hash-collapsed (deterministic, so redeliveries still dedup) below. const MAX_EVENT_ID_LENGTH = 256; @@ -118,17 +118,17 @@ export class Datalyr { private timer?: NodeJS.Timeout; private isFlushing: boolean = false; private isClosing: boolean = false; - private closeFinished = false; // close() has given up; a late transient failure is dropped, not re-queued (DLR-8) - private currentFlush?: Promise; // the in-flight drain — callers/close() await this instead of getting a no-op (NODE-3/TR-25) - private closePromise?: Promise; // memoized so close() is idempotent under repeat/concurrent calls (9.D.3) - private warnedNoId = false; // one-time warn for calls with neither userId nor anonymousId (NODE-6) - private warnedQueueFull = false; // one-time prod warn when the queue overflows (NODE-5) - private warnedClosed = false; // one-time loud error for track() after close() (9.D.3) - private warnedAuthFailure = false; // one-time loud error for 401/403 (9.D.8) - private flushAttempts = new WeakMap(); // failed-flush-cycle count per event (NODE-8); WeakMap → no payload pollution + private closeFinished = false; // close() has given up; a late transient failure is dropped, not re-queued + private currentFlush?: Promise; // the in-flight drain — callers/close() await this instead of getting a no-op + private closePromise?: Promise; // memoized so close() is idempotent under repeat/concurrent calls + private warnedNoId = false; // one-time warn for calls with neither userId nor anonymousId + private warnedQueueFull = false; // one-time prod warn when the queue overflows + private warnedClosed = false; // one-time loud error for track() after close() + private warnedAuthFailure = false; // one-time loud error for 401/403 + private flushAttempts = new WeakMap(); // failed-flush-cycle count per event; WeakMap → no payload pollution private exitHook?: () => void; // the beforeExit listener (stored so close() can remove it — review M2) - private onError?: (event: TrackEvent, error: Error) => void; // 9.D.7 - private onDrop?: (events: TrackEvent[], reason: DropReason) => void; // 9.D.7 + private onError?: (event: TrackEvent, error: Error) => void; + private onDrop?: (events: TrackEvent[], reason: DropReason) => void; constructor(config: DatalyrConfig | string) { if (typeof config === 'string') { @@ -170,7 +170,7 @@ export class Datalyr { if (this.timeout > 60000) this.timeout = 60000; if (this.maxQueueSize < 100) this.maxQueueSize = 100; if (this.maxQueueSize > 10000) this.maxQueueSize = 10000; - // NODE-12: flushInterval was never validated — 0/negative/NaN makes setInterval + // flushInterval was never validated — 0/negative/NaN makes setInterval // busy-loop. (The `|| 10000` above only catches 0/undefined, not negatives.) if (!(this.flushInterval >= 1000)) this.flushInterval = 10000; if (this.flushInterval > 3_600_000) this.flushInterval = 3_600_000; @@ -180,7 +180,7 @@ export class Datalyr { if (!(this.retryLimit >= 0)) this.retryLimit = 3; if (this.retryLimit > 10) this.retryLimit = 10; - // NODE-11: best-effort drain on process exit (short scripts/cron/serverless that + // best-effort drain on process exit (short scripts/cron/serverless that // finish before flushAt would otherwise lose buffered events — the timer is unref'd // and track() doesn't await the network). Does NOT replace `await close()`. this.registerExitHook(); @@ -202,7 +202,7 @@ export class Datalyr { process.once('beforeExit', this.exitHook); } - // 9.D.7: fan a drop/error out to the caller's observability hook. A hook that throws must + // fan a drop/error out to the caller's observability hook. A hook that throws must // never crash the SDK (the whole point is defensive delivery), so swallow its exceptions. private notifyDrop(events: TrackEvent[], reason: DropReason): void { if (!this.onDrop) return; @@ -243,7 +243,7 @@ export class Datalyr { eventProperties = properties || {}; } - // 9.D.4: NEVER throw. An invalid event name from deep in caller business logic used to + // NEVER throw. An invalid event name from deep in caller business logic used to // throw out of this fire-and-forget promise → an ERR_UNHANDLED_REJECTION that crashed // the host process (exit 1). Warn, hand it to onDrop, and resolve. if (!eventName || typeof eventName !== 'string') { @@ -252,7 +252,7 @@ export class Datalyr { return; } - // 9.D.3: close() is terminal. Post-close track() used to drop silently (debug-only). Emit + // close() is terminal. Post-close track() used to drop silently (debug-only). Emit // ONE loud, un-gated error so a mis-ordered shutdown (close() before the last track) is // visible in prod; every dropped event still reaches onDrop for programmatic handling. // For serverless, prefer `await flush()` per invocation and reserve close() for shutdown. @@ -265,7 +265,7 @@ export class Datalyr { return; } - // NODE-6: use the caller-provided anonymousId, else a FRESH one per call — NEVER a + // use the caller-provided anonymousId, else a FRESH one per call — NEVER a // shared instance value (that merged distinct end-users tracked from one server // process into a single identity). A call with neither userId nor anonymousId can't // be stitched to a user server-side; warn once so the integrator passes an id. @@ -284,11 +284,11 @@ export class Datalyr { const trackEvent: TrackEvent = { userId: userId || undefined, anonymousId: anonymousId, // Always include for identity resolution - // Person contract §6: declared namespaces ride the envelope top-level; + // declared namespaces ride the envelope top-level; // the ingest worker classifies + preserves them for identity joining. ...(providedExternalIds && typeof providedExternalIds === 'object' ? { externalIds: providedExternalIds } : {}), - // 9.D.1: honor a caller-supplied eventId VERBATIM — it is the ingest server's dedup + // honor a caller-supplied eventId VERBATIM — it is the ingest server's dedup // key (6h window), so webhook handlers can pass the source event id (e.g. Stripe // `event.id`) and at-least-once redeliveries no longer double-count revenue. A fresh // uuid per call (the old unconditional behavior) made every redelivery look new. @@ -299,9 +299,9 @@ export class Datalyr { library: '@datalyr/api', version: SDK_VERSION, source: 'api', - schema_version: 1 // A3-25: versioned-envelope stamp + schema_version: 1 // versioned-envelope stamp }, - // 9.D.5: honor a caller-supplied timestamp (ingest reads `event.timestamp || now`), + // honor a caller-supplied timestamp (ingest reads `event.timestamp || now`), // so delayed webhook replays land on the day the event happened, not the replay day. timestamp: this.resolveTimestamp(providedTimestamp) }; @@ -310,20 +310,20 @@ export class Datalyr { } async identify(userId: string, traits?: any, anonymousId?: string): Promise { - // 9.D.4: warn-and-drop, never throw (see track()). + // warn-and-drop, never throw (see track()). if (!userId) { console.warn('[Datalyr] identify() requires a userId; call dropped.'); this.notifyDrop([{ event: '$identify' } as TrackEvent], 'validation_error'); return; } - // Route through the options form so a caller-provided anonymousId is honored (NODE-6). + // Route through the options form so a caller-provided anonymousId is honored. // track() stamps anonymous_id itself — no need to inject the (formerly shared) one. // Traits stay flat (not wrapped in $set) so the user-properties-updater extracts them. return this.track({ userId, anonymousId, event: '$identify', properties: { ...traits } }); } async alias(newUserId: string, previousId?: string, anonymousId?: string): Promise { - // 9.D.4: warn-and-drop, never throw. + // warn-and-drop, never throw. if (!newUserId) { console.warn('[Datalyr] alias() requires a newUserId; call dropped.'); this.notifyDrop([{ event: '$alias' } as TrackEvent], 'validation_error'); @@ -360,7 +360,7 @@ export class Datalyr { * B2B account rollups yet. */ async group(userId: string, groupId: string, traits?: any, anonymousId?: string): Promise { - // 9.D.4: warn-and-drop, never throw. + // warn-and-drop, never throw. if (!groupId) { console.warn('[Datalyr] group() requires a groupId; call dropped.'); this.notifyDrop([{ event: '$group', userId } as TrackEvent], 'validation_error'); @@ -370,7 +370,7 @@ export class Datalyr { } /** - * 9.D.6: purchase helper with a validated revenue amount. The ingest revenue pipeline + * purchase helper with a validated revenue amount. The ingest revenue pipeline * reads `value ?? revenue ?? amount` (in that order) — `value` is the canonical field — * so this stamps `value` and (defensively) requires it to be a FINITE number. A NaN / * Infinity / non-number value would land as $0 or corrupt revenue rollups, so it is @@ -398,7 +398,7 @@ export class Datalyr { }); } - // 9.D.1 + B-4: caller-supplied idempotency key. Defensive by design — this SDK must never + // caller-supplied idempotency key. Defensive by design — this SDK must never // crash the host — so anything that isn't a non-empty string is IGNORED (fresh uuid, same // as omitting it) with a debug warning, never a throw. An over-long id (pathological Redis // key server-side) is collapsed to a DETERMINISTIC sha256-based value so redeliveries of @@ -419,7 +419,7 @@ export class Datalyr { return generateEventId(); } - // 9.D.5: caller-supplied event time, normalized to ISO-8601. Accepts ISO string, Date, + // caller-supplied event time, normalized to ISO-8601. Accepts ISO string, Date, // or numeric epoch. Numbers < 1e12 are treated as epoch SECONDS (webhook payloads like // Stripe's `event.created` are seconds; 1e12 ms is Sep 2001, so real ms timestamps are // always above it). Invalid input → now, with a debug warning — never a throw. @@ -444,7 +444,7 @@ export class Datalyr { } private enqueue(event: TrackEvent): void { - // Check queue size limit to prevent memory issues. NODE-5: surface the drop in PROD + // Check queue size limit to prevent memory issues. Surface the drop in PROD // (once) — it was debug-only, so silent data loss under sustained overload. if (this.queue.length >= this.maxQueueSize) { if (!this.warnedQueueFull) { @@ -452,7 +452,7 @@ export class Datalyr { console.warn(`[Datalyr] Queue full (${this.maxQueueSize}) — dropping oldest events. Increase maxQueueSize, or flush()/close() more often.`); } const dropped = this.queue.shift(); // Remove oldest event - // 9.D.7: overflow is a drop path — surface it so callers can persist to their own DLQ. + // overflow is a drop path — surface it so callers can persist to their own DLQ. if (dropped) this.notifyDrop([dropped], 'queue_overflow'); } @@ -473,11 +473,11 @@ export class Datalyr { } async flush(): Promise { - // NODE-3 / TR-25: if a drain is already running, AWAIT it (return the in-flight promise) + // if a drain is already running, AWAIT it (return the in-flight promise) // rather than no-op'ing. Because the drain LOOPS until the queue empties, awaiting it now // also guarantees events enqueued AFTER it started are sent — fixing the serverless // `track(); track(); await flush(); return` bug where the second event stranded. - // DLR-8: this check must come BEFORE the empty-queue return. _flush() empties the queue + // this check must come BEFORE the empty-queue return. _flush() empties the queue // as soon as a pass starts, so after an auto-flush (flushAt reached) took the events the // queue is empty while their POSTs/retries are still running — returning early there let // `await flush()` resolve with sends in flight (serverless freeze → silent loss). @@ -496,7 +496,7 @@ export class Datalyr { } } - // TR-25: a single _flush pass snapshots the queue, so events enqueued during the pass — or + // a single _flush pass snapshots the queue, so events enqueued during the pass — or // failures it re-queues — would strand on `await flush()`. Loop passes until the queue is // empty or a pass DELIVERS NOTHING (every event failed: a down endpoint re-queued/dropped // them all). Progress must be measured by successful sends, NOT queue length — a pass that @@ -522,7 +522,7 @@ export class Datalyr { console.log(`[Datalyr] Flushing ${events.length} events`); } - // NODE-7: this is a CONCURRENCY window (10 events in parallel), NOT a single batched + // this is a CONCURRENCY window (10 events in parallel), NOT a single batched // HTTP request — one POST per event. (Real payload batching is gated on the ingest // `/batch` endpoint, currently disabled.) const batchSize = 10; @@ -533,10 +533,10 @@ export class Datalyr { const promises = batch.map(event => this.sendEvent(event).catch((err: any) => { failed++; - // 9.D.7: every send failure reaches onError before any drop/requeue decision. + // every send failure reaches onError before any drop/requeue decision. this.notifyError(event, err instanceof Error ? err : new Error(String(err))); - // 9.D.8: a permanent client error (4xx ≠ 408/429 — bad key, malformed, forbidden) + // a permanent client error (4xx ≠ 408/429 — bad key, malformed, forbidden) // will NEVER succeed on retry, so drop it IMMEDIATELY instead of cycling it 10 // times. A wrong API key (401/403) black-holes everything, so raise it loudly ONCE // as an auth failure — the single most common "no data" support case. @@ -549,12 +549,12 @@ export class Datalyr { return; } - // NODE-8 / NODE-9 / NODE-10: bound re-queue attempts so a permanently-failing + // bound re-queue attempts so a permanently-failing // (transient) event can't cycle at the front forever (re-failing every flush). // Count failed flush-cycles per event (WeakMap, no payload pollution); drop with a // VISIBLE warn after MAX_FLUSH_ATTEMPTS cycles. Re-queue at the front so failures // retry first. - // DLR-8: a send still running when close()'s budget expired is not in the queue, + // a send still running when close()'s budget expired is not in the queue, // so close() could not report it. If it now fails transiently, re-queueing would // strand it on a closed client (no timer, no further drain) — never sent, never // reported. Hand it to onDrop as close_timeout instead. @@ -588,7 +588,7 @@ export class Datalyr { const controller = new AbortController(); const timeoutId = setTimeout(() => controller.abort(), this.timeout); - // NODE-15: clear the abort timer on settle (success OR reject). A fetch rejection + // clear the abort timer on settle (success OR reject). A fetch rejection // (DNS / ECONNRESET / TLS) used to skip clearTimeout, leaving a non-unref'd timer // pending up to `timeout` ms that can delay process exit. const response = await fetch(this.host, { @@ -610,7 +610,7 @@ export class Datalyr { // Ignore body read errors } - // 9.D.8: 408 (Request Timeout) and 429 (Too Many Requests) are TRANSIENT — retry + // 408 (Request Timeout) and 429 (Too Many Requests) are TRANSIENT — retry // them like 5xx. Every other 4xx is a permanent client error: tag it so the flush // layer drops it immediately instead of cycling it MAX_FLUSH_ATTEMPTS times. if (response.status !== 408 && response.status !== 429 && @@ -650,7 +650,7 @@ export class Datalyr { if (this.debug) { console.log(`[Datalyr] Retrying event (attempt ${retryCount + 1}/${this.retryLimit})`); } - // NODE-8: full jitter so many SDK instances don't retry in lockstep against a + // full jitter so many SDK instances don't retry in lockstep against a // recovering server. const backoffMs = Math.min(Math.pow(2, retryCount) * 1000, 10000); // Max 10s const jittered = backoffMs * (0.5 + Math.random() * 0.5); @@ -680,7 +680,7 @@ export class Datalyr { } /** - * Generate a NEW anonymous id. NODE-6: there is no longer a shared process-wide anon + * Generate a NEW anonymous id. There is no longer a shared process-wide anon * (that merged distinct users). Each call returns a fresh id — persist it in YOUR * per-user/session store and pass it back as `anonymousId` to stitch that user's * events. (Behavior change from <=1.2.3, which returned one shared id.) @@ -689,7 +689,7 @@ export class Datalyr { return generateAnonymousId(); } - // A cancelable delay: TR-09. Returns the promise AND a cancel() that clears the underlying + // A cancelable delay. Returns the promise AND a cancel() that clears the underlying // timer, so a Promise.race that settles via the OTHER arm doesn't leave a live (non-unref'd) // timer holding the event loop open until it fires — the exact hang the 1.3.0 unref work // fixed and the close() race timer had reintroduced. @@ -701,7 +701,7 @@ export class Datalyr { // Cleanup async close(): Promise { - // 9.D.3: idempotent — repeat or concurrent close() calls share ONE drain and never + // idempotent — repeat or concurrent close() calls share ONE drain and never // restart it (a second close() must not re-run the loop or double-remove the exit hook). if (this.closePromise) return this.closePromise; this.closePromise = this._close(); @@ -716,7 +716,7 @@ export class Datalyr { this.timer = undefined; } - // NODE-1/2/4: actually DRAIN the queue. The old close() flushed ONCE and raced a hard + // actually DRAIN the queue. The old close() flushed ONCE and raced a hard // 5s timeout — one flush isn't enough (it re-queues failures), a no-op flush won if one // was in flight, and 5s < worst-case retry (~7s) dropped mid-retry events. Loop flush() // (which now drains until the queue empties instead of no-op'ing) until the queue drains @@ -729,11 +729,11 @@ export class Datalyr { // background (best-effort delivery; it has its own .catch), so close() never blocks past // its budget. // - // TR-09: the budget + pause timers are CANCELED when their race settles (this.delay), so + // the budget + pause timers are CANCELED when their race settles (this.delay), so // a won race never leaves a live timer pinning the event loop for up to closeTimeout ms // after close() resolved (proven: close resolved 14ms, process exited 8016ms). // - // DLR-8: also loop while a drain is in flight with an EMPTY queue (an auto-flush already + // also loop while a drain is in flight with an EMPTY queue (an auto-flush already // took the events). flush() returns that drain, so close() waits for its sends — and // their onDrop/onError — instead of resolving at ~0ms. const start = Date.now(); @@ -772,7 +772,7 @@ export class Datalyr { if (this.queue.length > 0) { const undelivered = [...this.queue]; console.warn(`[Datalyr] close(): ${undelivered.length} event(s) undelivered after ~${Date.now() - start}ms (budget ${this.closeTimeout}ms).`); - // 9.D.7: hand the survivors to onDrop so callers can persist them (their durability is + // hand the survivors to onDrop so callers can persist them (their durability is // now the caller's — close() has given up on them). this.notifyDrop(undelivered, 'close_timeout'); }