@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/index.cjs CHANGED
@@ -24,7 +24,9 @@ __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,
@@ -38,10 +40,12 @@ __export(index_exports, {
38
40
  browserContext: () => browserContext,
39
41
  contextValue: () => contextValue,
40
42
  controlVariant: () => controlVariant,
43
+ countsForHoldout: () => countsForHoldout,
41
44
  createClient: () => createClient,
42
45
  createFetchTransport: () => createFetchTransport,
43
46
  debugLog: () => debugLog,
44
47
  debugMode: () => debugMode,
48
+ decideRedirect: () => decideRedirect,
45
49
  defineConfig: () => defineConfig,
46
50
  devNote: () => devNote,
47
51
  evaluateCondition: () => evaluateCondition,
@@ -52,26 +56,36 @@ __export(index_exports, {
52
56
  getOrCreateVisitorId: () => getOrCreateVisitorId,
53
57
  hasVisitorId: () => hasVisitorId,
54
58
  hashToUnit: () => hashToUnit,
59
+ holdoutExperiment: () => holdoutExperiment,
60
+ holdoutGroup: () => holdoutGroup,
61
+ inLayer: () => inLayer,
55
62
  inSchedule: () => inSchedule,
56
63
  isActive: () => isActive,
64
+ isBot: () => isBot,
57
65
  isBrowser: () => isBrowser,
66
+ isCrawler: () => isCrawler,
58
67
  isDebug: () => isDebug,
59
68
  isDevDraft: () => isDevDraft,
60
69
  isDevEnvironment: () => isDevEnvironment,
61
70
  isRemoteOverrides: () => isRemoteOverrides,
62
71
  isSplitHubConfig: () => isSplitHubConfig,
72
+ layerBucket: () => layerBucket,
63
73
  matchConditions: () => matchConditions,
74
+ matchPath: () => matchPath,
75
+ measuredGoals: () => measuredGoals,
64
76
  murmur3: () => murmur3,
65
77
  mvtVariants: () => mvtVariants,
66
78
  newId: () => newId,
67
79
  newSessionId: () => newSessionId,
68
80
  newVisitorId: () => newVisitorId,
81
+ normalizePath: () => normalizePath,
69
82
  onDebug: () => onDebug,
70
83
  parseCookies: () => parseCookies,
71
84
  parseForceParam: () => parseForceParam,
72
85
  parseUserAgent: () => parseUserAgent,
73
86
  pickVariant: () => pickVariant,
74
87
  readRemoteCache: () => readRemoteCache,
88
+ redirectTarget: () => redirectTarget,
75
89
  resetDevNotes: () => resetDevNotes,
76
90
  resolveOverridesUrl: () => resolveOverridesUrl,
77
91
  runFlow: () => runFlow,
@@ -145,6 +159,28 @@ var TARGET_FIELDS = ["country", "region", "city", "device", "browser", "os", "la
145
159
  var TARGET_OPS = ["is", "is_not", "contains", "not_contains", "starts_with", "in", "not_in", "matches", "exists", "not_exists"];
146
160
  var KEYED_FIELDS = ["query", "cookie"];
147
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
+ }
148
184
  function queryParam(url, name) {
149
185
  if (!url) return void 0;
150
186
  const q = url.indexOf("?");
@@ -194,16 +230,12 @@ function contextValue(field, key, ctx) {
194
230
  case "cookie":
195
231
  v = key ? ctx.cookies?.[key] : void 0;
196
232
  break;
197
- case "hour": {
198
- const d = ctx.now ? new Date(ctx.now) : /* @__PURE__ */ new Date();
199
- v = d.getUTCHours();
233
+ case "hour":
234
+ v = localClock(ctx).hour;
200
235
  break;
201
- }
202
- case "weekday": {
203
- const d = ctx.now ? new Date(ctx.now) : /* @__PURE__ */ new Date();
204
- v = ["sun", "mon", "tue", "wed", "thu", "fri", "sat"][d.getUTCDay()];
236
+ case "weekday":
237
+ v = WEEKDAYS[localClock(ctx).weekday];
205
238
  break;
206
- }
207
239
  }
208
240
  return v === void 0 || v === null ? void 0 : String(v).toLowerCase();
209
241
  }
@@ -338,13 +370,21 @@ function validateFlow(flow, variantKeys) {
338
370
  }
339
371
  return null;
340
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;
341
374
  function parseUserAgent(ua) {
342
375
  const s = ua ?? "";
343
- const device = /bot|crawl|spider|slurp|headless/i.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";
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";
344
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";
345
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";
346
379
  return { device, browser, os };
347
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
+ }
348
388
  function parseCookies(header) {
349
389
  const out = {};
350
390
  for (const part of (header ?? "").split(";")) {
@@ -371,9 +411,17 @@ function browserContext(extra = {}) {
371
411
  referrer: typeof document !== "undefined" ? document.referrer || void 0 : void 0,
372
412
  url: location.href,
373
413
  cookies: typeof document !== "undefined" ? parseCookies(document.cookie) : {},
414
+ timezone: deviceTimezone(),
374
415
  ...extra
375
416
  };
376
417
  }
418
+ function deviceTimezone() {
419
+ try {
420
+ return Intl.DateTimeFormat().resolvedOptions().timeZone || void 0;
421
+ } catch {
422
+ return void 0;
423
+ }
424
+ }
377
425
 
378
426
  // src/config.ts
379
427
  var KEY_PATTERN = /^[a-z0-9][a-z0-9_-]{0,63}$/;
@@ -442,7 +490,60 @@ function normalizeVariants(expKey, input) {
442
490
  }
443
491
  return raw.map((v) => ({ ...v, weight: v.weight / total }));
444
492
  }
445
- function normalizeExperiment(key, input, goals) {
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 = {}) {
446
547
  assertKey("experiment", key);
447
548
  const traffic = input.traffic ?? 1;
448
549
  if (traffic < 0 || traffic > 1) {
@@ -457,10 +558,18 @@ function normalizeExperiment(key, input, goals) {
457
558
  if (input.maxExposures !== void 0 && (!Number.isFinite(input.maxExposures) || input.maxExposures < 1)) {
458
559
  throw new ConfigError(`experiment "${key}": maxExposures must be a positive number.`);
459
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
+ }
564
+ if (input.goodSample !== void 0 && !(Number.isInteger(input.goodSample) && input.goodSample >= 100 && input.goodSample <= 1e7)) {
565
+ throw new ConfigError(`experiment "${key}": goodSample must be a whole number from 100 to 10,000,000.`);
566
+ }
460
567
  for (const [k, v] of Object.entries(input.schedule ?? {})) {
461
568
  if (v !== void 0 && Number.isNaN(Date.parse(v))) throw new ConfigError(`experiment "${key}": schedule.${k} must be an ISO date.`);
462
569
  }
463
570
  const variants = normalizeVariants(key, input);
571
+ const metrics = normalizeMetrics(key, input, goals);
572
+ const layer = normalizeLayer(key, input, layers);
464
573
  if (input.flow) {
465
574
  const problem = validateFlow(input.flow, variants.map((v) => v.key));
466
575
  if (problem) throw new ConfigError(`experiment "${key}": flow: ${problem}`);
@@ -477,6 +586,10 @@ function normalizeExperiment(key, input, goals) {
477
586
  variants,
478
587
  ...input.kind === "mvt" ? { factors: mvtVariants(key, input.factors).factors } : {},
479
588
  ...input.flow ? { flow: input.flow } : {},
589
+ ...metrics ? { metrics } : {},
590
+ ...layer ? { layer } : {},
591
+ ...input.minDays !== void 0 ? { minDays: input.minDays } : {},
592
+ ...input.goodSample !== void 0 ? { goodSample: input.goodSample } : {},
480
593
  ...input.maxExposures ? { maxExposures: Math.floor(input.maxExposures) } : {},
481
594
  ...input.schedule && (input.schedule.startAt || input.schedule.endAt) ? { schedule: { startAt: input.schedule.startAt ?? null, endAt: input.schedule.endAt ?? null } } : {}
482
595
  };
@@ -499,9 +612,16 @@ function defineConfig(input) {
499
612
  description: g.description ?? null
500
613
  };
501
614
  });
615
+ const layers = {};
616
+ for (const [key, l] of Object.entries(input.layers ?? {})) {
617
+ assertKey("layer", key);
618
+ layers[key] = { seed: l?.seed ?? key };
619
+ }
502
620
  const experiments = Object.entries(input.experiments ?? {}).map(
503
- ([key, exp]) => normalizeExperiment(key, exp, goals)
621
+ ([key, exp]) => normalizeExperiment(key, exp, goals, layers)
504
622
  );
623
+ assertNoOverlap(experiments);
624
+ const holdout = normalizeHoldout(input, goals);
505
625
  return {
506
626
  project: input.project,
507
627
  storage: input.storage,
@@ -509,6 +629,8 @@ function defineConfig(input) {
509
629
  runDraftsInDev: input.runDraftsInDev === true,
510
630
  goals,
511
631
  experiments,
632
+ ...Object.keys(layers).length ? { layers } : {},
633
+ ...holdout ? { holdout } : {},
512
634
  __splithub: 2
513
635
  };
514
636
  }
@@ -518,6 +640,40 @@ function isSplitHubConfig(value) {
518
640
  function getExperiment(config, key) {
519
641
  return config.experiments.find((e) => e.key === key);
520
642
  }
643
+ function holdoutExperiment(config) {
644
+ const h = config.holdout;
645
+ if (!h) return null;
646
+ const share = h.percent / 100;
647
+ const secondary = config.goals.map((g) => g.key).filter((g) => g !== h.goal);
648
+ return {
649
+ key: HOLDOUT_KEY,
650
+ kind: "component",
651
+ status: "running",
652
+ traffic: 1,
653
+ goal: h.goal,
654
+ seed: h.seed,
655
+ description: `Holdout: ${h.percent}% of visitors see no test at all`,
656
+ match: null,
657
+ variants: [
658
+ { key: "holdout", weight: share },
659
+ { key: "enrolled", weight: 1 - share }
660
+ ],
661
+ ...h.goal && secondary.length ? { metrics: { secondary, guardrails: [] } } : {}
662
+ };
663
+ }
664
+ function measuredGoals(config) {
665
+ const goals = {};
666
+ const metrics = {};
667
+ const all = [...config.experiments];
668
+ const h = holdoutExperiment(config);
669
+ if (h) all.push(h);
670
+ for (const e of all) {
671
+ goals[e.key] = e.goal ?? null;
672
+ const extra = [...e.metrics?.secondary ?? [], ...(e.metrics?.guardrails ?? []).map((g) => g.goal)];
673
+ if (extra.length) metrics[e.key] = extra;
674
+ }
675
+ return { goals, metrics };
676
+ }
521
677
 
522
678
  // src/assignment.ts
523
679
  function isDevEnvironment() {
@@ -544,6 +700,24 @@ function pickVariant(experiment, visitorId) {
544
700
  }
545
701
  return experiment.variants[experiment.variants.length - 1] ?? null;
546
702
  }
703
+ function holdoutGroup(config, visitorId) {
704
+ const h = config.holdout;
705
+ if (!h || !(h.percent > 0)) return null;
706
+ return hashToUnit(`${h.seed}:${HOLDOUT_KEY}:${visitorId}`) < h.percent / 100 ? "holdout" : "enrolled";
707
+ }
708
+ function layerBucket(config, layerKey, visitorId) {
709
+ const seed = config.layers?.[layerKey]?.seed ?? layerKey;
710
+ return Math.min(LAYER_BUCKETS - 1, Math.floor(hashToUnit(`${seed}:layer:${layerKey}:${visitorId}`) * LAYER_BUCKETS));
711
+ }
712
+ function inLayer(config, experiment, visitorId) {
713
+ const l = experiment.layer;
714
+ if (!l) return true;
715
+ const b = layerBucket(config, l.key, visitorId);
716
+ return b >= l.range[0] && b < l.range[1];
717
+ }
718
+ function countsForHoldout(a) {
719
+ return a.reason === "assigned" || a.reason === "holdout" || a.reason === "outside_traffic" || a.reason === "targeting" || a.reason === "layer";
720
+ }
547
721
  function assign(config, experimentKey, visitorId, options = {}) {
548
722
  const experiment = config.experiments.find((e) => e.key === experimentKey);
549
723
  if (!experiment) return { experiment: experimentKey, variant: null, reason: "unknown_experiment" };
@@ -552,10 +726,13 @@ function assign(config, experimentKey, visitorId, options = {}) {
552
726
  const variant2 = experiment.variants.find((v) => v.key === forced) ?? null;
553
727
  if (variant2) return { experiment: experimentKey, variant: variant2, reason: "override" };
554
728
  }
729
+ if (options.context?.device === "bot") return { experiment: experimentKey, variant: null, reason: "bot" };
555
730
  const devDraft = isDevDraft(config, experiment);
556
731
  if (!devDraft && (experiment.status !== "running" || !inSchedule(experiment, options.context?.now))) {
557
732
  return { experiment: experimentKey, variant: null, reason: "not_running" };
558
733
  }
734
+ if (holdoutGroup(config, visitorId) === "holdout") return { experiment: experimentKey, variant: null, reason: "holdout" };
735
+ if (!inLayer(config, experiment, visitorId)) return { experiment: experimentKey, variant: null, reason: "layer" };
559
736
  const reason = devDraft ? "dev" : "assigned";
560
737
  if (experiment.flow) {
561
738
  const trafficUnit = hashToUnit(`${experiment.seed}:${experiment.key}:traffic:${visitorId}`);
@@ -581,7 +758,13 @@ function parseForceParam(search) {
581
758
  const out = {};
582
759
  const match = /[?&]sh_force=([^&]+)/.exec(search);
583
760
  if (!match || !match[1]) return out;
584
- for (const pair of decodeURIComponent(match[1]).split(",")) {
761
+ let raw;
762
+ try {
763
+ raw = decodeURIComponent(match[1]);
764
+ } catch {
765
+ return out;
766
+ }
767
+ for (const pair of raw.split(",")) {
585
768
  const [exp, variant] = pair.split(":");
586
769
  if (exp && variant) out[exp] = variant;
587
770
  }
@@ -612,6 +795,14 @@ function explainAssignment(experiment, a) {
612
795
  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}`);
613
796
  return;
614
797
  }
798
+ if (a.reason === "holdout") {
799
+ 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.`);
800
+ return;
801
+ }
802
+ if (a.reason === "layer") {
803
+ 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.`);
804
+ return;
805
+ }
615
806
  if (a.reason !== "not_running") return;
616
807
  const second = experiment.variants[1]?.key ?? "variant";
617
808
  if (experiment.status === "draft") {
@@ -707,14 +898,65 @@ function persistExposureSet(set, key = "sh_exposed") {
707
898
  safeStorage("sessionStorage")?.setItem(key, JSON.stringify([...set]));
708
899
  }
709
900
 
901
+ // src/paths.ts
902
+ function normalizePath(path) {
903
+ return path.length > 1 && path.endsWith("/") ? path.replace(/\/+$/, "") || "/" : path;
904
+ }
905
+ function matchPath(pattern, pathname) {
906
+ if (pattern.endsWith("*")) return pathname.startsWith(pattern.slice(0, -1));
907
+ return normalizePath(pattern) === normalizePath(pathname);
908
+ }
909
+ function redirectTarget(to, currentHref) {
910
+ const current = new URL(currentHref);
911
+ const target = new URL(to, current);
912
+ const own = new Set(target.searchParams.keys());
913
+ current.searchParams.forEach((value, key) => {
914
+ if (!own.has(key)) target.searchParams.append(key, value);
915
+ });
916
+ if (!target.hash) target.hash = current.hash;
917
+ return target;
918
+ }
919
+
920
+ // src/redirect.ts
921
+ function decideRedirect(config, pathname, visitorId, context = {}, overrides = {}, explain) {
922
+ for (const exp of config.experiments) {
923
+ if (exp.kind !== "redirect" || !exp.match || !matchPath(exp.match, pathname)) continue;
924
+ if (!isActive(config, exp, context.now)) {
925
+ explain?.(exp, { experiment: exp.key, variant: null, reason: "not_running" });
926
+ continue;
927
+ }
928
+ const a = assign(config, exp.key, visitorId, { overrides, context });
929
+ explain?.(exp, a);
930
+ if (!a.variant) continue;
931
+ const to = a.variant.to || null;
932
+ const stays = !to || normalizePath(to.split(/[?#]/)[0] ?? "") === normalizePath(pathname);
933
+ return { experiment: exp.key, variant: a.variant.key, to: stays ? null : to, reason: a.reason };
934
+ }
935
+ return null;
936
+ }
937
+
710
938
  // src/events.ts
939
+ function beaconUrl(options) {
940
+ if (!options.key) return options.endpoint;
941
+ if (!options.keyInQuery) return null;
942
+ return `${options.endpoint}${options.endpoint.includes("?") ? "&" : "?"}key=${encodeURIComponent(options.key)}`;
943
+ }
711
944
  function createFetchTransport(options) {
712
945
  return {
713
946
  async send(batch, { beacon }) {
714
947
  const body = JSON.stringify(batch);
715
- if (beacon && isBrowser() && typeof navigator.sendBeacon === "function" && !options.key) {
716
- const blob = new Blob([body], { type: "application/json" });
717
- if (navigator.sendBeacon(options.endpoint, blob)) return;
948
+ const url = beacon && isBrowser() && typeof navigator.sendBeacon === "function" ? beaconUrl(options) : null;
949
+ if (url) {
950
+ let sameOrigin = false;
951
+ try {
952
+ sameOrigin = new URL(url, location.href).origin === location.origin;
953
+ } catch {
954
+ }
955
+ const blob = new Blob([body], { type: sameOrigin ? "application/json" : "text/plain;charset=UTF-8" });
956
+ try {
957
+ if (navigator.sendBeacon(url, blob)) return;
958
+ } catch {
959
+ }
718
960
  }
719
961
  const headers = { "content-type": "application/json" };
720
962
  if (options.key) headers.authorization = `Bearer ${options.key}`;
@@ -727,37 +969,61 @@ function createFetchTransport(options) {
727
969
  }
728
970
  };
729
971
  }
972
+ var MAX_BACKOFF_MS = 3e4;
730
973
  var EventQueue = class {
731
974
  constructor(options) {
732
975
  this.options = options;
733
976
  this.pending = [];
734
977
  this.retry = [];
978
+ this.attempts = 0;
735
979
  this.timer = null;
980
+ this.backoffUntil = 0;
736
981
  this.unbind = null;
737
982
  this.maxBatch = options.maxBatch ?? 20;
738
983
  this.flushInterval = options.flushInterval ?? 2e3;
739
- if (isBrowser()) {
740
- const onHide = () => {
741
- if (document.visibilityState === "hidden") void this.flush(true);
742
- };
743
- document.addEventListener("visibilitychange", onHide);
744
- window.addEventListener("pagehide", () => void this.flush(true));
745
- this.unbind = () => document.removeEventListener("visibilitychange", onHide);
746
- }
984
+ this.maxQueue = options.maxQueue ?? 200;
985
+ this.maxAttempts = options.maxAttempts ?? 5;
986
+ }
987
+ bind() {
988
+ if (this.unbind || !isBrowser()) return;
989
+ const onHidden = () => {
990
+ if (document.visibilityState === "hidden") void this.flush(true);
991
+ };
992
+ const onPageHide = () => void this.flush(true);
993
+ document.addEventListener("visibilitychange", onHidden);
994
+ window.addEventListener("pagehide", onPageHide);
995
+ this.unbind = () => {
996
+ document.removeEventListener("visibilitychange", onHidden);
997
+ window.removeEventListener("pagehide", onPageHide);
998
+ };
999
+ }
1000
+ schedule(delay) {
1001
+ if (this.timer) return;
1002
+ this.timer = setTimeout(() => {
1003
+ this.timer = null;
1004
+ void this.flush(false);
1005
+ }, delay);
747
1006
  }
748
1007
  push(event) {
1008
+ this.bind();
749
1009
  this.pending.push(event);
750
- if (this.pending.length >= this.maxBatch) {
1010
+ const overflow = this.size - this.maxQueue;
1011
+ if (overflow > 0) {
1012
+ const fromRetry = Math.min(overflow, this.retry.length);
1013
+ this.retry.splice(0, fromRetry);
1014
+ this.pending.splice(0, overflow - fromRetry);
1015
+ }
1016
+ const waiting = Date.now() < this.backoffUntil;
1017
+ if (!waiting && this.pending.length >= this.maxBatch) {
751
1018
  void this.flush(false);
752
1019
  return;
753
1020
  }
754
- if (!this.timer) {
755
- this.timer = setTimeout(() => void this.flush(false), this.flushInterval);
756
- }
1021
+ this.schedule(waiting ? this.backoffUntil - Date.now() : this.flushInterval);
757
1022
  }
758
1023
  get size() {
759
1024
  return this.pending.length + this.retry.length;
760
1025
  }
1026
+ /** Send everything now. `beacon` is for page hide: it ignores the backoff, since the page is going away. */
761
1027
  async flush(beacon = false) {
762
1028
  if (this.timer) {
763
1029
  clearTimeout(this.timer);
@@ -770,15 +1036,31 @@ var EventQueue = class {
770
1036
  const batch = { project: this.options.project, sdk: this.options.sdk, events };
771
1037
  try {
772
1038
  await this.options.transport.send(batch, { beacon });
1039
+ this.attempts = 0;
1040
+ this.backoffUntil = 0;
773
1041
  } catch (error) {
774
1042
  const status = error.status;
775
- if (!(status && status >= 400 && status < 500)) this.retry = events.slice(-200);
1043
+ const refused = status !== void 0 && status >= 400 && status < 500 && status !== 408 && status !== 429;
1044
+ this.attempts += 1;
1045
+ if (!refused && this.attempts < this.maxAttempts) {
1046
+ this.retry = events.slice(-this.maxQueue);
1047
+ const base = Math.min(MAX_BACKOFF_MS, 1e3 * 2 ** (this.attempts - 1));
1048
+ const delay = Math.round(base / 2 + Math.random() * (base / 2));
1049
+ this.backoffUntil = Date.now() + delay;
1050
+ this.schedule(delay);
1051
+ } else {
1052
+ this.attempts = 0;
1053
+ this.backoffUntil = 0;
1054
+ }
776
1055
  this.options.onError?.(error);
777
1056
  }
778
1057
  }
1058
+ /** Stop the timer and the page listeners. Pending events stay; a later `push` binds again. */
779
1059
  destroy() {
780
1060
  this.unbind?.();
1061
+ this.unbind = null;
781
1062
  if (this.timer) clearTimeout(this.timer);
1063
+ this.timer = null;
782
1064
  }
783
1065
  };
784
1066
 
@@ -861,10 +1143,14 @@ function applyRemoteOverrides(config, overrides) {
861
1143
  const added = (overrides.added ?? []).filter((e) => e && typeof e.key === "string" && !known.has(e.key) && Array.isArray(e.variants) && e.variants.length >= 2);
862
1144
  const knownGoals = new Set(config.goals.map((g) => g.key));
863
1145
  const addedGoals = (overrides.goals ?? []).filter((g) => g && typeof g.key === "string" && !knownGoals.has(g.key));
864
- if (Object.keys(patches).length === 0 && added.length === 0 && addedGoals.length === 0) return config;
1146
+ const holdout = !config.holdout && validHoldout(overrides.holdout) ? overrides.holdout : null;
1147
+ const layers = overrides.layers && typeof overrides.layers === "object" ? { ...overrides.layers, ...config.layers ?? {} } : null;
1148
+ if (Object.keys(patches).length === 0 && added.length === 0 && addedGoals.length === 0 && !holdout && !layers) return config;
865
1149
  const merged = [...config.experiments, ...added.map((e) => ({ ...e, origin: "dashboard" }))];
866
1150
  return {
867
1151
  ...config,
1152
+ ...holdout ? { holdout } : {},
1153
+ ...layers ? { layers } : {},
868
1154
  goals: addedGoals.length ? [...config.goals, ...addedGoals] : config.goals,
869
1155
  experiments: merged.map((e) => {
870
1156
  const o = patches[e.key];
@@ -872,6 +1158,9 @@ function applyRemoteOverrides(config, overrides) {
872
1158
  })
873
1159
  };
874
1160
  }
1161
+ function validHoldout(h) {
1162
+ return Boolean(h) && typeof h.percent === "number" && h.percent > 0 && h.percent <= 50 && typeof h.seed === "string";
1163
+ }
875
1164
  function isRemoteOverrides(value) {
876
1165
  return Boolean(value) && typeof value === "object" && typeof value.version === "number" && typeof value.experiments === "object";
877
1166
  }
@@ -964,9 +1253,15 @@ function createClient(config, options = {}) {
964
1253
  config = effective;
965
1254
  const hadVisitor = browser && !options.visitorId ? hasVisitorId(config.visitorKey) : void 0;
966
1255
  const visitorId = options.visitorId ?? (browser ? getOrCreateVisitorId(config.visitorKey) : "server");
1256
+ const noVisitor = !browser && !options.visitorId;
967
1257
  const sessionId = options.sessionId ?? (browser ? getOrCreateSessionId() : "server");
968
- const contextFor = (g) => browser ? browserContext({ ...g ?? {}, ...hadVisitor === void 0 ? {} : { visitor: hadVisitor ? "returning" : "new" }, ...options.context ?? {} }) : { ...g ?? {}, ...options.context ?? {} };
1258
+ const contextFor = (g) => {
1259
+ if (!browser) return { ...g ?? {}, ...options.context ?? {} };
1260
+ const forPage = g?.timezone ? { ...g, timezone: void 0 } : g;
1261
+ return browserContext({ ...stripUndefined(forPage ?? {}), ...hadVisitor === void 0 ? {} : { visitor: hadVisitor ? "returning" : "new" }, ...options.context ?? {} });
1262
+ };
969
1263
  let context = contextFor(geo);
1264
+ const isBot2 = () => context.device === "bot";
970
1265
  const overrides = {
971
1266
  ...browser ? parseForceParam(location.search) : {},
972
1267
  ...options.overrides ?? {}
@@ -981,7 +1276,10 @@ function createClient(config, options = {}) {
981
1276
  held.add(key);
982
1277
  debugLog(kind, message);
983
1278
  };
984
- const transport = options.transport ?? createFetchTransport(resolveEndpoint(config));
1279
+ const transport = options.transport ?? createFetchTransport({
1280
+ ...resolveEndpoint(config),
1281
+ keyInQuery: options.keyInQuery ?? (config.storage.mode === "cloud" && !config.storage.endpoint)
1282
+ });
985
1283
  const queue = new EventQueue({
986
1284
  project: config.project,
987
1285
  sdk: `core/${SDK_VERSION}`,
@@ -990,13 +1288,29 @@ function createClient(config, options = {}) {
990
1288
  });
991
1289
  const exposed = browser ? sessionExposureSet() : /* @__PURE__ */ new Set();
992
1290
  const currentUrl = () => browser ? location.pathname + location.search : void 0;
1291
+ const markHoldout = (ts) => {
1292
+ const group = holdoutGroup(config, visitorId);
1293
+ if (!group || noVisitor) return;
1294
+ const dedupKey = `${HOLDOUT_KEY}:${group}`;
1295
+ if (exposed.has(dedupKey)) return;
1296
+ if (devLocal) {
1297
+ hold(`x:${HOLDOUT_KEY}`, "exposure", `${HOLDOUT_KEY} / ${group} not sent: development never sends to the cloud`);
1298
+ return;
1299
+ }
1300
+ exposed.add(dedupKey);
1301
+ if (browser) persistExposureSet(exposed);
1302
+ const event = { id: newId("e_"), type: "exposure", exp: HOLDOUT_KEY, var: group, vid: visitorId, sid: sessionId, ts, url: currentUrl() };
1303
+ debugLog("exposure", `${HOLDOUT_KEY} / ${group} recorded`, event);
1304
+ queue.push(event);
1305
+ };
993
1306
  let pending = waitFor !== null;
994
1307
  const waiting = [];
995
1308
  const listeners = /* @__PURE__ */ new Set();
996
1309
  const sendExposure = (experimentKey, ts) => {
997
1310
  const a = client.assignment(experimentKey);
1311
+ if (config.holdout && countsForHoldout(a)) markHoldout(ts);
998
1312
  if (!a.variant || a.reason === "override") return;
999
- if (devLocal) {
1313
+ if (typeof __SPLITHUB_LITE__ === "undefined" && devLocal) {
1000
1314
  devNote("dev-events", DEV_NOTE);
1001
1315
  hold(`x:${experimentKey}`, "exposure", `${experimentKey} / ${a.variant.key} not sent: development never sends to the cloud`);
1002
1316
  return;
@@ -1010,10 +1324,11 @@ function createClient(config, options = {}) {
1010
1324
  queue.push(event);
1011
1325
  };
1012
1326
  const sendGoal = (goal, props, ts) => {
1327
+ if (isBot2()) return;
1013
1328
  if (!config.goals.some((g) => g.key === goal)) {
1014
1329
  warn(`goal "${goal}" is not declared in splithub.config.ts; sending anyway.`);
1015
1330
  }
1016
- if (devLocal) {
1331
+ if (typeof __SPLITHUB_LITE__ === "undefined" && devLocal) {
1017
1332
  devNote("dev-events", DEV_NOTE);
1018
1333
  hold(`g:${goal}`, "goal", `${goal} not sent: development never sends to the cloud`);
1019
1334
  return;
@@ -1062,8 +1377,9 @@ function createClient(config, options = {}) {
1062
1377
  },
1063
1378
  assignment(experimentKey) {
1064
1379
  if (pending) return { experiment: experimentKey, variant: null, reason: "pending" };
1065
- const a = assign(config, experimentKey, visitorId, { overrides, context });
1066
- explainAssignment(getExperiment(config, experimentKey), a);
1380
+ let a = assign(config, experimentKey, visitorId, { overrides, context });
1381
+ if (noVisitor && a.variant && a.reason !== "override") a = { experiment: experimentKey, variant: null, reason: "no_visitor" };
1382
+ if (typeof __SPLITHUB_LITE__ === "undefined") explainAssignment(getExperiment(config, experimentKey), a);
1067
1383
  if (isDebug() && !decided.has(experimentKey)) {
1068
1384
  decided.add(experimentKey);
1069
1385
  const exp = getExperiment(config, experimentKey);
@@ -1100,7 +1416,7 @@ function createClient(config, options = {}) {
1100
1416
  return (a.variant ?? experiment.variants[0]).value;
1101
1417
  },
1102
1418
  track(goal, props) {
1103
- if (disabled) return;
1419
+ if (disabled || isBot2()) return;
1104
1420
  if (pending) waiting.push({ goal, ...props ? { props } : {}, ts: Date.now() });
1105
1421
  else sendGoal(goal, props, Date.now());
1106
1422
  },
@@ -1111,12 +1427,12 @@ function createClient(config, options = {}) {
1111
1427
  const ts = Date.now();
1112
1428
  void ready.then(() => {
1113
1429
  if (disabled) return;
1114
- for (const goal of config.goals) if (goal.type === "pageview" && matchPath(goal, current)) sendGoal(goal.key, void 0, ts);
1430
+ for (const goal of config.goals) if (goal.type === "pageview" && goal.path && matchPath(goal.path, current)) sendGoal(goal.key, void 0, ts);
1115
1431
  });
1116
1432
  return;
1117
1433
  }
1118
1434
  for (const goal of config.goals) {
1119
- if (goal.type === "pageview" && matchPath(goal, current)) {
1435
+ if (goal.type === "pageview" && goal.path && matchPath(goal.path, current)) {
1120
1436
  debugLog("pageview", `${current} matches goal ${goal.key}`);
1121
1437
  client.track(goal.key);
1122
1438
  }
@@ -1141,6 +1457,8 @@ function createClient(config, options = {}) {
1141
1457
  return () => target.removeEventListener("click", onClick, true);
1142
1458
  },
1143
1459
  flush: () => queue.flush(false),
1460
+ // Unbinds the page listeners; pending events are kept and a later event binds again,
1461
+ // so a provider may destroy on unmount even under StrictMode's double mount.
1144
1462
  destroy: () => queue.destroy()
1145
1463
  };
1146
1464
  if (browser && isDebug()) {
@@ -1149,6 +1467,9 @@ function createClient(config, options = {}) {
1149
1467
  }
1150
1468
  return client;
1151
1469
  }
1470
+ function stripUndefined(o) {
1471
+ return Object.fromEntries(Object.entries(o).filter(([, v]) => v !== void 0));
1472
+ }
1152
1473
  function withTimeout(p, ms) {
1153
1474
  return new Promise((resolve) => {
1154
1475
  const t = setTimeout(() => resolve(null), ms);
@@ -1164,11 +1485,6 @@ function withTimeout(p, ms) {
1164
1485
  );
1165
1486
  });
1166
1487
  }
1167
- function matchPath(goal, path) {
1168
- if (!goal.path) return false;
1169
- if (goal.path.endsWith("*")) return path.startsWith(goal.path.slice(0, -1));
1170
- return goal.path === path;
1171
- }
1172
1488
  var warned = /* @__PURE__ */ new Set();
1173
1489
  function warn(message) {
1174
1490
  if (warned.has(message)) return;
@@ -1184,7 +1500,9 @@ function warnUnknown(key) {
1184
1500
  ConfigError,
1185
1501
  EMPTY_OVERRIDES,
1186
1502
  EventQueue,
1503
+ HOLDOUT_KEY,
1187
1504
  KEYED_FIELDS,
1505
+ LAYER_BUCKETS,
1188
1506
  MVT_MAX_COMBINATIONS,
1189
1507
  MVT_MAX_FACTORS,
1190
1508
  MVT_MAX_LEVELS,
@@ -1198,10 +1516,12 @@ function warnUnknown(key) {
1198
1516
  browserContext,
1199
1517
  contextValue,
1200
1518
  controlVariant,
1519
+ countsForHoldout,
1201
1520
  createClient,
1202
1521
  createFetchTransport,
1203
1522
  debugLog,
1204
1523
  debugMode,
1524
+ decideRedirect,
1205
1525
  defineConfig,
1206
1526
  devNote,
1207
1527
  evaluateCondition,
@@ -1212,26 +1532,36 @@ function warnUnknown(key) {
1212
1532
  getOrCreateVisitorId,
1213
1533
  hasVisitorId,
1214
1534
  hashToUnit,
1535
+ holdoutExperiment,
1536
+ holdoutGroup,
1537
+ inLayer,
1215
1538
  inSchedule,
1216
1539
  isActive,
1540
+ isBot,
1217
1541
  isBrowser,
1542
+ isCrawler,
1218
1543
  isDebug,
1219
1544
  isDevDraft,
1220
1545
  isDevEnvironment,
1221
1546
  isRemoteOverrides,
1222
1547
  isSplitHubConfig,
1548
+ layerBucket,
1223
1549
  matchConditions,
1550
+ matchPath,
1551
+ measuredGoals,
1224
1552
  murmur3,
1225
1553
  mvtVariants,
1226
1554
  newId,
1227
1555
  newSessionId,
1228
1556
  newVisitorId,
1557
+ normalizePath,
1229
1558
  onDebug,
1230
1559
  parseCookies,
1231
1560
  parseForceParam,
1232
1561
  parseUserAgent,
1233
1562
  pickVariant,
1234
1563
  readRemoteCache,
1564
+ redirectTarget,
1235
1565
  resetDevNotes,
1236
1566
  resolveOverridesUrl,
1237
1567
  runFlow,