@funnelsgrove/analytics 0.2.0 → 0.3.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.
- package/dist/services/analytics-export.d.ts +16 -0
- package/dist/services/analytics-export.js +8 -0
- package/dist/services/browser-event-delivery.d.ts +29 -0
- package/dist/services/browser-event-delivery.js +181 -0
- package/dist/services/posthog-delivery.d.ts +3 -20
- package/dist/services/posthog-delivery.js +5 -176
- package/dist/services/public-analytics-sdk.service.d.ts +1 -0
- package/dist/services/public-analytics-sdk.service.js +11 -4
- package/dist/services/rudderstack-delivery.d.ts +15 -0
- package/dist/services/rudderstack-delivery.js +38 -0
- package/package.json +8 -3
|
@@ -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,22 +1,5 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
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 {
|
|
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
|
-
|
|
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
|
-
|
|
27
|
-
|
|
28
|
-
|
|
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
|
}
|
|
@@ -110,6 +110,7 @@ type SecureBootstrapCrypto = Pick<Crypto, 'getRandomValues'> & {
|
|
|
110
110
|
export declare const createBootstrapIdempotencyKey: (secureCrypto?: SecureBootstrapCrypto) => string;
|
|
111
111
|
export declare class PublicAnalyticsSdkService {
|
|
112
112
|
private readonly delivery;
|
|
113
|
+
private readonly rudderstack;
|
|
113
114
|
private userId;
|
|
114
115
|
constructor(options?: Partial<PublicAnalyticsSdkOptions>);
|
|
115
116
|
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';
|
|
@@ -179,6 +180,7 @@ export class PublicAnalyticsSdkService {
|
|
|
179
180
|
constructor(options = {}) {
|
|
180
181
|
this.userId = null;
|
|
181
182
|
this.delivery = new PostHogDelivery(options);
|
|
183
|
+
this.rudderstack = RudderstackDelivery.create(options);
|
|
182
184
|
googleTagService.initialize();
|
|
183
185
|
}
|
|
184
186
|
getCurrentUserId() {
|
|
@@ -283,7 +285,7 @@ export class PublicAnalyticsSdkService {
|
|
|
283
285
|
}
|
|
284
286
|
}
|
|
285
287
|
trackTrusted(event) {
|
|
286
|
-
var _a, _b, _c, _d, _e, _f;
|
|
288
|
+
var _a, _b, _c, _d, _e, _f, _g;
|
|
287
289
|
const eventType = asString(event.eventType);
|
|
288
290
|
if (!eventType) {
|
|
289
291
|
return null;
|
|
@@ -316,7 +318,9 @@ export class PublicAnalyticsSdkService {
|
|
|
316
318
|
metadata,
|
|
317
319
|
featureFlags: normalizeFeatureFlags(event.featureFlags),
|
|
318
320
|
};
|
|
319
|
-
|
|
321
|
+
const normalized = this.toPostHogEvent(envelope);
|
|
322
|
+
(_g = this.rudderstack) === null || _g === void 0 ? void 0 : _g.enqueue(normalized);
|
|
323
|
+
return this.delivery.enqueue(normalized) ? envelope.eventId : null;
|
|
320
324
|
}
|
|
321
325
|
trackContractCallback(eventName, input) {
|
|
322
326
|
const contract = FUNNEL_ANALYTICS_EVENT_CONTRACTS[eventName];
|
|
@@ -517,8 +521,11 @@ export class PublicAnalyticsSdkService {
|
|
|
517
521
|
featureFlags: input.featureFlags,
|
|
518
522
|
});
|
|
519
523
|
}
|
|
520
|
-
flush() {
|
|
521
|
-
|
|
524
|
+
async flush() {
|
|
525
|
+
if (!this.rudderstack)
|
|
526
|
+
return this.delivery.flush();
|
|
527
|
+
const [accepted] = await Promise.all([this.delivery.flush(), this.rudderstack.flush()]);
|
|
528
|
+
return accepted;
|
|
522
529
|
}
|
|
523
530
|
ensureUserId() {
|
|
524
531
|
const bound = getPaywallUser();
|
|
@@ -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.
|
|
3
|
+
"version": "0.3.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.
|
|
48
|
+
"@funnelsgrove/runtime": "0.20.0"
|
|
44
49
|
},
|
|
45
50
|
"peerDependencies": {
|
|
46
|
-
"@funnelsgrove/runtime": "^0.
|
|
51
|
+
"@funnelsgrove/runtime": "^0.20.0"
|
|
47
52
|
}
|
|
48
53
|
}
|