@funnelsgrove/analytics 0.1.3 → 0.1.5

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.
package/dist/index.d.ts CHANGED
@@ -1,4 +1,7 @@
1
1
  export * from './services/runtime-api.config.js';
2
2
  export * from './services/sdk-user-id.storage.js';
3
3
  export * from './services/bootstrap-public-analytics-user.js';
4
+ export * from './services/google-tag.service.js';
5
+ export * from './services/meta-pixel.service.js';
6
+ export * from './services/purchase-attributes.service.js';
4
7
  export * from './services/public-analytics-sdk.service.js';
package/dist/index.js CHANGED
@@ -1,4 +1,7 @@
1
1
  export * from './services/runtime-api.config.js';
2
2
  export * from './services/sdk-user-id.storage.js';
3
3
  export * from './services/bootstrap-public-analytics-user.js';
4
+ export * from './services/google-tag.service.js';
5
+ export * from './services/meta-pixel.service.js';
6
+ export * from './services/purchase-attributes.service.js';
4
7
  export * from './services/public-analytics-sdk.service.js';
@@ -0,0 +1,29 @@
1
+ type GoogleTagEventName = 'purchase';
2
+ export type GoogleTagTrackInput = {
3
+ eventName: GoogleTagEventName;
4
+ parameters?: Record<string, unknown>;
5
+ };
6
+ export type AnalyticsEventForGoogleTag = {
7
+ eventId?: string | null;
8
+ eventType: string;
9
+ metadata?: Record<string, unknown>;
10
+ };
11
+ declare global {
12
+ interface Window {
13
+ __funnelsgroveGoogleTagServiceReady?: boolean;
14
+ dataLayer?: unknown[];
15
+ gtag?: (...args: unknown[]) => void;
16
+ }
17
+ }
18
+ export declare const mapAnalyticsEventToGoogleTagEvent: (event: AnalyticsEventForGoogleTag) => GoogleTagTrackInput | null;
19
+ export declare class GoogleTagService {
20
+ private initialized;
21
+ initialize(): void;
22
+ track(input: GoogleTagTrackInput): void;
23
+ private isConfigured;
24
+ private ensureInitialized;
25
+ private ensureDataLayer;
26
+ private installScript;
27
+ }
28
+ export declare const googleTagService: GoogleTagService;
29
+ export {};
@@ -0,0 +1,91 @@
1
+ import { GOOGLE_ANALYTICS_ID, GOOGLE_TAG_ENABLED, GOOGLE_TAG_EVENT_TARGET, GOOGLE_TAG_MANAGER_ID, } from './runtime-api.config.js';
2
+ import { buildBrowserPurchaseAnalyticsAttributes } from './purchase-attributes.service.js';
3
+ const normalizeEventTarget = (value) => {
4
+ return value === 'dataLayer' || value === 'gtag' || value === 'both' ? value : 'both';
5
+ };
6
+ export const mapAnalyticsEventToGoogleTagEvent = (event) => {
7
+ var _a;
8
+ switch (event.eventType) {
9
+ case 'checkout_completed':
10
+ return {
11
+ eventName: 'purchase',
12
+ parameters: buildBrowserPurchaseAnalyticsAttributes(Object.assign(Object.assign({}, ((_a = event.metadata) !== null && _a !== void 0 ? _a : {})), { transactionId: event.eventId })),
13
+ };
14
+ default:
15
+ return null;
16
+ }
17
+ };
18
+ export class GoogleTagService {
19
+ constructor() {
20
+ this.initialized = false;
21
+ }
22
+ initialize() {
23
+ if (!this.isConfigured()) {
24
+ return;
25
+ }
26
+ this.ensureInitialized();
27
+ }
28
+ track(input) {
29
+ var _a, _b, _c;
30
+ if (!this.isConfigured()) {
31
+ return;
32
+ }
33
+ this.initialize();
34
+ const parameters = (_a = input.parameters) !== null && _a !== void 0 ? _a : {};
35
+ const eventTarget = normalizeEventTarget(GOOGLE_TAG_EVENT_TARGET);
36
+ if (eventTarget === 'dataLayer' || eventTarget === 'both') {
37
+ (_b = window.dataLayer) === null || _b === void 0 ? void 0 : _b.push(Object.assign({ event: input.eventName }, parameters));
38
+ }
39
+ if (eventTarget === 'gtag' || eventTarget === 'both') {
40
+ (_c = window.gtag) === null || _c === void 0 ? void 0 : _c.call(window, 'event', input.eventName, parameters);
41
+ }
42
+ }
43
+ isConfigured() {
44
+ return Boolean(GOOGLE_TAG_ENABLED &&
45
+ (GOOGLE_ANALYTICS_ID || GOOGLE_TAG_MANAGER_ID) &&
46
+ typeof window !== 'undefined');
47
+ }
48
+ ensureInitialized() {
49
+ var _a, _b, _c;
50
+ if (this.initialized) {
51
+ return;
52
+ }
53
+ this.initialized = true;
54
+ window.__funnelsgroveGoogleTagServiceReady = true;
55
+ this.ensureDataLayer();
56
+ if (GOOGLE_ANALYTICS_ID) {
57
+ this.installScript(`https://www.googletagmanager.com/gtag/js?id=${encodeURIComponent(GOOGLE_ANALYTICS_ID)}`);
58
+ (_a = window.gtag) === null || _a === void 0 ? void 0 : _a.call(window, 'js', new Date());
59
+ (_b = window.gtag) === null || _b === void 0 ? void 0 : _b.call(window, 'config', GOOGLE_ANALYTICS_ID);
60
+ }
61
+ if (GOOGLE_TAG_MANAGER_ID) {
62
+ (_c = window.dataLayer) === null || _c === void 0 ? void 0 : _c.push({
63
+ 'gtm.start': Date.now(),
64
+ event: 'gtm.js',
65
+ });
66
+ this.installScript(`https://www.googletagmanager.com/gtm.js?id=${encodeURIComponent(GOOGLE_TAG_MANAGER_ID)}`);
67
+ }
68
+ }
69
+ ensureDataLayer() {
70
+ window.dataLayer = window.dataLayer || [];
71
+ window.gtag = window.gtag || ((...args) => {
72
+ var _a;
73
+ (_a = window.dataLayer) === null || _a === void 0 ? void 0 : _a.push(args);
74
+ });
75
+ }
76
+ installScript(src) {
77
+ if (typeof document === 'undefined') {
78
+ return;
79
+ }
80
+ const firstScript = document.getElementsByTagName('script')[0];
81
+ const parent = firstScript === null || firstScript === void 0 ? void 0 : firstScript.parentNode;
82
+ if (!parent) {
83
+ return;
84
+ }
85
+ const script = document.createElement('script');
86
+ script.async = true;
87
+ script.src = src;
88
+ parent.insertBefore(script, firstScript);
89
+ }
90
+ }
91
+ export const googleTagService = new GoogleTagService();
@@ -0,0 +1,26 @@
1
+ type MetaPixelEventName = 'AddPaymentInfo' | 'InitiateCheckout' | 'Lead' | 'ViewContent';
2
+ export type MetaPixelTrackInput = {
3
+ eventName: MetaPixelEventName;
4
+ eventId: string;
5
+ customData?: Record<string, unknown>;
6
+ };
7
+ export type AnalyticsEventForMetaPixel = {
8
+ eventType: string;
9
+ eventId: string;
10
+ metadata?: Record<string, unknown>;
11
+ };
12
+ declare global {
13
+ interface Window {
14
+ fbq?: (...args: unknown[]) => void;
15
+ }
16
+ }
17
+ export declare const mapAnalyticsEventToMetaPixelEvent: (event: AnalyticsEventForMetaPixel) => MetaPixelTrackInput | null;
18
+ export declare class MetaPixelService {
19
+ private initialized;
20
+ track(input: MetaPixelTrackInput): void;
21
+ private isConfigured;
22
+ private ensureInitialized;
23
+ private installScript;
24
+ }
25
+ export declare const metaPixelService: MetaPixelService;
26
+ export {};
@@ -0,0 +1,100 @@
1
+ import { META_PIXEL_ENABLED, META_PIXEL_ID } from './runtime-api.config.js';
2
+ const toNumber = (value) => {
3
+ if (typeof value !== 'number' || !Number.isFinite(value)) {
4
+ return null;
5
+ }
6
+ return value;
7
+ };
8
+ const toCurrency = (value) => {
9
+ return typeof value === 'string' && value.trim() ? value.trim().toUpperCase() : undefined;
10
+ };
11
+ const buildCommerceCustomData = (metadata = {}) => {
12
+ var _a;
13
+ const amountCents = toNumber(metadata.amountCents);
14
+ const value = (_a = toNumber(metadata.value)) !== null && _a !== void 0 ? _a : (amountCents === null ? null : amountCents / 100);
15
+ const currency = toCurrency(metadata.currency);
16
+ const customData = {};
17
+ if (currency) {
18
+ customData.currency = currency;
19
+ }
20
+ if (value !== null) {
21
+ customData.value = value;
22
+ }
23
+ return customData;
24
+ };
25
+ export const mapAnalyticsEventToMetaPixelEvent = (event) => {
26
+ switch (event.eventType) {
27
+ case 'first_step_viewed':
28
+ case 'first_step_clicked':
29
+ return {
30
+ eventName: 'ViewContent',
31
+ eventId: event.eventId,
32
+ customData: {},
33
+ };
34
+ case 'email_captured':
35
+ case 'lead':
36
+ return {
37
+ eventName: 'Lead',
38
+ eventId: event.eventId,
39
+ customData: {},
40
+ };
41
+ case 'checkout_started':
42
+ return {
43
+ eventName: 'InitiateCheckout',
44
+ eventId: event.eventId,
45
+ customData: buildCommerceCustomData(event.metadata),
46
+ };
47
+ case 'checkout_completed':
48
+ case 'payment_checkout_succeeded':
49
+ return {
50
+ eventName: 'AddPaymentInfo',
51
+ eventId: event.eventId,
52
+ customData: buildCommerceCustomData(event.metadata),
53
+ };
54
+ default:
55
+ return null;
56
+ }
57
+ };
58
+ export class MetaPixelService {
59
+ constructor() {
60
+ this.initialized = false;
61
+ }
62
+ track(input) {
63
+ var _a, _b;
64
+ if (!this.isConfigured()) {
65
+ return;
66
+ }
67
+ this.ensureInitialized();
68
+ (_a = window.fbq) === null || _a === void 0 ? void 0 : _a.call(window, 'track', input.eventName, (_b = input.customData) !== null && _b !== void 0 ? _b : {}, {
69
+ eventID: input.eventId,
70
+ });
71
+ }
72
+ isConfigured() {
73
+ return Boolean(META_PIXEL_ENABLED && META_PIXEL_ID && typeof window !== 'undefined');
74
+ }
75
+ ensureInitialized() {
76
+ var _a, _b;
77
+ if (this.initialized) {
78
+ return;
79
+ }
80
+ this.initialized = true;
81
+ this.installScript();
82
+ (_a = window.fbq) === null || _a === void 0 ? void 0 : _a.call(window, 'init', META_PIXEL_ID);
83
+ (_b = window.fbq) === null || _b === void 0 ? void 0 : _b.call(window, 'track', 'PageView');
84
+ }
85
+ installScript() {
86
+ if (typeof document === 'undefined') {
87
+ return;
88
+ }
89
+ const firstScript = document.getElementsByTagName('script')[0];
90
+ const parent = firstScript === null || firstScript === void 0 ? void 0 : firstScript.parentNode;
91
+ if (!parent) {
92
+ return;
93
+ }
94
+ const script = document.createElement('script');
95
+ script.async = true;
96
+ script.src = 'https://connect.facebook.net/en_US/fbevents.js';
97
+ parent.insertBefore(script, firstScript);
98
+ }
99
+ }
100
+ export const metaPixelService = new MetaPixelService();
@@ -26,6 +26,23 @@ export type PublicSdkStepEndInput = {
26
26
  selected?: Record<string, unknown>;
27
27
  featureFlags?: Record<string, string | null | undefined>;
28
28
  };
29
+ export type PublicSdkStepEngagedInput = {
30
+ stepId: string;
31
+ stepName: string;
32
+ startedAt: string;
33
+ engagedAt: string;
34
+ durationMs: number;
35
+ engagementThresholdMs: number;
36
+ featureFlags?: Record<string, string | null | undefined>;
37
+ };
38
+ export type PublicSdkConversionCallbackInput = {
39
+ eventId?: string;
40
+ occurredAt?: string;
41
+ stepId?: string;
42
+ stepName?: string;
43
+ metadata?: Record<string, unknown>;
44
+ featureFlags?: Record<string, string | null | undefined>;
45
+ };
29
46
  export type PublicSdkIdentifyInput = {
30
47
  user_id?: string;
31
48
  email?: string;
@@ -56,6 +73,12 @@ export declare class PublicAnalyticsSdkService {
56
73
  track(event: PublicSdkTrackEventInput): string | null;
57
74
  trackStepStarted(input: PublicSdkStepStartInput): string | null;
58
75
  trackStepCompleted(input: PublicSdkStepEndInput): string | null;
76
+ trackStepEngaged(input: PublicSdkStepEngagedInput): string | null;
77
+ trackFirstStepClicked(input: PublicSdkConversionCallbackInput): string | null;
78
+ trackFirstStepViewed(input: PublicSdkConversionCallbackInput): string | null;
79
+ trackLead(input: PublicSdkConversionCallbackInput): string | null;
80
+ trackCheckoutStarted(input: PublicSdkConversionCallbackInput): string | null;
81
+ trackCheckoutCompleted(input: PublicSdkConversionCallbackInput): string | null;
59
82
  flush(): Promise<number>;
60
83
  private ensureUserId;
61
84
  private resolveBootstrapUserId;
@@ -1,5 +1,7 @@
1
1
  import { buildMainApiUrl, buildSdkHeaders, FUNNEL_ID, FUNNEL_VERSION_ID, getFunnelSdkPublishableKey, hasPostHogRuntimeConfig, POSTHOG_API_HOST, POSTHOG_PROJECT_API_KEY, PROJECT_ID, } from './runtime-api.config.js';
2
2
  import { canUseDom, getOrCreateUserId, persistUserId, readStoredUserId, } from './sdk-user-id.storage.js';
3
+ import { mapAnalyticsEventToMetaPixelEvent, metaPixelService, } from './meta-pixel.service.js';
4
+ import { googleTagService, mapAnalyticsEventToGoogleTagEvent, } from './google-tag.service.js';
3
5
  const DEFAULT_OPTIONS = {
4
6
  batchSize: 20,
5
7
  flushIntervalMs: 1500,
@@ -27,6 +29,23 @@ const toIsoOrNow = (value) => {
27
29
  }
28
30
  return new Date().toISOString();
29
31
  };
32
+ const toFiniteNumber = (value) => {
33
+ if (typeof value !== 'number' || !Number.isFinite(value)) {
34
+ return null;
35
+ }
36
+ return value;
37
+ };
38
+ const toDurationMs = (startedAt, endedAt) => {
39
+ if (!startedAt || !endedAt) {
40
+ return null;
41
+ }
42
+ const startedMs = new Date(startedAt).getTime();
43
+ const endedMs = new Date(endedAt).getTime();
44
+ if (!Number.isFinite(startedMs) || !Number.isFinite(endedMs) || endedMs < startedMs) {
45
+ return null;
46
+ }
47
+ return endedMs - startedMs;
48
+ };
30
49
  const buildEventId = () => {
31
50
  var _a;
32
51
  if (canUseDom() && typeof ((_a = window.crypto) === null || _a === void 0 ? void 0 : _a.randomUUID) === 'function') {
@@ -67,6 +86,7 @@ export class PublicAnalyticsSdkService {
67
86
  this.flushTimerId = null;
68
87
  this.inFlightFlush = null;
69
88
  this.userId = null;
89
+ googleTagService.initialize();
70
90
  }
71
91
  getCurrentUserId() {
72
92
  return this.ensureUserId();
@@ -144,21 +164,41 @@ export class PublicAnalyticsSdkService {
144
164
  }
145
165
  }
146
166
  track(event) {
167
+ var _a, _b, _c, _d;
147
168
  const eventType = asString(event.eventType);
148
169
  if (!eventType) {
149
170
  return null;
150
171
  }
172
+ const eventId = asString(event.eventId) || buildEventId();
173
+ const metaPixelEvent = mapAnalyticsEventToMetaPixelEvent({
174
+ eventType,
175
+ eventId,
176
+ metadata: asRecord(event.metadata),
177
+ });
178
+ if (metaPixelEvent) {
179
+ metaPixelService.track(metaPixelEvent);
180
+ }
181
+ const googleTagEvent = mapAnalyticsEventToGoogleTagEvent({
182
+ eventType,
183
+ eventId,
184
+ metadata: asRecord(event.metadata),
185
+ });
186
+ if (googleTagEvent) {
187
+ googleTagService.track(googleTagEvent);
188
+ }
151
189
  if (!getFunnelSdkPublishableKey()) {
152
- return asString(event.eventId) || buildEventId();
190
+ return eventId;
153
191
  }
154
192
  const envelope = {
155
193
  eventType,
156
- eventId: asString(event.eventId) || buildEventId(),
194
+ eventId,
157
195
  occurredAt: toIsoOrNow(event.occurredAt),
158
196
  stepId: asString(event.stepId),
159
197
  stepName: asString(event.stepName),
160
198
  startedAt: asString(event.startedAt),
161
199
  endedAt: asString(event.endedAt),
200
+ durationMs: (_b = toFiniteNumber((_a = event.metadata) === null || _a === void 0 ? void 0 : _a.durationMs)) !== null && _b !== void 0 ? _b : null,
201
+ engagementThresholdMs: (_d = toFiniteNumber((_c = event.metadata) === null || _c === void 0 ? void 0 : _c.engagementThresholdMs)) !== null && _d !== void 0 ? _d : null,
162
202
  selected: asRecord(event.selected),
163
203
  payload: asRecord(event.payload),
164
204
  context: asRecord(event.context),
@@ -184,14 +224,90 @@ export class PublicAnalyticsSdkService {
184
224
  });
185
225
  }
186
226
  trackStepCompleted(input) {
227
+ var _a;
228
+ const startedAt = asString(input.startedAt);
229
+ const endedAt = asString(input.endedAt);
187
230
  return this.track({
188
231
  eventType: 'step_end',
189
232
  stepId: input.stepId,
190
233
  stepName: input.stepName,
191
- startedAt: input.startedAt,
192
- endedAt: input.endedAt,
234
+ startedAt: startedAt || input.startedAt,
235
+ endedAt: endedAt || input.endedAt,
193
236
  occurredAt: input.endedAt,
194
237
  selected: asRecord(input.selected),
238
+ metadata: {
239
+ durationMs: (_a = toDurationMs(startedAt, endedAt)) !== null && _a !== void 0 ? _a : undefined,
240
+ },
241
+ featureFlags: input.featureFlags,
242
+ });
243
+ }
244
+ trackStepEngaged(input) {
245
+ return this.track({
246
+ eventType: 'step_engaged',
247
+ stepId: input.stepId,
248
+ stepName: input.stepName,
249
+ startedAt: input.startedAt,
250
+ endedAt: input.engagedAt,
251
+ occurredAt: input.engagedAt,
252
+ metadata: {
253
+ durationMs: input.durationMs,
254
+ engagementThresholdMs: input.engagementThresholdMs,
255
+ },
256
+ featureFlags: input.featureFlags,
257
+ });
258
+ }
259
+ trackFirstStepClicked(input) {
260
+ return this.track({
261
+ eventType: 'first_step_clicked',
262
+ eventId: input.eventId,
263
+ occurredAt: input.occurredAt,
264
+ stepId: input.stepId,
265
+ stepName: input.stepName,
266
+ metadata: input.metadata,
267
+ featureFlags: input.featureFlags,
268
+ });
269
+ }
270
+ trackFirstStepViewed(input) {
271
+ return this.track({
272
+ eventType: 'first_step_viewed',
273
+ eventId: input.eventId,
274
+ occurredAt: input.occurredAt,
275
+ stepId: input.stepId,
276
+ stepName: input.stepName,
277
+ metadata: input.metadata,
278
+ featureFlags: input.featureFlags,
279
+ });
280
+ }
281
+ trackLead(input) {
282
+ return this.track({
283
+ eventType: 'email_captured',
284
+ eventId: input.eventId,
285
+ occurredAt: input.occurredAt,
286
+ stepId: input.stepId,
287
+ stepName: input.stepName,
288
+ metadata: input.metadata,
289
+ featureFlags: input.featureFlags,
290
+ });
291
+ }
292
+ trackCheckoutStarted(input) {
293
+ return this.track({
294
+ eventType: 'checkout_started',
295
+ eventId: input.eventId,
296
+ occurredAt: input.occurredAt,
297
+ stepId: input.stepId,
298
+ stepName: input.stepName,
299
+ metadata: input.metadata,
300
+ featureFlags: input.featureFlags,
301
+ });
302
+ }
303
+ trackCheckoutCompleted(input) {
304
+ return this.track({
305
+ eventType: 'checkout_completed',
306
+ eventId: input.eventId,
307
+ occurredAt: input.occurredAt,
308
+ stepId: input.stepId,
309
+ stepName: input.stepName,
310
+ metadata: input.metadata,
195
311
  featureFlags: input.featureFlags,
196
312
  });
197
313
  }
@@ -271,13 +387,16 @@ export class PublicAnalyticsSdkService {
271
387
  if (!getFunnelSdkPublishableKey() || !hasPostHogRuntimeConfig()) {
272
388
  return true;
273
389
  }
274
- const batch = events.map((event) => ({
275
- event: toPostHogEventName(event.eventType),
276
- properties: buildDefinedRecord(Object.assign(Object.assign({ distinct_id: this.ensureUserId(), $groups: {
277
- project: PROJECT_ID,
278
- }, $insert_id: event.eventId, project_id: PROJECT_ID, funnel_id: FUNNEL_ID || undefined, funnel_version_id: FUNNEL_VERSION_ID || undefined, step_id: event.stepId || undefined, step_name: event.stepName || undefined, event_source: 'client' }, buildFeatureFlagProperties(event.featureFlags)), { selected: Object.keys(event.selected).length > 0 ? event.selected : undefined, payload: Object.keys(event.payload).length > 0 ? event.payload : undefined, context: Object.keys(event.context).length > 0 ? event.context : undefined, metadata: Object.keys(event.metadata).length > 0 ? event.metadata : undefined })),
279
- timestamp: event.occurredAt,
280
- }));
390
+ const batch = events.map((event) => {
391
+ var _a, _b;
392
+ return ({
393
+ event: toPostHogEventName(event.eventType),
394
+ properties: buildDefinedRecord(Object.assign(Object.assign({ distinct_id: this.ensureUserId(), $groups: {
395
+ project: PROJECT_ID,
396
+ }, $insert_id: event.eventId, project_id: PROJECT_ID, funnel_id: FUNNEL_ID || undefined, funnel_version_id: FUNNEL_VERSION_ID || undefined, step_id: event.stepId || undefined, step_name: event.stepName || undefined, started_at: event.startedAt || undefined, ended_at: event.endedAt || undefined, duration_ms: (_a = event.durationMs) !== null && _a !== void 0 ? _a : undefined, engagement_threshold_ms: (_b = event.engagementThresholdMs) !== null && _b !== void 0 ? _b : undefined, event_source: 'client' }, buildFeatureFlagProperties(event.featureFlags)), { selected: Object.keys(event.selected).length > 0 ? event.selected : undefined, payload: Object.keys(event.payload).length > 0 ? event.payload : undefined, context: Object.keys(event.context).length > 0 ? event.context : undefined, metadata: Object.keys(event.metadata).length > 0 ? event.metadata : undefined })),
397
+ timestamp: event.occurredAt,
398
+ });
399
+ });
281
400
  const payload = JSON.stringify({
282
401
  api_key: POSTHOG_PROJECT_API_KEY,
283
402
  batch,
@@ -0,0 +1,28 @@
1
+ export type PurchaseAnalyticsAttributesInput = {
2
+ amountCents?: unknown;
3
+ attribution?: unknown;
4
+ couponId?: unknown;
5
+ currency?: unknown;
6
+ environment?: unknown;
7
+ funnelId?: unknown;
8
+ funnelUserDocument?: unknown;
9
+ funnelVersion?: unknown;
10
+ funnelVersionId?: unknown;
11
+ geoCity?: unknown;
12
+ geoCountry?: unknown;
13
+ ipAddress?: unknown;
14
+ planId?: unknown;
15
+ projectId?: unknown;
16
+ providerPlanId?: unknown;
17
+ transactionId?: unknown;
18
+ url?: unknown;
19
+ userAgent?: unknown;
20
+ userId?: unknown;
21
+ value?: unknown;
22
+ };
23
+ export declare const buildPurchaseAnalyticsAttributes: (input?: PurchaseAnalyticsAttributesInput & Record<string, unknown>, options?: {
24
+ includeUrl?: boolean;
25
+ }) => Record<string, unknown>;
26
+ export declare const buildBrowserPurchaseAnalyticsAttributes: (input?: PurchaseAnalyticsAttributesInput & Record<string, unknown>) => Record<string, unknown>;
27
+ export declare const toStripeMetadata: (attributes: Record<string, unknown>) => Record<string, string>;
28
+ export declare const buildStripePurchaseMetadata: (input?: PurchaseAnalyticsAttributesInput & Record<string, unknown>) => Record<string, string>;
@@ -0,0 +1,101 @@
1
+ const STRIPE_METADATA_KEY_MAX_LENGTH = 40;
2
+ const STRIPE_METADATA_VALUE_MAX_LENGTH = 500;
3
+ const isRecord = (value) => {
4
+ return Boolean(value) && typeof value === 'object' && !Array.isArray(value);
5
+ };
6
+ const asRecord = (value) => {
7
+ return isRecord(value) ? value : {};
8
+ };
9
+ const toString = (value) => {
10
+ if (typeof value !== 'string') {
11
+ return undefined;
12
+ }
13
+ const trimmed = value.trim();
14
+ return trimmed || undefined;
15
+ };
16
+ const toScalar = (value) => {
17
+ if (typeof value === 'number' && Number.isFinite(value)) {
18
+ return value;
19
+ }
20
+ if (typeof value === 'boolean') {
21
+ return value;
22
+ }
23
+ return toString(value);
24
+ };
25
+ const toNumber = (value) => {
26
+ if (typeof value === 'number' && Number.isFinite(value)) {
27
+ return value;
28
+ }
29
+ const normalized = toString(value);
30
+ if (!normalized) {
31
+ return undefined;
32
+ }
33
+ const parsed = Number(normalized);
34
+ return Number.isFinite(parsed) ? parsed : undefined;
35
+ };
36
+ const toCurrency = (value) => {
37
+ var _a;
38
+ return (_a = toString(value)) === null || _a === void 0 ? void 0 : _a.toUpperCase();
39
+ };
40
+ const firstString = (...values) => {
41
+ for (const value of values) {
42
+ const normalized = toString(value);
43
+ if (normalized) {
44
+ return normalized;
45
+ }
46
+ }
47
+ return undefined;
48
+ };
49
+ const buildDefinedRecord = (value) => {
50
+ return Object.fromEntries(Object.entries(value).filter(([, candidate]) => candidate !== undefined && candidate !== null && candidate !== ''));
51
+ };
52
+ const normalizeAttributionTouch = (value) => {
53
+ return Object.fromEntries(Object.entries(asRecord(value)).flatMap(([key, candidate]) => {
54
+ const normalizedKey = key.trim();
55
+ const normalizedValue = toScalar(candidate);
56
+ if (!normalizedKey || normalizedValue === undefined) {
57
+ return [];
58
+ }
59
+ return [[normalizedKey, normalizedValue]];
60
+ }));
61
+ };
62
+ const currentBrowserUrl = () => {
63
+ var _a;
64
+ if (typeof window === 'undefined') {
65
+ return undefined;
66
+ }
67
+ return toString((_a = window.location) === null || _a === void 0 ? void 0 : _a.href);
68
+ };
69
+ export const buildPurchaseAnalyticsAttributes = (input = {}, options = {}) => {
70
+ var _a, _b;
71
+ const document = asRecord(input.funnelUserDocument);
72
+ const attribution = asRecord((_a = input.attribution) !== null && _a !== void 0 ? _a : document.attribution);
73
+ const attributionContext = asRecord(attribution.context);
74
+ const transactionInfo = asRecord(document.transactionInfo);
75
+ const amountCents = toNumber(input.amountCents);
76
+ const value = (_b = toNumber(input.value)) !== null && _b !== void 0 ? _b : (amountCents === undefined ? undefined : amountCents / 100);
77
+ return buildDefinedRecord(Object.assign(Object.assign({}, normalizeAttributionTouch(attribution.firstTouch)), { 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), user_id: firstString(input.userId, input.user_id), 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), geo_city: firstString(input.geoCity, input.geo_city, 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, 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 ? firstString(input.url, currentBrowserUrl()) : undefined }));
78
+ };
79
+ export const buildBrowserPurchaseAnalyticsAttributes = (input = {}) => {
80
+ return buildPurchaseAnalyticsAttributes(input, { includeUrl: true });
81
+ };
82
+ const toStripeMetadataValue = (value) => {
83
+ const scalar = toScalar(value);
84
+ if (scalar === undefined) {
85
+ return undefined;
86
+ }
87
+ return String(scalar).slice(0, STRIPE_METADATA_VALUE_MAX_LENGTH);
88
+ };
89
+ export const toStripeMetadata = (attributes) => {
90
+ return Object.fromEntries(Object.entries(attributes).flatMap(([key, value]) => {
91
+ const normalizedKey = key.trim().slice(0, STRIPE_METADATA_KEY_MAX_LENGTH);
92
+ const normalizedValue = toStripeMetadataValue(value);
93
+ if (!normalizedKey || normalizedValue === undefined) {
94
+ return [];
95
+ }
96
+ return [[normalizedKey, normalizedValue]];
97
+ }));
98
+ };
99
+ export const buildStripePurchaseMetadata = (input = {}) => {
100
+ return toStripeMetadata(buildPurchaseAnalyticsAttributes(input, { includeUrl: false }));
101
+ };
@@ -5,6 +5,12 @@ export declare const FUNNEL_VERSION_ID: string;
5
5
  export declare const PROJECT_ID: string;
6
6
  export declare const POSTHOG_API_HOST = "https://us.i.posthog.com";
7
7
  export declare const POSTHOG_PROJECT_API_KEY: string;
8
+ export declare const META_PIXEL_ENABLED: boolean;
9
+ export declare const META_PIXEL_ID: string;
10
+ export declare const GOOGLE_TAG_ENABLED: boolean;
11
+ export declare const GOOGLE_ANALYTICS_ID: string;
12
+ export declare const GOOGLE_TAG_MANAGER_ID: string;
13
+ export declare const GOOGLE_TAG_EVENT_TARGET: string;
8
14
  export declare const hasRealFunnelSdkPublishableKey: (value?: string) => boolean;
9
15
  export declare const getFunnelSdkPublishableKey: () => string | null;
10
16
  export declare const hasPostHogRuntimeConfig: () => boolean;
@@ -1,4 +1,4 @@
1
- var _a, _b, _c, _d, _e, _f;
1
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m;
2
2
  import { resolveRuntimeSdkApiBaseUrl, runtimeEnvConfig, } from '@funnelsgrove/runtime/config/env.config';
3
3
  const DEFAULT_API_BASE_URL = 'https://sdk-api.funnelsgrove.com';
4
4
  const DEFAULT_FUNNEL_SDK_PUBLISHABLE_KEY = 'pk_test_app_deals_seed_public';
@@ -26,6 +26,12 @@ export const FUNNEL_VERSION_ID = ((_d = runtimeEnvConfig.funnelVersionId) !== nu
26
26
  export const PROJECT_ID = ((_e = runtimeEnvConfig.projectId) !== null && _e !== void 0 ? _e : '').trim();
27
27
  export const POSTHOG_API_HOST = 'https://us.i.posthog.com';
28
28
  export const POSTHOG_PROJECT_API_KEY = ((_f = runtimeEnvConfig.posthogProjectApiKey) !== null && _f !== void 0 ? _f : '').trim();
29
+ export const META_PIXEL_ENABLED = ((_g = runtimeEnvConfig.metaPixelEnabled) !== null && _g !== void 0 ? _g : '').trim() === 'true';
30
+ export const META_PIXEL_ID = ((_h = runtimeEnvConfig.metaPixelId) !== null && _h !== void 0 ? _h : '').trim();
31
+ export const GOOGLE_TAG_ENABLED = ((_j = runtimeEnvConfig.googleTagEnabled) !== null && _j !== void 0 ? _j : '').trim() === 'true';
32
+ export const GOOGLE_ANALYTICS_ID = ((_k = runtimeEnvConfig.googleAnalyticsId) !== null && _k !== void 0 ? _k : '').trim();
33
+ export const GOOGLE_TAG_MANAGER_ID = ((_l = runtimeEnvConfig.googleTagManagerId) !== null && _l !== void 0 ? _l : '').trim();
34
+ export const GOOGLE_TAG_EVENT_TARGET = ((_m = runtimeEnvConfig.googleTagEventTarget) !== null && _m !== void 0 ? _m : '').trim();
29
35
  export const hasRealFunnelSdkPublishableKey = (value = FUNNEL_SDK_PUBLISHABLE_KEY) => {
30
36
  const normalized = value.trim();
31
37
  return Boolean(normalized) && normalized !== DEFAULT_FUNNEL_SDK_PUBLISHABLE_KEY;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@funnelsgrove/analytics",
3
- "version": "0.1.3",
3
+ "version": "0.1.5",
4
4
  "type": "module",
5
5
  "private": false,
6
6
  "main": "./dist/index.js",
@@ -26,7 +26,7 @@
26
26
  "test:run": "vitest run --passWithNoTests"
27
27
  },
28
28
  "dependencies": {
29
- "@funnelsgrove/runtime": "0.1.3"
29
+ "@funnelsgrove/runtime": "0.1.14"
30
30
  },
31
31
  "devDependencies": {
32
32
  "@types/node": "^20",