@splithub/core 0.1.9 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.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-C9OHv2W2.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-C9OHv2W2.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-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';
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. */
@@ -213,6 +320,12 @@ interface ClientOptions {
213
320
  sessionId?: string;
214
321
  /** Custom transport, e.g. a no-op for tests or SSR. */
215
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;
216
329
  /** Force variants, merged with `?sh_force=` in the browser. */
217
330
  overrides?: Record<string, string>;
218
331
  /** Disable all network activity (SSR, tests, `status: draft` previews). */
@@ -290,4 +403,4 @@ declare function debugLog(kind: DebugKind, message: string, data?: Record<string
290
403
  /** Subscribe to debug entries (the devtools panel). Returns an unsubscribe function. */
291
404
  declare function onDebug(listener: (e: DebugEntry) => void): () => void;
292
405
 
293
- 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, REMOTE_WAIT_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-C9OHv2W2.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-C9OHv2W2.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-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';
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. */
@@ -213,6 +320,12 @@ interface ClientOptions {
213
320
  sessionId?: string;
214
321
  /** Custom transport, e.g. a no-op for tests or SSR. */
215
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;
216
329
  /** Force variants, merged with `?sh_force=` in the browser. */
217
330
  overrides?: Record<string, string>;
218
331
  /** Disable all network activity (SSR, tests, `status: draft` previews). */
@@ -290,4 +403,4 @@ declare function debugLog(kind: DebugKind, message: string, data?: Record<string
290
403
  /** Subscribe to debug entries (the devtools panel). Returns an unsubscribe function. */
291
404
  declare function onDebug(listener: (e: DebugEntry) => void): () => void;
292
405
 
293
- 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, REMOTE_WAIT_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,7 +3,9 @@ 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,
@@ -17,6 +19,7 @@ import {
17
19
  browserContext,
18
20
  contextValue,
19
21
  controlVariant,
22
+ countsForHoldout,
20
23
  createClient,
21
24
  createFetchTransport,
22
25
  debugLog,
@@ -31,38 +34,68 @@ import {
31
34
  getOrCreateVisitorId,
32
35
  hasVisitorId,
33
36
  hashToUnit,
37
+ holdoutExperiment,
38
+ holdoutGroup,
39
+ inLayer,
34
40
  inSchedule,
35
41
  isActive,
42
+ isBot,
36
43
  isBrowser,
44
+ isCrawler,
37
45
  isDebug,
38
46
  isDevDraft,
39
47
  isDevEnvironment,
40
48
  isRemoteOverrides,
41
49
  isSplitHubConfig,
50
+ layerBucket,
42
51
  matchConditions,
52
+ matchPath,
53
+ measuredGoals,
43
54
  murmur3,
44
55
  mvtVariants,
45
56
  newId,
46
57
  newSessionId,
47
58
  newVisitorId,
59
+ normalizePath,
48
60
  onDebug,
49
61
  parseCookies,
50
62
  parseForceParam,
51
63
  parseUserAgent,
52
64
  pickVariant,
53
65
  readRemoteCache,
66
+ redirectTarget,
54
67
  resetDevNotes,
55
68
  resolveOverridesUrl,
56
69
  runFlow,
57
70
  validateFlow,
58
71
  writeRemoteCache
59
- } from "./chunk-MQCAGUUJ.js";
72
+ } from "./chunk-X6QEO4I4.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
+ }
60
91
  export {
61
92
  CLOUD_ENDPOINT,
62
93
  ConfigError,
63
94
  EMPTY_OVERRIDES,
64
95
  EventQueue,
96
+ HOLDOUT_KEY,
65
97
  KEYED_FIELDS,
98
+ LAYER_BUCKETS,
66
99
  MVT_MAX_COMBINATIONS,
67
100
  MVT_MAX_FACTORS,
68
101
  MVT_MAX_LEVELS,
@@ -76,10 +109,12 @@ export {
76
109
  browserContext,
77
110
  contextValue,
78
111
  controlVariant,
112
+ countsForHoldout,
79
113
  createClient,
80
114
  createFetchTransport,
81
115
  debugLog,
82
116
  debugMode,
117
+ decideRedirect,
83
118
  defineConfig,
84
119
  devNote,
85
120
  evaluateCondition,
@@ -90,26 +125,36 @@ export {
90
125
  getOrCreateVisitorId,
91
126
  hasVisitorId,
92
127
  hashToUnit,
128
+ holdoutExperiment,
129
+ holdoutGroup,
130
+ inLayer,
93
131
  inSchedule,
94
132
  isActive,
133
+ isBot,
95
134
  isBrowser,
135
+ isCrawler,
96
136
  isDebug,
97
137
  isDevDraft,
98
138
  isDevEnvironment,
99
139
  isRemoteOverrides,
100
140
  isSplitHubConfig,
141
+ layerBucket,
101
142
  matchConditions,
143
+ matchPath,
144
+ measuredGoals,
102
145
  murmur3,
103
146
  mvtVariants,
104
147
  newId,
105
148
  newSessionId,
106
149
  newVisitorId,
150
+ normalizePath,
107
151
  onDebug,
108
152
  parseCookies,
109
153
  parseForceParam,
110
154
  parseUserAgent,
111
155
  pickVariant,
112
156
  readRemoteCache,
157
+ redirectTarget,
113
158
  resetDevNotes,
114
159
  resolveOverridesUrl,
115
160
  runFlow,
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
1
+ {"version":3,"sources":["../src/redirect.ts"],"sourcesContent":["import { assign, isActive } from './assignment';\nimport { normalizePath, matchPath } from './paths';\nimport type { Assignment, Experiment, SplitHubConfig, TargetingContext } from './types';\n\nexport interface RedirectDecision {\n experiment: string;\n variant: string;\n /** Destination (`to` of the variant) when the visitor must be moved; null when they stay. */\n to: string | null;\n /** Why this variant: `assigned`, `dev` (a draft in development) or `override` (`?sh_force`). */\n reason: Assignment['reason'];\n}\n\n/**\n * Which redirect experiment applies to `pathname`, and where the visitor goes.\n * The first active experiment that matches and assigns a variant wins. Pure:\n * sh.js and the Next.js middleware ask the same question and get the same answer.\n * `explain` hears every assignment it made for a matching experiment (the\n * middleware prints the surprising ones in development).\n */\nexport function decideRedirect(\n config: SplitHubConfig,\n pathname: string,\n visitorId: string,\n context: TargetingContext = {},\n overrides: Record<string, string> = {},\n explain?: (experiment: Experiment, assignment: Assignment) => void\n): RedirectDecision | null {\n for (const exp of config.experiments) {\n if (exp.kind !== 'redirect' || !exp.match || !matchPath(exp.match, pathname)) continue;\n if (!isActive(config, exp, context.now)) {\n explain?.(exp, { experiment: exp.key, variant: null, reason: 'not_running' });\n continue;\n }\n const a = assign(config, exp.key, visitorId, { overrides, context });\n explain?.(exp, a);\n if (!a.variant) continue;\n const to = a.variant.to || null;\n const stays = !to || normalizePath(to.split(/[?#]/)[0] ?? '') === normalizePath(pathname);\n return { experiment: exp.key, variant: a.variant.key, to: stays ? null : to, reason: a.reason };\n }\n return null;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoBO,SAAS,eACd,QACA,UACA,WACA,UAA4B,CAAC,GAC7B,YAAoC,CAAC,GACrC,SACyB;AACzB,aAAW,OAAO,OAAO,aAAa;AACpC,QAAI,IAAI,SAAS,cAAc,CAAC,IAAI,SAAS,CAAC,UAAU,IAAI,OAAO,QAAQ,EAAG;AAC9E,QAAI,CAAC,SAAS,QAAQ,KAAK,QAAQ,GAAG,GAAG;AACvC,gBAAU,KAAK,EAAE,YAAY,IAAI,KAAK,SAAS,MAAM,QAAQ,cAAc,CAAC;AAC5E;AAAA,IACF;AACA,UAAM,IAAI,OAAO,QAAQ,IAAI,KAAK,WAAW,EAAE,WAAW,QAAQ,CAAC;AACnE,cAAU,KAAK,CAAC;AAChB,QAAI,CAAC,EAAE,QAAS;AAChB,UAAM,KAAK,EAAE,QAAQ,MAAM;AAC3B,UAAM,QAAQ,CAAC,MAAM,cAAc,GAAG,MAAM,MAAM,EAAE,CAAC,KAAK,EAAE,MAAM,cAAc,QAAQ;AACxF,WAAO,EAAE,YAAY,IAAI,KAAK,SAAS,EAAE,QAAQ,KAAK,IAAI,QAAQ,OAAO,IAAI,QAAQ,EAAE,OAAO;AAAA,EAChG;AACA,SAAO;AACT;","names":[]}