@splithub/core 0.1.9 → 0.2.1
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-MQCAGUUJ.js → chunk-X6QEO4I4.js} +341 -44
- package/dist/chunk-X6QEO4I4.js.map +1 -0
- package/dist/index.cjs +373 -43
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +120 -7
- package/dist/index.d.ts +120 -7
- package/dist/index.js +46 -1
- package/dist/index.js.map +1 -1
- package/dist/{types-C9OHv2W2.d.cts → types-DiW3b8D4.d.cts} +92 -3
- package/dist/{types-C9OHv2W2.d.ts → types-DiW3b8D4.d.ts} +92 -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-MQCAGUUJ.js.map +0 -1
|
@@ -63,6 +63,28 @@ var TARGET_FIELDS = ["country", "region", "city", "device", "browser", "os", "la
|
|
|
63
63
|
var TARGET_OPS = ["is", "is_not", "contains", "not_contains", "starts_with", "in", "not_in", "matches", "exists", "not_exists"];
|
|
64
64
|
var KEYED_FIELDS = ["query", "cookie"];
|
|
65
65
|
var MAX_STEPS = 64;
|
|
66
|
+
var WEEKDAYS = ["sun", "mon", "tue", "wed", "thu", "fri", "sat"];
|
|
67
|
+
var formatters = /* @__PURE__ */ new Map();
|
|
68
|
+
function localClock(ctx) {
|
|
69
|
+
const d = new Date(ctx.now ?? Date.now());
|
|
70
|
+
const tz = ctx.timezone;
|
|
71
|
+
let f = tz ? formatters.get(tz) : null;
|
|
72
|
+
if (tz && f === void 0) {
|
|
73
|
+
try {
|
|
74
|
+
f = new Intl.DateTimeFormat("en-US", { timeZone: tz, hour: "numeric", hourCycle: "h23", weekday: "short" });
|
|
75
|
+
} catch {
|
|
76
|
+
f = null;
|
|
77
|
+
}
|
|
78
|
+
formatters.set(tz, f);
|
|
79
|
+
}
|
|
80
|
+
if (f) {
|
|
81
|
+
const parts = f.formatToParts(d);
|
|
82
|
+
const hour = Number(parts.find((p) => p.type === "hour")?.value);
|
|
83
|
+
const weekday = WEEKDAYS.indexOf((parts.find((p) => p.type === "weekday")?.value ?? "").slice(0, 3).toLowerCase());
|
|
84
|
+
if (hour >= 0 && hour < 24 && weekday >= 0) return { hour, weekday };
|
|
85
|
+
}
|
|
86
|
+
return { hour: d.getUTCHours(), weekday: d.getUTCDay() };
|
|
87
|
+
}
|
|
66
88
|
function queryParam(url, name) {
|
|
67
89
|
if (!url) return void 0;
|
|
68
90
|
const q = url.indexOf("?");
|
|
@@ -112,16 +134,12 @@ function contextValue(field, key, ctx) {
|
|
|
112
134
|
case "cookie":
|
|
113
135
|
v = key ? ctx.cookies?.[key] : void 0;
|
|
114
136
|
break;
|
|
115
|
-
case "hour":
|
|
116
|
-
|
|
117
|
-
v = d.getUTCHours();
|
|
137
|
+
case "hour":
|
|
138
|
+
v = localClock(ctx).hour;
|
|
118
139
|
break;
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
const d = ctx.now ? new Date(ctx.now) : /* @__PURE__ */ new Date();
|
|
122
|
-
v = ["sun", "mon", "tue", "wed", "thu", "fri", "sat"][d.getUTCDay()];
|
|
140
|
+
case "weekday":
|
|
141
|
+
v = WEEKDAYS[localClock(ctx).weekday];
|
|
123
142
|
break;
|
|
124
|
-
}
|
|
125
143
|
}
|
|
126
144
|
return v === void 0 || v === null ? void 0 : String(v).toLowerCase();
|
|
127
145
|
}
|
|
@@ -256,13 +274,21 @@ function validateFlow(flow, variantKeys) {
|
|
|
256
274
|
}
|
|
257
275
|
return null;
|
|
258
276
|
}
|
|
277
|
+
var BOT_UA = /bot|crawl|spider|slurp|headless|lighthouse|pingdom|facebookexternalhit|google-inspectiontool|bingpreview|mediapartners|ahrefs|semrush|phantomjs|python-requests|curl\/|wget\//i;
|
|
259
278
|
function parseUserAgent(ua) {
|
|
260
279
|
const s = ua ?? "";
|
|
261
|
-
const device =
|
|
280
|
+
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";
|
|
262
281
|
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";
|
|
263
282
|
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";
|
|
264
283
|
return { device, browser, os };
|
|
265
284
|
}
|
|
285
|
+
function isBot(ua) {
|
|
286
|
+
return Boolean(ua) && BOT_UA.test(ua);
|
|
287
|
+
}
|
|
288
|
+
var HTTP_CLIENT_UA = /^(curl|wget|python-requests)\//i;
|
|
289
|
+
function isCrawler(ua) {
|
|
290
|
+
return isBot(ua) && !HTTP_CLIENT_UA.test(ua.trim());
|
|
291
|
+
}
|
|
266
292
|
function parseCookies(header) {
|
|
267
293
|
const out = {};
|
|
268
294
|
for (const part of (header ?? "").split(";")) {
|
|
@@ -289,9 +315,17 @@ function browserContext(extra = {}) {
|
|
|
289
315
|
referrer: typeof document !== "undefined" ? document.referrer || void 0 : void 0,
|
|
290
316
|
url: location.href,
|
|
291
317
|
cookies: typeof document !== "undefined" ? parseCookies(document.cookie) : {},
|
|
318
|
+
timezone: deviceTimezone(),
|
|
292
319
|
...extra
|
|
293
320
|
};
|
|
294
321
|
}
|
|
322
|
+
function deviceTimezone() {
|
|
323
|
+
try {
|
|
324
|
+
return Intl.DateTimeFormat().resolvedOptions().timeZone || void 0;
|
|
325
|
+
} catch {
|
|
326
|
+
return void 0;
|
|
327
|
+
}
|
|
328
|
+
}
|
|
295
329
|
|
|
296
330
|
// src/config.ts
|
|
297
331
|
var KEY_PATTERN = /^[a-z0-9][a-z0-9_-]{0,63}$/;
|
|
@@ -360,7 +394,60 @@ function normalizeVariants(expKey, input) {
|
|
|
360
394
|
}
|
|
361
395
|
return raw.map((v) => ({ ...v, weight: v.weight / total }));
|
|
362
396
|
}
|
|
363
|
-
|
|
397
|
+
var HOLDOUT_KEY = "__holdout";
|
|
398
|
+
var LAYER_BUCKETS = 100;
|
|
399
|
+
function normalizeMetrics(key, input, goals) {
|
|
400
|
+
const m = input.metrics;
|
|
401
|
+
if (!m) return void 0;
|
|
402
|
+
if (!input.goal) throw new ConfigError(`experiment "${key}": metrics need a primary "goal" too.`);
|
|
403
|
+
const seen = /* @__PURE__ */ new Set([input.goal]);
|
|
404
|
+
const check = (goal, where) => {
|
|
405
|
+
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".`);
|
|
406
|
+
if (seen.has(goal)) throw new ConfigError(`experiment "${key}": goal "${goal}" is listed twice (primary goal and metrics count once each).`);
|
|
407
|
+
seen.add(goal);
|
|
408
|
+
return goal;
|
|
409
|
+
};
|
|
410
|
+
const secondary = (m.secondary ?? []).map((g) => check(g, "secondary"));
|
|
411
|
+
const guardrails = (m.guardrails ?? []).map((g) => {
|
|
412
|
+
const obj = typeof g === "string" ? { goal: g } : g;
|
|
413
|
+
const worse = obj.worse ?? "lower";
|
|
414
|
+
if (worse !== "lower" && worse !== "higher") throw new ConfigError(`experiment "${key}": guardrail "${obj.goal}": worse must be "lower" or "higher".`);
|
|
415
|
+
return { goal: check(obj.goal, "guardrails"), worse };
|
|
416
|
+
});
|
|
417
|
+
if (secondary.length === 0 && guardrails.length === 0) return void 0;
|
|
418
|
+
return { secondary, guardrails };
|
|
419
|
+
}
|
|
420
|
+
function normalizeLayer(key, input, layers) {
|
|
421
|
+
const l = input.layer;
|
|
422
|
+
if (!l) return void 0;
|
|
423
|
+
if (!l.key || !(l.key in layers)) throw new ConfigError(`experiment "${key}": layer "${String(l.key)}" is not declared in "layers".`);
|
|
424
|
+
const [start, end] = Array.isArray(l.range) ? l.range : [NaN, NaN];
|
|
425
|
+
const ok = (n) => typeof n === "number" && Number.isInteger(n) && n >= 0 && n <= LAYER_BUCKETS;
|
|
426
|
+
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}.`);
|
|
427
|
+
return { key: l.key, range: [start, end] };
|
|
428
|
+
}
|
|
429
|
+
function assertNoOverlap(experiments) {
|
|
430
|
+
const live = experiments.filter((e) => e.layer && e.status !== "finished");
|
|
431
|
+
for (let i = 0; i < live.length; i++) {
|
|
432
|
+
for (let j = i + 1; j < live.length; j++) {
|
|
433
|
+
const a = live[i];
|
|
434
|
+
const b = live[j];
|
|
435
|
+
if (a.layer.key !== b.layer.key) continue;
|
|
436
|
+
if (a.layer.range[0] < b.layer.range[1] && b.layer.range[0] < a.layer.range[1]) {
|
|
437
|
+
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.`);
|
|
438
|
+
}
|
|
439
|
+
}
|
|
440
|
+
}
|
|
441
|
+
}
|
|
442
|
+
function normalizeHoldout(input, goals) {
|
|
443
|
+
const h = input.holdout;
|
|
444
|
+
if (!h) return null;
|
|
445
|
+
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.");
|
|
446
|
+
if (h.goal && !goals.some((g) => g.key === h.goal)) throw new ConfigError(`holdout.goal "${h.goal}" is not declared in "goals".`);
|
|
447
|
+
if (h.percent === 0) return null;
|
|
448
|
+
return { percent: h.percent, seed: h.seed ?? HOLDOUT_KEY, goal: h.goal ?? goals[0]?.key ?? null };
|
|
449
|
+
}
|
|
450
|
+
function normalizeExperiment(key, input, goals, layers = {}) {
|
|
364
451
|
assertKey("experiment", key);
|
|
365
452
|
const traffic = input.traffic ?? 1;
|
|
366
453
|
if (traffic < 0 || traffic > 1) {
|
|
@@ -375,10 +462,18 @@ function normalizeExperiment(key, input, goals) {
|
|
|
375
462
|
if (input.maxExposures !== void 0 && (!Number.isFinite(input.maxExposures) || input.maxExposures < 1)) {
|
|
376
463
|
throw new ConfigError(`experiment "${key}": maxExposures must be a positive number.`);
|
|
377
464
|
}
|
|
465
|
+
if (input.minDays !== void 0 && !(Number.isInteger(input.minDays) && input.minDays >= 0 && input.minDays <= 30)) {
|
|
466
|
+
throw new ConfigError(`experiment "${key}": minDays must be a whole number from 0 to 30.`);
|
|
467
|
+
}
|
|
468
|
+
if (input.goodSample !== void 0 && !(Number.isInteger(input.goodSample) && input.goodSample >= 100 && input.goodSample <= 1e7)) {
|
|
469
|
+
throw new ConfigError(`experiment "${key}": goodSample must be a whole number from 100 to 10,000,000.`);
|
|
470
|
+
}
|
|
378
471
|
for (const [k, v] of Object.entries(input.schedule ?? {})) {
|
|
379
472
|
if (v !== void 0 && Number.isNaN(Date.parse(v))) throw new ConfigError(`experiment "${key}": schedule.${k} must be an ISO date.`);
|
|
380
473
|
}
|
|
381
474
|
const variants = normalizeVariants(key, input);
|
|
475
|
+
const metrics = normalizeMetrics(key, input, goals);
|
|
476
|
+
const layer = normalizeLayer(key, input, layers);
|
|
382
477
|
if (input.flow) {
|
|
383
478
|
const problem = validateFlow(input.flow, variants.map((v) => v.key));
|
|
384
479
|
if (problem) throw new ConfigError(`experiment "${key}": flow: ${problem}`);
|
|
@@ -395,6 +490,10 @@ function normalizeExperiment(key, input, goals) {
|
|
|
395
490
|
variants,
|
|
396
491
|
...input.kind === "mvt" ? { factors: mvtVariants(key, input.factors).factors } : {},
|
|
397
492
|
...input.flow ? { flow: input.flow } : {},
|
|
493
|
+
...metrics ? { metrics } : {},
|
|
494
|
+
...layer ? { layer } : {},
|
|
495
|
+
...input.minDays !== void 0 ? { minDays: input.minDays } : {},
|
|
496
|
+
...input.goodSample !== void 0 ? { goodSample: input.goodSample } : {},
|
|
398
497
|
...input.maxExposures ? { maxExposures: Math.floor(input.maxExposures) } : {},
|
|
399
498
|
...input.schedule && (input.schedule.startAt || input.schedule.endAt) ? { schedule: { startAt: input.schedule.startAt ?? null, endAt: input.schedule.endAt ?? null } } : {}
|
|
400
499
|
};
|
|
@@ -417,9 +516,16 @@ function defineConfig(input) {
|
|
|
417
516
|
description: g.description ?? null
|
|
418
517
|
};
|
|
419
518
|
});
|
|
519
|
+
const layers = {};
|
|
520
|
+
for (const [key, l] of Object.entries(input.layers ?? {})) {
|
|
521
|
+
assertKey("layer", key);
|
|
522
|
+
layers[key] = { seed: l?.seed ?? key };
|
|
523
|
+
}
|
|
420
524
|
const experiments = Object.entries(input.experiments ?? {}).map(
|
|
421
|
-
([key, exp]) => normalizeExperiment(key, exp, goals)
|
|
525
|
+
([key, exp]) => normalizeExperiment(key, exp, goals, layers)
|
|
422
526
|
);
|
|
527
|
+
assertNoOverlap(experiments);
|
|
528
|
+
const holdout = normalizeHoldout(input, goals);
|
|
423
529
|
return {
|
|
424
530
|
project: input.project,
|
|
425
531
|
storage: input.storage,
|
|
@@ -427,6 +533,8 @@ function defineConfig(input) {
|
|
|
427
533
|
runDraftsInDev: input.runDraftsInDev === true,
|
|
428
534
|
goals,
|
|
429
535
|
experiments,
|
|
536
|
+
...Object.keys(layers).length ? { layers } : {},
|
|
537
|
+
...holdout ? { holdout } : {},
|
|
430
538
|
__splithub: 2
|
|
431
539
|
};
|
|
432
540
|
}
|
|
@@ -436,6 +544,40 @@ function isSplitHubConfig(value) {
|
|
|
436
544
|
function getExperiment(config, key) {
|
|
437
545
|
return config.experiments.find((e) => e.key === key);
|
|
438
546
|
}
|
|
547
|
+
function holdoutExperiment(config) {
|
|
548
|
+
const h = config.holdout;
|
|
549
|
+
if (!h) return null;
|
|
550
|
+
const share = h.percent / 100;
|
|
551
|
+
const secondary = config.goals.map((g) => g.key).filter((g) => g !== h.goal);
|
|
552
|
+
return {
|
|
553
|
+
key: HOLDOUT_KEY,
|
|
554
|
+
kind: "component",
|
|
555
|
+
status: "running",
|
|
556
|
+
traffic: 1,
|
|
557
|
+
goal: h.goal,
|
|
558
|
+
seed: h.seed,
|
|
559
|
+
description: `Holdout: ${h.percent}% of visitors see no test at all`,
|
|
560
|
+
match: null,
|
|
561
|
+
variants: [
|
|
562
|
+
{ key: "holdout", weight: share },
|
|
563
|
+
{ key: "enrolled", weight: 1 - share }
|
|
564
|
+
],
|
|
565
|
+
...h.goal && secondary.length ? { metrics: { secondary, guardrails: [] } } : {}
|
|
566
|
+
};
|
|
567
|
+
}
|
|
568
|
+
function measuredGoals(config) {
|
|
569
|
+
const goals = {};
|
|
570
|
+
const metrics = {};
|
|
571
|
+
const all = [...config.experiments];
|
|
572
|
+
const h = holdoutExperiment(config);
|
|
573
|
+
if (h) all.push(h);
|
|
574
|
+
for (const e of all) {
|
|
575
|
+
goals[e.key] = e.goal ?? null;
|
|
576
|
+
const extra = [...e.metrics?.secondary ?? [], ...(e.metrics?.guardrails ?? []).map((g) => g.goal)];
|
|
577
|
+
if (extra.length) metrics[e.key] = extra;
|
|
578
|
+
}
|
|
579
|
+
return { goals, metrics };
|
|
580
|
+
}
|
|
439
581
|
|
|
440
582
|
// src/assignment.ts
|
|
441
583
|
function isDevEnvironment() {
|
|
@@ -462,6 +604,24 @@ function pickVariant(experiment, visitorId) {
|
|
|
462
604
|
}
|
|
463
605
|
return experiment.variants[experiment.variants.length - 1] ?? null;
|
|
464
606
|
}
|
|
607
|
+
function holdoutGroup(config, visitorId) {
|
|
608
|
+
const h = config.holdout;
|
|
609
|
+
if (!h || !(h.percent > 0)) return null;
|
|
610
|
+
return hashToUnit(`${h.seed}:${HOLDOUT_KEY}:${visitorId}`) < h.percent / 100 ? "holdout" : "enrolled";
|
|
611
|
+
}
|
|
612
|
+
function layerBucket(config, layerKey, visitorId) {
|
|
613
|
+
const seed = config.layers?.[layerKey]?.seed ?? layerKey;
|
|
614
|
+
return Math.min(LAYER_BUCKETS - 1, Math.floor(hashToUnit(`${seed}:layer:${layerKey}:${visitorId}`) * LAYER_BUCKETS));
|
|
615
|
+
}
|
|
616
|
+
function inLayer(config, experiment, visitorId) {
|
|
617
|
+
const l = experiment.layer;
|
|
618
|
+
if (!l) return true;
|
|
619
|
+
const b = layerBucket(config, l.key, visitorId);
|
|
620
|
+
return b >= l.range[0] && b < l.range[1];
|
|
621
|
+
}
|
|
622
|
+
function countsForHoldout(a) {
|
|
623
|
+
return a.reason === "assigned" || a.reason === "holdout" || a.reason === "outside_traffic" || a.reason === "targeting" || a.reason === "layer";
|
|
624
|
+
}
|
|
465
625
|
function assign(config, experimentKey, visitorId, options = {}) {
|
|
466
626
|
const experiment = config.experiments.find((e) => e.key === experimentKey);
|
|
467
627
|
if (!experiment) return { experiment: experimentKey, variant: null, reason: "unknown_experiment" };
|
|
@@ -470,10 +630,13 @@ function assign(config, experimentKey, visitorId, options = {}) {
|
|
|
470
630
|
const variant2 = experiment.variants.find((v) => v.key === forced) ?? null;
|
|
471
631
|
if (variant2) return { experiment: experimentKey, variant: variant2, reason: "override" };
|
|
472
632
|
}
|
|
633
|
+
if (options.context?.device === "bot") return { experiment: experimentKey, variant: null, reason: "bot" };
|
|
473
634
|
const devDraft = isDevDraft(config, experiment);
|
|
474
635
|
if (!devDraft && (experiment.status !== "running" || !inSchedule(experiment, options.context?.now))) {
|
|
475
636
|
return { experiment: experimentKey, variant: null, reason: "not_running" };
|
|
476
637
|
}
|
|
638
|
+
if (holdoutGroup(config, visitorId) === "holdout") return { experiment: experimentKey, variant: null, reason: "holdout" };
|
|
639
|
+
if (!inLayer(config, experiment, visitorId)) return { experiment: experimentKey, variant: null, reason: "layer" };
|
|
477
640
|
const reason = devDraft ? "dev" : "assigned";
|
|
478
641
|
if (experiment.flow) {
|
|
479
642
|
const trafficUnit = hashToUnit(`${experiment.seed}:${experiment.key}:traffic:${visitorId}`);
|
|
@@ -499,7 +662,13 @@ function parseForceParam(search) {
|
|
|
499
662
|
const out = {};
|
|
500
663
|
const match = /[?&]sh_force=([^&]+)/.exec(search);
|
|
501
664
|
if (!match || !match[1]) return out;
|
|
502
|
-
|
|
665
|
+
let raw;
|
|
666
|
+
try {
|
|
667
|
+
raw = decodeURIComponent(match[1]);
|
|
668
|
+
} catch {
|
|
669
|
+
return out;
|
|
670
|
+
}
|
|
671
|
+
for (const pair of raw.split(",")) {
|
|
503
672
|
const [exp, variant] = pair.split(":");
|
|
504
673
|
if (exp && variant) out[exp] = variant;
|
|
505
674
|
}
|
|
@@ -530,6 +699,14 @@ function explainAssignment(experiment, a) {
|
|
|
530
699
|
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}`);
|
|
531
700
|
return;
|
|
532
701
|
}
|
|
702
|
+
if (a.reason === "holdout") {
|
|
703
|
+
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.`);
|
|
704
|
+
return;
|
|
705
|
+
}
|
|
706
|
+
if (a.reason === "layer") {
|
|
707
|
+
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.`);
|
|
708
|
+
return;
|
|
709
|
+
}
|
|
533
710
|
if (a.reason !== "not_running") return;
|
|
534
711
|
const second = experiment.variants[1]?.key ?? "variant";
|
|
535
712
|
if (experiment.status === "draft") {
|
|
@@ -625,14 +802,47 @@ function persistExposureSet(set, key = "sh_exposed") {
|
|
|
625
802
|
safeStorage("sessionStorage")?.setItem(key, JSON.stringify([...set]));
|
|
626
803
|
}
|
|
627
804
|
|
|
805
|
+
// src/paths.ts
|
|
806
|
+
function normalizePath(path) {
|
|
807
|
+
return path.length > 1 && path.endsWith("/") ? path.replace(/\/+$/, "") || "/" : path;
|
|
808
|
+
}
|
|
809
|
+
function matchPath(pattern, pathname) {
|
|
810
|
+
if (pattern.endsWith("*")) return pathname.startsWith(pattern.slice(0, -1));
|
|
811
|
+
return normalizePath(pattern) === normalizePath(pathname);
|
|
812
|
+
}
|
|
813
|
+
function redirectTarget(to, currentHref) {
|
|
814
|
+
const current = new URL(currentHref);
|
|
815
|
+
const target = new URL(to, current);
|
|
816
|
+
const own = new Set(target.searchParams.keys());
|
|
817
|
+
current.searchParams.forEach((value, key) => {
|
|
818
|
+
if (!own.has(key)) target.searchParams.append(key, value);
|
|
819
|
+
});
|
|
820
|
+
if (!target.hash) target.hash = current.hash;
|
|
821
|
+
return target;
|
|
822
|
+
}
|
|
823
|
+
|
|
628
824
|
// src/events.ts
|
|
825
|
+
function beaconUrl(options) {
|
|
826
|
+
if (!options.key) return options.endpoint;
|
|
827
|
+
if (!options.keyInQuery) return null;
|
|
828
|
+
return `${options.endpoint}${options.endpoint.includes("?") ? "&" : "?"}key=${encodeURIComponent(options.key)}`;
|
|
829
|
+
}
|
|
629
830
|
function createFetchTransport(options) {
|
|
630
831
|
return {
|
|
631
832
|
async send(batch, { beacon }) {
|
|
632
833
|
const body = JSON.stringify(batch);
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
834
|
+
const url = beacon && isBrowser() && typeof navigator.sendBeacon === "function" ? beaconUrl(options) : null;
|
|
835
|
+
if (url) {
|
|
836
|
+
let sameOrigin = false;
|
|
837
|
+
try {
|
|
838
|
+
sameOrigin = new URL(url, location.href).origin === location.origin;
|
|
839
|
+
} catch {
|
|
840
|
+
}
|
|
841
|
+
const blob = new Blob([body], { type: sameOrigin ? "application/json" : "text/plain;charset=UTF-8" });
|
|
842
|
+
try {
|
|
843
|
+
if (navigator.sendBeacon(url, blob)) return;
|
|
844
|
+
} catch {
|
|
845
|
+
}
|
|
636
846
|
}
|
|
637
847
|
const headers = { "content-type": "application/json" };
|
|
638
848
|
if (options.key) headers.authorization = `Bearer ${options.key}`;
|
|
@@ -645,37 +855,61 @@ function createFetchTransport(options) {
|
|
|
645
855
|
}
|
|
646
856
|
};
|
|
647
857
|
}
|
|
858
|
+
var MAX_BACKOFF_MS = 3e4;
|
|
648
859
|
var EventQueue = class {
|
|
649
860
|
constructor(options) {
|
|
650
861
|
this.options = options;
|
|
651
862
|
this.pending = [];
|
|
652
863
|
this.retry = [];
|
|
864
|
+
this.attempts = 0;
|
|
653
865
|
this.timer = null;
|
|
866
|
+
this.backoffUntil = 0;
|
|
654
867
|
this.unbind = null;
|
|
655
868
|
this.maxBatch = options.maxBatch ?? 20;
|
|
656
869
|
this.flushInterval = options.flushInterval ?? 2e3;
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
}
|
|
870
|
+
this.maxQueue = options.maxQueue ?? 200;
|
|
871
|
+
this.maxAttempts = options.maxAttempts ?? 5;
|
|
872
|
+
}
|
|
873
|
+
bind() {
|
|
874
|
+
if (this.unbind || !isBrowser()) return;
|
|
875
|
+
const onHidden = () => {
|
|
876
|
+
if (document.visibilityState === "hidden") void this.flush(true);
|
|
877
|
+
};
|
|
878
|
+
const onPageHide = () => void this.flush(true);
|
|
879
|
+
document.addEventListener("visibilitychange", onHidden);
|
|
880
|
+
window.addEventListener("pagehide", onPageHide);
|
|
881
|
+
this.unbind = () => {
|
|
882
|
+
document.removeEventListener("visibilitychange", onHidden);
|
|
883
|
+
window.removeEventListener("pagehide", onPageHide);
|
|
884
|
+
};
|
|
885
|
+
}
|
|
886
|
+
schedule(delay) {
|
|
887
|
+
if (this.timer) return;
|
|
888
|
+
this.timer = setTimeout(() => {
|
|
889
|
+
this.timer = null;
|
|
890
|
+
void this.flush(false);
|
|
891
|
+
}, delay);
|
|
665
892
|
}
|
|
666
893
|
push(event) {
|
|
894
|
+
this.bind();
|
|
667
895
|
this.pending.push(event);
|
|
668
|
-
|
|
896
|
+
const overflow = this.size - this.maxQueue;
|
|
897
|
+
if (overflow > 0) {
|
|
898
|
+
const fromRetry = Math.min(overflow, this.retry.length);
|
|
899
|
+
this.retry.splice(0, fromRetry);
|
|
900
|
+
this.pending.splice(0, overflow - fromRetry);
|
|
901
|
+
}
|
|
902
|
+
const waiting = Date.now() < this.backoffUntil;
|
|
903
|
+
if (!waiting && this.pending.length >= this.maxBatch) {
|
|
669
904
|
void this.flush(false);
|
|
670
905
|
return;
|
|
671
906
|
}
|
|
672
|
-
|
|
673
|
-
this.timer = setTimeout(() => void this.flush(false), this.flushInterval);
|
|
674
|
-
}
|
|
907
|
+
this.schedule(waiting ? this.backoffUntil - Date.now() : this.flushInterval);
|
|
675
908
|
}
|
|
676
909
|
get size() {
|
|
677
910
|
return this.pending.length + this.retry.length;
|
|
678
911
|
}
|
|
912
|
+
/** Send everything now. `beacon` is for page hide: it ignores the backoff, since the page is going away. */
|
|
679
913
|
async flush(beacon = false) {
|
|
680
914
|
if (this.timer) {
|
|
681
915
|
clearTimeout(this.timer);
|
|
@@ -688,15 +922,31 @@ var EventQueue = class {
|
|
|
688
922
|
const batch = { project: this.options.project, sdk: this.options.sdk, events };
|
|
689
923
|
try {
|
|
690
924
|
await this.options.transport.send(batch, { beacon });
|
|
925
|
+
this.attempts = 0;
|
|
926
|
+
this.backoffUntil = 0;
|
|
691
927
|
} catch (error) {
|
|
692
928
|
const status = error.status;
|
|
693
|
-
|
|
929
|
+
const refused = status !== void 0 && status >= 400 && status < 500 && status !== 408 && status !== 429;
|
|
930
|
+
this.attempts += 1;
|
|
931
|
+
if (!refused && this.attempts < this.maxAttempts) {
|
|
932
|
+
this.retry = events.slice(-this.maxQueue);
|
|
933
|
+
const base = Math.min(MAX_BACKOFF_MS, 1e3 * 2 ** (this.attempts - 1));
|
|
934
|
+
const delay = Math.round(base / 2 + Math.random() * (base / 2));
|
|
935
|
+
this.backoffUntil = Date.now() + delay;
|
|
936
|
+
this.schedule(delay);
|
|
937
|
+
} else {
|
|
938
|
+
this.attempts = 0;
|
|
939
|
+
this.backoffUntil = 0;
|
|
940
|
+
}
|
|
694
941
|
this.options.onError?.(error);
|
|
695
942
|
}
|
|
696
943
|
}
|
|
944
|
+
/** Stop the timer and the page listeners. Pending events stay; a later `push` binds again. */
|
|
697
945
|
destroy() {
|
|
698
946
|
this.unbind?.();
|
|
947
|
+
this.unbind = null;
|
|
699
948
|
if (this.timer) clearTimeout(this.timer);
|
|
949
|
+
this.timer = null;
|
|
700
950
|
}
|
|
701
951
|
};
|
|
702
952
|
|
|
@@ -779,10 +1029,14 @@ function applyRemoteOverrides(config, overrides) {
|
|
|
779
1029
|
const added = (overrides.added ?? []).filter((e) => e && typeof e.key === "string" && !known.has(e.key) && Array.isArray(e.variants) && e.variants.length >= 2);
|
|
780
1030
|
const knownGoals = new Set(config.goals.map((g) => g.key));
|
|
781
1031
|
const addedGoals = (overrides.goals ?? []).filter((g) => g && typeof g.key === "string" && !knownGoals.has(g.key));
|
|
782
|
-
|
|
1032
|
+
const holdout = !config.holdout && validHoldout(overrides.holdout) ? overrides.holdout : null;
|
|
1033
|
+
const layers = overrides.layers && typeof overrides.layers === "object" ? { ...overrides.layers, ...config.layers ?? {} } : null;
|
|
1034
|
+
if (Object.keys(patches).length === 0 && added.length === 0 && addedGoals.length === 0 && !holdout && !layers) return config;
|
|
783
1035
|
const merged = [...config.experiments, ...added.map((e) => ({ ...e, origin: "dashboard" }))];
|
|
784
1036
|
return {
|
|
785
1037
|
...config,
|
|
1038
|
+
...holdout ? { holdout } : {},
|
|
1039
|
+
...layers ? { layers } : {},
|
|
786
1040
|
goals: addedGoals.length ? [...config.goals, ...addedGoals] : config.goals,
|
|
787
1041
|
experiments: merged.map((e) => {
|
|
788
1042
|
const o = patches[e.key];
|
|
@@ -790,6 +1044,9 @@ function applyRemoteOverrides(config, overrides) {
|
|
|
790
1044
|
})
|
|
791
1045
|
};
|
|
792
1046
|
}
|
|
1047
|
+
function validHoldout(h) {
|
|
1048
|
+
return Boolean(h) && typeof h.percent === "number" && h.percent > 0 && h.percent <= 50 && typeof h.seed === "string";
|
|
1049
|
+
}
|
|
793
1050
|
function isRemoteOverrides(value) {
|
|
794
1051
|
return Boolean(value) && typeof value === "object" && typeof value.version === "number" && typeof value.experiments === "object";
|
|
795
1052
|
}
|
|
@@ -882,9 +1139,15 @@ function createClient(config, options = {}) {
|
|
|
882
1139
|
config = effective;
|
|
883
1140
|
const hadVisitor = browser && !options.visitorId ? hasVisitorId(config.visitorKey) : void 0;
|
|
884
1141
|
const visitorId = options.visitorId ?? (browser ? getOrCreateVisitorId(config.visitorKey) : "server");
|
|
1142
|
+
const noVisitor = !browser && !options.visitorId;
|
|
885
1143
|
const sessionId = options.sessionId ?? (browser ? getOrCreateSessionId() : "server");
|
|
886
|
-
const contextFor = (g) =>
|
|
1144
|
+
const contextFor = (g) => {
|
|
1145
|
+
if (!browser) return { ...g ?? {}, ...options.context ?? {} };
|
|
1146
|
+
const forPage = g?.timezone ? { ...g, timezone: void 0 } : g;
|
|
1147
|
+
return browserContext({ ...stripUndefined(forPage ?? {}), ...hadVisitor === void 0 ? {} : { visitor: hadVisitor ? "returning" : "new" }, ...options.context ?? {} });
|
|
1148
|
+
};
|
|
887
1149
|
let context = contextFor(geo);
|
|
1150
|
+
const isBot2 = () => context.device === "bot";
|
|
888
1151
|
const overrides = {
|
|
889
1152
|
...browser ? parseForceParam(location.search) : {},
|
|
890
1153
|
...options.overrides ?? {}
|
|
@@ -899,7 +1162,10 @@ function createClient(config, options = {}) {
|
|
|
899
1162
|
held.add(key);
|
|
900
1163
|
debugLog(kind, message);
|
|
901
1164
|
};
|
|
902
|
-
const transport = options.transport ?? createFetchTransport(
|
|
1165
|
+
const transport = options.transport ?? createFetchTransport({
|
|
1166
|
+
...resolveEndpoint(config),
|
|
1167
|
+
keyInQuery: options.keyInQuery ?? (config.storage.mode === "cloud" && !config.storage.endpoint)
|
|
1168
|
+
});
|
|
903
1169
|
const queue = new EventQueue({
|
|
904
1170
|
project: config.project,
|
|
905
1171
|
sdk: `core/${SDK_VERSION}`,
|
|
@@ -908,13 +1174,29 @@ function createClient(config, options = {}) {
|
|
|
908
1174
|
});
|
|
909
1175
|
const exposed = browser ? sessionExposureSet() : /* @__PURE__ */ new Set();
|
|
910
1176
|
const currentUrl = () => browser ? location.pathname + location.search : void 0;
|
|
1177
|
+
const markHoldout = (ts) => {
|
|
1178
|
+
const group = holdoutGroup(config, visitorId);
|
|
1179
|
+
if (!group || noVisitor) return;
|
|
1180
|
+
const dedupKey = `${HOLDOUT_KEY}:${group}`;
|
|
1181
|
+
if (exposed.has(dedupKey)) return;
|
|
1182
|
+
if (devLocal) {
|
|
1183
|
+
hold(`x:${HOLDOUT_KEY}`, "exposure", `${HOLDOUT_KEY} / ${group} not sent: development never sends to the cloud`);
|
|
1184
|
+
return;
|
|
1185
|
+
}
|
|
1186
|
+
exposed.add(dedupKey);
|
|
1187
|
+
if (browser) persistExposureSet(exposed);
|
|
1188
|
+
const event = { id: newId("e_"), type: "exposure", exp: HOLDOUT_KEY, var: group, vid: visitorId, sid: sessionId, ts, url: currentUrl() };
|
|
1189
|
+
debugLog("exposure", `${HOLDOUT_KEY} / ${group} recorded`, event);
|
|
1190
|
+
queue.push(event);
|
|
1191
|
+
};
|
|
911
1192
|
let pending = waitFor !== null;
|
|
912
1193
|
const waiting = [];
|
|
913
1194
|
const listeners = /* @__PURE__ */ new Set();
|
|
914
1195
|
const sendExposure = (experimentKey, ts) => {
|
|
915
1196
|
const a = client.assignment(experimentKey);
|
|
1197
|
+
if (config.holdout && countsForHoldout(a)) markHoldout(ts);
|
|
916
1198
|
if (!a.variant || a.reason === "override") return;
|
|
917
|
-
if (devLocal) {
|
|
1199
|
+
if (typeof __SPLITHUB_LITE__ === "undefined" && devLocal) {
|
|
918
1200
|
devNote("dev-events", DEV_NOTE);
|
|
919
1201
|
hold(`x:${experimentKey}`, "exposure", `${experimentKey} / ${a.variant.key} not sent: development never sends to the cloud`);
|
|
920
1202
|
return;
|
|
@@ -928,10 +1210,11 @@ function createClient(config, options = {}) {
|
|
|
928
1210
|
queue.push(event);
|
|
929
1211
|
};
|
|
930
1212
|
const sendGoal = (goal, props, ts) => {
|
|
1213
|
+
if (isBot2()) return;
|
|
931
1214
|
if (!config.goals.some((g) => g.key === goal)) {
|
|
932
1215
|
warn(`goal "${goal}" is not declared in splithub.config.ts; sending anyway.`);
|
|
933
1216
|
}
|
|
934
|
-
if (devLocal) {
|
|
1217
|
+
if (typeof __SPLITHUB_LITE__ === "undefined" && devLocal) {
|
|
935
1218
|
devNote("dev-events", DEV_NOTE);
|
|
936
1219
|
hold(`g:${goal}`, "goal", `${goal} not sent: development never sends to the cloud`);
|
|
937
1220
|
return;
|
|
@@ -980,8 +1263,9 @@ function createClient(config, options = {}) {
|
|
|
980
1263
|
},
|
|
981
1264
|
assignment(experimentKey) {
|
|
982
1265
|
if (pending) return { experiment: experimentKey, variant: null, reason: "pending" };
|
|
983
|
-
|
|
984
|
-
|
|
1266
|
+
let a = assign(config, experimentKey, visitorId, { overrides, context });
|
|
1267
|
+
if (noVisitor && a.variant && a.reason !== "override") a = { experiment: experimentKey, variant: null, reason: "no_visitor" };
|
|
1268
|
+
if (typeof __SPLITHUB_LITE__ === "undefined") explainAssignment(getExperiment(config, experimentKey), a);
|
|
985
1269
|
if (isDebug() && !decided.has(experimentKey)) {
|
|
986
1270
|
decided.add(experimentKey);
|
|
987
1271
|
const exp = getExperiment(config, experimentKey);
|
|
@@ -1018,7 +1302,7 @@ function createClient(config, options = {}) {
|
|
|
1018
1302
|
return (a.variant ?? experiment.variants[0]).value;
|
|
1019
1303
|
},
|
|
1020
1304
|
track(goal, props) {
|
|
1021
|
-
if (disabled) return;
|
|
1305
|
+
if (disabled || isBot2()) return;
|
|
1022
1306
|
if (pending) waiting.push({ goal, ...props ? { props } : {}, ts: Date.now() });
|
|
1023
1307
|
else sendGoal(goal, props, Date.now());
|
|
1024
1308
|
},
|
|
@@ -1029,12 +1313,12 @@ function createClient(config, options = {}) {
|
|
|
1029
1313
|
const ts = Date.now();
|
|
1030
1314
|
void ready.then(() => {
|
|
1031
1315
|
if (disabled) return;
|
|
1032
|
-
for (const goal of config.goals) if (goal.type === "pageview" && matchPath(goal, current)) sendGoal(goal.key, void 0, ts);
|
|
1316
|
+
for (const goal of config.goals) if (goal.type === "pageview" && goal.path && matchPath(goal.path, current)) sendGoal(goal.key, void 0, ts);
|
|
1033
1317
|
});
|
|
1034
1318
|
return;
|
|
1035
1319
|
}
|
|
1036
1320
|
for (const goal of config.goals) {
|
|
1037
|
-
if (goal.type === "pageview" && matchPath(goal, current)) {
|
|
1321
|
+
if (goal.type === "pageview" && goal.path && matchPath(goal.path, current)) {
|
|
1038
1322
|
debugLog("pageview", `${current} matches goal ${goal.key}`);
|
|
1039
1323
|
client.track(goal.key);
|
|
1040
1324
|
}
|
|
@@ -1059,6 +1343,8 @@ function createClient(config, options = {}) {
|
|
|
1059
1343
|
return () => target.removeEventListener("click", onClick, true);
|
|
1060
1344
|
},
|
|
1061
1345
|
flush: () => queue.flush(false),
|
|
1346
|
+
// Unbinds the page listeners; pending events are kept and a later event binds again,
|
|
1347
|
+
// so a provider may destroy on unmount even under StrictMode's double mount.
|
|
1062
1348
|
destroy: () => queue.destroy()
|
|
1063
1349
|
};
|
|
1064
1350
|
if (browser && isDebug()) {
|
|
@@ -1067,6 +1353,9 @@ function createClient(config, options = {}) {
|
|
|
1067
1353
|
}
|
|
1068
1354
|
return client;
|
|
1069
1355
|
}
|
|
1356
|
+
function stripUndefined(o) {
|
|
1357
|
+
return Object.fromEntries(Object.entries(o).filter(([, v]) => v !== void 0));
|
|
1358
|
+
}
|
|
1070
1359
|
function withTimeout(p, ms) {
|
|
1071
1360
|
return new Promise((resolve) => {
|
|
1072
1361
|
const t = setTimeout(() => resolve(null), ms);
|
|
@@ -1082,11 +1371,6 @@ function withTimeout(p, ms) {
|
|
|
1082
1371
|
);
|
|
1083
1372
|
});
|
|
1084
1373
|
}
|
|
1085
|
-
function matchPath(goal, path) {
|
|
1086
|
-
if (!goal.path) return false;
|
|
1087
|
-
if (goal.path.endsWith("*")) return path.startsWith(goal.path.slice(0, -1));
|
|
1088
|
-
return goal.path === path;
|
|
1089
|
-
}
|
|
1090
1374
|
var warned = /* @__PURE__ */ new Set();
|
|
1091
1375
|
function warn(message) {
|
|
1092
1376
|
if (warned.has(message)) return;
|
|
@@ -1109,6 +1393,8 @@ export {
|
|
|
1109
1393
|
runFlow,
|
|
1110
1394
|
validateFlow,
|
|
1111
1395
|
parseUserAgent,
|
|
1396
|
+
isBot,
|
|
1397
|
+
isCrawler,
|
|
1112
1398
|
parseCookies,
|
|
1113
1399
|
browserContext,
|
|
1114
1400
|
ConfigError,
|
|
@@ -1116,13 +1402,21 @@ export {
|
|
|
1116
1402
|
MVT_MAX_LEVELS,
|
|
1117
1403
|
MVT_MAX_COMBINATIONS,
|
|
1118
1404
|
mvtVariants,
|
|
1405
|
+
HOLDOUT_KEY,
|
|
1406
|
+
LAYER_BUCKETS,
|
|
1119
1407
|
defineConfig,
|
|
1120
1408
|
isSplitHubConfig,
|
|
1121
1409
|
getExperiment,
|
|
1410
|
+
holdoutExperiment,
|
|
1411
|
+
measuredGoals,
|
|
1122
1412
|
isDevEnvironment,
|
|
1123
1413
|
isDevDraft,
|
|
1124
1414
|
isActive,
|
|
1125
1415
|
pickVariant,
|
|
1416
|
+
holdoutGroup,
|
|
1417
|
+
layerBucket,
|
|
1418
|
+
inLayer,
|
|
1419
|
+
countsForHoldout,
|
|
1126
1420
|
assign,
|
|
1127
1421
|
inSchedule,
|
|
1128
1422
|
controlVariant,
|
|
@@ -1137,6 +1431,9 @@ export {
|
|
|
1137
1431
|
hasVisitorId,
|
|
1138
1432
|
getOrCreateVisitorId,
|
|
1139
1433
|
getOrCreateSessionId,
|
|
1434
|
+
normalizePath,
|
|
1435
|
+
matchPath,
|
|
1436
|
+
redirectTarget,
|
|
1140
1437
|
createFetchTransport,
|
|
1141
1438
|
EventQueue,
|
|
1142
1439
|
debugMode,
|
|
@@ -1156,4 +1453,4 @@ export {
|
|
|
1156
1453
|
CLOUD_ENDPOINT,
|
|
1157
1454
|
createClient
|
|
1158
1455
|
};
|
|
1159
|
-
//# sourceMappingURL=chunk-
|
|
1456
|
+
//# sourceMappingURL=chunk-X6QEO4I4.js.map
|