@splithub/core 0.2.2 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.cts CHANGED
@@ -1,5 +1,5 @@
1
- import { S as SplitHubConfigInput, a as SplitHubConfig, E as Experiment, V as Variant, F as Factor, T as TargetingContext, A as Assignment, b as Flow, c as TargetCondition, d as TargetField, e as TargetOp, f as EventBatch, g as SplitHubEvent, h as ExperimentStatus, G as Goal, H as Holdout } from './types-DiW3b8D4.cjs';
2
- export { n as ComponentExperimentInput, C as ComponentVariantInput, l as ExperimentBase, q as ExperimentInput, i as ExperimentKind, t as ExperimentMetrics, u as ExposureEvent, k as FlowNode, v as GoalEvent, r as GoalInput, m as GuardrailInput, M as MvtExperimentInput, p as RedirectExperimentInput, R as RedirectVariantInput, s as StorageInput, o as ValueExperimentInput, j as ValueVariantInput } from './types-DiW3b8D4.cjs';
1
+ import { S as SplitHubConfigInput, a as SplitHubConfig, E as Experiment, V as Variant, F as Factor, T as TargetingContext, A as Assignment, b as Flow, c as TargetCondition, d as TargetField, e as TargetOp, f as EventBatch, g as SplitHubEvent, h as ExperimentStatus, G as Goal, H as Holdout } from './types-DlycK6Py.cjs';
2
+ export { n as ComponentExperimentInput, C as ComponentVariantInput, l as ExperimentBase, q as ExperimentInput, i as ExperimentKind, t as ExperimentMetrics, u as ExposureEvent, k as FlowNode, v as GoalEvent, r as GoalInput, m as GuardrailInput, M as MvtExperimentInput, p as RedirectExperimentInput, R as RedirectVariantInput, s as StorageInput, o as ValueExperimentInput, j as ValueVariantInput } from './types-DlycK6Py.cjs';
3
3
 
4
4
  declare class ConfigError extends Error {
5
5
  constructor(message: string);
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { S as SplitHubConfigInput, a as SplitHubConfig, E as Experiment, V as Variant, F as Factor, T as TargetingContext, A as Assignment, b as Flow, c as TargetCondition, d as TargetField, e as TargetOp, f as EventBatch, g as SplitHubEvent, h as ExperimentStatus, G as Goal, H as Holdout } from './types-DiW3b8D4.js';
2
- export { n as ComponentExperimentInput, C as ComponentVariantInput, l as ExperimentBase, q as ExperimentInput, i as ExperimentKind, t as ExperimentMetrics, u as ExposureEvent, k as FlowNode, v as GoalEvent, r as GoalInput, m as GuardrailInput, M as MvtExperimentInput, p as RedirectExperimentInput, R as RedirectVariantInput, s as StorageInput, o as ValueExperimentInput, j as ValueVariantInput } from './types-DiW3b8D4.js';
1
+ import { S as SplitHubConfigInput, a as SplitHubConfig, E as Experiment, V as Variant, F as Factor, T as TargetingContext, A as Assignment, b as Flow, c as TargetCondition, d as TargetField, e as TargetOp, f as EventBatch, g as SplitHubEvent, h as ExperimentStatus, G as Goal, H as Holdout } from './types-DlycK6Py.js';
2
+ export { n as ComponentExperimentInput, C as ComponentVariantInput, l as ExperimentBase, q as ExperimentInput, i as ExperimentKind, t as ExperimentMetrics, u as ExposureEvent, k as FlowNode, v as GoalEvent, r as GoalInput, m as GuardrailInput, M as MvtExperimentInput, p as RedirectExperimentInput, R as RedirectVariantInput, s as StorageInput, o as ValueExperimentInput, j as ValueVariantInput } from './types-DlycK6Py.js';
3
3
 
4
4
  declare class ConfigError extends Error {
5
5
  constructor(message: string);
package/dist/index.js CHANGED
@@ -69,7 +69,7 @@ import {
69
69
  runFlow,
70
70
  validateFlow,
71
71
  writeRemoteCache
72
- } from "./chunk-X6QEO4I4.js";
72
+ } from "./chunk-D4LRWPNH.js";
73
73
 
74
74
  // src/redirect.ts
75
75
  function decideRedirect(config, pathname, visitorId, context = {}, overrides = {}, explain) {
@@ -98,6 +98,11 @@ interface ExperimentBase {
98
98
  seed?: string;
99
99
  /** Free-form note shown in the dashboard and CLI. */
100
100
  description?: string;
101
+ /**
102
+ * Human name shown in the dashboard and CLI instead of the key (up to 80 characters). Rename
103
+ * freely: the key stays, and with it the assignment and the collected data.
104
+ */
105
+ name?: string;
101
106
  /**
102
107
  * Opt-in runtime minimum: days of data (24-hour periods since the first exposure) before a
103
108
  * verdict, integer 0..30. Default 0: verdicts depend on sample size, not runtime.
@@ -244,6 +249,8 @@ interface Experiment {
244
249
  goal: string | null;
245
250
  seed: string;
246
251
  description: string | null;
252
+ /** Human name; absent = show the key. */
253
+ name?: string;
247
254
  match: string | null;
248
255
  /** Ordered: the first variant is the control. */
249
256
  variants: Variant[];
@@ -98,6 +98,11 @@ interface ExperimentBase {
98
98
  seed?: string;
99
99
  /** Free-form note shown in the dashboard and CLI. */
100
100
  description?: string;
101
+ /**
102
+ * Human name shown in the dashboard and CLI instead of the key (up to 80 characters). Rename
103
+ * freely: the key stays, and with it the assignment and the collected data.
104
+ */
105
+ name?: string;
101
106
  /**
102
107
  * Opt-in runtime minimum: days of data (24-hour periods since the first exposure) before a
103
108
  * verdict, integer 0..30. Default 0: verdicts depend on sample size, not runtime.
@@ -244,6 +249,8 @@ interface Experiment {
244
249
  goal: string | null;
245
250
  seed: string;
246
251
  description: string | null;
252
+ /** Human name; absent = show the key. */
253
+ name?: string;
247
254
  match: string | null;
248
255
  /** Ordered: the first variant is the control. */
249
256
  variants: Variant[];
package/dist/vite.cjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/vite.ts","../src/config.ts","../src/remote.ts","../src/client.ts"],"sourcesContent":["// Vite plugin: SplitHub notes in the terminal that runs `vite` / `npm run dev`.\n//\n// // vite.config.ts\n// import { splithub } from '@splithub/core/vite';\n// export default defineConfig({ plugins: [react(), splithub()] });\n//\n// On start and on every save of splithub.config.ts it prints what each\n// experiment does in development (draft hidden or shown, running, paused,\n// started from the dashboard). The SDK's development notes from the browser\n// (\"this visitor got control\", \"events held back\") are forwarded here too,\n// once per message until the config changes. Dev server only; builds are untouched.\n//\n// Vite's types are described structurally so @splithub/core keeps zero dependencies.\n\nimport { CLOUD_ENDPOINT } from './client';\nimport { isSplitHubConfig } from './config';\nimport { applyRemoteOverrides, fetchRemoteOverrides, resolveOverridesUrl } from './remote';\nimport type { Experiment, SplitHubConfig } from './types';\n\ninterface Logger {\n info(message: string, options?: { timestamp?: boolean }): void;\n}\ninterface DevServer {\n config: { root: string; logger: Logger };\n httpServer: { once(event: 'listening', listener: () => void): unknown } | null;\n ssrLoadModule(url: string): Promise<Record<string, unknown>>;\n ws: { on(event: string, listener: (data: unknown) => void): void };\n}\ninterface HotContext {\n file: string;\n server: DevServer;\n}\nexport interface SplitHubVitePlugin {\n name: string;\n apply: 'serve';\n configureServer(server: DevServer): void;\n handleHotUpdate(ctx: HotContext): void;\n resolveId(id: string): string | undefined;\n load(id: string): string | undefined;\n transformIndexHtml(): Array<{ tag: string; attrs: Record<string, string>; injectTo: 'head-prepend' }>;\n}\n\nexport interface SplitHubViteOptions {\n /** Path of the config, relative to the Vite root. Default: splithub.config.ts, .js or .mjs. */\n config?: string;\n /** Print the experiment summary on start and on config changes. Default true. */\n summary?: boolean;\n /** Forward the SDK's development notes from the browser. Default true. */\n browserNotes?: boolean;\n}\n\nconst VIRTUAL = 'virtual:splithub-dev';\nconst RESOLVED = '\\0' + VIRTUAL;\nconst CANDIDATES = ['splithub.config.ts', 'splithub.config.js', 'splithub.config.mjs'];\nconst tag = (s: string) => `\\x1b[36m[splithub]\\x1b[39m ${s}`;\nconst dim = (s: string) => `\\x1b[2m${s}\\x1b[22m`;\n\n// The browser side: the SDK announces notes as a window event; this sends them to the\n// dev server and tells the SDK that the terminal has them, so the browser console stays quiet.\nconst CLIENT = `if (import.meta.hot) {\n window.__splithubTerminal = true;\n window.addEventListener('splithub:dev', (e) => import.meta.hot.send('splithub:note', e.detail));\n}`;\n\n/** One line per experiment, in the words a developer needs. `live` is the experiment after dashboard changes. */\nexport function describeExperiment(config: SplitHubConfig, e: Experiment, live?: Experiment): string {\n const changed = live && live.status !== e.status ? live.status : null;\n const status = changed ?? e.status;\n const second = e.variants[1]?.key ?? 'variant';\n if (status === 'running') return `${e.key}: running${changed ? ' (started from the dashboard)' : ''}`;\n if (status === 'draft') {\n return config.runDraftsInDev\n ? `${e.key}: draft, shown here as if running; visitors see it after ${dim(`npx splithub start ${e.key}`)}`\n : `${e.key}: draft, everyone sees the control, here too; add runDraftsInDev: true or open ${dim(`?sh_force=${e.key}:${second}`)}`;\n }\n return `${e.key}: ${status}${changed ? ' from the dashboard' : ''}, everyone sees the control`;\n}\n\nasync function liveConfig(config: SplitHubConfig): Promise<SplitHubConfig | null> {\n if (config.storage.mode !== 'cloud' || !config.storage.key) return null;\n const url = resolveOverridesUrl(config.storage.endpoint ?? CLOUD_ENDPOINT, config.storage.key);\n const timeout = new Promise<null>((resolve) => setTimeout(() => resolve(null), 3000));\n const overrides = await Promise.race([fetchRemoteOverrides(url), timeout]);\n return overrides ? applyRemoteOverrides(config, overrides) : null;\n}\n\nexport function splithub(options: SplitHubViteOptions = {}): SplitHubVitePlugin {\n const seen = new Set<string>();\n let configPath: string | null = null;\n\n async function load(server: DevServer): Promise<SplitHubConfig | null> {\n for (const file of options.config ? [options.config] : CANDIDATES) {\n const path = file.replace(/^\\.?\\//, '');\n try {\n const mod = await server.ssrLoadModule(`/${path}`);\n if (isSplitHubConfig(mod.default)) {\n configPath = path;\n return mod.default;\n }\n } catch {\n // not this file, or it does not compile right now: try the next one\n }\n }\n return null;\n }\n\n async function summary(server: DevServer): Promise<void> {\n if (options.summary === false) return;\n const log = server.config.logger;\n const config = await load(server);\n if (!config) {\n log.info(tag('no splithub.config.ts found; run npx splithub init'), { timestamp: true });\n return;\n }\n const live = await liveConfig(config).catch(() => null);\n const mode = config.storage.mode === 'cloud' ? (config.storage.key ? 'cloud' : 'cloud, no public key yet') : 'self-hosted';\n const count = `${config.experiments.length} experiment${config.experiments.length === 1 ? '' : 's'}`;\n log.info(tag(`${config.project} · ${mode} · ${count}${config.runDraftsInDev ? ' · drafts run in development' : ''}`), { timestamp: true });\n for (const e of config.experiments) log.info(tag(` ${describeExperiment(config, e, live?.experiments.find((x) => x.key === e.key))}`));\n if (config.storage.mode === 'cloud') {\n log.info(tag(dim(' development sends nothing to the cloud; deployed builds do')));\n if (!(live ?? config).experiments.some((e) => e.status === 'running')) log.info(tag(dim(' nothing is running yet, so deployed builds record nothing either')));\n }\n }\n\n return {\n name: 'splithub',\n apply: 'serve',\n configureServer(server) {\n if (options.browserNotes !== false) {\n server.ws.on('splithub:note', (data) => {\n if (typeof data !== 'string' || seen.has(data)) return;\n seen.add(data);\n server.config.logger.info(tag(data), { timestamp: true });\n });\n }\n const start = () => void summary(server);\n if (server.httpServer) server.httpServer.once('listening', start);\n else start();\n },\n handleHotUpdate({ file, server }) {\n if (!configPath || !file.replace(/\\\\/g, '/').endsWith(`/${configPath}`)) return;\n seen.clear();\n void summary(server);\n },\n resolveId(id) {\n return id === VIRTUAL ? RESOLVED : undefined;\n },\n load(id) {\n if (id !== RESOLVED) return undefined;\n return options.browserNotes === false ? '' : CLIENT;\n },\n transformIndexHtml() {\n return [{ tag: 'script', attrs: { type: 'module', src: `/@id/${VIRTUAL}` }, injectTo: 'head-prepend' }];\n },\n };\n}\n","import { validateFlow } from './targeting';\nimport type {\n Experiment,\n ExperimentInput,\n ExperimentMetrics,\n Holdout,\n Factor,\n Goal,\n SplitHubConfig,\n SplitHubConfigInput,\n Variant,\n} from './types';\n\nconst KEY_PATTERN = /^[a-z0-9][a-z0-9_-]{0,63}$/;\n\nexport class ConfigError extends Error {\n constructor(message: string) {\n super(`[splithub] ${message}`);\n this.name = 'ConfigError';\n }\n}\n\nfunction assertKey(kind: string, key: string): void {\n if (!KEY_PATTERN.test(key)) {\n throw new ConfigError(\n `${kind} key \"${key}\" is invalid. Use lowercase letters, digits, \"-\" and \"_\" (max 64 chars).`\n );\n }\n}\n\nexport const MVT_MAX_FACTORS = 4;\nexport const MVT_MAX_LEVELS = 4;\nexport const MVT_MAX_COMBINATIONS = 16;\n\n/**\n * Every combination of the factors' levels as a variant, in order (first levels\n * first, so the all-control combination is the control), equal weights. The\n * variant's `value` is `{ factor: levelValue }`, what `useValue()` returns.\n */\nexport function mvtVariants(expKey: string, factors: Record<string, Record<string, unknown>>): { variants: Variant[]; factors: Factor[] } {\n const list: Factor[] = [];\n const valuesOf = new Map<string, Record<string, unknown>>();\n for (const [key, levels] of Object.entries(factors ?? {})) {\n assertKey('factor', key);\n const levelKeys = Object.keys(levels ?? {});\n if (levelKeys.length < 2) throw new ConfigError(`experiment \"${expKey}\", factor \"${key}\": needs at least 2 levels.`);\n if (levelKeys.length > MVT_MAX_LEVELS) throw new ConfigError(`experiment \"${expKey}\", factor \"${key}\": at most ${MVT_MAX_LEVELS} levels.`);\n for (const l of levelKeys) assertKey('level', l);\n list.push({ key, levels: levelKeys });\n valuesOf.set(key, levels);\n }\n if (list.length === 0) throw new ConfigError(`experiment \"${expKey}\": mvt experiments need \"factors\".`);\n if (list.length > MVT_MAX_FACTORS) throw new ConfigError(`experiment \"${expKey}\": at most ${MVT_MAX_FACTORS} factors.`);\n let combos: Array<Record<string, string>> = [{}];\n for (const f of list) combos = combos.flatMap((c) => f.levels.map((l) => ({ ...c, [f.key]: l })));\n if (combos.length > MVT_MAX_COMBINATIONS) throw new ConfigError(`experiment \"${expKey}\": ${combos.length} combinations; at most ${MVT_MAX_COMBINATIONS}.`);\n const variants: Variant[] = combos.map((levels) => ({\n key: list.map((f) => levels[f.key]).join('-'),\n weight: 1 / combos.length,\n value: Object.fromEntries(list.map((f) => [f.key, valuesOf.get(f.key)![levels[f.key]!]])),\n levels,\n }));\n return { variants, factors: list };\n}\n\nfunction normalizeVariants(expKey: string, input: ExperimentInput): Variant[] {\n if (input.kind === 'mvt') return mvtVariants(expKey, input.factors).variants;\n const entries = Object.entries(input.variants);\n if (entries.length < 2) {\n throw new ConfigError(`experiment \"${expKey}\" needs at least 2 variants.`);\n }\n const raw = entries.map(([key, v]) => {\n assertKey('variant', key);\n const weight = typeof v === 'number' ? v : v.weight;\n if (!Number.isFinite(weight) || weight < 0) {\n throw new ConfigError(`experiment \"${expKey}\", variant \"${key}\": weight must be a non-negative number.`);\n }\n const variant: Variant = { key, weight };\n const obj = typeof v === 'object' ? (v as Record<string, unknown>) : {};\n if (input.kind === 'value') variant.value = obj.value;\n if (input.kind === 'redirect') variant.to = String(obj.to ?? '');\n return variant;\n });\n const total = raw.reduce((s, v) => s + v.weight, 0);\n if (total <= 0) {\n throw new ConfigError(`experiment \"${expKey}\": variant weights sum to 0.`);\n }\n return raw.map((v) => ({ ...v, weight: v.weight / total }));\n}\n\n/** Reserved experiment key of the holdout comparison (never a valid config key: keys start with a letter or digit). */\nexport const HOLDOUT_KEY = '__holdout';\n/** Buckets per layer: an experiment's `layer.range` is a slice of 0..LAYER_BUCKETS. */\nexport const LAYER_BUCKETS = 100;\n\nfunction normalizeMetrics(key: string, input: ExperimentInput, goals: Goal[]): ExperimentMetrics | undefined {\n const m = input.metrics;\n if (!m) return undefined;\n if (!input.goal) throw new ConfigError(`experiment \"${key}\": metrics need a primary \"goal\" too.`);\n const seen = new Set<string>([input.goal]);\n const check = (goal: unknown, where: string): string => {\n 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\".`);\n if (seen.has(goal)) throw new ConfigError(`experiment \"${key}\": goal \"${goal}\" is listed twice (primary goal and metrics count once each).`);\n seen.add(goal);\n return goal;\n };\n const secondary = (m.secondary ?? []).map((g) => check(g, 'secondary'));\n const guardrails = (m.guardrails ?? []).map((g) => {\n const obj = typeof g === 'string' ? { goal: g } : g;\n const worse = obj.worse ?? 'lower';\n if (worse !== 'lower' && worse !== 'higher') throw new ConfigError(`experiment \"${key}\": guardrail \"${obj.goal}\": worse must be \"lower\" or \"higher\".`);\n return { goal: check(obj.goal, 'guardrails'), worse };\n });\n if (secondary.length === 0 && guardrails.length === 0) return undefined;\n return { secondary, guardrails };\n}\n\nfunction normalizeLayer(key: string, input: ExperimentInput, layers: Record<string, unknown>): Experiment['layer'] {\n const l = input.layer;\n if (!l) return undefined;\n if (!l.key || !(l.key in layers)) throw new ConfigError(`experiment \"${key}\": layer \"${String(l.key)}\" is not declared in \"layers\".`);\n const [start, end] = Array.isArray(l.range) ? l.range : [NaN, NaN];\n const ok = (n: unknown) => typeof n === 'number' && Number.isInteger(n) && n >= 0 && n <= LAYER_BUCKETS;\n 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}.`);\n return { key: l.key, range: [start!, end!] };\n}\n\n/** Two experiments of one layer that are not finished must not claim the same bucket. */\nfunction assertNoOverlap(experiments: Experiment[]): void {\n const live = experiments.filter((e) => e.layer && e.status !== 'finished');\n for (let i = 0; i < live.length; i++) {\n for (let j = i + 1; j < live.length; j++) {\n const a = live[i]!;\n const b = live[j]!;\n if (a.layer!.key !== b.layer!.key) continue;\n if (a.layer!.range[0] < b.layer!.range[1] && b.layer!.range[0] < a.layer!.range[1]) {\n 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.`);\n }\n }\n }\n}\n\nfunction normalizeHoldout(input: SplitHubConfigInput, goals: Goal[]): Holdout | null {\n const h = input.holdout;\n if (!h) return null;\n 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.');\n if (h.goal && !goals.some((g) => g.key === h.goal)) throw new ConfigError(`holdout.goal \"${h.goal}\" is not declared in \"goals\".`);\n if (h.percent === 0) return null;\n return { percent: h.percent, seed: h.seed ?? HOLDOUT_KEY, goal: h.goal ?? goals[0]?.key ?? null };\n}\n\nfunction normalizeExperiment(key: string, input: ExperimentInput, goals: Goal[], layers: Record<string, unknown> = {}): Experiment {\n assertKey('experiment', key);\n const traffic = input.traffic ?? 1;\n if (traffic < 0 || traffic > 1) {\n throw new ConfigError(`experiment \"${key}\": traffic must be between 0 and 1.`);\n }\n if (input.goal && !goals.some((g) => g.key === input.goal)) {\n throw new ConfigError(`experiment \"${key}\": goal \"${input.goal}\" is not declared in \"goals\".`);\n }\n if (input.kind === 'redirect' && !input.match) {\n throw new ConfigError(`experiment \"${key}\": redirect experiments need \"match\".`);\n }\n if (input.maxExposures !== undefined && (!Number.isFinite(input.maxExposures) || input.maxExposures < 1)) {\n throw new ConfigError(`experiment \"${key}\": maxExposures must be a positive number.`);\n }\n if (input.minDays !== undefined && !(Number.isInteger(input.minDays) && input.minDays >= 0 && input.minDays <= 30)) {\n throw new ConfigError(`experiment \"${key}\": minDays must be a whole number from 0 to 30.`);\n }\n if (input.goodSample !== undefined && !(Number.isInteger(input.goodSample) && input.goodSample >= 100 && input.goodSample <= 10_000_000)) {\n throw new ConfigError(`experiment \"${key}\": goodSample must be a whole number from 100 to 10,000,000.`);\n }\n for (const [k, v] of Object.entries(input.schedule ?? {})) {\n if (v !== undefined && Number.isNaN(Date.parse(v))) throw new ConfigError(`experiment \"${key}\": schedule.${k} must be an ISO date.`);\n }\n const variants = normalizeVariants(key, input);\n const metrics = normalizeMetrics(key, input, goals);\n const layer = normalizeLayer(key, input, layers);\n if (input.flow) {\n const problem = validateFlow(input.flow, variants.map((v) => v.key));\n if (problem) throw new ConfigError(`experiment \"${key}\": flow: ${problem}`);\n }\n return {\n key,\n kind: input.kind,\n status: input.status,\n traffic,\n goal: input.goal ?? null,\n seed: input.seed ?? key,\n description: input.description ?? null,\n match: input.kind === 'redirect' ? input.match : null,\n variants,\n ...(input.kind === 'mvt' ? { factors: mvtVariants(key, input.factors).factors } : {}),\n ...(input.flow ? { flow: input.flow } : {}),\n ...(metrics ? { metrics } : {}),\n ...(layer ? { layer } : {}),\n ...(input.minDays !== undefined ? { minDays: input.minDays } : {}),\n ...(input.goodSample !== undefined ? { goodSample: input.goodSample } : {}),\n ...(input.maxExposures ? { maxExposures: Math.floor(input.maxExposures) } : {}),\n ...(input.schedule && (input.schedule.startAt || input.schedule.endAt) ? { schedule: { startAt: input.schedule.startAt ?? null, endAt: input.schedule.endAt ?? null } } : {}),\n };\n}\n\n/**\n * Validate and normalize a config. Call it once in `splithub.config.ts`:\n *\n * ```ts\n * export default defineConfig({ project: 'my-app', storage: { mode: 'self', endpoint: '/api/splithub' }, experiments: { ... } });\n * ```\n */\nexport function defineConfig(input: SplitHubConfigInput): SplitHubConfig {\n if (!input || typeof input !== 'object') throw new ConfigError('config must be an object.');\n if (!input.project) throw new ConfigError('\"project\" is required.');\n if (!input.storage || !('mode' in input.storage)) throw new ConfigError('\"storage.mode\" is required.');\n if (input.storage.mode === 'self' && !input.storage.endpoint) {\n throw new ConfigError('\"storage.endpoint\" is required in self mode.');\n }\n\n const goals: Goal[] = Object.entries(input.goals ?? {}).map(([key, g]) => {\n assertKey('goal', key);\n return {\n key,\n type: g.type,\n path: g.type === 'pageview' ? g.path : null,\n selector: g.type === 'click' ? g.selector : null,\n revenue: g.type === 'event' ? Boolean(g.revenue) : false,\n description: g.description ?? null,\n };\n });\n\n const layers: Record<string, { seed: string }> = {};\n for (const [key, l] of Object.entries(input.layers ?? {})) {\n assertKey('layer', key);\n layers[key] = { seed: l?.seed ?? key };\n }\n const experiments = Object.entries(input.experiments ?? {}).map(([key, exp]) =>\n normalizeExperiment(key, exp, goals, layers)\n );\n assertNoOverlap(experiments);\n const holdout = normalizeHoldout(input, goals);\n\n return {\n project: input.project,\n storage: input.storage,\n visitorKey: input.visitorKey ?? 'sh_vid',\n runDraftsInDev: input.runDraftsInDev === true,\n goals,\n experiments,\n ...(Object.keys(layers).length ? { layers } : {}),\n ...(holdout ? { holdout } : {}),\n __splithub: 2,\n };\n}\n\nexport function isSplitHubConfig(value: unknown): value is SplitHubConfig {\n return Boolean(value) && typeof value === 'object' && (value as SplitHubConfig).__splithub === 2;\n}\n\nexport function getExperiment(config: SplitHubConfig, key: string): Experiment | undefined {\n return config.experiments.find((e) => e.key === key);\n}\n\n/**\n * The holdout read as an experiment, for results: `holdout` (the control: no test\n * changed anything for them) against `enrolled`, weighted by the holdout share.\n * Every declared goal but the primary is a secondary metric. Null without a holdout.\n */\nexport function holdoutExperiment(config: Pick<SplitHubConfig, 'holdout' | 'goals'>): Experiment | null {\n const h = config.holdout;\n if (!h) return null;\n const share = h.percent / 100;\n const secondary = config.goals.map((g) => g.key).filter((g) => g !== h.goal);\n return {\n key: HOLDOUT_KEY,\n kind: 'component',\n status: 'running',\n traffic: 1,\n goal: h.goal,\n seed: h.seed,\n description: `Holdout: ${h.percent}% of visitors see no test at all`,\n match: null,\n variants: [\n { key: 'holdout', weight: share },\n { key: 'enrolled', weight: 1 - share },\n ],\n ...(h.goal && secondary.length ? { metrics: { secondary, guardrails: [] } } : {}),\n };\n}\n\n/**\n * Which goals each experiment measures, for stores that attribute at ingest (the\n * cloud): `goals` is the primary goal, `metrics` the secondary and guardrail goals.\n * Includes `__holdout` when the config has a holdout.\n */\nexport function measuredGoals(config: Pick<SplitHubConfig, 'experiments' | 'holdout' | 'goals'>): { goals: Record<string, string | null>; metrics: Record<string, string[]> } {\n const goals: Record<string, string | null> = {};\n const metrics: Record<string, string[]> = {};\n const all = [...config.experiments];\n const h = holdoutExperiment(config);\n if (h) all.push(h);\n for (const e of all) {\n goals[e.key] = e.goal ?? null;\n const extra = [...(e.metrics?.secondary ?? []), ...(e.metrics?.guardrails ?? []).map((g) => g.goal)];\n if (extra.length) metrics[e.key] = extra;\n }\n return { goals, metrics };\n}\n","import type { Experiment, ExperimentStatus, Goal, Holdout, SplitHubConfig, TargetingContext } from './types';\n\n/**\n * Remote overrides let the dashboard, the CLI or an agent pause an experiment,\n * change traffic/weights or swap `value` payloads without a deploy. The\n * config file stays the source of truth for the next deploy; overrides are a\n * live patch on top of it.\n */\nexport interface ExperimentOverride {\n status?: ExperimentStatus;\n traffic?: number;\n /** Relative weights by variant key; unknown keys are ignored. */\n weights?: Record<string, number>;\n /** `value` payloads by variant key (value experiments only). */\n values?: Record<string, unknown>;\n seed?: string;\n}\n\nexport interface RemoteOverrides {\n version: number;\n experiments: Record<string, ExperimentOverride>;\n /** Experiments created in the dashboard that are not in the config file yet (hosted config). */\n added?: Experiment[];\n /** Goals declared in the dashboard (hosted config). */\n goals?: Goal[];\n /**\n * Holdout and layer seeds of the hosted config (sites on sh.js have no config file).\n * A config file's own `holdout` / `layers` win over these.\n */\n holdout?: Holdout | null;\n layers?: Record<string, { seed: string }>;\n /** What the cloud knows about this request: country, region, city. Per visitor. */\n ctx?: Pick<TargetingContext, 'country' | 'region' | 'city' | 'timezone'>;\n}\n\nexport const EMPTY_OVERRIDES: RemoteOverrides = { version: 0, experiments: {} };\n\nfunction applyToExperiment(experiment: Experiment, o: ExperimentOverride): Experiment {\n let variants = experiment.variants;\n if (o.weights) {\n const raw = variants.map((v) => ({ ...v, weight: Math.max(0, o.weights![v.key] ?? v.weight) }));\n const total = raw.reduce((s, v) => s + v.weight, 0);\n if (total > 0) variants = raw.map((v) => ({ ...v, weight: v.weight / total }));\n }\n if (o.values && experiment.kind === 'value') {\n variants = variants.map((v) => (v.key in o.values! ? { ...v, value: o.values![v.key] } : v));\n }\n return {\n ...experiment,\n status: o.status ?? experiment.status,\n traffic: o.traffic !== undefined && o.traffic >= 0 && o.traffic <= 1 ? o.traffic : experiment.traffic,\n seed: o.seed ?? experiment.seed,\n variants,\n };\n}\n\n/** Pure merge: returns a new config, never mutates the input. */\nexport function applyRemoteOverrides(config: SplitHubConfig, overrides: RemoteOverrides | null | undefined): SplitHubConfig {\n if (!overrides) return config;\n const patches = overrides.experiments ?? {};\n const known = new Set(config.experiments.map((e) => e.key));\n const added = (overrides.added ?? []).filter((e) => e && typeof e.key === 'string' && !known.has(e.key) && Array.isArray(e.variants) && e.variants.length >= 2);\n const knownGoals = new Set(config.goals.map((g) => g.key));\n const addedGoals = (overrides.goals ?? []).filter((g) => g && typeof g.key === 'string' && !knownGoals.has(g.key));\n const holdout = !config.holdout && validHoldout(overrides.holdout) ? overrides.holdout : null;\n const layers = overrides.layers && typeof overrides.layers === 'object' ? { ...overrides.layers, ...(config.layers ?? {}) } : null;\n if (Object.keys(patches).length === 0 && added.length === 0 && addedGoals.length === 0 && !holdout && !layers) return config;\n const merged = [...config.experiments, ...added.map((e) => ({ ...e, origin: 'dashboard' as const }))];\n return {\n ...config,\n ...(holdout ? { holdout } : {}),\n ...(layers ? { layers } : {}),\n goals: addedGoals.length ? [...config.goals, ...addedGoals] : config.goals,\n experiments: merged.map((e) => {\n const o = patches[e.key];\n return o ? applyToExperiment(e, o) : e;\n }),\n };\n}\n\nfunction validHoldout(h: Holdout | null | undefined): h is Holdout {\n return Boolean(h) && typeof h!.percent === 'number' && h!.percent > 0 && h!.percent <= 50 && typeof h!.seed === 'string';\n}\n\nexport function isRemoteOverrides(value: unknown): value is RemoteOverrides {\n return Boolean(value) && typeof value === 'object' && typeof (value as RemoteOverrides).version === 'number' && typeof (value as RemoteOverrides).experiments === 'object';\n}\n\n/** `https://go.splithub.io/v1/events` → `https://go.splithub.io/v1/overrides/<pk>.json` */\nexport function resolveOverridesUrl(eventsEndpoint: string, publicKey: string): string {\n const base = eventsEndpoint.replace(/\\/events\\/?$/, '');\n return `${base}/overrides/${encodeURIComponent(publicKey)}.json`;\n}\n\n// ---------------------------------------------------------------------------\n// Browser cache: overrides are applied synchronously from cache on page load\n// (no flicker) and refreshed in the background for the next load.\n// ---------------------------------------------------------------------------\n\ninterface CacheEntry {\n fetchedAt: number;\n overrides: RemoteOverrides;\n}\n\nexport const REMOTE_CACHE_KEY = 'sh_remote';\nexport const REMOTE_TTL_MS = 60_000;\n\nfunction storage(): Storage | null {\n try {\n if (typeof window === 'undefined' || !window.localStorage) return null;\n return window.localStorage;\n } catch {\n return null;\n }\n}\n\nexport function readRemoteCache(publicKey: string): CacheEntry | null {\n try {\n const raw = storage()?.getItem(`${REMOTE_CACHE_KEY}:${publicKey}`);\n if (!raw) return null;\n const parsed = JSON.parse(raw) as CacheEntry;\n return isRemoteOverrides(parsed.overrides) && typeof parsed.fetchedAt === 'number' ? parsed : null;\n } catch {\n return null;\n }\n}\n\nexport function writeRemoteCache(publicKey: string, overrides: RemoteOverrides): void {\n try {\n storage()?.setItem(`${REMOTE_CACHE_KEY}:${publicKey}`, JSON.stringify({ fetchedAt: Date.now(), overrides } satisfies CacheEntry));\n } catch {\n // storage unavailable\n }\n}\n\nexport async function fetchRemoteOverrides(url: string, fetchImpl: typeof fetch = fetch): Promise<RemoteOverrides | null> {\n try {\n const res = await fetchImpl(url, { cache: 'no-cache' });\n if (!res.ok) return null;\n const body = (await res.json()) as unknown;\n return isRemoteOverrides(body) ? body : null;\n } catch {\n return null;\n }\n}\n","import { assign, countsForHoldout, holdoutGroup, isDevEnvironment, parseForceParam } from './assignment';\nimport { debugLog, isDebug } from './debug';\nimport { devNote, explainAssignment } from './dev';\nimport { getExperiment, HOLDOUT_KEY, isSplitHubConfig } from './config';\nimport { EventQueue, createFetchTransport, type Transport } from './events';\nimport { newId } from './ids';\nimport {\n applyRemoteOverrides,\n fetchRemoteOverrides,\n readRemoteCache,\n REMOTE_TTL_MS,\n resolveOverridesUrl,\n writeRemoteCache,\n type RemoteOverrides,\n} from './remote';\nimport { matchPath } from './paths';\nimport { browserContext } from './targeting';\nimport type { Assignment, Experiment, SplitHubConfig, TargetingContext, Variant } from './types';\nimport {\n getOrCreateSessionId,\n getOrCreateVisitorId,\n hasVisitorId,\n isBrowser,\n persistExposureSet,\n sessionExposureSet,\n} from './visitor';\n\n// The drop-in script's build defines this as true, so `typeof` folds and the development\n// notes (strings included) drop out of sh.js. It has to be written inline at each use:\n// a constant imported from another module is inlined too late to remove the dead branch.\ndeclare const __SPLITHUB_LITE__: true | undefined;\n\nexport const SDK_VERSION = '0.1.0';\n/** First visit without cached overrides: the longest the client waits for them. The fetch usually takes ~150 ms. */\nexport const REMOTE_WAIT_MS = 400;\nconst DEV_NOTE = 'Development sends nothing to the cloud, so your own visits never reach the results. Deployed builds send as usual.';\nexport const CLOUD_ENDPOINT = 'https://go.splithub.io/v1/events';\n\nexport interface ClientOptions {\n /** Provide on the server (from the cookie) so SSR and client agree. */\n visitorId?: string;\n sessionId?: string;\n /** Custom transport, e.g. a no-op for tests or SSR. */\n transport?: Transport;\n /**\n * Send the cloud key as `?key=` so page-hide batches can use `navigator.sendBeacon`.\n * On by default for SplitHub Cloud (the key is public); off for a custom endpoint,\n * which may not read the key from the query.\n */\n keyInQuery?: boolean;\n /** Force variants, merged with `?sh_force=` in the browser. */\n overrides?: Record<string, string>;\n /** Disable all network activity (SSR, tests, `status: draft` previews). */\n disabled?: boolean;\n /**\n * Remote overrides (cloud mode): pause, traffic, weights and values changed\n * from the dashboard/CLI without a deploy. Cached in localStorage and\n * applied synchronously on later page loads. A first visit has no cache, so\n * the client waits up to `waitMs` for them, serving control meanwhile, then\n * decides once; a decided variant never changes mid-page.\n */\n remote?: {\n /** Apply these overrides now (SSR: pass what the server fetched). */\n overrides?: RemoteOverrides | null;\n /** Skip fetching. Default: fetch in cloud mode in the browser. */\n disabled?: boolean;\n url?: string;\n ttlMs?: number;\n /** First visit (nothing cached): how long to wait for the overrides before deciding from the file. Default 400 ms; 0 decides at once. */\n waitMs?: number;\n };\n /**\n * Visitor context for targeting (country, device, UTM ...). In the browser it\n * is collected automatically and merged with the cloud's geo (`ctx` in the\n * overrides JSON); on the server pass what you know from the request.\n */\n context?: TargetingContext;\n onError?: (error: unknown) => void;\n}\n\nexport interface SplitHubClient {\n readonly config: SplitHubConfig;\n readonly visitorId: string;\n readonly sessionId: string;\n /** Targeting context used for assignments. */\n readonly context: TargetingContext;\n /**\n * True on a first visit in cloud mode while the dashboard's overrides are on\n * their way (at most `remote.waitMs`). Every experiment serves control and\n * events wait; then the client decides once and notifies subscribers.\n */\n readonly pending: boolean;\n /** Resolves once experiments are decided (at once unless `pending`). */\n readonly ready: Promise<void>;\n /** Called once when a pending client decides. Returns an unsubscribe function. */\n subscribe(listener: () => void): () => void;\n /** Assignment without side effects. */\n assignment(experimentKey: string): Assignment;\n /** Variant key (control when not in experiment). Records an exposure. */\n variant(experimentKey: string): string;\n /** Payload of a `value` experiment (control value when not in experiment). Records an exposure. */\n value<T = unknown>(experimentKey: string): T;\n /** Record an exposure explicitly (the React components call this on mount). */\n exposure(experimentKey: string): void;\n track(goal: string, props?: Record<string, unknown>): void;\n /** Automatic pageview goals for the current URL. */\n pageview(path?: string): void;\n /** Bind click goals (`type: 'click'`, CSS selector) to the document. Returns an unbind function. No-op outside the browser. */\n autoGoals(root?: Document | HTMLElement): () => void;\n flush(): Promise<void>;\n destroy(): void;\n}\n\nfunction resolveEndpoint(config: SplitHubConfig): { endpoint: string; key?: string } {\n if (config.storage.mode === 'self') return { endpoint: config.storage.endpoint };\n return { endpoint: config.storage.endpoint ?? CLOUD_ENDPOINT, key: config.storage.key };\n}\n\nexport function createClient(config: SplitHubConfig, options: ClientOptions = {}): SplitHubClient {\n if (!isSplitHubConfig(config)) {\n throw new Error('[splithub] pass the object returned by defineConfig() from splithub.config.ts');\n }\n\n const browser = isBrowser();\n\n // Remote overrides: apply the cached copy synchronously, refresh in the background.\n // A first visit has no cache: wait briefly for the fresh copy instead, so a test\n // paused or started in the dashboard is right from the first page.\n const base = config;\n const publicKey = config.storage.mode === 'cloud' ? config.storage.key : undefined;\n let effective = config;\n let geo: RemoteOverrides['ctx'] | undefined;\n let waitFor: Promise<RemoteOverrides | null> | null = null;\n if (options.remote?.overrides) {\n effective = applyRemoteOverrides(config, options.remote.overrides);\n geo = options.remote.overrides.ctx;\n } else if (browser && publicKey && !options.remote?.disabled) {\n const cached = readRemoteCache(publicKey);\n if (cached) {\n effective = applyRemoteOverrides(config, cached.overrides);\n geo = cached.overrides.ctx;\n debugLog('remote', `overrides v${cached.overrides.version} from cache (${Math.round((Date.now() - cached.fetchedAt) / 1000)} s old)`, { experiments: cached.overrides.experiments });\n }\n const stale = !cached || Date.now() - cached.fetchedAt > (options.remote?.ttlMs ?? REMOTE_TTL_MS);\n if (stale) {\n const url = options.remote?.url ?? resolveOverridesUrl(config.storage.endpoint ?? CLOUD_ENDPOINT, publicKey);\n const fetched = fetchRemoteOverrides(url).then((fresh) => {\n if (fresh) writeRemoteCache(publicKey, fresh);\n return fresh;\n });\n // `overrides: null` from the server (Next.js) means the HTML already follows the\n // file: waiting would make the first client render disagree with it.\n const waitMs = options.remote?.waitMs ?? REMOTE_WAIT_MS;\n if (!cached && waitMs > 0 && options.remote?.overrides === undefined) waitFor = withTimeout(fetched, waitMs);\n else {\n void fetched.then((fresh) => {\n if (fresh) debugLog('remote', `fresh overrides v${fresh.version} fetched; applied on the next page load`, { experiments: fresh.experiments });\n });\n }\n }\n }\n config = effective;\n\n const hadVisitor = browser && !options.visitorId ? hasVisitorId(config.visitorKey) : undefined;\n const visitorId = options.visitorId ?? (browser ? getOrCreateVisitorId(config.visitorKey) : 'server');\n // On the server without the visitor's id, any variant would be a guess the browser then\n // contradicts; the control is the stable answer until the id is passed in.\n const noVisitor = !browser && !options.visitorId;\n const sessionId = options.sessionId ?? (browser ? getOrCreateSessionId() : 'server');\n // In the browser the device's own time zone beats the one guessed from the IP.\n const contextFor = (g: RemoteOverrides['ctx'] | undefined): TargetingContext => {\n if (!browser) return { ...(g ?? {}), ...(options.context ?? {}) };\n const forPage = g?.timezone ? { ...g, timezone: undefined } : g;\n return browserContext({ ...stripUndefined(forPage ?? {}), ...(hadVisitor === undefined ? {} : { visitor: hadVisitor ? 'returning' : 'new' }), ...(options.context ?? {}) });\n };\n let context = contextFor(geo);\n // Crawlers and headless browsers get the control (see assign) and send nothing.\n const isBot = (): boolean => context.device === 'bot';\n const overrides = {\n ...(browser ? parseForceParam(location.search) : {}),\n ...(options.overrides ?? {}),\n };\n const disabled = options.disabled ?? (!browser && !options.transport);\n // The cloud refuses a project with nothing running (429) and drops exposures of drafts.\n // Sending them anyway only fills the console with errors, so they stay local (and visible in debug mode).\n const cloud = config.storage.mode === 'cloud';\n const cloudIdle = (): boolean => cloud && !config.experiments.some((e) => e.status === 'running');\n // Tests are running in the config from the start, so `next dev` / `vite` would count the\n // developer as a visitor. Development never sends to the cloud; `vite preview` or a deploy does.\n const devLocal = cloud && isDevEnvironment();\n const held = new Set<string>();\n const hold = (key: string, kind: 'exposure' | 'goal', message: string): void => {\n if (held.has(key)) return;\n held.add(key);\n debugLog(kind, message);\n };\n\n const transport = options.transport ?? createFetchTransport({\n ...resolveEndpoint(config),\n keyInQuery: options.keyInQuery ?? (config.storage.mode === 'cloud' && !config.storage.endpoint),\n });\n const queue = new EventQueue({\n project: config.project,\n sdk: `core/${SDK_VERSION}`,\n transport,\n onError: options.onError,\n });\n const exposed = browser ? sessionExposureSet() : new Set<string>();\n\n const currentUrl = (): string | undefined =>\n browser ? location.pathname + location.search : undefined;\n\n // Holdout marker: one `__holdout` exposure per visitor (holdout or enrolled) the first time they reach a running test.\n const markHoldout = (ts: number): void => {\n const group = holdoutGroup(config, visitorId);\n if (!group || noVisitor) return;\n const dedupKey = `${HOLDOUT_KEY}:${group}`;\n if (exposed.has(dedupKey)) return;\n if (devLocal) {\n hold(`x:${HOLDOUT_KEY}`, 'exposure', `${HOLDOUT_KEY} / ${group} not sent: development never sends to the cloud`);\n return;\n }\n exposed.add(dedupKey);\n if (browser) persistExposureSet(exposed);\n const event = { id: newId('e_'), type: 'exposure' as const, exp: HOLDOUT_KEY, var: group, vid: visitorId, sid: sessionId, ts, url: currentUrl() };\n debugLog('exposure', `${HOLDOUT_KEY} / ${group} recorded`, event);\n queue.push(event);\n };\n\n // While pending, exposures and goals wait here with the time they happened, so a\n // goal on the first page still counts (the cloud needs exposure time <= goal time).\n let pending = waitFor !== null;\n const waiting: Array<{ exp: string; ts: number } | { goal: string; props?: Record<string, unknown>; ts: number }> = [];\n const listeners = new Set<() => void>();\n\n const sendExposure = (experimentKey: string, ts: number): void => {\n const a = client.assignment(experimentKey);\n if (config.holdout && countsForHoldout(a)) markHoldout(ts);\n if (!a.variant || a.reason === 'override') return;\n if (typeof __SPLITHUB_LITE__ === 'undefined' && devLocal) {\n devNote('dev-events', DEV_NOTE);\n hold(`x:${experimentKey}`, 'exposure', `${experimentKey} / ${a.variant.key} not sent: development never sends to the cloud`);\n return;\n }\n const dedupKey = `${experimentKey}:${a.variant.key}`;\n if (exposed.has(dedupKey)) return;\n exposed.add(dedupKey);\n if (browser) persistExposureSet(exposed);\n const event = { id: newId('e_'), type: 'exposure' as const, exp: experimentKey, var: a.variant.key, vid: visitorId, sid: sessionId, ts, url: currentUrl() };\n debugLog('exposure', `${experimentKey} / ${a.variant.key} recorded`, event);\n queue.push(event);\n };\n\n const sendGoal = (goal: string, props: Record<string, unknown> | undefined, ts: number): void => {\n // The overrides' geo may only now say this is a crawler.\n if (isBot()) return;\n if (!config.goals.some((g) => g.key === goal)) {\n warn(`goal \"${goal}\" is not declared in splithub.config.ts; sending anyway.`);\n }\n if (typeof __SPLITHUB_LITE__ === 'undefined' && devLocal) {\n devNote('dev-events', DEV_NOTE);\n hold(`g:${goal}`, 'goal', `${goal} not sent: development never sends to the cloud`);\n return;\n }\n if (cloudIdle()) {\n hold(`g:${goal}`, 'goal', `${goal} not sent: no experiment is running in this project yet`);\n return;\n }\n const event = { id: newId('g_'), type: 'goal' as const, goal, vid: visitorId, sid: sessionId, ts, url: currentUrl(), ...(props ? { props } : {}) };\n debugLog('goal', `${goal}${props ? ' ' + JSON.stringify(props) : ''}`, event);\n queue.push(event);\n };\n\n const ready: Promise<void> = waitFor\n ? waitFor.then((fresh) => {\n if (fresh) {\n config = applyRemoteOverrides(base, fresh);\n context = contextFor(fresh.ctx);\n debugLog('remote', `first visit: overrides v${fresh.version} arrived, experiments decided`, { experiments: fresh.experiments });\n } else {\n debugLog('remote', 'first visit: overrides did not arrive in time; experiments follow splithub.config.ts');\n }\n pending = false;\n // Exposures first: a goal only converts a visitor already in the test.\n for (const w of waiting) if ('exp' in w) sendExposure(w.exp, w.ts);\n for (const w of waiting) if ('goal' in w) sendGoal(w.goal, w.props, w.ts);\n waiting.length = 0;\n for (const listener of [...listeners]) listener();\n listeners.clear();\n })\n : Promise.resolve();\n\n const decided = new Set<string>();\n const client: SplitHubClient = {\n get config() {\n return config;\n },\n visitorId,\n sessionId,\n get context() {\n return context;\n },\n get pending() {\n return pending;\n },\n ready,\n subscribe(listener) {\n if (!pending) return () => undefined;\n listeners.add(listener);\n return () => void listeners.delete(listener);\n },\n\n assignment(experimentKey) {\n if (pending) return { experiment: experimentKey, variant: null, reason: 'pending' };\n let a = assign(config, experimentKey, visitorId, { overrides, context });\n if (noVisitor && a.variant && a.reason !== 'override') a = { experiment: experimentKey, variant: null, reason: 'no_visitor' };\n if (typeof __SPLITHUB_LITE__ === 'undefined') explainAssignment(getExperiment(config, experimentKey), a);\n if (isDebug() && !decided.has(experimentKey)) {\n decided.add(experimentKey);\n const exp = getExperiment(config, experimentKey);\n debugLog('assign', `${experimentKey} → ${a.variant?.key ?? 'control (no variant)'} · ${a.reason}`, { kind: exp?.kind, status: exp?.status, traffic: exp?.traffic, flow: Boolean(exp?.flow), ...(a.variant?.value !== undefined && a.variant?.value !== null ? { value: a.variant.value } : {}), ...(a.variant?.to ? { to: a.variant.to } : {}) });\n }\n return a;\n },\n\n exposure(experimentKey) {\n if (disabled) return;\n if (pending) {\n if (!waiting.some((w) => 'exp' in w && w.exp === experimentKey)) waiting.push({ exp: experimentKey, ts: Date.now() });\n return;\n }\n sendExposure(experimentKey, Date.now());\n },\n\n variant(experimentKey) {\n const experiment = getExperiment(config, experimentKey);\n if (!experiment) {\n warnUnknown(experimentKey);\n return 'control';\n }\n const a = client.assignment(experimentKey);\n client.exposure(experimentKey);\n return (a.variant ?? experiment.variants[0]!).key;\n },\n\n value<T>(experimentKey: string): T {\n const experiment = getExperiment(config, experimentKey);\n if (!experiment) {\n warnUnknown(experimentKey);\n return undefined as T;\n }\n const a = client.assignment(experimentKey);\n client.exposure(experimentKey);\n return (a.variant ?? experiment.variants[0]!).value as T;\n },\n\n track(goal, props) {\n if (disabled || isBot()) return;\n if (pending) waiting.push({ goal, ...(props ? { props } : {}), ts: Date.now() });\n else sendGoal(goal, props, Date.now());\n },\n\n pageview(path) {\n const current = path ?? (browser ? location.pathname : undefined);\n if (!current) return;\n // Pageview goals may be declared in the dashboard: match them once the overrides are in.\n if (pending) {\n const ts = Date.now();\n void ready.then(() => {\n if (disabled) return;\n for (const goal of config.goals) if (goal.type === 'pageview' && goal.path && matchPath(goal.path, current)) sendGoal(goal.key, undefined, ts);\n });\n return;\n }\n for (const goal of config.goals) {\n if (goal.type === 'pageview' && goal.path && matchPath(goal.path, current)) {\n debugLog('pageview', `${current} matches goal ${goal.key}`);\n client.track(goal.key);\n }\n }\n },\n\n autoGoals(root) {\n if (!browser) return () => undefined;\n const clickGoals = config.goals.filter((g) => g.type === 'click' && g.selector);\n if (clickGoals.length === 0) return () => undefined;\n const target: Document | HTMLElement = root ?? document;\n const onClick = (ev: Event) => {\n const el = ev.target as Element | null;\n if (!el || typeof el.closest !== 'function') return;\n for (const g of clickGoals) {\n try {\n if (el.closest(g.selector!)) client.track(g.key);\n } catch {\n // invalid selector: ignore\n }\n }\n };\n target.addEventListener('click', onClick, true);\n return () => target.removeEventListener('click', onClick, true);\n },\n\n flush: () => queue.flush(false),\n // Unbinds the page listeners; pending events are kept and a later event binds again,\n // so a provider may destroy on unmount even under StrictMode's double mount.\n destroy: () => queue.destroy(),\n };\n\n if (browser && isDebug()) {\n (window as unknown as { __splithub?: SplitHubClient }).__splithub = client;\n debugLog('info', `client ready · ${config.experiments.length} experiments · visitor ${visitorId} · ${config.storage.mode} mode`, { context });\n }\n return client;\n}\n\nfunction stripUndefined<T extends object>(o: T): Partial<T> {\n return Object.fromEntries(Object.entries(o).filter(([, v]) => v !== undefined)) as Partial<T>;\n}\n\nfunction withTimeout<T>(p: Promise<T | null>, ms: number): Promise<T | null> {\n return new Promise((resolve) => {\n const t = setTimeout(() => resolve(null), ms);\n p.then(\n (v) => {\n clearTimeout(t);\n resolve(v);\n },\n () => {\n clearTimeout(t);\n resolve(null);\n }\n );\n });\n}\n\nconst warned = new Set<string>();\nfunction warn(message: string): void {\n if (warned.has(message)) return;\n warned.add(message);\n if (typeof console !== 'undefined') console.warn(`[splithub] ${message}`);\n}\nfunction warnUnknown(key: string): void {\n warn(`experiment \"${key}\" is not in splithub.config.ts; rendering control.`);\n}\n\nexport type { Experiment, Variant };\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;AC8PO,SAAS,iBAAiB,OAAyC;AACxE,SAAO,QAAQ,KAAK,KAAK,OAAO,UAAU,YAAa,MAAyB,eAAe;AACjG;;;AC3NA,SAAS,kBAAkB,YAAwB,GAAmC;AACpF,MAAI,WAAW,WAAW;AAC1B,MAAI,EAAE,SAAS;AACb,UAAM,MAAM,SAAS,IAAI,CAAC,OAAO,EAAE,GAAG,GAAG,QAAQ,KAAK,IAAI,GAAG,EAAE,QAAS,EAAE,GAAG,KAAK,EAAE,MAAM,EAAE,EAAE;AAC9F,UAAM,QAAQ,IAAI,OAAO,CAAC,GAAG,MAAM,IAAI,EAAE,QAAQ,CAAC;AAClD,QAAI,QAAQ,EAAG,YAAW,IAAI,IAAI,CAAC,OAAO,EAAE,GAAG,GAAG,QAAQ,EAAE,SAAS,MAAM,EAAE;AAAA,EAC/E;AACA,MAAI,EAAE,UAAU,WAAW,SAAS,SAAS;AAC3C,eAAW,SAAS,IAAI,CAAC,MAAO,EAAE,OAAO,EAAE,SAAU,EAAE,GAAG,GAAG,OAAO,EAAE,OAAQ,EAAE,GAAG,EAAE,IAAI,CAAE;AAAA,EAC7F;AACA,SAAO;AAAA,IACL,GAAG;AAAA,IACH,QAAQ,EAAE,UAAU,WAAW;AAAA,IAC/B,SAAS,EAAE,YAAY,UAAa,EAAE,WAAW,KAAK,EAAE,WAAW,IAAI,EAAE,UAAU,WAAW;AAAA,IAC9F,MAAM,EAAE,QAAQ,WAAW;AAAA,IAC3B;AAAA,EACF;AACF;AAGO,SAAS,qBAAqB,QAAwB,WAA+D;AAC1H,MAAI,CAAC,UAAW,QAAO;AACvB,QAAM,UAAU,UAAU,eAAe,CAAC;A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AW,KAAK,aAAa,KAAK;AAAA,UAC3D,OAAM;AAAA,IACb;AAAA,IACA,gBAAgB,EAAE,MAAM,OAAO,GAAG;AAChC,UAAI,CAAC,cAAc,CAAC,KAAK,QAAQ,OAAO,GAAG,EAAE,SAAS,IAAI,UAAU,EAAE,EAAG;AACzE,WAAK,MAAM;AACX,WAAK,QAAQ,MAAM;AAAA,IACrB;AAAA,IACA,UAAU,IAAI;AACZ,aAAO,OAAO,UAAU,WAAW;AAAA,IACrC;AAAA,IACA,KAAK,IAAI;AACP,UAAI,OAAO,SAAU,QAAO;AAC5B,aAAO,QAAQ,iBAAiB,QAAQ,KAAK;AAAA,IAC/C;AAAA,IACA,qBAAqB;AACnB,aAAO,CAAC,EAAE,KAAK,UAAU,OAAO,EAAE,MAAM,UAAU,KAAK,QAAQ,OAAO,GAAG,GAAG,UAAU,eAAe,CAAC;AAAA,IACxG;AAAA,EACF;AACF;","names":[]}
1
+ {"version":3,"sources":["../src/vite.ts","../src/config.ts","../src/remote.ts","../src/client.ts"],"sourcesContent":["// Vite plugin: SplitHub notes in the terminal that runs `vite` / `npm run dev`.\n//\n// // vite.config.ts\n// import { splithub } from '@splithub/core/vite';\n// export default defineConfig({ plugins: [react(), splithub()] });\n//\n// On start and on every save of splithub.config.ts it prints what each\n// experiment does in development (draft hidden or shown, running, paused,\n// started from the dashboard). The SDK's development notes from the browser\n// (\"this visitor got control\", \"events held back\") are forwarded here too,\n// once per message until the config changes. Dev server only; builds are untouched.\n//\n// Vite's types are described structurally so @splithub/core keeps zero dependencies.\n\nimport { CLOUD_ENDPOINT } from './client';\nimport { isSplitHubConfig } from './config';\nimport { applyRemoteOverrides, fetchRemoteOverrides, resolveOverridesUrl } from './remote';\nimport type { Experiment, SplitHubConfig } from './types';\n\ninterface Logger {\n info(message: string, options?: { timestamp?: boolean }): void;\n}\ninterface DevServer {\n config: { root: string; logger: Logger };\n httpServer: { once(event: 'listening', listener: () => void): unknown } | null;\n ssrLoadModule(url: string): Promise<Record<string, unknown>>;\n ws: { on(event: string, listener: (data: unknown) => void): void };\n}\ninterface HotContext {\n file: string;\n server: DevServer;\n}\nexport interface SplitHubVitePlugin {\n name: string;\n apply: 'serve';\n configureServer(server: DevServer): void;\n handleHotUpdate(ctx: HotContext): void;\n resolveId(id: string): string | undefined;\n load(id: string): string | undefined;\n transformIndexHtml(): Array<{ tag: string; attrs: Record<string, string>; injectTo: 'head-prepend' }>;\n}\n\nexport interface SplitHubViteOptions {\n /** Path of the config, relative to the Vite root. Default: splithub.config.ts, .js or .mjs. */\n config?: string;\n /** Print the experiment summary on start and on config changes. Default true. */\n summary?: boolean;\n /** Forward the SDK's development notes from the browser. Default true. */\n browserNotes?: boolean;\n}\n\nconst VIRTUAL = 'virtual:splithub-dev';\nconst RESOLVED = '\\0' + VIRTUAL;\nconst CANDIDATES = ['splithub.config.ts', 'splithub.config.js', 'splithub.config.mjs'];\nconst tag = (s: string) => `\\x1b[36m[splithub]\\x1b[39m ${s}`;\nconst dim = (s: string) => `\\x1b[2m${s}\\x1b[22m`;\n\n// The browser side: the SDK announces notes as a window event; this sends them to the\n// dev server and tells the SDK that the terminal has them, so the browser console stays quiet.\nconst CLIENT = `if (import.meta.hot) {\n window.__splithubTerminal = true;\n window.addEventListener('splithub:dev', (e) => import.meta.hot.send('splithub:note', e.detail));\n}`;\n\n/** One line per experiment, in the words a developer needs. `live` is the experiment after dashboard changes. */\nexport function describeExperiment(config: SplitHubConfig, e: Experiment, live?: Experiment): string {\n const changed = live && live.status !== e.status ? live.status : null;\n const status = changed ?? e.status;\n const second = e.variants[1]?.key ?? 'variant';\n if (status === 'running') return `${e.key}: running${changed ? ' (started from the dashboard)' : ''}`;\n if (status === 'draft') {\n return config.runDraftsInDev\n ? `${e.key}: draft, shown here as if running; visitors see it after ${dim(`npx splithub start ${e.key}`)}`\n : `${e.key}: draft, everyone sees the control, here too; add runDraftsInDev: true or open ${dim(`?sh_force=${e.key}:${second}`)}`;\n }\n return `${e.key}: ${status}${changed ? ' from the dashboard' : ''}, everyone sees the control`;\n}\n\nasync function liveConfig(config: SplitHubConfig): Promise<SplitHubConfig | null> {\n if (config.storage.mode !== 'cloud' || !config.storage.key) return null;\n const url = resolveOverridesUrl(config.storage.endpoint ?? CLOUD_ENDPOINT, config.storage.key);\n const timeout = new Promise<null>((resolve) => setTimeout(() => resolve(null), 3000));\n const overrides = await Promise.race([fetchRemoteOverrides(url), timeout]);\n return overrides ? applyRemoteOverrides(config, overrides) : null;\n}\n\nexport function splithub(options: SplitHubViteOptions = {}): SplitHubVitePlugin {\n const seen = new Set<string>();\n let configPath: string | null = null;\n\n async function load(server: DevServer): Promise<SplitHubConfig | null> {\n for (const file of options.config ? [options.config] : CANDIDATES) {\n const path = file.replace(/^\\.?\\//, '');\n try {\n const mod = await server.ssrLoadModule(`/${path}`);\n if (isSplitHubConfig(mod.default)) {\n configPath = path;\n return mod.default;\n }\n } catch {\n // not this file, or it does not compile right now: try the next one\n }\n }\n return null;\n }\n\n async function summary(server: DevServer): Promise<void> {\n if (options.summary === false) return;\n const log = server.config.logger;\n const config = await load(server);\n if (!config) {\n log.info(tag('no splithub.config.ts found; run npx splithub init'), { timestamp: true });\n return;\n }\n const live = await liveConfig(config).catch(() => null);\n const mode = config.storage.mode === 'cloud' ? (config.storage.key ? 'cloud' : 'cloud, no public key yet') : 'self-hosted';\n const count = `${config.experiments.length} experiment${config.experiments.length === 1 ? '' : 's'}`;\n log.info(tag(`${config.project} · ${mode} · ${count}${config.runDraftsInDev ? ' · drafts run in development' : ''}`), { timestamp: true });\n for (const e of config.experiments) log.info(tag(` ${describeExperiment(config, e, live?.experiments.find((x) => x.key === e.key))}`));\n if (config.storage.mode === 'cloud') {\n log.info(tag(dim(' development sends nothing to the cloud; deployed builds do')));\n if (!(live ?? config).experiments.some((e) => e.status === 'running')) log.info(tag(dim(' nothing is running yet, so deployed builds record nothing either')));\n }\n }\n\n return {\n name: 'splithub',\n apply: 'serve',\n configureServer(server) {\n if (options.browserNotes !== false) {\n server.ws.on('splithub:note', (data) => {\n if (typeof data !== 'string' || seen.has(data)) return;\n seen.add(data);\n server.config.logger.info(tag(data), { timestamp: true });\n });\n }\n const start = () => void summary(server);\n if (server.httpServer) server.httpServer.once('listening', start);\n else start();\n },\n handleHotUpdate({ file, server }) {\n if (!configPath || !file.replace(/\\\\/g, '/').endsWith(`/${configPath}`)) return;\n seen.clear();\n void summary(server);\n },\n resolveId(id) {\n return id === VIRTUAL ? RESOLVED : undefined;\n },\n load(id) {\n if (id !== RESOLVED) return undefined;\n return options.browserNotes === false ? '' : CLIENT;\n },\n transformIndexHtml() {\n return [{ tag: 'script', attrs: { type: 'module', src: `/@id/${VIRTUAL}` }, injectTo: 'head-prepend' }];\n },\n };\n}\n","import { validateFlow } from './targeting';\nimport type {\n Experiment,\n ExperimentInput,\n ExperimentMetrics,\n Holdout,\n Factor,\n Goal,\n SplitHubConfig,\n SplitHubConfigInput,\n Variant,\n} from './types';\n\nconst KEY_PATTERN = /^[a-z0-9][a-z0-9_-]{0,63}$/;\n\nexport class ConfigError extends Error {\n constructor(message: string) {\n super(`[splithub] ${message}`);\n this.name = 'ConfigError';\n }\n}\n\nfunction assertKey(kind: string, key: string): void {\n if (!KEY_PATTERN.test(key)) {\n throw new ConfigError(\n `${kind} key \"${key}\" is invalid. Use lowercase letters, digits, \"-\" and \"_\" (max 64 chars).`\n );\n }\n}\n\nexport const MVT_MAX_FACTORS = 4;\nexport const MVT_MAX_LEVELS = 4;\nexport const MVT_MAX_COMBINATIONS = 16;\n\n/**\n * Every combination of the factors' levels as a variant, in order (first levels\n * first, so the all-control combination is the control), equal weights. The\n * variant's `value` is `{ factor: levelValue }`, what `useValue()` returns.\n */\nexport function mvtVariants(expKey: string, factors: Record<string, Record<string, unknown>>): { variants: Variant[]; factors: Factor[] } {\n const list: Factor[] = [];\n const valuesOf = new Map<string, Record<string, unknown>>();\n for (const [key, levels] of Object.entries(factors ?? {})) {\n assertKey('factor', key);\n const levelKeys = Object.keys(levels ?? {});\n if (levelKeys.length < 2) throw new ConfigError(`experiment \"${expKey}\", factor \"${key}\": needs at least 2 levels.`);\n if (levelKeys.length > MVT_MAX_LEVELS) throw new ConfigError(`experiment \"${expKey}\", factor \"${key}\": at most ${MVT_MAX_LEVELS} levels.`);\n for (const l of levelKeys) assertKey('level', l);\n list.push({ key, levels: levelKeys });\n valuesOf.set(key, levels);\n }\n if (list.length === 0) throw new ConfigError(`experiment \"${expKey}\": mvt experiments need \"factors\".`);\n if (list.length > MVT_MAX_FACTORS) throw new ConfigError(`experiment \"${expKey}\": at most ${MVT_MAX_FACTORS} factors.`);\n let combos: Array<Record<string, string>> = [{}];\n for (const f of list) combos = combos.flatMap((c) => f.levels.map((l) => ({ ...c, [f.key]: l })));\n if (combos.length > MVT_MAX_COMBINATIONS) throw new ConfigError(`experiment \"${expKey}\": ${combos.length} combinations; at most ${MVT_MAX_COMBINATIONS}.`);\n const variants: Variant[] = combos.map((levels) => ({\n key: list.map((f) => levels[f.key]).join('-'),\n weight: 1 / combos.length,\n value: Object.fromEntries(list.map((f) => [f.key, valuesOf.get(f.key)![levels[f.key]!]])),\n levels,\n }));\n return { variants, factors: list };\n}\n\nfunction normalizeVariants(expKey: string, input: ExperimentInput): Variant[] {\n if (input.kind === 'mvt') return mvtVariants(expKey, input.factors).variants;\n const entries = Object.entries(input.variants);\n if (entries.length < 2) {\n throw new ConfigError(`experiment \"${expKey}\" needs at least 2 variants.`);\n }\n const raw = entries.map(([key, v]) => {\n assertKey('variant', key);\n const weight = typeof v === 'number' ? v : v.weight;\n if (!Number.isFinite(weight) || weight < 0) {\n throw new ConfigError(`experiment \"${expKey}\", variant \"${key}\": weight must be a non-negative number.`);\n }\n const variant: Variant = { key, weight };\n const obj = typeof v === 'object' ? (v as Record<string, unknown>) : {};\n if (input.kind === 'value') variant.value = obj.value;\n if (input.kind === 'redirect') variant.to = String(obj.to ?? '');\n return variant;\n });\n const total = raw.reduce((s, v) => s + v.weight, 0);\n if (total <= 0) {\n throw new ConfigError(`experiment \"${expKey}\": variant weights sum to 0.`);\n }\n return raw.map((v) => ({ ...v, weight: v.weight / total }));\n}\n\n/** Reserved experiment key of the holdout comparison (never a valid config key: keys start with a letter or digit). */\nexport const HOLDOUT_KEY = '__holdout';\n/** Buckets per layer: an experiment's `layer.range` is a slice of 0..LAYER_BUCKETS. */\nexport const LAYER_BUCKETS = 100;\n\nfunction normalizeMetrics(key: string, input: ExperimentInput, goals: Goal[]): ExperimentMetrics | undefined {\n const m = input.metrics;\n if (!m) return undefined;\n if (!input.goal) throw new ConfigError(`experiment \"${key}\": metrics need a primary \"goal\" too.`);\n const seen = new Set<string>([input.goal]);\n const check = (goal: unknown, where: string): string => {\n 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\".`);\n if (seen.has(goal)) throw new ConfigError(`experiment \"${key}\": goal \"${goal}\" is listed twice (primary goal and metrics count once each).`);\n seen.add(goal);\n return goal;\n };\n const secondary = (m.secondary ?? []).map((g) => check(g, 'secondary'));\n const guardrails = (m.guardrails ?? []).map((g) => {\n const obj = typeof g === 'string' ? { goal: g } : g;\n const worse = obj.worse ?? 'lower';\n if (worse !== 'lower' && worse !== 'higher') throw new ConfigError(`experiment \"${key}\": guardrail \"${obj.goal}\": worse must be \"lower\" or \"higher\".`);\n return { goal: check(obj.goal, 'guardrails'), worse };\n });\n if (secondary.length === 0 && guardrails.length === 0) return undefined;\n return { secondary, guardrails };\n}\n\nfunction normalizeLayer(key: string, input: ExperimentInput, layers: Record<string, unknown>): Experiment['layer'] {\n const l = input.layer;\n if (!l) return undefined;\n if (!l.key || !(l.key in layers)) throw new ConfigError(`experiment \"${key}\": layer \"${String(l.key)}\" is not declared in \"layers\".`);\n const [start, end] = Array.isArray(l.range) ? l.range : [NaN, NaN];\n const ok = (n: unknown) => typeof n === 'number' && Number.isInteger(n) && n >= 0 && n <= LAYER_BUCKETS;\n 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}.`);\n return { key: l.key, range: [start!, end!] };\n}\n\n/** Two experiments of one layer that are not finished must not claim the same bucket. */\nfunction assertNoOverlap(experiments: Experiment[]): void {\n const live = experiments.filter((e) => e.layer && e.status !== 'finished');\n for (let i = 0; i < live.length; i++) {\n for (let j = i + 1; j < live.length; j++) {\n const a = live[i]!;\n const b = live[j]!;\n if (a.layer!.key !== b.layer!.key) continue;\n if (a.layer!.range[0] < b.layer!.range[1] && b.layer!.range[0] < a.layer!.range[1]) {\n 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.`);\n }\n }\n }\n}\n\nfunction normalizeHoldout(input: SplitHubConfigInput, goals: Goal[]): Holdout | null {\n const h = input.holdout;\n if (!h) return null;\n 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.');\n if (h.goal && !goals.some((g) => g.key === h.goal)) throw new ConfigError(`holdout.goal \"${h.goal}\" is not declared in \"goals\".`);\n if (h.percent === 0) return null;\n return { percent: h.percent, seed: h.seed ?? HOLDOUT_KEY, goal: h.goal ?? goals[0]?.key ?? null };\n}\n\nfunction normalizeExperiment(key: string, input: ExperimentInput, goals: Goal[], layers: Record<string, unknown> = {}): Experiment {\n assertKey('experiment', key);\n const traffic = input.traffic ?? 1;\n if (traffic < 0 || traffic > 1) {\n throw new ConfigError(`experiment \"${key}\": traffic must be between 0 and 1.`);\n }\n if (input.goal && !goals.some((g) => g.key === input.goal)) {\n throw new ConfigError(`experiment \"${key}\": goal \"${input.goal}\" is not declared in \"goals\".`);\n }\n if (input.kind === 'redirect' && !input.match) {\n throw new ConfigError(`experiment \"${key}\": redirect experiments need \"match\".`);\n }\n if (input.maxExposures !== undefined && (!Number.isFinite(input.maxExposures) || input.maxExposures < 1)) {\n throw new ConfigError(`experiment \"${key}\": maxExposures must be a positive number.`);\n }\n if (input.minDays !== undefined && !(Number.isInteger(input.minDays) && input.minDays >= 0 && input.minDays <= 30)) {\n throw new ConfigError(`experiment \"${key}\": minDays must be a whole number from 0 to 30.`);\n }\n if (input.goodSample !== undefined && !(Number.isInteger(input.goodSample) && input.goodSample >= 100 && input.goodSample <= 10_000_000)) {\n throw new ConfigError(`experiment \"${key}\": goodSample must be a whole number from 100 to 10,000,000.`);\n }\n if (input.name !== undefined && !(typeof input.name === 'string' && input.name.trim() && input.name.trim().length <= 80)) {\n throw new ConfigError(`experiment \"${key}\": name must be text of 1 to 80 characters.`);\n }\n for (const [k, v] of Object.entries(input.schedule ?? {})) {\n if (v !== undefined && Number.isNaN(Date.parse(v))) throw new ConfigError(`experiment \"${key}\": schedule.${k} must be an ISO date.`);\n }\n const variants = normalizeVariants(key, input);\n const metrics = normalizeMetrics(key, input, goals);\n const layer = normalizeLayer(key, input, layers);\n if (input.flow) {\n const problem = validateFlow(input.flow, variants.map((v) => v.key));\n if (problem) throw new ConfigError(`experiment \"${key}\": flow: ${problem}`);\n }\n return {\n key,\n kind: input.kind,\n status: input.status,\n traffic,\n goal: input.goal ?? null,\n seed: input.seed ?? key,\n description: input.description ?? null,\n ...(input.name !== undefined ? { name: input.name.trim() } : {}),\n match: input.kind === 'redirect' ? input.match : null,\n variants,\n ...(input.kind === 'mvt' ? { factors: mvtVariants(key, input.factors).factors } : {}),\n ...(input.flow ? { flow: input.flow } : {}),\n ...(metrics ? { metrics } : {}),\n ...(layer ? { layer } : {}),\n ...(input.minDays !== undefined ? { minDays: input.minDays } : {}),\n ...(input.goodSample !== undefined ? { goodSample: input.goodSample } : {}),\n ...(input.maxExposures ? { maxExposures: Math.floor(input.maxExposures) } : {}),\n ...(input.schedule && (input.schedule.startAt || input.schedule.endAt) ? { schedule: { startAt: input.schedule.startAt ?? null, endAt: input.schedule.endAt ?? null } } : {}),\n };\n}\n\n/**\n * Validate and normalize a config. Call it once in `splithub.config.ts`:\n *\n * ```ts\n * export default defineConfig({ project: 'my-app', storage: { mode: 'self', endpoint: '/api/splithub' }, experiments: { ... } });\n * ```\n */\nexport function defineConfig(input: SplitHubConfigInput): SplitHubConfig {\n if (!input || typeof input !== 'object') throw new ConfigError('config must be an object.');\n if (!input.project) throw new ConfigError('\"project\" is required.');\n if (!input.storage || !('mode' in input.storage)) throw new ConfigError('\"storage.mode\" is required.');\n if (input.storage.mode === 'self' && !input.storage.endpoint) {\n throw new ConfigError('\"storage.endpoint\" is required in self mode.');\n }\n\n const goals: Goal[] = Object.entries(input.goals ?? {}).map(([key, g]) => {\n assertKey('goal', key);\n return {\n key,\n type: g.type,\n path: g.type === 'pageview' ? g.path : null,\n selector: g.type === 'click' ? g.selector : null,\n revenue: g.type === 'event' ? Boolean(g.revenue) : false,\n description: g.description ?? null,\n };\n });\n\n const layers: Record<string, { seed: string }> = {};\n for (const [key, l] of Object.entries(input.layers ?? {})) {\n assertKey('layer', key);\n layers[key] = { seed: l?.seed ?? key };\n }\n const experiments = Object.entries(input.experiments ?? {}).map(([key, exp]) =>\n normalizeExperiment(key, exp, goals, layers)\n );\n assertNoOverlap(experiments);\n const holdout = normalizeHoldout(input, goals);\n\n return {\n project: input.project,\n storage: input.storage,\n visitorKey: input.visitorKey ?? 'sh_vid',\n runDraftsInDev: input.runDraftsInDev === true,\n goals,\n experiments,\n ...(Object.keys(layers).length ? { layers } : {}),\n ...(holdout ? { holdout } : {}),\n __splithub: 2,\n };\n}\n\nexport function isSplitHubConfig(value: unknown): value is SplitHubConfig {\n return Boolean(value) && typeof value === 'object' && (value as SplitHubConfig).__splithub === 2;\n}\n\nexport function getExperiment(config: SplitHubConfig, key: string): Experiment | undefined {\n return config.experiments.find((e) => e.key === key);\n}\n\n/**\n * The holdout read as an experiment, for results: `holdout` (the control: no test\n * changed anything for them) against `enrolled`, weighted by the holdout share.\n * Every declared goal but the primary is a secondary metric. Null without a holdout.\n */\nexport function holdoutExperiment(config: Pick<SplitHubConfig, 'holdout' | 'goals'>): Experiment | null {\n const h = config.holdout;\n if (!h) return null;\n const share = h.percent / 100;\n const secondary = config.goals.map((g) => g.key).filter((g) => g !== h.goal);\n return {\n key: HOLDOUT_KEY,\n kind: 'component',\n status: 'running',\n traffic: 1,\n goal: h.goal,\n seed: h.seed,\n description: `Holdout: ${h.percent}% of visitors see no test at all`,\n match: null,\n variants: [\n { key: 'holdout', weight: share },\n { key: 'enrolled', weight: 1 - share },\n ],\n ...(h.goal && secondary.length ? { metrics: { secondary, guardrails: [] } } : {}),\n };\n}\n\n/**\n * Which goals each experiment measures, for stores that attribute at ingest (the\n * cloud): `goals` is the primary goal, `metrics` the secondary and guardrail goals.\n * Includes `__holdout` when the config has a holdout.\n */\nexport function measuredGoals(config: Pick<SplitHubConfig, 'experiments' | 'holdout' | 'goals'>): { goals: Record<string, string | null>; metrics: Record<string, string[]> } {\n const goals: Record<string, string | null> = {};\n const metrics: Record<string, string[]> = {};\n const all = [...config.experiments];\n const h = holdoutExperiment(config);\n if (h) all.push(h);\n for (const e of all) {\n goals[e.key] = e.goal ?? null;\n const extra = [...(e.metrics?.secondary ?? []), ...(e.metrics?.guardrails ?? []).map((g) => g.goal)];\n if (extra.length) metrics[e.key] = extra;\n }\n return { goals, metrics };\n}\n","import type { Experiment, ExperimentStatus, Goal, Holdout, SplitHubConfig, TargetingContext } from './types';\n\n/**\n * Remote overrides let the dashboard, the CLI or an agent pause an experiment,\n * change traffic/weights or swap `value` payloads without a deploy. The\n * config file stays the source of truth for the next deploy; overrides are a\n * live patch on top of it.\n */\nexport interface ExperimentOverride {\n status?: ExperimentStatus;\n traffic?: number;\n /** Relative weights by variant key; unknown keys are ignored. */\n weights?: Record<string, number>;\n /** `value` payloads by variant key (value experiments only). */\n values?: Record<string, unknown>;\n seed?: string;\n}\n\nexport interface RemoteOverrides {\n version: number;\n experiments: Record<string, ExperimentOverride>;\n /** Experiments created in the dashboard that are not in the config file yet (hosted config). */\n added?: Experiment[];\n /** Goals declared in the dashboard (hosted config). */\n goals?: Goal[];\n /**\n * Holdout and layer seeds of the hosted config (sites on sh.js have no config file).\n * A config file's own `holdout` / `layers` win over these.\n */\n holdout?: Holdout | null;\n layers?: Record<string, { seed: string }>;\n /** What the cloud knows about this request: country, region, city. Per visitor. */\n ctx?: Pick<TargetingContext, 'country' | 'region' | 'city' | 'timezone'>;\n}\n\nexport const EMPTY_OVERRIDES: RemoteOverrides = { version: 0, experiments: {} };\n\nfunction applyToExperiment(experiment: Experiment, o: ExperimentOverride): Experiment {\n let variants = experiment.variants;\n if (o.weights) {\n const raw = variants.map((v) => ({ ...v, weight: Math.max(0, o.weights![v.key] ?? v.weight) }));\n const total = raw.reduce((s, v) => s + v.weight, 0);\n if (total > 0) variants = raw.map((v) => ({ ...v, weight: v.weight / total }));\n }\n if (o.values && experiment.kind === 'value') {\n variants = variants.map((v) => (v.key in o.values! ? { ...v, value: o.values![v.key] } : v));\n }\n return {\n ...experiment,\n status: o.status ?? experiment.status,\n traffic: o.traffic !== undefined && o.traffic >= 0 && o.traffic <= 1 ? o.traffic : experiment.traffic,\n seed: o.seed ?? experiment.seed,\n variants,\n };\n}\n\n/** Pure merge: returns a new config, never mutates the input. */\nexport function applyRemoteOverrides(config: SplitHubConfig, overrides: RemoteOverrides | null | undefined): SplitHubConfig {\n if (!overrides) return config;\n const patches = overrides.experiments ?? {};\n const known = new Set(config.experiments.map((e) => e.key));\n const added = (overrides.added ?? []).filter((e) => e && typeof e.key === 'string' && !known.has(e.key) && Array.isArray(e.variants) && e.variants.length >= 2);\n const knownGoals = new Set(config.goals.map((g) => g.key));\n const addedGoals = (overrides.goals ?? []).filter((g) => g && typeof g.key === 'string' && !knownGoals.has(g.key));\n const holdout = !config.holdout && validHoldout(overrides.holdout) ? overrides.holdout : null;\n const layers = overrides.layers && typeof overrides.layers === 'object' ? { ...overrides.layers, ...(config.layers ?? {}) } : null;\n if (Object.keys(patches).length === 0 && added.length === 0 && addedGoals.length === 0 && !holdout && !layers) return config;\n const merged = [...config.experiments, ...added.map((e) => ({ ...e, origin: 'dashboard' as const }))];\n return {\n ...config,\n ...(holdout ? { holdout } : {}),\n ...(layers ? { layers } : {}),\n goals: addedGoals.length ? [...config.goals, ...addedGoals] : config.goals,\n experiments: merged.map((e) => {\n const o = patches[e.key];\n return o ? applyToExperiment(e, o) : e;\n }),\n };\n}\n\nfunction validHoldout(h: Holdout | null | undefined): h is Holdout {\n return Boolean(h) && typeof h!.percent === 'number' && h!.percent > 0 && h!.percent <= 50 && typeof h!.seed === 'string';\n}\n\nexport function isRemoteOverrides(value: unknown): value is RemoteOverrides {\n return Boolean(value) && typeof value === 'object' && typeof (value as RemoteOverrides).version === 'number' && typeof (value as RemoteOverrides).experiments === 'object';\n}\n\n/** `https://go.splithub.io/v1/events` → `https://go.splithub.io/v1/overrides/<pk>.json` */\nexport function resolveOverridesUrl(eventsEndpoint: string, publicKey: string): string {\n const base = eventsEndpoint.replace(/\\/events\\/?$/, '');\n return `${base}/overrides/${encodeURIComponent(publicKey)}.json`;\n}\n\n// ---------------------------------------------------------------------------\n// Browser cache: overrides are applied synchronously from cache on page load\n// (no flicker) and refreshed in the background for the next load.\n// ---------------------------------------------------------------------------\n\ninterface CacheEntry {\n fetchedAt: number;\n overrides: RemoteOverrides;\n}\n\nexport const REMOTE_CACHE_KEY = 'sh_remote';\nexport const REMOTE_TTL_MS = 60_000;\n\nfunction storage(): Storage | null {\n try {\n if (typeof window === 'undefined' || !window.localStorage) return null;\n return window.localStorage;\n } catch {\n return null;\n }\n}\n\nexport function readRemoteCache(publicKey: string): CacheEntry | null {\n try {\n const raw = storage()?.getItem(`${REMOTE_CACHE_KEY}:${publicKey}`);\n if (!raw) return null;\n const parsed = JSON.parse(raw) as CacheEntry;\n return isRemoteOverrides(parsed.overrides) && typeof parsed.fetchedAt === 'number' ? parsed : null;\n } catch {\n return null;\n }\n}\n\nexport function writeRemoteCache(publicKey: string, overrides: RemoteOverrides): void {\n try {\n storage()?.setItem(`${REMOTE_CACHE_KEY}:${publicKey}`, JSON.stringify({ fetchedAt: Date.now(), overrides } satisfies CacheEntry));\n } catch {\n // storage unavailable\n }\n}\n\nexport async function fetchRemoteOverrides(url: string, fetchImpl: typeof fetch = fetch): Promise<RemoteOverrides | null> {\n try {\n const res = await fetchImpl(url, { cache: 'no-cache' });\n if (!res.ok) return null;\n const body = (await res.json()) as unknown;\n return isRemoteOverrides(body) ? body : null;\n } catch {\n return null;\n }\n}\n","import { assign, countsForHoldout, holdoutGroup, isDevEnvironment, parseForceParam } from './assignment';\nimport { debugLog, isDebug } from './debug';\nimport { devNote, explainAssignment } from './dev';\nimport { getExperiment, HOLDOUT_KEY, isSplitHubConfig } from './config';\nimport { EventQueue, createFetchTransport, type Transport } from './events';\nimport { newId } from './ids';\nimport {\n applyRemoteOverrides,\n fetchRemoteOverrides,\n readRemoteCache,\n REMOTE_TTL_MS,\n resolveOverridesUrl,\n writeRemoteCache,\n type RemoteOverrides,\n} from './remote';\nimport { matchPath } from './paths';\nimport { browserContext } from './targeting';\nimport type { Assignment, Experiment, SplitHubConfig, TargetingContext, Variant } from './types';\nimport {\n getOrCreateSessionId,\n getOrCreateVisitorId,\n hasVisitorId,\n isBrowser,\n persistExposureSet,\n sessionExposureSet,\n} from './visitor';\n\n// The drop-in script's build defines this as true, so `typeof` folds and the development\n// notes (strings included) drop out of sh.js. It has to be written inline at each use:\n// a constant imported from another module is inlined too late to remove the dead branch.\ndeclare const __SPLITHUB_LITE__: true | undefined;\n\nexport const SDK_VERSION = '0.1.0';\n/** First visit without cached overrides: the longest the client waits for them. The fetch usually takes ~150 ms. */\nexport const REMOTE_WAIT_MS = 400;\nconst DEV_NOTE = 'Development sends nothing to the cloud, so your own visits never reach the results. Deployed builds send as usual.';\nexport const CLOUD_ENDPOINT = 'https://go.splithub.io/v1/events';\n\nexport interface ClientOptions {\n /** Provide on the server (from the cookie) so SSR and client agree. */\n visitorId?: string;\n sessionId?: string;\n /** Custom transport, e.g. a no-op for tests or SSR. */\n transport?: Transport;\n /**\n * Send the cloud key as `?key=` so page-hide batches can use `navigator.sendBeacon`.\n * On by default for SplitHub Cloud (the key is public); off for a custom endpoint,\n * which may not read the key from the query.\n */\n keyInQuery?: boolean;\n /** Force variants, merged with `?sh_force=` in the browser. */\n overrides?: Record<string, string>;\n /** Disable all network activity (SSR, tests, `status: draft` previews). */\n disabled?: boolean;\n /**\n * Remote overrides (cloud mode): pause, traffic, weights and values changed\n * from the dashboard/CLI without a deploy. Cached in localStorage and\n * applied synchronously on later page loads. A first visit has no cache, so\n * the client waits up to `waitMs` for them, serving control meanwhile, then\n * decides once; a decided variant never changes mid-page.\n */\n remote?: {\n /** Apply these overrides now (SSR: pass what the server fetched). */\n overrides?: RemoteOverrides | null;\n /** Skip fetching. Default: fetch in cloud mode in the browser. */\n disabled?: boolean;\n url?: string;\n ttlMs?: number;\n /** First visit (nothing cached): how long to wait for the overrides before deciding from the file. Default 400 ms; 0 decides at once. */\n waitMs?: number;\n };\n /**\n * Visitor context for targeting (country, device, UTM ...). In the browser it\n * is collected automatically and merged with the cloud's geo (`ctx` in the\n * overrides JSON); on the server pass what you know from the request.\n */\n context?: TargetingContext;\n onError?: (error: unknown) => void;\n}\n\nexport interface SplitHubClient {\n readonly config: SplitHubConfig;\n readonly visitorId: string;\n readonly sessionId: string;\n /** Targeting context used for assignments. */\n readonly context: TargetingContext;\n /**\n * True on a first visit in cloud mode while the dashboard's overrides are on\n * their way (at most `remote.waitMs`). Every experiment serves control and\n * events wait; then the client decides once and notifies subscribers.\n */\n readonly pending: boolean;\n /** Resolves once experiments are decided (at once unless `pending`). */\n readonly ready: Promise<void>;\n /** Called once when a pending client decides. Returns an unsubscribe function. */\n subscribe(listener: () => void): () => void;\n /** Assignment without side effects. */\n assignment(experimentKey: string): Assignment;\n /** Variant key (control when not in experiment). Records an exposure. */\n variant(experimentKey: string): string;\n /** Payload of a `value` experiment (control value when not in experiment). Records an exposure. */\n value<T = unknown>(experimentKey: string): T;\n /** Record an exposure explicitly (the React components call this on mount). */\n exposure(experimentKey: string): void;\n track(goal: string, props?: Record<string, unknown>): void;\n /** Automatic pageview goals for the current URL. */\n pageview(path?: string): void;\n /** Bind click goals (`type: 'click'`, CSS selector) to the document. Returns an unbind function. No-op outside the browser. */\n autoGoals(root?: Document | HTMLElement): () => void;\n flush(): Promise<void>;\n destroy(): void;\n}\n\nfunction resolveEndpoint(config: SplitHubConfig): { endpoint: string; key?: string } {\n if (config.storage.mode === 'self') return { endpoint: config.storage.endpoint };\n return { endpoint: config.storage.endpoint ?? CLOUD_ENDPOINT, key: config.storage.key };\n}\n\nexport function createClient(config: SplitHubConfig, options: ClientOptions = {}): SplitHubClient {\n if (!isSplitHubConfig(config)) {\n throw new Error('[splithub] pass the object returned by defineConfig() from splithub.config.ts');\n }\n\n const browser = isBrowser();\n\n // Remote overrides: apply the cached copy synchronously, refresh in the background.\n // A first visit has no cache: wait briefly for the fresh copy instead, so a test\n // paused or started in the dashboard is right from the first page.\n const base = config;\n const publicKey = config.storage.mode === 'cloud' ? config.storage.key : undefined;\n let effective = config;\n let geo: RemoteOverrides['ctx'] | undefined;\n let waitFor: Promise<RemoteOverrides | null> | null = null;\n if (options.remote?.overrides) {\n effective = applyRemoteOverrides(config, options.remote.overrides);\n geo = options.remote.overrides.ctx;\n } else if (browser && publicKey && !options.remote?.disabled) {\n const cached = readRemoteCache(publicKey);\n if (cached) {\n effective = applyRemoteOverrides(config, cached.overrides);\n geo = cached.overrides.ctx;\n debugLog('remote', `overrides v${cached.overrides.version} from cache (${Math.round((Date.now() - cached.fetchedAt) / 1000)} s old)`, { experiments: cached.overrides.experiments });\n }\n const stale = !cached || Date.now() - cached.fetchedAt > (options.remote?.ttlMs ?? REMOTE_TTL_MS);\n if (stale) {\n const url = options.remote?.url ?? resolveOverridesUrl(config.storage.endpoint ?? CLOUD_ENDPOINT, publicKey);\n const fetched = fetchRemoteOverrides(url).then((fresh) => {\n if (fresh) writeRemoteCache(publicKey, fresh);\n return fresh;\n });\n // `overrides: null` from the server (Next.js) means the HTML already follows the\n // file: waiting would make the first client render disagree with it.\n const waitMs = options.remote?.waitMs ?? REMOTE_WAIT_MS;\n if (!cached && waitMs > 0 && options.remote?.overrides === undefined) waitFor = withTimeout(fetched, waitMs);\n else {\n void fetched.then((fresh) => {\n if (fresh) debugLog('remote', `fresh overrides v${fresh.version} fetched; applied on the next page load`, { experiments: fresh.experiments });\n });\n }\n }\n }\n config = effective;\n\n const hadVisitor = browser && !options.visitorId ? hasVisitorId(config.visitorKey) : undefined;\n const visitorId = options.visitorId ?? (browser ? getOrCreateVisitorId(config.visitorKey) : 'server');\n // On the server without the visitor's id, any variant would be a guess the browser then\n // contradicts; the control is the stable answer until the id is passed in.\n const noVisitor = !browser && !options.visitorId;\n const sessionId = options.sessionId ?? (browser ? getOrCreateSessionId() : 'server');\n // In the browser the device's own time zone beats the one guessed from the IP.\n const contextFor = (g: RemoteOverrides['ctx'] | undefined): TargetingContext => {\n if (!browser) return { ...(g ?? {}), ...(options.context ?? {}) };\n const forPage = g?.timezone ? { ...g, timezone: undefined } : g;\n return browserContext({ ...stripUndefined(forPage ?? {}), ...(hadVisitor === undefined ? {} : { visitor: hadVisitor ? 'returning' : 'new' }), ...(options.context ?? {}) });\n };\n let context = contextFor(geo);\n // Crawlers and headless browsers get the control (see assign) and send nothing.\n const isBot = (): boolean => context.device === 'bot';\n const overrides = {\n ...(browser ? parseForceParam(location.search) : {}),\n ...(options.overrides ?? {}),\n };\n for (const [key, forced] of Object.entries(overrides)) {\n const experiment = config.experiments.find((e) => e.key === key);\n if (experiment && !experiment.variants.some((v) => v.key === forced)) {\n warn(`sh_force asks for variant \"${forced}\" of \"${key}\", which has ${experiment.variants.map((v) => `\"${v.key}\"`).join(', ')}; showing the control, not counted.`);\n }\n }\n const disabled = options.disabled ?? (!browser && !options.transport);\n // The cloud refuses a project with nothing running (429) and drops exposures of drafts.\n // Sending them anyway only fills the console with errors, so they stay local (and visible in debug mode).\n const cloud = config.storage.mode === 'cloud';\n const cloudIdle = (): boolean => cloud && !config.experiments.some((e) => e.status === 'running');\n // Tests are running in the config from the start, so `next dev` / `vite` would count the\n // developer as a visitor. Development never sends to the cloud; `vite preview` or a deploy does.\n const devLocal = cloud && isDevEnvironment();\n const held = new Set<string>();\n const hold = (key: string, kind: 'exposure' | 'goal', message: string): void => {\n if (held.has(key)) return;\n held.add(key);\n debugLog(kind, message);\n };\n\n const transport = options.transport ?? createFetchTransport({\n ...resolveEndpoint(config),\n keyInQuery: options.keyInQuery ?? (config.storage.mode === 'cloud' && !config.storage.endpoint),\n });\n const queue = new EventQueue({\n project: config.project,\n sdk: `core/${SDK_VERSION}`,\n transport,\n onError: options.onError,\n });\n const exposed = browser ? sessionExposureSet() : new Set<string>();\n\n const currentUrl = (): string | undefined =>\n browser ? location.pathname + location.search : undefined;\n\n // Holdout marker: one `__holdout` exposure per visitor (holdout or enrolled) the first time they reach a running test.\n const markHoldout = (ts: number): void => {\n const group = holdoutGroup(config, visitorId);\n if (!group || noVisitor) return;\n const dedupKey = `${HOLDOUT_KEY}:${group}`;\n if (exposed.has(dedupKey)) return;\n if (devLocal) {\n hold(`x:${HOLDOUT_KEY}`, 'exposure', `${HOLDOUT_KEY} / ${group} not sent: development never sends to the cloud`);\n return;\n }\n exposed.add(dedupKey);\n if (browser) persistExposureSet(exposed);\n const event = { id: newId('e_'), type: 'exposure' as const, exp: HOLDOUT_KEY, var: group, vid: visitorId, sid: sessionId, ts, url: currentUrl() };\n debugLog('exposure', `${HOLDOUT_KEY} / ${group} recorded`, event);\n queue.push(event);\n };\n\n // While pending, exposures and goals wait here with the time they happened, so a\n // goal on the first page still counts (the cloud needs exposure time <= goal time).\n let pending = waitFor !== null;\n const waiting: Array<{ exp: string; ts: number } | { goal: string; props?: Record<string, unknown>; ts: number }> = [];\n const listeners = new Set<() => void>();\n\n const sendExposure = (experimentKey: string, ts: number): void => {\n const a = client.assignment(experimentKey);\n if (config.holdout && countsForHoldout(a)) markHoldout(ts);\n if (!a.variant || a.reason === 'override') return;\n if (typeof __SPLITHUB_LITE__ === 'undefined' && devLocal) {\n devNote('dev-events', DEV_NOTE);\n hold(`x:${experimentKey}`, 'exposure', `${experimentKey} / ${a.variant.key} not sent: development never sends to the cloud`);\n return;\n }\n const dedupKey = `${experimentKey}:${a.variant.key}`;\n if (exposed.has(dedupKey)) return;\n exposed.add(dedupKey);\n if (browser) persistExposureSet(exposed);\n const event = { id: newId('e_'), type: 'exposure' as const, exp: experimentKey, var: a.variant.key, vid: visitorId, sid: sessionId, ts, url: currentUrl() };\n debugLog('exposure', `${experimentKey} / ${a.variant.key} recorded`, event);\n queue.push(event);\n };\n\n const sendGoal = (goal: string, props: Record<string, unknown> | undefined, ts: number): void => {\n // The overrides' geo may only now say this is a crawler.\n if (isBot()) return;\n if (!config.goals.some((g) => g.key === goal)) {\n warn(`goal \"${goal}\" is not declared in splithub.config.ts; sending anyway.`);\n }\n if (typeof __SPLITHUB_LITE__ === 'undefined' && devLocal) {\n devNote('dev-events', DEV_NOTE);\n hold(`g:${goal}`, 'goal', `${goal} not sent: development never sends to the cloud`);\n return;\n }\n if (cloudIdle()) {\n hold(`g:${goal}`, 'goal', `${goal} not sent: no experiment is running in this project yet`);\n return;\n }\n const event = { id: newId('g_'), type: 'goal' as const, goal, vid: visitorId, sid: sessionId, ts, url: currentUrl(), ...(props ? { props } : {}) };\n debugLog('goal', `${goal}${props ? ' ' + JSON.stringify(props) : ''}`, event);\n queue.push(event);\n };\n\n const ready: Promise<void> = waitFor\n ? waitFor.then((fresh) => {\n if (fresh) {\n config = applyRemoteOverrides(base, fresh);\n context = contextFor(fresh.ctx);\n debugLog('remote', `first visit: overrides v${fresh.version} arrived, experiments decided`, { experiments: fresh.experiments });\n } else {\n debugLog('remote', 'first visit: overrides did not arrive in time; experiments follow splithub.config.ts');\n }\n pending = false;\n // Exposures first: a goal only converts a visitor already in the test.\n for (const w of waiting) if ('exp' in w) sendExposure(w.exp, w.ts);\n for (const w of waiting) if ('goal' in w) sendGoal(w.goal, w.props, w.ts);\n waiting.length = 0;\n for (const listener of [...listeners]) listener();\n listeners.clear();\n })\n : Promise.resolve();\n\n const decided = new Set<string>();\n const client: SplitHubClient = {\n get config() {\n return config;\n },\n visitorId,\n sessionId,\n get context() {\n return context;\n },\n get pending() {\n return pending;\n },\n ready,\n subscribe(listener) {\n if (!pending) return () => undefined;\n listeners.add(listener);\n return () => void listeners.delete(listener);\n },\n\n assignment(experimentKey) {\n if (pending) return { experiment: experimentKey, variant: null, reason: 'pending' };\n let a = assign(config, experimentKey, visitorId, { overrides, context });\n if (noVisitor && a.variant && a.reason !== 'override') a = { experiment: experimentKey, variant: null, reason: 'no_visitor' };\n if (typeof __SPLITHUB_LITE__ === 'undefined') explainAssignment(getExperiment(config, experimentKey), a);\n if (isDebug() && !decided.has(experimentKey)) {\n decided.add(experimentKey);\n const exp = getExperiment(config, experimentKey);\n debugLog('assign', `${experimentKey} → ${a.variant?.key ?? 'control (no variant)'} · ${a.reason}`, { kind: exp?.kind, status: exp?.status, traffic: exp?.traffic, flow: Boolean(exp?.flow), ...(a.variant?.value !== undefined && a.variant?.value !== null ? { value: a.variant.value } : {}), ...(a.variant?.to ? { to: a.variant.to } : {}) });\n }\n return a;\n },\n\n exposure(experimentKey) {\n if (disabled) return;\n if (pending) {\n if (!waiting.some((w) => 'exp' in w && w.exp === experimentKey)) waiting.push({ exp: experimentKey, ts: Date.now() });\n return;\n }\n sendExposure(experimentKey, Date.now());\n },\n\n variant(experimentKey) {\n const experiment = getExperiment(config, experimentKey);\n if (!experiment) {\n warnUnknown(experimentKey);\n return 'control';\n }\n const a = client.assignment(experimentKey);\n client.exposure(experimentKey);\n return (a.variant ?? experiment.variants[0]!).key;\n },\n\n value<T>(experimentKey: string): T {\n const experiment = getExperiment(config, experimentKey);\n if (!experiment) {\n warnUnknown(experimentKey);\n return undefined as T;\n }\n const a = client.assignment(experimentKey);\n client.exposure(experimentKey);\n return (a.variant ?? experiment.variants[0]!).value as T;\n },\n\n track(goal, props) {\n if (disabled || isBot()) return;\n if (pending) waiting.push({ goal, ...(props ? { props } : {}), ts: Date.now() });\n else sendGoal(goal, props, Date.now());\n },\n\n pageview(path) {\n const current = path ?? (browser ? location.pathname : undefined);\n if (!current) return;\n // Pageview goals may be declared in the dashboard: match them once the overrides are in.\n if (pending) {\n const ts = Date.now();\n void ready.then(() => {\n if (disabled) return;\n for (const goal of config.goals) if (goal.type === 'pageview' && goal.path && matchPath(goal.path, current)) sendGoal(goal.key, undefined, ts);\n });\n return;\n }\n for (const goal of config.goals) {\n if (goal.type === 'pageview' && goal.path && matchPath(goal.path, current)) {\n debugLog('pageview', `${current} matches goal ${goal.key}`);\n client.track(goal.key);\n }\n }\n },\n\n autoGoals(root) {\n if (!browser) return () => undefined;\n const clickGoals = config.goals.filter((g) => g.type === 'click' && g.selector);\n if (clickGoals.length === 0) return () => undefined;\n const target: Document | HTMLElement = root ?? document;\n const onClick = (ev: Event) => {\n const el = ev.target as Element | null;\n if (!el || typeof el.closest !== 'function') return;\n for (const g of clickGoals) {\n try {\n if (el.closest(g.selector!)) client.track(g.key);\n } catch {\n // invalid selector: ignore\n }\n }\n };\n target.addEventListener('click', onClick, true);\n return () => target.removeEventListener('click', onClick, true);\n },\n\n flush: () => queue.flush(false),\n // Unbinds the page listeners; pending events are kept and a later event binds again,\n // so a provider may destroy on unmount even under StrictMode's double mount.\n destroy: () => queue.destroy(),\n };\n\n if (browser && isDebug()) {\n (window as unknown as { __splithub?: SplitHubClient }).__splithub = client;\n debugLog('info', `client ready · ${config.experiments.length} experiments · visitor ${visitorId} · ${config.storage.mode} mode`, { context });\n }\n return client;\n}\n\nfunction stripUndefined<T extends object>(o: T): Partial<T> {\n return Object.fromEntries(Object.entries(o).filter(([, v]) => v !== undefined)) as Partial<T>;\n}\n\nfunction withTimeout<T>(p: Promise<T | null>, ms: number): Promise<T | null> {\n return new Promise((resolve) => {\n const t = setTimeout(() => resolve(null), ms);\n p.then(\n (v) => {\n clearTimeout(t);\n resolve(v);\n },\n () => {\n clearTimeout(t);\n resolve(null);\n }\n );\n });\n}\n\nconst warned = new Set<string>();\nfunction warn(message: string): void {\n if (warned.has(message)) return;\n warned.add(message);\n if (typeof console !== 'undefined') console.warn(`[splithub] ${message}`);\n}\nfunction warnUnknown(key: string): void {\n warn(`experiment \"${key}\" is not in splithub.config.ts; rendering control.`);\n}\n\nexport type { Experiment, Variant };\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACkQO,SAAS,iBAAiB,OAAyC;AACxE,SAAO,QAAQ,KAAK,KAAK,OAAO,UAAU,YAAa,MAAyB,eAAe;AACjG;;;AC/NA,SAAS,kBAAkB,YAAwB,GAAmC;AACpF,MAAI,WAAW,WAAW;AAC1B,MAAI,EAAE,SAAS;AACb,UAAM,MAAM,SAAS,IAAI,CAAC,OAAO,EAAE,GAAG,GAAG,QAAQ,KAAK,IAAI,GAAG,EAAE,QAAS,EAAE,GAAG,KAAK,EAAE,MAAM,EAAE,EAAE;AAC9F,UAAM,QAAQ,IAAI,OAAO,CAAC,GAAG,MAAM,IAAI,EAAE,QAAQ,CAAC;AAClD,QAAI,QAAQ,EAAG,YAAW,IAAI,IAAI,CAAC,OAAO,EAAE,GAAG,GAAG,QAAQ,EAAE,SAAS,MAAM,EAAE;AAAA,EAC/E;AACA,MAAI,EAAE,UAAU,WAAW,SAAS,SAAS;AAC3C,eAAW,SAAS,IAAI,CAAC,MAAO,EAAE,OAAO,EAAE,SAAU,EAAE,GAAG,GAAG,OAAO,EAAE,OAAQ,EAAE,GAAG,EAAE,IAAI,CAAE;AAAA,EAC7F;AACA,SAAO;AAAA,IACL,GAAG;AAAA,IACH,QAAQ,EAAE,UAAU,WAAW;AAAA,IAC/B,SAAS,EAAE,YAAY,UAAa,EAAE,WAAW,KAAK,EA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G;AAChD,eAAK,IAAI,IAAI;AACb,iBAAO,OAAO,OAAO,KAAK,IAAI,IAAI,GAAG,EAAE,WAAW,KAAK,CAAC;AAAA,QAC1D,CAAC;AAAA,MACH;AACA,YAAM,QAAQ,MAAM,KAAK,QAAQ,MAAM;AACvC,UAAI,OAAO,WAAY,QAAO,WAAW,KAAK,aAAa,KAAK;AAAA,UAC3D,OAAM;AAAA,IACb;AAAA,IACA,gBAAgB,EAAE,MAAM,OAAO,GAAG;AAChC,UAAI,CAAC,cAAc,CAAC,KAAK,QAAQ,OAAO,GAAG,EAAE,SAAS,IAAI,UAAU,EAAE,EAAG;AACzE,WAAK,MAAM;AACX,WAAK,QAAQ,MAAM;AAAA,IACrB;AAAA,IACA,UAAU,IAAI;AACZ,aAAO,OAAO,UAAU,WAAW;AAAA,IACrC;AAAA,IACA,KAAK,IAAI;AACP,UAAI,OAAO,SAAU,QAAO;AAC5B,aAAO,QAAQ,iBAAiB,QAAQ,KAAK;AAAA,IAC/C;AAAA,IACA,qBAAqB;AACnB,aAAO,CAAC,EAAE,KAAK,UAAU,OAAO,EAAE,MAAM,UAAU,KAAK,QAAQ,OAAO,GAAG,GAAG,UAAU,eAAe,CAAC;AAAA,IACxG;AAAA,EACF;AACF;","names":[]}
package/dist/vite.d.cts CHANGED
@@ -1,4 +1,4 @@
1
- import { a as SplitHubConfig, E as Experiment } from './types-DiW3b8D4.cjs';
1
+ import { a as SplitHubConfig, E as Experiment } from './types-DlycK6Py.cjs';
2
2
 
3
3
  interface Logger {
4
4
  info(message: string, options?: {
package/dist/vite.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { a as SplitHubConfig, E as Experiment } from './types-DiW3b8D4.js';
1
+ import { a as SplitHubConfig, E as Experiment } from './types-DlycK6Py.js';
2
2
 
3
3
  interface Logger {
4
4
  info(message: string, options?: {
package/dist/vite.js CHANGED
@@ -4,7 +4,7 @@ import {
4
4
  fetchRemoteOverrides,
5
5
  isSplitHubConfig,
6
6
  resolveOverridesUrl
7
- } from "./chunk-X6QEO4I4.js";
7
+ } from "./chunk-D4LRWPNH.js";
8
8
 
9
9
  // src/vite.ts
10
10
  var VIRTUAL = "virtual:splithub-dev";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@splithub/core",
3
- "version": "0.2.2",
3
+ "version": "0.3.0",
4
4
  "description": "The heart of SplitHub: the config, who sees which variant, and the event queue. No framework, no dependencies.",
5
5
  "license": "MIT",
6
6
  "repository": {