From 7a4acdd988604dafb5b60bf5f985664b5da8f4ba Mon Sep 17 00:00:00 2001 From: czy Date: Sun, 22 Nov 2026 14:24:49 -0600 Subject: [PATCH 1/9] W3: log each drop warning once per client, then only with debug Per-event warnings (validation drops in track/identify/alias/group/trackPurchase and the max-flush-attempts drop) printed on every event and ignored debug. Log the first of each kind once per instance, repeats only with debug: true. onDrop/onError unchanged. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 5 +++++ src/index.ts | 26 ++++++++++++++++++++------ tests/test.ts | 43 +++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 68 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index bc33294..4751f4f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,11 @@ All notable changes to this project will be documented in this file. ## [Unreleased] +### Changed +- Warnings for dropped events (invalid `track()`/`identify()`/`alias()`/`group()`/`trackPurchase()` + arguments, and events dropped after the maximum failed flush attempts) are logged once per + client for each kind, then only with `debug: true`. `onDrop` and `onError` still fire for every event. + ## [1.3.4] - 2026-11-14 ### Fixed diff --git a/src/index.ts b/src/index.ts index 698105c..f132733 100644 --- a/src/index.ts +++ b/src/index.ts @@ -125,6 +125,7 @@ export class Datalyr { 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 warnedKinds = new Set(); // warnings already logged once on this instance (see warnOnce) 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; @@ -209,6 +210,19 @@ export class Datalyr { try { this.onDrop(events, reason); } catch { /* a hook must never break the SDK */ } } + // Log a warning the first time each kind happens on this instance; repeats are logged + // only with `debug: true`. Per-event warnings used to print on EVERY dropped event and + // ignore `debug`, flooding logs under a bad integration or an outage. onDrop/onError + // still fire for every event, so nothing is lost to callers who need the full count. + private warnOnce(kind: string, message: string): void { + if (this.warnedKinds.has(kind)) { + if (this.debug) console.warn(message); + return; + } + this.warnedKinds.add(kind); + console.warn(message + ' (Logged once; set debug: true to log every occurrence.)'); + } + private notifyError(event: TrackEvent, error: Error): void { if (!this.onError) return; try { this.onError(event, error); } catch { /* a hook must never break the SDK */ } @@ -247,7 +261,7 @@ export class Datalyr { // 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') { - console.warn('[Datalyr] track() requires a non-empty string event name; event dropped.'); + this.warnOnce('track_event_name', '[Datalyr] track() requires a non-empty string event name; event dropped.'); this.notifyDrop([{ event: String(eventName ?? ''), userId } as TrackEvent], 'validation_error'); return; } @@ -312,7 +326,7 @@ export class Datalyr { async identify(userId: string, traits?: any, anonymousId?: string): Promise { // warn-and-drop, never throw (see track()). if (!userId) { - console.warn('[Datalyr] identify() requires a userId; call dropped.'); + this.warnOnce('identify_user_id', '[Datalyr] identify() requires a userId; call dropped.'); this.notifyDrop([{ event: '$identify' } as TrackEvent], 'validation_error'); return; } @@ -325,7 +339,7 @@ export class Datalyr { async alias(newUserId: string, previousId?: string, anonymousId?: string): Promise { // warn-and-drop, never throw. if (!newUserId) { - console.warn('[Datalyr] alias() requires a newUserId; call dropped.'); + this.warnOnce('alias_user_id', '[Datalyr] alias() requires a newUserId; call dropped.'); this.notifyDrop([{ event: '$alias' } as TrackEvent], 'validation_error'); return; } @@ -362,7 +376,7 @@ export class Datalyr { async group(userId: string, groupId: string, traits?: any, anonymousId?: string): Promise { // warn-and-drop, never throw. if (!groupId) { - console.warn('[Datalyr] group() requires a groupId; call dropped.'); + this.warnOnce('group_id', '[Datalyr] group() requires a groupId; call dropped.'); this.notifyDrop([{ event: '$group', userId } as TrackEvent], 'validation_error'); return; } @@ -384,7 +398,7 @@ export class Datalyr { ): Promise { const value = purchase?.value; if (typeof value !== 'number' || !Number.isFinite(value)) { - console.warn('[Datalyr] trackPurchase() requires a finite numeric `value` (revenue amount); event dropped.'); + this.warnOnce('purchase_value', '[Datalyr] trackPurchase() requires a finite numeric `value` (revenue amount); event dropped.'); this.notifyDrop([{ event: 'purchase', userId: userId || undefined } as TrackEvent], 'validation_error'); return; } @@ -566,7 +580,7 @@ export class Datalyr { const n = (this.flushAttempts.get(event) || 0) + 1; this.flushAttempts.set(event, n); if (n >= MAX_FLUSH_ATTEMPTS) { - console.warn(`[Datalyr] Dropping event after ${n} failed flush attempts: ${event.event}`); + this.warnOnce('max_flush_attempts', `[Datalyr] Dropping event after ${n} failed flush attempts: ${event.event}`); this.notifyDrop([event], 'max_flush_attempts'); } else { this.queue.unshift(event); diff --git a/tests/test.ts b/tests/test.ts index d594f16..d5a1848 100644 --- a/tests/test.ts +++ b/tests/test.ts @@ -302,6 +302,49 @@ async function main() { assert(drops8c.length === 1 && drops8c[0] === 'close_timeout', `DLR-8: a late transient failure after close() fires onDrop('close_timeout') instead of stranding (got ${JSON.stringify(drops8c)})`); + // ---- W3: per-event warnings log once per instance (then only with debug); hooks still fire ---- + { + const warns: string[] = []; + const origWarn = console.warn; + console.warn = (...args: any[]) => { warns.push(args.map(String).join(' ')); }; + try { + let n3 = 0; + (globalThis as any).fetch = async (_u: string, opts: any) => { + if (JSON.parse(opts.body).event.startsWith('w3_')) n3++; + return { ok: false, status: 503, statusText: 'down', text: async () => '' }; + }; + const drops3: string[] = []; + const dl3w = new Datalyr({ apiKey: 'dk_test', flushAt: 100, flushInterval: 3_600_000, retryLimit: 0, closeTimeout: 1000, onDrop: (_e, r) => drops3.push(r) }); + await dl3w.track({ userId: 'u', event: 'w3_a' }); + await dl3w.track({ userId: 'u', event: 'w3_b' }); + for (let i = 0; i < 10; i++) await dl3w.flush(); // each flush = one failed cycle per event + const maxWarns = warns.filter((w) => w.includes('failed flush attempts')).length; + assert(drops3.filter((r) => r === 'max_flush_attempts').length === 2, + `W3: both events still reach onDrop('max_flush_attempts') (got ${drops3.filter((r) => r === 'max_flush_attempts').length})`); + assert(maxWarns === 1, `W3: max-attempts drop warned ONCE per instance, not per event (got ${maxWarns})`); + + warns.length = 0; + await dl3w.identify('' as any); await dl3w.identify('' as any); await dl3w.identify('' as any); + await dl3w.alias('' as any); await dl3w.alias('' as any); + await dl3w.group('u', '' as any); await dl3w.group('u', '' as any); + await dl3w.track({ event: '' } as any); await dl3w.track(null, ''); + await dl3w.trackPurchase('u', { value: NaN }); await dl3w.trackPurchase('u', { value: NaN }); + assert(warns.length === 5, `W3: 11 invalid calls of 5 kinds log 5 warnings, one per kind (got ${warns.length})`); + assert(drops3.filter((r) => r === 'validation_error').length === 11, + `W3: every invalid call still reaches onDrop('validation_error') (got ${drops3.filter((r) => r === 'validation_error').length})`); + await dl3w.close(); + + warns.length = 0; + const dl3d = new Datalyr({ apiKey: 'dk_test', flushAt: 100, flushInterval: 3_600_000, debug: true }); + await dl3d.identify('' as any); await dl3d.identify('' as any); + assert(warns.filter((w) => w.includes('identify() requires')).length === 2, + 'W3: with debug: true every occurrence is still logged'); + await dl3d.close(); + } finally { + console.warn = origWarn; + } + } + console.log(failures === 0 ? '\nALL PASS' : `\n${failures} FAILED`); process.exit(failures === 0 ? 0 : 1); } From 8afa9b95dfd3ff26126091de5efb548bf818989e Mon Sep 17 00:00:00 2001 From: czy Date: Sun, 22 Nov 2026 14:25:37 -0600 Subject: [PATCH 2/9] W12: one shared beforeExit listener, accept sk_ keys, Stripe example uses externalIds - One process-level beforeExit listener for all live clients (was one per instance); each client is still flushed once on exit; listener removed when the last client closes. - Key-prefix warning also accepts sk_ (server key). - examples/stripe-webhook.js: Stripe customer id goes in externalIds.stripe, not userId. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 6 ++++ examples/stripe-webhook.js | 51 ++++++++++++++++++------------- src/index.ts | 61 +++++++++++++++++++++++++++----------- tests/test.ts | 44 +++++++++++++++++++++++++++ 4 files changed, 124 insertions(+), 38 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4751f4f..efc1bf7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,12 @@ All notable changes to this project will be documented in this file. - Warnings for dropped events (invalid `track()`/`identify()`/`alias()`/`group()`/`trackPurchase()` arguments, and events dropped after the maximum failed flush attempts) are logged once per client for each kind, then only with `debug: true`. `onDrop` and `onError` still fire for every event. +- All clients share one process `beforeExit` listener (it was one per client, which triggered + `MaxListenersExceededWarning` when a client was created per request). Each live client is + still flushed once on exit; the listener is removed when the last client is closed. +- The API key prefix warning accepts `sk_` keys as well as `dk_`. +- `examples/stripe-webhook.js` sends the Stripe customer id as `externalIds: { stripe }` + instead of using it as `userId`. ## [1.3.4] - 2026-11-14 diff --git a/examples/stripe-webhook.js b/examples/stripe-webhook.js index a46b191..dad83bd 100644 --- a/examples/stripe-webhook.js +++ b/examples/stripe-webhook.js @@ -6,6 +6,10 @@ // 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. +// +// IDENTITY: `userId` is YOUR app's user id (the one your client-side identify() uses). +// Never put the Stripe customer id there. Send it as `externalIds: { stripe: }`; +// DATALYR joins it to the customer journey once that Stripe customer is linked to a user. const express = require('express'); const { Datalyr } = require('@datalyr/api'); const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY); @@ -61,7 +65,8 @@ app.post('/webhooks/stripe', // Track subscription start await datalyr.track({ - userId: subscription.metadata?.userId || subscription.customer, + userId: subscription.metadata?.userId, + externalIds: { stripe: subscription.customer }, event: 'subscription_started', eventId: event.id, timestamp: event.created, @@ -74,15 +79,17 @@ app.post('/webhooks/stripe', } }); - // Update user traits - await datalyr.identify( - subscription.metadata?.userId || subscription.customer, - { - subscriptionStatus: 'active', - subscriptionPlan: subscription.items.data[0].price.nickname, - stripeCustomerId: subscription.customer - } - ); + // Update user traits (only when you know your own user id) + if (subscription.metadata?.userId) { + await datalyr.identify( + subscription.metadata.userId, + { + subscriptionStatus: 'active', + subscriptionPlan: subscription.items.data[0].price.nickname, + stripeCustomerId: subscription.customer + } + ); + } break; case 'customer.subscription.deleted': @@ -90,7 +97,8 @@ app.post('/webhooks/stripe', // Track cancellation await datalyr.track({ - userId: canceledSub.metadata?.userId || canceledSub.customer, + userId: canceledSub.metadata?.userId, + externalIds: { stripe: canceledSub.customer }, event: 'subscription_canceled', eventId: event.id, timestamp: event.created, @@ -101,14 +109,16 @@ app.post('/webhooks/stripe', } }); - // Update user traits - await datalyr.identify( - canceledSub.metadata?.userId || canceledSub.customer, - { - subscriptionStatus: 'canceled', - subscriptionEndDate: new Date(canceledSub.ended_at * 1000).toISOString() - } - ); + // Update user traits (only when you know your own user id) + if (canceledSub.metadata?.userId) { + await datalyr.identify( + canceledSub.metadata.userId, + { + subscriptionStatus: 'canceled', + subscriptionEndDate: new Date(canceledSub.ended_at * 1000).toISOString() + } + ); + } break; case 'invoice.payment_failed': @@ -116,7 +126,8 @@ app.post('/webhooks/stripe', // Track failed payment await datalyr.track({ - userId: invoice.metadata?.userId || invoice.customer, + userId: invoice.metadata?.userId, + externalIds: { stripe: invoice.customer }, event: 'payment_failed', eventId: event.id, timestamp: event.created, diff --git a/src/index.ts b/src/index.ts index f132733..19ffdbe 100644 --- a/src/index.ts +++ b/src/index.ts @@ -127,7 +127,13 @@ export class Datalyr { private warnedAuthFailure = false; // one-time loud error for 401/403 private warnedKinds = new Set(); // warnings already logged once on this instance (see warnOnce) 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 exitFlushed = false; // the process-exit flush already ran for this client (once, like the old process.once) + // ONE process-level beforeExit listener shared by every live client. One listener per + // instance made apps that build a client per request hit MaxListenersExceededWarning and + // pinned every instance. A plain Set is enough: an unclosed client is already held by its + // flush timer, and close() removes it here (and the listener when the last client closes). + private static liveClients = new Set(); + private static exitListener?: () => void; private onError?: (event: TrackEvent, error: Error) => void; private onDrop?: (events: TrackEvent[], reason: DropReason) => void; @@ -160,8 +166,8 @@ export class Datalyr { throw new Error('Datalyr API key is required'); } - if (!this.apiKey.startsWith('dk_')) { - console.warn('[Datalyr] API key should start with "dk_"'); + if (!this.apiKey.startsWith('dk_') && !this.apiKey.startsWith('sk_')) { + console.warn('[Datalyr] API key should start with "dk_" or "sk_"'); } // Validate config values @@ -191,16 +197,37 @@ export class Datalyr { } private registerExitHook(): void { - if (typeof process === 'undefined' || typeof process.once !== 'function') return; - // Stored on the instance so close() can removeListener it (review M2: `once` without - // removal leaks the instance + its queue for the process lifetime when close() is - // called and the hook never fires — bad for per-request client construction). - this.exitHook = () => { - if (this.isClosing || this.queue.length === 0) return; - // beforeExit lets the loop run async work; best-effort (use close() for guarantees). - this.flush().catch(() => {}); - }; - process.once('beforeExit', this.exitHook); + if (typeof process === 'undefined' || typeof process.on !== 'function') return; + Datalyr.liveClients.add(this); + if (!Datalyr.exitListener) { + Datalyr.exitListener = () => Datalyr.flushAllOnExit(); + process.on('beforeExit', Datalyr.exitListener); + } + } + + // beforeExit lets the loop run async work; best-effort (use close() for guarantees). Each + // client is flushed at most once here, as with the old per-instance process.once, so a + // down endpoint cannot keep re-triggering beforeExit and hold the process open. + private static flushAllOnExit(): void { + for (const client of [...Datalyr.liveClients]) { + if (client.exitFlushed) continue; + client.exitFlushed = true; + Datalyr.liveClients.delete(client); + if (client.isClosing || client.queue.length === 0) continue; + client.flush().catch(() => {}); + } + if (Datalyr.liveClients.size === 0) Datalyr.removeExitListener(); + } + + private unregisterExitHook(): void { + Datalyr.liveClients.delete(this); + if (Datalyr.liveClients.size === 0) Datalyr.removeExitListener(); + } + + private static removeExitListener(): void { + if (!Datalyr.exitListener) return; + try { process.removeListener('beforeExit', Datalyr.exitListener); } catch { /* noop */ } + Datalyr.exitListener = undefined; } // fan a drop/error out to the caller's observability hook. A hook that throws must @@ -777,11 +804,9 @@ export class Datalyr { this.closeFinished = true; - // review M2: stop leaking the beforeExit listener (+ the instance/queue it pins). - if (this.exitHook) { - try { process.removeListener('beforeExit', this.exitHook); } catch { /* noop */ } - this.exitHook = undefined; - } + // review M2: stop pinning this client (+ its queue) from the shared beforeExit + // listener; the listener itself goes when the last live client closes. + this.unregisterExitHook(); if (this.queue.length > 0) { const undelivered = [...this.queue]; diff --git a/tests/test.ts b/tests/test.ts index d5a1848..7e89c72 100644 --- a/tests/test.ts +++ b/tests/test.ts @@ -16,6 +16,50 @@ function mockFetch(into: any[]) { } async function main() { + // ---- W12a: ONE shared beforeExit listener, not one per instance; removed on close() ---- + // Runs first, before any other test creates a client, so the counts start clean. + { + const before = process.listenerCount('beforeExit'); + const clients = Array.from({ length: 20 }, () => new Datalyr({ apiKey: 'dk_test', flushAt: 100, flushInterval: 3_600_000 })); + const during = process.listenerCount('beforeExit'); + assert(during - before <= 1, `W12a: 20 clients add at most ONE beforeExit listener (added ${during - before})`); + for (const c of clients) await c.close(); + assert(process.listenerCount('beforeExit') === before, + `W12a: the listener is removed once the last client closes (have ${process.listenerCount('beforeExit')}, started with ${before})`); + + // the shared listener still flushes every live client's queue on beforeExit + const sentX: any[] = []; + mockFetch(sentX); + const x1 = new Datalyr({ apiKey: 'dk_test', flushAt: 100, flushInterval: 3_600_000 }); + const x2 = new Datalyr({ apiKey: 'dk_test', flushAt: 100, flushInterval: 3_600_000 }); + await x1.track({ userId: 'u', event: 'exit_1' }); + await x2.track({ userId: 'u', event: 'exit_2' }); + process.emit('beforeExit', 0); + await new Promise((r) => setTimeout(r, 50)); + assert(sentX.some((e) => e.event === 'exit_1') && sentX.some((e) => e.event === 'exit_2'), + 'W12a: beforeExit flushes the queue of every live client'); + assert(process.listenerCount('beforeExit') === before, + 'W12a: after the exit flush the shared listener is gone (each client flushes once, like process.once)'); + await x1.close(); await x2.close(); + } + + // ---- W12b: the key-prefix warning accepts sk_ (server key) as well as dk_ ---- + { + const warns: string[] = []; + const origWarn = console.warn; + console.warn = (...args: any[]) => { warns.push(args.map(String).join(' ')); }; + try { + const k1 = new Datalyr({ apiKey: 'sk_test', flushAt: 100, flushInterval: 3_600_000 }); + const k2 = new Datalyr({ apiKey: 'dk_test', flushAt: 100, flushInterval: 3_600_000 }); + assert(!warns.some((w) => w.includes('should start with')), 'W12b: sk_ and dk_ keys do not trigger the key-prefix warning'); + const k3 = new Datalyr({ apiKey: 'xx_test', flushAt: 100, flushInterval: 3_600_000 }); + assert(warns.some((w) => w.includes('should start with')), 'W12b: any other prefix still warns'); + await k1.close(); await k2.close(); await k3.close(); + } finally { + console.warn = origWarn; + } + } + // ---- NODE-6: distinct users get DISTINCT anonymous ids (no shared/merged identity) ---- const sent: any[] = []; mockFetch(sent); From 034683ae73876fec09a0f860730cbb01e85e8cb1 Mon Sep 17 00:00:00 2001 From: czy Date: Sun, 22 Nov 2026 14:26:06 -0600 Subject: [PATCH 3/9] W14: tests for page(), group(), externalIds, network errors, timeout, context and version Co-Authored-By: Claude Opus 5.5 --- tests/test.ts | 82 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 82 insertions(+) diff --git a/tests/test.ts b/tests/test.ts index 7e89c72..a589108 100644 --- a/tests/test.ts +++ b/tests/test.ts @@ -1,5 +1,6 @@ // Functional tests for the Node SDK. Mocks global fetch (no real network) and asserts // the 1.2.4 fixes. Run with: node tests/test.ts (Node 23+ strips types). +import { readFileSync } from 'node:fs'; import { Datalyr } from '../src/index.ts'; let failures = 0; @@ -346,6 +347,87 @@ async function main() { assert(drops8c.length === 1 && drops8c[0] === 'close_timeout', `DLR-8: a late transient failure after close() fires onDrop('close_timeout') instead of stranding (got ${JSON.stringify(drops8c)})`); + // ---- W14: page(), group(), externalIds, context shape, SDK version ---- + { + const sentW: any[] = []; + const headersW: any[] = []; + (globalThis as any).fetch = async (_url: string, opts: any) => { + sentW.push(JSON.parse(opts.body)); + headersW.push(opts.headers); + return { ok: true, status: 200, statusText: 'OK', text: async () => '', json: async () => ({}) }; + }; + const dlW = new Datalyr({ apiKey: 'dk_test', flushAt: 100, flushInterval: 3_600_000 }); + await dlW.page('u_page', 'Pricing', { url: 'https://example.com/pricing', plan: 'pro' }, 'anon_page'); + await dlW.group('u_group', 'org_1', { name: 'Org One', seats: 5 }); + await dlW.track({ userId: 'u_ext', event: 'ext_on', externalIds: { stripe: 'cus_123', crm: 'acct_9' } }); + await dlW.track({ userId: 'u_ext', event: 'ext_off' }); + await dlW.flush(); + const w = (n: string) => sentW.find((e) => e.event === n); + + const pv = w('$pageview'); + assert(!!pv && pv.userId === 'u_page' && pv.anonymousId === 'anon_page' && pv.properties.name === 'Pricing' && + pv.properties.url === 'https://example.com/pricing' && pv.properties.plan === 'pro', + 'W14: page() sends $pageview with userId, anonymousId, name, the given url and extra properties'); + + const grp = w('$group'); + assert(!!grp && grp.userId === 'u_group' && grp.properties.groupId === 'org_1' && + grp.properties.name === 'Org One' && grp.properties.seats === 5, + 'W14: group() sends $group with userId, groupId and the traits'); + + assert(JSON.stringify(w('ext_on').externalIds) === JSON.stringify({ stripe: 'cus_123', crm: 'acct_9' }), + 'W14: track() externalIds ride the envelope top-level, unchanged'); + assert(!('externalIds' in w('ext_off')), 'W14: no externalIds key when none passed'); + + const pkgVersion = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version; + assert(JSON.stringify(w('ext_off').context) === JSON.stringify({ library: '@datalyr/api', version: pkgVersion, source: 'api', schema_version: 1 }), + `W14: context is exactly { library, version, source: 'api', schema_version: 1 } (got ${JSON.stringify(w('ext_off').context)})`); + assert(w('ext_off').context.version === pkgVersion, + `W14: SDK_VERSION (${w('ext_off').context.version}) equals package.json version (${pkgVersion})`); + assert(headersW[0]['User-Agent'] === `@datalyr/api/${pkgVersion}`, 'W14: User-Agent carries the package.json version'); + await dlW.close(); + } + + // ---- W14: a fetch that throws is transient (onError, re-queued, sent on the next flush) ---- + { + let failNet = true; + const sentN: any[] = []; + (globalThis as any).fetch = async (_url: string, opts: any) => { + const body = JSON.parse(opts.body); + if (body.event !== 'net_fail') return { ok: true, status: 200, statusText: 'OK', text: async () => '' }; + if (failNet) throw new TypeError('fetch failed'); + sentN.push(body); + return { ok: true, status: 200, statusText: 'OK', text: async () => '', json: async () => ({}) }; + }; + const errsN: Error[] = []; const dropsN: string[] = []; + const dlN = new Datalyr({ apiKey: 'dk_test', flushAt: 100, flushInterval: 3_600_000, retryLimit: 0, + onError: (_e, err) => errsN.push(err), onDrop: (_e, r) => dropsN.push(r) }); + await dlN.track({ userId: 'u', event: 'net_fail' }); + await dlN.flush(); + assert(errsN.length === 1 && errsN[0].message === 'fetch failed', `W14: a throwing fetch reaches onError with its error (got ${errsN.map((e) => e.message)})`); + assert(dropsN.length === 0 && sentN.length === 0, 'W14: a throwing fetch does not drop the event'); + failNet = false; + await dlN.flush(); + assert(sentN.length === 1, 'W14: the event is re-queued and sent once the network recovers'); + await dlN.close(); + } + + // ---- W14: a fetch that never answers is aborted after `timeout` ms ---- + { + (globalThis as any).fetch = (_url: string, opts: any) => new Promise((_res, rej) => { + opts.signal.addEventListener('abort', () => rej(Object.assign(new Error('aborted'), { name: 'AbortError' }))); + }); + const errsT: Error[] = []; + const dlT = new Datalyr({ apiKey: 'dk_test', flushAt: 100, flushInterval: 3_600_000, retryLimit: 0, timeout: 1000, closeTimeout: 1000, + onError: (_e, err) => errsT.push(err) }); + await dlT.track({ userId: 'u', event: 'hangs' }); + const tT = Date.now(); + await dlT.flush(); + const elT = Date.now() - tT; + assert(errsT.length === 1 && errsT[0].name === 'AbortError', `W14: a hung request is aborted and reaches onError (got ${errsT.map((e) => e.name)})`); + assert(elT >= 900 && elT < 3000, `W14: the abort fires at the configured timeout (~1000ms, took ${elT}ms)`); + await dlT.close(); + } + // ---- W3: per-event warnings log once per instance (then only with debug); hooks still fire ---- { const warns: string[] = []; From 90acc0882d360cf7cea6684fc7d219853c54a26b Mon Sep 17 00:00:00 2001 From: czy Date: Sun, 22 Nov 2026 14:26:20 -0600 Subject: [PATCH 4/9] W15: CHANGELOG backfill for 1.0.1-1.0.4, 1.2.2, 1.2.3; registry dates for 1.1.0-1.2.1 Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 47 ++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 44 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index efc1bf7..3649656 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -144,17 +144,42 @@ All notable changes to this project will be documented in this file. - "Batching" is a 10-wide concurrency window, not a single batched HTTP request (one POST per event); the `/batch` endpoint is not used. -## [1.2.1] - 2025-01 +## [1.2.3] - 2026-03-20 + +(entry added later) + +### Added +- `eventId` (a UUID) on every event, so the ingest server can de-duplicate. +- `User-Agent: @datalyr/api/` header on every request. +- `alias()` for linking identities (`$alias` events). + +### Fixed +- `identify()` sends traits as flat properties instead of wrapping them in `$set`. +- `group()` sends traits as flat properties instead of nesting them under `traits`. + +## [1.2.2] - 2026-03-20 + +(entry added later) + +### Fixed +- Events are sent to `https://ingest.datalyr.com/track` instead of `api.datalyr.com`, + which did not record them. +- `SDK_VERSION` constant matches the package version. + +### Changed +- README rewritten with the full API reference. + +## [1.2.1] - 2026-01-01 ### Changed - Complete README rewrite to match iOS/React Native/Web SDK documentation style -## [1.2.0] - 2025-01 +## [1.2.0] - 2026-01-01 ### Changed - Version bump for ecosystem consistency across all Datalyr SDKs -## [1.1.0] - 2025-01 +## [1.1.0] - 2025-09-04 ### Added - Anonymous ID support for complete user journey tracking @@ -166,6 +191,22 @@ All notable changes to this project will be documented in this file. - track() now supports both legacy (userId, event, properties) and new object signature - identify() now supports both legacy and new object signature with anonymousId +## [1.0.4] - 2025-08-19 + +(entry added later) Published to npm; no source history was kept for this version. + +## [1.0.3] - 2025-08-19 + +(entry added later) Published to npm; no source history was kept for this version. + +## [1.0.2] - 2025-08-18 + +(entry added later) Published to npm; no source history was kept for this version. + +## [1.0.1] - 2025-08-18 + +(entry added later) Published to npm; no source history was kept for this version. + ## [1.0.0] - 2024-12 ### Added From 3aac1614c613b6a991d9d72ec5996edab975b206 Mon Sep 17 00:00:00 2001 From: czy Date: Sun, 22 Nov 2026 14:26:30 -0600 Subject: [PATCH 5/9] SEND CHANGE C7: page() stops copying name into properties.url page() put the page name into properties.url when no url was passed, so a name like "Pricing" was recorded as the page URL. name now goes only in properties.name. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 ++ src/index.ts | 7 +++---- tests/test.ts | 4 ++++ 3 files changed, 9 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3649656..deb5ae0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,6 +14,8 @@ All notable changes to this project will be documented in this file. - The API key prefix warning accepts `sk_` keys as well as `dk_`. - `examples/stripe-webhook.js` sends the Stripe customer id as `externalIds: { stripe }` instead of using it as `userId`. +- `page()` no longer copies the page `name` into `properties.url` when no url is passed. + Pass `properties.url` to record the page URL. ## [1.3.4] - 2026-11-14 diff --git a/src/index.ts b/src/index.ts index 19ffdbe..c26a13a 100644 --- a/src/index.ts +++ b/src/index.ts @@ -386,11 +386,10 @@ export class Datalyr { } async page(userId: string, name?: string, properties?: any, anonymousId?: string): Promise { + // `name` goes in properties.name only. It used to be copied into properties.url when no + // url was passed, which recorded a page name (e.g. "Pricing") as the page URL. Pass + // `properties.url` for the real URL. const props: Record = { name, ...properties }; - // P3: ingest derives page_url ONLY from props.url, so a name-only page() call left - // page_url blank server-side. When the caller gives no url, fall back to the page name - // so the pageview is at least addressable (callers who want a real URL should pass one). - if (props.url == null && name != null) props.url = name; return this.track({ userId: userId || undefined, anonymousId, event: '$pageview', properties: props }); } diff --git a/tests/test.ts b/tests/test.ts index a589108..d172e2c 100644 --- a/tests/test.ts +++ b/tests/test.ts @@ -359,6 +359,7 @@ async function main() { const dlW = new Datalyr({ apiKey: 'dk_test', flushAt: 100, flushInterval: 3_600_000 }); await dlW.page('u_page', 'Pricing', { url: 'https://example.com/pricing', plan: 'pro' }, 'anon_page'); await dlW.group('u_group', 'org_1', { name: 'Org One', seats: 5 }); + await dlW.page('u_page2', 'Checkout'); await dlW.track({ userId: 'u_ext', event: 'ext_on', externalIds: { stripe: 'cus_123', crm: 'acct_9' } }); await dlW.track({ userId: 'u_ext', event: 'ext_off' }); await dlW.flush(); @@ -368,6 +369,9 @@ async function main() { assert(!!pv && pv.userId === 'u_page' && pv.anonymousId === 'anon_page' && pv.properties.name === 'Pricing' && pv.properties.url === 'https://example.com/pricing' && pv.properties.plan === 'pro', 'W14: page() sends $pageview with userId, anonymousId, name, the given url and extra properties'); + const pvNoUrl = sentW.find((e) => e.event === '$pageview' && e.userId === 'u_page2'); + assert(!!pvNoUrl && pvNoUrl.properties.name === 'Checkout' && !('url' in pvNoUrl.properties), + `C7: page() without a url sends name only; name is NOT copied into properties.url (got ${JSON.stringify(pvNoUrl && pvNoUrl.properties)})`); const grp = w('$group'); assert(!!grp && grp.userId === 'u_group' && grp.properties.groupId === 'org_1' && From f60a168b0b3bea428c1b2f756a57495a2d9d350b Mon Sep 17 00:00:00 2001 From: czy Date: Sun, 22 Nov 2026 14:26:51 -0600 Subject: [PATCH 6/9] SEND CHANGE C8: trackPurchase() accepts externalIds trackPurchase() options take externalIds (same shape and handling as track()) and send it on the envelope the same way, only when passed. The Stripe example passes the Stripe customer id this way. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 3 +++ examples/stripe-webhook.js | 9 +++++++-- src/index.ts | 14 +++++++++++--- tests/test.ts | 6 ++++++ 4 files changed, 27 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index deb5ae0..5d08317 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,6 +17,9 @@ All notable changes to this project will be documented in this file. - `page()` no longer copies the page `name` into `properties.url` when no url is passed. Pass `properties.url` to record the page URL. +### Added +- `trackPurchase()` options accept `externalIds` (same as `track()`), sent only when passed. + ## [1.3.4] - 2026-11-14 ### Fixed diff --git a/examples/stripe-webhook.js b/examples/stripe-webhook.js index dad83bd..e216e71 100644 --- a/examples/stripe-webhook.js +++ b/examples/stripe-webhook.js @@ -48,7 +48,7 @@ app.post('/webhooks/stripe', // dropped rather than counted as $0. eventId makes redeliveries idempotent (no // double-counted revenue); timestamp backdates delayed replays. await datalyr.trackPurchase( - session.client_reference_id || session.customer, + session.client_reference_id || null, { value: session.amount_total / 100, currency: session.currency, @@ -56,7 +56,12 @@ app.post('/webhooks/stripe', stripeSessionId: session.id, customerEmail: session.customer_details?.email }, - { eventId: event.id, timestamp: event.created } + { + eventId: event.id, + timestamp: event.created, + // guest checkouts have no Stripe customer + externalIds: session.customer ? { stripe: session.customer } : undefined + } ); break; diff --git a/src/index.ts b/src/index.ts index c26a13a..292dd23 100644 --- a/src/index.ts +++ b/src/index.ts @@ -414,13 +414,20 @@ export class Datalyr { * 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 - * warned-and-dropped rather than sent. `opts` forwards eventId (webhook idempotency) and - * timestamp (backdating) exactly like track(). + * warned-and-dropped rather than sent. `opts` forwards eventId (webhook idempotency), + * timestamp (backdating) and externalIds (declared namespaces, e.g. `{ stripe: 'cus_123' }`) + * exactly like track(); externalIds is sent only when passed. */ async trackPurchase( userId: string | null, purchase: PurchaseProperties, - opts?: { anonymousId?: string; eventId?: string; timestamp?: string | Date | number } + opts?: { + anonymousId?: string; + eventId?: string; + timestamp?: string | Date | number; + /** Same as track()'s `externalIds`: `{ namespace: id }`, e.g. `{ stripe: 'cus_123' }`. */ + externalIds?: Record; + } ): Promise { const value = purchase?.value; if (typeof value !== 'number' || !Number.isFinite(value)) { @@ -434,6 +441,7 @@ export class Datalyr { event: 'purchase', eventId: opts?.eventId, timestamp: opts?.timestamp, + externalIds: opts?.externalIds, properties: { ...purchase, value, currency: (purchase.currency || 'USD').toUpperCase() } }); } diff --git a/tests/test.ts b/tests/test.ts index d172e2c..a88c3f9 100644 --- a/tests/test.ts +++ b/tests/test.ts @@ -300,6 +300,12 @@ async function main() { const purch = sentTP.filter((e) => e.event === 'purchase'); assert(purch.length === 1 && purch[0].properties.value === 49.99 && purch[0].properties.currency === 'USD' && purch[0].eventId === 'order_1', '9.D.6: trackPurchase sends value+uppercased currency+eventId for a valid finite value'); + await dlTP.trackPurchase('u', { value: 10 }, { eventId: 'order_ext', externalIds: { stripe: 'cus_42' } }); + await dlTP.flush(); + const purchExt = sentTP.find((e) => e.eventId === 'order_ext'); + assert(!!purchExt && JSON.stringify(purchExt.externalIds) === JSON.stringify({ stripe: 'cus_42' }), + `C8: trackPurchase() sends opts.externalIds on the envelope like track() (got ${JSON.stringify(purchExt && purchExt.externalIds)})`); + assert(!('externalIds' in purch[0]), 'C8: trackPurchase() without externalIds sends no externalIds key'); assert(dropsTP.filter((r) => r === 'validation_error').length === 3, `9.D.6: NaN/non-number/missing value each dropped (got ${dropsTP.filter((r) => r === 'validation_error').length})`); await dlTP.close(); From 5c0fded3e8f21523f5bdc54a199e6715a1a5a737 Mon Sep 17 00:00:00 2001 From: czy Date: Sun, 22 Nov 2026 14:44:43 -0600 Subject: [PATCH 7/9] Stripe example: do not promise a join on externalIds.stripe (ingest links provider ids only from the provider's own connection) Co-Authored-By: Claude Opus 5.5 --- examples/stripe-webhook.js | 12 ++++-------- 1 file changed, 4 insertions(+), 8 deletions(-) diff --git a/examples/stripe-webhook.js b/examples/stripe-webhook.js index e216e71..28b7a89 100644 --- a/examples/stripe-webhook.js +++ b/examples/stripe-webhook.js @@ -8,8 +8,9 @@ // day the event actually happened, not the day the retry arrived. // // IDENTITY: `userId` is YOUR app's user id (the one your client-side identify() uses). -// Never put the Stripe customer id there. Send it as `externalIds: { stripe: }`; -// DATALYR joins it to the customer journey once that Stripe customer is linked to a user. +// Never put the Stripe customer id there. DATALYR links Stripe customers to users through +// its own Stripe connection; a `stripe` id sent from this SDK is stored on the event but +// does not link anyone. Keep it in properties if you want to see it on the event. const express = require('express'); const { Datalyr } = require('@datalyr/api'); const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY); @@ -58,9 +59,7 @@ app.post('/webhooks/stripe', }, { eventId: event.id, - timestamp: event.created, - // guest checkouts have no Stripe customer - externalIds: session.customer ? { stripe: session.customer } : undefined + timestamp: event.created } ); break; @@ -71,7 +70,6 @@ app.post('/webhooks/stripe', // Track subscription start await datalyr.track({ userId: subscription.metadata?.userId, - externalIds: { stripe: subscription.customer }, event: 'subscription_started', eventId: event.id, timestamp: event.created, @@ -103,7 +101,6 @@ app.post('/webhooks/stripe', // Track cancellation await datalyr.track({ userId: canceledSub.metadata?.userId, - externalIds: { stripe: canceledSub.customer }, event: 'subscription_canceled', eventId: event.id, timestamp: event.created, @@ -132,7 +129,6 @@ app.post('/webhooks/stripe', // Track failed payment await datalyr.track({ userId: invoice.metadata?.userId, - externalIds: { stripe: invoice.customer }, event: 'payment_failed', eventId: event.id, timestamp: event.created, From 374af7c72704be7e278bfa64ee66be7ee9121cac Mon Sep 17 00:00:00 2001 From: czy Date: Sun, 22 Nov 2026 14:59:25 -0600 Subject: [PATCH 8/9] Correct externalIds guidance: which namespaces join a user from this SDK (comments and changelog only) Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 4 ++-- src/index.ts | 17 ++++++++--------- 2 files changed, 10 insertions(+), 11 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5d08317..59d8e28 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,8 +12,8 @@ All notable changes to this project will be documented in this file. `MaxListenersExceededWarning` when a client was created per request). Each live client is still flushed once on exit; the listener is removed when the last client is closed. - The API key prefix warning accepts `sk_` keys as well as `dk_`. -- `examples/stripe-webhook.js` sends the Stripe customer id as `externalIds: { stripe }` - instead of using it as `userId`. +- `examples/stripe-webhook.js` no longer uses the Stripe customer id as `userId`. DATALYR + links Stripe customers only through its own Stripe connection. - `page()` no longer copies the page `name` into `properties.url` when no url is passed. Pass `properties.url` to record the page URL. diff --git a/src/index.ts b/src/index.ts index 292dd23..9efc296 100644 --- a/src/index.ts +++ b/src/index.ts @@ -57,14 +57,13 @@ 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: - * `{ 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 - * join the customer journey the moment the same namespace value is bound to an - * account identifier from any producer. Do NOT put private ids in `userId` or - * `anonymousId` — they cannot join there and the workspace health surface will - * flag them as an unjoined namespace. */ + /** Identifiers from other systems: `{ namespace: id }`, e.g. `{ firebase: 'uid_42' }`. + * Never put another system's id in `userId` or `anonymousId`. + * From this SDK, `firebase` joins a user when the same value is bound to that user, + * and `klaviyo` joins after DATALYR's Klaviyo checks. Provider namespaces (`stripe`, + * `shopify`, `whop`, `revenuecat`, `superwall` and the other connected sources) and + * any other namespace are stored on the event but join no one: only the provider's + * own connection in DATALYR links its ids. */ externalIds?: Record; } @@ -415,7 +414,7 @@ export class Datalyr { * 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 * warned-and-dropped rather than sent. `opts` forwards eventId (webhook idempotency), - * timestamp (backdating) and externalIds (declared namespaces, e.g. `{ stripe: 'cus_123' }`) + * timestamp (backdating) and externalIds (see TrackEvent.externalIds) * exactly like track(); externalIds is sent only when passed. */ async trackPurchase( From e94fde4b9745a8527a4262ae4c53f1c547980394 Mon Sep 17 00:00:00 2001 From: czy Date: Sun, 22 Nov 2026 14:59:33 -0600 Subject: [PATCH 9/9] JSDoc: trackPurchase externalIds points to the track() rules Co-Authored-By: Claude Opus 5.5 --- src/index.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/index.ts b/src/index.ts index 9efc296..1128ee9 100644 --- a/src/index.ts +++ b/src/index.ts @@ -424,7 +424,7 @@ export class Datalyr { anonymousId?: string; eventId?: string; timestamp?: string | Date | number; - /** Same as track()'s `externalIds`: `{ namespace: id }`, e.g. `{ stripe: 'cus_123' }`. */ + /** Same as track()'s `externalIds` (see TrackEvent.externalIds for which namespaces join a user). */ externalIds?: Record; } ): Promise {