@splithub/node 0.1.9 → 0.2.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/index.cjs +414 -64
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +131 -16
- package/dist/index.d.ts +131 -16
- package/dist/index.js +405 -65
- package/dist/index.js.map +1 -1
- package/package.json +12 -4
package/dist/index.js
CHANGED
|
@@ -1,55 +1,184 @@
|
|
|
1
|
+
// src/handler.ts
|
|
2
|
+
import { isCrawler } from "@splithub/core";
|
|
3
|
+
|
|
1
4
|
// src/results.ts
|
|
2
|
-
import { getExperiment } from "@splithub/core";
|
|
3
|
-
import { compareVariants, computeVerdict } from "@splithub/stats";
|
|
4
|
-
|
|
5
|
+
import { getExperiment, HOLDOUT_KEY, holdoutExperiment } from "@splithub/core";
|
|
6
|
+
import { compareMeans, compareVariants, computeVerdict, estimateDaysToVerdict, holm, VERDICT_DEFAULTS } from "@splithub/stats";
|
|
7
|
+
var DAY_MS = 864e5;
|
|
8
|
+
function factorLevels(experiment, factor, counts2) {
|
|
9
|
+
return factor.levels.map((level) => {
|
|
10
|
+
const combos = experiment.variants.filter((v) => v.levels?.[factor.key] === level).map((v) => v.key);
|
|
11
|
+
const rows = counts2.filter((c) => combos.includes(c.variant));
|
|
12
|
+
return { variant: level, exposures: rows.reduce((s, r) => s + r.exposures, 0), conversions: rows.reduce((s, r) => s + r.conversions, 0) };
|
|
13
|
+
});
|
|
14
|
+
}
|
|
15
|
+
function factorPValues(experiment, counts2) {
|
|
16
|
+
const out = [];
|
|
17
|
+
for (const factor of experiment.factors ?? []) {
|
|
18
|
+
const perLevel = factorLevels(experiment, factor, counts2);
|
|
19
|
+
if (perLevel.every((l) => l.exposures > 0)) out.push(...compareVariants(perLevel).map((c) => c.sequential.pValue));
|
|
20
|
+
}
|
|
21
|
+
return out;
|
|
22
|
+
}
|
|
23
|
+
function factorEffects(experiment, counts2, options = {}) {
|
|
5
24
|
if (!experiment.factors?.length) return [];
|
|
6
|
-
|
|
7
|
-
const perLevel =
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
25
|
+
const perFactor = experiment.factors.map((factor) => {
|
|
26
|
+
const perLevel = factorLevels(experiment, factor, counts2);
|
|
27
|
+
return { factor, perLevel, comparisons: perLevel.every((l) => l.exposures > 0) ? compareVariants(perLevel) : [] };
|
|
28
|
+
});
|
|
29
|
+
const all = perFactor.flatMap((f) => f.comparisons);
|
|
30
|
+
const rejected = holm([...all.map((c) => c.sequential.pValue), ...options.familyPValues ?? []], 1 - VERDICT_DEFAULTS.confidence);
|
|
31
|
+
const significant = new Map(all.map((c, i) => [c, rejected[i]]));
|
|
32
|
+
return perFactor.map(({ factor, perLevel, comparisons }) => {
|
|
13
33
|
const levels = perLevel.map((l, i) => {
|
|
14
|
-
const cmp = comparisons.find((c) => c.variant === l.variant);
|
|
34
|
+
const cmp = i === 0 ? void 0 : comparisons.find((c) => c.variant === l.variant);
|
|
15
35
|
return {
|
|
16
36
|
level: l.variant,
|
|
17
37
|
exposures: l.exposures,
|
|
18
38
|
conversions: l.conversions,
|
|
19
39
|
rate: l.exposures ? l.conversions / l.exposures : 0,
|
|
20
|
-
relativeLift:
|
|
21
|
-
pValue:
|
|
22
|
-
|
|
40
|
+
relativeLift: cmp?.relativeLift ?? null,
|
|
41
|
+
pValue: cmp?.pValue ?? null,
|
|
42
|
+
sequentialPValue: cmp?.sequential.pValue ?? null,
|
|
43
|
+
probabilityToBeat: cmp?.probabilityToBeat ?? null,
|
|
44
|
+
significant: cmp ? Boolean(significant.get(cmp)) : false
|
|
23
45
|
};
|
|
24
46
|
});
|
|
25
47
|
const winners = levels.filter((l) => l.significant && (l.relativeLift ?? 0) > 0).sort((a, b) => (b.relativeLift ?? 0) - (a.relativeLift ?? 0));
|
|
26
48
|
return { key: factor.key, levels, best: winners[0]?.level ?? null };
|
|
27
49
|
});
|
|
28
50
|
}
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
const
|
|
33
|
-
|
|
34
|
-
|
|
51
|
+
var sum = (xs) => xs.reduce((s, x) => s + x, 0);
|
|
52
|
+
var sameShares = (a, b) => {
|
|
53
|
+
const sa = sum(a);
|
|
54
|
+
const sb = sum(b);
|
|
55
|
+
return a.every((x, i) => Math.abs(x / sa - b[i] / sb) < 1e-9);
|
|
56
|
+
};
|
|
57
|
+
function flowExpectedShares(experiment, flow) {
|
|
58
|
+
const keys = experiment.variants.map((v) => v.key);
|
|
59
|
+
const zero = () => new Array(keys.length).fill(0);
|
|
60
|
+
const memo = /* @__PURE__ */ new Map();
|
|
61
|
+
const walk = (id, depth) => {
|
|
62
|
+
if (!id) return { mass: zero(), known: true };
|
|
63
|
+
if (depth > 64) return "unknown";
|
|
64
|
+
const cached = memo.get(id);
|
|
65
|
+
if (cached) return cached;
|
|
66
|
+
const node = flow.nodes[id];
|
|
67
|
+
let out;
|
|
68
|
+
if (!node || node.type === "skip") out = { mass: zero(), known: true };
|
|
69
|
+
else if (node.type === "variant") {
|
|
70
|
+
const mass = zero();
|
|
71
|
+
const i = keys.indexOf(node.variant);
|
|
72
|
+
if (i >= 0) mass[i] = 1;
|
|
73
|
+
out = { mass, known: true };
|
|
74
|
+
} else {
|
|
75
|
+
const raw = node.type === "split" ? node.outputs.filter((o) => o.weight > 0).map((o) => ({ weight: o.weight, reach: walk(o.to, depth + 1) })) : [{ weight: 1, reach: walk(node.then, depth + 1) }, { weight: 1, reach: walk(node.else, depth + 1) }];
|
|
76
|
+
const branches = [];
|
|
77
|
+
for (const b of raw) if (b.reach !== "unknown") branches.push({ weight: b.weight, reach: b.reach });
|
|
78
|
+
const live = branches.filter((b) => sum(b.reach.mass) > 0);
|
|
79
|
+
if (branches.length < raw.length) out = "unknown";
|
|
80
|
+
else if (node.type === "split" && branches.every((b) => b.reach.known)) {
|
|
81
|
+
const total = sum(branches.map((b) => b.weight));
|
|
82
|
+
const mass = zero();
|
|
83
|
+
for (const b of branches) b.reach.mass.forEach((m, i) => mass[i] += b.weight / total * m);
|
|
84
|
+
out = { mass, known: true };
|
|
85
|
+
} else if (live.length === 0) out = { mass: zero(), known: true };
|
|
86
|
+
else if (live.every((b) => sameShares(b.reach.mass, live[0].reach.mass))) {
|
|
87
|
+
const ref = live[0].reach.mass;
|
|
88
|
+
out = { mass: ref.map((m) => m / sum(ref)), known: false };
|
|
89
|
+
} else out = "unknown";
|
|
90
|
+
}
|
|
91
|
+
memo.set(id, out);
|
|
92
|
+
return out;
|
|
93
|
+
};
|
|
94
|
+
const reach = walk(flow.start, 0);
|
|
95
|
+
if (reach === "unknown" || sum(reach.mass) <= 0) return null;
|
|
96
|
+
return reach.mass;
|
|
97
|
+
}
|
|
98
|
+
function resultsExperiment(config, key) {
|
|
99
|
+
return getExperiment(config, key) ?? (key === HOLDOUT_KEY ? holdoutExperiment(config) : null);
|
|
100
|
+
}
|
|
101
|
+
function alignCounts(experiment, observed) {
|
|
102
|
+
return experiment.variants.map((v) => {
|
|
35
103
|
const row = observed.find((o) => o.variant === v.key);
|
|
36
|
-
return {
|
|
104
|
+
return {
|
|
105
|
+
variant: v.key,
|
|
106
|
+
exposures: row?.exposures ?? 0,
|
|
107
|
+
conversions: row?.conversions ?? 0,
|
|
108
|
+
revenue: row?.revenue ?? row?.revenueSum ?? 0,
|
|
109
|
+
...row?.revenueSum !== void 0 ? { revenueSum: row.revenueSum } : {},
|
|
110
|
+
...row?.revenueSumSq !== void 0 ? { revenueSumSq: row.revenueSumSq } : {}
|
|
111
|
+
};
|
|
37
112
|
});
|
|
38
|
-
|
|
39
|
-
|
|
113
|
+
}
|
|
114
|
+
async function metricInputs(experiment, store) {
|
|
115
|
+
const m = experiment.metrics;
|
|
116
|
+
if (!m) return [];
|
|
117
|
+
const list = [
|
|
118
|
+
...m.secondary.map((metric) => ({ metric, role: "secondary" })),
|
|
119
|
+
...m.guardrails.map((g) => ({ metric: g.goal, role: "guardrail", worse: g.worse }))
|
|
120
|
+
];
|
|
121
|
+
return Promise.all(list.map(async (x) => ({ ...x, counts: alignCounts(experiment, await store.variantCounts(experiment.key, x.metric)) })));
|
|
122
|
+
}
|
|
123
|
+
async function experimentResults(config, store, key, options = {}) {
|
|
124
|
+
const experiment = resultsExperiment(config, key);
|
|
125
|
+
if (!experiment) return null;
|
|
126
|
+
const goal2 = experiment.goal;
|
|
127
|
+
const observed = goal2 ? await store.variantCounts(key, goal2) : [];
|
|
128
|
+
const counts2 = alignCounts(experiment, observed);
|
|
129
|
+
const metrics = goal2 ? await metricInputs(experiment, store) : [];
|
|
130
|
+
const now = options.now ?? /* @__PURE__ */ new Date();
|
|
131
|
+
const summary = options.summary !== void 0 ? options.summary : goal2 ? (await store.summaries()).find((s) => s.experiment === key) ?? null : null;
|
|
132
|
+
const span = summary?.firstExposureAt != null && summary.lastExposureAt != null ? (summary.lastExposureAt - summary.firstExposureAt) / DAY_MS : void 0;
|
|
133
|
+
const days = options.days ?? span;
|
|
134
|
+
const visitors = counts2.reduce((s, c) => s + c.exposures, 0);
|
|
135
|
+
const visitorsPerDay = options.visitorsPerDay ?? (days !== void 0 && days >= 1 / 24 && visitors > 0 ? visitors / days : null);
|
|
136
|
+
let expected = { expectedWeights: experiment.variants.map((v) => v.weight) };
|
|
137
|
+
if (experiment.flow) {
|
|
138
|
+
const shares = flowExpectedShares(experiment, experiment.flow);
|
|
139
|
+
expected = shares ? { expectedWeights: shares } : { skipSrm: "Split check skipped: targeting conditions decide which variant a visitor reaches, so the expected split depends on who visits." };
|
|
140
|
+
}
|
|
141
|
+
const isMvt = experiment.kind === "mvt" && Boolean(goal2);
|
|
142
|
+
const familyPValues = isMvt ? factorPValues(experiment, counts2) : void 0;
|
|
143
|
+
const verdict = goal2 ? computeVerdict(key, counts2, { ...expected, days, familyPValues, now, ...experiment.minDays !== void 0 ? { minDays: experiment.minDays } : {}, ...metrics.length ? { metrics } : {} }) : { ...computeVerdict(key, [], { now }), message: "No goal configured for this experiment; add `goal` in splithub.config.ts." };
|
|
144
|
+
const factors = isMvt ? factorEffects(experiment, counts2, { familyPValues: verdict.comparisons.map((c) => c.sequential.pValue) }) : void 0;
|
|
145
|
+
const revenue = goal2 ? revenueResult(counts2, Boolean(config.goals.find((g) => g.key === goal2)?.revenue)) : void 0;
|
|
146
|
+
return {
|
|
147
|
+
experiment: key,
|
|
148
|
+
kind: experiment.kind,
|
|
149
|
+
status: experiment.status,
|
|
150
|
+
goal: goal2,
|
|
151
|
+
description: experiment.description,
|
|
152
|
+
verdict,
|
|
153
|
+
daysToVerdict: goal2 ? estimateDaysToVerdict(verdict, visitorsPerDay) : null,
|
|
154
|
+
visitorsPerDay: visitorsPerDay === null ? null : Math.round(visitorsPerDay * 10) / 10,
|
|
155
|
+
...factors ? { factors } : {},
|
|
156
|
+
...revenue ? { revenue } : {}
|
|
157
|
+
};
|
|
158
|
+
}
|
|
159
|
+
function revenueResult(counts2, goalHasRevenue) {
|
|
160
|
+
if (!counts2.every((c) => typeof c.revenueSumSq === "number")) return void 0;
|
|
161
|
+
const rows = counts2.map((c) => ({ variant: c.variant, n: c.exposures, sum: c.revenueSum ?? c.revenue ?? 0, sumSq: c.revenueSumSq ?? 0 }));
|
|
162
|
+
if (!goalHasRevenue && rows.every((r) => r.sum === 0)) return void 0;
|
|
163
|
+
return {
|
|
164
|
+
variants: rows.map((r) => ({ variant: r.variant, visitors: r.n, revenue: r.sum, perVisitor: r.n > 0 ? r.sum / r.n : 0 })),
|
|
165
|
+
comparisons: compareMeans(rows)
|
|
166
|
+
};
|
|
40
167
|
}
|
|
41
168
|
async function statusTable(config, store) {
|
|
42
169
|
const summaries = await store.summaries();
|
|
43
170
|
const byKey = new Map(summaries.map((s) => [s.experiment, s]));
|
|
44
171
|
const rows = [];
|
|
45
|
-
|
|
172
|
+
const holdout = holdoutExperiment(config);
|
|
173
|
+
const all = holdout && byKey.has(HOLDOUT_KEY) ? [...config.experiments, holdout] : config.experiments;
|
|
174
|
+
for (const exp of all) {
|
|
46
175
|
const s = byKey.get(exp.key);
|
|
47
176
|
const days = s?.firstExposureAt && s.lastExposureAt ? Math.max(1, Math.ceil((s.lastExposureAt - s.firstExposureAt) / 864e5)) : 0;
|
|
48
177
|
let verdict = null;
|
|
49
178
|
let headline = null;
|
|
50
179
|
let best = null;
|
|
51
180
|
if (exp.goal && s) {
|
|
52
|
-
const r = await experimentResults(config, store, exp.key);
|
|
181
|
+
const r = await experimentResults(config, store, exp.key, { summary: s });
|
|
53
182
|
verdict = r?.verdict.status ?? null;
|
|
54
183
|
headline = r ? headlineFor(r.verdict) : null;
|
|
55
184
|
best = r ? bestOf(r.verdict) : null;
|
|
@@ -75,6 +204,8 @@ function headlineFor(v) {
|
|
|
75
204
|
return best ? `#${best.index} ${lift} (too early)` : "too early";
|
|
76
205
|
case "srm_detected":
|
|
77
206
|
return "SRM! check setup";
|
|
207
|
+
case "guardrail_breached":
|
|
208
|
+
return `guardrail hit: ${v.guardrailBreached?.[0]?.metric ?? "?"}`;
|
|
78
209
|
case "no_significant_difference":
|
|
79
210
|
return "no difference";
|
|
80
211
|
default:
|
|
@@ -83,6 +214,7 @@ function headlineFor(v) {
|
|
|
83
214
|
}
|
|
84
215
|
|
|
85
216
|
// src/validate.ts
|
|
217
|
+
import { HOLDOUT_KEY as HOLDOUT_KEY2 } from "@splithub/core";
|
|
86
218
|
var ID = /^[a-z0-9_-]{8,64}$/i;
|
|
87
219
|
var KEY = /^[a-z0-9][a-z0-9_-]{0,63}$/;
|
|
88
220
|
var MAX_EVENTS = 500;
|
|
@@ -113,7 +245,7 @@ function normalize(e, now) {
|
|
|
113
245
|
const ts = Math.abs(e.ts - now) > MAX_SKEW_MS ? now : Math.round(e.ts);
|
|
114
246
|
const url = typeof e.url === "string" ? e.url.slice(0, 512) : null;
|
|
115
247
|
if (e.type === "exposure") {
|
|
116
|
-
if (typeof e.exp !== "string" || !KEY.test(e.exp)) return "exposure.exp is invalid";
|
|
248
|
+
if (typeof e.exp !== "string" || !(KEY.test(e.exp) || e.exp === HOLDOUT_KEY2)) return "exposure.exp is invalid";
|
|
117
249
|
if (typeof e.var !== "string" || !KEY.test(e.var)) return "exposure.var is invalid";
|
|
118
250
|
return { id: e.id, type: "exposure", experiment: e.exp, variant: e.var, goal: null, visitorId: e.vid, sessionId: e.sid, ts, url, props: null, receivedAt: now };
|
|
119
251
|
}
|
|
@@ -131,6 +263,8 @@ function normalize(e, now) {
|
|
|
131
263
|
}
|
|
132
264
|
|
|
133
265
|
// src/handler.ts
|
|
266
|
+
var isBotUserAgent = (ua) => isCrawler(ua);
|
|
267
|
+
var visitorUserAgent = (request) => request.headers.get("x-splithub-ua") ?? request.headers.get("user-agent");
|
|
134
268
|
function createSplitHubHandler(options) {
|
|
135
269
|
const { config, store } = options;
|
|
136
270
|
const corsHeaders = (request) => {
|
|
@@ -165,6 +299,7 @@ function createSplitHubHandler(options) {
|
|
|
165
299
|
}
|
|
166
300
|
const result = validateBatch(body, config.project);
|
|
167
301
|
if (!result.ok) return json(request, { error: result.error }, 400);
|
|
302
|
+
if (isBotUserAgent(visitorUserAgent(request))) return json(request, { ok: true, received: result.events.length, inserted: 0 }, 202);
|
|
168
303
|
const inserted = await store.insertEvents(result.events);
|
|
169
304
|
return json(request, { ok: true, received: result.events.length, inserted }, 202);
|
|
170
305
|
}
|
|
@@ -215,11 +350,136 @@ async function toRequest(req) {
|
|
|
215
350
|
if (method !== "GET" && method !== "HEAD") {
|
|
216
351
|
const chunks = [];
|
|
217
352
|
for await (const chunk of req) chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
|
|
218
|
-
|
|
353
|
+
const all = Buffer.concat(chunks);
|
|
354
|
+
const copy = new Uint8Array(all.byteLength);
|
|
355
|
+
copy.set(all);
|
|
356
|
+
body = copy.buffer;
|
|
219
357
|
}
|
|
220
358
|
return new Request(url, { method, headers, body });
|
|
221
359
|
}
|
|
222
360
|
|
|
361
|
+
// src/attribution.ts
|
|
362
|
+
var ATTRIBUTION_SKEW_MS = 6e4;
|
|
363
|
+
var GOAL_DAILY_CAP = 50;
|
|
364
|
+
var DAY_MS2 = 864e5;
|
|
365
|
+
function revenueOf(props) {
|
|
366
|
+
const v = props?.revenue;
|
|
367
|
+
return typeof v === "number" && Number.isFinite(v) ? v : 0;
|
|
368
|
+
}
|
|
369
|
+
function attributeVariants(events, experiment, goal2) {
|
|
370
|
+
const first = /* @__PURE__ */ new Map();
|
|
371
|
+
const goals = /* @__PURE__ */ new Map();
|
|
372
|
+
for (const e of events) {
|
|
373
|
+
if (e.type === "exposure") {
|
|
374
|
+
if (e.experiment !== experiment || !e.variant) continue;
|
|
375
|
+
const prev = first.get(e.visitorId);
|
|
376
|
+
if (prev === void 0 || e.ts < prev.ts || e.ts === prev.ts && e.variant < prev.variant) first.set(e.visitorId, { variant: e.variant, ts: e.ts });
|
|
377
|
+
} else if (e.goal === goal2) {
|
|
378
|
+
const key = `${e.visitorId}\0${e.ts - e.ts % DAY_MS2}`;
|
|
379
|
+
const list = goals.get(key) ?? [];
|
|
380
|
+
list.push(e);
|
|
381
|
+
goals.set(key, list);
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
const counted = /* @__PURE__ */ new Map();
|
|
385
|
+
const revenueByVisitor = /* @__PURE__ */ new Map();
|
|
386
|
+
for (const list of goals.values()) {
|
|
387
|
+
list.sort((a, b) => a.ts - b.ts || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
|
|
388
|
+
for (const g of list.slice(0, GOAL_DAILY_CAP)) {
|
|
389
|
+
(counted.get(g.visitorId) ?? counted.set(g.visitorId, []).get(g.visitorId)).push(g.ts);
|
|
390
|
+
(revenueByVisitor.get(g.visitorId) ?? revenueByVisitor.set(g.visitorId, []).get(g.visitorId)).push(revenueOf(g.props));
|
|
391
|
+
}
|
|
392
|
+
}
|
|
393
|
+
const out = /* @__PURE__ */ new Map();
|
|
394
|
+
for (const [visitor, { variant, ts }] of first) {
|
|
395
|
+
const row = out.get(variant) ?? { variant, exposures: 0, conversions: 0, revenue: 0, revenueSum: 0, revenueSumSq: 0 };
|
|
396
|
+
row.exposures++;
|
|
397
|
+
const times = counted.get(visitor) ?? [];
|
|
398
|
+
const revenues = revenueByVisitor.get(visitor) ?? [];
|
|
399
|
+
let converted = false;
|
|
400
|
+
let revenue = 0;
|
|
401
|
+
times.forEach((t, i) => {
|
|
402
|
+
if (t < ts - ATTRIBUTION_SKEW_MS) return;
|
|
403
|
+
converted = true;
|
|
404
|
+
revenue += revenues[i];
|
|
405
|
+
});
|
|
406
|
+
if (converted) {
|
|
407
|
+
row.conversions++;
|
|
408
|
+
row.revenueSum += revenue;
|
|
409
|
+
row.revenueSumSq += revenue * revenue;
|
|
410
|
+
row.revenue = row.revenueSum;
|
|
411
|
+
}
|
|
412
|
+
out.set(variant, row);
|
|
413
|
+
}
|
|
414
|
+
return [...out.values()];
|
|
415
|
+
}
|
|
416
|
+
var IDENT = /^[a-z_][a-z0-9_]*$/i;
|
|
417
|
+
function revenueExpr(dialect, alias) {
|
|
418
|
+
if (dialect === "postgres") return `CASE WHEN jsonb_typeof(${alias}.props::jsonb -> 'revenue') = 'number' THEN (${alias}.props::jsonb ->> 'revenue')::float8 ELSE 0 END`;
|
|
419
|
+
if (dialect === "mysql") return `CASE WHEN JSON_TYPE(JSON_EXTRACT(${alias}.props, '$.revenue')) IN ('INTEGER', 'UNSIGNED INTEGER', 'DOUBLE', 'DECIMAL') THEN JSON_EXTRACT(${alias}.props, '$.revenue') + 0 ELSE 0 END`;
|
|
420
|
+
return `CASE WHEN json_type(${alias}.props, '$.revenue') IN ('integer', 'real') THEN json_extract(${alias}.props, '$.revenue') ELSE 0 END`;
|
|
421
|
+
}
|
|
422
|
+
function variantCountsSql(options) {
|
|
423
|
+
const { dialect } = options;
|
|
424
|
+
const t = options.table ?? "splithub_events";
|
|
425
|
+
if (!IDENT.test(t)) throw new Error("[splithub] invalid table name");
|
|
426
|
+
if (options.projectColumn !== void 0 && !IDENT.test(options.projectColumn)) throw new Error("[splithub] invalid column name");
|
|
427
|
+
const params = [];
|
|
428
|
+
const p = (name) => {
|
|
429
|
+
if (dialect === "postgres") {
|
|
430
|
+
const i = params.indexOf(name);
|
|
431
|
+
if (i >= 0) return `$${i + 1}`;
|
|
432
|
+
params.push(name);
|
|
433
|
+
return `$${params.length}`;
|
|
434
|
+
}
|
|
435
|
+
params.push(name);
|
|
436
|
+
return "?";
|
|
437
|
+
};
|
|
438
|
+
const proj = (alias) => options.projectColumn ? `${alias}.${options.projectColumn} = ${p("project")} AND ` : "";
|
|
439
|
+
const fv = `SELECT x.visitor_id, MIN(x.ts) AS first_ts FROM ${t} x WHERE ${proj("x")}x.type = 'exposure' AND x.experiment = ${p("experiment")} GROUP BY x.visitor_id`;
|
|
440
|
+
const fe = `SELECT MIN(e.variant) AS variant, fv.visitor_id, fv.first_ts
|
|
441
|
+
FROM (${fv}) fv
|
|
442
|
+
JOIN ${t} e ON ${proj("e")}e.type = 'exposure' AND e.experiment = ${p("experiment")} AND e.visitor_id = fv.visitor_id AND e.ts = fv.first_ts
|
|
443
|
+
GROUP BY fv.visitor_id, fv.first_ts`;
|
|
444
|
+
const goalJoin = `${proj("g")}g.type = 'goal' AND g.goal = ${p("goal")} AND g.visitor_id = fe.visitor_id AND g.ts >= fe.first_ts - ${ATTRIBUTION_SKEW_MS}
|
|
445
|
+
AND (SELECT COUNT(*) FROM ${t} g2
|
|
446
|
+
WHERE ${proj("g2")}g2.type = 'goal' AND g2.goal = g.goal AND g2.visitor_id = g.visitor_id
|
|
447
|
+
AND g2.ts >= g.ts - (g.ts % ${DAY_MS2}) AND (g2.ts < g.ts OR (g2.ts = g.ts AND g2.id < g.id))) < ${GOAL_DAILY_CAP}`;
|
|
448
|
+
const sql = `SELECT v.variant AS variant, COUNT(*) AS exposures, SUM(v.converted) AS conversions,
|
|
449
|
+
COALESCE(SUM(v.revenue), 0) AS revenue_sum, COALESCE(SUM(v.revenue * v.revenue), 0) AS revenue_sum_sq
|
|
450
|
+
FROM (
|
|
451
|
+
SELECT fe.variant, fe.visitor_id,
|
|
452
|
+
CASE WHEN COUNT(g.id) > 0 THEN 1 ELSE 0 END AS converted,
|
|
453
|
+
COALESCE(SUM(${revenueExpr(dialect, "g")}), 0) AS revenue
|
|
454
|
+
FROM (${fe}) fe
|
|
455
|
+
LEFT JOIN ${t} g ON ${goalJoin}
|
|
456
|
+
GROUP BY fe.variant, fe.visitor_id
|
|
457
|
+
) v
|
|
458
|
+
GROUP BY v.variant`;
|
|
459
|
+
return {
|
|
460
|
+
sql,
|
|
461
|
+
params,
|
|
462
|
+
bind(values) {
|
|
463
|
+
return params.map((name) => {
|
|
464
|
+
const v = values[name];
|
|
465
|
+
if (v === void 0) throw new Error(`[splithub] missing "${name}" for the attribution query`);
|
|
466
|
+
return v;
|
|
467
|
+
});
|
|
468
|
+
}
|
|
469
|
+
};
|
|
470
|
+
}
|
|
471
|
+
function countsFromRow(row) {
|
|
472
|
+
const revenueSum = Number(row.revenue_sum ?? 0);
|
|
473
|
+
return {
|
|
474
|
+
variant: String(row.variant),
|
|
475
|
+
exposures: Number(row.exposures ?? 0),
|
|
476
|
+
conversions: Number(row.conversions ?? 0),
|
|
477
|
+
revenue: revenueSum,
|
|
478
|
+
revenueSum,
|
|
479
|
+
revenueSumSq: Number(row.revenue_sum_sq ?? 0)
|
|
480
|
+
};
|
|
481
|
+
}
|
|
482
|
+
|
|
223
483
|
// src/store.ts
|
|
224
484
|
function createMemoryStore() {
|
|
225
485
|
const events = [];
|
|
@@ -236,43 +496,8 @@ function createMemoryStore() {
|
|
|
236
496
|
}
|
|
237
497
|
return n;
|
|
238
498
|
},
|
|
239
|
-
async variantCounts(experiment,
|
|
240
|
-
|
|
241
|
-
for (const e of events) {
|
|
242
|
-
if (e.type !== "exposure" || e.experiment !== experiment || !e.variant) continue;
|
|
243
|
-
const prev = earliest.get(e.visitorId);
|
|
244
|
-
if (prev === void 0 || e.ts < prev.ts || e.ts === prev.ts && e.variant < prev.variant) {
|
|
245
|
-
earliest.set(e.visitorId, { variant: e.variant, ts: e.ts });
|
|
246
|
-
}
|
|
247
|
-
}
|
|
248
|
-
const firstExposure = /* @__PURE__ */ new Map();
|
|
249
|
-
for (const [visitor, { variant, ts }] of earliest) {
|
|
250
|
-
const byVisitor = firstExposure.get(variant) ?? /* @__PURE__ */ new Map();
|
|
251
|
-
byVisitor.set(visitor, ts);
|
|
252
|
-
firstExposure.set(variant, byVisitor);
|
|
253
|
-
}
|
|
254
|
-
const goalsByVisitor = /* @__PURE__ */ new Map();
|
|
255
|
-
for (const e of events) {
|
|
256
|
-
if (e.type !== "goal" || e.goal !== goal) continue;
|
|
257
|
-
const list = goalsByVisitor.get(e.visitorId) ?? [];
|
|
258
|
-
const revenue = typeof e.props?.revenue === "number" ? e.props.revenue : 0;
|
|
259
|
-
list.push({ ts: e.ts, revenue });
|
|
260
|
-
goalsByVisitor.set(e.visitorId, list);
|
|
261
|
-
}
|
|
262
|
-
const out = [];
|
|
263
|
-
for (const [variant, byVisitor] of firstExposure) {
|
|
264
|
-
let conversions = 0;
|
|
265
|
-
let revenue = 0;
|
|
266
|
-
for (const [visitor, first] of byVisitor) {
|
|
267
|
-
const goals = (goalsByVisitor.get(visitor) ?? []).filter((g) => g.ts >= first);
|
|
268
|
-
if (goals.length > 0) {
|
|
269
|
-
conversions++;
|
|
270
|
-
revenue += goals.reduce((s, g) => s + g.revenue, 0);
|
|
271
|
-
}
|
|
272
|
-
}
|
|
273
|
-
out.push({ variant, exposures: byVisitor.size, conversions, revenue });
|
|
274
|
-
}
|
|
275
|
-
return out;
|
|
499
|
+
async variantCounts(experiment, goal2) {
|
|
500
|
+
return attributeVariants(events, experiment, goal2);
|
|
276
501
|
},
|
|
277
502
|
async summaries() {
|
|
278
503
|
const map = /* @__PURE__ */ new Map();
|
|
@@ -296,15 +521,130 @@ function createMemoryStore() {
|
|
|
296
521
|
}
|
|
297
522
|
};
|
|
298
523
|
}
|
|
524
|
+
|
|
525
|
+
// src/conformance.ts
|
|
526
|
+
var T = Date.UTC(2026, 0, 10, 12, 0, 0);
|
|
527
|
+
var DAY = 864e5;
|
|
528
|
+
var seq = 0;
|
|
529
|
+
function exposure(visitorId, variant, ts, experiment = "hero") {
|
|
530
|
+
seq++;
|
|
531
|
+
return { id: `exp_${String(seq).padStart(6, "0")}`, type: "exposure", experiment, variant, goal: null, visitorId, sessionId: `s_${visitorId}`, ts, url: null, props: null, receivedAt: ts };
|
|
532
|
+
}
|
|
533
|
+
function goal(visitorId, ts, revenue, key = "signup") {
|
|
534
|
+
seq++;
|
|
535
|
+
return { id: `goal_${String(seq).padStart(6, "0")}`, type: "goal", experiment: null, variant: null, goal: key, visitorId, sessionId: `s_${visitorId}`, ts, url: null, props: revenue === void 0 ? null : { revenue }, receivedAt: ts };
|
|
536
|
+
}
|
|
537
|
+
function counts(variant, exposures, conversions, revenueSum = 0, revenueSumSq = 0) {
|
|
538
|
+
return { variant, exposures, conversions, revenue: revenueSum, revenueSum, revenueSumSq };
|
|
539
|
+
}
|
|
540
|
+
var attributionConformance = [
|
|
541
|
+
{
|
|
542
|
+
name: "a visitor belongs to the variant of their earliest exposure (tie: smallest key)",
|
|
543
|
+
experiment: "hero",
|
|
544
|
+
goal: "signup",
|
|
545
|
+
readTimeOnly: true,
|
|
546
|
+
events: [
|
|
547
|
+
exposure("v1", "control", T + 1e3),
|
|
548
|
+
exposure("v1", "bold", T),
|
|
549
|
+
// earlier, arrives later
|
|
550
|
+
goal("v1", T + 5e3),
|
|
551
|
+
exposure("v2", "control", T),
|
|
552
|
+
exposure("v2", "bold", T),
|
|
553
|
+
exposure("v3", "bold", T),
|
|
554
|
+
exposure("v4", "control", T)
|
|
555
|
+
],
|
|
556
|
+
expected: [counts("bold", 3, 1), counts("control", 1, 0)]
|
|
557
|
+
},
|
|
558
|
+
{
|
|
559
|
+
name: "counts unique visitors, not events",
|
|
560
|
+
experiment: "hero",
|
|
561
|
+
goal: "signup",
|
|
562
|
+
events: [exposure("v1", "control", T), exposure("v1", "control", T + 10), exposure("v1", "bold", T + 20), goal("v1", T + 30), goal("v1", T + 40), exposure("v2", "bold", T)],
|
|
563
|
+
expected: [counts("bold", 1, 0), counts("control", 1, 1)]
|
|
564
|
+
},
|
|
565
|
+
{
|
|
566
|
+
name: "goals well before the exposure, of other goals or from unexposed visitors do not convert",
|
|
567
|
+
experiment: "hero",
|
|
568
|
+
goal: "signup",
|
|
569
|
+
events: [
|
|
570
|
+
exposure("v1", "control", T),
|
|
571
|
+
goal("v1", T - ATTRIBUTION_SKEW_MS - 1e3, 9),
|
|
572
|
+
goal("v1", T + 1e3, 9, "other"),
|
|
573
|
+
exposure("other_exp", "x", T, "pricing"),
|
|
574
|
+
goal("nobody", T + 1e3, 9),
|
|
575
|
+
goal("other_exp", T + 1e3, 9)
|
|
576
|
+
],
|
|
577
|
+
expected: [counts("control", 1, 0)]
|
|
578
|
+
},
|
|
579
|
+
{
|
|
580
|
+
name: `a goal up to ${ATTRIBUTION_SKEW_MS / 1e3} s before the exposure still counts (server vs browser clock)`,
|
|
581
|
+
experiment: "hero",
|
|
582
|
+
goal: "signup",
|
|
583
|
+
events: [
|
|
584
|
+
exposure("v1", "control", T),
|
|
585
|
+
goal("v1", T - ATTRIBUTION_SKEW_MS, 2),
|
|
586
|
+
exposure("v2", "bold", T),
|
|
587
|
+
goal("v2", T - 3e4, 3),
|
|
588
|
+
exposure("v3", "bold", T),
|
|
589
|
+
goal("v3", T - ATTRIBUTION_SKEW_MS - 1, 4)
|
|
590
|
+
],
|
|
591
|
+
expected: [counts("bold", 2, 1, 3, 9), counts("control", 1, 1, 2, 4)]
|
|
592
|
+
},
|
|
593
|
+
{
|
|
594
|
+
name: `at most ${GOAL_DAILY_CAP} of one goal per visitor and UTC day`,
|
|
595
|
+
experiment: "hero",
|
|
596
|
+
goal: "signup",
|
|
597
|
+
events: [
|
|
598
|
+
exposure("v1", "control", T),
|
|
599
|
+
...Array.from({ length: GOAL_DAILY_CAP + 10 }, (_, i) => goal("v1", T + 1e3 + i, 1)),
|
|
600
|
+
...Array.from({ length: 3 }, (_, i) => goal("v1", T + DAY + i, 1))
|
|
601
|
+
],
|
|
602
|
+
expected: [counts("control", 1, 1, GOAL_DAILY_CAP + 3, (GOAL_DAILY_CAP + 3) ** 2)]
|
|
603
|
+
},
|
|
604
|
+
{
|
|
605
|
+
name: "revenue is summed per visitor; variants report the sum and the sum of squares",
|
|
606
|
+
experiment: "hero",
|
|
607
|
+
goal: "signup",
|
|
608
|
+
events: [
|
|
609
|
+
exposure("v1", "control", T),
|
|
610
|
+
goal("v1", T + 1e3, 10),
|
|
611
|
+
goal("v1", T + 2e3, 5),
|
|
612
|
+
exposure("v2", "control", T),
|
|
613
|
+
goal("v2", T + 1e3, 20),
|
|
614
|
+
exposure("v3", "control", T),
|
|
615
|
+
goal("v3", T + 1e3, "lots"),
|
|
616
|
+
exposure("v4", "control", T),
|
|
617
|
+
exposure("v5", "bold", T),
|
|
618
|
+
goal("v5", T + 1e3, 2.5)
|
|
619
|
+
],
|
|
620
|
+
expected: [counts("bold", 1, 1, 2.5, 6.25), counts("control", 4, 3, 35, 625)]
|
|
621
|
+
}
|
|
622
|
+
];
|
|
623
|
+
function sortCounts(rows) {
|
|
624
|
+
return rows.map((r) => {
|
|
625
|
+
const revenueSum = r.revenueSum ?? r.revenue ?? 0;
|
|
626
|
+
return { variant: r.variant, exposures: r.exposures, conversions: r.conversions, revenue: revenueSum, revenueSum, revenueSumSq: r.revenueSumSq ?? 0 };
|
|
627
|
+
}).sort((a, b) => a.variant < b.variant ? -1 : a.variant > b.variant ? 1 : 0);
|
|
628
|
+
}
|
|
299
629
|
export {
|
|
630
|
+
ATTRIBUTION_SKEW_MS,
|
|
631
|
+
GOAL_DAILY_CAP,
|
|
632
|
+
attributeVariants,
|
|
633
|
+
attributionConformance,
|
|
300
634
|
bestOf,
|
|
635
|
+
countsFromRow,
|
|
301
636
|
createMemoryStore,
|
|
302
637
|
createSplitHubHandler,
|
|
303
638
|
experimentResults,
|
|
304
639
|
factorEffects,
|
|
640
|
+
flowExpectedShares,
|
|
305
641
|
headlineFor,
|
|
642
|
+
resultsExperiment,
|
|
643
|
+
revenueOf,
|
|
644
|
+
sortCounts,
|
|
306
645
|
statusTable,
|
|
307
646
|
toNodeListener,
|
|
308
|
-
validateBatch
|
|
647
|
+
validateBatch,
|
|
648
|
+
variantCountsSql
|
|
309
649
|
};
|
|
310
650
|
//# sourceMappingURL=index.js.map
|