@splithub/core 0.2.3 → 0.4.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.
@@ -396,13 +396,13 @@ function normalizeVariants(expKey, input) {
396
396
  }
397
397
  var HOLDOUT_KEY = "__holdout";
398
398
  var LAYER_BUCKETS = 100;
399
- function normalizeMetrics(key, input, goals) {
399
+ function normalizeMetrics(key, input, primary, goals) {
400
400
  const m = input.metrics;
401
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".`);
402
+ if (!primary) throw new ConfigError(`experiment "${key}": metrics need a primary "goal" too.`);
403
+ const seen = /* @__PURE__ */ new Set([primary]);
404
+ const check = (name, where) => {
405
+ const goal = goalFor(name, goals, `experiment "${key}": metrics.${where}`);
406
406
  if (seen.has(goal)) throw new ConfigError(`experiment "${key}": goal "${goal}" is listed twice (primary goal and metrics count once each).`);
407
407
  seen.add(goal);
408
408
  return goal;
@@ -443,9 +443,9 @@ function normalizeHoldout(input, goals) {
443
443
  const h = input.holdout;
444
444
  if (!h) return null;
445
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".`);
446
+ const goal = h.goal ? goalFor(h.goal, goals, "holdout.goal") : null;
447
447
  if (h.percent === 0) return null;
448
- return { percent: h.percent, seed: h.seed ?? HOLDOUT_KEY, goal: h.goal ?? goals[0]?.key ?? null };
448
+ return { percent: h.percent, seed: h.seed ?? HOLDOUT_KEY, goal: goal ?? goals[0]?.key ?? null };
449
449
  }
450
450
  function normalizeExperiment(key, input, goals, layers = {}) {
451
451
  assertKey("experiment", key);
@@ -453,9 +453,7 @@ function normalizeExperiment(key, input, goals, layers = {}) {
453
453
  if (traffic < 0 || traffic > 1) {
454
454
  throw new ConfigError(`experiment "${key}": traffic must be between 0 and 1.`);
455
455
  }
456
- if (input.goal && !goals.some((g) => g.key === input.goal)) {
457
- throw new ConfigError(`experiment "${key}": goal "${input.goal}" is not declared in "goals".`);
458
- }
456
+ const goal = input.goal ? goalFor(input.goal, goals, `experiment "${key}"`) : null;
459
457
  if (input.kind === "redirect" && !input.match) {
460
458
  throw new ConfigError(`experiment "${key}": redirect experiments need "match".`);
461
459
  }
@@ -468,11 +466,14 @@ function normalizeExperiment(key, input, goals, layers = {}) {
468
466
  if (input.goodSample !== void 0 && !(Number.isInteger(input.goodSample) && input.goodSample >= 100 && input.goodSample <= 1e7)) {
469
467
  throw new ConfigError(`experiment "${key}": goodSample must be a whole number from 100 to 10,000,000.`);
470
468
  }
469
+ if (input.name !== void 0 && !(typeof input.name === "string" && input.name.trim() && input.name.trim().length <= 80)) {
470
+ throw new ConfigError(`experiment "${key}": name must be text of 1 to 80 characters.`);
471
+ }
471
472
  for (const [k, v] of Object.entries(input.schedule ?? {})) {
472
473
  if (v !== void 0 && Number.isNaN(Date.parse(v))) throw new ConfigError(`experiment "${key}": schedule.${k} must be an ISO date.`);
473
474
  }
474
475
  const variants = normalizeVariants(key, input);
475
- const metrics = normalizeMetrics(key, input, goals);
476
+ const metrics = normalizeMetrics(key, input, goal, goals);
476
477
  const layer = normalizeLayer(key, input, layers);
477
478
  if (input.flow) {
478
479
  const problem = validateFlow(input.flow, variants.map((v) => v.key));
@@ -483,9 +484,10 @@ function normalizeExperiment(key, input, goals, layers = {}) {
483
484
  kind: input.kind,
484
485
  status: input.status,
485
486
  traffic,
486
- goal: input.goal ?? null,
487
+ goal,
487
488
  seed: input.seed ?? key,
488
489
  description: input.description ?? null,
490
+ ...input.name !== void 0 ? { name: input.name.trim() } : {},
489
491
  match: input.kind === "redirect" ? input.match : null,
490
492
  variants,
491
493
  ...input.kind === "mvt" ? { factors: mvtVariants(key, input.factors).factors } : {},
@@ -498,6 +500,67 @@ function normalizeExperiment(key, input, goals, layers = {}) {
498
500
  ...input.schedule && (input.schedule.startAt || input.schedule.endAt) ? { schedule: { startAt: input.schedule.startAt ?? null, endAt: input.schedule.endAt ?? null } } : {}
499
501
  };
500
502
  }
503
+ function goalExtras(key, g) {
504
+ if (g.name !== void 0 && !(typeof g.name === "string" && g.name.trim() && g.name.trim().length <= 80)) throw new ConfigError(`goal "${key}": name must be text of 1 to 80 characters.`);
505
+ if (g.value !== void 0 && !(typeof g.value === "number" && Number.isFinite(g.value) && g.value >= 0)) throw new ConfigError(`goal "${key}": value must be a number of 0 or more.`);
506
+ const event = g.type === "event" ? g.event : void 0;
507
+ if (event !== void 0 && !EVENT_NAME_PATTERN.test(event)) throw new ConfigError(`goal "${key}": event "${event}" is not a valid event name.`);
508
+ return { ...g.name !== void 0 ? { name: g.name.trim() } : {}, ...g.value !== void 0 ? { value: g.value } : {}, ...event !== void 0 && event !== key ? { event } : {} };
509
+ }
510
+ var PROPERTY_KEY_PATTERN = KEY_PATTERN;
511
+ var ID_ALPHABET = "abcdefghjkmnpqrstuvwxyz23456789";
512
+ function newPropertyId() {
513
+ const bytes = new Uint8Array(6);
514
+ globalThis.crypto.getRandomValues(bytes);
515
+ return `sh-${Array.from(bytes, (b) => ID_ALPHABET[b % ID_ALPHABET.length]).join("")}`;
516
+ }
517
+ var EVENT_NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9 _.:/-]{0,63}$/;
518
+ function eventKey(name) {
519
+ return String(name).trim().toLowerCase().replace(/[^a-z0-9_-]+/g, "-").replace(/^[^a-z0-9]+/, "").slice(0, 64).replace(/-+$/, "");
520
+ }
521
+ function goalKeyFor(goals, name) {
522
+ if (goals.some((g) => g.key === name)) return name;
523
+ const byEvent = goals.find((g) => g.event === name);
524
+ if (byEvent) return byEvent.key;
525
+ const slug = eventKey(name);
526
+ return KEY_PATTERN.test(slug) ? slug : null;
527
+ }
528
+ function goalFor(name, goals, where) {
529
+ if (typeof name !== "string" || !(KEY_PATTERN.test(name) || EVENT_NAME_PATTERN.test(name))) {
530
+ throw new ConfigError(`${where}: goal "${String(name)}" is not a valid event name (letters, digits, spaces and "_ . : / -", up to 64 characters).`);
531
+ }
532
+ const key = goalKeyFor(goals, name);
533
+ if (!key) throw new ConfigError(`${where}: goal "${name}" has no usable key; use letters or digits in the name.`);
534
+ if (!goals.some((g) => g.key === key)) {
535
+ goals.push({ key, type: "event", path: null, selector: null, revenue: false, description: null, ...name !== key ? { event: name } : {} });
536
+ }
537
+ return key;
538
+ }
539
+ function normalizeProperty(key, input, goals) {
540
+ assertKey("property", key);
541
+ const p = input ?? {};
542
+ const status = p.status ?? "running";
543
+ if (status !== "running" && status !== "paused") throw new ConfigError(`property "${key}": status must be "running" or "paused".`);
544
+ if (p.name !== void 0 && !(typeof p.name === "string" && p.name.trim() && p.name.trim().length <= 80)) {
545
+ throw new ConfigError(`property "${key}": name must be text of 1 to 80 characters.`);
546
+ }
547
+ const list2 = p.goals ?? [];
548
+ if (!Array.isArray(list2)) throw new ConfigError(`property "${key}": goals must be a list of goal keys.`);
549
+ for (const g of list2) {
550
+ if (!goals.some((d) => d.key === g)) throw new ConfigError(`property "${key}": goal "${String(g)}" is not declared in "goals".`);
551
+ }
552
+ return {
553
+ key,
554
+ status,
555
+ ...p.name !== void 0 ? { name: p.name.trim() } : {},
556
+ description: p.description ?? null,
557
+ goals: [...new Set(list2)]
558
+ };
559
+ }
560
+ function pickProperty(config, key) {
561
+ if (!key) return null;
562
+ return (config.properties ?? []).find((p) => p.key === key) ?? null;
563
+ }
501
564
  function defineConfig(input) {
502
565
  if (!input || typeof input !== "object") throw new ConfigError("config must be an object.");
503
566
  if (!input.project) throw new ConfigError('"project" is required.');
@@ -513,7 +576,8 @@ function defineConfig(input) {
513
576
  path: g.type === "pageview" ? g.path : null,
514
577
  selector: g.type === "click" ? g.selector : null,
515
578
  revenue: g.type === "event" ? Boolean(g.revenue) : false,
516
- description: g.description ?? null
579
+ description: g.description ?? null,
580
+ ...goalExtras(key, g)
517
581
  };
518
582
  });
519
583
  const layers = {};
@@ -526,6 +590,7 @@ function defineConfig(input) {
526
590
  );
527
591
  assertNoOverlap(experiments);
528
592
  const holdout = normalizeHoldout(input, goals);
593
+ const properties = Object.entries(input.properties ?? {}).map(([key, p]) => normalizeProperty(key, p, goals));
529
594
  return {
530
595
  project: input.project,
531
596
  storage: input.storage,
@@ -533,6 +598,7 @@ function defineConfig(input) {
533
598
  runDraftsInDev: input.runDraftsInDev === true,
534
599
  goals,
535
600
  experiments,
601
+ ...properties.length ? { properties } : {},
536
602
  ...Object.keys(layers).length ? { layers } : {},
537
603
  ...holdout ? { holdout } : {},
538
604
  __splithub: 2
@@ -556,7 +622,7 @@ function holdoutExperiment(config) {
556
622
  traffic: 1,
557
623
  goal: h.goal,
558
624
  seed: h.seed,
559
- description: `Holdout: ${h.percent}% of visitors see no test at all`,
625
+ description: `Holdout: ${h.percent}% of visitors see no experiment at all`,
560
626
  match: null,
561
627
  variants: [
562
628
  { key: "holdout", weight: share },
@@ -700,11 +766,11 @@ function explainAssignment(experiment, a) {
700
766
  return;
701
767
  }
702
768
  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.`);
769
+ devNote("holdout", `This visitor is in the holdout, so every experiment shows its control. Open ?sh_force=${key}:${experiment.variants[1]?.key ?? "variant"} to see a variant.`);
704
770
  return;
705
771
  }
706
772
  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.`);
773
+ devNote(`${key}:layer`, `"${key}" shares layer "${experiment.layer?.key}" with other experiments and this visitor's bucket belongs to another one, so they see the control.`);
708
774
  return;
709
775
  }
710
776
  if (a.reason !== "not_running") return;
@@ -718,6 +784,29 @@ function explainAssignment(experiment, a) {
718
784
  }
719
785
  }
720
786
 
787
+ // src/shared.ts
788
+ var REGISTRY = /* @__PURE__ */ Symbol.for("splithub.analytics");
789
+ function registry() {
790
+ if (typeof window === "undefined") return null;
791
+ const g = globalThis;
792
+ return g[REGISTRY] ?? (g[REGISTRY] = /* @__PURE__ */ new Map());
793
+ }
794
+ function claimAnalytics(key, owner) {
795
+ const r = registry();
796
+ if (!r) return true;
797
+ const held = r.get(key);
798
+ if (held && held !== owner) return false;
799
+ r.set(key, owner);
800
+ return true;
801
+ }
802
+ function releaseAnalytics(key, owner) {
803
+ const r = registry();
804
+ if (r?.get(key) === owner) r.delete(key);
805
+ }
806
+ function resetAnalyticsClaims() {
807
+ registry()?.clear();
808
+ }
809
+
721
810
  // src/ids.ts
722
811
  var ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyz";
723
812
  function randomBytes(n) {
@@ -744,6 +833,38 @@ function newSessionId() {
744
833
  return newId("s_");
745
834
  }
746
835
 
836
+ // src/paths.ts
837
+ function normalizePath(path) {
838
+ return path.length > 1 && path.endsWith("/") ? path.replace(/\/+$/, "") || "/" : path;
839
+ }
840
+ function matchPath(pattern, pathname) {
841
+ if (pattern.endsWith("*")) return pathname.startsWith(pattern.slice(0, -1));
842
+ return normalizePath(pattern) === normalizePath(pathname);
843
+ }
844
+ function redirectTarget(to, currentHref) {
845
+ const current = new URL(currentHref);
846
+ const target = new URL(to, current);
847
+ const own = new Set(target.searchParams.keys());
848
+ current.searchParams.forEach((value, key) => {
849
+ if (!own.has(key)) target.searchParams.append(key, value);
850
+ });
851
+ if (!target.hash) target.hash = current.hash;
852
+ return target;
853
+ }
854
+ function referrerOrigin(referrer, siteHost) {
855
+ if (!referrer) return "";
856
+ let url;
857
+ try {
858
+ url = new URL(referrer);
859
+ } catch {
860
+ return void 0;
861
+ }
862
+ const host = url.hostname.toLowerCase().replace(/^www\./, "");
863
+ const site = (siteHost ?? "").toLowerCase().replace(/:\d+$/, "").replace(/^www\./, "");
864
+ if (!host || host === site) return void 0;
865
+ return `${url.protocol}//${url.host}`.slice(0, 300);
866
+ }
867
+
747
868
  // src/visitor.ts
748
869
  var ONE_YEAR = 60 * 60 * 24 * 365;
749
870
  var isBrowser = () => typeof window !== "undefined" && typeof document !== "undefined";
@@ -801,24 +922,28 @@ function sessionExposureSet(key = "sh_exposed") {
801
922
  function persistExposureSet(set, key = "sh_exposed") {
802
923
  safeStorage("sessionStorage")?.setItem(key, JSON.stringify([...set]));
803
924
  }
804
-
805
- // src/paths.ts
806
- function normalizePath(path) {
807
- return path.length > 1 && path.endsWith("/") ? path.replace(/\/+$/, "") || "/" : path;
925
+ function readStored(kind, key) {
926
+ try {
927
+ return safeStorage(kind)?.getItem(key) ?? null;
928
+ } catch {
929
+ return null;
930
+ }
808
931
  }
809
- function matchPath(pattern, pathname) {
810
- if (pattern.endsWith("*")) return pathname.startsWith(pattern.slice(0, -1));
811
- return normalizePath(pattern) === normalizePath(pathname);
932
+ function writeStored(kind, key, value) {
933
+ try {
934
+ const s = safeStorage(kind);
935
+ if (value === null) s?.removeItem(key);
936
+ else s?.setItem(key, value);
937
+ } catch {
938
+ }
812
939
  }
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;
940
+ function sessionReferrer(key = "sh_ref") {
941
+ if (!isBrowser()) return void 0;
942
+ const stored = readStored("sessionStorage", key);
943
+ if (stored !== null) return stored;
944
+ const ref = referrerOrigin(document.referrer, location.host);
945
+ if (ref !== void 0) writeStored("sessionStorage", key, ref);
946
+ return ref;
822
947
  }
823
948
 
824
949
  // src/events.ts
@@ -1031,13 +1156,22 @@ function applyRemoteOverrides(config, overrides) {
1031
1156
  const addedGoals = (overrides.goals ?? []).filter((g) => g && typeof g.key === "string" && !knownGoals.has(g.key));
1032
1157
  const holdout = !config.holdout && validHoldout(overrides.holdout) ? overrides.holdout : null;
1033
1158
  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;
1159
+ const propertyPatches = overrides.properties ?? {};
1160
+ const knownProps = new Set((config.properties ?? []).map((p) => p.key));
1161
+ const addedProps = (overrides.addedProperties ?? []).filter((p) => p && typeof p.key === "string" && !knownProps.has(p.key));
1162
+ const propsChanged = Object.keys(propertyPatches).length > 0 || addedProps.length > 0;
1163
+ if (Object.keys(patches).length === 0 && added.length === 0 && addedGoals.length === 0 && !holdout && !layers && !propsChanged) return config;
1164
+ const properties = propsChanged ? [...config.properties ?? [], ...addedProps.map((p) => ({ ...p, goals: Array.isArray(p.goals) ? p.goals : [], origin: "dashboard" }))].map((p) => {
1165
+ const status = propertyPatches[p.key]?.status;
1166
+ return status === "running" || status === "paused" ? { ...p, status } : p;
1167
+ }) : config.properties;
1035
1168
  const merged = [...config.experiments, ...added.map((e) => ({ ...e, origin: "dashboard" }))];
1036
1169
  return {
1037
1170
  ...config,
1038
1171
  ...holdout ? { holdout } : {},
1039
1172
  ...layers ? { layers } : {},
1040
1173
  goals: addedGoals.length ? [...config.goals, ...addedGoals] : config.goals,
1174
+ ...properties ? { properties } : {},
1041
1175
  experiments: merged.map((e) => {
1042
1176
  const o = patches[e.key];
1043
1177
  return o ? applyToExperiment(e, o) : e;
@@ -1096,6 +1230,11 @@ var SDK_VERSION = "0.1.0";
1096
1230
  var REMOTE_WAIT_MS = 400;
1097
1231
  var DEV_NOTE = "Development sends nothing to the cloud, so your own visits never reach the results. Deployed builds send as usual.";
1098
1232
  var CLOUD_ENDPOINT = "https://go.splithub.io/v1/events";
1233
+ var PROPERTY_WAIT_MS = 5e3;
1234
+ var MAX_PROPS_BYTES = 4096;
1235
+ var MAX_ENGAGE_MS = 36e5;
1236
+ var UID_KEY = "sh_uid";
1237
+ var UID_SENT_KEY = "sh_uid_sent";
1099
1238
  function resolveEndpoint(config) {
1100
1239
  if (config.storage.mode === "self") return { endpoint: config.storage.endpoint };
1101
1240
  return { endpoint: config.storage.endpoint ?? CLOUD_ENDPOINT, key: config.storage.key };
@@ -1110,6 +1249,7 @@ function createClient(config, options = {}) {
1110
1249
  let effective = config;
1111
1250
  let geo;
1112
1251
  let waitFor = null;
1252
+ let arriving = options.remote?.arriving ?? null;
1113
1253
  if (options.remote?.overrides) {
1114
1254
  effective = applyRemoteOverrides(config, options.remote.overrides);
1115
1255
  geo = options.remote.overrides.ctx;
@@ -1127,6 +1267,7 @@ function createClient(config, options = {}) {
1127
1267
  if (fresh) writeRemoteCache(publicKey, fresh);
1128
1268
  return fresh;
1129
1269
  });
1270
+ arriving = fetched;
1130
1271
  const waitMs = options.remote?.waitMs ?? REMOTE_WAIT_MS;
1131
1272
  if (!cached && waitMs > 0 && options.remote?.overrides === void 0) waitFor = withTimeout(fetched, waitMs);
1132
1273
  else {
@@ -1140,7 +1281,7 @@ function createClient(config, options = {}) {
1140
1281
  const hadVisitor = browser && !options.visitorId ? hasVisitorId(config.visitorKey) : void 0;
1141
1282
  const visitorId = options.visitorId ?? (browser ? getOrCreateVisitorId(config.visitorKey) : "server");
1142
1283
  const noVisitor = !browser && !options.visitorId;
1143
- const sessionId = options.sessionId ?? (browser ? getOrCreateSessionId() : "server");
1284
+ const sessionId = options.sessionId ?? (browser ? getOrCreateSessionId() : options.visitorId ? `srv_${murmur3(options.visitorId).toString(36)}` : "server");
1144
1285
  const contextFor = (g) => {
1145
1286
  if (!browser) return { ...g ?? {}, ...options.context ?? {} };
1146
1287
  const forPage = g?.timezone ? { ...g, timezone: void 0 } : g;
@@ -1160,7 +1301,15 @@ function createClient(config, options = {}) {
1160
1301
  }
1161
1302
  const disabled = options.disabled ?? (!browser && !options.transport);
1162
1303
  const cloud = config.storage.mode === "cloud";
1163
- const cloudIdle = () => cloud && !config.experiments.some((e) => e.status === "running");
1304
+ const cloudIdle = () => cloud && !config.experiments.some((e) => e.status === "running") && !(config.properties ?? []).some((p) => p.status === "running");
1305
+ const wanted = typeof options.property === "string" ? options.property.trim().toLowerCase() || null : null;
1306
+ let propConfig = config;
1307
+ const known = () => wanted !== null && pickProperty(propConfig, wanted) !== null;
1308
+ const property = () => {
1309
+ if (!wanted) return null;
1310
+ const p = pickProperty(propConfig, wanted);
1311
+ return p && p.status === "running" ? p.key : null;
1312
+ };
1164
1313
  const devLocal = cloud && isDevEnvironment();
1165
1314
  const held = /* @__PURE__ */ new Set();
1166
1315
  const hold = (key, kind, message) => {
@@ -1180,6 +1329,8 @@ function createClient(config, options = {}) {
1180
1329
  });
1181
1330
  const exposed = browser ? sessionExposureSet() : /* @__PURE__ */ new Set();
1182
1331
  const currentUrl = () => browser ? location.pathname + location.search : void 0;
1332
+ const entryRef = browser ? sessionReferrer() : void 0;
1333
+ const refField = entryRef === void 0 ? {} : { ref: entryRef };
1183
1334
  const markHoldout = (ts) => {
1184
1335
  const group = holdoutGroup(config, visitorId);
1185
1336
  if (!group || noVisitor) return;
@@ -1191,7 +1342,7 @@ function createClient(config, options = {}) {
1191
1342
  }
1192
1343
  exposed.add(dedupKey);
1193
1344
  if (browser) persistExposureSet(exposed);
1194
- const event = { id: newId("e_"), type: "exposure", exp: HOLDOUT_KEY, var: group, vid: visitorId, sid: sessionId, ts, url: currentUrl() };
1345
+ const event = { id: newId("e_"), type: "exposure", exp: HOLDOUT_KEY, var: group, vid: visitorId, sid: sessionId, ts, url: currentUrl(), ...refField };
1195
1346
  debugLog("exposure", `${HOLDOUT_KEY} / ${group} recorded`, event);
1196
1347
  queue.push(event);
1197
1348
  };
@@ -1211,15 +1362,14 @@ function createClient(config, options = {}) {
1211
1362
  if (exposed.has(dedupKey)) return;
1212
1363
  exposed.add(dedupKey);
1213
1364
  if (browser) persistExposureSet(exposed);
1214
- const event = { id: newId("e_"), type: "exposure", exp: experimentKey, var: a.variant.key, vid: visitorId, sid: sessionId, ts, url: currentUrl() };
1365
+ const event = { id: newId("e_"), type: "exposure", exp: experimentKey, var: a.variant.key, vid: visitorId, sid: sessionId, ts, url: currentUrl(), ...refField };
1215
1366
  debugLog("exposure", `${experimentKey} / ${a.variant.key} recorded`, event);
1216
1367
  queue.push(event);
1217
1368
  };
1218
- const sendGoal = (goal, props, ts) => {
1369
+ const sendGoal = (name, props, ts) => {
1219
1370
  if (isBot2()) return;
1220
- if (!config.goals.some((g) => g.key === goal)) {
1221
- warn(`goal "${goal}" is not declared in splithub.config.ts; sending anyway.`);
1222
- }
1371
+ const goal = goalKeyFor(config.goals, name);
1372
+ if (!goal) return;
1223
1373
  if (typeof __SPLITHUB_LITE__ === "undefined" && devLocal) {
1224
1374
  devNote("dev-events", DEV_NOTE);
1225
1375
  hold(`g:${goal}`, "goal", `${goal} not sent: development never sends to the cloud`);
@@ -1233,21 +1383,231 @@ function createClient(config, options = {}) {
1233
1383
  debugLog("goal", `${goal}${props ? " " + JSON.stringify(props) : ""}`, event);
1234
1384
  queue.push(event);
1235
1385
  };
1386
+ let propertyFetch = null;
1387
+ const propertyWaiting = [];
1388
+ const warnUnknownProperty = () => {
1389
+ if (wanted && !known() && (isDevEnvironment() || isDebug())) {
1390
+ warn(`property "${wanted}" is not in splithub.config.ts or the dashboard, so no pageviews or events are sent. Check the id (it looks like sh-x1h78w).`);
1391
+ }
1392
+ };
1393
+ const withProperty = (send) => {
1394
+ if (!wanted) return;
1395
+ if (!known() && propertyFetch) {
1396
+ propertyWaiting.push(send);
1397
+ return;
1398
+ }
1399
+ send();
1400
+ };
1401
+ const hashRoute = () => {
1402
+ if (!browser || options.trackHash === false) return null;
1403
+ const hash = location.hash;
1404
+ const route = hash.startsWith("#/") ? hash.slice(1) : hash.startsWith("#!/") ? hash.slice(2) : null;
1405
+ if (route === null || options.trackHash !== true && location.pathname !== "/") return null;
1406
+ return route.includes("?") || !location.search ? route : route + location.search;
1407
+ };
1408
+ const pageUrl = () => hashRoute() ?? location.pathname + location.search;
1409
+ const pagePath = () => hashRoute()?.split("?")[0] ?? location.pathname;
1410
+ let engage = null;
1411
+ const pageVisible = () => typeof document === "undefined" || document.visibilityState !== "hidden";
1412
+ const scrollDepth = () => {
1413
+ if (!browser) return 0;
1414
+ const doc = document.documentElement;
1415
+ const height = Math.max(doc.scrollHeight, document.body?.scrollHeight ?? 0);
1416
+ const seen = (window.scrollY || doc.scrollTop || 0) + window.innerHeight;
1417
+ if (!height || seen >= height) return 100;
1418
+ return Math.max(0, Math.min(100, Math.round(seen / height * 100)));
1419
+ };
1420
+ const emitEngage = (final) => {
1421
+ const e = engage;
1422
+ if (!e) return false;
1423
+ const now = Date.now();
1424
+ const ms = Math.min(MAX_ENGAGE_MS, Math.round(e.ms + (e.since !== null ? now - e.since : 0)));
1425
+ e.ms = 0;
1426
+ e.since = !final && pageVisible() ? now : null;
1427
+ if (final) engage = null;
1428
+ if (ms <= 0 || isBot2()) return false;
1429
+ const event = { id: newId("n_"), type: "engage", prop: e.prop, vid: visitorId, sid: sessionId, ts: now, url: e.url, ms, scroll: e.scroll };
1430
+ debugLog("pageview", `${e.prop}: ${e.url} engaged ${Math.round(ms / 1e3)} s, scrolled ${e.scroll}%`, event);
1431
+ queue.push(event);
1432
+ return true;
1433
+ };
1434
+ let sentIdentity = browser ? readStored("sessionStorage", UID_SENT_KEY) : null;
1435
+ const sendIdentify = (uid, traits, ts) => {
1436
+ if (!wanted || isBot2() || noVisitor) return;
1437
+ const mark = `${uid}
1438
+ ${traits ? JSON.stringify(traits) : ""}`;
1439
+ withProperty(() => {
1440
+ const prop = property();
1441
+ if (!prop || isBot2() || sentIdentity === mark || browser && readStored("sessionStorage", UID_SENT_KEY) === mark) return;
1442
+ if (typeof __SPLITHUB_LITE__ === "undefined" && devLocal) {
1443
+ hold(`i:${prop}`, "pageview", `${prop}: identify not sent: development never sends to the cloud`);
1444
+ return;
1445
+ }
1446
+ sentIdentity = mark;
1447
+ if (browser) writeStored("sessionStorage", UID_SENT_KEY, mark);
1448
+ const event = { id: newId("i_"), type: "identify", prop, vid: visitorId, sid: sessionId, ts, uid, ...traits ? { traits } : {} };
1449
+ debugLog("info", `${prop}: identify ${uid}`, event);
1450
+ queue.push(event);
1451
+ });
1452
+ };
1453
+ const resendIdentity = (ts) => {
1454
+ const uid = browser ? readStored("localStorage", UID_KEY) : null;
1455
+ if (uid && !(sentIdentity ?? "").startsWith(`${uid}
1456
+ `)) sendIdentify(uid, void 0, ts);
1457
+ };
1458
+ const sendPageGoals = (path, ts) => {
1459
+ if (isBot2()) return;
1460
+ for (const goal of config.goals) {
1461
+ if (goal.type === "pageview" && goal.path && matchPath(goal.path, path)) {
1462
+ debugLog("pageview", `${path} matches goal ${goal.key}`);
1463
+ sendGoal(goal.key, void 0, ts);
1464
+ }
1465
+ }
1466
+ };
1467
+ const endpointKey = resolveEndpoint(config).endpoint;
1468
+ const owner = {};
1469
+ const claimed = /* @__PURE__ */ new Set();
1470
+ const collects = (prop) => {
1471
+ if (claimAnalytics(`${endpointKey}|${prop}`, owner)) {
1472
+ claimed.add(prop);
1473
+ return true;
1474
+ }
1475
+ if (typeof __SPLITHUB_LITE__ === "undefined") devNote(`shared:${prop}`, `Another SplitHub script on this page already collects pageviews for "${prop}", so this one leaves them to it. Keep one install per property: the SDK or sh.js.`);
1476
+ hold(`s:${prop}`, "pageview", `${prop}: pageviews left to the other SplitHub script on this page`);
1477
+ return false;
1478
+ };
1479
+ let lastPage = null;
1480
+ const sendPage = (path, ts) => {
1481
+ if (isBot2()) return;
1482
+ if (!wanted || noVisitor) {
1483
+ sendPageGoals(path, ts);
1484
+ return;
1485
+ }
1486
+ const url = browser && path === pagePath() ? pageUrl() : path;
1487
+ const title = browser && typeof document !== "undefined" ? document.title.slice(0, 200) : "";
1488
+ const ref = browser && typeof document !== "undefined" ? document.referrer.slice(0, 512) : "";
1489
+ withProperty(() => {
1490
+ const prop = property();
1491
+ if (isBot2()) return;
1492
+ if (!prop) {
1493
+ sendPageGoals(path, ts);
1494
+ return;
1495
+ }
1496
+ if (lastPage && lastPage.url === url && ts - lastPage.ts < 1e3) return;
1497
+ lastPage = { url, ts };
1498
+ if (typeof __SPLITHUB_LITE__ === "undefined" && devLocal) {
1499
+ devNote("dev-events", DEV_NOTE);
1500
+ hold(`p:${prop}`, "pageview", `${prop}: pageviews not sent: development never sends to the cloud`);
1501
+ return;
1502
+ }
1503
+ if (!collects(prop)) return;
1504
+ emitEngage(true);
1505
+ const event = { id: newId("p_"), type: "page", prop, vid: visitorId, sid: sessionId, ts, url, ...title ? { title } : {}, ...ref ? { ref } : {} };
1506
+ debugLog("pageview", `${prop}: ${url}`, event);
1507
+ queue.push(event);
1508
+ if (browser) engage = { prop, url, ms: 0, since: pageVisible() ? ts : null, scroll: scrollDepth() };
1509
+ resendIdentity(ts);
1510
+ });
1511
+ };
1512
+ const sendTracked = (name, props, ts) => {
1513
+ if (isBot2()) return;
1514
+ if (!wanted || noVisitor) {
1515
+ sendGoal(name, props, ts);
1516
+ return;
1517
+ }
1518
+ if (!EVENT_NAME_PATTERN.test(name)) {
1519
+ warn(`event name "${name}" is invalid: letters, digits, spaces and "_ . : / -", up to 64 characters.`);
1520
+ sendGoal(name, props, ts);
1521
+ return;
1522
+ }
1523
+ const url = currentUrl();
1524
+ withProperty(() => {
1525
+ const prop = property();
1526
+ if (isBot2()) return;
1527
+ if (!prop) {
1528
+ sendGoal(name, props, ts);
1529
+ return;
1530
+ }
1531
+ if (typeof __SPLITHUB_LITE__ === "undefined" && devLocal) {
1532
+ hold(`v:${prop}:${name}`, "goal", `${prop}: event ${name} not sent: development never sends to the cloud`);
1533
+ return;
1534
+ }
1535
+ const event = { id: newId("v_"), type: "event", prop, name, vid: visitorId, sid: sessionId, ts, url, ...props ? { props } : {} };
1536
+ debugLog("goal", `${prop}: event ${name}${props ? " " + JSON.stringify(props) : ""}`, event);
1537
+ queue.push(event);
1538
+ });
1539
+ };
1540
+ const emit = (name, props) => {
1541
+ if (disabled || isBot2()) return;
1542
+ const ts = Date.now();
1543
+ props = fitProps(props, `event "${name}"`);
1544
+ if (pending) void ready.then(() => sendTracked(name, props, ts));
1545
+ else sendTracked(name, props, ts);
1546
+ };
1547
+ let unwatch = null;
1548
+ const watch = () => {
1549
+ if (unwatch || !browser || options.trackNavigation === false) return;
1550
+ let last = pageUrl();
1551
+ unwatch = onNavigation(() => {
1552
+ const now = pageUrl();
1553
+ if (now === last) return;
1554
+ last = now;
1555
+ client.pageview();
1556
+ });
1557
+ };
1558
+ let unbindPage = null;
1559
+ const bindPage = () => {
1560
+ if (unbindPage || !browser || !wanted || disabled) return;
1561
+ const onScroll = () => {
1562
+ if (engage) engage.scroll = Math.max(engage.scroll, scrollDepth());
1563
+ };
1564
+ const leave = () => {
1565
+ if (emitEngage(false)) void queue.flush(true);
1566
+ if (engage) engage.since = null;
1567
+ };
1568
+ const onVisibility = () => {
1569
+ if (document.visibilityState === "hidden") leave();
1570
+ else if (engage && engage.since === null) engage.since = Date.now();
1571
+ };
1572
+ const onShow = () => {
1573
+ if (engage && engage.since === null && pageVisible()) engage.since = Date.now();
1574
+ };
1575
+ addEventListener("scroll", onScroll, { passive: true });
1576
+ document.addEventListener("visibilitychange", onVisibility);
1577
+ addEventListener("pagehide", leave);
1578
+ addEventListener("pageshow", onShow);
1579
+ unbindPage = () => {
1580
+ removeEventListener("scroll", onScroll);
1581
+ document.removeEventListener("visibilitychange", onVisibility);
1582
+ removeEventListener("pagehide", leave);
1583
+ removeEventListener("pageshow", onShow);
1584
+ };
1585
+ };
1236
1586
  const ready = waitFor ? waitFor.then((fresh) => {
1237
1587
  if (fresh) {
1238
1588
  config = applyRemoteOverrides(base, fresh);
1589
+ propConfig = config;
1239
1590
  context = contextFor(fresh.ctx);
1240
1591
  debugLog("remote", `first visit: overrides v${fresh.version} arrived, experiments decided`, { experiments: fresh.experiments });
1241
1592
  } else {
1242
1593
  debugLog("remote", "first visit: overrides did not arrive in time; experiments follow splithub.config.ts");
1243
1594
  }
1244
1595
  pending = false;
1245
- for (const w of waiting) if ("exp" in w) sendExposure(w.exp, w.ts);
1246
- for (const w of waiting) if ("goal" in w) sendGoal(w.goal, w.props, w.ts);
1596
+ for (const w of waiting) sendExposure(w.exp, w.ts);
1247
1597
  waiting.length = 0;
1248
1598
  for (const listener of [...listeners]) listener();
1249
1599
  listeners.clear();
1250
1600
  }) : Promise.resolve();
1601
+ if (wanted && !known()) {
1602
+ if (arriving) {
1603
+ propertyFetch = withTimeout(arriving, PROPERTY_WAIT_MS).then((fresh) => {
1604
+ if (fresh) propConfig = applyRemoteOverrides(base, fresh);
1605
+ propertyFetch = null;
1606
+ warnUnknownProperty();
1607
+ for (const send of propertyWaiting.splice(0)) send();
1608
+ });
1609
+ } else warnUnknownProperty();
1610
+ }
1251
1611
  const decided = /* @__PURE__ */ new Set();
1252
1612
  const client = {
1253
1613
  get config() {
@@ -1282,7 +1642,7 @@ function createClient(config, options = {}) {
1282
1642
  exposure(experimentKey) {
1283
1643
  if (disabled) return;
1284
1644
  if (pending) {
1285
- if (!waiting.some((w) => "exp" in w && w.exp === experimentKey)) waiting.push({ exp: experimentKey, ts: Date.now() });
1645
+ if (!waiting.some((w) => w.exp === experimentKey)) waiting.push({ exp: experimentKey, ts: Date.now() });
1286
1646
  return;
1287
1647
  }
1288
1648
  sendExposure(experimentKey, Date.now());
@@ -1307,28 +1667,37 @@ function createClient(config, options = {}) {
1307
1667
  client.exposure(experimentKey);
1308
1668
  return (a.variant ?? experiment.variants[0]).value;
1309
1669
  },
1310
- track(goal, props) {
1311
- if (disabled || isBot2()) return;
1312
- if (pending) waiting.push({ goal, ...props ? { props } : {}, ts: Date.now() });
1313
- else sendGoal(goal, props, Date.now());
1670
+ track(name, props) {
1671
+ emit(name, props);
1314
1672
  },
1315
1673
  pageview(path) {
1316
- const current = path ?? (browser ? location.pathname : void 0);
1674
+ const current = path ?? (browser ? pagePath() : void 0);
1317
1675
  if (!current) return;
1676
+ if (path === void 0) watch();
1677
+ bindPage();
1678
+ if (disabled) return;
1318
1679
  if (pending) {
1319
1680
  const ts = Date.now();
1320
- void ready.then(() => {
1321
- if (disabled) return;
1322
- for (const goal of config.goals) if (goal.type === "pageview" && goal.path && matchPath(goal.path, current)) sendGoal(goal.key, void 0, ts);
1323
- });
1681
+ void ready.then(() => sendPage(current, ts));
1324
1682
  return;
1325
1683
  }
1326
- for (const goal of config.goals) {
1327
- if (goal.type === "pageview" && goal.path && matchPath(goal.path, current)) {
1328
- debugLog("pageview", `${current} matches goal ${goal.key}`);
1329
- client.track(goal.key);
1330
- }
1684
+ sendPage(current, Date.now());
1685
+ },
1686
+ identify(uid, traits) {
1687
+ if (uid === null) {
1688
+ writeStored("localStorage", UID_KEY, null);
1689
+ writeStored("sessionStorage", UID_SENT_KEY, null);
1690
+ sentIdentity = null;
1691
+ return;
1692
+ }
1693
+ const id = typeof uid === "string" ? uid.trim() : "";
1694
+ if (!id || id.length > 128) {
1695
+ warn("identify() needs a user id of 1 to 128 characters.");
1696
+ return;
1331
1697
  }
1698
+ if (browser) writeStored("localStorage", UID_KEY, id);
1699
+ if (disabled || isBot2()) return;
1700
+ sendIdentify(id, cleanTraits(traits), Date.now());
1332
1701
  },
1333
1702
  autoGoals(root) {
1334
1703
  if (!browser) return () => void 0;
@@ -1351,7 +1720,15 @@ function createClient(config, options = {}) {
1351
1720
  flush: () => queue.flush(false),
1352
1721
  // Unbinds the page listeners; pending events are kept and a later event binds again,
1353
1722
  // so a provider may destroy on unmount even under StrictMode's double mount.
1354
- destroy: () => queue.destroy()
1723
+ destroy: () => {
1724
+ queue.destroy();
1725
+ unwatch?.();
1726
+ unwatch = null;
1727
+ unbindPage?.();
1728
+ unbindPage = null;
1729
+ for (const prop of claimed) releaseAnalytics(`${endpointKey}|${prop}`, owner);
1730
+ claimed.clear();
1731
+ }
1355
1732
  };
1356
1733
  if (browser && isDebug()) {
1357
1734
  window.__splithub = client;
@@ -1359,6 +1736,25 @@ function createClient(config, options = {}) {
1359
1736
  }
1360
1737
  return client;
1361
1738
  }
1739
+ var navListeners = /* @__PURE__ */ new Set();
1740
+ var historyWrapped = false;
1741
+ function onNavigation(listener) {
1742
+ if (!historyWrapped && typeof history !== "undefined") {
1743
+ historyWrapped = true;
1744
+ for (const method of ["pushState", "replaceState"]) {
1745
+ const original = history[method];
1746
+ history[method] = function(...args) {
1747
+ const out = original.apply(this, args);
1748
+ setTimeout(() => navListeners.forEach((l) => l()), 0);
1749
+ return out;
1750
+ };
1751
+ }
1752
+ addEventListener("popstate", () => navListeners.forEach((l) => l()));
1753
+ addEventListener("hashchange", () => navListeners.forEach((l) => l()));
1754
+ }
1755
+ navListeners.add(listener);
1756
+ return () => void navListeners.delete(listener);
1757
+ }
1362
1758
  function stripUndefined(o) {
1363
1759
  return Object.fromEntries(Object.entries(o).filter(([, v]) => v !== void 0));
1364
1760
  }
@@ -1377,6 +1773,53 @@ function withTimeout(p, ms) {
1377
1773
  );
1378
1774
  });
1379
1775
  }
1776
+ function fitProps(props, what) {
1777
+ if (!props || typeof props !== "object") return void 0;
1778
+ let json;
1779
+ try {
1780
+ json = JSON.stringify(props);
1781
+ } catch {
1782
+ warn(`${what}: props cannot be sent as JSON, so they were left out.`);
1783
+ return void 0;
1784
+ }
1785
+ if (json.length <= MAX_PROPS_BYTES) return props;
1786
+ const out = {};
1787
+ let size = 2;
1788
+ const entries = Object.entries(props).sort(([a], [b]) => a === "revenue" ? -1 : b === "revenue" ? 1 : 0);
1789
+ for (const [key, value] of entries) {
1790
+ if (value !== null && typeof value === "object") continue;
1791
+ const part = JSON.stringify({ [key]: value }).length - 1;
1792
+ if (size + part > MAX_PROPS_BYTES) continue;
1793
+ out[key] = value;
1794
+ size += part;
1795
+ }
1796
+ const kept = Object.keys(out);
1797
+ warn(`${what}: props are larger than 4 KB, so ${kept.length ? `only ${kept.join(", ")} went out` : "none went out"}.`);
1798
+ return kept.length ? out : void 0;
1799
+ }
1800
+ function cleanTraits(traits) {
1801
+ if (!traits || typeof traits !== "object") return void 0;
1802
+ const out = {};
1803
+ let size = 2;
1804
+ let skipped = false;
1805
+ for (const [key, value] of Object.entries(traits)) {
1806
+ const plain = typeof value === "string" || typeof value === "boolean" || typeof value === "number" && Number.isFinite(value);
1807
+ if (!plain || key.length > 64) {
1808
+ if (value !== void 0) skipped = true;
1809
+ continue;
1810
+ }
1811
+ const v = typeof value === "string" ? value.slice(0, 256) : value;
1812
+ const part = JSON.stringify({ [key]: v }).length - 1;
1813
+ if (size + part > MAX_PROPS_BYTES) {
1814
+ skipped = true;
1815
+ continue;
1816
+ }
1817
+ out[key] = v;
1818
+ size += part;
1819
+ }
1820
+ if (skipped) warn("identify(): traits keep text, numbers and true/false up to 4 KB; the rest was left out.");
1821
+ return Object.keys(out).length ? out : void 0;
1822
+ }
1380
1823
  var warned = /* @__PURE__ */ new Set();
1381
1824
  function warn(message) {
1382
1825
  if (warned.has(message)) return;
@@ -1410,6 +1853,13 @@ export {
1410
1853
  mvtVariants,
1411
1854
  HOLDOUT_KEY,
1412
1855
  LAYER_BUCKETS,
1856
+ PROPERTY_KEY_PATTERN,
1857
+ newPropertyId,
1858
+ EVENT_NAME_PATTERN,
1859
+ eventKey,
1860
+ goalKeyFor,
1861
+ normalizeProperty,
1862
+ pickProperty,
1413
1863
  defineConfig,
1414
1864
  isSplitHubConfig,
1415
1865
  getExperiment,
@@ -1430,16 +1880,18 @@ export {
1430
1880
  devNote,
1431
1881
  resetDevNotes,
1432
1882
  explainAssignment,
1883
+ resetAnalyticsClaims,
1433
1884
  newId,
1434
1885
  newVisitorId,
1435
1886
  newSessionId,
1887
+ normalizePath,
1888
+ matchPath,
1889
+ redirectTarget,
1890
+ referrerOrigin,
1436
1891
  isBrowser,
1437
1892
  hasVisitorId,
1438
1893
  getOrCreateVisitorId,
1439
1894
  getOrCreateSessionId,
1440
- normalizePath,
1441
- matchPath,
1442
- redirectTarget,
1443
1895
  createFetchTransport,
1444
1896
  EventQueue,
1445
1897
  debugMode,
@@ -1459,4 +1911,4 @@ export {
1459
1911
  CLOUD_ENDPOINT,
1460
1912
  createClient
1461
1913
  };
1462
- //# sourceMappingURL=chunk-LRAW5YQY.js.map
1914
+ //# sourceMappingURL=chunk-7CE2FI5Y.js.map