@splithub/core 0.1.7 → 0.1.9

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
@@ -29,6 +29,7 @@ __export(index_exports, {
29
29
  MVT_MAX_FACTORS: () => MVT_MAX_FACTORS,
30
30
  MVT_MAX_LEVELS: () => MVT_MAX_LEVELS,
31
31
  REMOTE_TTL_MS: () => REMOTE_TTL_MS,
32
+ REMOTE_WAIT_MS: () => REMOTE_WAIT_MS,
32
33
  SDK_VERSION: () => SDK_VERSION,
33
34
  TARGET_FIELDS: () => TARGET_FIELDS,
34
35
  TARGET_OPS: () => TARGET_OPS,
@@ -917,6 +918,8 @@ async function fetchRemoteOverrides(url, fetchImpl = fetch) {
917
918
 
918
919
  // src/client.ts
919
920
  var SDK_VERSION = "0.1.0";
921
+ var REMOTE_WAIT_MS = 400;
922
+ var DEV_NOTE = "Development sends nothing to the cloud, so your own visits never reach the results. Deployed builds send as usual.";
920
923
  var CLOUD_ENDPOINT = "https://go.splithub.io/v1/events";
921
924
  function resolveEndpoint(config) {
922
925
  if (config.storage.mode === "self") return { endpoint: config.storage.endpoint };
@@ -927,9 +930,11 @@ function createClient(config, options = {}) {
927
930
  throw new Error("[splithub] pass the object returned by defineConfig() from splithub.config.ts");
928
931
  }
929
932
  const browser = isBrowser();
933
+ const base = config;
930
934
  const publicKey = config.storage.mode === "cloud" ? config.storage.key : void 0;
931
935
  let effective = config;
932
936
  let geo;
937
+ let waitFor = null;
933
938
  if (options.remote?.overrides) {
934
939
  effective = applyRemoteOverrides(config, options.remote.overrides);
935
940
  geo = options.remote.overrides.ctx;
@@ -943,26 +948,33 @@ function createClient(config, options = {}) {
943
948
  const stale = !cached || Date.now() - cached.fetchedAt > (options.remote?.ttlMs ?? REMOTE_TTL_MS);
944
949
  if (stale) {
945
950
  const url = options.remote?.url ?? resolveOverridesUrl(config.storage.endpoint ?? CLOUD_ENDPOINT, publicKey);
946
- void fetchRemoteOverrides(url).then((fresh) => {
947
- if (fresh) {
948
- writeRemoteCache(publicKey, fresh);
949
- debugLog("remote", `fresh overrides v${fresh.version} fetched; applied on the next page load`, { experiments: fresh.experiments });
950
- }
951
+ const fetched = fetchRemoteOverrides(url).then((fresh) => {
952
+ if (fresh) writeRemoteCache(publicKey, fresh);
953
+ return fresh;
951
954
  });
955
+ const waitMs = options.remote?.waitMs ?? REMOTE_WAIT_MS;
956
+ if (!cached && waitMs > 0 && options.remote?.overrides === void 0) waitFor = withTimeout(fetched, waitMs);
957
+ else {
958
+ void fetched.then((fresh) => {
959
+ if (fresh) debugLog("remote", `fresh overrides v${fresh.version} fetched; applied on the next page load`, { experiments: fresh.experiments });
960
+ });
961
+ }
952
962
  }
953
963
  }
954
964
  config = effective;
955
965
  const hadVisitor = browser && !options.visitorId ? hasVisitorId(config.visitorKey) : void 0;
956
966
  const visitorId = options.visitorId ?? (browser ? getOrCreateVisitorId(config.visitorKey) : "server");
957
967
  const sessionId = options.sessionId ?? (browser ? getOrCreateSessionId() : "server");
958
- const context = browser ? browserContext({ ...geo ?? {}, ...hadVisitor === void 0 ? {} : { visitor: hadVisitor ? "returning" : "new" }, ...options.context ?? {} }) : { ...geo ?? {}, ...options.context ?? {} };
968
+ const contextFor = (g) => browser ? browserContext({ ...g ?? {}, ...hadVisitor === void 0 ? {} : { visitor: hadVisitor ? "returning" : "new" }, ...options.context ?? {} }) : { ...g ?? {}, ...options.context ?? {} };
969
+ let context = contextFor(geo);
959
970
  const overrides = {
960
971
  ...browser ? parseForceParam(location.search) : {},
961
972
  ...options.overrides ?? {}
962
973
  };
963
974
  const disabled = options.disabled ?? (!browser && !options.transport);
964
975
  const cloud = config.storage.mode === "cloud";
965
- const cloudIdle = cloud && !config.experiments.some((e) => e.status === "running");
976
+ const cloudIdle = () => cloud && !config.experiments.some((e) => e.status === "running");
977
+ const devLocal = cloud && isDevEnvironment();
966
978
  const held = /* @__PURE__ */ new Set();
967
979
  const hold = (key, kind, message) => {
968
980
  if (held.has(key)) return;
@@ -978,13 +990,78 @@ function createClient(config, options = {}) {
978
990
  });
979
991
  const exposed = browser ? sessionExposureSet() : /* @__PURE__ */ new Set();
980
992
  const currentUrl = () => browser ? location.pathname + location.search : void 0;
993
+ let pending = waitFor !== null;
994
+ const waiting = [];
995
+ const listeners = /* @__PURE__ */ new Set();
996
+ const sendExposure = (experimentKey, ts) => {
997
+ const a = client.assignment(experimentKey);
998
+ if (!a.variant || a.reason === "override") return;
999
+ if (devLocal) {
1000
+ devNote("dev-events", DEV_NOTE);
1001
+ hold(`x:${experimentKey}`, "exposure", `${experimentKey} / ${a.variant.key} not sent: development never sends to the cloud`);
1002
+ return;
1003
+ }
1004
+ const dedupKey = `${experimentKey}:${a.variant.key}`;
1005
+ if (exposed.has(dedupKey)) return;
1006
+ exposed.add(dedupKey);
1007
+ if (browser) persistExposureSet(exposed);
1008
+ const event = { id: newId("e_"), type: "exposure", exp: experimentKey, var: a.variant.key, vid: visitorId, sid: sessionId, ts, url: currentUrl() };
1009
+ debugLog("exposure", `${experimentKey} / ${a.variant.key} recorded`, event);
1010
+ queue.push(event);
1011
+ };
1012
+ const sendGoal = (goal, props, ts) => {
1013
+ if (!config.goals.some((g) => g.key === goal)) {
1014
+ warn(`goal "${goal}" is not declared in splithub.config.ts; sending anyway.`);
1015
+ }
1016
+ if (devLocal) {
1017
+ devNote("dev-events", DEV_NOTE);
1018
+ hold(`g:${goal}`, "goal", `${goal} not sent: development never sends to the cloud`);
1019
+ return;
1020
+ }
1021
+ if (cloudIdle()) {
1022
+ hold(`g:${goal}`, "goal", `${goal} not sent: no experiment is running in this project yet`);
1023
+ return;
1024
+ }
1025
+ const event = { id: newId("g_"), type: "goal", goal, vid: visitorId, sid: sessionId, ts, url: currentUrl(), ...props ? { props } : {} };
1026
+ debugLog("goal", `${goal}${props ? " " + JSON.stringify(props) : ""}`, event);
1027
+ queue.push(event);
1028
+ };
1029
+ const ready = waitFor ? waitFor.then((fresh) => {
1030
+ if (fresh) {
1031
+ config = applyRemoteOverrides(base, fresh);
1032
+ context = contextFor(fresh.ctx);
1033
+ debugLog("remote", `first visit: overrides v${fresh.version} arrived, experiments decided`, { experiments: fresh.experiments });
1034
+ } else {
1035
+ debugLog("remote", "first visit: overrides did not arrive in time; experiments follow splithub.config.ts");
1036
+ }
1037
+ pending = false;
1038
+ for (const w of waiting) if ("exp" in w) sendExposure(w.exp, w.ts);
1039
+ for (const w of waiting) if ("goal" in w) sendGoal(w.goal, w.props, w.ts);
1040
+ waiting.length = 0;
1041
+ for (const listener of [...listeners]) listener();
1042
+ listeners.clear();
1043
+ }) : Promise.resolve();
981
1044
  const decided = /* @__PURE__ */ new Set();
982
1045
  const client = {
983
- config,
1046
+ get config() {
1047
+ return config;
1048
+ },
984
1049
  visitorId,
985
1050
  sessionId,
986
- context,
1051
+ get context() {
1052
+ return context;
1053
+ },
1054
+ get pending() {
1055
+ return pending;
1056
+ },
1057
+ ready,
1058
+ subscribe(listener) {
1059
+ if (!pending) return () => void 0;
1060
+ listeners.add(listener);
1061
+ return () => void listeners.delete(listener);
1062
+ },
987
1063
  assignment(experimentKey) {
1064
+ if (pending) return { experiment: experimentKey, variant: null, reason: "pending" };
988
1065
  const a = assign(config, experimentKey, visitorId, { overrides, context });
989
1066
  explainAssignment(getExperiment(config, experimentKey), a);
990
1067
  if (isDebug() && !decided.has(experimentKey)) {
@@ -996,20 +1073,11 @@ function createClient(config, options = {}) {
996
1073
  },
997
1074
  exposure(experimentKey) {
998
1075
  if (disabled) return;
999
- const a = client.assignment(experimentKey);
1000
- if (!a.variant || a.reason === "override") return;
1001
- if (cloud && a.reason === "dev") {
1002
- devNote("dev-events", "Drafts shown in development record nothing in the cloud; their numbers start when you start the test.");
1003
- hold(`x:${experimentKey}`, "exposure", `${experimentKey} / ${a.variant.key} not sent: a draft shown in development (the cloud records only running tests)`);
1076
+ if (pending) {
1077
+ if (!waiting.some((w) => "exp" in w && w.exp === experimentKey)) waiting.push({ exp: experimentKey, ts: Date.now() });
1004
1078
  return;
1005
1079
  }
1006
- const dedupKey = `${experimentKey}:${a.variant.key}`;
1007
- if (exposed.has(dedupKey)) return;
1008
- exposed.add(dedupKey);
1009
- if (browser) persistExposureSet(exposed);
1010
- const event = { id: newId("e_"), type: "exposure", exp: experimentKey, var: a.variant.key, vid: visitorId, sid: sessionId, ts: Date.now(), url: currentUrl() };
1011
- debugLog("exposure", `${experimentKey} / ${a.variant.key} recorded`, event);
1012
- queue.push(event);
1080
+ sendExposure(experimentKey, Date.now());
1013
1081
  },
1014
1082
  variant(experimentKey) {
1015
1083
  const experiment = getExperiment(config, experimentKey);
@@ -1033,21 +1101,20 @@ function createClient(config, options = {}) {
1033
1101
  },
1034
1102
  track(goal, props) {
1035
1103
  if (disabled) return;
1036
- if (!config.goals.some((g) => g.key === goal)) {
1037
- warn(`goal "${goal}" is not declared in splithub.config.ts; sending anyway.`);
1038
- }
1039
- if (cloudIdle) {
1040
- hold(`g:${goal}`, "goal", `${goal} not sent: no experiment is running in this project yet`);
1041
- devNote("idle", `No experiment is running in project "${config.project}", so goals and exposures are not sent. Start one with npx splithub start <id> or in the dashboard.`);
1042
- return;
1043
- }
1044
- const event = { id: newId("g_"), type: "goal", goal, vid: visitorId, sid: sessionId, ts: Date.now(), url: currentUrl(), ...props ? { props } : {} };
1045
- debugLog("goal", `${goal}${props ? " " + JSON.stringify(props) : ""}`, event);
1046
- queue.push(event);
1104
+ if (pending) waiting.push({ goal, ...props ? { props } : {}, ts: Date.now() });
1105
+ else sendGoal(goal, props, Date.now());
1047
1106
  },
1048
1107
  pageview(path) {
1049
1108
  const current = path ?? (browser ? location.pathname : void 0);
1050
1109
  if (!current) return;
1110
+ if (pending) {
1111
+ const ts = Date.now();
1112
+ void ready.then(() => {
1113
+ if (disabled) return;
1114
+ for (const goal of config.goals) if (goal.type === "pageview" && matchPath(goal, current)) sendGoal(goal.key, void 0, ts);
1115
+ });
1116
+ return;
1117
+ }
1051
1118
  for (const goal of config.goals) {
1052
1119
  if (goal.type === "pageview" && matchPath(goal, current)) {
1053
1120
  debugLog("pageview", `${current} matches goal ${goal.key}`);
@@ -1082,6 +1149,21 @@ function createClient(config, options = {}) {
1082
1149
  }
1083
1150
  return client;
1084
1151
  }
1152
+ function withTimeout(p, ms) {
1153
+ return new Promise((resolve) => {
1154
+ const t = setTimeout(() => resolve(null), ms);
1155
+ p.then(
1156
+ (v) => {
1157
+ clearTimeout(t);
1158
+ resolve(v);
1159
+ },
1160
+ () => {
1161
+ clearTimeout(t);
1162
+ resolve(null);
1163
+ }
1164
+ );
1165
+ });
1166
+ }
1085
1167
  function matchPath(goal, path) {
1086
1168
  if (!goal.path) return false;
1087
1169
  if (goal.path.endsWith("*")) return path.startsWith(goal.path.slice(0, -1));
@@ -1107,6 +1189,7 @@ function warnUnknown(key) {
1107
1189
  MVT_MAX_FACTORS,
1108
1190
  MVT_MAX_LEVELS,
1109
1191
  REMOTE_TTL_MS,
1192
+ REMOTE_WAIT_MS,
1110
1193
  SDK_VERSION,
1111
1194
  TARGET_FIELDS,
1112
1195
  TARGET_OPS,