diff --git a/CHANGELOG.md b/CHANGELOG.md index ade6249..154ee81 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -40,11 +40,23 @@ instead of `void` (see Changed). - added: `N event(s) dropped since the last report (=, ...); getStats() has the totals.` (at most once per flush cycle) - added: `flush(): N event(s) not delivered yet; kept in memory and retried later.` - changed: `close(): N event(s) undelivered after ~Xms (budget Yms)` now ends with `: Q queued, F still in flight.` and counts in-flight events +- Warnings for calls dropped because of invalid `track()`/`identify()`/`alias()`/`group()`/`trackPurchase()` + arguments are logged once per client for each kind, then only with `debug: true`. `onDrop` still + fires for every dropped call. Events dropped while sending are reported by the `N event(s) dropped since the last report` line. +- 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` 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. ### Added - `getStats()`: queued, in-flight and dropped counts, by drop reason. - `flushTimeout` and `maxRetryDuration` options. - Drop reason `auth_refused`. +- `trackPurchase()` options accept `externalIds` (same as `track()`), sent only when passed. ## [1.3.4] - 2026-11-14 @@ -175,17 +187,42 @@ instead of `void` (see Changed). - "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 @@ -197,6 +234,22 @@ instead of `void` (see Changed). - 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 diff --git a/examples/stripe-webhook.js b/examples/stripe-webhook.js index a46b191..28b7a89 100644 --- a/examples/stripe-webhook.js +++ b/examples/stripe-webhook.js @@ -6,6 +6,11 @@ // 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. 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); @@ -44,7 +49,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, @@ -52,7 +57,10 @@ app.post('/webhooks/stripe', stripeSessionId: session.id, customerEmail: session.customer_details?.email }, - { eventId: event.id, timestamp: event.created } + { + eventId: event.id, + timestamp: event.created + } ); break; @@ -61,7 +69,7 @@ app.post('/webhooks/stripe', // Track subscription start await datalyr.track({ - userId: subscription.metadata?.userId || subscription.customer, + userId: subscription.metadata?.userId, event: 'subscription_started', eventId: event.id, timestamp: event.created, @@ -74,15 +82,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 +100,7 @@ app.post('/webhooks/stripe', // Track cancellation await datalyr.track({ - userId: canceledSub.metadata?.userId || canceledSub.customer, + userId: canceledSub.metadata?.userId, event: 'subscription_canceled', eventId: event.id, timestamp: event.created, @@ -101,14 +111,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 +128,7 @@ app.post('/webhooks/stripe', // Track failed payment await datalyr.track({ - userId: invoice.metadata?.userId || invoice.customer, + userId: invoice.metadata?.userId, event: 'payment_failed', eventId: event.id, timestamp: event.created, diff --git a/src/index.ts b/src/index.ts index 420fee5..7970c99 100644 --- a/src/index.ts +++ b/src/index.ts @@ -66,14 +66,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 (Datalyr person contract ): - * `{ 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; } @@ -201,13 +200,20 @@ export class Datalyr { private warnedNoId = false; // one-time warn for calls with neither userId nor anonymousId 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 retryState = new WeakMap(); // per-event retry clock; WeakMap → no payload pollution private inFlight = 0; // events taken from the queue by a pass and not settled yet private nextSeq = 0; // arrival order, so the cap always evicts the oldest private seqOf = new WeakMap(); private droppedByReason: Record = Object.fromEntries(ALL_DROP_REASONS.map((r) => [r, 0])) as Record; private reportedByReason: Record = Object.fromEntries(ALL_DROP_REASONS.map((r) => [r, 0])) as Record; - 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; // @@ -244,8 +250,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 @@ -281,16 +287,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.startDrain()?.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.startDrain()?.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 @@ -301,6 +328,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 */ } @@ -339,7 +379,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; } @@ -404,7 +444,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; } @@ -417,7 +457,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; } @@ -437,11 +477,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 }); } @@ -454,7 +493,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; } @@ -466,17 +505,24 @@ 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 (see TrackEvent.externalIds) + * 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` (see TrackEvent.externalIds for which namespaces join a user). */ + externalIds?: Record; + } ): 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; } @@ -486,6 +532,7 @@ export class Datalyr { event: 'purchase', eventId: opts?.eventId, timestamp: opts?.timestamp, + externalIds: opts?.externalIds, properties: { ...purchase, value, currency: (purchase.currency || 'USD').toUpperCase() } }); } @@ -950,11 +997,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(); this.reportDrops(); const unsent = this.pendingCount(); diff --git a/tests/test.ts b/tests/test.ts index 44cf7b3..156f8fe 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; @@ -16,6 +17,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); @@ -255,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(); @@ -302,6 +353,134 @@ 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.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(); + 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 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' && + 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 new Promise((r) => setTimeout(r, 1100)); // FX-047: a failed event waits out its backoff (first one at most 1 s) + 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 ---- + // Send-side drops (here a final 400) are reported by FX-047's summary: ONE line per flush + // cycle, never one per event. Validation drops use warnOnce: one line per kind. + { + const warns: string[] = []; + const origWarn = console.warn; + console.warn = (...args: any[]) => { warns.push(args.map(String).join(' ')); }; + try { + (globalThis as any).fetch = async () => ({ ok: false, status: 400, statusText: 'bad request', 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' }); + await dl3w.flush(); + const dropLines = warns.filter((w) => w.includes('dropped since the last report')); + assert(drops3.filter((r) => r === 'permanent_client_error').length === 2, + `W3: both events still reach onDrop('permanent_client_error') (got ${drops3.filter((r) => r === 'permanent_client_error').length})`); + assert(dropLines.length === 1 && dropLines[0].includes('permanent_client_error=2'), + `W3: two final-4xx drops in one flush log ONE summary line, not one per event (got ${JSON.stringify(dropLines)})`); + + 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); }