@funnelsgrove/analytics 0.2.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -2,3 +2,19 @@ export declare const sanitizeAnalyticsUrl: (value: unknown, sensitiveKeys?: RegE
2
2
  export declare const analyticsUrlSanitizerSource: string;
3
3
  /** Snapshot before filtering so custom toJSON values cannot bypass the export policy. */
4
4
  export declare const sanitizeAnalyticsExport: (value: unknown) => unknown;
5
+ export type RudderstackTrackEvent = {
6
+ type: 'track';
7
+ event: string;
8
+ userId: string;
9
+ messageId: string;
10
+ timestamp?: string;
11
+ properties: Record<string, unknown>;
12
+ };
13
+ /** Provider-neutral normalized input shared by browser and server destinations. */
14
+ export declare const toRudderstackTrackEvent: (input: {
15
+ distinctId: string;
16
+ event: string;
17
+ messageId: string;
18
+ timestamp?: string;
19
+ properties?: Record<string, unknown>;
20
+ }) => RudderstackTrackEvent;
@@ -46,3 +46,11 @@ export const sanitizeAnalyticsExport = (value) => {
46
46
  };
47
47
  return project(JSON.parse(json), 0);
48
48
  };
49
+ /** Provider-neutral normalized input shared by browser and server destinations. */
50
+ export const toRudderstackTrackEvent = (input) => {
51
+ const properties = Object.assign({}, input.properties);
52
+ delete properties.distinct_id;
53
+ delete properties.$insert_id;
54
+ delete properties.$groups;
55
+ return sanitizeAnalyticsExport(Object.assign(Object.assign({ type: 'track', event: input.event, userId: input.distinctId, messageId: input.messageId }, (input.timestamp ? { timestamp: input.timestamp } : {})), { properties }));
56
+ };
@@ -0,0 +1,29 @@
1
+ export type BrowserDeliveryOptions = {
2
+ batchSize: number;
3
+ flushIntervalMs: number;
4
+ };
5
+ /** Owns a bounded, in-memory, best-effort delivery queue; it is not a durable outbox. */
6
+ export declare class BrowserEventDelivery {
7
+ private readonly target;
8
+ private readonly batchSize;
9
+ private readonly flushIntervalMs;
10
+ private queue;
11
+ private queuedBytes;
12
+ private sendingCount;
13
+ private sendingBytes;
14
+ private timer;
15
+ private inFlight;
16
+ constructor(options: Partial<BrowserDeliveryOptions>, target: {
17
+ enabled: boolean;
18
+ endpoint: string;
19
+ batchPrefix: string;
20
+ headers?: Record<string, string>;
21
+ beacon?: boolean;
22
+ });
23
+ enqueue(event: unknown): boolean;
24
+ flush(): Promise<number>;
25
+ private trim;
26
+ private schedule;
27
+ private drain;
28
+ private send;
29
+ }
@@ -0,0 +1,181 @@
1
+ import { canUseDom } from './sdk-user-id.storage.js';
2
+ import { sanitizeAnalyticsExport } from './analytics-export.js';
3
+ const MAX_EVENTS = 200;
4
+ const MAX_BYTES = 512 * 1024;
5
+ const MAX_EVENT_BYTES = 16 * 1024;
6
+ const MAX_BATCH_BYTES = 48 * 1024;
7
+ const MAX_AGE_MS = 5 * 60000;
8
+ const FLUSH_BUDGET_MS = 2000;
9
+ const RETRY_DELAY_MS = 1500;
10
+ const encoder = new TextEncoder();
11
+ const boundedOption = (value, fallback, maximum) => value !== undefined && Number.isFinite(value) && value > 0 ? Math.min(Math.floor(value) || 1, maximum) : fallback;
12
+ const retryDelay = (response) => {
13
+ var _a, _b;
14
+ const value = (_b = (_a = response.headers) === null || _a === void 0 ? void 0 : _a.get('retry-after')) === null || _b === void 0 ? void 0 : _b.trim();
15
+ if (!value)
16
+ return RETRY_DELAY_MS;
17
+ if (/^\d+$/.test(value))
18
+ return Math.max(RETRY_DELAY_MS, Number(value) * 1000);
19
+ const date = Date.parse(value);
20
+ return Number.isFinite(date) ? Math.max(RETRY_DELAY_MS, date - Date.now()) : RETRY_DELAY_MS;
21
+ };
22
+ /** Owns a bounded, in-memory, best-effort delivery queue; it is not a durable outbox. */
23
+ export class BrowserEventDelivery {
24
+ constructor(options, target) {
25
+ this.target = target;
26
+ this.queue = [];
27
+ this.queuedBytes = 0;
28
+ this.sendingCount = 0;
29
+ this.sendingBytes = 0;
30
+ this.timer = null;
31
+ this.inFlight = null;
32
+ this.batchSize = boundedOption(options.batchSize, 20, 200);
33
+ this.flushIntervalMs = boundedOption(options.flushIntervalMs, 1500, 60000);
34
+ }
35
+ enqueue(event) {
36
+ if (!this.target.enabled)
37
+ return true;
38
+ let json;
39
+ try {
40
+ json = JSON.stringify(sanitizeAnalyticsExport(event));
41
+ }
42
+ catch (_a) {
43
+ return false;
44
+ }
45
+ if (!json)
46
+ return false;
47
+ const bytes = encoder.encode(json).length;
48
+ if (bytes > MAX_EVENT_BYTES)
49
+ return false;
50
+ const now = performance.now();
51
+ this.queue.push({ json, bytes, createdAt: now, attempts: 0, notBefore: now });
52
+ this.trim(now);
53
+ if (this.queue.length >= this.batchSize)
54
+ void this.flush();
55
+ else
56
+ this.schedule();
57
+ return true;
58
+ }
59
+ flush() {
60
+ if (this.inFlight)
61
+ return this.inFlight;
62
+ if (this.timer !== null) {
63
+ if (canUseDom())
64
+ window.clearTimeout(this.timer);
65
+ this.timer = null;
66
+ }
67
+ this.inFlight = this.drain().finally(() => {
68
+ this.inFlight = null;
69
+ this.schedule();
70
+ });
71
+ return this.inFlight;
72
+ }
73
+ trim(now) {
74
+ this.queue = this.queue.filter((event) => now - event.createdAt < MAX_AGE_MS && event.attempts < 3
75
+ && event.notBefore - event.createdAt < MAX_AGE_MS);
76
+ this.queuedBytes = this.queue.reduce((total, event) => total + event.bytes, 0);
77
+ while (this.queue.length + this.sendingCount > MAX_EVENTS || this.queuedBytes + this.sendingBytes > MAX_BYTES) {
78
+ const removed = this.queue.shift();
79
+ if (!removed)
80
+ break;
81
+ this.queuedBytes -= removed.bytes;
82
+ }
83
+ }
84
+ schedule() {
85
+ if (!canUseDom() || this.timer !== null || this.inFlight || this.queue.length === 0)
86
+ return;
87
+ const now = performance.now();
88
+ const nextAttempt = Math.min(...this.queue.map((event) => event.notBefore));
89
+ const nextExpiry = Math.min(...this.queue.map((event) => event.createdAt + MAX_AGE_MS));
90
+ const delay = Math.max(0, Math.min(Math.max(this.flushIntervalMs, nextAttempt - now), nextExpiry - now));
91
+ this.timer = window.setTimeout(() => { this.timer = null; void this.flush(); }, delay);
92
+ }
93
+ async drain() {
94
+ var _a;
95
+ this.trim(performance.now());
96
+ const deadline = performance.now() + FLUSH_BUDGET_MS;
97
+ const available = this.queue.length;
98
+ let processed = 0;
99
+ let accepted = 0;
100
+ const prefix = this.target.batchPrefix;
101
+ while (processed < available && performance.now() < deadline) {
102
+ const batch = [];
103
+ let bytes = encoder.encode(prefix).length + 2;
104
+ for (let index = 0; index < this.queue.length && batch.length < this.batchSize && processed + batch.length < available;) {
105
+ const event = this.queue[index];
106
+ if (event.notBefore > performance.now()) {
107
+ index++;
108
+ continue;
109
+ }
110
+ const addedBytes = event.bytes + (batch.length ? 1 : 0);
111
+ if (bytes + addedBytes > MAX_BATCH_BYTES)
112
+ break;
113
+ this.queue.splice(index, 1);
114
+ this.queuedBytes -= event.bytes;
115
+ batch.push(event);
116
+ bytes += addedBytes;
117
+ }
118
+ if (batch.length === 0)
119
+ break;
120
+ this.sendingCount = batch.length;
121
+ this.sendingBytes = batch.reduce((sum, event) => sum + event.bytes, 0);
122
+ const result = await this.send(`${prefix}${batch.map((event) => event.json).join(',')}]}`, deadline - performance.now());
123
+ this.sendingCount = 0;
124
+ this.sendingBytes = 0;
125
+ processed += batch.length;
126
+ if (result.kind === 'accepted')
127
+ accepted += batch.length;
128
+ if (result.kind === 'retry') {
129
+ const notBefore = performance.now() + ((_a = result.retryDelayMs) !== null && _a !== void 0 ? _a : RETRY_DELAY_MS);
130
+ for (const event of batch) {
131
+ event.attempts++;
132
+ event.notBefore = notBefore;
133
+ }
134
+ this.queue.unshift(...batch);
135
+ }
136
+ this.trim(performance.now());
137
+ }
138
+ return accepted;
139
+ }
140
+ async send(payload, budgetMs) {
141
+ const endpoint = this.target.endpoint;
142
+ if (this.target.beacon && canUseDom() && typeof navigator !== 'undefined' && typeof navigator.sendBeacon === 'function') {
143
+ try {
144
+ if (navigator.sendBeacon(endpoint, new Blob([payload], { type: 'application/json' })))
145
+ return { kind: 'accepted' };
146
+ }
147
+ catch ( /* A rejected beacon can still use the bounded fetch path. */_a) { /* A rejected beacon can still use the bounded fetch path. */ }
148
+ }
149
+ const controller = new AbortController();
150
+ let timer;
151
+ const timedOut = new Promise((resolve) => {
152
+ timer = setTimeout(() => {
153
+ controller.abort();
154
+ resolve({ kind: 'retry' });
155
+ }, Math.max(0, budgetMs));
156
+ });
157
+ const request = async () => {
158
+ var _a;
159
+ try {
160
+ const response = await fetch(endpoint, {
161
+ method: 'POST', headers: Object.assign({ 'Content-Type': 'application/json' }, this.target.headers), body: payload,
162
+ keepalive: true, signal: controller.signal,
163
+ });
164
+ await ((_a = response.body) === null || _a === void 0 ? void 0 : _a.cancel());
165
+ if (response.ok)
166
+ return { kind: 'accepted' };
167
+ return [408, 429, 500, 502, 503, 504].includes(response.status)
168
+ ? { kind: 'retry', retryDelayMs: retryDelay(response) } : { kind: 'drop' };
169
+ }
170
+ catch (_b) {
171
+ return { kind: 'retry' };
172
+ }
173
+ };
174
+ try {
175
+ return await Promise.race([request(), timedOut]);
176
+ }
177
+ finally {
178
+ clearTimeout(timer);
179
+ }
180
+ }
181
+ }
@@ -1,5 +1,6 @@
1
1
  import { isSystemPreviewHostname } from '@funnelsgrove/runtime';
2
2
  import { META_PIXEL_ENABLED, META_PIXEL_ID, STRIPE_ACTIVE_MODE } from './runtime-api.config.js';
3
+ import { buildPurchaseAnalyticsAttributes } from './purchase-attributes.service.js';
3
4
  const toNumber = (value) => {
4
5
  if (typeof value !== 'number' || !Number.isFinite(value)) {
5
6
  return null;
@@ -10,10 +11,9 @@ const toCurrency = (value) => {
10
11
  return typeof value === 'string' && value.trim() ? value.trim().toUpperCase() : undefined;
11
12
  };
12
13
  const buildCommerceCustomData = (metadata = {}) => {
13
- var _a;
14
- const amountCents = toNumber(metadata.amountCents);
15
- const value = (_a = toNumber(metadata.value)) !== null && _a !== void 0 ? _a : (amountCents === null ? null : amountCents / 100);
16
- const currency = toCurrency(metadata.currency);
14
+ const attributes = buildPurchaseAnalyticsAttributes(metadata);
15
+ const value = toNumber(attributes.value);
16
+ const currency = toCurrency(attributes.currency);
17
17
  const customData = {};
18
18
  if (currency) {
19
19
  customData.currency = currency;
@@ -1,22 +1,5 @@
1
- export type PostHogDeliveryOptions = {
2
- batchSize: number;
3
- flushIntervalMs: number;
4
- };
5
- /** Owns a bounded, in-memory, best-effort delivery queue; it is not a durable outbox. */
6
- export declare class PostHogDelivery {
7
- private readonly batchSize;
8
- private readonly flushIntervalMs;
9
- private queue;
10
- private queuedBytes;
11
- private sendingCount;
12
- private sendingBytes;
13
- private timer;
14
- private inFlight;
1
+ import { BrowserEventDelivery, type BrowserDeliveryOptions } from './browser-event-delivery.js';
2
+ export type PostHogDeliveryOptions = BrowserDeliveryOptions;
3
+ export declare class PostHogDelivery extends BrowserEventDelivery {
15
4
  constructor(options: Partial<PostHogDeliveryOptions>);
16
- enqueue(event: unknown): boolean;
17
- flush(): Promise<number>;
18
- private trim;
19
- private schedule;
20
- private drain;
21
- private send;
22
5
  }
@@ -1,181 +1,10 @@
1
- import { canUseDom } from './sdk-user-id.storage.js';
2
- import { sanitizeAnalyticsExport } from './analytics-export.js';
1
+ import { BrowserEventDelivery } from './browser-event-delivery.js';
3
2
  import { hasPostHogRuntimeConfig, POSTHOG_API_HOST, POSTHOG_PROJECT_API_KEY } from './runtime-api.config.js';
4
- const MAX_EVENTS = 200;
5
- const MAX_BYTES = 512 * 1024;
6
- const MAX_EVENT_BYTES = 16 * 1024;
7
- const MAX_BATCH_BYTES = 48 * 1024;
8
- const MAX_AGE_MS = 5 * 60000;
9
- const FLUSH_BUDGET_MS = 2000;
10
- const RETRY_DELAY_MS = 1500;
11
- const encoder = new TextEncoder();
12
- const boundedOption = (value, fallback, maximum) => value !== undefined && Number.isFinite(value) && value > 0 ? Math.min(Math.floor(value) || 1, maximum) : fallback;
13
- const retryDelay = (response) => {
14
- var _a, _b;
15
- const value = (_b = (_a = response.headers) === null || _a === void 0 ? void 0 : _a.get('retry-after')) === null || _b === void 0 ? void 0 : _b.trim();
16
- if (!value)
17
- return RETRY_DELAY_MS;
18
- if (/^\d+$/.test(value))
19
- return Math.max(RETRY_DELAY_MS, Number(value) * 1000);
20
- const date = Date.parse(value);
21
- return Number.isFinite(date) ? Math.max(RETRY_DELAY_MS, date - Date.now()) : RETRY_DELAY_MS;
22
- };
23
- /** Owns a bounded, in-memory, best-effort delivery queue; it is not a durable outbox. */
24
- export class PostHogDelivery {
3
+ export class PostHogDelivery extends BrowserEventDelivery {
25
4
  constructor(options) {
26
- this.queue = [];
27
- this.queuedBytes = 0;
28
- this.sendingCount = 0;
29
- this.sendingBytes = 0;
30
- this.timer = null;
31
- this.inFlight = null;
32
- this.batchSize = boundedOption(options.batchSize, 20, 200);
33
- this.flushIntervalMs = boundedOption(options.flushIntervalMs, 1500, 60000);
34
- }
35
- enqueue(event) {
36
- if (!hasPostHogRuntimeConfig())
37
- return true;
38
- let json;
39
- try {
40
- json = JSON.stringify(sanitizeAnalyticsExport(event));
41
- }
42
- catch (_a) {
43
- return false;
44
- }
45
- if (!json)
46
- return false;
47
- const bytes = encoder.encode(json).length;
48
- if (bytes > MAX_EVENT_BYTES)
49
- return false;
50
- const now = performance.now();
51
- this.queue.push({ json, bytes, createdAt: now, attempts: 0, notBefore: now });
52
- this.trim(now);
53
- if (this.queue.length >= this.batchSize)
54
- void this.flush();
55
- else
56
- this.schedule();
57
- return true;
58
- }
59
- flush() {
60
- if (this.inFlight)
61
- return this.inFlight;
62
- if (this.timer !== null) {
63
- if (canUseDom())
64
- window.clearTimeout(this.timer);
65
- this.timer = null;
66
- }
67
- this.inFlight = this.drain().finally(() => {
68
- this.inFlight = null;
69
- this.schedule();
70
- });
71
- return this.inFlight;
72
- }
73
- trim(now) {
74
- this.queue = this.queue.filter((event) => now - event.createdAt < MAX_AGE_MS && event.attempts < 3
75
- && event.notBefore - event.createdAt < MAX_AGE_MS);
76
- this.queuedBytes = this.queue.reduce((total, event) => total + event.bytes, 0);
77
- while (this.queue.length + this.sendingCount > MAX_EVENTS || this.queuedBytes + this.sendingBytes > MAX_BYTES) {
78
- const removed = this.queue.shift();
79
- if (!removed)
80
- break;
81
- this.queuedBytes -= removed.bytes;
82
- }
83
- }
84
- schedule() {
85
- if (!canUseDom() || this.timer !== null || this.inFlight || this.queue.length === 0)
86
- return;
87
- const now = performance.now();
88
- const nextAttempt = Math.min(...this.queue.map((event) => event.notBefore));
89
- const nextExpiry = Math.min(...this.queue.map((event) => event.createdAt + MAX_AGE_MS));
90
- const delay = Math.max(0, Math.min(Math.max(this.flushIntervalMs, nextAttempt - now), nextExpiry - now));
91
- this.timer = window.setTimeout(() => { this.timer = null; void this.flush(); }, delay);
92
- }
93
- async drain() {
94
- var _a;
95
- this.trim(performance.now());
96
- const deadline = performance.now() + FLUSH_BUDGET_MS;
97
- const available = this.queue.length;
98
- let processed = 0;
99
- let accepted = 0;
100
- const prefix = `{"api_key":${JSON.stringify(POSTHOG_PROJECT_API_KEY)},"batch":[`;
101
- while (processed < available && performance.now() < deadline) {
102
- const batch = [];
103
- let bytes = encoder.encode(prefix).length + 2;
104
- for (let index = 0; index < this.queue.length && batch.length < this.batchSize && processed + batch.length < available;) {
105
- const event = this.queue[index];
106
- if (event.notBefore > performance.now()) {
107
- index++;
108
- continue;
109
- }
110
- const addedBytes = event.bytes + (batch.length ? 1 : 0);
111
- if (bytes + addedBytes > MAX_BATCH_BYTES)
112
- break;
113
- this.queue.splice(index, 1);
114
- this.queuedBytes -= event.bytes;
115
- batch.push(event);
116
- bytes += addedBytes;
117
- }
118
- if (batch.length === 0)
119
- break;
120
- this.sendingCount = batch.length;
121
- this.sendingBytes = batch.reduce((sum, event) => sum + event.bytes, 0);
122
- const result = await this.send(`${prefix}${batch.map((event) => event.json).join(',')}]}`, deadline - performance.now());
123
- this.sendingCount = 0;
124
- this.sendingBytes = 0;
125
- processed += batch.length;
126
- if (result.kind === 'accepted')
127
- accepted += batch.length;
128
- if (result.kind === 'retry') {
129
- const notBefore = performance.now() + ((_a = result.retryDelayMs) !== null && _a !== void 0 ? _a : RETRY_DELAY_MS);
130
- for (const event of batch) {
131
- event.attempts++;
132
- event.notBefore = notBefore;
133
- }
134
- this.queue.unshift(...batch);
135
- }
136
- this.trim(performance.now());
137
- }
138
- return accepted;
139
- }
140
- async send(payload, budgetMs) {
141
- const endpoint = `${POSTHOG_API_HOST}/batch/`;
142
- if (canUseDom() && typeof navigator !== 'undefined' && typeof navigator.sendBeacon === 'function') {
143
- try {
144
- if (navigator.sendBeacon(endpoint, new Blob([payload], { type: 'application/json' })))
145
- return { kind: 'accepted' };
146
- }
147
- catch ( /* A rejected beacon can still use the bounded fetch path. */_a) { /* A rejected beacon can still use the bounded fetch path. */ }
148
- }
149
- const controller = new AbortController();
150
- let timer;
151
- const timedOut = new Promise((resolve) => {
152
- timer = setTimeout(() => {
153
- controller.abort();
154
- resolve({ kind: 'retry' });
155
- }, Math.max(0, budgetMs));
5
+ super(options, {
6
+ enabled: hasPostHogRuntimeConfig(), endpoint: `${POSTHOG_API_HOST}/batch/`,
7
+ batchPrefix: `{"api_key":${JSON.stringify(POSTHOG_PROJECT_API_KEY)},"batch":[`, beacon: true,
156
8
  });
157
- const request = async () => {
158
- var _a;
159
- try {
160
- const response = await fetch(endpoint, {
161
- method: 'POST', headers: { 'Content-Type': 'application/json' }, body: payload,
162
- keepalive: true, signal: controller.signal,
163
- });
164
- await ((_a = response.body) === null || _a === void 0 ? void 0 : _a.cancel());
165
- if (response.ok)
166
- return { kind: 'accepted' };
167
- return [408, 429, 500, 502, 503, 504].includes(response.status)
168
- ? { kind: 'retry', retryDelayMs: retryDelay(response) } : { kind: 'drop' };
169
- }
170
- catch (_b) {
171
- return { kind: 'retry' };
172
- }
173
- };
174
- try {
175
- return await Promise.race([request(), timedOut]);
176
- }
177
- finally {
178
- clearTimeout(timer);
179
- }
180
9
  }
181
10
  }
@@ -1,5 +1,6 @@
1
1
  import { type PostHogDeliveryOptions } from './posthog-delivery.js';
2
2
  import { type FunnelStepExitReason, type FunnelStepType } from '@funnelsgrove/runtime';
3
+ export type PublicAnalyticsFeatureFlags = Readonly<Record<string, string | boolean | null | undefined>>;
3
4
  export type PublicSdkTrackEventInput = {
4
5
  eventType: string;
5
6
  userId?: string;
@@ -18,7 +19,7 @@ export type PublicSdkTrackEventInput = {
18
19
  payload?: Record<string, unknown>;
19
20
  context?: Record<string, unknown>;
20
21
  metadata?: Record<string, unknown>;
21
- featureFlags?: Record<string, string | null | undefined>;
22
+ featureFlags?: PublicAnalyticsFeatureFlags;
22
23
  };
23
24
  export type PublicSdkStepStartInput = {
24
25
  userId?: string;
@@ -29,7 +30,7 @@ export type PublicSdkStepStartInput = {
29
30
  stepContractVersion: number;
30
31
  startedAt: string;
31
32
  metadata?: Record<string, unknown>;
32
- featureFlags?: Record<string, string | null | undefined>;
33
+ featureFlags?: PublicAnalyticsFeatureFlags;
33
34
  };
34
35
  export type PublicSdkStepEndInput = {
35
36
  userId?: string;
@@ -42,7 +43,7 @@ export type PublicSdkStepEndInput = {
42
43
  endedAt: string;
43
44
  selected?: Record<string, unknown>;
44
45
  metadata?: Record<string, unknown>;
45
- featureFlags?: Record<string, string | null | undefined>;
46
+ featureFlags?: PublicAnalyticsFeatureFlags;
46
47
  };
47
48
  export type PublicSdkStepExitInput = {
48
49
  userId?: string;
@@ -56,7 +57,7 @@ export type PublicSdkStepExitInput = {
56
57
  exitReason: FunnelStepExitReason;
57
58
  stepContractVersion: number;
58
59
  metadata?: Record<string, unknown>;
59
- featureFlags?: Record<string, string | null | undefined>;
60
+ featureFlags?: PublicAnalyticsFeatureFlags;
60
61
  };
61
62
  export type PublicSdkStepEngagedInput = {
62
63
  userId?: string;
@@ -70,7 +71,7 @@ export type PublicSdkStepEngagedInput = {
70
71
  durationMs: number;
71
72
  engagementThresholdMs: number;
72
73
  metadata?: Record<string, unknown>;
73
- featureFlags?: Record<string, string | null | undefined>;
74
+ featureFlags?: PublicAnalyticsFeatureFlags;
74
75
  };
75
76
  export type PublicSdkConversionCallbackInput = {
76
77
  userId?: string;
@@ -82,7 +83,7 @@ export type PublicSdkConversionCallbackInput = {
82
83
  stepType?: string;
83
84
  stepContractVersion?: number;
84
85
  metadata?: Record<string, unknown>;
85
- featureFlags?: Record<string, string | null | undefined>;
86
+ featureFlags?: PublicAnalyticsFeatureFlags;
86
87
  };
87
88
  export type PublicSdkFunnelConversionCallbackInput = PublicSdkConversionCallbackInput & {
88
89
  stepContractVersion: number;
@@ -110,6 +111,7 @@ type SecureBootstrapCrypto = Pick<Crypto, 'getRandomValues'> & {
110
111
  export declare const createBootstrapIdempotencyKey: (secureCrypto?: SecureBootstrapCrypto) => string;
111
112
  export declare class PublicAnalyticsSdkService {
112
113
  private readonly delivery;
114
+ private readonly rudderstack;
113
115
  private userId;
114
116
  constructor(options?: Partial<PublicAnalyticsSdkOptions>);
115
117
  getCurrentUserId(): string;
@@ -1,3 +1,4 @@
1
+ import { RudderstackDelivery } from './rudderstack-delivery.js';
1
2
  import { PostHogDelivery } from './posthog-delivery.js';
2
3
  import { FUNNEL_ANALYTICS_EVENT_CONTRACTS, funnelSdkService, getPaywallUser, FUNNEL_STEP_CONTRACTS, } from '@funnelsgrove/runtime';
3
4
  import { APP_DEALS_API_BASE_URL, FUNNEL_ID, FUNNEL_VERSION_ID, getFunnelSdkPublishableKey, PROJECT_ID, } from './runtime-api.config.js';
@@ -131,7 +132,10 @@ const normalizeFeatureFlags = (featureFlags) => {
131
132
  return {};
132
133
  }
133
134
  return Object.fromEntries(Object.entries(featureFlags)
134
- .map(([key, value]) => [key.trim(), (value === null || value === void 0 ? void 0 : value.trim()) || ''])
135
+ .map(([key, value]) => [
136
+ key.trim(),
137
+ typeof value === 'boolean' ? String(value) : (value === null || value === void 0 ? void 0 : value.trim()) || '',
138
+ ])
135
139
  .filter(([key, value]) => Boolean(key && value)));
136
140
  };
137
141
  const buildFeatureFlagProperties = (featureFlags) => {
@@ -179,6 +183,7 @@ export class PublicAnalyticsSdkService {
179
183
  constructor(options = {}) {
180
184
  this.userId = null;
181
185
  this.delivery = new PostHogDelivery(options);
186
+ this.rudderstack = RudderstackDelivery.create(options);
182
187
  googleTagService.initialize();
183
188
  }
184
189
  getCurrentUserId() {
@@ -283,7 +288,7 @@ export class PublicAnalyticsSdkService {
283
288
  }
284
289
  }
285
290
  trackTrusted(event) {
286
- var _a, _b, _c, _d, _e, _f;
291
+ var _a, _b, _c, _d, _e, _f, _g;
287
292
  const eventType = asString(event.eventType);
288
293
  if (!eventType) {
289
294
  return null;
@@ -316,7 +321,9 @@ export class PublicAnalyticsSdkService {
316
321
  metadata,
317
322
  featureFlags: normalizeFeatureFlags(event.featureFlags),
318
323
  };
319
- return this.delivery.enqueue(this.toPostHogEvent(envelope)) ? envelope.eventId : null;
324
+ const normalized = this.toPostHogEvent(envelope);
325
+ (_g = this.rudderstack) === null || _g === void 0 ? void 0 : _g.enqueue(normalized);
326
+ return this.delivery.enqueue(normalized) ? envelope.eventId : null;
320
327
  }
321
328
  trackContractCallback(eventName, input) {
322
329
  const contract = FUNNEL_ANALYTICS_EVENT_CONTRACTS[eventName];
@@ -517,8 +524,11 @@ export class PublicAnalyticsSdkService {
517
524
  featureFlags: input.featureFlags,
518
525
  });
519
526
  }
520
- flush() {
521
- return this.delivery.flush();
527
+ async flush() {
528
+ if (!this.rudderstack)
529
+ return this.delivery.flush();
530
+ const [accepted] = await Promise.all([this.delivery.flush(), this.rudderstack.flush()]);
531
+ return accepted;
522
532
  }
523
533
  ensureUserId() {
524
534
  const bound = getPaywallUser();
@@ -1,5 +1,6 @@
1
1
  export type PurchaseAnalyticsAttributesInput = {
2
2
  amountCents?: unknown;
3
+ money?: unknown;
3
4
  attribution?: unknown;
4
5
  couponId?: unknown;
5
6
  currency?: unknown;
@@ -1,4 +1,5 @@
1
1
  import { sanitizeAnalyticsUrl } from './analytics-export.js';
2
+ import { moneyToMajor, normalizeProviderMoney } from '@funnelsgrove/runtime';
2
3
  const STRIPE_METADATA_KEY_MAX_LENGTH = 40;
3
4
  const STRIPE_METADATA_VALUE_MAX_LENGTH = 500;
4
5
  const FLAT_ATTRIBUTION_KEYS = new Set([
@@ -118,17 +119,23 @@ export const currentBrowserPurchaseUrl = () => {
118
119
  return sanitizePurchaseUrl((_a = window.location) === null || _a === void 0 ? void 0 : _a.href);
119
120
  };
120
121
  export const buildPurchaseAnalyticsAttributes = (input = {}, options = {}) => {
121
- var _a, _b;
122
+ var _a, _b, _c, _d;
122
123
  const document = asRecord(input.funnelUserDocument);
123
124
  const attribution = asRecord((_a = input.attribution) !== null && _a !== void 0 ? _a : document.attribution);
124
125
  const attributionContext = asRecord(attribution.context);
125
126
  const progressAttributes = asRecord(asRecord(document.progress).attributes);
126
127
  const transactionInfo = asRecord(document.transactionInfo);
127
128
  const amountCents = toNumber(input.amountCents);
128
- const value = (_b = toNumber(input.value)) !== null && _b !== void 0 ? _b : (amountCents === undefined ? undefined : amountCents / 100);
129
+ const money = (_b = normalizeProviderMoney(input.money)) !== null && _b !== void 0 ? _b : undefined;
130
+ const hasExplicitMoney = input.money !== undefined && input.money !== null;
131
+ const value = (_c = toNumber(input.value)) !== null && _c !== void 0 ? _c : (money
132
+ ? moneyToMajor(money)
133
+ : hasExplicitMoney || amountCents === undefined
134
+ ? undefined
135
+ : amountCents / 100);
129
136
  const funnelUserId = firstString(input.userId, input.user_id, input.cwClientUserId, input.cw_client_user_id);
130
137
  const lastNonOrganicTouch = resolveLastNonOrganicTouch(input, attribution);
131
- return buildDefinedRecord(Object.assign(Object.assign({}, normalizeAttributionTouch(lastNonOrganicTouch)), { currency: toCurrency(input.currency), value, plan_id: firstString(input.planId, input.plan_id), provider_plan_id: firstString(input.providerPlanId, input.provider_plan_id), coupon_id: firstString(input.couponId, input.coupon_id), environment: firstString(input.environment), checkout_start_source: firstString(input.checkoutStartSource, input.checkout_start_source), step_id: firstString(input.stepId, input.step_id), step_name: firstString(input.stepName, input.step_name), step_type: firstString(input.stepType, input.step_type), user_id: funnelUserId, cw_client_user_id: funnelUserId, project_id: firstString(input.projectId, input.project_id), funnel_id: firstString(input.funnelId, input.funnel_id), funnel_version: firstString(input.funnelVersion, input.funnelVersionId, input.funnel_version), ip_address: firstString(input.ipAddress, input.ip_address, transactionInfo.ipAddress, transactionInfo.ip_address), user_agent: firstString(input.userAgent, input.user_agent, attributionContext.userAgent), timezone: firstString(input.timezone, input.time_zone, progressAttributes.timezone, progressAttributes.time_zone, document.timezone, document.time_zone, attributionContext.timezone, attributionContext.time_zone), geo_city: firstString(input.geoCity, input.geo_city, progressAttributes.geo_city, progressAttributes.geoCity, document.geo_city, document.geoCity, asRecord(document.geo).city, attributionContext.geo_city, attributionContext.geoCity, attributionContext.cityName, attributionContext.city), geo_country: firstString(input.geoCountry, input.geo_country, progressAttributes.geo_country, progressAttributes.geoCountry, document.geo_country, document.geoCountry, asRecord(document.geo).country, attributionContext.geo_country, attributionContext.geoCountry, attributionContext.countryName, attributionContext.countryCode, attributionContext.country), transaction_id: firstString(input.transactionId, input.transaction_id), url: options.includeUrl
138
+ return buildDefinedRecord(Object.assign(Object.assign({}, normalizeAttributionTouch(lastNonOrganicTouch)), { currency: (_d = money === null || money === void 0 ? void 0 : money.currency) !== null && _d !== void 0 ? _d : toCurrency(input.currency), value, plan_id: firstString(input.planId, input.plan_id), provider_plan_id: firstString(input.providerPlanId, input.provider_plan_id), coupon_id: firstString(input.couponId, input.coupon_id), environment: firstString(input.environment), checkout_start_source: firstString(input.checkoutStartSource, input.checkout_start_source), step_id: firstString(input.stepId, input.step_id), step_name: firstString(input.stepName, input.step_name), step_type: firstString(input.stepType, input.step_type), user_id: funnelUserId, cw_client_user_id: funnelUserId, project_id: firstString(input.projectId, input.project_id), funnel_id: firstString(input.funnelId, input.funnel_id), funnel_version: firstString(input.funnelVersion, input.funnelVersionId, input.funnel_version), ip_address: firstString(input.ipAddress, input.ip_address, transactionInfo.ipAddress, transactionInfo.ip_address), user_agent: firstString(input.userAgent, input.user_agent, attributionContext.userAgent), timezone: firstString(input.timezone, input.time_zone, progressAttributes.timezone, progressAttributes.time_zone, document.timezone, document.time_zone, attributionContext.timezone, attributionContext.time_zone), geo_city: firstString(input.geoCity, input.geo_city, progressAttributes.geo_city, progressAttributes.geoCity, document.geo_city, document.geoCity, asRecord(document.geo).city, attributionContext.geo_city, attributionContext.geoCity, attributionContext.cityName, attributionContext.city), geo_country: firstString(input.geoCountry, input.geo_country, progressAttributes.geo_country, progressAttributes.geoCountry, document.geo_country, document.geoCountry, asRecord(document.geo).country, attributionContext.geo_country, attributionContext.geoCountry, attributionContext.countryName, attributionContext.countryCode, attributionContext.country), transaction_id: firstString(input.transactionId, input.transaction_id), url: options.includeUrl
132
139
  ? sanitizePurchaseUrl(firstString(input.url, currentBrowserPurchaseUrl()))
133
140
  : undefined }));
134
141
  };
@@ -0,0 +1,15 @@
1
+ import { type BrowserDeliveryOptions } from './browser-event-delivery.js';
2
+ type AnalyticsEvent = {
3
+ event: string;
4
+ properties: Record<string, unknown>;
5
+ timestamp?: string;
6
+ };
7
+ /** Maps the same normalized event used by PostHog, preserving its identity. */
8
+ export declare class RudderstackDelivery {
9
+ private readonly delivery;
10
+ static create(options: Partial<BrowserDeliveryOptions>): RudderstackDelivery | null;
11
+ private constructor();
12
+ enqueue(event: AnalyticsEvent): boolean;
13
+ flush(): Promise<number>;
14
+ }
15
+ export {};
@@ -0,0 +1,38 @@
1
+ import { toRudderstackTrackEvent } from './analytics-export.js';
2
+ import { runtimeEnvConfig } from '@funnelsgrove/runtime/config/env.config';
3
+ import { BrowserEventDelivery } from './browser-event-delivery.js';
4
+ /** Maps the same normalized event used by PostHog, preserving its identity. */
5
+ export class RudderstackDelivery {
6
+ static create(options) {
7
+ var _a, _b;
8
+ if (runtimeEnvConfig.rudderstackEnabled !== 'true')
9
+ return null;
10
+ const url = ((_a = runtimeEnvConfig.rudderstackDataPlaneUrl) === null || _a === void 0 ? void 0 : _a.trim().replace(/\/+$/, '')) || '';
11
+ const configuredKey = ((_b = runtimeEnvConfig.rudderstackWriteKey) === null || _b === void 0 ? void 0 : _b.trim()) || '';
12
+ const key = /^[\x21-\x7e]+$/.test(configuredKey) ? configuredKey : '';
13
+ if (!url || !key)
14
+ return null;
15
+ return new RudderstackDelivery(options, url, key);
16
+ }
17
+ constructor(options, url, key) {
18
+ this.delivery = new BrowserEventDelivery(options, {
19
+ enabled: true,
20
+ endpoint: `${url}/v1/batch`, batchPrefix: '{"batch":[',
21
+ headers: { Authorization: `Basic ${btoa(`${key}:`)}` },
22
+ });
23
+ }
24
+ enqueue(event) {
25
+ if (event.properties.environment !== 'live' && runtimeEnvConfig.rudderstackIncludeTestEvents !== 'true')
26
+ return true;
27
+ try {
28
+ return this.delivery.enqueue(toRudderstackTrackEvent({
29
+ distinctId: String(event.properties.distinct_id), messageId: String(event.properties.$insert_id),
30
+ event: event.event, properties: event.properties, timestamp: event.timestamp,
31
+ }));
32
+ }
33
+ catch (_a) {
34
+ return false;
35
+ }
36
+ }
37
+ flush() { return this.delivery.flush(); }
38
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@funnelsgrove/analytics",
3
- "version": "0.2.0",
3
+ "version": "0.4.0",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/The-Solid-Grove/funnelsgrove.git",
@@ -21,6 +21,11 @@
21
21
  "types": "./dist/services/experiment-result-metrics.service.d.ts",
22
22
  "import": "./dist/services/experiment-result-metrics.service.js",
23
23
  "default": "./dist/services/experiment-result-metrics.service.js"
24
+ },
25
+ "./export": {
26
+ "types": "./dist/services/analytics-export.d.ts",
27
+ "import": "./dist/services/analytics-export.js",
28
+ "default": "./dist/services/analytics-export.js"
24
29
  }
25
30
  },
26
31
  "files": [
@@ -40,9 +45,9 @@
40
45
  "@types/node": "^20",
41
46
  "typescript": "^5",
42
47
  "vitest": "^3.2.4",
43
- "@funnelsgrove/runtime": "0.19.1"
48
+ "@funnelsgrove/runtime": "0.21.0"
44
49
  },
45
50
  "peerDependencies": {
46
- "@funnelsgrove/runtime": "^0.19.1"
51
+ "@funnelsgrove/runtime": "^0.21.0"
47
52
  }
48
53
  }