@splithub/core 0.1.8 → 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/{chunk-BLP4ZZ7Q.js → chunk-XTJVALWN.js} +445 -75
- package/dist/chunk-XTJVALWN.js.map +1 -0
- package/dist/index.cjs +478 -74
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +137 -8
- package/dist/index.d.ts +137 -8
- package/dist/index.js +48 -1
- package/dist/index.js.map +1 -1
- package/dist/{types-V-RgA0yG.d.cts → types-BibC0pt1.d.cts} +85 -3
- package/dist/{types-V-RgA0yG.d.ts → types-BibC0pt1.d.ts} +85 -3
- package/dist/vite.cjs +8 -1
- package/dist/vite.cjs.map +1 -1
- package/dist/vite.d.cts +1 -1
- package/dist/vite.d.ts +1 -1
- package/dist/vite.js +1 -1
- package/package.json +10 -2
- package/dist/chunk-BLP4ZZ7Q.js.map +0 -1
package/dist/index.cjs
CHANGED
|
@@ -24,11 +24,14 @@ __export(index_exports, {
|
|
|
24
24
|
ConfigError: () => ConfigError,
|
|
25
25
|
EMPTY_OVERRIDES: () => EMPTY_OVERRIDES,
|
|
26
26
|
EventQueue: () => EventQueue,
|
|
27
|
+
HOLDOUT_KEY: () => HOLDOUT_KEY,
|
|
27
28
|
KEYED_FIELDS: () => KEYED_FIELDS,
|
|
29
|
+
LAYER_BUCKETS: () => LAYER_BUCKETS,
|
|
28
30
|
MVT_MAX_COMBINATIONS: () => MVT_MAX_COMBINATIONS,
|
|
29
31
|
MVT_MAX_FACTORS: () => MVT_MAX_FACTORS,
|
|
30
32
|
MVT_MAX_LEVELS: () => MVT_MAX_LEVELS,
|
|
31
33
|
REMOTE_TTL_MS: () => REMOTE_TTL_MS,
|
|
34
|
+
REMOTE_WAIT_MS: () => REMOTE_WAIT_MS,
|
|
32
35
|
SDK_VERSION: () => SDK_VERSION,
|
|
33
36
|
TARGET_FIELDS: () => TARGET_FIELDS,
|
|
34
37
|
TARGET_OPS: () => TARGET_OPS,
|
|
@@ -37,10 +40,12 @@ __export(index_exports, {
|
|
|
37
40
|
browserContext: () => browserContext,
|
|
38
41
|
contextValue: () => contextValue,
|
|
39
42
|
controlVariant: () => controlVariant,
|
|
43
|
+
countsForHoldout: () => countsForHoldout,
|
|
40
44
|
createClient: () => createClient,
|
|
41
45
|
createFetchTransport: () => createFetchTransport,
|
|
42
46
|
debugLog: () => debugLog,
|
|
43
47
|
debugMode: () => debugMode,
|
|
48
|
+
decideRedirect: () => decideRedirect,
|
|
44
49
|
defineConfig: () => defineConfig,
|
|
45
50
|
devNote: () => devNote,
|
|
46
51
|
evaluateCondition: () => evaluateCondition,
|
|
@@ -51,26 +56,36 @@ __export(index_exports, {
|
|
|
51
56
|
getOrCreateVisitorId: () => getOrCreateVisitorId,
|
|
52
57
|
hasVisitorId: () => hasVisitorId,
|
|
53
58
|
hashToUnit: () => hashToUnit,
|
|
59
|
+
holdoutExperiment: () => holdoutExperiment,
|
|
60
|
+
holdoutGroup: () => holdoutGroup,
|
|
61
|
+
inLayer: () => inLayer,
|
|
54
62
|
inSchedule: () => inSchedule,
|
|
55
63
|
isActive: () => isActive,
|
|
64
|
+
isBot: () => isBot,
|
|
56
65
|
isBrowser: () => isBrowser,
|
|
66
|
+
isCrawler: () => isCrawler,
|
|
57
67
|
isDebug: () => isDebug,
|
|
58
68
|
isDevDraft: () => isDevDraft,
|
|
59
69
|
isDevEnvironment: () => isDevEnvironment,
|
|
60
70
|
isRemoteOverrides: () => isRemoteOverrides,
|
|
61
71
|
isSplitHubConfig: () => isSplitHubConfig,
|
|
72
|
+
layerBucket: () => layerBucket,
|
|
62
73
|
matchConditions: () => matchConditions,
|
|
74
|
+
matchPath: () => matchPath,
|
|
75
|
+
measuredGoals: () => measuredGoals,
|
|
63
76
|
murmur3: () => murmur3,
|
|
64
77
|
mvtVariants: () => mvtVariants,
|
|
65
78
|
newId: () => newId,
|
|
66
79
|
newSessionId: () => newSessionId,
|
|
67
80
|
newVisitorId: () => newVisitorId,
|
|
81
|
+
normalizePath: () => normalizePath,
|
|
68
82
|
onDebug: () => onDebug,
|
|
69
83
|
parseCookies: () => parseCookies,
|
|
70
84
|
parseForceParam: () => parseForceParam,
|
|
71
85
|
parseUserAgent: () => parseUserAgent,
|
|
72
86
|
pickVariant: () => pickVariant,
|
|
73
87
|
readRemoteCache: () => readRemoteCache,
|
|
88
|
+
redirectTarget: () => redirectTarget,
|
|
74
89
|
resetDevNotes: () => resetDevNotes,
|
|
75
90
|
resolveOverridesUrl: () => resolveOverridesUrl,
|
|
76
91
|
runFlow: () => runFlow,
|
|
@@ -144,6 +159,28 @@ var TARGET_FIELDS = ["country", "region", "city", "device", "browser", "os", "la
|
|
|
144
159
|
var TARGET_OPS = ["is", "is_not", "contains", "not_contains", "starts_with", "in", "not_in", "matches", "exists", "not_exists"];
|
|
145
160
|
var KEYED_FIELDS = ["query", "cookie"];
|
|
146
161
|
var MAX_STEPS = 64;
|
|
162
|
+
var WEEKDAYS = ["sun", "mon", "tue", "wed", "thu", "fri", "sat"];
|
|
163
|
+
var formatters = /* @__PURE__ */ new Map();
|
|
164
|
+
function localClock(ctx) {
|
|
165
|
+
const d = new Date(ctx.now ?? Date.now());
|
|
166
|
+
const tz = ctx.timezone;
|
|
167
|
+
let f = tz ? formatters.get(tz) : null;
|
|
168
|
+
if (tz && f === void 0) {
|
|
169
|
+
try {
|
|
170
|
+
f = new Intl.DateTimeFormat("en-US", { timeZone: tz, hour: "numeric", hourCycle: "h23", weekday: "short" });
|
|
171
|
+
} catch {
|
|
172
|
+
f = null;
|
|
173
|
+
}
|
|
174
|
+
formatters.set(tz, f);
|
|
175
|
+
}
|
|
176
|
+
if (f) {
|
|
177
|
+
const parts = f.formatToParts(d);
|
|
178
|
+
const hour = Number(parts.find((p) => p.type === "hour")?.value);
|
|
179
|
+
const weekday = WEEKDAYS.indexOf((parts.find((p) => p.type === "weekday")?.value ?? "").slice(0, 3).toLowerCase());
|
|
180
|
+
if (hour >= 0 && hour < 24 && weekday >= 0) return { hour, weekday };
|
|
181
|
+
}
|
|
182
|
+
return { hour: d.getUTCHours(), weekday: d.getUTCDay() };
|
|
183
|
+
}
|
|
147
184
|
function queryParam(url, name) {
|
|
148
185
|
if (!url) return void 0;
|
|
149
186
|
const q = url.indexOf("?");
|
|
@@ -193,16 +230,12 @@ function contextValue(field, key, ctx) {
|
|
|
193
230
|
case "cookie":
|
|
194
231
|
v = key ? ctx.cookies?.[key] : void 0;
|
|
195
232
|
break;
|
|
196
|
-
case "hour":
|
|
197
|
-
|
|
198
|
-
v = d.getUTCHours();
|
|
233
|
+
case "hour":
|
|
234
|
+
v = localClock(ctx).hour;
|
|
199
235
|
break;
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
const d = ctx.now ? new Date(ctx.now) : /* @__PURE__ */ new Date();
|
|
203
|
-
v = ["sun", "mon", "tue", "wed", "thu", "fri", "sat"][d.getUTCDay()];
|
|
236
|
+
case "weekday":
|
|
237
|
+
v = WEEKDAYS[localClock(ctx).weekday];
|
|
204
238
|
break;
|
|
205
|
-
}
|
|
206
239
|
}
|
|
207
240
|
return v === void 0 || v === null ? void 0 : String(v).toLowerCase();
|
|
208
241
|
}
|
|
@@ -337,13 +370,21 @@ function validateFlow(flow, variantKeys) {
|
|
|
337
370
|
}
|
|
338
371
|
return null;
|
|
339
372
|
}
|
|
373
|
+
var BOT_UA = /bot|crawl|spider|slurp|headless|lighthouse|pingdom|facebookexternalhit|google-inspectiontool|bingpreview|mediapartners|ahrefs|semrush|phantomjs|python-requests|curl\/|wget\//i;
|
|
340
374
|
function parseUserAgent(ua) {
|
|
341
375
|
const s = ua ?? "";
|
|
342
|
-
const device =
|
|
376
|
+
const device = BOT_UA.test(s) ? "bot" : /iPad|Tablet|PlayBook|Silk/i.test(s) || /Android/i.test(s) && !/Mobile/i.test(s) ? "tablet" : /Mobi|iPhone|iPod|Android|BlackBerry|Opera Mini|IEMobile/i.test(s) ? "mobile" : "desktop";
|
|
343
377
|
const browser = /Edg\//i.test(s) ? "edge" : /OPR\/|Opera/i.test(s) ? "opera" : /SamsungBrowser/i.test(s) ? "samsung" : /Firefox\//i.test(s) ? "firefox" : /Chrome\/|CriOS/i.test(s) ? "chrome" : /Safari\//i.test(s) && /Version\//i.test(s) ? "safari" : s ? "other" : "unknown";
|
|
344
378
|
const os = /Windows/i.test(s) ? "windows" : /iPhone|iPad|iPod/i.test(s) ? "ios" : /Android/i.test(s) ? "android" : /Mac OS X|Macintosh/i.test(s) ? "macos" : /CrOS/i.test(s) ? "chromeos" : /Linux/i.test(s) ? "linux" : s ? "other" : "unknown";
|
|
345
379
|
return { device, browser, os };
|
|
346
380
|
}
|
|
381
|
+
function isBot(ua) {
|
|
382
|
+
return Boolean(ua) && BOT_UA.test(ua);
|
|
383
|
+
}
|
|
384
|
+
var HTTP_CLIENT_UA = /^(curl|wget|python-requests)\//i;
|
|
385
|
+
function isCrawler(ua) {
|
|
386
|
+
return isBot(ua) && !HTTP_CLIENT_UA.test(ua.trim());
|
|
387
|
+
}
|
|
347
388
|
function parseCookies(header) {
|
|
348
389
|
const out = {};
|
|
349
390
|
for (const part of (header ?? "").split(";")) {
|
|
@@ -370,9 +411,17 @@ function browserContext(extra = {}) {
|
|
|
370
411
|
referrer: typeof document !== "undefined" ? document.referrer || void 0 : void 0,
|
|
371
412
|
url: location.href,
|
|
372
413
|
cookies: typeof document !== "undefined" ? parseCookies(document.cookie) : {},
|
|
414
|
+
timezone: deviceTimezone(),
|
|
373
415
|
...extra
|
|
374
416
|
};
|
|
375
417
|
}
|
|
418
|
+
function deviceTimezone() {
|
|
419
|
+
try {
|
|
420
|
+
return Intl.DateTimeFormat().resolvedOptions().timeZone || void 0;
|
|
421
|
+
} catch {
|
|
422
|
+
return void 0;
|
|
423
|
+
}
|
|
424
|
+
}
|
|
376
425
|
|
|
377
426
|
// src/config.ts
|
|
378
427
|
var KEY_PATTERN = /^[a-z0-9][a-z0-9_-]{0,63}$/;
|
|
@@ -441,7 +490,60 @@ function normalizeVariants(expKey, input) {
|
|
|
441
490
|
}
|
|
442
491
|
return raw.map((v) => ({ ...v, weight: v.weight / total }));
|
|
443
492
|
}
|
|
444
|
-
|
|
493
|
+
var HOLDOUT_KEY = "__holdout";
|
|
494
|
+
var LAYER_BUCKETS = 100;
|
|
495
|
+
function normalizeMetrics(key, input, goals) {
|
|
496
|
+
const m = input.metrics;
|
|
497
|
+
if (!m) return void 0;
|
|
498
|
+
if (!input.goal) throw new ConfigError(`experiment "${key}": metrics need a primary "goal" too.`);
|
|
499
|
+
const seen = /* @__PURE__ */ new Set([input.goal]);
|
|
500
|
+
const check = (goal, where) => {
|
|
501
|
+
if (typeof goal !== "string" || !goals.some((g) => g.key === goal)) throw new ConfigError(`experiment "${key}": metrics.${where} goal "${String(goal)}" is not declared in "goals".`);
|
|
502
|
+
if (seen.has(goal)) throw new ConfigError(`experiment "${key}": goal "${goal}" is listed twice (primary goal and metrics count once each).`);
|
|
503
|
+
seen.add(goal);
|
|
504
|
+
return goal;
|
|
505
|
+
};
|
|
506
|
+
const secondary = (m.secondary ?? []).map((g) => check(g, "secondary"));
|
|
507
|
+
const guardrails = (m.guardrails ?? []).map((g) => {
|
|
508
|
+
const obj = typeof g === "string" ? { goal: g } : g;
|
|
509
|
+
const worse = obj.worse ?? "lower";
|
|
510
|
+
if (worse !== "lower" && worse !== "higher") throw new ConfigError(`experiment "${key}": guardrail "${obj.goal}": worse must be "lower" or "higher".`);
|
|
511
|
+
return { goal: check(obj.goal, "guardrails"), worse };
|
|
512
|
+
});
|
|
513
|
+
if (secondary.length === 0 && guardrails.length === 0) return void 0;
|
|
514
|
+
return { secondary, guardrails };
|
|
515
|
+
}
|
|
516
|
+
function normalizeLayer(key, input, layers) {
|
|
517
|
+
const l = input.layer;
|
|
518
|
+
if (!l) return void 0;
|
|
519
|
+
if (!l.key || !(l.key in layers)) throw new ConfigError(`experiment "${key}": layer "${String(l.key)}" is not declared in "layers".`);
|
|
520
|
+
const [start, end] = Array.isArray(l.range) ? l.range : [NaN, NaN];
|
|
521
|
+
const ok = (n) => typeof n === "number" && Number.isInteger(n) && n >= 0 && n <= LAYER_BUCKETS;
|
|
522
|
+
if (!ok(start) || !ok(end) || !(start < end)) throw new ConfigError(`experiment "${key}": layer.range must be [start, end] with whole numbers 0 <= start < end <= ${LAYER_BUCKETS}.`);
|
|
523
|
+
return { key: l.key, range: [start, end] };
|
|
524
|
+
}
|
|
525
|
+
function assertNoOverlap(experiments) {
|
|
526
|
+
const live = experiments.filter((e) => e.layer && e.status !== "finished");
|
|
527
|
+
for (let i = 0; i < live.length; i++) {
|
|
528
|
+
for (let j = i + 1; j < live.length; j++) {
|
|
529
|
+
const a = live[i];
|
|
530
|
+
const b = live[j];
|
|
531
|
+
if (a.layer.key !== b.layer.key) continue;
|
|
532
|
+
if (a.layer.range[0] < b.layer.range[1] && b.layer.range[0] < a.layer.range[1]) {
|
|
533
|
+
throw new ConfigError(`experiments "${a.key}" and "${b.key}" overlap in layer "${a.layer.key}" ([${a.layer.range.join(", ")}) and [${b.layer.range.join(", ")})). Give each its own range.`);
|
|
534
|
+
}
|
|
535
|
+
}
|
|
536
|
+
}
|
|
537
|
+
}
|
|
538
|
+
function normalizeHoldout(input, goals) {
|
|
539
|
+
const h = input.holdout;
|
|
540
|
+
if (!h) return null;
|
|
541
|
+
if (typeof h.percent !== "number" || !Number.isFinite(h.percent) || h.percent < 0 || h.percent > 50) throw new ConfigError("holdout.percent must be a number between 0 and 50.");
|
|
542
|
+
if (h.goal && !goals.some((g) => g.key === h.goal)) throw new ConfigError(`holdout.goal "${h.goal}" is not declared in "goals".`);
|
|
543
|
+
if (h.percent === 0) return null;
|
|
544
|
+
return { percent: h.percent, seed: h.seed ?? HOLDOUT_KEY, goal: h.goal ?? goals[0]?.key ?? null };
|
|
545
|
+
}
|
|
546
|
+
function normalizeExperiment(key, input, goals, layers = {}) {
|
|
445
547
|
assertKey("experiment", key);
|
|
446
548
|
const traffic = input.traffic ?? 1;
|
|
447
549
|
if (traffic < 0 || traffic > 1) {
|
|
@@ -456,10 +558,15 @@ function normalizeExperiment(key, input, goals) {
|
|
|
456
558
|
if (input.maxExposures !== void 0 && (!Number.isFinite(input.maxExposures) || input.maxExposures < 1)) {
|
|
457
559
|
throw new ConfigError(`experiment "${key}": maxExposures must be a positive number.`);
|
|
458
560
|
}
|
|
561
|
+
if (input.minDays !== void 0 && !(Number.isInteger(input.minDays) && input.minDays >= 0 && input.minDays <= 30)) {
|
|
562
|
+
throw new ConfigError(`experiment "${key}": minDays must be a whole number from 0 to 30.`);
|
|
563
|
+
}
|
|
459
564
|
for (const [k, v] of Object.entries(input.schedule ?? {})) {
|
|
460
565
|
if (v !== void 0 && Number.isNaN(Date.parse(v))) throw new ConfigError(`experiment "${key}": schedule.${k} must be an ISO date.`);
|
|
461
566
|
}
|
|
462
567
|
const variants = normalizeVariants(key, input);
|
|
568
|
+
const metrics = normalizeMetrics(key, input, goals);
|
|
569
|
+
const layer = normalizeLayer(key, input, layers);
|
|
463
570
|
if (input.flow) {
|
|
464
571
|
const problem = validateFlow(input.flow, variants.map((v) => v.key));
|
|
465
572
|
if (problem) throw new ConfigError(`experiment "${key}": flow: ${problem}`);
|
|
@@ -476,6 +583,9 @@ function normalizeExperiment(key, input, goals) {
|
|
|
476
583
|
variants,
|
|
477
584
|
...input.kind === "mvt" ? { factors: mvtVariants(key, input.factors).factors } : {},
|
|
478
585
|
...input.flow ? { flow: input.flow } : {},
|
|
586
|
+
...metrics ? { metrics } : {},
|
|
587
|
+
...layer ? { layer } : {},
|
|
588
|
+
...input.minDays !== void 0 ? { minDays: input.minDays } : {},
|
|
479
589
|
...input.maxExposures ? { maxExposures: Math.floor(input.maxExposures) } : {},
|
|
480
590
|
...input.schedule && (input.schedule.startAt || input.schedule.endAt) ? { schedule: { startAt: input.schedule.startAt ?? null, endAt: input.schedule.endAt ?? null } } : {}
|
|
481
591
|
};
|
|
@@ -498,9 +608,16 @@ function defineConfig(input) {
|
|
|
498
608
|
description: g.description ?? null
|
|
499
609
|
};
|
|
500
610
|
});
|
|
611
|
+
const layers = {};
|
|
612
|
+
for (const [key, l] of Object.entries(input.layers ?? {})) {
|
|
613
|
+
assertKey("layer", key);
|
|
614
|
+
layers[key] = { seed: l?.seed ?? key };
|
|
615
|
+
}
|
|
501
616
|
const experiments = Object.entries(input.experiments ?? {}).map(
|
|
502
|
-
([key, exp]) => normalizeExperiment(key, exp, goals)
|
|
617
|
+
([key, exp]) => normalizeExperiment(key, exp, goals, layers)
|
|
503
618
|
);
|
|
619
|
+
assertNoOverlap(experiments);
|
|
620
|
+
const holdout = normalizeHoldout(input, goals);
|
|
504
621
|
return {
|
|
505
622
|
project: input.project,
|
|
506
623
|
storage: input.storage,
|
|
@@ -508,6 +625,8 @@ function defineConfig(input) {
|
|
|
508
625
|
runDraftsInDev: input.runDraftsInDev === true,
|
|
509
626
|
goals,
|
|
510
627
|
experiments,
|
|
628
|
+
...Object.keys(layers).length ? { layers } : {},
|
|
629
|
+
...holdout ? { holdout } : {},
|
|
511
630
|
__splithub: 2
|
|
512
631
|
};
|
|
513
632
|
}
|
|
@@ -517,6 +636,40 @@ function isSplitHubConfig(value) {
|
|
|
517
636
|
function getExperiment(config, key) {
|
|
518
637
|
return config.experiments.find((e) => e.key === key);
|
|
519
638
|
}
|
|
639
|
+
function holdoutExperiment(config) {
|
|
640
|
+
const h = config.holdout;
|
|
641
|
+
if (!h) return null;
|
|
642
|
+
const share = h.percent / 100;
|
|
643
|
+
const secondary = config.goals.map((g) => g.key).filter((g) => g !== h.goal);
|
|
644
|
+
return {
|
|
645
|
+
key: HOLDOUT_KEY,
|
|
646
|
+
kind: "component",
|
|
647
|
+
status: "running",
|
|
648
|
+
traffic: 1,
|
|
649
|
+
goal: h.goal,
|
|
650
|
+
seed: h.seed,
|
|
651
|
+
description: `Holdout: ${h.percent}% of visitors see no test at all`,
|
|
652
|
+
match: null,
|
|
653
|
+
variants: [
|
|
654
|
+
{ key: "holdout", weight: share },
|
|
655
|
+
{ key: "enrolled", weight: 1 - share }
|
|
656
|
+
],
|
|
657
|
+
...h.goal && secondary.length ? { metrics: { secondary, guardrails: [] } } : {}
|
|
658
|
+
};
|
|
659
|
+
}
|
|
660
|
+
function measuredGoals(config) {
|
|
661
|
+
const goals = {};
|
|
662
|
+
const metrics = {};
|
|
663
|
+
const all = [...config.experiments];
|
|
664
|
+
const h = holdoutExperiment(config);
|
|
665
|
+
if (h) all.push(h);
|
|
666
|
+
for (const e of all) {
|
|
667
|
+
goals[e.key] = e.goal ?? null;
|
|
668
|
+
const extra = [...e.metrics?.secondary ?? [], ...(e.metrics?.guardrails ?? []).map((g) => g.goal)];
|
|
669
|
+
if (extra.length) metrics[e.key] = extra;
|
|
670
|
+
}
|
|
671
|
+
return { goals, metrics };
|
|
672
|
+
}
|
|
520
673
|
|
|
521
674
|
// src/assignment.ts
|
|
522
675
|
function isDevEnvironment() {
|
|
@@ -543,6 +696,24 @@ function pickVariant(experiment, visitorId) {
|
|
|
543
696
|
}
|
|
544
697
|
return experiment.variants[experiment.variants.length - 1] ?? null;
|
|
545
698
|
}
|
|
699
|
+
function holdoutGroup(config, visitorId) {
|
|
700
|
+
const h = config.holdout;
|
|
701
|
+
if (!h || !(h.percent > 0)) return null;
|
|
702
|
+
return hashToUnit(`${h.seed}:${HOLDOUT_KEY}:${visitorId}`) < h.percent / 100 ? "holdout" : "enrolled";
|
|
703
|
+
}
|
|
704
|
+
function layerBucket(config, layerKey, visitorId) {
|
|
705
|
+
const seed = config.layers?.[layerKey]?.seed ?? layerKey;
|
|
706
|
+
return Math.min(LAYER_BUCKETS - 1, Math.floor(hashToUnit(`${seed}:layer:${layerKey}:${visitorId}`) * LAYER_BUCKETS));
|
|
707
|
+
}
|
|
708
|
+
function inLayer(config, experiment, visitorId) {
|
|
709
|
+
const l = experiment.layer;
|
|
710
|
+
if (!l) return true;
|
|
711
|
+
const b = layerBucket(config, l.key, visitorId);
|
|
712
|
+
return b >= l.range[0] && b < l.range[1];
|
|
713
|
+
}
|
|
714
|
+
function countsForHoldout(a) {
|
|
715
|
+
return a.reason === "assigned" || a.reason === "holdout" || a.reason === "outside_traffic" || a.reason === "targeting" || a.reason === "layer";
|
|
716
|
+
}
|
|
546
717
|
function assign(config, experimentKey, visitorId, options = {}) {
|
|
547
718
|
const experiment = config.experiments.find((e) => e.key === experimentKey);
|
|
548
719
|
if (!experiment) return { experiment: experimentKey, variant: null, reason: "unknown_experiment" };
|
|
@@ -551,10 +722,13 @@ function assign(config, experimentKey, visitorId, options = {}) {
|
|
|
551
722
|
const variant2 = experiment.variants.find((v) => v.key === forced) ?? null;
|
|
552
723
|
if (variant2) return { experiment: experimentKey, variant: variant2, reason: "override" };
|
|
553
724
|
}
|
|
725
|
+
if (options.context?.device === "bot") return { experiment: experimentKey, variant: null, reason: "bot" };
|
|
554
726
|
const devDraft = isDevDraft(config, experiment);
|
|
555
727
|
if (!devDraft && (experiment.status !== "running" || !inSchedule(experiment, options.context?.now))) {
|
|
556
728
|
return { experiment: experimentKey, variant: null, reason: "not_running" };
|
|
557
729
|
}
|
|
730
|
+
if (holdoutGroup(config, visitorId) === "holdout") return { experiment: experimentKey, variant: null, reason: "holdout" };
|
|
731
|
+
if (!inLayer(config, experiment, visitorId)) return { experiment: experimentKey, variant: null, reason: "layer" };
|
|
558
732
|
const reason = devDraft ? "dev" : "assigned";
|
|
559
733
|
if (experiment.flow) {
|
|
560
734
|
const trafficUnit = hashToUnit(`${experiment.seed}:${experiment.key}:traffic:${visitorId}`);
|
|
@@ -580,7 +754,13 @@ function parseForceParam(search) {
|
|
|
580
754
|
const out = {};
|
|
581
755
|
const match = /[?&]sh_force=([^&]+)/.exec(search);
|
|
582
756
|
if (!match || !match[1]) return out;
|
|
583
|
-
|
|
757
|
+
let raw;
|
|
758
|
+
try {
|
|
759
|
+
raw = decodeURIComponent(match[1]);
|
|
760
|
+
} catch {
|
|
761
|
+
return out;
|
|
762
|
+
}
|
|
763
|
+
for (const pair of raw.split(",")) {
|
|
584
764
|
const [exp, variant] = pair.split(":");
|
|
585
765
|
if (exp && variant) out[exp] = variant;
|
|
586
766
|
}
|
|
@@ -611,6 +791,14 @@ function explainAssignment(experiment, a) {
|
|
|
611
791
|
devNote(`${key}:dev`, `"${key}" is a draft. You see it here because runDraftsInDev is on; this visitor gets "${shown}", try ?sh_force=${key}:${others(experiment, shown)} for the others. Visitors see it only after you start it: npx splithub start ${key}`);
|
|
612
792
|
return;
|
|
613
793
|
}
|
|
794
|
+
if (a.reason === "holdout") {
|
|
795
|
+
devNote("holdout", `This visitor is in the holdout, so every test shows its control. Open ?sh_force=${key}:${experiment.variants[1]?.key ?? "variant"} to see a variant.`);
|
|
796
|
+
return;
|
|
797
|
+
}
|
|
798
|
+
if (a.reason === "layer") {
|
|
799
|
+
devNote(`${key}:layer`, `"${key}" shares layer "${experiment.layer?.key}" with other tests and this visitor's bucket belongs to another one, so they see the control.`);
|
|
800
|
+
return;
|
|
801
|
+
}
|
|
614
802
|
if (a.reason !== "not_running") return;
|
|
615
803
|
const second = experiment.variants[1]?.key ?? "variant";
|
|
616
804
|
if (experiment.status === "draft") {
|
|
@@ -706,14 +894,65 @@ function persistExposureSet(set, key = "sh_exposed") {
|
|
|
706
894
|
safeStorage("sessionStorage")?.setItem(key, JSON.stringify([...set]));
|
|
707
895
|
}
|
|
708
896
|
|
|
897
|
+
// src/paths.ts
|
|
898
|
+
function normalizePath(path) {
|
|
899
|
+
return path.length > 1 && path.endsWith("/") ? path.replace(/\/+$/, "") || "/" : path;
|
|
900
|
+
}
|
|
901
|
+
function matchPath(pattern, pathname) {
|
|
902
|
+
if (pattern.endsWith("*")) return pathname.startsWith(pattern.slice(0, -1));
|
|
903
|
+
return normalizePath(pattern) === normalizePath(pathname);
|
|
904
|
+
}
|
|
905
|
+
function redirectTarget(to, currentHref) {
|
|
906
|
+
const current = new URL(currentHref);
|
|
907
|
+
const target = new URL(to, current);
|
|
908
|
+
const own = new Set(target.searchParams.keys());
|
|
909
|
+
current.searchParams.forEach((value, key) => {
|
|
910
|
+
if (!own.has(key)) target.searchParams.append(key, value);
|
|
911
|
+
});
|
|
912
|
+
if (!target.hash) target.hash = current.hash;
|
|
913
|
+
return target;
|
|
914
|
+
}
|
|
915
|
+
|
|
916
|
+
// src/redirect.ts
|
|
917
|
+
function decideRedirect(config, pathname, visitorId, context = {}, overrides = {}, explain) {
|
|
918
|
+
for (const exp of config.experiments) {
|
|
919
|
+
if (exp.kind !== "redirect" || !exp.match || !matchPath(exp.match, pathname)) continue;
|
|
920
|
+
if (!isActive(config, exp, context.now)) {
|
|
921
|
+
explain?.(exp, { experiment: exp.key, variant: null, reason: "not_running" });
|
|
922
|
+
continue;
|
|
923
|
+
}
|
|
924
|
+
const a = assign(config, exp.key, visitorId, { overrides, context });
|
|
925
|
+
explain?.(exp, a);
|
|
926
|
+
if (!a.variant) continue;
|
|
927
|
+
const to = a.variant.to || null;
|
|
928
|
+
const stays = !to || normalizePath(to.split(/[?#]/)[0] ?? "") === normalizePath(pathname);
|
|
929
|
+
return { experiment: exp.key, variant: a.variant.key, to: stays ? null : to, reason: a.reason };
|
|
930
|
+
}
|
|
931
|
+
return null;
|
|
932
|
+
}
|
|
933
|
+
|
|
709
934
|
// src/events.ts
|
|
935
|
+
function beaconUrl(options) {
|
|
936
|
+
if (!options.key) return options.endpoint;
|
|
937
|
+
if (!options.keyInQuery) return null;
|
|
938
|
+
return `${options.endpoint}${options.endpoint.includes("?") ? "&" : "?"}key=${encodeURIComponent(options.key)}`;
|
|
939
|
+
}
|
|
710
940
|
function createFetchTransport(options) {
|
|
711
941
|
return {
|
|
712
942
|
async send(batch, { beacon }) {
|
|
713
943
|
const body = JSON.stringify(batch);
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
944
|
+
const url = beacon && isBrowser() && typeof navigator.sendBeacon === "function" ? beaconUrl(options) : null;
|
|
945
|
+
if (url) {
|
|
946
|
+
let sameOrigin = false;
|
|
947
|
+
try {
|
|
948
|
+
sameOrigin = new URL(url, location.href).origin === location.origin;
|
|
949
|
+
} catch {
|
|
950
|
+
}
|
|
951
|
+
const blob = new Blob([body], { type: sameOrigin ? "application/json" : "text/plain;charset=UTF-8" });
|
|
952
|
+
try {
|
|
953
|
+
if (navigator.sendBeacon(url, blob)) return;
|
|
954
|
+
} catch {
|
|
955
|
+
}
|
|
717
956
|
}
|
|
718
957
|
const headers = { "content-type": "application/json" };
|
|
719
958
|
if (options.key) headers.authorization = `Bearer ${options.key}`;
|
|
@@ -726,37 +965,61 @@ function createFetchTransport(options) {
|
|
|
726
965
|
}
|
|
727
966
|
};
|
|
728
967
|
}
|
|
968
|
+
var MAX_BACKOFF_MS = 3e4;
|
|
729
969
|
var EventQueue = class {
|
|
730
970
|
constructor(options) {
|
|
731
971
|
this.options = options;
|
|
732
972
|
this.pending = [];
|
|
733
973
|
this.retry = [];
|
|
974
|
+
this.attempts = 0;
|
|
734
975
|
this.timer = null;
|
|
976
|
+
this.backoffUntil = 0;
|
|
735
977
|
this.unbind = null;
|
|
736
978
|
this.maxBatch = options.maxBatch ?? 20;
|
|
737
979
|
this.flushInterval = options.flushInterval ?? 2e3;
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
}
|
|
980
|
+
this.maxQueue = options.maxQueue ?? 200;
|
|
981
|
+
this.maxAttempts = options.maxAttempts ?? 5;
|
|
982
|
+
}
|
|
983
|
+
bind() {
|
|
984
|
+
if (this.unbind || !isBrowser()) return;
|
|
985
|
+
const onHidden = () => {
|
|
986
|
+
if (document.visibilityState === "hidden") void this.flush(true);
|
|
987
|
+
};
|
|
988
|
+
const onPageHide = () => void this.flush(true);
|
|
989
|
+
document.addEventListener("visibilitychange", onHidden);
|
|
990
|
+
window.addEventListener("pagehide", onPageHide);
|
|
991
|
+
this.unbind = () => {
|
|
992
|
+
document.removeEventListener("visibilitychange", onHidden);
|
|
993
|
+
window.removeEventListener("pagehide", onPageHide);
|
|
994
|
+
};
|
|
995
|
+
}
|
|
996
|
+
schedule(delay) {
|
|
997
|
+
if (this.timer) return;
|
|
998
|
+
this.timer = setTimeout(() => {
|
|
999
|
+
this.timer = null;
|
|
1000
|
+
void this.flush(false);
|
|
1001
|
+
}, delay);
|
|
746
1002
|
}
|
|
747
1003
|
push(event) {
|
|
1004
|
+
this.bind();
|
|
748
1005
|
this.pending.push(event);
|
|
749
|
-
|
|
1006
|
+
const overflow = this.size - this.maxQueue;
|
|
1007
|
+
if (overflow > 0) {
|
|
1008
|
+
const fromRetry = Math.min(overflow, this.retry.length);
|
|
1009
|
+
this.retry.splice(0, fromRetry);
|
|
1010
|
+
this.pending.splice(0, overflow - fromRetry);
|
|
1011
|
+
}
|
|
1012
|
+
const waiting = Date.now() < this.backoffUntil;
|
|
1013
|
+
if (!waiting && this.pending.length >= this.maxBatch) {
|
|
750
1014
|
void this.flush(false);
|
|
751
1015
|
return;
|
|
752
1016
|
}
|
|
753
|
-
|
|
754
|
-
this.timer = setTimeout(() => void this.flush(false), this.flushInterval);
|
|
755
|
-
}
|
|
1017
|
+
this.schedule(waiting ? this.backoffUntil - Date.now() : this.flushInterval);
|
|
756
1018
|
}
|
|
757
1019
|
get size() {
|
|
758
1020
|
return this.pending.length + this.retry.length;
|
|
759
1021
|
}
|
|
1022
|
+
/** Send everything now. `beacon` is for page hide: it ignores the backoff, since the page is going away. */
|
|
760
1023
|
async flush(beacon = false) {
|
|
761
1024
|
if (this.timer) {
|
|
762
1025
|
clearTimeout(this.timer);
|
|
@@ -769,15 +1032,31 @@ var EventQueue = class {
|
|
|
769
1032
|
const batch = { project: this.options.project, sdk: this.options.sdk, events };
|
|
770
1033
|
try {
|
|
771
1034
|
await this.options.transport.send(batch, { beacon });
|
|
1035
|
+
this.attempts = 0;
|
|
1036
|
+
this.backoffUntil = 0;
|
|
772
1037
|
} catch (error) {
|
|
773
1038
|
const status = error.status;
|
|
774
|
-
|
|
1039
|
+
const refused = status !== void 0 && status >= 400 && status < 500 && status !== 408 && status !== 429;
|
|
1040
|
+
this.attempts += 1;
|
|
1041
|
+
if (!refused && this.attempts < this.maxAttempts) {
|
|
1042
|
+
this.retry = events.slice(-this.maxQueue);
|
|
1043
|
+
const base = Math.min(MAX_BACKOFF_MS, 1e3 * 2 ** (this.attempts - 1));
|
|
1044
|
+
const delay = Math.round(base / 2 + Math.random() * (base / 2));
|
|
1045
|
+
this.backoffUntil = Date.now() + delay;
|
|
1046
|
+
this.schedule(delay);
|
|
1047
|
+
} else {
|
|
1048
|
+
this.attempts = 0;
|
|
1049
|
+
this.backoffUntil = 0;
|
|
1050
|
+
}
|
|
775
1051
|
this.options.onError?.(error);
|
|
776
1052
|
}
|
|
777
1053
|
}
|
|
1054
|
+
/** Stop the timer and the page listeners. Pending events stay; a later `push` binds again. */
|
|
778
1055
|
destroy() {
|
|
779
1056
|
this.unbind?.();
|
|
1057
|
+
this.unbind = null;
|
|
780
1058
|
if (this.timer) clearTimeout(this.timer);
|
|
1059
|
+
this.timer = null;
|
|
781
1060
|
}
|
|
782
1061
|
};
|
|
783
1062
|
|
|
@@ -860,10 +1139,14 @@ function applyRemoteOverrides(config, overrides) {
|
|
|
860
1139
|
const added = (overrides.added ?? []).filter((e) => e && typeof e.key === "string" && !known.has(e.key) && Array.isArray(e.variants) && e.variants.length >= 2);
|
|
861
1140
|
const knownGoals = new Set(config.goals.map((g) => g.key));
|
|
862
1141
|
const addedGoals = (overrides.goals ?? []).filter((g) => g && typeof g.key === "string" && !knownGoals.has(g.key));
|
|
863
|
-
|
|
1142
|
+
const holdout = !config.holdout && validHoldout(overrides.holdout) ? overrides.holdout : null;
|
|
1143
|
+
const layers = overrides.layers && typeof overrides.layers === "object" ? { ...overrides.layers, ...config.layers ?? {} } : null;
|
|
1144
|
+
if (Object.keys(patches).length === 0 && added.length === 0 && addedGoals.length === 0 && !holdout && !layers) return config;
|
|
864
1145
|
const merged = [...config.experiments, ...added.map((e) => ({ ...e, origin: "dashboard" }))];
|
|
865
1146
|
return {
|
|
866
1147
|
...config,
|
|
1148
|
+
...holdout ? { holdout } : {},
|
|
1149
|
+
...layers ? { layers } : {},
|
|
867
1150
|
goals: addedGoals.length ? [...config.goals, ...addedGoals] : config.goals,
|
|
868
1151
|
experiments: merged.map((e) => {
|
|
869
1152
|
const o = patches[e.key];
|
|
@@ -871,6 +1154,9 @@ function applyRemoteOverrides(config, overrides) {
|
|
|
871
1154
|
})
|
|
872
1155
|
};
|
|
873
1156
|
}
|
|
1157
|
+
function validHoldout(h) {
|
|
1158
|
+
return Boolean(h) && typeof h.percent === "number" && h.percent > 0 && h.percent <= 50 && typeof h.seed === "string";
|
|
1159
|
+
}
|
|
874
1160
|
function isRemoteOverrides(value) {
|
|
875
1161
|
return Boolean(value) && typeof value === "object" && typeof value.version === "number" && typeof value.experiments === "object";
|
|
876
1162
|
}
|
|
@@ -917,6 +1203,8 @@ async function fetchRemoteOverrides(url, fetchImpl = fetch) {
|
|
|
917
1203
|
|
|
918
1204
|
// src/client.ts
|
|
919
1205
|
var SDK_VERSION = "0.1.0";
|
|
1206
|
+
var REMOTE_WAIT_MS = 400;
|
|
1207
|
+
var DEV_NOTE = "Development sends nothing to the cloud, so your own visits never reach the results. Deployed builds send as usual.";
|
|
920
1208
|
var CLOUD_ENDPOINT = "https://go.splithub.io/v1/events";
|
|
921
1209
|
function resolveEndpoint(config) {
|
|
922
1210
|
if (config.storage.mode === "self") return { endpoint: config.storage.endpoint };
|
|
@@ -927,9 +1215,11 @@ function createClient(config, options = {}) {
|
|
|
927
1215
|
throw new Error("[splithub] pass the object returned by defineConfig() from splithub.config.ts");
|
|
928
1216
|
}
|
|
929
1217
|
const browser = isBrowser();
|
|
1218
|
+
const base = config;
|
|
930
1219
|
const publicKey = config.storage.mode === "cloud" ? config.storage.key : void 0;
|
|
931
1220
|
let effective = config;
|
|
932
1221
|
let geo;
|
|
1222
|
+
let waitFor = null;
|
|
933
1223
|
if (options.remote?.overrides) {
|
|
934
1224
|
effective = applyRemoteOverrides(config, options.remote.overrides);
|
|
935
1225
|
geo = options.remote.overrides.ctx;
|
|
@@ -943,26 +1233,38 @@ function createClient(config, options = {}) {
|
|
|
943
1233
|
const stale = !cached || Date.now() - cached.fetchedAt > (options.remote?.ttlMs ?? REMOTE_TTL_MS);
|
|
944
1234
|
if (stale) {
|
|
945
1235
|
const url = options.remote?.url ?? resolveOverridesUrl(config.storage.endpoint ?? CLOUD_ENDPOINT, publicKey);
|
|
946
|
-
|
|
947
|
-
if (fresh)
|
|
948
|
-
|
|
949
|
-
debugLog("remote", `fresh overrides v${fresh.version} fetched; applied on the next page load`, { experiments: fresh.experiments });
|
|
950
|
-
}
|
|
1236
|
+
const fetched = fetchRemoteOverrides(url).then((fresh) => {
|
|
1237
|
+
if (fresh) writeRemoteCache(publicKey, fresh);
|
|
1238
|
+
return fresh;
|
|
951
1239
|
});
|
|
1240
|
+
const waitMs = options.remote?.waitMs ?? REMOTE_WAIT_MS;
|
|
1241
|
+
if (!cached && waitMs > 0 && options.remote?.overrides === void 0) waitFor = withTimeout(fetched, waitMs);
|
|
1242
|
+
else {
|
|
1243
|
+
void fetched.then((fresh) => {
|
|
1244
|
+
if (fresh) debugLog("remote", `fresh overrides v${fresh.version} fetched; applied on the next page load`, { experiments: fresh.experiments });
|
|
1245
|
+
});
|
|
1246
|
+
}
|
|
952
1247
|
}
|
|
953
1248
|
}
|
|
954
1249
|
config = effective;
|
|
955
1250
|
const hadVisitor = browser && !options.visitorId ? hasVisitorId(config.visitorKey) : void 0;
|
|
956
1251
|
const visitorId = options.visitorId ?? (browser ? getOrCreateVisitorId(config.visitorKey) : "server");
|
|
1252
|
+
const noVisitor = !browser && !options.visitorId;
|
|
957
1253
|
const sessionId = options.sessionId ?? (browser ? getOrCreateSessionId() : "server");
|
|
958
|
-
const
|
|
1254
|
+
const contextFor = (g) => {
|
|
1255
|
+
if (!browser) return { ...g ?? {}, ...options.context ?? {} };
|
|
1256
|
+
const forPage = g?.timezone ? { ...g, timezone: void 0 } : g;
|
|
1257
|
+
return browserContext({ ...stripUndefined(forPage ?? {}), ...hadVisitor === void 0 ? {} : { visitor: hadVisitor ? "returning" : "new" }, ...options.context ?? {} });
|
|
1258
|
+
};
|
|
1259
|
+
let context = contextFor(geo);
|
|
1260
|
+
const isBot2 = () => context.device === "bot";
|
|
959
1261
|
const overrides = {
|
|
960
1262
|
...browser ? parseForceParam(location.search) : {},
|
|
961
1263
|
...options.overrides ?? {}
|
|
962
1264
|
};
|
|
963
1265
|
const disabled = options.disabled ?? (!browser && !options.transport);
|
|
964
1266
|
const cloud = config.storage.mode === "cloud";
|
|
965
|
-
const cloudIdle = cloud && !config.experiments.some((e) => e.status === "running");
|
|
1267
|
+
const cloudIdle = () => cloud && !config.experiments.some((e) => e.status === "running");
|
|
966
1268
|
const devLocal = cloud && isDevEnvironment();
|
|
967
1269
|
const held = /* @__PURE__ */ new Set();
|
|
968
1270
|
const hold = (key, kind, message) => {
|
|
@@ -970,7 +1272,10 @@ function createClient(config, options = {}) {
|
|
|
970
1272
|
held.add(key);
|
|
971
1273
|
debugLog(kind, message);
|
|
972
1274
|
};
|
|
973
|
-
const transport = options.transport ?? createFetchTransport(
|
|
1275
|
+
const transport = options.transport ?? createFetchTransport({
|
|
1276
|
+
...resolveEndpoint(config),
|
|
1277
|
+
keyInQuery: options.keyInQuery ?? (config.storage.mode === "cloud" && !config.storage.endpoint)
|
|
1278
|
+
});
|
|
974
1279
|
const queue = new EventQueue({
|
|
975
1280
|
project: config.project,
|
|
976
1281
|
sdk: `core/${SDK_VERSION}`,
|
|
@@ -979,15 +1284,98 @@ function createClient(config, options = {}) {
|
|
|
979
1284
|
});
|
|
980
1285
|
const exposed = browser ? sessionExposureSet() : /* @__PURE__ */ new Set();
|
|
981
1286
|
const currentUrl = () => browser ? location.pathname + location.search : void 0;
|
|
1287
|
+
const markHoldout = (ts) => {
|
|
1288
|
+
const group = holdoutGroup(config, visitorId);
|
|
1289
|
+
if (!group || noVisitor) return;
|
|
1290
|
+
const dedupKey = `${HOLDOUT_KEY}:${group}`;
|
|
1291
|
+
if (exposed.has(dedupKey)) return;
|
|
1292
|
+
if (devLocal) {
|
|
1293
|
+
hold(`x:${HOLDOUT_KEY}`, "exposure", `${HOLDOUT_KEY} / ${group} not sent: development never sends to the cloud`);
|
|
1294
|
+
return;
|
|
1295
|
+
}
|
|
1296
|
+
exposed.add(dedupKey);
|
|
1297
|
+
if (browser) persistExposureSet(exposed);
|
|
1298
|
+
const event = { id: newId("e_"), type: "exposure", exp: HOLDOUT_KEY, var: group, vid: visitorId, sid: sessionId, ts, url: currentUrl() };
|
|
1299
|
+
debugLog("exposure", `${HOLDOUT_KEY} / ${group} recorded`, event);
|
|
1300
|
+
queue.push(event);
|
|
1301
|
+
};
|
|
1302
|
+
let pending = waitFor !== null;
|
|
1303
|
+
const waiting = [];
|
|
1304
|
+
const listeners = /* @__PURE__ */ new Set();
|
|
1305
|
+
const sendExposure = (experimentKey, ts) => {
|
|
1306
|
+
const a = client.assignment(experimentKey);
|
|
1307
|
+
if (config.holdout && countsForHoldout(a)) markHoldout(ts);
|
|
1308
|
+
if (!a.variant || a.reason === "override") return;
|
|
1309
|
+
if (typeof __SPLITHUB_LITE__ === "undefined" && devLocal) {
|
|
1310
|
+
devNote("dev-events", DEV_NOTE);
|
|
1311
|
+
hold(`x:${experimentKey}`, "exposure", `${experimentKey} / ${a.variant.key} not sent: development never sends to the cloud`);
|
|
1312
|
+
return;
|
|
1313
|
+
}
|
|
1314
|
+
const dedupKey = `${experimentKey}:${a.variant.key}`;
|
|
1315
|
+
if (exposed.has(dedupKey)) return;
|
|
1316
|
+
exposed.add(dedupKey);
|
|
1317
|
+
if (browser) persistExposureSet(exposed);
|
|
1318
|
+
const event = { id: newId("e_"), type: "exposure", exp: experimentKey, var: a.variant.key, vid: visitorId, sid: sessionId, ts, url: currentUrl() };
|
|
1319
|
+
debugLog("exposure", `${experimentKey} / ${a.variant.key} recorded`, event);
|
|
1320
|
+
queue.push(event);
|
|
1321
|
+
};
|
|
1322
|
+
const sendGoal = (goal, props, ts) => {
|
|
1323
|
+
if (isBot2()) return;
|
|
1324
|
+
if (!config.goals.some((g) => g.key === goal)) {
|
|
1325
|
+
warn(`goal "${goal}" is not declared in splithub.config.ts; sending anyway.`);
|
|
1326
|
+
}
|
|
1327
|
+
if (typeof __SPLITHUB_LITE__ === "undefined" && devLocal) {
|
|
1328
|
+
devNote("dev-events", DEV_NOTE);
|
|
1329
|
+
hold(`g:${goal}`, "goal", `${goal} not sent: development never sends to the cloud`);
|
|
1330
|
+
return;
|
|
1331
|
+
}
|
|
1332
|
+
if (cloudIdle()) {
|
|
1333
|
+
hold(`g:${goal}`, "goal", `${goal} not sent: no experiment is running in this project yet`);
|
|
1334
|
+
return;
|
|
1335
|
+
}
|
|
1336
|
+
const event = { id: newId("g_"), type: "goal", goal, vid: visitorId, sid: sessionId, ts, url: currentUrl(), ...props ? { props } : {} };
|
|
1337
|
+
debugLog("goal", `${goal}${props ? " " + JSON.stringify(props) : ""}`, event);
|
|
1338
|
+
queue.push(event);
|
|
1339
|
+
};
|
|
1340
|
+
const ready = waitFor ? waitFor.then((fresh) => {
|
|
1341
|
+
if (fresh) {
|
|
1342
|
+
config = applyRemoteOverrides(base, fresh);
|
|
1343
|
+
context = contextFor(fresh.ctx);
|
|
1344
|
+
debugLog("remote", `first visit: overrides v${fresh.version} arrived, experiments decided`, { experiments: fresh.experiments });
|
|
1345
|
+
} else {
|
|
1346
|
+
debugLog("remote", "first visit: overrides did not arrive in time; experiments follow splithub.config.ts");
|
|
1347
|
+
}
|
|
1348
|
+
pending = false;
|
|
1349
|
+
for (const w of waiting) if ("exp" in w) sendExposure(w.exp, w.ts);
|
|
1350
|
+
for (const w of waiting) if ("goal" in w) sendGoal(w.goal, w.props, w.ts);
|
|
1351
|
+
waiting.length = 0;
|
|
1352
|
+
for (const listener of [...listeners]) listener();
|
|
1353
|
+
listeners.clear();
|
|
1354
|
+
}) : Promise.resolve();
|
|
982
1355
|
const decided = /* @__PURE__ */ new Set();
|
|
983
1356
|
const client = {
|
|
984
|
-
config
|
|
1357
|
+
get config() {
|
|
1358
|
+
return config;
|
|
1359
|
+
},
|
|
985
1360
|
visitorId,
|
|
986
1361
|
sessionId,
|
|
987
|
-
context
|
|
1362
|
+
get context() {
|
|
1363
|
+
return context;
|
|
1364
|
+
},
|
|
1365
|
+
get pending() {
|
|
1366
|
+
return pending;
|
|
1367
|
+
},
|
|
1368
|
+
ready,
|
|
1369
|
+
subscribe(listener) {
|
|
1370
|
+
if (!pending) return () => void 0;
|
|
1371
|
+
listeners.add(listener);
|
|
1372
|
+
return () => void listeners.delete(listener);
|
|
1373
|
+
},
|
|
988
1374
|
assignment(experimentKey) {
|
|
989
|
-
|
|
990
|
-
|
|
1375
|
+
if (pending) return { experiment: experimentKey, variant: null, reason: "pending" };
|
|
1376
|
+
let a = assign(config, experimentKey, visitorId, { overrides, context });
|
|
1377
|
+
if (noVisitor && a.variant && a.reason !== "override") a = { experiment: experimentKey, variant: null, reason: "no_visitor" };
|
|
1378
|
+
if (typeof __SPLITHUB_LITE__ === "undefined") explainAssignment(getExperiment(config, experimentKey), a);
|
|
991
1379
|
if (isDebug() && !decided.has(experimentKey)) {
|
|
992
1380
|
decided.add(experimentKey);
|
|
993
1381
|
const exp = getExperiment(config, experimentKey);
|
|
@@ -997,20 +1385,11 @@ function createClient(config, options = {}) {
|
|
|
997
1385
|
},
|
|
998
1386
|
exposure(experimentKey) {
|
|
999
1387
|
if (disabled) return;
|
|
1000
|
-
|
|
1001
|
-
|
|
1002
|
-
if (devLocal) {
|
|
1003
|
-
devNote("dev-events", "Development sends nothing to the cloud, so your own visits never reach the results. Deployed builds send as usual.");
|
|
1004
|
-
hold(`x:${experimentKey}`, "exposure", `${experimentKey} / ${a.variant.key} not sent: development never sends to the cloud`);
|
|
1388
|
+
if (pending) {
|
|
1389
|
+
if (!waiting.some((w) => "exp" in w && w.exp === experimentKey)) waiting.push({ exp: experimentKey, ts: Date.now() });
|
|
1005
1390
|
return;
|
|
1006
1391
|
}
|
|
1007
|
-
|
|
1008
|
-
if (exposed.has(dedupKey)) return;
|
|
1009
|
-
exposed.add(dedupKey);
|
|
1010
|
-
if (browser) persistExposureSet(exposed);
|
|
1011
|
-
const event = { id: newId("e_"), type: "exposure", exp: experimentKey, var: a.variant.key, vid: visitorId, sid: sessionId, ts: Date.now(), url: currentUrl() };
|
|
1012
|
-
debugLog("exposure", `${experimentKey} / ${a.variant.key} recorded`, event);
|
|
1013
|
-
queue.push(event);
|
|
1392
|
+
sendExposure(experimentKey, Date.now());
|
|
1014
1393
|
},
|
|
1015
1394
|
variant(experimentKey) {
|
|
1016
1395
|
const experiment = getExperiment(config, experimentKey);
|
|
@@ -1033,28 +1412,23 @@ function createClient(config, options = {}) {
|
|
|
1033
1412
|
return (a.variant ?? experiment.variants[0]).value;
|
|
1034
1413
|
},
|
|
1035
1414
|
track(goal, props) {
|
|
1036
|
-
if (disabled) return;
|
|
1037
|
-
if (
|
|
1038
|
-
|
|
1039
|
-
}
|
|
1040
|
-
if (devLocal) {
|
|
1041
|
-
devNote("dev-events", "Development sends nothing to the cloud, so your own visits never reach the results. Deployed builds send as usual.");
|
|
1042
|
-
hold(`g:${goal}`, "goal", `${goal} not sent: development never sends to the cloud`);
|
|
1043
|
-
return;
|
|
1044
|
-
}
|
|
1045
|
-
if (cloudIdle) {
|
|
1046
|
-
hold(`g:${goal}`, "goal", `${goal} not sent: no experiment is running in this project yet`);
|
|
1047
|
-
return;
|
|
1048
|
-
}
|
|
1049
|
-
const event = { id: newId("g_"), type: "goal", goal, vid: visitorId, sid: sessionId, ts: Date.now(), url: currentUrl(), ...props ? { props } : {} };
|
|
1050
|
-
debugLog("goal", `${goal}${props ? " " + JSON.stringify(props) : ""}`, event);
|
|
1051
|
-
queue.push(event);
|
|
1415
|
+
if (disabled || isBot2()) return;
|
|
1416
|
+
if (pending) waiting.push({ goal, ...props ? { props } : {}, ts: Date.now() });
|
|
1417
|
+
else sendGoal(goal, props, Date.now());
|
|
1052
1418
|
},
|
|
1053
1419
|
pageview(path) {
|
|
1054
1420
|
const current = path ?? (browser ? location.pathname : void 0);
|
|
1055
1421
|
if (!current) return;
|
|
1422
|
+
if (pending) {
|
|
1423
|
+
const ts = Date.now();
|
|
1424
|
+
void ready.then(() => {
|
|
1425
|
+
if (disabled) return;
|
|
1426
|
+
for (const goal of config.goals) if (goal.type === "pageview" && goal.path && matchPath(goal.path, current)) sendGoal(goal.key, void 0, ts);
|
|
1427
|
+
});
|
|
1428
|
+
return;
|
|
1429
|
+
}
|
|
1056
1430
|
for (const goal of config.goals) {
|
|
1057
|
-
if (goal.type === "pageview" && matchPath(goal, current)) {
|
|
1431
|
+
if (goal.type === "pageview" && goal.path && matchPath(goal.path, current)) {
|
|
1058
1432
|
debugLog("pageview", `${current} matches goal ${goal.key}`);
|
|
1059
1433
|
client.track(goal.key);
|
|
1060
1434
|
}
|
|
@@ -1079,6 +1453,8 @@ function createClient(config, options = {}) {
|
|
|
1079
1453
|
return () => target.removeEventListener("click", onClick, true);
|
|
1080
1454
|
},
|
|
1081
1455
|
flush: () => queue.flush(false),
|
|
1456
|
+
// Unbinds the page listeners; pending events are kept and a later event binds again,
|
|
1457
|
+
// so a provider may destroy on unmount even under StrictMode's double mount.
|
|
1082
1458
|
destroy: () => queue.destroy()
|
|
1083
1459
|
};
|
|
1084
1460
|
if (browser && isDebug()) {
|
|
@@ -1087,10 +1463,23 @@ function createClient(config, options = {}) {
|
|
|
1087
1463
|
}
|
|
1088
1464
|
return client;
|
|
1089
1465
|
}
|
|
1090
|
-
function
|
|
1091
|
-
|
|
1092
|
-
|
|
1093
|
-
|
|
1466
|
+
function stripUndefined(o) {
|
|
1467
|
+
return Object.fromEntries(Object.entries(o).filter(([, v]) => v !== void 0));
|
|
1468
|
+
}
|
|
1469
|
+
function withTimeout(p, ms) {
|
|
1470
|
+
return new Promise((resolve) => {
|
|
1471
|
+
const t = setTimeout(() => resolve(null), ms);
|
|
1472
|
+
p.then(
|
|
1473
|
+
(v) => {
|
|
1474
|
+
clearTimeout(t);
|
|
1475
|
+
resolve(v);
|
|
1476
|
+
},
|
|
1477
|
+
() => {
|
|
1478
|
+
clearTimeout(t);
|
|
1479
|
+
resolve(null);
|
|
1480
|
+
}
|
|
1481
|
+
);
|
|
1482
|
+
});
|
|
1094
1483
|
}
|
|
1095
1484
|
var warned = /* @__PURE__ */ new Set();
|
|
1096
1485
|
function warn(message) {
|
|
@@ -1107,11 +1496,14 @@ function warnUnknown(key) {
|
|
|
1107
1496
|
ConfigError,
|
|
1108
1497
|
EMPTY_OVERRIDES,
|
|
1109
1498
|
EventQueue,
|
|
1499
|
+
HOLDOUT_KEY,
|
|
1110
1500
|
KEYED_FIELDS,
|
|
1501
|
+
LAYER_BUCKETS,
|
|
1111
1502
|
MVT_MAX_COMBINATIONS,
|
|
1112
1503
|
MVT_MAX_FACTORS,
|
|
1113
1504
|
MVT_MAX_LEVELS,
|
|
1114
1505
|
REMOTE_TTL_MS,
|
|
1506
|
+
REMOTE_WAIT_MS,
|
|
1115
1507
|
SDK_VERSION,
|
|
1116
1508
|
TARGET_FIELDS,
|
|
1117
1509
|
TARGET_OPS,
|
|
@@ -1120,10 +1512,12 @@ function warnUnknown(key) {
|
|
|
1120
1512
|
browserContext,
|
|
1121
1513
|
contextValue,
|
|
1122
1514
|
controlVariant,
|
|
1515
|
+
countsForHoldout,
|
|
1123
1516
|
createClient,
|
|
1124
1517
|
createFetchTransport,
|
|
1125
1518
|
debugLog,
|
|
1126
1519
|
debugMode,
|
|
1520
|
+
decideRedirect,
|
|
1127
1521
|
defineConfig,
|
|
1128
1522
|
devNote,
|
|
1129
1523
|
evaluateCondition,
|
|
@@ -1134,26 +1528,36 @@ function warnUnknown(key) {
|
|
|
1134
1528
|
getOrCreateVisitorId,
|
|
1135
1529
|
hasVisitorId,
|
|
1136
1530
|
hashToUnit,
|
|
1531
|
+
holdoutExperiment,
|
|
1532
|
+
holdoutGroup,
|
|
1533
|
+
inLayer,
|
|
1137
1534
|
inSchedule,
|
|
1138
1535
|
isActive,
|
|
1536
|
+
isBot,
|
|
1139
1537
|
isBrowser,
|
|
1538
|
+
isCrawler,
|
|
1140
1539
|
isDebug,
|
|
1141
1540
|
isDevDraft,
|
|
1142
1541
|
isDevEnvironment,
|
|
1143
1542
|
isRemoteOverrides,
|
|
1144
1543
|
isSplitHubConfig,
|
|
1544
|
+
layerBucket,
|
|
1145
1545
|
matchConditions,
|
|
1546
|
+
matchPath,
|
|
1547
|
+
measuredGoals,
|
|
1146
1548
|
murmur3,
|
|
1147
1549
|
mvtVariants,
|
|
1148
1550
|
newId,
|
|
1149
1551
|
newSessionId,
|
|
1150
1552
|
newVisitorId,
|
|
1553
|
+
normalizePath,
|
|
1151
1554
|
onDebug,
|
|
1152
1555
|
parseCookies,
|
|
1153
1556
|
parseForceParam,
|
|
1154
1557
|
parseUserAgent,
|
|
1155
1558
|
pickVariant,
|
|
1156
1559
|
readRemoteCache,
|
|
1560
|
+
redirectTarget,
|
|
1157
1561
|
resetDevNotes,
|
|
1158
1562
|
resolveOverridesUrl,
|
|
1159
1563
|
runFlow,
|