@probat/react 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/README.md +33 -344
- package/dist/index.d.mts +76 -224
- package/dist/index.d.ts +76 -224
- package/dist/index.js +397 -1185
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +394 -1169
- package/dist/index.mjs.map +1 -1
- package/package.json +19 -12
- package/src/__tests__/Experiment.test.tsx +764 -0
- package/src/__tests__/setup.ts +63 -0
- package/src/__tests__/utils.test.ts +79 -0
- package/src/components/Experiment.tsx +291 -0
- package/src/components/ProbatProviderClient.tsx +19 -7
- package/src/context/ProbatContext.tsx +30 -132
- package/src/hooks/useProbatMetrics.ts +18 -134
- package/src/index.ts +9 -32
- package/src/utils/api.ts +96 -577
- package/src/utils/dedupeStorage.ts +40 -0
- package/src/utils/eventContext.ts +94 -0
- package/src/utils/stableInstanceId.ts +113 -0
- package/src/utils/storage.ts +18 -60
- package/src/hoc/itrt-frontend.code-workspace +0 -38
- package/src/hoc/withExperiment.tsx +0 -290
- package/src/hooks/useExperiment.ts +0 -164
- package/src/utils/documentClickTracker.ts +0 -215
- package/src/utils/heatmapTracker.ts +0 -478
package/dist/index.mjs
CHANGED
|
@@ -1,6 +1,39 @@
|
|
|
1
1
|
"use client";
|
|
2
2
|
"use client";
|
|
3
|
-
import
|
|
3
|
+
import React3, { createContext, useRef, useState, useEffect, useMemo, useCallback, useContext } from 'react';
|
|
4
|
+
|
|
5
|
+
var ProbatContext = createContext(null);
|
|
6
|
+
var DEFAULT_HOST = "https://gushi.onrender.com";
|
|
7
|
+
function ProbatProvider({
|
|
8
|
+
userId,
|
|
9
|
+
host = DEFAULT_HOST,
|
|
10
|
+
bootstrap,
|
|
11
|
+
children
|
|
12
|
+
}) {
|
|
13
|
+
const value = useMemo(
|
|
14
|
+
() => ({
|
|
15
|
+
host: host.replace(/\/$/, ""),
|
|
16
|
+
userId,
|
|
17
|
+
bootstrap: bootstrap ?? {}
|
|
18
|
+
}),
|
|
19
|
+
[userId, host, bootstrap]
|
|
20
|
+
);
|
|
21
|
+
return /* @__PURE__ */ React3.createElement(ProbatContext.Provider, { value }, children);
|
|
22
|
+
}
|
|
23
|
+
function useProbatContext() {
|
|
24
|
+
const ctx = useContext(ProbatContext);
|
|
25
|
+
if (!ctx) {
|
|
26
|
+
throw new Error(
|
|
27
|
+
"useProbatContext must be used within <ProbatProviderClient>. Wrap your app with <ProbatProviderClient userId={...}>."
|
|
28
|
+
);
|
|
29
|
+
}
|
|
30
|
+
return ctx;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
// src/components/ProbatProviderClient.tsx
|
|
34
|
+
function ProbatProviderClient(props) {
|
|
35
|
+
return React3.createElement(ProbatProvider, props);
|
|
36
|
+
}
|
|
4
37
|
|
|
5
38
|
// src/utils/environment.ts
|
|
6
39
|
function detectEnvironment() {
|
|
@@ -14,1250 +47,442 @@ function detectEnvironment() {
|
|
|
14
47
|
return "prod";
|
|
15
48
|
}
|
|
16
49
|
|
|
17
|
-
// src/utils/
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
50
|
+
// src/utils/eventContext.ts
|
|
51
|
+
var DISTINCT_ID_KEY = "probat:distinct_id";
|
|
52
|
+
var SESSION_ID_KEY = "probat:session_id";
|
|
53
|
+
var cachedDistinctId = null;
|
|
54
|
+
var cachedSessionId = null;
|
|
55
|
+
function generateId() {
|
|
56
|
+
if (typeof crypto !== "undefined" && crypto.randomUUID) {
|
|
57
|
+
return crypto.randomUUID();
|
|
58
|
+
}
|
|
59
|
+
const bytes = new Uint8Array(16);
|
|
60
|
+
if (typeof crypto !== "undefined" && crypto.getRandomValues) {
|
|
61
|
+
crypto.getRandomValues(bytes);
|
|
62
|
+
} else {
|
|
63
|
+
for (let i = 0; i < 16; i++) bytes[i] = Math.floor(Math.random() * 256);
|
|
26
64
|
}
|
|
65
|
+
return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
|
|
27
66
|
}
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
this.handleMouseMove = (event) => {
|
|
37
|
-
if (!this.config.enabled || !this.config.trackCursor) return;
|
|
38
|
-
if (typeof window === "undefined") return;
|
|
39
|
-
const stored = getStoredExperimentInfo();
|
|
40
|
-
const proposalId = this.config.proposalId || stored.proposalId;
|
|
41
|
-
const variantLabel = this.config.variantLabel || stored.variantLabel;
|
|
42
|
-
const now2 = Date.now();
|
|
43
|
-
const cursorThrottle = this.config.cursorThrottle ?? 100;
|
|
44
|
-
if (now2 - this.lastCursorTime < cursorThrottle) {
|
|
45
|
-
return;
|
|
46
|
-
}
|
|
47
|
-
this.lastCursorTime = now2;
|
|
48
|
-
if (this.movements.length < 3) {
|
|
49
|
-
console.log("[PROBAT Heatmap] Cursor movement captured:", {
|
|
50
|
-
x: event.clientX,
|
|
51
|
-
y: event.clientY,
|
|
52
|
-
movementsInBatch: this.movements.length + 1
|
|
53
|
-
});
|
|
54
|
-
}
|
|
55
|
-
const pageUrl = window.location.href;
|
|
56
|
-
const siteUrl = window.location.origin;
|
|
57
|
-
const x = event.clientX;
|
|
58
|
-
const y = event.clientY;
|
|
59
|
-
const viewportWidth = window.innerWidth;
|
|
60
|
-
const viewportHeight = window.innerHeight;
|
|
61
|
-
const movementEvent = {
|
|
62
|
-
page_url: pageUrl,
|
|
63
|
-
site_url: siteUrl,
|
|
64
|
-
x_coordinate: x,
|
|
65
|
-
y_coordinate: y,
|
|
66
|
-
viewport_width: viewportWidth,
|
|
67
|
-
viewport_height: viewportHeight,
|
|
68
|
-
session_id: this.sessionId,
|
|
69
|
-
proposal_id: proposalId,
|
|
70
|
-
variant_label: variantLabel
|
|
71
|
-
};
|
|
72
|
-
this.movements.push(movementEvent);
|
|
73
|
-
const cursorBatchSize = this.config.cursorBatchSize ?? 50;
|
|
74
|
-
if (this.movements.length >= cursorBatchSize) {
|
|
75
|
-
this.sendCursorBatch();
|
|
76
|
-
} else {
|
|
77
|
-
this.scheduleCursorBatchSend();
|
|
78
|
-
}
|
|
79
|
-
};
|
|
80
|
-
this.handleClick = (event) => {
|
|
81
|
-
if (!this.config.enabled) return;
|
|
82
|
-
if (typeof window === "undefined") return;
|
|
83
|
-
const stored = getStoredExperimentInfo();
|
|
84
|
-
const proposalId = this.config.proposalId || stored.proposalId;
|
|
85
|
-
const variantLabel = this.config.variantLabel || stored.variantLabel;
|
|
86
|
-
const target = event.target;
|
|
87
|
-
if (!target) return;
|
|
88
|
-
if (this.shouldExcludeElement(target)) {
|
|
89
|
-
return;
|
|
90
|
-
}
|
|
91
|
-
const pageUrl = window.location.href;
|
|
92
|
-
const siteUrl = window.location.origin;
|
|
93
|
-
const x = event.clientX;
|
|
94
|
-
const y = event.clientY;
|
|
95
|
-
const viewportWidth = window.innerWidth;
|
|
96
|
-
const viewportHeight = window.innerHeight;
|
|
97
|
-
const elementInfo = this.extractElementInfo(target);
|
|
98
|
-
const clickEvent = {
|
|
99
|
-
page_url: pageUrl,
|
|
100
|
-
site_url: siteUrl,
|
|
101
|
-
x_coordinate: x,
|
|
102
|
-
y_coordinate: y,
|
|
103
|
-
viewport_width: viewportWidth,
|
|
104
|
-
viewport_height: viewportHeight,
|
|
105
|
-
element_tag: elementInfo.tag,
|
|
106
|
-
element_class: elementInfo.class,
|
|
107
|
-
element_id: elementInfo.id,
|
|
108
|
-
session_id: this.sessionId,
|
|
109
|
-
proposal_id: proposalId,
|
|
110
|
-
variant_label: variantLabel
|
|
111
|
-
};
|
|
112
|
-
this.clicks.push(clickEvent);
|
|
113
|
-
const batchSize = this.config.batchSize ?? 10;
|
|
114
|
-
if (this.clicks.length >= batchSize) {
|
|
115
|
-
this.sendBatch();
|
|
116
|
-
} else {
|
|
117
|
-
this.scheduleBatchSend();
|
|
118
|
-
}
|
|
119
|
-
};
|
|
120
|
-
this.sessionId = this.getOrCreateSessionId();
|
|
121
|
-
const stored = getStoredExperimentInfo();
|
|
122
|
-
this.config = {
|
|
123
|
-
apiBaseUrl: config.apiBaseUrl,
|
|
124
|
-
batchSize: config.batchSize || 10,
|
|
125
|
-
batchInterval: config.batchInterval || 5e3,
|
|
126
|
-
enabled: config.enabled !== false,
|
|
127
|
-
excludeSelectors: config.excludeSelectors || [
|
|
128
|
-
"[data-heatmap-exclude]",
|
|
129
|
-
'input[type="password"]',
|
|
130
|
-
'input[type="email"]',
|
|
131
|
-
"textarea"
|
|
132
|
-
],
|
|
133
|
-
trackCursor: config.trackCursor !== false,
|
|
134
|
-
// Enable cursor tracking by default
|
|
135
|
-
cursorThrottle: config.cursorThrottle || 100,
|
|
136
|
-
// Capture cursor position every 100ms
|
|
137
|
-
cursorBatchSize: config.cursorBatchSize || 50,
|
|
138
|
-
// Send every 50 movements
|
|
139
|
-
proposalId: config.proposalId || stored.proposalId,
|
|
140
|
-
variantLabel: config.variantLabel || stored.variantLabel
|
|
141
|
-
};
|
|
142
|
-
}
|
|
143
|
-
getOrCreateSessionId() {
|
|
144
|
-
if (typeof window === "undefined") return "";
|
|
145
|
-
const storageKey = "probat_heatmap_session_id";
|
|
146
|
-
let sessionId = localStorage.getItem(storageKey);
|
|
147
|
-
if (!sessionId) {
|
|
148
|
-
sessionId = `heatmap_${Date.now()}_${Math.random().toString(36).substring(2, 15)}`;
|
|
149
|
-
localStorage.setItem(storageKey, sessionId);
|
|
150
|
-
}
|
|
151
|
-
return sessionId;
|
|
152
|
-
}
|
|
153
|
-
shouldExcludeElement(element) {
|
|
154
|
-
if (!this.config.excludeSelectors) return false;
|
|
155
|
-
for (const selector of this.config.excludeSelectors) {
|
|
156
|
-
if (element.matches(selector) || element.closest(selector)) {
|
|
157
|
-
return true;
|
|
158
|
-
}
|
|
159
|
-
}
|
|
160
|
-
return false;
|
|
161
|
-
}
|
|
162
|
-
extractElementInfo(element) {
|
|
163
|
-
return {
|
|
164
|
-
tag: element.tagName || null,
|
|
165
|
-
class: element.className && typeof element.className === "string" ? element.className : null,
|
|
166
|
-
id: element.id || null
|
|
167
|
-
};
|
|
168
|
-
}
|
|
169
|
-
scheduleCursorBatchSend() {
|
|
170
|
-
if (this.cursorBatchTimer) {
|
|
171
|
-
clearTimeout(this.cursorBatchTimer);
|
|
172
|
-
}
|
|
173
|
-
this.cursorBatchTimer = setTimeout(() => {
|
|
174
|
-
if (this.movements.length > 0) {
|
|
175
|
-
this.sendCursorBatch();
|
|
176
|
-
}
|
|
177
|
-
}, this.config.batchInterval ?? 5e3);
|
|
178
|
-
}
|
|
179
|
-
async sendCursorBatch() {
|
|
180
|
-
if (this.movements.length === 0) return;
|
|
181
|
-
const siteUrl = this.movements[0]?.site_url || window.location.origin;
|
|
182
|
-
const batch = {
|
|
183
|
-
movements: this.movements,
|
|
184
|
-
site_url: siteUrl,
|
|
185
|
-
proposal_id: this.config.proposalId,
|
|
186
|
-
variant_label: this.config.variantLabel
|
|
187
|
-
};
|
|
188
|
-
this.movements = [];
|
|
189
|
-
if (this.cursorBatchTimer) {
|
|
190
|
-
clearTimeout(this.cursorBatchTimer);
|
|
191
|
-
this.cursorBatchTimer = null;
|
|
192
|
-
}
|
|
193
|
-
try {
|
|
194
|
-
console.log("[PROBAT Heatmap] Sending cursor movements batch:", {
|
|
195
|
-
count: batch.movements.length,
|
|
196
|
-
site_url: batch.site_url
|
|
197
|
-
});
|
|
198
|
-
const response = await fetch(`${this.config.apiBaseUrl}/api/heatmap/cursor-movements`, {
|
|
199
|
-
method: "POST",
|
|
200
|
-
headers: {
|
|
201
|
-
"Content-Type": "application/json"
|
|
202
|
-
},
|
|
203
|
-
body: JSON.stringify(batch)
|
|
204
|
-
// Don't wait for response - fire and forget for performance
|
|
205
|
-
});
|
|
206
|
-
if (!response.ok) {
|
|
207
|
-
console.warn("[PROBAT Heatmap] Failed to send cursor movements:", response.status);
|
|
208
|
-
} else {
|
|
209
|
-
console.log("[PROBAT Heatmap] Successfully sent cursor movements batch");
|
|
210
|
-
}
|
|
211
|
-
} catch (error) {
|
|
212
|
-
console.warn("[PROBAT Heatmap] Error sending cursor movements:", error);
|
|
213
|
-
}
|
|
214
|
-
}
|
|
215
|
-
scheduleBatchSend() {
|
|
216
|
-
if (this.batchTimer) {
|
|
217
|
-
clearTimeout(this.batchTimer);
|
|
218
|
-
}
|
|
219
|
-
this.batchTimer = setTimeout(() => {
|
|
220
|
-
if (this.clicks.length > 0) {
|
|
221
|
-
this.sendBatch();
|
|
222
|
-
}
|
|
223
|
-
}, this.config.batchInterval ?? 5e3);
|
|
224
|
-
}
|
|
225
|
-
async sendBatch() {
|
|
226
|
-
if (this.clicks.length === 0) return;
|
|
227
|
-
if (this.batchTimer) {
|
|
228
|
-
clearTimeout(this.batchTimer);
|
|
229
|
-
this.batchTimer = null;
|
|
230
|
-
}
|
|
231
|
-
const siteUrl = this.clicks[0]?.site_url || window.location.origin;
|
|
232
|
-
const batch = {
|
|
233
|
-
clicks: [...this.clicks],
|
|
234
|
-
site_url: siteUrl
|
|
235
|
-
};
|
|
236
|
-
this.clicks = [];
|
|
237
|
-
try {
|
|
238
|
-
const response = await fetch(`${this.config.apiBaseUrl}/api/heatmap/clicks`, {
|
|
239
|
-
method: "POST",
|
|
240
|
-
headers: {
|
|
241
|
-
"Content-Type": "application/json"
|
|
242
|
-
},
|
|
243
|
-
body: JSON.stringify(batch)
|
|
244
|
-
});
|
|
245
|
-
if (!response.ok) {
|
|
246
|
-
console.warn("[PROBAT Heatmap] Failed to send clicks:", response.status);
|
|
247
|
-
}
|
|
248
|
-
} catch (error) {
|
|
249
|
-
console.warn("[PROBAT Heatmap] Error sending clicks:", error);
|
|
67
|
+
function getDistinctId() {
|
|
68
|
+
if (cachedDistinctId) return cachedDistinctId;
|
|
69
|
+
if (typeof window === "undefined") return "server";
|
|
70
|
+
try {
|
|
71
|
+
const stored = localStorage.getItem(DISTINCT_ID_KEY);
|
|
72
|
+
if (stored) {
|
|
73
|
+
cachedDistinctId = stored;
|
|
74
|
+
return stored;
|
|
250
75
|
}
|
|
76
|
+
} catch {
|
|
251
77
|
}
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
if (typeof window === "undefined") {
|
|
258
|
-
return;
|
|
259
|
-
}
|
|
260
|
-
document.addEventListener("click", this.handleClick, true);
|
|
261
|
-
if (this.config.trackCursor) {
|
|
262
|
-
document.addEventListener("mousemove", this.handleMouseMove, { passive: true });
|
|
263
|
-
console.log("[PROBAT Heatmap] Cursor tracking enabled");
|
|
264
|
-
} else {
|
|
265
|
-
console.log("[PROBAT Heatmap] Cursor tracking disabled");
|
|
266
|
-
}
|
|
267
|
-
this.isInitialized = true;
|
|
268
|
-
console.log("[PROBAT Heatmap] Tracker initialized", {
|
|
269
|
-
enabled: this.config.enabled,
|
|
270
|
-
trackCursor: this.config.trackCursor,
|
|
271
|
-
cursorThrottle: this.config.cursorThrottle,
|
|
272
|
-
cursorBatchSize: this.config.cursorBatchSize
|
|
273
|
-
});
|
|
274
|
-
window.addEventListener("beforeunload", () => {
|
|
275
|
-
if (this.clicks.length > 0) {
|
|
276
|
-
const siteUrl = this.clicks[0]?.site_url || window.location.origin;
|
|
277
|
-
const batch = {
|
|
278
|
-
clicks: this.clicks,
|
|
279
|
-
site_url: siteUrl
|
|
280
|
-
};
|
|
281
|
-
const blob = new Blob([JSON.stringify(batch)], {
|
|
282
|
-
type: "application/json"
|
|
283
|
-
});
|
|
284
|
-
navigator.sendBeacon(
|
|
285
|
-
`${this.config.apiBaseUrl}/api/heatmap/clicks`,
|
|
286
|
-
blob
|
|
287
|
-
);
|
|
288
|
-
}
|
|
289
|
-
if (this.movements.length > 0) {
|
|
290
|
-
const siteUrl = this.movements[0]?.site_url || window.location.origin;
|
|
291
|
-
const batch = {
|
|
292
|
-
movements: this.movements,
|
|
293
|
-
site_url: siteUrl
|
|
294
|
-
};
|
|
295
|
-
const blob = new Blob([JSON.stringify(batch)], {
|
|
296
|
-
type: "application/json"
|
|
297
|
-
});
|
|
298
|
-
navigator.sendBeacon(
|
|
299
|
-
`${this.config.apiBaseUrl}/api/heatmap/cursor-movements`,
|
|
300
|
-
blob
|
|
301
|
-
);
|
|
302
|
-
}
|
|
303
|
-
});
|
|
78
|
+
const id = `anon_${generateId()}`;
|
|
79
|
+
cachedDistinctId = id;
|
|
80
|
+
try {
|
|
81
|
+
localStorage.setItem(DISTINCT_ID_KEY, id);
|
|
82
|
+
} catch {
|
|
304
83
|
}
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
document.removeEventListener("mousemove", this.handleMouseMove);
|
|
316
|
-
}
|
|
317
|
-
if (this.batchTimer) {
|
|
318
|
-
clearTimeout(this.batchTimer);
|
|
319
|
-
this.batchTimer = null;
|
|
320
|
-
}
|
|
321
|
-
if (this.cursorBatchTimer) {
|
|
322
|
-
clearTimeout(this.cursorBatchTimer);
|
|
323
|
-
this.cursorBatchTimer = null;
|
|
84
|
+
return id;
|
|
85
|
+
}
|
|
86
|
+
function getSessionId() {
|
|
87
|
+
if (cachedSessionId) return cachedSessionId;
|
|
88
|
+
if (typeof window === "undefined") return "server";
|
|
89
|
+
try {
|
|
90
|
+
const stored = sessionStorage.getItem(SESSION_ID_KEY);
|
|
91
|
+
if (stored) {
|
|
92
|
+
cachedSessionId = stored;
|
|
93
|
+
return stored;
|
|
324
94
|
}
|
|
325
|
-
|
|
95
|
+
} catch {
|
|
326
96
|
}
|
|
327
|
-
}
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
97
|
+
const id = `sess_${generateId()}`;
|
|
98
|
+
cachedSessionId = id;
|
|
99
|
+
try {
|
|
100
|
+
sessionStorage.setItem(SESSION_ID_KEY, id);
|
|
101
|
+
} catch {
|
|
332
102
|
}
|
|
333
|
-
|
|
334
|
-
trackerInstance.init();
|
|
335
|
-
return trackerInstance;
|
|
103
|
+
return id;
|
|
336
104
|
}
|
|
337
|
-
function
|
|
338
|
-
return
|
|
105
|
+
function getPageKey() {
|
|
106
|
+
if (typeof window === "undefined") return "";
|
|
107
|
+
return window.location.pathname + window.location.search;
|
|
339
108
|
}
|
|
340
|
-
function
|
|
341
|
-
if (
|
|
342
|
-
|
|
343
|
-
trackerInstance = null;
|
|
344
|
-
}
|
|
109
|
+
function getPageUrl() {
|
|
110
|
+
if (typeof window === "undefined") return "";
|
|
111
|
+
return window.location.href;
|
|
345
112
|
}
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
function ProbatProvider({
|
|
350
|
-
apiBaseUrl,
|
|
351
|
-
clientKey,
|
|
352
|
-
environment: explicitEnvironment,
|
|
353
|
-
repoFullName: explicitRepoFullName,
|
|
354
|
-
proposalId,
|
|
355
|
-
variantLabel,
|
|
356
|
-
children
|
|
357
|
-
}) {
|
|
358
|
-
const storedProposalId = typeof window !== "undefined" ? window.localStorage.getItem("probat_active_proposal_id") || void 0 : void 0;
|
|
359
|
-
const storedVariantLabel = typeof window !== "undefined" ? window.localStorage.getItem("probat_active_variant_label") || void 0 : void 0;
|
|
360
|
-
const contextValue = useMemo(() => {
|
|
361
|
-
const resolvedApiBaseUrl = apiBaseUrl || typeof import.meta !== "undefined" && import.meta.env?.VITE_PROBAT_API || typeof globalThis !== "undefined" && globalThis.process?.env?.NEXT_PUBLIC_PROBAT_API || typeof window !== "undefined" && window.__PROBAT_API || "https://gushi.onrender.com";
|
|
362
|
-
const environment = explicitEnvironment || detectEnvironment();
|
|
363
|
-
const resolvedRepoFullName = explicitRepoFullName || typeof globalThis !== "undefined" && globalThis.process?.env?.NEXT_PUBLIC_PROBAT_REPO || typeof import.meta !== "undefined" && import.meta.env?.VITE_PROBAT_REPO || typeof window !== "undefined" && window.__PROBAT_REPO || void 0;
|
|
364
|
-
return {
|
|
365
|
-
apiBaseUrl: resolvedApiBaseUrl,
|
|
366
|
-
environment,
|
|
367
|
-
clientKey,
|
|
368
|
-
repoFullName: resolvedRepoFullName,
|
|
369
|
-
proposalId: proposalId || storedProposalId,
|
|
370
|
-
variantLabel: variantLabel || storedVariantLabel
|
|
371
|
-
};
|
|
372
|
-
}, [apiBaseUrl, clientKey, explicitEnvironment, explicitRepoFullName, proposalId, variantLabel, storedProposalId, storedVariantLabel]);
|
|
373
|
-
useEffect(() => {
|
|
374
|
-
if (typeof window !== "undefined") {
|
|
375
|
-
initHeatmapTracking({
|
|
376
|
-
apiBaseUrl: contextValue.apiBaseUrl,
|
|
377
|
-
batchSize: 10,
|
|
378
|
-
batchInterval: 5e3,
|
|
379
|
-
enabled: true,
|
|
380
|
-
excludeSelectors: [
|
|
381
|
-
"[data-heatmap-exclude]",
|
|
382
|
-
'input[type="password"]',
|
|
383
|
-
'input[type="email"]',
|
|
384
|
-
"textarea"
|
|
385
|
-
],
|
|
386
|
-
// Explicitly enable cursor tracking with sensible defaults
|
|
387
|
-
trackCursor: true,
|
|
388
|
-
cursorThrottle: 100,
|
|
389
|
-
// capture every 100ms
|
|
390
|
-
cursorBatchSize: 50,
|
|
391
|
-
// send every 50 movements (or after batchInterval)
|
|
392
|
-
proposalId: contextValue.proposalId,
|
|
393
|
-
variantLabel: contextValue.variantLabel
|
|
394
|
-
});
|
|
395
|
-
}
|
|
396
|
-
return () => {
|
|
397
|
-
stopHeatmapTracking();
|
|
398
|
-
};
|
|
399
|
-
}, [contextValue.apiBaseUrl]);
|
|
400
|
-
return /* @__PURE__ */ React4.createElement(ProbatContext.Provider, { value: contextValue }, children);
|
|
401
|
-
}
|
|
402
|
-
function useProbatContext() {
|
|
403
|
-
const context = useContext(ProbatContext);
|
|
404
|
-
if (!context) {
|
|
405
|
-
throw new Error(
|
|
406
|
-
"useProbatContext must be used within a ProbatProvider. Please wrap your app with <ProbatProvider>."
|
|
407
|
-
);
|
|
408
|
-
}
|
|
409
|
-
return context;
|
|
113
|
+
function getReferrer() {
|
|
114
|
+
if (typeof document === "undefined") return "";
|
|
115
|
+
return document.referrer;
|
|
410
116
|
}
|
|
411
|
-
function
|
|
412
|
-
return
|
|
117
|
+
function buildEventContext() {
|
|
118
|
+
return {
|
|
119
|
+
distinct_id: getDistinctId(),
|
|
120
|
+
session_id: getSessionId(),
|
|
121
|
+
$page_url: getPageUrl(),
|
|
122
|
+
$pathname: typeof window !== "undefined" ? window.location.pathname : "",
|
|
123
|
+
$referrer: getReferrer()
|
|
124
|
+
};
|
|
413
125
|
}
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
const
|
|
126
|
+
|
|
127
|
+
// src/utils/api.ts
|
|
128
|
+
var pendingDecisions = /* @__PURE__ */ new Map();
|
|
129
|
+
async function fetchDecision(host, experimentId, distinctId) {
|
|
130
|
+
const existing = pendingDecisions.get(experimentId);
|
|
131
|
+
if (existing) return existing;
|
|
132
|
+
const promise = (async () => {
|
|
421
133
|
try {
|
|
422
|
-
const url = `${
|
|
134
|
+
const url = `${host.replace(/\/$/, "")}/experiment/decide`;
|
|
423
135
|
const res = await fetch(url, {
|
|
424
136
|
method: "POST",
|
|
425
|
-
headers: {
|
|
426
|
-
|
|
427
|
-
|
|
137
|
+
headers: {
|
|
138
|
+
"Content-Type": "application/json",
|
|
139
|
+
Accept: "application/json"
|
|
140
|
+
},
|
|
141
|
+
credentials: "include",
|
|
142
|
+
body: JSON.stringify({
|
|
143
|
+
experiment_id: experimentId,
|
|
144
|
+
distinct_id: distinctId
|
|
145
|
+
})
|
|
428
146
|
});
|
|
429
147
|
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
|
430
148
|
const data = await res.json();
|
|
431
|
-
|
|
432
|
-
const label = data.label && data.label.trim() ? data.label : "control";
|
|
433
|
-
if (typeof window !== "undefined") {
|
|
434
|
-
try {
|
|
435
|
-
window.localStorage.setItem("probat_active_proposal_id", proposalId);
|
|
436
|
-
window.localStorage.setItem("probat_active_variant_label", label);
|
|
437
|
-
} catch (e) {
|
|
438
|
-
console.warn("[PROBAT] Failed to set proposal/variant in localStorage:", e);
|
|
439
|
-
}
|
|
440
|
-
}
|
|
441
|
-
return { experiment_id, label };
|
|
149
|
+
return data.variant_key || "control";
|
|
442
150
|
} finally {
|
|
443
|
-
|
|
151
|
+
pendingDecisions.delete(experimentId);
|
|
444
152
|
}
|
|
445
153
|
})();
|
|
446
|
-
|
|
447
|
-
return
|
|
154
|
+
pendingDecisions.set(experimentId, promise);
|
|
155
|
+
return promise;
|
|
448
156
|
}
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
const
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
captured_at: (/* @__PURE__ */ new Date()).toISOString()
|
|
157
|
+
function sendMetric(host, event, properties) {
|
|
158
|
+
if (typeof window === "undefined") return;
|
|
159
|
+
const ctx = buildEventContext();
|
|
160
|
+
const payload = {
|
|
161
|
+
event,
|
|
162
|
+
properties: {
|
|
163
|
+
...ctx,
|
|
164
|
+
environment: detectEnvironment(),
|
|
165
|
+
source: "react-sdk",
|
|
166
|
+
captured_at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
167
|
+
...properties
|
|
168
|
+
}
|
|
462
169
|
};
|
|
463
170
|
try {
|
|
464
|
-
|
|
171
|
+
const url = `${host.replace(/\/$/, "")}/experiment/metrics`;
|
|
172
|
+
fetch(url, {
|
|
465
173
|
method: "POST",
|
|
466
|
-
headers: {
|
|
467
|
-
Accept: "application/json",
|
|
468
|
-
"Content-Type": "application/json"
|
|
469
|
-
},
|
|
174
|
+
headers: { "Content-Type": "application/json" },
|
|
470
175
|
credentials: "include",
|
|
471
|
-
|
|
472
|
-
|
|
176
|
+
body: JSON.stringify(payload)
|
|
177
|
+
}).catch(() => {
|
|
473
178
|
});
|
|
474
179
|
} catch {
|
|
475
180
|
}
|
|
476
181
|
}
|
|
477
|
-
function extractClickMeta(
|
|
478
|
-
if (!
|
|
479
|
-
const
|
|
480
|
-
if (
|
|
481
|
-
const
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
182
|
+
function extractClickMeta(target) {
|
|
183
|
+
if (!target || !(target instanceof HTMLElement)) return null;
|
|
184
|
+
const primary = target.closest('[data-probat-click="primary"]');
|
|
185
|
+
if (primary) return buildMeta(primary, true);
|
|
186
|
+
const interactive = target.closest('button, a, [role="button"]');
|
|
187
|
+
if (interactive) return buildMeta(interactive, false);
|
|
188
|
+
return null;
|
|
189
|
+
}
|
|
190
|
+
function buildMeta(el, isPrimary) {
|
|
485
191
|
const meta = {
|
|
486
|
-
|
|
192
|
+
click_target_tag: el.tagName,
|
|
193
|
+
click_is_primary: isPrimary
|
|
487
194
|
};
|
|
488
|
-
if (
|
|
489
|
-
const
|
|
490
|
-
if (
|
|
491
|
-
const text = actionable.textContent?.trim();
|
|
492
|
-
if (text) meta.target_text = text.slice(0, 120);
|
|
195
|
+
if (el.id) meta.click_target_id = el.id;
|
|
196
|
+
const text = el.textContent?.trim();
|
|
197
|
+
if (text) meta.click_target_text = text.slice(0, 120);
|
|
493
198
|
return meta;
|
|
494
199
|
}
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
}
|
|
502
|
-
const fetchPromise = (async () => {
|
|
503
|
-
try {
|
|
504
|
-
const url = new URL(`${baseUrl.replace(/\/$/, "")}/get_component_experiment_config`);
|
|
505
|
-
url.searchParams.set("repo_full_name", repoFullName);
|
|
506
|
-
url.searchParams.set("component_path", componentPath);
|
|
507
|
-
const res = await fetch(url.toString(), {
|
|
508
|
-
method: "GET",
|
|
509
|
-
headers: { Accept: "application/json" },
|
|
510
|
-
credentials: "include"
|
|
511
|
-
});
|
|
512
|
-
if (res.status === 404) {
|
|
513
|
-
return null;
|
|
514
|
-
}
|
|
515
|
-
if (!res.ok) {
|
|
516
|
-
throw new Error(`HTTP ${res.status}`);
|
|
517
|
-
}
|
|
518
|
-
const data = await res.json();
|
|
519
|
-
if (typeof window !== "undefined" && data?.proposal_id) {
|
|
520
|
-
try {
|
|
521
|
-
window.localStorage.setItem("probat_active_proposal_id", data.proposal_id);
|
|
522
|
-
} catch (e) {
|
|
523
|
-
console.warn("[PROBAT] Failed to set proposal_id in localStorage:", e);
|
|
524
|
-
}
|
|
525
|
-
}
|
|
526
|
-
return data;
|
|
527
|
-
} catch (e) {
|
|
528
|
-
console.warn(`[PROBAT] Failed to fetch component config: ${e}`);
|
|
529
|
-
return null;
|
|
530
|
-
} finally {
|
|
531
|
-
componentConfigCache.delete(cacheKey);
|
|
532
|
-
}
|
|
533
|
-
})();
|
|
534
|
-
componentConfigCache.set(cacheKey, fetchPromise);
|
|
535
|
-
return fetchPromise;
|
|
200
|
+
|
|
201
|
+
// src/utils/dedupeStorage.ts
|
|
202
|
+
var PREFIX = "probat:seen:";
|
|
203
|
+
var memorySet = /* @__PURE__ */ new Set();
|
|
204
|
+
function makeDedupeKey(experimentId, variantKey, instanceId, pageKey) {
|
|
205
|
+
return `${PREFIX}${experimentId}:${variantKey}:${instanceId}:${pageKey}`;
|
|
536
206
|
}
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
if (typeof window
|
|
540
|
-
|
|
541
|
-
|
|
207
|
+
function hasSeen(key) {
|
|
208
|
+
if (memorySet.has(key)) return true;
|
|
209
|
+
if (typeof window === "undefined") return false;
|
|
210
|
+
try {
|
|
211
|
+
return sessionStorage.getItem(key) === "1";
|
|
212
|
+
} catch {
|
|
213
|
+
return false;
|
|
214
|
+
}
|
|
542
215
|
}
|
|
543
|
-
function
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
parts.pop();
|
|
550
|
-
} else if (part !== ".") {
|
|
551
|
-
parts.push(part);
|
|
552
|
-
}
|
|
216
|
+
function markSeen(key) {
|
|
217
|
+
memorySet.add(key);
|
|
218
|
+
if (typeof window === "undefined") return;
|
|
219
|
+
try {
|
|
220
|
+
sessionStorage.setItem(key, "1");
|
|
221
|
+
} catch {
|
|
553
222
|
}
|
|
554
|
-
return "/" + parts.join("/");
|
|
555
223
|
}
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
224
|
+
var INSTANCE_PREFIX = "probat:instance:";
|
|
225
|
+
function shortId() {
|
|
226
|
+
const bytes = new Uint8Array(4);
|
|
227
|
+
if (typeof crypto !== "undefined" && crypto.getRandomValues) {
|
|
228
|
+
crypto.getRandomValues(bytes);
|
|
229
|
+
} else {
|
|
230
|
+
for (let i = 0; i < 4; i++) bytes[i] = Math.floor(Math.random() * 256);
|
|
560
231
|
}
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
const testPath = absolutePath + (absolutePath.includes(".") ? "" : ext);
|
|
232
|
+
return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
|
|
233
|
+
}
|
|
234
|
+
function resolveStableId(storageKey) {
|
|
235
|
+
if (typeof window !== "undefined") {
|
|
566
236
|
try {
|
|
567
|
-
const
|
|
568
|
-
|
|
569
|
-
headers: { Accept: "text/plain" }
|
|
570
|
-
});
|
|
571
|
-
if (localRes.ok) {
|
|
572
|
-
moduleCode = await localRes.text();
|
|
573
|
-
modulePath = testPath;
|
|
574
|
-
break;
|
|
575
|
-
}
|
|
237
|
+
const stored = sessionStorage.getItem(storageKey);
|
|
238
|
+
if (stored) return stored;
|
|
576
239
|
} catch {
|
|
577
240
|
}
|
|
578
|
-
if (!moduleCode && repoFullName) {
|
|
579
|
-
try {
|
|
580
|
-
const githubPath = testPath.startsWith("/") ? testPath.substring(1) : testPath;
|
|
581
|
-
const githubUrl = `https://raw.githubusercontent.com/${repoFullName}/${baseRef || "main"}/${githubPath}`;
|
|
582
|
-
const res = await fetch(githubUrl, { method: "GET", headers: { Accept: "text/plain" } });
|
|
583
|
-
if (res.ok) {
|
|
584
|
-
moduleCode = await res.text();
|
|
585
|
-
modulePath = testPath;
|
|
586
|
-
break;
|
|
587
|
-
}
|
|
588
|
-
} catch {
|
|
589
|
-
}
|
|
590
|
-
}
|
|
591
|
-
}
|
|
592
|
-
if (!moduleCode || !modulePath) {
|
|
593
|
-
throw new Error(`Could not resolve module: ${absolutePath} from ${baseFilePath}`);
|
|
594
241
|
}
|
|
595
|
-
|
|
596
|
-
if (typeof window !== "undefined"
|
|
597
|
-
Babel = window.Babel;
|
|
598
|
-
} else {
|
|
242
|
+
const id = `inst_${shortId()}`;
|
|
243
|
+
if (typeof window !== "undefined") {
|
|
599
244
|
try {
|
|
600
|
-
|
|
601
|
-
Babel = babelModule.default || babelModule;
|
|
245
|
+
sessionStorage.setItem(storageKey, id);
|
|
602
246
|
} catch {
|
|
603
|
-
throw new Error("Babel not available for compiling relative import");
|
|
604
247
|
}
|
|
605
248
|
}
|
|
606
|
-
|
|
607
|
-
processedCode = processedCode.replace(/^import\s+['"].*\.css['"];?\s*$/gm, "");
|
|
608
|
-
processedCode = processedCode.replace(/^import\s+React\s+from\s+['"]react['"];?\s*$/m, "const React = window.React || globalThis.React;");
|
|
609
|
-
processedCode = processedCode.replace(/import\.meta\.env\.[\w$]+/g, "undefined");
|
|
610
|
-
processedCode = processedCode.replace(/\bimport\.meta\b/g, "({})");
|
|
611
|
-
const isTSX = modulePath.endsWith(".tsx");
|
|
612
|
-
const compiled = Babel.transform(processedCode, {
|
|
613
|
-
presets: [
|
|
614
|
-
["react", { runtime: "classic" }],
|
|
615
|
-
["typescript", { allExtensions: true, isTSX }]
|
|
616
|
-
],
|
|
617
|
-
plugins: [["transform-modules-commonjs", { allowTopLevelThis: true }]],
|
|
618
|
-
sourceType: "module",
|
|
619
|
-
filename: modulePath
|
|
620
|
-
}).code;
|
|
621
|
-
const moduleCodeWrapper = `
|
|
622
|
-
var require = function(name) {
|
|
623
|
-
if (name === "react" || name === "react/jsx-runtime") {
|
|
624
|
-
return window.React || globalThis.React;
|
|
625
|
-
}
|
|
626
|
-
if (name.startsWith("/@vite") || name.includes("@vite/client")) {
|
|
627
|
-
return {};
|
|
628
|
-
}
|
|
629
|
-
throw new Error("Unsupported module in relative import: " + name);
|
|
630
|
-
};
|
|
631
|
-
var module = { exports: {} };
|
|
632
|
-
var exports = module.exports;
|
|
633
|
-
${compiled}
|
|
634
|
-
return module.exports;
|
|
635
|
-
`;
|
|
636
|
-
const moduleExports = new Function(moduleCodeWrapper)();
|
|
637
|
-
moduleCache.set(cacheKey, moduleExports);
|
|
638
|
-
return moduleExports;
|
|
249
|
+
return id;
|
|
639
250
|
}
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
251
|
+
var slotCounters = /* @__PURE__ */ new Map();
|
|
252
|
+
var resetScheduled = false;
|
|
253
|
+
function claimSlot(groupKey) {
|
|
254
|
+
const idx = slotCounters.get(groupKey) ?? 0;
|
|
255
|
+
slotCounters.set(groupKey, idx + 1);
|
|
256
|
+
if (!resetScheduled) {
|
|
257
|
+
resetScheduled = true;
|
|
258
|
+
Promise.resolve().then(() => {
|
|
259
|
+
slotCounters.clear();
|
|
260
|
+
resetScheduled = false;
|
|
261
|
+
});
|
|
648
262
|
}
|
|
649
|
-
|
|
650
|
-
try {
|
|
651
|
-
let code = "";
|
|
652
|
-
let rawCode = "";
|
|
653
|
-
let rawCodeFetched = false;
|
|
654
|
-
const isBrowser = typeof window !== "undefined";
|
|
655
|
-
const isNextJS = isBrowser && (window.__NEXT_DATA__ !== void 0 || window.__NEXT_LOADED_PAGES__ !== void 0 || typeof globalThis.__NEXT_DATA__ !== "undefined");
|
|
656
|
-
if (isBrowser && !isNextJS) {
|
|
657
|
-
try {
|
|
658
|
-
const variantUrl = `/probat/${filePath}`;
|
|
659
|
-
const dynamicImportFunc = new Function("url", "return import(url)");
|
|
660
|
-
const mod = await dynamicImportFunc(variantUrl);
|
|
661
|
-
const VariantComponent2 = mod?.default || mod;
|
|
662
|
-
if (VariantComponent2 && typeof VariantComponent2 === "function") {
|
|
663
|
-
console.log(`[PROBAT] \u2705 Loaded variant via dynamic import (CSR): ${variantUrl}`);
|
|
664
|
-
return VariantComponent2;
|
|
665
|
-
}
|
|
666
|
-
} catch (dynamicImportError) {
|
|
667
|
-
console.debug(`[PROBAT] Dynamic import failed, using fetch+babel:`, dynamicImportError);
|
|
668
|
-
}
|
|
669
|
-
}
|
|
670
|
-
const localUrl = `/probat/${filePath}`;
|
|
671
|
-
try {
|
|
672
|
-
const localRes = await fetch(localUrl, {
|
|
673
|
-
method: "GET",
|
|
674
|
-
headers: { Accept: "text/plain" }
|
|
675
|
-
});
|
|
676
|
-
if (localRes.ok) {
|
|
677
|
-
rawCode = await localRes.text();
|
|
678
|
-
rawCodeFetched = true;
|
|
679
|
-
console.log(`[PROBAT] \u2705 Loaded variant from local (user's repo): ${localUrl}`);
|
|
680
|
-
}
|
|
681
|
-
} catch {
|
|
682
|
-
console.debug(`[PROBAT] Local file not available (${localUrl}), trying GitHub...`);
|
|
683
|
-
}
|
|
684
|
-
if (!rawCodeFetched && repoFullName) {
|
|
685
|
-
const githubPath = `probat/${filePath}`;
|
|
686
|
-
const gitRef = baseRef || "main";
|
|
687
|
-
const githubUrl = `https://raw.githubusercontent.com/${repoFullName}/${gitRef}/${githubPath}`;
|
|
688
|
-
const res = await fetch(githubUrl, { method: "GET", headers: { Accept: "text/plain" } });
|
|
689
|
-
if (res.ok) {
|
|
690
|
-
rawCode = await res.text();
|
|
691
|
-
rawCodeFetched = true;
|
|
692
|
-
console.log(`[PROBAT] \u26A0\uFE0F Loaded variant from GitHub (fallback): ${githubUrl}`);
|
|
693
|
-
} else {
|
|
694
|
-
console.warn(`[PROBAT] \u26A0\uFE0F GitHub fetch failed (${res.status}), falling back to server compilation`);
|
|
695
|
-
}
|
|
696
|
-
}
|
|
697
|
-
if (rawCodeFetched && rawCode) {
|
|
698
|
-
let Babel;
|
|
699
|
-
if (typeof window !== "undefined" && window.Babel) {
|
|
700
|
-
Babel = window.Babel;
|
|
701
|
-
} else {
|
|
702
|
-
try {
|
|
703
|
-
const babelModule = await import('@babel/standalone');
|
|
704
|
-
Babel = babelModule.default || babelModule;
|
|
705
|
-
} catch (importError) {
|
|
706
|
-
try {
|
|
707
|
-
await new Promise((resolve, reject) => {
|
|
708
|
-
if (typeof document === "undefined") {
|
|
709
|
-
reject(new Error("Document not available"));
|
|
710
|
-
return;
|
|
711
|
-
}
|
|
712
|
-
if (window.Babel) {
|
|
713
|
-
Babel = window.Babel;
|
|
714
|
-
resolve();
|
|
715
|
-
return;
|
|
716
|
-
}
|
|
717
|
-
const script = document.createElement("script");
|
|
718
|
-
script.src = "https://unpkg.com/@babel/standalone/babel.min.js";
|
|
719
|
-
script.async = true;
|
|
720
|
-
script.onload = () => {
|
|
721
|
-
Babel = window.Babel;
|
|
722
|
-
if (!Babel) reject(new Error("Babel not found after script load"));
|
|
723
|
-
else resolve();
|
|
724
|
-
};
|
|
725
|
-
script.onerror = () => reject(new Error("Failed to load Babel from CDN"));
|
|
726
|
-
document.head.appendChild(script);
|
|
727
|
-
});
|
|
728
|
-
} catch (babelError) {
|
|
729
|
-
console.error("[PROBAT] Failed to load Babel, falling back to server compilation", babelError);
|
|
730
|
-
rawCodeFetched = false;
|
|
731
|
-
}
|
|
732
|
-
}
|
|
733
|
-
}
|
|
734
|
-
if (rawCodeFetched && rawCode && Babel) {
|
|
735
|
-
const isTSX = filePath.endsWith(".tsx");
|
|
736
|
-
rawCode = rawCode.replace(/^import\s+['"].*\.css['"];?\s*$/gm, "");
|
|
737
|
-
rawCode = rawCode.replace(/^import\s+.*from\s+['"].*\.css['"];?\s*$/gm, "");
|
|
738
|
-
rawCode = rawCode.replace(
|
|
739
|
-
/^import\s+React(?:\s*,\s*\{[^}]*\})?\s+from\s+['"]react['"];?\s*$/m,
|
|
740
|
-
"const React = window.React || globalThis.React;"
|
|
741
|
-
);
|
|
742
|
-
rawCode = rawCode.replace(
|
|
743
|
-
/^import\s+\*\s+as\s+React\s+from\s+['"]react['"];?\s*$/m,
|
|
744
|
-
"const React = window.React || globalThis.React;"
|
|
745
|
-
);
|
|
746
|
-
rawCode = rawCode.replace(
|
|
747
|
-
/^import\s+\{([^}]+)\}\s+from\s+['"]react['"];?\s*$/m,
|
|
748
|
-
(match, imports) => `const {${imports}} = window.React || globalThis.React;`
|
|
749
|
-
);
|
|
750
|
-
rawCode = rawCode.replace(/import\.meta\.env\.[\w$]+/g, "undefined");
|
|
751
|
-
rawCode = rawCode.replace(/\bimport\.meta\b/g, "({})");
|
|
752
|
-
rawCode = rawCode.replace(/^import\s+.*\/@vite\/client.*$/gm, "");
|
|
753
|
-
rawCode = rawCode.replace(/import\.meta\.hot(?:\.[\w$]+)*/g, "undefined");
|
|
754
|
-
const relativeImportMap = /* @__PURE__ */ new Map();
|
|
755
|
-
rawCode = rawCode.replace(
|
|
756
|
-
/^import\s+(\w+)\s+from\s+['"](\.\.?\/[^'"]+)['"];?\s*$/gm,
|
|
757
|
-
(match, importName, relativePath) => {
|
|
758
|
-
const baseDir = filePath.substring(0, filePath.lastIndexOf("/"));
|
|
759
|
-
const resolvedPath = resolveRelativePath(relativePath, baseDir);
|
|
760
|
-
const absolutePath = resolvedPath.startsWith("/") ? resolvedPath : "/" + resolvedPath;
|
|
761
|
-
relativeImportMap.set(importName, absolutePath);
|
|
762
|
-
return `import ${importName} from "${absolutePath}";`;
|
|
763
|
-
}
|
|
764
|
-
);
|
|
765
|
-
const compiled = Babel.transform(rawCode, {
|
|
766
|
-
presets: [
|
|
767
|
-
["react", { runtime: "classic" }],
|
|
768
|
-
["typescript", { allExtensions: true, isTSX }]
|
|
769
|
-
],
|
|
770
|
-
plugins: [["transform-modules-commonjs", { allowTopLevelThis: true }]],
|
|
771
|
-
sourceType: "module",
|
|
772
|
-
filename: filePath
|
|
773
|
-
}).code;
|
|
774
|
-
const relativeModules = {};
|
|
775
|
-
if (relativeImportMap.size > 0) {
|
|
776
|
-
for (const [importName, absolutePath] of relativeImportMap.entries()) {
|
|
777
|
-
try {
|
|
778
|
-
const moduleExports = await loadRelativeModule(absolutePath, filePath, repoFullName, baseRef);
|
|
779
|
-
relativeModules[absolutePath] = moduleExports.default || moduleExports;
|
|
780
|
-
} catch (err) {
|
|
781
|
-
console.warn(`[PROBAT] Failed to load relative import ${absolutePath}:`, err);
|
|
782
|
-
relativeModules[absolutePath] = null;
|
|
783
|
-
}
|
|
784
|
-
}
|
|
785
|
-
}
|
|
786
|
-
const relativeModulesJson = JSON.stringify(relativeModules);
|
|
787
|
-
code = `
|
|
788
|
-
var __probatVariant = (function() {
|
|
789
|
-
var relativeModules = ${relativeModulesJson};
|
|
790
|
-
var require = function(name) {
|
|
791
|
-
if (name === "react" || name === "react/jsx-runtime") {
|
|
792
|
-
return window.React || globalThis.React;
|
|
793
|
-
}
|
|
794
|
-
if (name.startsWith("/@vite") || name.includes("@vite/client") || name.includes(".vite/deps")) {
|
|
795
|
-
return {};
|
|
796
|
-
}
|
|
797
|
-
if (name === "react/jsx-runtime.js") {
|
|
798
|
-
return window.React || globalThis.React;
|
|
799
|
-
}
|
|
800
|
-
// Handle relative imports (now converted to absolute paths)
|
|
801
|
-
if (name.startsWith("/") && relativeModules.hasOwnProperty(name)) {
|
|
802
|
-
var mod = relativeModules[name];
|
|
803
|
-
if (mod === null) {
|
|
804
|
-
throw new Error("Failed to load module: " + name);
|
|
805
|
-
}
|
|
806
|
-
return mod;
|
|
807
|
-
}
|
|
808
|
-
throw new Error("Unsupported module: " + name);
|
|
809
|
-
};
|
|
810
|
-
var module = { exports: {} };
|
|
811
|
-
var exports = module.exports;
|
|
812
|
-
${compiled}
|
|
813
|
-
return module.exports.default || module.exports;
|
|
814
|
-
})();
|
|
815
|
-
`;
|
|
816
|
-
} else {
|
|
817
|
-
rawCodeFetched = false;
|
|
818
|
-
code = "";
|
|
819
|
-
}
|
|
820
|
-
}
|
|
821
|
-
if (!rawCodeFetched || code === "") {
|
|
822
|
-
const variantUrl = `${baseUrl.replace(/\/$/, "")}/variants/${filePath}`;
|
|
823
|
-
const serverRes = await fetch(variantUrl, {
|
|
824
|
-
method: "GET",
|
|
825
|
-
headers: { Accept: "text/javascript" },
|
|
826
|
-
credentials: "include"
|
|
827
|
-
});
|
|
828
|
-
if (!serverRes.ok) {
|
|
829
|
-
throw new Error(`HTTP ${serverRes.status}`);
|
|
830
|
-
}
|
|
831
|
-
code = await serverRes.text();
|
|
832
|
-
}
|
|
833
|
-
if (typeof window !== "undefined") {
|
|
834
|
-
window.React = window.React || React4;
|
|
835
|
-
}
|
|
836
|
-
const evalFunc = new Function(`
|
|
837
|
-
var __probatVariant;
|
|
838
|
-
${code}
|
|
839
|
-
return __probatVariant;
|
|
840
|
-
`);
|
|
841
|
-
const result = evalFunc();
|
|
842
|
-
const VariantComponent = result?.default || result;
|
|
843
|
-
if (typeof VariantComponent === "function") {
|
|
844
|
-
return VariantComponent;
|
|
845
|
-
}
|
|
846
|
-
console.warn("[PROBAT] Variant component is not a function", result);
|
|
847
|
-
return null;
|
|
848
|
-
} catch (e) {
|
|
849
|
-
console.warn(`[PROBAT] Failed to load variant component: ${e}`);
|
|
850
|
-
return null;
|
|
851
|
-
} finally {
|
|
852
|
-
variantComponentCache.delete(cacheKey);
|
|
853
|
-
}
|
|
854
|
-
})();
|
|
855
|
-
variantComponentCache.set(cacheKey, loadPromise);
|
|
856
|
-
return loadPromise;
|
|
263
|
+
return idx;
|
|
857
264
|
}
|
|
858
|
-
|
|
859
|
-
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
(
|
|
864
|
-
|
|
865
|
-
|
|
866
|
-
return false;
|
|
867
|
-
}
|
|
868
|
-
const proposalId = options?.proposalId;
|
|
869
|
-
const variantLabel = options?.variantLabel || "control";
|
|
870
|
-
if (!proposalId) {
|
|
871
|
-
console.warn(
|
|
872
|
-
"[Probat] trackClick called without proposalId. Provide it in options or use useExperiment hook."
|
|
873
|
-
);
|
|
874
|
-
return false;
|
|
875
|
-
}
|
|
876
|
-
void sendMetric(
|
|
877
|
-
apiBaseUrl,
|
|
878
|
-
proposalId,
|
|
879
|
-
"click",
|
|
880
|
-
variantLabel,
|
|
881
|
-
void 0,
|
|
882
|
-
{ ...meta, ...options?.dimensions }
|
|
883
|
-
);
|
|
884
|
-
return true;
|
|
885
|
-
},
|
|
886
|
-
[apiBaseUrl]
|
|
887
|
-
);
|
|
888
|
-
const trackMetric = useCallback(
|
|
889
|
-
(metricName, proposalId, variantLabel = "control", dimensions = {}) => {
|
|
890
|
-
void sendMetric(
|
|
891
|
-
apiBaseUrl,
|
|
892
|
-
proposalId,
|
|
893
|
-
metricName,
|
|
894
|
-
variantLabel,
|
|
895
|
-
void 0,
|
|
896
|
-
dimensions
|
|
897
|
-
);
|
|
898
|
-
},
|
|
899
|
-
[apiBaseUrl]
|
|
900
|
-
);
|
|
901
|
-
const trackImpression = useCallback(
|
|
902
|
-
(proposalId, variantLabel = "control", experimentId) => {
|
|
903
|
-
void sendMetric(
|
|
904
|
-
apiBaseUrl,
|
|
905
|
-
proposalId,
|
|
906
|
-
"visit",
|
|
907
|
-
variantLabel,
|
|
908
|
-
experimentId
|
|
909
|
-
);
|
|
910
|
-
},
|
|
911
|
-
[apiBaseUrl]
|
|
912
|
-
);
|
|
913
|
-
return {
|
|
914
|
-
trackClick,
|
|
915
|
-
trackMetric,
|
|
916
|
-
trackImpression
|
|
917
|
-
};
|
|
265
|
+
function useStableInstanceIdV18(experimentId) {
|
|
266
|
+
const reactId = React3.useId();
|
|
267
|
+
const ref = useRef("");
|
|
268
|
+
if (!ref.current) {
|
|
269
|
+
const key = `${INSTANCE_PREFIX}${experimentId}:${getPageKey()}:${reactId}`;
|
|
270
|
+
ref.current = resolveStableId(key);
|
|
271
|
+
}
|
|
272
|
+
return ref.current;
|
|
918
273
|
}
|
|
919
|
-
|
|
920
|
-
|
|
921
|
-
|
|
922
|
-
|
|
923
|
-
|
|
924
|
-
const raw = localStorage.getItem(k);
|
|
925
|
-
return raw ? JSON.parse(raw) : null;
|
|
926
|
-
} catch {
|
|
927
|
-
return null;
|
|
274
|
+
function useStableInstanceIdFallback(experimentId) {
|
|
275
|
+
const slotRef = useRef(-1);
|
|
276
|
+
const ref = useRef("");
|
|
277
|
+
if (slotRef.current === -1) {
|
|
278
|
+
slotRef.current = claimSlot(`${experimentId}:${getPageKey()}`);
|
|
928
279
|
}
|
|
929
|
-
|
|
930
|
-
|
|
931
|
-
|
|
932
|
-
localStorage.setItem(k, JSON.stringify(v));
|
|
933
|
-
} catch {
|
|
280
|
+
if (!ref.current) {
|
|
281
|
+
const key = `${INSTANCE_PREFIX}${experimentId}:${getPageKey()}:${slotRef.current}`;
|
|
282
|
+
ref.current = resolveStableId(key);
|
|
934
283
|
}
|
|
284
|
+
return ref.current;
|
|
935
285
|
}
|
|
936
|
-
function
|
|
937
|
-
|
|
938
|
-
|
|
939
|
-
|
|
940
|
-
|
|
941
|
-
|
|
942
|
-
var KEY = (proposalId) => `probat_choice_v3:${proposalId}`;
|
|
943
|
-
var VISIT_KEY = (proposalId, label) => `probat_visit_v1:${proposalId}:${label}`;
|
|
944
|
-
function readChoice(proposalId) {
|
|
945
|
-
const c = safeGet(KEY(proposalId));
|
|
946
|
-
return c && fresh(c.ts) ? c : null;
|
|
947
|
-
}
|
|
948
|
-
function writeChoice(proposalId, experiment_id, label) {
|
|
949
|
-
safeSet(KEY(proposalId), { experiment_id, label, ts: now() });
|
|
950
|
-
}
|
|
951
|
-
var visitMemo = /* @__PURE__ */ new Set();
|
|
952
|
-
function hasTrackedVisit(proposalId, label) {
|
|
953
|
-
const key = VISIT_KEY(proposalId, label);
|
|
954
|
-
if (visitMemo.has(key)) return true;
|
|
286
|
+
var useStableInstanceId = typeof React3.useId === "function" ? useStableInstanceIdV18 : useStableInstanceIdFallback;
|
|
287
|
+
|
|
288
|
+
// src/components/Experiment.tsx
|
|
289
|
+
var ASSIGNMENT_PREFIX = "probat:assignment:";
|
|
290
|
+
function readAssignment(id) {
|
|
291
|
+
if (typeof window === "undefined") return null;
|
|
955
292
|
try {
|
|
956
|
-
const raw = localStorage.getItem(
|
|
957
|
-
if (!raw) return
|
|
958
|
-
const
|
|
959
|
-
|
|
960
|
-
if (now() - ts > TTL_MS) {
|
|
961
|
-
localStorage.removeItem(key);
|
|
962
|
-
return false;
|
|
963
|
-
}
|
|
964
|
-
visitMemo.add(key);
|
|
965
|
-
return true;
|
|
293
|
+
const raw = localStorage.getItem(ASSIGNMENT_PREFIX + id);
|
|
294
|
+
if (!raw) return null;
|
|
295
|
+
const parsed = JSON.parse(raw);
|
|
296
|
+
return parsed.variantKey ?? null;
|
|
966
297
|
} catch {
|
|
967
|
-
return
|
|
298
|
+
return null;
|
|
968
299
|
}
|
|
969
300
|
}
|
|
970
|
-
function
|
|
971
|
-
|
|
972
|
-
visitMemo.add(key);
|
|
301
|
+
function writeAssignment(id, variantKey) {
|
|
302
|
+
if (typeof window === "undefined") return;
|
|
973
303
|
try {
|
|
974
|
-
|
|
304
|
+
const entry = { variantKey, ts: Date.now() };
|
|
305
|
+
localStorage.setItem(ASSIGNMENT_PREFIX + id, JSON.stringify(entry));
|
|
975
306
|
} catch {
|
|
976
307
|
}
|
|
977
308
|
}
|
|
978
|
-
|
|
979
|
-
|
|
980
|
-
|
|
981
|
-
|
|
982
|
-
|
|
983
|
-
|
|
984
|
-
|
|
985
|
-
|
|
309
|
+
function Experiment({
|
|
310
|
+
id,
|
|
311
|
+
control,
|
|
312
|
+
variants,
|
|
313
|
+
track,
|
|
314
|
+
componentInstanceId,
|
|
315
|
+
fallback = "control",
|
|
316
|
+
debug = false
|
|
317
|
+
}) {
|
|
318
|
+
const { host, bootstrap } = useProbatContext();
|
|
319
|
+
const autoInstanceId = useStableInstanceId(id);
|
|
320
|
+
const instanceId = componentInstanceId ?? autoInstanceId;
|
|
321
|
+
const trackImpression = track?.impression !== false;
|
|
322
|
+
const trackClick = track?.primaryClick !== false;
|
|
323
|
+
const impressionEvent = track?.impressionEventName ?? "$experiment_exposure";
|
|
324
|
+
const clickEvent = track?.clickEventName ?? "$experiment_click";
|
|
325
|
+
const [variantKey, setVariantKey] = useState(() => {
|
|
326
|
+
if (bootstrap[id]) return bootstrap[id];
|
|
327
|
+
const cached = readAssignment(id);
|
|
328
|
+
if (cached) return cached;
|
|
329
|
+
return "control";
|
|
330
|
+
});
|
|
331
|
+
const [resolved, setResolved] = useState(() => {
|
|
332
|
+
return !!(bootstrap[id] || readAssignment(id));
|
|
333
|
+
});
|
|
986
334
|
useEffect(() => {
|
|
987
|
-
|
|
988
|
-
|
|
989
|
-
|
|
990
|
-
|
|
991
|
-
|
|
992
|
-
}
|
|
993
|
-
|
|
994
|
-
|
|
995
|
-
|
|
996
|
-
|
|
997
|
-
|
|
998
|
-
|
|
999
|
-
|
|
1000
|
-
if (
|
|
1001
|
-
|
|
1002
|
-
|
|
1003
|
-
|
|
1004
|
-
} catch (e) {
|
|
1005
|
-
if (!alive) return;
|
|
1006
|
-
const err = e instanceof Error ? e : new Error(String(e));
|
|
1007
|
-
setError(err);
|
|
1008
|
-
setChoice({
|
|
1009
|
-
experiment_id: `exp_${proposalId}`,
|
|
1010
|
-
label: "control"
|
|
1011
|
-
});
|
|
1012
|
-
} finally {
|
|
1013
|
-
if (alive) {
|
|
1014
|
-
setIsLoading(false);
|
|
335
|
+
if (bootstrap[id] || readAssignment(id)) {
|
|
336
|
+
const key = bootstrap[id] ?? readAssignment(id) ?? "control";
|
|
337
|
+
setVariantKey(key);
|
|
338
|
+
setResolved(true);
|
|
339
|
+
return;
|
|
340
|
+
}
|
|
341
|
+
let cancelled = false;
|
|
342
|
+
(async () => {
|
|
343
|
+
try {
|
|
344
|
+
const distinctId = getDistinctId();
|
|
345
|
+
const key = await fetchDecision(host, id, distinctId);
|
|
346
|
+
if (cancelled) return;
|
|
347
|
+
if (key !== "control" && !(key in variants)) {
|
|
348
|
+
if (debug) {
|
|
349
|
+
console.warn(
|
|
350
|
+
`[probat] Unknown variant "${key}" for experiment "${id}", falling back to control`
|
|
351
|
+
);
|
|
1015
352
|
}
|
|
353
|
+
setVariantKey("control");
|
|
354
|
+
} else {
|
|
355
|
+
setVariantKey(key);
|
|
356
|
+
writeAssignment(id, key);
|
|
1016
357
|
}
|
|
1017
|
-
}
|
|
1018
|
-
|
|
358
|
+
} catch (err) {
|
|
359
|
+
if (cancelled) return;
|
|
360
|
+
if (debug) {
|
|
361
|
+
console.error(`[probat] fetchDecision failed for "${id}":`, err);
|
|
362
|
+
}
|
|
363
|
+
if (fallback === "suspend") throw err;
|
|
364
|
+
setVariantKey("control");
|
|
365
|
+
} finally {
|
|
366
|
+
if (!cancelled) setResolved(true);
|
|
367
|
+
}
|
|
368
|
+
})();
|
|
1019
369
|
return () => {
|
|
1020
|
-
|
|
370
|
+
cancelled = true;
|
|
1021
371
|
};
|
|
1022
|
-
}, [
|
|
372
|
+
}, [id, host]);
|
|
1023
373
|
useEffect(() => {
|
|
1024
|
-
if (
|
|
1025
|
-
|
|
1026
|
-
|
|
1027
|
-
|
|
1028
|
-
|
|
1029
|
-
|
|
1030
|
-
|
|
1031
|
-
|
|
1032
|
-
|
|
1033
|
-
|
|
1034
|
-
|
|
1035
|
-
|
|
1036
|
-
|
|
1037
|
-
|
|
1038
|
-
if (!rawTarget) return void 0;
|
|
1039
|
-
const actionable = rawTarget.closest(
|
|
1040
|
-
"[data-probat-conversion='true'], button, a, [role='button']"
|
|
1041
|
-
);
|
|
1042
|
-
if (!actionable) return void 0;
|
|
1043
|
-
const meta2 = {
|
|
1044
|
-
target_tag: actionable.tagName
|
|
1045
|
-
};
|
|
1046
|
-
if (actionable.id) meta2.target_id = actionable.id;
|
|
1047
|
-
const attr = actionable.getAttribute("data-probat-conversion");
|
|
1048
|
-
if (attr) meta2.conversion_attr = attr;
|
|
1049
|
-
const text = actionable.textContent?.trim();
|
|
1050
|
-
if (text) meta2.target_text = text.slice(0, 120);
|
|
1051
|
-
return meta2;
|
|
1052
|
-
})() : void 0;
|
|
1053
|
-
void sendMetric(apiBaseUrl, proposalId, "click", lbl, void 0, meta);
|
|
1054
|
-
},
|
|
1055
|
-
[proposalId, choice?.experiment_id, choice?.label, apiBaseUrl]
|
|
374
|
+
if (debug && resolved) {
|
|
375
|
+
console.log(`[probat] Experiment "${id}" \u2192 variant "${variantKey}"`, {
|
|
376
|
+
instanceId,
|
|
377
|
+
pageKey: getPageKey()
|
|
378
|
+
});
|
|
379
|
+
}
|
|
380
|
+
}, [debug, id, variantKey, resolved, instanceId]);
|
|
381
|
+
const eventProps = useMemo(
|
|
382
|
+
() => ({
|
|
383
|
+
experiment_id: id,
|
|
384
|
+
variant_key: variantKey,
|
|
385
|
+
component_instance_id: instanceId
|
|
386
|
+
}),
|
|
387
|
+
[id, variantKey, instanceId]
|
|
1056
388
|
);
|
|
1057
|
-
|
|
1058
|
-
|
|
1059
|
-
|
|
1060
|
-
|
|
1061
|
-
|
|
1062
|
-
|
|
1063
|
-
|
|
1064
|
-
|
|
1065
|
-
|
|
1066
|
-
|
|
1067
|
-
|
|
1068
|
-
|
|
1069
|
-
|
|
1070
|
-
|
|
1071
|
-
|
|
1072
|
-
|
|
1073
|
-
|
|
1074
|
-
|
|
1075
|
-
|
|
1076
|
-
if (!useNewAPI && !useOldAPI) {
|
|
1077
|
-
console.warn("[PROBAT] withExperiment: Invalid config, returning Control");
|
|
1078
|
-
return Control;
|
|
1079
|
-
}
|
|
1080
|
-
const ControlComponent = Control;
|
|
1081
|
-
function Wrapped(props) {
|
|
1082
|
-
const context = useProbatContext();
|
|
1083
|
-
const apiBaseUrl = context?.apiBaseUrl || "https://gushi.onrender.com";
|
|
1084
|
-
const contextRepoFullName = context?.repoFullName;
|
|
1085
|
-
const [config, setConfig] = useState(null);
|
|
1086
|
-
const [configLoading, setConfigLoading] = useState(useNewAPI);
|
|
1087
|
-
const [choice, setChoice] = useState(null);
|
|
1088
|
-
const repoFullName = options.repoFullName || contextRepoFullName;
|
|
1089
|
-
const proposalId = useNewAPI ? config?.proposalId : options.proposalId;
|
|
1090
|
-
useEffect(() => {
|
|
1091
|
-
if (!useNewAPI) return;
|
|
1092
|
-
if (!repoFullName) {
|
|
1093
|
-
console.warn("[PROBAT] componentPath provided but repoFullName not found");
|
|
1094
|
-
setConfigLoading(false);
|
|
1095
|
-
return;
|
|
389
|
+
const containerRef = useRef(null);
|
|
390
|
+
const impressionSent = useRef(false);
|
|
391
|
+
useEffect(() => {
|
|
392
|
+
if (!trackImpression || !resolved) return;
|
|
393
|
+
impressionSent.current = false;
|
|
394
|
+
const pageKey = getPageKey();
|
|
395
|
+
const dedupeKey = makeDedupeKey(id, variantKey, instanceId, pageKey);
|
|
396
|
+
if (hasSeen(dedupeKey)) {
|
|
397
|
+
impressionSent.current = true;
|
|
398
|
+
return;
|
|
399
|
+
}
|
|
400
|
+
const el = containerRef.current;
|
|
401
|
+
if (!el) return;
|
|
402
|
+
if (typeof IntersectionObserver === "undefined") {
|
|
403
|
+
if (!impressionSent.current) {
|
|
404
|
+
impressionSent.current = true;
|
|
405
|
+
markSeen(dedupeKey);
|
|
406
|
+
sendMetric(host, impressionEvent, eventProps);
|
|
407
|
+
if (debug) console.log(`[probat] Impression sent (no IO) for "${id}"`);
|
|
1096
408
|
}
|
|
1097
|
-
|
|
1098
|
-
|
|
1099
|
-
|
|
1100
|
-
|
|
1101
|
-
|
|
1102
|
-
|
|
1103
|
-
|
|
1104
|
-
|
|
1105
|
-
|
|
1106
|
-
|
|
1107
|
-
|
|
1108
|
-
|
|
1109
|
-
|
|
1110
|
-
|
|
1111
|
-
}
|
|
1112
|
-
|
|
1113
|
-
|
|
1114
|
-
|
|
1115
|
-
for (const [label2, variantInfo] of Object.entries(componentConfig.variants)) {
|
|
1116
|
-
if (label2 === "control") continue;
|
|
1117
|
-
if (variantInfo?.file_path) {
|
|
1118
|
-
try {
|
|
1119
|
-
const VariantComp = await loadVariantComponent(
|
|
1120
|
-
apiBaseUrl,
|
|
1121
|
-
componentConfig.proposal_id,
|
|
1122
|
-
variantInfo.experiment_id,
|
|
1123
|
-
variantInfo.file_path,
|
|
1124
|
-
componentConfig.repo_full_name,
|
|
1125
|
-
componentConfig.base_ref
|
|
1126
|
-
);
|
|
1127
|
-
if (VariantComp && typeof VariantComp === "function" && alive) {
|
|
1128
|
-
variantComponents[label2] = VariantComp;
|
|
1129
|
-
}
|
|
1130
|
-
} catch (e) {
|
|
1131
|
-
console.warn(`[PROBAT] Failed to load variant ${label2}:`, e);
|
|
1132
|
-
}
|
|
1133
|
-
}
|
|
1134
|
-
}
|
|
1135
|
-
if (alive) {
|
|
1136
|
-
setConfig({
|
|
1137
|
-
proposalId: componentConfig.proposal_id,
|
|
1138
|
-
variants: variantComponents
|
|
1139
|
-
});
|
|
1140
|
-
setConfigLoading(false);
|
|
1141
|
-
}
|
|
1142
|
-
} catch (e) {
|
|
1143
|
-
console.warn("[PROBAT] Failed to load component config:", e);
|
|
1144
|
-
if (alive) {
|
|
1145
|
-
setConfig(null);
|
|
1146
|
-
setConfigLoading(false);
|
|
1147
|
-
}
|
|
1148
|
-
}
|
|
1149
|
-
})();
|
|
1150
|
-
return () => {
|
|
1151
|
-
alive = false;
|
|
1152
|
-
};
|
|
1153
|
-
}, [useNewAPI, options.componentPath, repoFullName, apiBaseUrl]);
|
|
1154
|
-
useEffect(() => {
|
|
1155
|
-
if (!proposalId) return;
|
|
1156
|
-
if (useNewAPI && configLoading) return;
|
|
1157
|
-
let alive = true;
|
|
1158
|
-
const cached = readChoice(proposalId);
|
|
1159
|
-
if (cached) {
|
|
1160
|
-
const choiceData = {
|
|
1161
|
-
experiment_id: cached.experiment_id,
|
|
1162
|
-
label: cached.label
|
|
1163
|
-
};
|
|
1164
|
-
setChoice(choiceData);
|
|
1165
|
-
if (typeof window !== "undefined") {
|
|
1166
|
-
try {
|
|
1167
|
-
window.localStorage.setItem("probat_active_proposal_id", proposalId);
|
|
1168
|
-
window.localStorage.setItem("probat_active_variant_label", cached.label);
|
|
1169
|
-
} catch (e) {
|
|
1170
|
-
console.warn("[PROBAT] Failed to set proposal/variant in localStorage:", e);
|
|
1171
|
-
}
|
|
409
|
+
return;
|
|
410
|
+
}
|
|
411
|
+
let timer = null;
|
|
412
|
+
const observer = new IntersectionObserver(
|
|
413
|
+
([entry]) => {
|
|
414
|
+
if (!entry || impressionSent.current) return;
|
|
415
|
+
if (entry.isIntersecting) {
|
|
416
|
+
timer = setTimeout(() => {
|
|
417
|
+
if (impressionSent.current) return;
|
|
418
|
+
impressionSent.current = true;
|
|
419
|
+
markSeen(dedupeKey);
|
|
420
|
+
sendMetric(host, impressionEvent, eventProps);
|
|
421
|
+
if (debug) console.log(`[probat] Impression sent for "${id}"`);
|
|
422
|
+
observer.disconnect();
|
|
423
|
+
}, 250);
|
|
424
|
+
} else if (timer) {
|
|
425
|
+
clearTimeout(timer);
|
|
426
|
+
timer = null;
|
|
1172
427
|
}
|
|
1173
|
-
} else {
|
|
1174
|
-
(async () => {
|
|
1175
|
-
try {
|
|
1176
|
-
const { experiment_id, label: label2 } = await fetchDecision(apiBaseUrl, proposalId);
|
|
1177
|
-
if (!alive) return;
|
|
1178
|
-
writeChoice(proposalId, experiment_id, label2);
|
|
1179
|
-
const choiceData = { experiment_id, label: label2 };
|
|
1180
|
-
setChoice(choiceData);
|
|
1181
|
-
if (typeof window !== "undefined") {
|
|
1182
|
-
try {
|
|
1183
|
-
window.localStorage.setItem("probat_active_proposal_id", proposalId);
|
|
1184
|
-
window.localStorage.setItem("probat_active_variant_label", label2);
|
|
1185
|
-
} catch (e) {
|
|
1186
|
-
console.warn("[PROBAT] Failed to set proposal/variant in localStorage:", e);
|
|
1187
|
-
}
|
|
1188
|
-
}
|
|
1189
|
-
} catch (e) {
|
|
1190
|
-
if (!alive) return;
|
|
1191
|
-
const choiceData = {
|
|
1192
|
-
experiment_id: `exp_${proposalId}`,
|
|
1193
|
-
label: "control"
|
|
1194
|
-
};
|
|
1195
|
-
setChoice(choiceData);
|
|
1196
|
-
if (typeof window !== "undefined") {
|
|
1197
|
-
try {
|
|
1198
|
-
window.localStorage.setItem("probat_active_proposal_id", proposalId);
|
|
1199
|
-
window.localStorage.setItem("probat_active_variant_label", "control");
|
|
1200
|
-
} catch (err) {
|
|
1201
|
-
console.warn("[PROBAT] Failed to set proposal/variant in localStorage:", err);
|
|
1202
|
-
}
|
|
1203
|
-
}
|
|
1204
|
-
}
|
|
1205
|
-
})();
|
|
1206
|
-
}
|
|
1207
|
-
return () => {
|
|
1208
|
-
alive = false;
|
|
1209
|
-
};
|
|
1210
|
-
}, [proposalId, apiBaseUrl, useNewAPI, configLoading]);
|
|
1211
|
-
useEffect(() => {
|
|
1212
|
-
if (!proposalId) return;
|
|
1213
|
-
const lbl = choice?.label ?? "control";
|
|
1214
|
-
if (!lbl || hasTrackedVisit(proposalId, lbl)) return;
|
|
1215
|
-
markTrackedVisit(proposalId, lbl);
|
|
1216
|
-
void sendMetric(apiBaseUrl, proposalId, "visit", lbl, choice?.experiment_id);
|
|
1217
|
-
}, [proposalId, choice?.experiment_id, choice?.label, apiBaseUrl]);
|
|
1218
|
-
const trackClick = useCallback(
|
|
1219
|
-
(event, opts) => {
|
|
1220
|
-
if (!proposalId) return false;
|
|
1221
|
-
const lbl = choice?.label ?? "control";
|
|
1222
|
-
const meta = extractClickMeta(event ?? void 0);
|
|
1223
|
-
if (!opts?.force && event && !meta) return false;
|
|
1224
|
-
void sendMetric(apiBaseUrl, proposalId, "click", lbl, void 0, meta);
|
|
1225
|
-
return true;
|
|
1226
428
|
},
|
|
1227
|
-
|
|
429
|
+
{ threshold: 0.5 }
|
|
1228
430
|
);
|
|
1229
|
-
|
|
1230
|
-
|
|
1231
|
-
|
|
1232
|
-
|
|
1233
|
-
|
|
1234
|
-
|
|
1235
|
-
|
|
1236
|
-
|
|
1237
|
-
|
|
1238
|
-
|
|
1239
|
-
|
|
1240
|
-
|
|
1241
|
-
|
|
1242
|
-
|
|
1243
|
-
|
|
1244
|
-
|
|
1245
|
-
|
|
1246
|
-
|
|
431
|
+
observer.observe(el);
|
|
432
|
+
return () => {
|
|
433
|
+
observer.disconnect();
|
|
434
|
+
if (timer) clearTimeout(timer);
|
|
435
|
+
};
|
|
436
|
+
}, [
|
|
437
|
+
trackImpression,
|
|
438
|
+
resolved,
|
|
439
|
+
id,
|
|
440
|
+
variantKey,
|
|
441
|
+
instanceId,
|
|
442
|
+
host,
|
|
443
|
+
impressionEvent,
|
|
444
|
+
eventProps,
|
|
445
|
+
debug
|
|
446
|
+
]);
|
|
447
|
+
const handleClick = useCallback(
|
|
448
|
+
(e) => {
|
|
449
|
+
if (!trackClick) return;
|
|
450
|
+
const meta = extractClickMeta(e.target);
|
|
451
|
+
if (!meta) return;
|
|
452
|
+
sendMetric(host, clickEvent, {
|
|
453
|
+
...eventProps,
|
|
454
|
+
...meta
|
|
455
|
+
});
|
|
456
|
+
if (debug) {
|
|
457
|
+
console.log(`[probat] Click tracked for "${id}"`, meta);
|
|
1247
458
|
}
|
|
1248
|
-
}
|
|
1249
|
-
|
|
1250
|
-
|
|
1251
|
-
|
|
1252
|
-
|
|
1253
|
-
|
|
1254
|
-
|
|
1255
|
-
|
|
1256
|
-
|
|
1257
|
-
|
|
1258
|
-
|
|
459
|
+
},
|
|
460
|
+
[trackClick, host, clickEvent, eventProps, id, debug]
|
|
461
|
+
);
|
|
462
|
+
const content = variantKey === "control" || !(variantKey in variants) ? control : variants[variantKey];
|
|
463
|
+
return /* @__PURE__ */ React3.createElement(
|
|
464
|
+
"div",
|
|
465
|
+
{
|
|
466
|
+
ref: containerRef,
|
|
467
|
+
onClick: handleClick,
|
|
468
|
+
"data-probat-experiment": id,
|
|
469
|
+
"data-probat-variant": variantKey,
|
|
470
|
+
style: { display: "contents" }
|
|
471
|
+
},
|
|
472
|
+
content
|
|
473
|
+
);
|
|
474
|
+
}
|
|
475
|
+
function useProbatMetrics() {
|
|
476
|
+
const { host } = useProbatContext();
|
|
477
|
+
const capture = useCallback(
|
|
478
|
+
(event, properties = {}) => {
|
|
479
|
+
sendMetric(host, event, properties);
|
|
480
|
+
},
|
|
481
|
+
[host]
|
|
482
|
+
);
|
|
483
|
+
return { capture };
|
|
1259
484
|
}
|
|
1260
485
|
|
|
1261
|
-
export {
|
|
486
|
+
export { Experiment, ProbatProviderClient, fetchDecision, sendMetric, useProbatMetrics };
|
|
1262
487
|
//# sourceMappingURL=index.mjs.map
|
|
1263
488
|
//# sourceMappingURL=index.mjs.map
|