@splithub/core 0.1.8 → 0.2.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 } from './types-V-RgA0yG.cjs';
2
- export { m as ComponentExperimentInput, C as ComponentVariantInput, l as ExperimentBase, p as ExperimentInput, i as ExperimentKind, s as ExposureEvent, k as FlowNode, t as GoalEvent, q as GoalInput, M as MvtExperimentInput, o as RedirectExperimentInput, R as RedirectVariantInput, r as StorageInput, n as ValueExperimentInput, j as ValueVariantInput } from './types-V-RgA0yG.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-BibC0pt1.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-BibC0pt1.cjs';
3
3
 
4
4
  declare class ConfigError extends Error {
5
5
  constructor(message: string);
@@ -16,6 +16,10 @@ declare function mvtVariants(expKey: string, factors: Record<string, Record<stri
16
16
  variants: Variant[];
17
17
  factors: Factor[];
18
18
  };
19
+ /** Reserved experiment key of the holdout comparison (never a valid config key: keys start with a letter or digit). */
20
+ declare const HOLDOUT_KEY = "__holdout";
21
+ /** Buckets per layer: an experiment's `layer.range` is a slice of 0..LAYER_BUCKETS. */
22
+ declare const LAYER_BUCKETS = 100;
19
23
  /**
20
24
  * Validate and normalize a config. Call it once in `splithub.config.ts`:
21
25
  *
@@ -26,6 +30,21 @@ declare function mvtVariants(expKey: string, factors: Record<string, Record<stri
26
30
  declare function defineConfig(input: SplitHubConfigInput): SplitHubConfig;
27
31
  declare function isSplitHubConfig(value: unknown): value is SplitHubConfig;
28
32
  declare function getExperiment(config: SplitHubConfig, key: string): Experiment | undefined;
33
+ /**
34
+ * The holdout read as an experiment, for results: `holdout` (the control: no test
35
+ * changed anything for them) against `enrolled`, weighted by the holdout share.
36
+ * Every declared goal but the primary is a secondary metric. Null without a holdout.
37
+ */
38
+ declare function holdoutExperiment(config: Pick<SplitHubConfig, 'holdout' | 'goals'>): Experiment | null;
39
+ /**
40
+ * Which goals each experiment measures, for stores that attribute at ingest (the
41
+ * cloud): `goals` is the primary goal, `metrics` the secondary and guardrail goals.
42
+ * Includes `__holdout` when the config has a holdout.
43
+ */
44
+ declare function measuredGoals(config: Pick<SplitHubConfig, 'experiments' | 'holdout' | 'goals'>): {
45
+ goals: Record<string, string | null>;
46
+ metrics: Record<string, string[]>;
47
+ };
29
48
 
30
49
  /**
31
50
  * True in `next dev` / `vite` and on the server of a dev build. Bundlers
@@ -45,6 +64,23 @@ declare function isActive(config: Pick<SplitHubConfig, 'runDraftsInDev'>, experi
45
64
  * reshuffle variants of visitors already inside the experiment.
46
65
  */
47
66
  declare function pickVariant(experiment: Experiment, visitorId: string): Variant | null;
67
+ /**
68
+ * Holdout group of a visitor: `holdout` (sees the control everywhere, sends no
69
+ * exposures but the `__holdout` marker) or `enrolled`. Null without a holdout.
70
+ * One hash per visitor and project, independent of every experiment's seed.
71
+ */
72
+ declare function holdoutGroup(config: Pick<SplitHubConfig, 'holdout'>, visitorId: string): 'holdout' | 'enrolled' | null;
73
+ /** The visitor's bucket 0..99 in a layer: the same in every experiment of the layer. */
74
+ declare function layerBucket(config: Pick<SplitHubConfig, 'layers'>, layerKey: string, visitorId: string): number;
75
+ /** True when the experiment has no layer or the visitor's bucket is inside its range. */
76
+ declare function inLayer(config: Pick<SplitHubConfig, 'layers'>, experiment: Pick<Experiment, 'layer'>, visitorId: string): boolean;
77
+ /**
78
+ * Whether an assignment puts the visitor in the holdout comparison: they reached a
79
+ * running experiment (in or out of its traffic, layer or targeting), so holdout and
80
+ * enrolled visitors are counted by the same rule. Overrides, bots and tests that are
81
+ * not running do not count.
82
+ */
83
+ declare function countsForHoldout(a: Pick<Assignment, 'reason'>): boolean;
48
84
  interface AssignOptions {
49
85
  /** Force a variant (QA, `?sh_force=hero-cta:bold`). */
50
86
  overrides?: Record<string, string>;
@@ -118,10 +154,52 @@ declare function parseUserAgent(ua: string | null | undefined): {
118
154
  browser: string;
119
155
  os: string;
120
156
  };
157
+ /**
158
+ * True for crawlers, link previews, monitors and headless browsers. They get the control
159
+ * and send no exposures or goals; servers use it to drop events from such requests.
160
+ */
161
+ declare function isBot(ua: string | null | undefined): boolean;
162
+ /**
163
+ * For ingest: a crawler rendering pages, not a plain HTTP client. A backend that
164
+ * sends goals with curl or python-requests is a real sender; `isBot` (targeting)
165
+ * calls those bots, so ingest must not use it.
166
+ */
167
+ declare function isCrawler(ua: string | null | undefined): boolean;
121
168
  declare function parseCookies(header: string | null | undefined): Record<string, string>;
122
169
  /** Context from the current browser page. Geo fields come from the cloud (`ctx` in the overrides JSON). */
123
170
  declare function browserContext(extra?: Partial<TargetingContext>): TargetingContext;
124
171
 
172
+ /** `/pricing/` → `/pricing`; the root stays `/`. */
173
+ declare function normalizePath(path: string): string;
174
+ /**
175
+ * `pattern` is an exact path (a trailing slash on either side is ignored) or a
176
+ * prefix ending with `*` (`/blog/*` matches `/blog/a/b`).
177
+ */
178
+ declare function matchPath(pattern: string, pathname: string): boolean;
179
+ /**
180
+ * Where a redirect variant sends the visitor: `to` resolved against the current
181
+ * URL, with the current query merged in (the variant's own parameters win, so
182
+ * `?utm_source` survives) and the current hash kept unless `to` has one.
183
+ */
184
+ declare function redirectTarget(to: string, currentHref: string): URL;
185
+
186
+ interface RedirectDecision {
187
+ experiment: string;
188
+ variant: string;
189
+ /** Destination (`to` of the variant) when the visitor must be moved; null when they stay. */
190
+ to: string | null;
191
+ /** Why this variant: `assigned`, `dev` (a draft in development) or `override` (`?sh_force`). */
192
+ reason: Assignment['reason'];
193
+ }
194
+ /**
195
+ * Which redirect experiment applies to `pathname`, and where the visitor goes.
196
+ * The first active experiment that matches and assigns a variant wins. Pure:
197
+ * sh.js and the Next.js middleware ask the same question and get the same answer.
198
+ * `explain` hears every assignment it made for a matching experiment (the
199
+ * middleware prints the surprising ones in development).
200
+ */
201
+ declare function decideRedirect(config: SplitHubConfig, pathname: string, visitorId: string, context?: TargetingContext, overrides?: Record<string, string>, explain?: (experiment: Experiment, assignment: Assignment) => void): RedirectDecision | null;
202
+
125
203
  interface Transport {
126
204
  send(batch: EventBatch, options: {
127
205
  beacon: boolean;
@@ -131,8 +209,14 @@ interface TransportOptions {
131
209
  endpoint: string;
132
210
  /** Sent as `Authorization: Bearer` (cloud public key). */
133
211
  key?: string;
212
+ /**
213
+ * Send the key as `?key=` so page-hide batches can use `navigator.sendBeacon`, which
214
+ * cannot set headers. Only for endpoints that accept it; otherwise keyed batches use
215
+ * `fetch(..., { keepalive: true })` on page hide, which also outlives the page.
216
+ */
217
+ keyInQuery?: boolean;
134
218
  }
135
- /** Default transport: fetch with keepalive, sendBeacon on page hide. */
219
+ /** Default transport: fetch with keepalive; sendBeacon on page hide when the endpoint allows it. */
136
220
  declare function createFetchTransport(options: TransportOptions): Transport;
137
221
  interface EventQueueOptions {
138
222
  project: string;
@@ -142,24 +226,39 @@ interface EventQueueOptions {
142
226
  maxBatch?: number;
143
227
  /** Flush at least this often (ms). Default 2000. */
144
228
  flushInterval?: number;
229
+ /** Events kept while the endpoint is unreachable; the oldest go first. Default 200. */
230
+ maxQueue?: number;
231
+ /** Attempts per event before it is dropped. Default 5. */
232
+ maxAttempts?: number;
145
233
  onError?: (error: unknown) => void;
146
234
  }
147
235
  /**
148
- * Batches events and flushes them on a timer, on size, and on page hide.
149
- * Failed batches are retried once on the next flush, then dropped.
236
+ * Batches events and sends them on a timer, when a batch is full, and when the page is
237
+ * hidden (sendBeacon / keepalive). A failed batch is retried with exponential backoff and
238
+ * jitter, up to `maxAttempts`; a 4xx other than 408/429 is a refusal and is not retried.
239
+ * At most `maxQueue` events wait in memory. Page listeners are bound on the first event
240
+ * and removed by `destroy()`, so a client created and thrown away (React StrictMode) leaks nothing.
150
241
  */
151
242
  declare class EventQueue {
152
243
  private readonly options;
153
244
  private pending;
154
245
  private retry;
246
+ private attempts;
155
247
  private timer;
248
+ private backoffUntil;
156
249
  private readonly maxBatch;
157
250
  private readonly flushInterval;
251
+ private readonly maxQueue;
252
+ private readonly maxAttempts;
158
253
  private unbind;
159
254
  constructor(options: EventQueueOptions);
255
+ private bind;
256
+ private schedule;
160
257
  push(event: SplitHubEvent): void;
161
258
  get size(): number;
259
+ /** Send everything now. `beacon` is for page hide: it ignores the backoff, since the page is going away. */
162
260
  flush(beacon?: boolean): Promise<void>;
261
+ /** Stop the timer and the page listeners. Pending events stay; a later `push` binds again. */
163
262
  destroy(): void;
164
263
  }
165
264
 
@@ -185,8 +284,16 @@ interface RemoteOverrides {
185
284
  added?: Experiment[];
186
285
  /** Goals declared in the dashboard (hosted config). */
187
286
  goals?: Goal[];
287
+ /**
288
+ * Holdout and layer seeds of the hosted config (sites on sh.js have no config file).
289
+ * A config file's own `holdout` / `layers` win over these.
290
+ */
291
+ holdout?: Holdout | null;
292
+ layers?: Record<string, {
293
+ seed: string;
294
+ }>;
188
295
  /** What the cloud knows about this request: country, region, city. Per visitor. */
189
- ctx?: Pick<TargetingContext, 'country' | 'region' | 'city'>;
296
+ ctx?: Pick<TargetingContext, 'country' | 'region' | 'city' | 'timezone'>;
190
297
  }
191
298
  declare const EMPTY_OVERRIDES: RemoteOverrides;
192
299
  /** Pure merge: returns a new config, never mutates the input. */
@@ -204,6 +311,8 @@ declare function writeRemoteCache(publicKey: string, overrides: RemoteOverrides)
204
311
  declare function fetchRemoteOverrides(url: string, fetchImpl?: typeof fetch): Promise<RemoteOverrides | null>;
205
312
 
206
313
  declare const SDK_VERSION = "0.1.0";
314
+ /** First visit without cached overrides: the longest the client waits for them. The fetch usually takes ~150 ms. */
315
+ declare const REMOTE_WAIT_MS = 400;
207
316
  declare const CLOUD_ENDPOINT = "https://go.splithub.io/v1/events";
208
317
  interface ClientOptions {
209
318
  /** Provide on the server (from the cookie) so SSR and client agree. */
@@ -211,6 +320,12 @@ interface ClientOptions {
211
320
  sessionId?: string;
212
321
  /** Custom transport, e.g. a no-op for tests or SSR. */
213
322
  transport?: Transport;
323
+ /**
324
+ * Send the cloud key as `?key=` so page-hide batches can use `navigator.sendBeacon`.
325
+ * On by default for SplitHub Cloud (the key is public); off for a custom endpoint,
326
+ * which may not read the key from the query.
327
+ */
328
+ keyInQuery?: boolean;
214
329
  /** Force variants, merged with `?sh_force=` in the browser. */
215
330
  overrides?: Record<string, string>;
216
331
  /** Disable all network activity (SSR, tests, `status: draft` previews). */
@@ -218,7 +333,9 @@ interface ClientOptions {
218
333
  /**
219
334
  * Remote overrides (cloud mode): pause, traffic, weights and values changed
220
335
  * from the dashboard/CLI without a deploy. Cached in localStorage and
221
- * applied synchronously on the next page load; never changed mid-page.
336
+ * applied synchronously on later page loads. A first visit has no cache, so
337
+ * the client waits up to `waitMs` for them, serving control meanwhile, then
338
+ * decides once; a decided variant never changes mid-page.
222
339
  */
223
340
  remote?: {
224
341
  /** Apply these overrides now (SSR: pass what the server fetched). */
@@ -227,6 +344,8 @@ interface ClientOptions {
227
344
  disabled?: boolean;
228
345
  url?: string;
229
346
  ttlMs?: number;
347
+ /** First visit (nothing cached): how long to wait for the overrides before deciding from the file. Default 400 ms; 0 decides at once. */
348
+ waitMs?: number;
230
349
  };
231
350
  /**
232
351
  * Visitor context for targeting (country, device, UTM ...). In the browser it
@@ -242,6 +361,16 @@ interface SplitHubClient {
242
361
  readonly sessionId: string;
243
362
  /** Targeting context used for assignments. */
244
363
  readonly context: TargetingContext;
364
+ /**
365
+ * True on a first visit in cloud mode while the dashboard's overrides are on
366
+ * their way (at most `remote.waitMs`). Every experiment serves control and
367
+ * events wait; then the client decides once and notifies subscribers.
368
+ */
369
+ readonly pending: boolean;
370
+ /** Resolves once experiments are decided (at once unless `pending`). */
371
+ readonly ready: Promise<void>;
372
+ /** Called once when a pending client decides. Returns an unsubscribe function. */
373
+ subscribe(listener: () => void): () => void;
245
374
  /** Assignment without side effects. */
246
375
  assignment(experimentKey: string): Assignment;
247
376
  /** Variant key (control when not in experiment). Records an exposure. */
@@ -274,4 +403,4 @@ declare function debugLog(kind: DebugKind, message: string, data?: Record<string
274
403
  /** Subscribe to debug entries (the devtools panel). Returns an unsubscribe function. */
275
404
  declare function onDebug(listener: (e: DebugEntry) => void): () => void;
276
405
 
277
- export { type AssignOptions, Assignment, CLOUD_ENDPOINT, type ClientOptions, ConfigError, type DebugEntry, type DebugKind, EMPTY_OVERRIDES, EventBatch, EventQueue, type EventQueueOptions, Experiment, type ExperimentOverride, ExperimentStatus, Factor, Flow, type FlowOutcome, Goal, KEYED_FIELDS, MVT_MAX_COMBINATIONS, MVT_MAX_FACTORS, MVT_MAX_LEVELS, REMOTE_TTL_MS, type RemoteOverrides, SDK_VERSION, type SplitHubClient, SplitHubConfig, SplitHubConfigInput, SplitHubEvent, TARGET_FIELDS, TARGET_OPS, TargetCondition, TargetField, TargetOp, TargetingContext, type Transport, type TransportOptions, Variant, applyRemoteOverrides, assign, browserContext, contextValue, controlVariant, createClient, createFetchTransport, debugLog, debugMode, defineConfig, devNote, evaluateCondition, explainAssignment, fetchRemoteOverrides, getExperiment, getOrCreateSessionId, getOrCreateVisitorId, hasVisitorId, hashToUnit, inSchedule, isActive, isBrowser, isDebug, isDevDraft, isDevEnvironment, isRemoteOverrides, isSplitHubConfig, matchConditions, murmur3, mvtVariants, newId, newSessionId, newVisitorId, onDebug, parseCookies, parseForceParam, parseUserAgent, pickVariant, readRemoteCache, resetDevNotes, resolveOverridesUrl, runFlow, validateFlow, writeRemoteCache };
406
+ export { type AssignOptions, Assignment, CLOUD_ENDPOINT, type ClientOptions, ConfigError, type DebugEntry, type DebugKind, EMPTY_OVERRIDES, EventBatch, EventQueue, type EventQueueOptions, Experiment, type ExperimentOverride, ExperimentStatus, Factor, Flow, type FlowOutcome, Goal, HOLDOUT_KEY, Holdout, KEYED_FIELDS, LAYER_BUCKETS, MVT_MAX_COMBINATIONS, MVT_MAX_FACTORS, MVT_MAX_LEVELS, REMOTE_TTL_MS, REMOTE_WAIT_MS, type RedirectDecision, type RemoteOverrides, SDK_VERSION, type SplitHubClient, SplitHubConfig, SplitHubConfigInput, SplitHubEvent, TARGET_FIELDS, TARGET_OPS, TargetCondition, TargetField, TargetOp, TargetingContext, type Transport, type TransportOptions, Variant, applyRemoteOverrides, assign, browserContext, contextValue, controlVariant, countsForHoldout, createClient, createFetchTransport, debugLog, debugMode, decideRedirect, defineConfig, devNote, evaluateCondition, explainAssignment, fetchRemoteOverrides, getExperiment, getOrCreateSessionId, getOrCreateVisitorId, hasVisitorId, hashToUnit, holdoutExperiment, holdoutGroup, inLayer, inSchedule, isActive, isBot, isBrowser, isCrawler, isDebug, isDevDraft, isDevEnvironment, isRemoteOverrides, isSplitHubConfig, layerBucket, matchConditions, matchPath, measuredGoals, murmur3, mvtVariants, newId, newSessionId, newVisitorId, normalizePath, onDebug, parseCookies, parseForceParam, parseUserAgent, pickVariant, readRemoteCache, redirectTarget, resetDevNotes, resolveOverridesUrl, runFlow, validateFlow, writeRemoteCache };
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 } from './types-V-RgA0yG.js';
2
- export { m as ComponentExperimentInput, C as ComponentVariantInput, l as ExperimentBase, p as ExperimentInput, i as ExperimentKind, s as ExposureEvent, k as FlowNode, t as GoalEvent, q as GoalInput, M as MvtExperimentInput, o as RedirectExperimentInput, R as RedirectVariantInput, r as StorageInput, n as ValueExperimentInput, j as ValueVariantInput } from './types-V-RgA0yG.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-BibC0pt1.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-BibC0pt1.js';
3
3
 
4
4
  declare class ConfigError extends Error {
5
5
  constructor(message: string);
@@ -16,6 +16,10 @@ declare function mvtVariants(expKey: string, factors: Record<string, Record<stri
16
16
  variants: Variant[];
17
17
  factors: Factor[];
18
18
  };
19
+ /** Reserved experiment key of the holdout comparison (never a valid config key: keys start with a letter or digit). */
20
+ declare const HOLDOUT_KEY = "__holdout";
21
+ /** Buckets per layer: an experiment's `layer.range` is a slice of 0..LAYER_BUCKETS. */
22
+ declare const LAYER_BUCKETS = 100;
19
23
  /**
20
24
  * Validate and normalize a config. Call it once in `splithub.config.ts`:
21
25
  *
@@ -26,6 +30,21 @@ declare function mvtVariants(expKey: string, factors: Record<string, Record<stri
26
30
  declare function defineConfig(input: SplitHubConfigInput): SplitHubConfig;
27
31
  declare function isSplitHubConfig(value: unknown): value is SplitHubConfig;
28
32
  declare function getExperiment(config: SplitHubConfig, key: string): Experiment | undefined;
33
+ /**
34
+ * The holdout read as an experiment, for results: `holdout` (the control: no test
35
+ * changed anything for them) against `enrolled`, weighted by the holdout share.
36
+ * Every declared goal but the primary is a secondary metric. Null without a holdout.
37
+ */
38
+ declare function holdoutExperiment(config: Pick<SplitHubConfig, 'holdout' | 'goals'>): Experiment | null;
39
+ /**
40
+ * Which goals each experiment measures, for stores that attribute at ingest (the
41
+ * cloud): `goals` is the primary goal, `metrics` the secondary and guardrail goals.
42
+ * Includes `__holdout` when the config has a holdout.
43
+ */
44
+ declare function measuredGoals(config: Pick<SplitHubConfig, 'experiments' | 'holdout' | 'goals'>): {
45
+ goals: Record<string, string | null>;
46
+ metrics: Record<string, string[]>;
47
+ };
29
48
 
30
49
  /**
31
50
  * True in `next dev` / `vite` and on the server of a dev build. Bundlers
@@ -45,6 +64,23 @@ declare function isActive(config: Pick<SplitHubConfig, 'runDraftsInDev'>, experi
45
64
  * reshuffle variants of visitors already inside the experiment.
46
65
  */
47
66
  declare function pickVariant(experiment: Experiment, visitorId: string): Variant | null;
67
+ /**
68
+ * Holdout group of a visitor: `holdout` (sees the control everywhere, sends no
69
+ * exposures but the `__holdout` marker) or `enrolled`. Null without a holdout.
70
+ * One hash per visitor and project, independent of every experiment's seed.
71
+ */
72
+ declare function holdoutGroup(config: Pick<SplitHubConfig, 'holdout'>, visitorId: string): 'holdout' | 'enrolled' | null;
73
+ /** The visitor's bucket 0..99 in a layer: the same in every experiment of the layer. */
74
+ declare function layerBucket(config: Pick<SplitHubConfig, 'layers'>, layerKey: string, visitorId: string): number;
75
+ /** True when the experiment has no layer or the visitor's bucket is inside its range. */
76
+ declare function inLayer(config: Pick<SplitHubConfig, 'layers'>, experiment: Pick<Experiment, 'layer'>, visitorId: string): boolean;
77
+ /**
78
+ * Whether an assignment puts the visitor in the holdout comparison: they reached a
79
+ * running experiment (in or out of its traffic, layer or targeting), so holdout and
80
+ * enrolled visitors are counted by the same rule. Overrides, bots and tests that are
81
+ * not running do not count.
82
+ */
83
+ declare function countsForHoldout(a: Pick<Assignment, 'reason'>): boolean;
48
84
  interface AssignOptions {
49
85
  /** Force a variant (QA, `?sh_force=hero-cta:bold`). */
50
86
  overrides?: Record<string, string>;
@@ -118,10 +154,52 @@ declare function parseUserAgent(ua: string | null | undefined): {
118
154
  browser: string;
119
155
  os: string;
120
156
  };
157
+ /**
158
+ * True for crawlers, link previews, monitors and headless browsers. They get the control
159
+ * and send no exposures or goals; servers use it to drop events from such requests.
160
+ */
161
+ declare function isBot(ua: string | null | undefined): boolean;
162
+ /**
163
+ * For ingest: a crawler rendering pages, not a plain HTTP client. A backend that
164
+ * sends goals with curl or python-requests is a real sender; `isBot` (targeting)
165
+ * calls those bots, so ingest must not use it.
166
+ */
167
+ declare function isCrawler(ua: string | null | undefined): boolean;
121
168
  declare function parseCookies(header: string | null | undefined): Record<string, string>;
122
169
  /** Context from the current browser page. Geo fields come from the cloud (`ctx` in the overrides JSON). */
123
170
  declare function browserContext(extra?: Partial<TargetingContext>): TargetingContext;
124
171
 
172
+ /** `/pricing/` → `/pricing`; the root stays `/`. */
173
+ declare function normalizePath(path: string): string;
174
+ /**
175
+ * `pattern` is an exact path (a trailing slash on either side is ignored) or a
176
+ * prefix ending with `*` (`/blog/*` matches `/blog/a/b`).
177
+ */
178
+ declare function matchPath(pattern: string, pathname: string): boolean;
179
+ /**
180
+ * Where a redirect variant sends the visitor: `to` resolved against the current
181
+ * URL, with the current query merged in (the variant's own parameters win, so
182
+ * `?utm_source` survives) and the current hash kept unless `to` has one.
183
+ */
184
+ declare function redirectTarget(to: string, currentHref: string): URL;
185
+
186
+ interface RedirectDecision {
187
+ experiment: string;
188
+ variant: string;
189
+ /** Destination (`to` of the variant) when the visitor must be moved; null when they stay. */
190
+ to: string | null;
191
+ /** Why this variant: `assigned`, `dev` (a draft in development) or `override` (`?sh_force`). */
192
+ reason: Assignment['reason'];
193
+ }
194
+ /**
195
+ * Which redirect experiment applies to `pathname`, and where the visitor goes.
196
+ * The first active experiment that matches and assigns a variant wins. Pure:
197
+ * sh.js and the Next.js middleware ask the same question and get the same answer.
198
+ * `explain` hears every assignment it made for a matching experiment (the
199
+ * middleware prints the surprising ones in development).
200
+ */
201
+ declare function decideRedirect(config: SplitHubConfig, pathname: string, visitorId: string, context?: TargetingContext, overrides?: Record<string, string>, explain?: (experiment: Experiment, assignment: Assignment) => void): RedirectDecision | null;
202
+
125
203
  interface Transport {
126
204
  send(batch: EventBatch, options: {
127
205
  beacon: boolean;
@@ -131,8 +209,14 @@ interface TransportOptions {
131
209
  endpoint: string;
132
210
  /** Sent as `Authorization: Bearer` (cloud public key). */
133
211
  key?: string;
212
+ /**
213
+ * Send the key as `?key=` so page-hide batches can use `navigator.sendBeacon`, which
214
+ * cannot set headers. Only for endpoints that accept it; otherwise keyed batches use
215
+ * `fetch(..., { keepalive: true })` on page hide, which also outlives the page.
216
+ */
217
+ keyInQuery?: boolean;
134
218
  }
135
- /** Default transport: fetch with keepalive, sendBeacon on page hide. */
219
+ /** Default transport: fetch with keepalive; sendBeacon on page hide when the endpoint allows it. */
136
220
  declare function createFetchTransport(options: TransportOptions): Transport;
137
221
  interface EventQueueOptions {
138
222
  project: string;
@@ -142,24 +226,39 @@ interface EventQueueOptions {
142
226
  maxBatch?: number;
143
227
  /** Flush at least this often (ms). Default 2000. */
144
228
  flushInterval?: number;
229
+ /** Events kept while the endpoint is unreachable; the oldest go first. Default 200. */
230
+ maxQueue?: number;
231
+ /** Attempts per event before it is dropped. Default 5. */
232
+ maxAttempts?: number;
145
233
  onError?: (error: unknown) => void;
146
234
  }
147
235
  /**
148
- * Batches events and flushes them on a timer, on size, and on page hide.
149
- * Failed batches are retried once on the next flush, then dropped.
236
+ * Batches events and sends them on a timer, when a batch is full, and when the page is
237
+ * hidden (sendBeacon / keepalive). A failed batch is retried with exponential backoff and
238
+ * jitter, up to `maxAttempts`; a 4xx other than 408/429 is a refusal and is not retried.
239
+ * At most `maxQueue` events wait in memory. Page listeners are bound on the first event
240
+ * and removed by `destroy()`, so a client created and thrown away (React StrictMode) leaks nothing.
150
241
  */
151
242
  declare class EventQueue {
152
243
  private readonly options;
153
244
  private pending;
154
245
  private retry;
246
+ private attempts;
155
247
  private timer;
248
+ private backoffUntil;
156
249
  private readonly maxBatch;
157
250
  private readonly flushInterval;
251
+ private readonly maxQueue;
252
+ private readonly maxAttempts;
158
253
  private unbind;
159
254
  constructor(options: EventQueueOptions);
255
+ private bind;
256
+ private schedule;
160
257
  push(event: SplitHubEvent): void;
161
258
  get size(): number;
259
+ /** Send everything now. `beacon` is for page hide: it ignores the backoff, since the page is going away. */
162
260
  flush(beacon?: boolean): Promise<void>;
261
+ /** Stop the timer and the page listeners. Pending events stay; a later `push` binds again. */
163
262
  destroy(): void;
164
263
  }
165
264
 
@@ -185,8 +284,16 @@ interface RemoteOverrides {
185
284
  added?: Experiment[];
186
285
  /** Goals declared in the dashboard (hosted config). */
187
286
  goals?: Goal[];
287
+ /**
288
+ * Holdout and layer seeds of the hosted config (sites on sh.js have no config file).
289
+ * A config file's own `holdout` / `layers` win over these.
290
+ */
291
+ holdout?: Holdout | null;
292
+ layers?: Record<string, {
293
+ seed: string;
294
+ }>;
188
295
  /** What the cloud knows about this request: country, region, city. Per visitor. */
189
- ctx?: Pick<TargetingContext, 'country' | 'region' | 'city'>;
296
+ ctx?: Pick<TargetingContext, 'country' | 'region' | 'city' | 'timezone'>;
190
297
  }
191
298
  declare const EMPTY_OVERRIDES: RemoteOverrides;
192
299
  /** Pure merge: returns a new config, never mutates the input. */
@@ -204,6 +311,8 @@ declare function writeRemoteCache(publicKey: string, overrides: RemoteOverrides)
204
311
  declare function fetchRemoteOverrides(url: string, fetchImpl?: typeof fetch): Promise<RemoteOverrides | null>;
205
312
 
206
313
  declare const SDK_VERSION = "0.1.0";
314
+ /** First visit without cached overrides: the longest the client waits for them. The fetch usually takes ~150 ms. */
315
+ declare const REMOTE_WAIT_MS = 400;
207
316
  declare const CLOUD_ENDPOINT = "https://go.splithub.io/v1/events";
208
317
  interface ClientOptions {
209
318
  /** Provide on the server (from the cookie) so SSR and client agree. */
@@ -211,6 +320,12 @@ interface ClientOptions {
211
320
  sessionId?: string;
212
321
  /** Custom transport, e.g. a no-op for tests or SSR. */
213
322
  transport?: Transport;
323
+ /**
324
+ * Send the cloud key as `?key=` so page-hide batches can use `navigator.sendBeacon`.
325
+ * On by default for SplitHub Cloud (the key is public); off for a custom endpoint,
326
+ * which may not read the key from the query.
327
+ */
328
+ keyInQuery?: boolean;
214
329
  /** Force variants, merged with `?sh_force=` in the browser. */
215
330
  overrides?: Record<string, string>;
216
331
  /** Disable all network activity (SSR, tests, `status: draft` previews). */
@@ -218,7 +333,9 @@ interface ClientOptions {
218
333
  /**
219
334
  * Remote overrides (cloud mode): pause, traffic, weights and values changed
220
335
  * from the dashboard/CLI without a deploy. Cached in localStorage and
221
- * applied synchronously on the next page load; never changed mid-page.
336
+ * applied synchronously on later page loads. A first visit has no cache, so
337
+ * the client waits up to `waitMs` for them, serving control meanwhile, then
338
+ * decides once; a decided variant never changes mid-page.
222
339
  */
223
340
  remote?: {
224
341
  /** Apply these overrides now (SSR: pass what the server fetched). */
@@ -227,6 +344,8 @@ interface ClientOptions {
227
344
  disabled?: boolean;
228
345
  url?: string;
229
346
  ttlMs?: number;
347
+ /** First visit (nothing cached): how long to wait for the overrides before deciding from the file. Default 400 ms; 0 decides at once. */
348
+ waitMs?: number;
230
349
  };
231
350
  /**
232
351
  * Visitor context for targeting (country, device, UTM ...). In the browser it
@@ -242,6 +361,16 @@ interface SplitHubClient {
242
361
  readonly sessionId: string;
243
362
  /** Targeting context used for assignments. */
244
363
  readonly context: TargetingContext;
364
+ /**
365
+ * True on a first visit in cloud mode while the dashboard's overrides are on
366
+ * their way (at most `remote.waitMs`). Every experiment serves control and
367
+ * events wait; then the client decides once and notifies subscribers.
368
+ */
369
+ readonly pending: boolean;
370
+ /** Resolves once experiments are decided (at once unless `pending`). */
371
+ readonly ready: Promise<void>;
372
+ /** Called once when a pending client decides. Returns an unsubscribe function. */
373
+ subscribe(listener: () => void): () => void;
245
374
  /** Assignment without side effects. */
246
375
  assignment(experimentKey: string): Assignment;
247
376
  /** Variant key (control when not in experiment). Records an exposure. */
@@ -274,4 +403,4 @@ declare function debugLog(kind: DebugKind, message: string, data?: Record<string
274
403
  /** Subscribe to debug entries (the devtools panel). Returns an unsubscribe function. */
275
404
  declare function onDebug(listener: (e: DebugEntry) => void): () => void;
276
405
 
277
- export { type AssignOptions, Assignment, CLOUD_ENDPOINT, type ClientOptions, ConfigError, type DebugEntry, type DebugKind, EMPTY_OVERRIDES, EventBatch, EventQueue, type EventQueueOptions, Experiment, type ExperimentOverride, ExperimentStatus, Factor, Flow, type FlowOutcome, Goal, KEYED_FIELDS, MVT_MAX_COMBINATIONS, MVT_MAX_FACTORS, MVT_MAX_LEVELS, REMOTE_TTL_MS, type RemoteOverrides, SDK_VERSION, type SplitHubClient, SplitHubConfig, SplitHubConfigInput, SplitHubEvent, TARGET_FIELDS, TARGET_OPS, TargetCondition, TargetField, TargetOp, TargetingContext, type Transport, type TransportOptions, Variant, applyRemoteOverrides, assign, browserContext, contextValue, controlVariant, createClient, createFetchTransport, debugLog, debugMode, defineConfig, devNote, evaluateCondition, explainAssignment, fetchRemoteOverrides, getExperiment, getOrCreateSessionId, getOrCreateVisitorId, hasVisitorId, hashToUnit, inSchedule, isActive, isBrowser, isDebug, isDevDraft, isDevEnvironment, isRemoteOverrides, isSplitHubConfig, matchConditions, murmur3, mvtVariants, newId, newSessionId, newVisitorId, onDebug, parseCookies, parseForceParam, parseUserAgent, pickVariant, readRemoteCache, resetDevNotes, resolveOverridesUrl, runFlow, validateFlow, writeRemoteCache };
406
+ export { type AssignOptions, Assignment, CLOUD_ENDPOINT, type ClientOptions, ConfigError, type DebugEntry, type DebugKind, EMPTY_OVERRIDES, EventBatch, EventQueue, type EventQueueOptions, Experiment, type ExperimentOverride, ExperimentStatus, Factor, Flow, type FlowOutcome, Goal, HOLDOUT_KEY, Holdout, KEYED_FIELDS, LAYER_BUCKETS, MVT_MAX_COMBINATIONS, MVT_MAX_FACTORS, MVT_MAX_LEVELS, REMOTE_TTL_MS, REMOTE_WAIT_MS, type RedirectDecision, type RemoteOverrides, SDK_VERSION, type SplitHubClient, SplitHubConfig, SplitHubConfigInput, SplitHubEvent, TARGET_FIELDS, TARGET_OPS, TargetCondition, TargetField, TargetOp, TargetingContext, type Transport, type TransportOptions, Variant, applyRemoteOverrides, assign, browserContext, contextValue, controlVariant, countsForHoldout, createClient, createFetchTransport, debugLog, debugMode, decideRedirect, defineConfig, devNote, evaluateCondition, explainAssignment, fetchRemoteOverrides, getExperiment, getOrCreateSessionId, getOrCreateVisitorId, hasVisitorId, hashToUnit, holdoutExperiment, holdoutGroup, inLayer, inSchedule, isActive, isBot, isBrowser, isCrawler, isDebug, isDevDraft, isDevEnvironment, isRemoteOverrides, isSplitHubConfig, layerBucket, matchConditions, matchPath, measuredGoals, murmur3, mvtVariants, newId, newSessionId, newVisitorId, normalizePath, onDebug, parseCookies, parseForceParam, parseUserAgent, pickVariant, readRemoteCache, redirectTarget, resetDevNotes, resolveOverridesUrl, runFlow, validateFlow, writeRemoteCache };
package/dist/index.js CHANGED
@@ -3,11 +3,14 @@ import {
3
3
  ConfigError,
4
4
  EMPTY_OVERRIDES,
5
5
  EventQueue,
6
+ HOLDOUT_KEY,
6
7
  KEYED_FIELDS,
8
+ LAYER_BUCKETS,
7
9
  MVT_MAX_COMBINATIONS,
8
10
  MVT_MAX_FACTORS,
9
11
  MVT_MAX_LEVELS,
10
12
  REMOTE_TTL_MS,
13
+ REMOTE_WAIT_MS,
11
14
  SDK_VERSION,
12
15
  TARGET_FIELDS,
13
16
  TARGET_OPS,
@@ -16,6 +19,7 @@ import {
16
19
  browserContext,
17
20
  contextValue,
18
21
  controlVariant,
22
+ countsForHoldout,
19
23
  createClient,
20
24
  createFetchTransport,
21
25
  debugLog,
@@ -30,42 +34,73 @@ import {
30
34
  getOrCreateVisitorId,
31
35
  hasVisitorId,
32
36
  hashToUnit,
37
+ holdoutExperiment,
38
+ holdoutGroup,
39
+ inLayer,
33
40
  inSchedule,
34
41
  isActive,
42
+ isBot,
35
43
  isBrowser,
44
+ isCrawler,
36
45
  isDebug,
37
46
  isDevDraft,
38
47
  isDevEnvironment,
39
48
  isRemoteOverrides,
40
49
  isSplitHubConfig,
50
+ layerBucket,
41
51
  matchConditions,
52
+ matchPath,
53
+ measuredGoals,
42
54
  murmur3,
43
55
  mvtVariants,
44
56
  newId,
45
57
  newSessionId,
46
58
  newVisitorId,
59
+ normalizePath,
47
60
  onDebug,
48
61
  parseCookies,
49
62
  parseForceParam,
50
63
  parseUserAgent,
51
64
  pickVariant,
52
65
  readRemoteCache,
66
+ redirectTarget,
53
67
  resetDevNotes,
54
68
  resolveOverridesUrl,
55
69
  runFlow,
56
70
  validateFlow,
57
71
  writeRemoteCache
58
- } from "./chunk-BLP4ZZ7Q.js";
72
+ } from "./chunk-XTJVALWN.js";
73
+
74
+ // src/redirect.ts
75
+ function decideRedirect(config, pathname, visitorId, context = {}, overrides = {}, explain) {
76
+ for (const exp of config.experiments) {
77
+ if (exp.kind !== "redirect" || !exp.match || !matchPath(exp.match, pathname)) continue;
78
+ if (!isActive(config, exp, context.now)) {
79
+ explain?.(exp, { experiment: exp.key, variant: null, reason: "not_running" });
80
+ continue;
81
+ }
82
+ const a = assign(config, exp.key, visitorId, { overrides, context });
83
+ explain?.(exp, a);
84
+ if (!a.variant) continue;
85
+ const to = a.variant.to || null;
86
+ const stays = !to || normalizePath(to.split(/[?#]/)[0] ?? "") === normalizePath(pathname);
87
+ return { experiment: exp.key, variant: a.variant.key, to: stays ? null : to, reason: a.reason };
88
+ }
89
+ return null;
90
+ }
59
91
  export {
60
92
  CLOUD_ENDPOINT,
61
93
  ConfigError,
62
94
  EMPTY_OVERRIDES,
63
95
  EventQueue,
96
+ HOLDOUT_KEY,
64
97
  KEYED_FIELDS,
98
+ LAYER_BUCKETS,
65
99
  MVT_MAX_COMBINATIONS,
66
100
  MVT_MAX_FACTORS,
67
101
  MVT_MAX_LEVELS,
68
102
  REMOTE_TTL_MS,
103
+ REMOTE_WAIT_MS,
69
104
  SDK_VERSION,
70
105
  TARGET_FIELDS,
71
106
  TARGET_OPS,
@@ -74,10 +109,12 @@ export {
74
109
  browserContext,
75
110
  contextValue,
76
111
  controlVariant,
112
+ countsForHoldout,
77
113
  createClient,
78
114
  createFetchTransport,
79
115
  debugLog,
80
116
  debugMode,
117
+ decideRedirect,
81
118
  defineConfig,
82
119
  devNote,
83
120
  evaluateCondition,
@@ -88,26 +125,36 @@ export {
88
125
  getOrCreateVisitorId,
89
126
  hasVisitorId,
90
127
  hashToUnit,
128
+ holdoutExperiment,
129
+ holdoutGroup,
130
+ inLayer,
91
131
  inSchedule,
92
132
  isActive,
133
+ isBot,
93
134
  isBrowser,
135
+ isCrawler,
94
136
  isDebug,
95
137
  isDevDraft,
96
138
  isDevEnvironment,
97
139
  isRemoteOverrides,
98
140
  isSplitHubConfig,
141
+ layerBucket,
99
142
  matchConditions,
143
+ matchPath,
144
+ measuredGoals,
100
145
  murmur3,
101
146
  mvtVariants,
102
147
  newId,
103
148
  newSessionId,
104
149
  newVisitorId,
150
+ normalizePath,
105
151
  onDebug,
106
152
  parseCookies,
107
153
  parseForceParam,
108
154
  parseUserAgent,
109
155
  pickVariant,
110
156
  readRemoteCache,
157
+ redirectTarget,
111
158
  resetDevNotes,
112
159
  resolveOverridesUrl,
113
160
  runFlow,