@splithub/node 0.2.3 → 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.cjs +2 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +4 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.js +2 -1
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
package/dist/index.cjs
CHANGED
|
@@ -89,6 +89,7 @@ async function rawResults(config, store, key, options = {}) {
|
|
|
89
89
|
status: experiment.status,
|
|
90
90
|
goal: goal2,
|
|
91
91
|
description: experiment.description ?? null,
|
|
92
|
+
name: experiment.name ?? null,
|
|
92
93
|
variants: rawVariants(experiment, observed, withRevenue),
|
|
93
94
|
...metrics?.length ? { metrics } : {},
|
|
94
95
|
days: Math.round(span * 10) / 10,
|
|
@@ -102,7 +103,7 @@ async function rawStatusTable(config, store) {
|
|
|
102
103
|
return all.map((exp) => {
|
|
103
104
|
const s = byKey.get(exp.key);
|
|
104
105
|
const days = s?.firstExposureAt && s.lastExposureAt ? Math.max(1, Math.ceil((s.lastExposureAt - s.firstExposureAt) / DAY_MS)) : 0;
|
|
105
|
-
return { experiment: exp.key, kind: exp.kind, status: exp.status, goal: exp.goal, description: exp.description ?? null, exposures: s?.exposures ?? 0, visitors: s?.visitors ?? 0, days };
|
|
106
|
+
return { experiment: exp.key, kind: exp.kind, status: exp.status, goal: exp.goal, description: exp.description ?? null, name: exp.name ?? null, exposures: s?.exposures ?? 0, visitors: s?.visitors ?? 0, days };
|
|
106
107
|
});
|
|
107
108
|
}
|
|
108
109
|
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/handler.ts","../src/raw.ts","../src/validate.ts","../src/nodeAdapter.ts","../src/attribution.ts","../src/store.ts","../src/conformance.ts"],"sourcesContent":["export { createSplitHubHandler } from './handler';\nexport type { HandlerOptions, FetchHandler } from './handler';\nexport { toNodeListener } from './nodeAdapter';\nexport { createMemoryStore } from './store';\nexport type { Store, StoredEvent, ExperimentSummary } from './store';\nexport { rawResults, rawStatusTable, resultsExperiment, ANALYSIS_UNAVAILABLE } from './raw';\nexport type { RawResults, RawStatusRow, RawVariant, RawMetric } from './raw';\nexport { validateBatch } from './validate';\nexport { ATTRIBUTION_SKEW_MS, GOAL_DAILY_CAP, attributeVariants, variantCountsSql, countsFromRow, revenueOf } from './attribution';\nexport type { VariantCounts, AttributedCounts, AttributionEvent, SqlDialect, VariantCountsSql, VariantCountsSqlOptions } from './attribution';\nexport type { StoreVariantCounts } from './store';\nexport { attributionConformance, sortCounts } from './conformance';\nexport type { ConformanceCase } from './conformance';\n","import { isCrawler } from '@splithub/core';\nimport type { SplitHubConfig } from '@splithub/core';\nimport { ANALYSIS_UNAVAILABLE, rawResults, rawStatusTable } from './raw';\nimport type { Store } from './store';\nimport { validateBatch } from './validate';\n\nexport interface HandlerOptions {\n config: SplitHubConfig;\n store: Store;\n /**\n * Protects the read endpoints (`/status`, `/results/:id`). When unset, they\n * are open, which is fine for local development only.\n */\n adminToken?: string;\n /** Allowed origins for CORS. Defaults to same-origin only (no CORS headers). */\n cors?: string[] | '*';\n}\n\n// Crawlers, link previews and headless audits render pages too; their exposures\n// would dilute every variant. Only a positive match counts: an empty UA or a\n// plain HTTP client is let through. The Next middleware forwards the visitor's\n// UA as `x-splithub-ua`, so that header wins over its own fetch's user-agent.\nexport const isBotUserAgent = (ua: string | null | undefined): boolean => isCrawler(ua);\nconst visitorUserAgent = (request: Request): string | null =>\n request.headers.get('x-splithub-ua') ?? request.headers.get('user-agent');\n\nexport type FetchHandler = (request: Request) => Promise<Response>;\n\n/**\n * One handler for ingest and results, mountable at any path:\n *\n * POST {base} → ingest an event batch\n * GET {base}/status → all experiments with exposures, visitors and days\n * GET {base}/results/:id → visitors, conversions, rate (and revenue) per variant\n *\n * Reads are raw counts; verdicts and recommendations are SplitHub Cloud's.\n * GET {base}/health → { ok: true }\n *\n * Works in Next.js route handlers, Remix, Hono, Bun, Deno and Node (via `toNodeListener`).\n */\nexport function createSplitHubHandler(options: HandlerOptions): FetchHandler {\n const { config, store } = options;\n\n const corsHeaders = (request: Request): Record<string, string> => {\n if (!options.cors) return {};\n const origin = request.headers.get('origin') ?? '';\n const allowed = options.cors === '*' ? '*' : options.cors.includes(origin) ? origin : '';\n if (!allowed) return {};\n return {\n 'access-control-allow-origin': allowed,\n 'access-control-allow-methods': 'GET, POST, OPTIONS',\n 'access-control-allow-headers': 'content-type, authorization',\n 'access-control-max-age': '86400',\n };\n };\n\n const json = (request: Request, body: unknown, status = 200): Response =>\n new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json', ...corsHeaders(request) } });\n\n const authorized = (request: Request): boolean => {\n if (!options.adminToken) return true;\n const header = request.headers.get('authorization') ?? '';\n return header === `Bearer ${options.adminToken}`;\n };\n\n return async (request) => {\n const url = new URL(request.url);\n const path = url.pathname.replace(/\\/+$/, '');\n const tail = path.split('/').slice(-2);\n\n if (request.method === 'OPTIONS') return new Response(null, { status: 204, headers: corsHeaders(request) });\n\n if (request.method === 'POST') {\n let body: unknown;\n try {\n body = await request.json();\n } catch {\n return json(request, { error: 'invalid JSON' }, 400);\n }\n const result = validateBatch(body, config.project);\n if (!result.ok) return json(request, { error: result.error }, 400);\n if (isBotUserAgent(visitorUserAgent(request))) return json(request, { ok: true, received: result.events.length, inserted: 0 }, 202);\n const inserted = await store.insertEvents(result.events);\n return json(request, { ok: true, received: result.events.length, inserted }, 202);\n }\n\n if (request.method === 'GET') {\n if (tail[1] === 'health') return json(request, { ok: true, project: config.project });\n if (!authorized(request)) return json(request, { error: 'unauthorized' }, 401);\n if (tail[1] === 'status') return json(request, { project: config.project, experiments: await rawStatusTable(config, store), analysis: ANALYSIS_UNAVAILABLE });\n if (tail[0] === 'results' && tail[1]) {\n const r = await rawResults(config, store, tail[1]);\n return r ? json(request, r) : json(request, { error: `unknown experiment \"${tail[1]}\"` }, 404);\n }\n }\n\n return json(request, { error: 'not found' }, 404);\n };\n}\n","import { getExperiment, HOLDOUT_KEY, holdoutExperiment, type Experiment, type SplitHubConfig } from '@splithub/core';\nimport type { ExperimentSummary, Store, StoreVariantCounts } from './store';\n\nconst DAY_MS = 86_400_000;\n\n/** Self-hosted reads give counts; verdicts and recommendations are computed by SplitHub Cloud. */\nexport const ANALYSIS_UNAVAILABLE = {\n available: false as const,\n message: 'Verdicts, stars and recommendations come with SplitHub Cloud.',\n url: 'https://splithub.io/cloud',\n};\n\nexport interface RawVariant {\n variant: string;\n /** Unique visitors counted in this variant (first exposure decides). */\n visitors: number;\n /** Visitors who reached the goal after their exposure. */\n conversions: number;\n /** conversions / visitors, 0 without visitors. */\n rate: number;\n /** Sum of per-visitor revenue, when the goal carries revenue. */\n revenue?: number;\n /** Sum of squared per-visitor revenue, when the store reports it. */\n revenueSumSq?: number;\n}\n\nexport interface RawMetric {\n metric: string;\n role: 'secondary' | 'guardrail';\n worse?: 'higher' | 'lower';\n variants: RawVariant[];\n}\n\nexport interface RawResults {\n experiment: string;\n kind: string;\n status: string;\n goal: string | null;\n description: string | null;\n /** Declared order: the first variant is the control. */\n variants: RawVariant[];\n metrics?: RawMetric[];\n /** Days between the first and the last exposure, one decimal; 0 without data. */\n days: number;\n analysis: typeof ANALYSIS_UNAVAILABLE;\n}\n\nexport interface RawStatusRow {\n experiment: string;\n kind: string;\n status: string;\n goal: string | null;\n description: string | null;\n exposures: number;\n visitors: number;\n /** Whole days with data, at least 1 once there is any; 0 without data. */\n days: number;\n}\n\n/** An experiment of the config, or the holdout comparison for `__holdout`. */\nexport function resultsExperiment(config: SplitHubConfig, key: string): Experiment | null {\n return getExperiment(config, key) ?? (key === HOLDOUT_KEY ? holdoutExperiment(config) : null);\n}\n\n/** Store rows in the config's order, silent variants as 0. */\nfunction rawVariants(experiment: Experiment, observed: StoreVariantCounts[], withRevenue: boolean): RawVariant[] {\n return experiment.variants.map((v) => {\n const row = observed.find((o) => o.variant === v.key);\n const visitors = row?.exposures ?? 0;\n const conversions = row?.conversions ?? 0;\n const revenue = row?.revenueSum ?? row?.revenue;\n return {\n variant: v.key,\n visitors,\n conversions,\n rate: visitors > 0 ? conversions / visitors : 0,\n ...(withRevenue && revenue !== undefined ? { revenue } : {}),\n ...(withRevenue && row?.revenueSumSq !== undefined ? { revenueSumSq: row.revenueSumSq } : {}),\n };\n });\n}\n\n/** Counts per variant for one experiment, its secondary and guardrail goals included. No statistics. */\nexport async function rawResults(config: SplitHubConfig, store: Store, key: string, options: { summary?: ExperimentSummary | null } = {}): Promise<RawResults | null> {\n const experiment = resultsExperiment(config, key);\n if (!experiment) return null;\n const goal = experiment.goal;\n const observed = goal ? await store.variantCounts(key, goal) : [];\n const goalHasRevenue = Boolean(goal && config.goals.find((g) => g.key === goal)?.revenue);\n const withRevenue = goalHasRevenue || observed.some((o) => (o.revenueSum ?? o.revenue ?? 0) !== 0);\n const summary = options.summary !== undefined ? options.summary : ((await store.summaries()).find((s) => s.experiment === key) ?? null);\n const span = summary?.firstExposureAt != null && summary.lastExposureAt != null ? (summary.lastExposureAt - summary.firstExposureAt) / DAY_MS : 0;\n\n const m = goal ? experiment.metrics : undefined;\n const metrics: RawMetric[] | undefined = m\n ? await Promise.all([\n ...m.secondary.map(async (metric) => ({ metric, role: 'secondary' as const, variants: rawVariants(experiment, await store.variantCounts(key, metric), false) })),\n ...m.guardrails.map(async (g) => ({ metric: g.goal, role: 'guardrail' as const, ...(g.worse ? { worse: g.worse } : {}), variants: rawVariants(experiment, await store.variantCounts(key, g.goal), false) })),\n ])\n : undefined;\n\n return {\n experiment: key,\n kind: experiment.kind,\n status: experiment.status,\n goal,\n description: experiment.description ?? null,\n variants: rawVariants(experiment, observed, withRevenue),\n ...(metrics?.length ? { metrics } : {}),\n days: Math.round(span * 10) / 10,\n analysis: ANALYSIS_UNAVAILABLE,\n };\n}\n\n/** Every experiment with exposures, visitors and days; the holdout once it has visitors. */\nexport async function rawStatusTable(config: SplitHubConfig, store: Store): Promise<RawStatusRow[]> {\n const byKey = new Map<string, ExperimentSummary>((await store.summaries()).map((s) => [s.experiment, s]));\n const holdout = holdoutExperiment(config);\n const all = holdout && byKey.has(HOLDOUT_KEY) ? [...config.experiments, holdout] : config.experiments;\n return all.map((exp) => {\n const s = byKey.get(exp.key);\n const days = s?.firstExposureAt && s.lastExposureAt ? Math.max(1, Math.ceil((s.lastExposureAt - s.firstExposureAt) / DAY_MS)) : 0;\n return { experiment: exp.key, kind: exp.kind, status: exp.status, goal: exp.goal, description: exp.description ?? null, exposures: s?.exposures ?? 0, visitors: s?.visitors ?? 0, days };\n });\n}\n","import { HOLDOUT_KEY, type EventBatch, type SplitHubEvent } from '@splithub/core';\nimport type { StoredEvent } from './store';\n\nconst ID = /^[a-z0-9_-]{8,64}$/i;\nconst KEY = /^[a-z0-9][a-z0-9_-]{0,63}$/;\nconst MAX_EVENTS = 500;\nconst MAX_PROPS_BYTES = 4096;\n/** Reject client timestamps more than this far from the server clock. */\nconst MAX_SKEW_MS = 7 * 24 * 60 * 60 * 1000;\n\nexport type ValidationResult = { ok: true; events: StoredEvent[] } | { ok: false; error: string };\n\n/** `expectedProject` null skips the name check (the caller already identified the project, e.g. by public key). */\nexport function validateBatch(body: unknown, expectedProject: string | null, now = Date.now()): ValidationResult {\n if (!body || typeof body !== 'object') return { ok: false, error: 'body must be a JSON object' };\n const batch = body as Partial<EventBatch>;\n if (typeof batch.project !== 'string') return { ok: false, error: '\"project\" must be a string' };\n if (expectedProject !== null && batch.project !== expectedProject) return { ok: false, error: `unknown project \"${batch.project}\"` };\n if (!Array.isArray(batch.events)) return { ok: false, error: '\"events\" must be an array' };\n if (batch.events.length === 0) return { ok: true, events: [] };\n if (batch.events.length > MAX_EVENTS) return { ok: false, error: `too many events (max ${MAX_EVENTS})` };\n\n const out: StoredEvent[] = [];\n for (const raw of batch.events as Partial<SplitHubEvent>[]) {\n const e = normalize(raw, now);\n if (typeof e === 'string') return { ok: false, error: e };\n out.push(e);\n }\n return { ok: true, events: out };\n}\n\nfunction normalize(e: Partial<SplitHubEvent>, now: number): StoredEvent | string {\n if (!e || typeof e !== 'object') return 'event must be an object';\n if (typeof e.id !== 'string' || !ID.test(e.id)) return 'event.id is invalid';\n if (typeof e.vid !== 'string' || e.vid.length === 0 || e.vid.length > 64) return 'event.vid is invalid';\n if (typeof e.sid !== 'string' || e.sid.length === 0 || e.sid.length > 64) return 'event.sid is invalid';\n if (typeof e.ts !== 'number' || !Number.isFinite(e.ts)) return 'event.ts must be a number';\n const ts = Math.abs(e.ts - now) > MAX_SKEW_MS ? now : Math.round(e.ts);\n const url = typeof e.url === 'string' ? e.url.slice(0, 512) : null;\n\n if (e.type === 'exposure') {\n if (typeof e.exp !== 'string' || !(KEY.test(e.exp) || e.exp === HOLDOUT_KEY)) return 'exposure.exp is invalid';\n if (typeof e.var !== 'string' || !KEY.test(e.var)) return 'exposure.var is invalid';\n return { id: e.id, type: 'exposure', experiment: e.exp, variant: e.var, goal: null, visitorId: e.vid, sessionId: e.sid, ts, url, props: null, receivedAt: now };\n }\n if (e.type === 'goal') {\n if (typeof e.goal !== 'string' || !KEY.test(e.goal)) return 'goal.goal is invalid';\n let props: Record<string, unknown> | null = null;\n if (e.props !== undefined) {\n if (!e.props || typeof e.props !== 'object' || Array.isArray(e.props)) return 'goal.props must be an object';\n if (JSON.stringify(e.props).length > MAX_PROPS_BYTES) return 'goal.props too large';\n props = e.props;\n }\n return { id: e.id, type: 'goal', experiment: null, variant: null, goal: e.goal, visitorId: e.vid, sessionId: e.sid, ts, url, props, receivedAt: now };\n }\n return `unknown event type \"${String((e as { type?: unknown }).type)}\"`;\n}\n","import type { IncomingMessage, ServerResponse } from 'node:http';\nimport type { FetchHandler } from './handler';\n\n/**\n * Adapt a fetch-style handler to Node's `http` / Express / Vite / Connect.\n *\n * http.createServer(toNodeListener(handler))\n * app.use('/api/splithub', toNodeListener(handler))\n * viteServer.middlewares.use('/api/splithub', toNodeListener(handler))\n */\nexport function toNodeListener(handler: FetchHandler): (req: IncomingMessage, res: ServerResponse) => void {\n return (req, res) => {\n void (async () => {\n try {\n const request = await toRequest(req);\n const response = await handler(request);\n res.statusCode = response.status;\n response.headers.forEach((value, key) => res.setHeader(key, value));\n const body = response.body ? Buffer.from(await response.arrayBuffer()) : null;\n res.end(body);\n } catch (error) {\n res.statusCode = 500;\n res.setHeader('content-type', 'application/json');\n res.end(JSON.stringify({ error: error instanceof Error ? error.message : 'internal error' }));\n }\n })();\n };\n}\n\nasync function toRequest(req: IncomingMessage): Promise<Request> {\n const host = req.headers.host ?? 'localhost';\n const proto = (req.headers['x-forwarded-proto'] as string | undefined) ?? 'http';\n // Connect-style mounts strip the prefix into req.url; prefer originalUrl when present.\n const rawUrl = (req as IncomingMessage & { originalUrl?: string }).originalUrl ?? req.url ?? '/';\n const url = new URL(rawUrl, `${proto}://${host}`);\n const headers = new Headers();\n for (const [key, value] of Object.entries(req.headers)) {\n if (Array.isArray(value)) value.forEach((v) => headers.append(key, v));\n else if (typeof value === 'string') headers.set(key, value);\n }\n const method = req.method ?? 'GET';\n // A fresh ArrayBuffer: newer DOM typings accept neither Node's Buffer nor a view over a\n // possibly shared buffer as BodyInit.\n let body: ArrayBuffer | undefined;\n if (method !== 'GET' && method !== 'HEAD') {\n const chunks: Buffer[] = [];\n for await (const chunk of req) chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));\n const all = Buffer.concat(chunks);\n const copy = new Uint8Array(all.byteLength);\n copy.set(all);\n body = copy.buffer;\n }\n return new Request(url, { method, headers, body });\n}\n","// The one attribution rule every SplitHub store follows. The memory store\n// implements it in TypeScript (`attributeVariants`), the SQL stores run the\n// query from `variantCountsSql`, and the cloud applies it at ingest\n// (splithub-go/src/services/projectStore.ts). Change it here and there together.\n//\n// 1. A visitor counts once per experiment, in the variant of their earliest\n// exposure (same ts: smallest variant key).\n// 2. A goal converts that visitor when its ts is at or after the exposure,\n// minus ATTRIBUTION_SKEW_MS: the Next middleware stamps exposures with the\n// server clock while goals carry the browser clock.\n// 3. Goals from visitors who never saw the experiment are ignored.\n// 4. Only the first GOAL_DAILY_CAP events of one goal per visitor and UTC day\n// count (ordered by ts, then id); past that only a loop is talking.\n// 5. Revenue is the sum of numeric `props.revenue` over the counted goals,\n// per visitor; stores report the per-variant sum and sum of squares.\n\n/** How far a goal may precede the exposure it converts, for clock differences between server and browser. */\nexport const ATTRIBUTION_SKEW_MS = 60_000;\n/** Events of one goal from one visitor counted per UTC day. */\nexport const GOAL_DAILY_CAP = 50;\nconst DAY_MS = 86_400_000;\n\n/** Unique exposed and unique converted visitors of one variant. */\nexport interface VariantCounts {\n variant: string;\n exposures: number;\n conversions: number;\n revenue?: number;\n revenueSum?: number;\n revenueSumSq?: number;\n}\n\n/** Per-variant counts every store returns: `revenueSum` / `revenueSumSq` are over per-visitor revenue (non-converted visitors add 0). */\nexport interface AttributedCounts extends VariantCounts {\n revenue: number;\n revenueSum: number;\n revenueSumSq: number;\n}\n\n/** The shape of an event the rule needs. */\nexport interface AttributionEvent {\n id: string;\n type: 'exposure' | 'goal';\n experiment: string | null;\n variant: string | null;\n goal: string | null;\n visitorId: string;\n ts: number;\n props: Record<string, unknown> | null;\n}\n\nexport function revenueOf(props: Record<string, unknown> | null | undefined): number {\n const v = props?.revenue;\n return typeof v === 'number' && Number.isFinite(v) ? v : 0;\n}\n\n/** Reference implementation of the rule over events in memory. */\nexport function attributeVariants(events: Iterable<AttributionEvent>, experiment: string, goal: string): AttributedCounts[] {\n const first = new Map<string, { variant: string; ts: number }>();\n const goals = new Map<string, AttributionEvent[]>(); // visitor + day -> goal events\n for (const e of events) {\n if (e.type === 'exposure') {\n if (e.experiment !== experiment || !e.variant) continue;\n const prev = first.get(e.visitorId);\n if (prev === undefined || e.ts < prev.ts || (e.ts === prev.ts && e.variant < prev.variant)) first.set(e.visitorId, { variant: e.variant, ts: e.ts });\n } else if (e.goal === goal) {\n const key = `${e.visitorId}\\u0000${e.ts - (e.ts % DAY_MS)}`;\n const list = goals.get(key) ?? [];\n list.push(e);\n goals.set(key, list);\n }\n }\n const counted = new Map<string, number[]>(); // visitor -> ts of counted goals\n const revenueByVisitor = new Map<string, number[]>();\n for (const list of goals.values()) {\n list.sort((a, b) => a.ts - b.ts || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));\n for (const g of list.slice(0, GOAL_DAILY_CAP)) {\n (counted.get(g.visitorId) ?? counted.set(g.visitorId, []).get(g.visitorId)!).push(g.ts);\n (revenueByVisitor.get(g.visitorId) ?? revenueByVisitor.set(g.visitorId, []).get(g.visitorId)!).push(revenueOf(g.props));\n }\n }\n const out = new Map<string, AttributedCounts>();\n for (const [visitor, { variant, ts }] of first) {\n const row = out.get(variant) ?? { variant, exposures: 0, conversions: 0, revenue: 0, revenueSum: 0, revenueSumSq: 0 };\n row.exposures++;\n const times = counted.get(visitor) ?? [];\n const revenues = revenueByVisitor.get(visitor) ?? [];\n let converted = false;\n let revenue = 0;\n times.forEach((t, i) => {\n if (t < ts - ATTRIBUTION_SKEW_MS) return;\n converted = true;\n revenue += revenues[i]!;\n });\n if (converted) {\n row.conversions++;\n row.revenueSum += revenue;\n row.revenueSumSq += revenue * revenue;\n row.revenue = row.revenueSum;\n }\n out.set(variant, row);\n }\n return [...out.values()];\n}\n\nexport type SqlDialect = 'sqlite' | 'postgres' | 'mysql';\nexport type AttributionParam = 'experiment' | 'goal' | 'project';\n\nexport interface VariantCountsSqlOptions {\n dialect: SqlDialect;\n /** Events table. Defaults to \"splithub_events\". */\n table?: string;\n /** Column partitioning a shared table by project (adapter-d1); bound from the `project` param. */\n projectColumn?: string;\n}\n\nexport interface VariantCountsSql {\n sql: string;\n /** Names of the values to bind, in placeholder order (Postgres numbers them, so each name appears once). */\n params: AttributionParam[];\n /** Binds values in the right order. */\n bind(values: { experiment: string; goal: string; project?: string }): unknown[];\n}\n\nconst IDENT = /^[a-z_][a-z0-9_]*$/i;\n\nfunction revenueExpr(dialect: SqlDialect, alias: string): string {\n if (dialect === 'postgres') return `CASE WHEN jsonb_typeof(${alias}.props::jsonb -> 'revenue') = 'number' THEN (${alias}.props::jsonb ->> 'revenue')::float8 ELSE 0 END`;\n if (dialect === 'mysql') return `CASE WHEN JSON_TYPE(JSON_EXTRACT(${alias}.props, '$.revenue')) IN ('INTEGER', 'UNSIGNED INTEGER', 'DOUBLE', 'DECIMAL') THEN JSON_EXTRACT(${alias}.props, '$.revenue') + 0 ELSE 0 END`;\n return `CASE WHEN json_type(${alias}.props, '$.revenue') IN ('integer', 'real') THEN json_extract(${alias}.props, '$.revenue') ELSE 0 END`;\n}\n\n/**\n * The attribution query for an events table with the columns of the SplitHub\n * stores (id, type, experiment, variant, goal, visitor_id, ts, props). Returns\n * one row per variant: variant, exposures, conversions, revenue_sum,\n * revenue_sum_sq. Derived tables only, no CTEs or window functions, so the same\n * shape runs on SQLite, D1, Postgres and MySQL 5.7.\n */\nexport function variantCountsSql(options: VariantCountsSqlOptions): VariantCountsSql {\n const { dialect } = options;\n const t = options.table ?? 'splithub_events';\n if (!IDENT.test(t)) throw new Error('[splithub] invalid table name');\n if (options.projectColumn !== undefined && !IDENT.test(options.projectColumn)) throw new Error('[splithub] invalid column name');\n\n const params: AttributionParam[] = [];\n const p = (name: AttributionParam): string => {\n if (dialect === 'postgres') {\n const i = params.indexOf(name);\n if (i >= 0) return `$${i + 1}`;\n params.push(name);\n return `$${params.length}`;\n }\n params.push(name);\n return '?';\n };\n const proj = (alias: string): string => (options.projectColumn ? `${alias}.${options.projectColumn} = ${p('project')} AND ` : '');\n\n // Placeholders are produced in text order, so build the string front to back.\n const fv = `SELECT x.visitor_id, MIN(x.ts) AS first_ts FROM ${t} x WHERE ${proj('x')}x.type = 'exposure' AND x.experiment = ${p('experiment')} GROUP BY x.visitor_id`;\n const fe = `SELECT MIN(e.variant) AS variant, fv.visitor_id, fv.first_ts\n FROM (${fv}) fv\n JOIN ${t} e ON ${proj('e')}e.type = 'exposure' AND e.experiment = ${p('experiment')} AND e.visitor_id = fv.visitor_id AND e.ts = fv.first_ts\n GROUP BY fv.visitor_id, fv.first_ts`;\n const goalJoin = `${proj('g')}g.type = 'goal' AND g.goal = ${p('goal')} AND g.visitor_id = fe.visitor_id AND g.ts >= fe.first_ts - ${ATTRIBUTION_SKEW_MS}\n AND (SELECT COUNT(*) FROM ${t} g2\n WHERE ${proj('g2')}g2.type = 'goal' AND g2.goal = g.goal AND g2.visitor_id = g.visitor_id\n AND g2.ts >= g.ts - (g.ts % ${DAY_MS}) AND (g2.ts < g.ts OR (g2.ts = g.ts AND g2.id < g.id))) < ${GOAL_DAILY_CAP}`;\n const sql = `SELECT v.variant AS variant, COUNT(*) AS exposures, SUM(v.converted) AS conversions,\n COALESCE(SUM(v.revenue), 0) AS revenue_sum, COALESCE(SUM(v.revenue * v.revenue), 0) AS revenue_sum_sq\nFROM (\n SELECT fe.variant, fe.visitor_id,\n CASE WHEN COUNT(g.id) > 0 THEN 1 ELSE 0 END AS converted,\n COALESCE(SUM(${revenueExpr(dialect, 'g')}), 0) AS revenue\n FROM (${fe}) fe\n LEFT JOIN ${t} g ON ${goalJoin}\n GROUP BY fe.variant, fe.visitor_id\n) v\nGROUP BY v.variant`;\n\n return {\n sql,\n params,\n bind(values) {\n return params.map((name) => {\n const v = values[name];\n if (v === undefined) throw new Error(`[splithub] missing \"${name}\" for the attribution query`);\n return v;\n });\n },\n };\n}\n\n/** Turns a row of `variantCountsSql` (numbers may come back as strings from pg / mysql2) into counts. */\nexport function countsFromRow(row: Record<string, unknown>): AttributedCounts {\n const revenueSum = Number(row.revenue_sum ?? 0);\n return {\n variant: String(row.variant),\n exposures: Number(row.exposures ?? 0),\n conversions: Number(row.conversions ?? 0),\n revenue: revenueSum,\n revenueSum,\n revenueSumSq: Number(row.revenue_sum_sq ?? 0),\n };\n}\n","import { attributeVariants, type AttributedCounts } from './attribution';\n\n/** One row in the events table, whatever the backing database. */\nexport interface StoredEvent {\n id: string;\n type: 'exposure' | 'goal';\n experiment: string | null;\n variant: string | null;\n goal: string | null;\n visitorId: string;\n sessionId: string;\n /** Unix ms, as reported by the client. */\n ts: number;\n url: string | null;\n props: Record<string, unknown> | null;\n /** Unix ms, server clock. */\n receivedAt: number;\n /** Request metadata filled by the ingest endpoint (origin host, GeoIP country, UA device/browser). */\n host?: string | null;\n country?: string | null;\n device?: string | null;\n browser?: string | null;\n /** Extra dimensions (SplitHub Cloud, `d1Store({ meta: 'extended' })`): OS, language, geo, referrer, UTM. */\n os?: string | null;\n language?: string | null;\n city?: string | null;\n region?: string | null;\n referrer?: string | null;\n utm_source?: string | null;\n utm_medium?: string | null;\n utm_campaign?: string | null;\n utm_term?: string | null;\n utm_content?: string | null;\n}\n\nexport interface ExperimentSummary {\n experiment: string;\n exposures: number;\n visitors: number;\n firstExposureAt: number | null;\n lastExposureAt: number | null;\n}\n\n/** What `variantCounts` returns. Older custom stores may omit the revenue fields; `revenue` then stands for the sum. */\nexport type StoreVariantCounts = Omit<AttributedCounts, 'revenue' | 'revenueSum' | 'revenueSumSq'> &\n Partial<Pick<AttributedCounts, 'revenue' | 'revenueSum' | 'revenueSumSq'>>;\n\n/**\n * Storage adapter. Implement this against your database to keep all data in\n * your own infrastructure. `variantCounts` follows the rule in `./attribution`\n * (first exposure decides the variant, goals count from 60 s before it, at most\n * 50 of one goal per visitor and day); SQL databases can run `variantCountsSql`.\n */\nexport interface Store {\n /** Insert events, ignoring ids already present. Returns the number inserted. */\n insertEvents(events: StoredEvent[]): Promise<number>;\n /** Unique exposed and converted visitors per variant (any order), with per-visitor revenue sum and sum of squares. */\n variantCounts(experiment: string, goal: string): Promise<StoreVariantCounts[]>;\n summaries(): Promise<ExperimentSummary[]>;\n close?(): Promise<void> | void;\n}\n\n/** In-memory store for tests and quick local runs. Not persistent. */\nexport function createMemoryStore(): Store & { events: StoredEvent[] } {\n const events: StoredEvent[] = [];\n const ids = new Set<string>();\n return {\n events,\n async insertEvents(batch) {\n let n = 0;\n for (const e of batch) {\n if (ids.has(e.id)) continue;\n ids.add(e.id);\n events.push(e);\n n++;\n }\n return n;\n },\n async variantCounts(experiment, goal) {\n return attributeVariants(events, experiment, goal);\n },\n async summaries() {\n const map = new Map<string, ExperimentSummary & { visitorSet: Set<string> }>();\n for (const e of events) {\n if (e.type !== 'exposure' || !e.experiment) continue;\n const s = map.get(e.experiment) ?? {\n experiment: e.experiment,\n exposures: 0,\n visitors: 0,\n firstExposureAt: null,\n lastExposureAt: null,\n visitorSet: new Set<string>(),\n };\n s.exposures++;\n s.visitorSet.add(e.visitorId);\n s.firstExposureAt = s.firstExposureAt === null ? e.ts : Math.min(s.firstExposureAt, e.ts);\n s.lastExposureAt = s.lastExposureAt === null ? e.ts : Math.max(s.lastExposureAt, e.ts);\n map.set(e.experiment, s);\n }\n return [...map.values()].map(({ visitorSet, ...s }) => ({ ...s, visitors: visitorSet.size }));\n },\n };\n}\n","// Shared cases for the attribution rule (./attribution). Every store's tests\n// insert `events` and compare `variantCounts(experiment, goal)`, sorted with\n// `sortCounts`, to `expected`. Plain data so this ships without a test runner.\n\nimport { ATTRIBUTION_SKEW_MS, GOAL_DAILY_CAP, type AttributedCounts } from './attribution';\nimport type { StoreVariantCounts, StoredEvent } from './store';\n\nexport interface ConformanceCase {\n name: string;\n experiment: string;\n goal: string;\n events: StoredEvent[];\n expected: AttributedCounts[];\n /**\n * The cloud decides at ingest in arrival order, so a later-arriving exposure\n * with an earlier ts cannot move a visitor. Cases that depend on that are\n * only for the read-time stores.\n */\n readTimeOnly?: boolean;\n}\n\nconst T = Date.UTC(2026, 0, 10, 12, 0, 0);\nconst DAY = 86_400_000;\nlet seq = 0;\n\nfunction exposure(visitorId: string, variant: string, ts: number, experiment = 'hero'): StoredEvent {\n seq++;\n return { id: `exp_${String(seq).padStart(6, '0')}`, type: 'exposure', experiment, variant, goal: null, visitorId, sessionId: `s_${visitorId}`, ts, url: null, props: null, receivedAt: ts };\n}\nfunction goal(visitorId: string, ts: number, revenue?: unknown, key = 'signup'): StoredEvent {\n seq++;\n return { id: `goal_${String(seq).padStart(6, '0')}`, type: 'goal', experiment: null, variant: null, goal: key, visitorId, sessionId: `s_${visitorId}`, ts, url: null, props: revenue === undefined ? null : { revenue }, receivedAt: ts };\n}\nfunction counts(variant: string, exposures: number, conversions: number, revenueSum = 0, revenueSumSq = 0): AttributedCounts {\n return { variant, exposures, conversions, revenue: revenueSum, revenueSum, revenueSumSq };\n}\n\nexport const attributionConformance: ConformanceCase[] = [\n {\n name: 'a visitor belongs to the variant of their earliest exposure (tie: smallest key)',\n experiment: 'hero',\n goal: 'signup',\n readTimeOnly: true,\n events: [\n exposure('v1', 'control', T + 1000),\n exposure('v1', 'bold', T), // earlier, arrives later\n goal('v1', T + 5000),\n exposure('v2', 'control', T),\n exposure('v2', 'bold', T),\n exposure('v3', 'bold', T),\n exposure('v4', 'control', T),\n ],\n expected: [counts('bold', 3, 1), counts('control', 1, 0)],\n },\n {\n name: 'counts unique visitors, not events',\n experiment: 'hero',\n goal: 'signup',\n events: [exposure('v1', 'control', T), exposure('v1', 'control', T + 10), exposure('v1', 'bold', T + 20), goal('v1', T + 30), goal('v1', T + 40), exposure('v2', 'bold', T)],\n expected: [counts('bold', 1, 0), counts('control', 1, 1)],\n },\n {\n name: 'goals well before the exposure, of other goals or from unexposed visitors do not convert',\n experiment: 'hero',\n goal: 'signup',\n events: [\n exposure('v1', 'control', T),\n goal('v1', T - ATTRIBUTION_SKEW_MS - 1000, 9),\n goal('v1', T + 1000, 9, 'other'),\n exposure('other_exp', 'x', T, 'pricing'),\n goal('nobody', T + 1000, 9),\n goal('other_exp', T + 1000, 9),\n ],\n expected: [counts('control', 1, 0)],\n },\n {\n name: `a goal up to ${ATTRIBUTION_SKEW_MS / 1000} s before the exposure still counts (server vs browser clock)`,\n experiment: 'hero',\n goal: 'signup',\n events: [\n exposure('v1', 'control', T),\n goal('v1', T - ATTRIBUTION_SKEW_MS, 2),\n exposure('v2', 'bold', T),\n goal('v2', T - 30_000, 3),\n exposure('v3', 'bold', T),\n goal('v3', T - ATTRIBUTION_SKEW_MS - 1, 4),\n ],\n expected: [counts('bold', 2, 1, 3, 9), counts('control', 1, 1, 2, 4)],\n },\n {\n name: `at most ${GOAL_DAILY_CAP} of one goal per visitor and UTC day`,\n experiment: 'hero',\n goal: 'signup',\n events: [\n exposure('v1', 'control', T),\n ...Array.from({ length: GOAL_DAILY_CAP + 10 }, (_, i) => goal('v1', T + 1000 + i, 1)),\n ...Array.from({ length: 3 }, (_, i) => goal('v1', T + DAY + i, 1)),\n ],\n expected: [counts('control', 1, 1, GOAL_DAILY_CAP + 3, (GOAL_DAILY_CAP + 3) ** 2)],\n },\n {\n name: 'revenue is summed per visitor; variants report the sum and the sum of squares',\n experiment: 'hero',\n goal: 'signup',\n events: [\n exposure('v1', 'control', T),\n goal('v1', T + 1000, 10),\n goal('v1', T + 2000, 5),\n exposure('v2', 'control', T),\n goal('v2', T + 1000, 20),\n exposure('v3', 'control', T),\n goal('v3', T + 1000, 'lots'),\n exposure('v4', 'control', T),\n exposure('v5', 'bold', T),\n goal('v5', T + 1000, 2.5),\n ],\n expected: [counts('bold', 1, 1, 2.5, 6.25), counts('control', 4, 3, 35, 625)],\n },\n];\n\n/** Sorts by variant and keeps the compared fields, so any store's output can be `toEqual`-ed with `expected`. */\nexport function sortCounts(rows: StoreVariantCounts[]): AttributedCounts[] {\n return rows\n .map((r) => {\n const revenueSum = r.revenueSum ?? r.revenue ?? 0;\n return { variant: r.variant, exposures: r.exposures, conversions: r.conversions, revenue: revenueSum, revenueSum, revenueSumSq: r.revenueSumSq ?? 0 };\n })\n .sort((a, b) => (a.variant < b.variant ? -1 : a.variant > b.variant ? 1 : 0));\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,IAAAA,eAA0B;;;ACA1B,kBAAoG;AAG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
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/handler.ts","../src/raw.ts","../src/validate.ts","../src/nodeAdapter.ts","../src/attribution.ts","../src/store.ts","../src/conformance.ts"],"sourcesContent":["export { createSplitHubHandler } from './handler';\nexport type { HandlerOptions, FetchHandler } from './handler';\nexport { toNodeListener } from './nodeAdapter';\nexport { createMemoryStore } from './store';\nexport type { Store, StoredEvent, ExperimentSummary } from './store';\nexport { rawResults, rawStatusTable, resultsExperiment, ANALYSIS_UNAVAILABLE } from './raw';\nexport type { RawResults, RawStatusRow, RawVariant, RawMetric } from './raw';\nexport { validateBatch } from './validate';\nexport { ATTRIBUTION_SKEW_MS, GOAL_DAILY_CAP, attributeVariants, variantCountsSql, countsFromRow, revenueOf } from './attribution';\nexport type { VariantCounts, AttributedCounts, AttributionEvent, SqlDialect, VariantCountsSql, VariantCountsSqlOptions } from './attribution';\nexport type { StoreVariantCounts } from './store';\nexport { attributionConformance, sortCounts } from './conformance';\nexport type { ConformanceCase } from './conformance';\n","import { isCrawler } from '@splithub/core';\nimport type { SplitHubConfig } from '@splithub/core';\nimport { ANALYSIS_UNAVAILABLE, rawResults, rawStatusTable } from './raw';\nimport type { Store } from './store';\nimport { validateBatch } from './validate';\n\nexport interface HandlerOptions {\n config: SplitHubConfig;\n store: Store;\n /**\n * Protects the read endpoints (`/status`, `/results/:id`). When unset, they\n * are open, which is fine for local development only.\n */\n adminToken?: string;\n /** Allowed origins for CORS. Defaults to same-origin only (no CORS headers). */\n cors?: string[] | '*';\n}\n\n// Crawlers, link previews and headless audits render pages too; their exposures\n// would dilute every variant. Only a positive match counts: an empty UA or a\n// plain HTTP client is let through. The Next middleware forwards the visitor's\n// UA as `x-splithub-ua`, so that header wins over its own fetch's user-agent.\nexport const isBotUserAgent = (ua: string | null | undefined): boolean => isCrawler(ua);\nconst visitorUserAgent = (request: Request): string | null =>\n request.headers.get('x-splithub-ua') ?? request.headers.get('user-agent');\n\nexport type FetchHandler = (request: Request) => Promise<Response>;\n\n/**\n * One handler for ingest and results, mountable at any path:\n *\n * POST {base} → ingest an event batch\n * GET {base}/status → all experiments with exposures, visitors and days\n * GET {base}/results/:id → visitors, conversions, rate (and revenue) per variant\n *\n * Reads are raw counts; verdicts and recommendations are SplitHub Cloud's.\n * GET {base}/health → { ok: true }\n *\n * Works in Next.js route handlers, Remix, Hono, Bun, Deno and Node (via `toNodeListener`).\n */\nexport function createSplitHubHandler(options: HandlerOptions): FetchHandler {\n const { config, store } = options;\n\n const corsHeaders = (request: Request): Record<string, string> => {\n if (!options.cors) return {};\n const origin = request.headers.get('origin') ?? '';\n const allowed = options.cors === '*' ? '*' : options.cors.includes(origin) ? origin : '';\n if (!allowed) return {};\n return {\n 'access-control-allow-origin': allowed,\n 'access-control-allow-methods': 'GET, POST, OPTIONS',\n 'access-control-allow-headers': 'content-type, authorization',\n 'access-control-max-age': '86400',\n };\n };\n\n const json = (request: Request, body: unknown, status = 200): Response =>\n new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json', ...corsHeaders(request) } });\n\n const authorized = (request: Request): boolean => {\n if (!options.adminToken) return true;\n const header = request.headers.get('authorization') ?? '';\n return header === `Bearer ${options.adminToken}`;\n };\n\n return async (request) => {\n const url = new URL(request.url);\n const path = url.pathname.replace(/\\/+$/, '');\n const tail = path.split('/').slice(-2);\n\n if (request.method === 'OPTIONS') return new Response(null, { status: 204, headers: corsHeaders(request) });\n\n if (request.method === 'POST') {\n let body: unknown;\n try {\n body = await request.json();\n } catch {\n return json(request, { error: 'invalid JSON' }, 400);\n }\n const result = validateBatch(body, config.project);\n if (!result.ok) return json(request, { error: result.error }, 400);\n if (isBotUserAgent(visitorUserAgent(request))) return json(request, { ok: true, received: result.events.length, inserted: 0 }, 202);\n const inserted = await store.insertEvents(result.events);\n return json(request, { ok: true, received: result.events.length, inserted }, 202);\n }\n\n if (request.method === 'GET') {\n if (tail[1] === 'health') return json(request, { ok: true, project: config.project });\n if (!authorized(request)) return json(request, { error: 'unauthorized' }, 401);\n if (tail[1] === 'status') return json(request, { project: config.project, experiments: await rawStatusTable(config, store), analysis: ANALYSIS_UNAVAILABLE });\n if (tail[0] === 'results' && tail[1]) {\n const r = await rawResults(config, store, tail[1]);\n return r ? json(request, r) : json(request, { error: `unknown experiment \"${tail[1]}\"` }, 404);\n }\n }\n\n return json(request, { error: 'not found' }, 404);\n };\n}\n","import { getExperiment, HOLDOUT_KEY, holdoutExperiment, type Experiment, type SplitHubConfig } from '@splithub/core';\nimport type { ExperimentSummary, Store, StoreVariantCounts } from './store';\n\nconst DAY_MS = 86_400_000;\n\n/** Self-hosted reads give counts; verdicts and recommendations are computed by SplitHub Cloud. */\nexport const ANALYSIS_UNAVAILABLE = {\n available: false as const,\n message: 'Verdicts, stars and recommendations come with SplitHub Cloud.',\n url: 'https://splithub.io/cloud',\n};\n\nexport interface RawVariant {\n variant: string;\n /** Unique visitors counted in this variant (first exposure decides). */\n visitors: number;\n /** Visitors who reached the goal after their exposure. */\n conversions: number;\n /** conversions / visitors, 0 without visitors. */\n rate: number;\n /** Sum of per-visitor revenue, when the goal carries revenue. */\n revenue?: number;\n /** Sum of squared per-visitor revenue, when the store reports it. */\n revenueSumSq?: number;\n}\n\nexport interface RawMetric {\n metric: string;\n role: 'secondary' | 'guardrail';\n worse?: 'higher' | 'lower';\n variants: RawVariant[];\n}\n\nexport interface RawResults {\n experiment: string;\n kind: string;\n status: string;\n goal: string | null;\n description: string | null;\n /** Human name; null = show the key. */\n name: string | null;\n /** Declared order: the first variant is the control. */\n variants: RawVariant[];\n metrics?: RawMetric[];\n /** Days between the first and the last exposure, one decimal; 0 without data. */\n days: number;\n analysis: typeof ANALYSIS_UNAVAILABLE;\n}\n\nexport interface RawStatusRow {\n experiment: string;\n kind: string;\n status: string;\n goal: string | null;\n description: string | null;\n /** Human name; null = show the key. */\n name: string | null;\n exposures: number;\n visitors: number;\n /** Whole days with data, at least 1 once there is any; 0 without data. */\n days: number;\n}\n\n/** An experiment of the config, or the holdout comparison for `__holdout`. */\nexport function resultsExperiment(config: SplitHubConfig, key: string): Experiment | null {\n return getExperiment(config, key) ?? (key === HOLDOUT_KEY ? holdoutExperiment(config) : null);\n}\n\n/** Store rows in the config's order, silent variants as 0. */\nfunction rawVariants(experiment: Experiment, observed: StoreVariantCounts[], withRevenue: boolean): RawVariant[] {\n return experiment.variants.map((v) => {\n const row = observed.find((o) => o.variant === v.key);\n const visitors = row?.exposures ?? 0;\n const conversions = row?.conversions ?? 0;\n const revenue = row?.revenueSum ?? row?.revenue;\n return {\n variant: v.key,\n visitors,\n conversions,\n rate: visitors > 0 ? conversions / visitors : 0,\n ...(withRevenue && revenue !== undefined ? { revenue } : {}),\n ...(withRevenue && row?.revenueSumSq !== undefined ? { revenueSumSq: row.revenueSumSq } : {}),\n };\n });\n}\n\n/** Counts per variant for one experiment, its secondary and guardrail goals included. No statistics. */\nexport async function rawResults(config: SplitHubConfig, store: Store, key: string, options: { summary?: ExperimentSummary | null } = {}): Promise<RawResults | null> {\n const experiment = resultsExperiment(config, key);\n if (!experiment) return null;\n const goal = experiment.goal;\n const observed = goal ? await store.variantCounts(key, goal) : [];\n const goalHasRevenue = Boolean(goal && config.goals.find((g) => g.key === goal)?.revenue);\n const withRevenue = goalHasRevenue || observed.some((o) => (o.revenueSum ?? o.revenue ?? 0) !== 0);\n const summary = options.summary !== undefined ? options.summary : ((await store.summaries()).find((s) => s.experiment === key) ?? null);\n const span = summary?.firstExposureAt != null && summary.lastExposureAt != null ? (summary.lastExposureAt - summary.firstExposureAt) / DAY_MS : 0;\n\n const m = goal ? experiment.metrics : undefined;\n const metrics: RawMetric[] | undefined = m\n ? await Promise.all([\n ...m.secondary.map(async (metric) => ({ metric, role: 'secondary' as const, variants: rawVariants(experiment, await store.variantCounts(key, metric), false) })),\n ...m.guardrails.map(async (g) => ({ metric: g.goal, role: 'guardrail' as const, ...(g.worse ? { worse: g.worse } : {}), variants: rawVariants(experiment, await store.variantCounts(key, g.goal), false) })),\n ])\n : undefined;\n\n return {\n experiment: key,\n kind: experiment.kind,\n status: experiment.status,\n goal,\n description: experiment.description ?? null,\n name: experiment.name ?? null,\n variants: rawVariants(experiment, observed, withRevenue),\n ...(metrics?.length ? { metrics } : {}),\n days: Math.round(span * 10) / 10,\n analysis: ANALYSIS_UNAVAILABLE,\n };\n}\n\n/** Every experiment with exposures, visitors and days; the holdout once it has visitors. */\nexport async function rawStatusTable(config: SplitHubConfig, store: Store): Promise<RawStatusRow[]> {\n const byKey = new Map<string, ExperimentSummary>((await store.summaries()).map((s) => [s.experiment, s]));\n const holdout = holdoutExperiment(config);\n const all = holdout && byKey.has(HOLDOUT_KEY) ? [...config.experiments, holdout] : config.experiments;\n return all.map((exp) => {\n const s = byKey.get(exp.key);\n const days = s?.firstExposureAt && s.lastExposureAt ? Math.max(1, Math.ceil((s.lastExposureAt - s.firstExposureAt) / DAY_MS)) : 0;\n return { experiment: exp.key, kind: exp.kind, status: exp.status, goal: exp.goal, description: exp.description ?? null, name: exp.name ?? null, exposures: s?.exposures ?? 0, visitors: s?.visitors ?? 0, days };\n });\n}\n","import { HOLDOUT_KEY, type EventBatch, type SplitHubEvent } from '@splithub/core';\nimport type { StoredEvent } from './store';\n\nconst ID = /^[a-z0-9_-]{8,64}$/i;\nconst KEY = /^[a-z0-9][a-z0-9_-]{0,63}$/;\nconst MAX_EVENTS = 500;\nconst MAX_PROPS_BYTES = 4096;\n/** Reject client timestamps more than this far from the server clock. */\nconst MAX_SKEW_MS = 7 * 24 * 60 * 60 * 1000;\n\nexport type ValidationResult = { ok: true; events: StoredEvent[] } | { ok: false; error: string };\n\n/** `expectedProject` null skips the name check (the caller already identified the project, e.g. by public key). */\nexport function validateBatch(body: unknown, expectedProject: string | null, now = Date.now()): ValidationResult {\n if (!body || typeof body !== 'object') return { ok: false, error: 'body must be a JSON object' };\n const batch = body as Partial<EventBatch>;\n if (typeof batch.project !== 'string') return { ok: false, error: '\"project\" must be a string' };\n if (expectedProject !== null && batch.project !== expectedProject) return { ok: false, error: `unknown project \"${batch.project}\"` };\n if (!Array.isArray(batch.events)) return { ok: false, error: '\"events\" must be an array' };\n if (batch.events.length === 0) return { ok: true, events: [] };\n if (batch.events.length > MAX_EVENTS) return { ok: false, error: `too many events (max ${MAX_EVENTS})` };\n\n const out: StoredEvent[] = [];\n for (const raw of batch.events as Partial<SplitHubEvent>[]) {\n const e = normalize(raw, now);\n if (typeof e === 'string') return { ok: false, error: e };\n out.push(e);\n }\n return { ok: true, events: out };\n}\n\nfunction normalize(e: Partial<SplitHubEvent>, now: number): StoredEvent | string {\n if (!e || typeof e !== 'object') return 'event must be an object';\n if (typeof e.id !== 'string' || !ID.test(e.id)) return 'event.id is invalid';\n if (typeof e.vid !== 'string' || e.vid.length === 0 || e.vid.length > 64) return 'event.vid is invalid';\n if (typeof e.sid !== 'string' || e.sid.length === 0 || e.sid.length > 64) return 'event.sid is invalid';\n if (typeof e.ts !== 'number' || !Number.isFinite(e.ts)) return 'event.ts must be a number';\n const ts = Math.abs(e.ts - now) > MAX_SKEW_MS ? now : Math.round(e.ts);\n const url = typeof e.url === 'string' ? e.url.slice(0, 512) : null;\n\n if (e.type === 'exposure') {\n if (typeof e.exp !== 'string' || !(KEY.test(e.exp) || e.exp === HOLDOUT_KEY)) return 'exposure.exp is invalid';\n if (typeof e.var !== 'string' || !KEY.test(e.var)) return 'exposure.var is invalid';\n return { id: e.id, type: 'exposure', experiment: e.exp, variant: e.var, goal: null, visitorId: e.vid, sessionId: e.sid, ts, url, props: null, receivedAt: now };\n }\n if (e.type === 'goal') {\n if (typeof e.goal !== 'string' || !KEY.test(e.goal)) return 'goal.goal is invalid';\n let props: Record<string, unknown> | null = null;\n if (e.props !== undefined) {\n if (!e.props || typeof e.props !== 'object' || Array.isArray(e.props)) return 'goal.props must be an object';\n if (JSON.stringify(e.props).length > MAX_PROPS_BYTES) return 'goal.props too large';\n props = e.props;\n }\n return { id: e.id, type: 'goal', experiment: null, variant: null, goal: e.goal, visitorId: e.vid, sessionId: e.sid, ts, url, props, receivedAt: now };\n }\n return `unknown event type \"${String((e as { type?: unknown }).type)}\"`;\n}\n","import type { IncomingMessage, ServerResponse } from 'node:http';\nimport type { FetchHandler } from './handler';\n\n/**\n * Adapt a fetch-style handler to Node's `http` / Express / Vite / Connect.\n *\n * http.createServer(toNodeListener(handler))\n * app.use('/api/splithub', toNodeListener(handler))\n * viteServer.middlewares.use('/api/splithub', toNodeListener(handler))\n */\nexport function toNodeListener(handler: FetchHandler): (req: IncomingMessage, res: ServerResponse) => void {\n return (req, res) => {\n void (async () => {\n try {\n const request = await toRequest(req);\n const response = await handler(request);\n res.statusCode = response.status;\n response.headers.forEach((value, key) => res.setHeader(key, value));\n const body = response.body ? Buffer.from(await response.arrayBuffer()) : null;\n res.end(body);\n } catch (error) {\n res.statusCode = 500;\n res.setHeader('content-type', 'application/json');\n res.end(JSON.stringify({ error: error instanceof Error ? error.message : 'internal error' }));\n }\n })();\n };\n}\n\nasync function toRequest(req: IncomingMessage): Promise<Request> {\n const host = req.headers.host ?? 'localhost';\n const proto = (req.headers['x-forwarded-proto'] as string | undefined) ?? 'http';\n // Connect-style mounts strip the prefix into req.url; prefer originalUrl when present.\n const rawUrl = (req as IncomingMessage & { originalUrl?: string }).originalUrl ?? req.url ?? '/';\n const url = new URL(rawUrl, `${proto}://${host}`);\n const headers = new Headers();\n for (const [key, value] of Object.entries(req.headers)) {\n if (Array.isArray(value)) value.forEach((v) => headers.append(key, v));\n else if (typeof value === 'string') headers.set(key, value);\n }\n const method = req.method ?? 'GET';\n // A fresh ArrayBuffer: newer DOM typings accept neither Node's Buffer nor a view over a\n // possibly shared buffer as BodyInit.\n let body: ArrayBuffer | undefined;\n if (method !== 'GET' && method !== 'HEAD') {\n const chunks: Buffer[] = [];\n for await (const chunk of req) chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));\n const all = Buffer.concat(chunks);\n const copy = new Uint8Array(all.byteLength);\n copy.set(all);\n body = copy.buffer;\n }\n return new Request(url, { method, headers, body });\n}\n","// The one attribution rule every SplitHub store follows. The memory store\n// implements it in TypeScript (`attributeVariants`), the SQL stores run the\n// query from `variantCountsSql`, and the cloud applies it at ingest\n// (splithub-go/src/services/projectStore.ts). Change it here and there together.\n//\n// 1. A visitor counts once per experiment, in the variant of their earliest\n// exposure (same ts: smallest variant key).\n// 2. A goal converts that visitor when its ts is at or after the exposure,\n// minus ATTRIBUTION_SKEW_MS: the Next middleware stamps exposures with the\n// server clock while goals carry the browser clock.\n// 3. Goals from visitors who never saw the experiment are ignored.\n// 4. Only the first GOAL_DAILY_CAP events of one goal per visitor and UTC day\n// count (ordered by ts, then id); past that only a loop is talking.\n// 5. Revenue is the sum of numeric `props.revenue` over the counted goals,\n// per visitor; stores report the per-variant sum and sum of squares.\n\n/** How far a goal may precede the exposure it converts, for clock differences between server and browser. */\nexport const ATTRIBUTION_SKEW_MS = 60_000;\n/** Events of one goal from one visitor counted per UTC day. */\nexport const GOAL_DAILY_CAP = 50;\nconst DAY_MS = 86_400_000;\n\n/** Unique exposed and unique converted visitors of one variant. */\nexport interface VariantCounts {\n variant: string;\n exposures: number;\n conversions: number;\n revenue?: number;\n revenueSum?: number;\n revenueSumSq?: number;\n}\n\n/** Per-variant counts every store returns: `revenueSum` / `revenueSumSq` are over per-visitor revenue (non-converted visitors add 0). */\nexport interface AttributedCounts extends VariantCounts {\n revenue: number;\n revenueSum: number;\n revenueSumSq: number;\n}\n\n/** The shape of an event the rule needs. */\nexport interface AttributionEvent {\n id: string;\n type: 'exposure' | 'goal';\n experiment: string | null;\n variant: string | null;\n goal: string | null;\n visitorId: string;\n ts: number;\n props: Record<string, unknown> | null;\n}\n\nexport function revenueOf(props: Record<string, unknown> | null | undefined): number {\n const v = props?.revenue;\n return typeof v === 'number' && Number.isFinite(v) ? v : 0;\n}\n\n/** Reference implementation of the rule over events in memory. */\nexport function attributeVariants(events: Iterable<AttributionEvent>, experiment: string, goal: string): AttributedCounts[] {\n const first = new Map<string, { variant: string; ts: number }>();\n const goals = new Map<string, AttributionEvent[]>(); // visitor + day -> goal events\n for (const e of events) {\n if (e.type === 'exposure') {\n if (e.experiment !== experiment || !e.variant) continue;\n const prev = first.get(e.visitorId);\n if (prev === undefined || e.ts < prev.ts || (e.ts === prev.ts && e.variant < prev.variant)) first.set(e.visitorId, { variant: e.variant, ts: e.ts });\n } else if (e.goal === goal) {\n const key = `${e.visitorId}\\u0000${e.ts - (e.ts % DAY_MS)}`;\n const list = goals.get(key) ?? [];\n list.push(e);\n goals.set(key, list);\n }\n }\n const counted = new Map<string, number[]>(); // visitor -> ts of counted goals\n const revenueByVisitor = new Map<string, number[]>();\n for (const list of goals.values()) {\n list.sort((a, b) => a.ts - b.ts || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));\n for (const g of list.slice(0, GOAL_DAILY_CAP)) {\n (counted.get(g.visitorId) ?? counted.set(g.visitorId, []).get(g.visitorId)!).push(g.ts);\n (revenueByVisitor.get(g.visitorId) ?? revenueByVisitor.set(g.visitorId, []).get(g.visitorId)!).push(revenueOf(g.props));\n }\n }\n const out = new Map<string, AttributedCounts>();\n for (const [visitor, { variant, ts }] of first) {\n const row = out.get(variant) ?? { variant, exposures: 0, conversions: 0, revenue: 0, revenueSum: 0, revenueSumSq: 0 };\n row.exposures++;\n const times = counted.get(visitor) ?? [];\n const revenues = revenueByVisitor.get(visitor) ?? [];\n let converted = false;\n let revenue = 0;\n times.forEach((t, i) => {\n if (t < ts - ATTRIBUTION_SKEW_MS) return;\n converted = true;\n revenue += revenues[i]!;\n });\n if (converted) {\n row.conversions++;\n row.revenueSum += revenue;\n row.revenueSumSq += revenue * revenue;\n row.revenue = row.revenueSum;\n }\n out.set(variant, row);\n }\n return [...out.values()];\n}\n\nexport type SqlDialect = 'sqlite' | 'postgres' | 'mysql';\nexport type AttributionParam = 'experiment' | 'goal' | 'project';\n\nexport interface VariantCountsSqlOptions {\n dialect: SqlDialect;\n /** Events table. Defaults to \"splithub_events\". */\n table?: string;\n /** Column partitioning a shared table by project (adapter-d1); bound from the `project` param. */\n projectColumn?: string;\n}\n\nexport interface VariantCountsSql {\n sql: string;\n /** Names of the values to bind, in placeholder order (Postgres numbers them, so each name appears once). */\n params: AttributionParam[];\n /** Binds values in the right order. */\n bind(values: { experiment: string; goal: string; project?: string }): unknown[];\n}\n\nconst IDENT = /^[a-z_][a-z0-9_]*$/i;\n\nfunction revenueExpr(dialect: SqlDialect, alias: string): string {\n if (dialect === 'postgres') return `CASE WHEN jsonb_typeof(${alias}.props::jsonb -> 'revenue') = 'number' THEN (${alias}.props::jsonb ->> 'revenue')::float8 ELSE 0 END`;\n if (dialect === 'mysql') return `CASE WHEN JSON_TYPE(JSON_EXTRACT(${alias}.props, '$.revenue')) IN ('INTEGER', 'UNSIGNED INTEGER', 'DOUBLE', 'DECIMAL') THEN JSON_EXTRACT(${alias}.props, '$.revenue') + 0 ELSE 0 END`;\n return `CASE WHEN json_type(${alias}.props, '$.revenue') IN ('integer', 'real') THEN json_extract(${alias}.props, '$.revenue') ELSE 0 END`;\n}\n\n/**\n * The attribution query for an events table with the columns of the SplitHub\n * stores (id, type, experiment, variant, goal, visitor_id, ts, props). Returns\n * one row per variant: variant, exposures, conversions, revenue_sum,\n * revenue_sum_sq. Derived tables only, no CTEs or window functions, so the same\n * shape runs on SQLite, D1, Postgres and MySQL 5.7.\n */\nexport function variantCountsSql(options: VariantCountsSqlOptions): VariantCountsSql {\n const { dialect } = options;\n const t = options.table ?? 'splithub_events';\n if (!IDENT.test(t)) throw new Error('[splithub] invalid table name');\n if (options.projectColumn !== undefined && !IDENT.test(options.projectColumn)) throw new Error('[splithub] invalid column name');\n\n const params: AttributionParam[] = [];\n const p = (name: AttributionParam): string => {\n if (dialect === 'postgres') {\n const i = params.indexOf(name);\n if (i >= 0) return `$${i + 1}`;\n params.push(name);\n return `$${params.length}`;\n }\n params.push(name);\n return '?';\n };\n const proj = (alias: string): string => (options.projectColumn ? `${alias}.${options.projectColumn} = ${p('project')} AND ` : '');\n\n // Placeholders are produced in text order, so build the string front to back.\n const fv = `SELECT x.visitor_id, MIN(x.ts) AS first_ts FROM ${t} x WHERE ${proj('x')}x.type = 'exposure' AND x.experiment = ${p('experiment')} GROUP BY x.visitor_id`;\n const fe = `SELECT MIN(e.variant) AS variant, fv.visitor_id, fv.first_ts\n FROM (${fv}) fv\n JOIN ${t} e ON ${proj('e')}e.type = 'exposure' AND e.experiment = ${p('experiment')} AND e.visitor_id = fv.visitor_id AND e.ts = fv.first_ts\n GROUP BY fv.visitor_id, fv.first_ts`;\n const goalJoin = `${proj('g')}g.type = 'goal' AND g.goal = ${p('goal')} AND g.visitor_id = fe.visitor_id AND g.ts >= fe.first_ts - ${ATTRIBUTION_SKEW_MS}\n AND (SELECT COUNT(*) FROM ${t} g2\n WHERE ${proj('g2')}g2.type = 'goal' AND g2.goal = g.goal AND g2.visitor_id = g.visitor_id\n AND g2.ts >= g.ts - (g.ts % ${DAY_MS}) AND (g2.ts < g.ts OR (g2.ts = g.ts AND g2.id < g.id))) < ${GOAL_DAILY_CAP}`;\n const sql = `SELECT v.variant AS variant, COUNT(*) AS exposures, SUM(v.converted) AS conversions,\n COALESCE(SUM(v.revenue), 0) AS revenue_sum, COALESCE(SUM(v.revenue * v.revenue), 0) AS revenue_sum_sq\nFROM (\n SELECT fe.variant, fe.visitor_id,\n CASE WHEN COUNT(g.id) > 0 THEN 1 ELSE 0 END AS converted,\n COALESCE(SUM(${revenueExpr(dialect, 'g')}), 0) AS revenue\n FROM (${fe}) fe\n LEFT JOIN ${t} g ON ${goalJoin}\n GROUP BY fe.variant, fe.visitor_id\n) v\nGROUP BY v.variant`;\n\n return {\n sql,\n params,\n bind(values) {\n return params.map((name) => {\n const v = values[name];\n if (v === undefined) throw new Error(`[splithub] missing \"${name}\" for the attribution query`);\n return v;\n });\n },\n };\n}\n\n/** Turns a row of `variantCountsSql` (numbers may come back as strings from pg / mysql2) into counts. */\nexport function countsFromRow(row: Record<string, unknown>): AttributedCounts {\n const revenueSum = Number(row.revenue_sum ?? 0);\n return {\n variant: String(row.variant),\n exposures: Number(row.exposures ?? 0),\n conversions: Number(row.conversions ?? 0),\n revenue: revenueSum,\n revenueSum,\n revenueSumSq: Number(row.revenue_sum_sq ?? 0),\n };\n}\n","import { attributeVariants, type AttributedCounts } from './attribution';\n\n/** One row in the events table, whatever the backing database. */\nexport interface StoredEvent {\n id: string;\n type: 'exposure' | 'goal';\n experiment: string | null;\n variant: string | null;\n goal: string | null;\n visitorId: string;\n sessionId: string;\n /** Unix ms, as reported by the client. */\n ts: number;\n url: string | null;\n props: Record<string, unknown> | null;\n /** Unix ms, server clock. */\n receivedAt: number;\n /** Request metadata filled by the ingest endpoint (origin host, GeoIP country, UA device/browser). */\n host?: string | null;\n country?: string | null;\n device?: string | null;\n browser?: string | null;\n /** Extra dimensions (SplitHub Cloud, `d1Store({ meta: 'extended' })`): OS, language, geo, referrer, UTM. */\n os?: string | null;\n language?: string | null;\n city?: string | null;\n region?: string | null;\n referrer?: string | null;\n utm_source?: string | null;\n utm_medium?: string | null;\n utm_campaign?: string | null;\n utm_term?: string | null;\n utm_content?: string | null;\n}\n\nexport interface ExperimentSummary {\n experiment: string;\n exposures: number;\n visitors: number;\n firstExposureAt: number | null;\n lastExposureAt: number | null;\n}\n\n/** What `variantCounts` returns. Older custom stores may omit the revenue fields; `revenue` then stands for the sum. */\nexport type StoreVariantCounts = Omit<AttributedCounts, 'revenue' | 'revenueSum' | 'revenueSumSq'> &\n Partial<Pick<AttributedCounts, 'revenue' | 'revenueSum' | 'revenueSumSq'>>;\n\n/**\n * Storage adapter. Implement this against your database to keep all data in\n * your own infrastructure. `variantCounts` follows the rule in `./attribution`\n * (first exposure decides the variant, goals count from 60 s before it, at most\n * 50 of one goal per visitor and day); SQL databases can run `variantCountsSql`.\n */\nexport interface Store {\n /** Insert events, ignoring ids already present. Returns the number inserted. */\n insertEvents(events: StoredEvent[]): Promise<number>;\n /** Unique exposed and converted visitors per variant (any order), with per-visitor revenue sum and sum of squares. */\n variantCounts(experiment: string, goal: string): Promise<StoreVariantCounts[]>;\n summaries(): Promise<ExperimentSummary[]>;\n close?(): Promise<void> | void;\n}\n\n/** In-memory store for tests and quick local runs. Not persistent. */\nexport function createMemoryStore(): Store & { events: StoredEvent[] } {\n const events: StoredEvent[] = [];\n const ids = new Set<string>();\n return {\n events,\n async insertEvents(batch) {\n let n = 0;\n for (const e of batch) {\n if (ids.has(e.id)) continue;\n ids.add(e.id);\n events.push(e);\n n++;\n }\n return n;\n },\n async variantCounts(experiment, goal) {\n return attributeVariants(events, experiment, goal);\n },\n async summaries() {\n const map = new Map<string, ExperimentSummary & { visitorSet: Set<string> }>();\n for (const e of events) {\n if (e.type !== 'exposure' || !e.experiment) continue;\n const s = map.get(e.experiment) ?? {\n experiment: e.experiment,\n exposures: 0,\n visitors: 0,\n firstExposureAt: null,\n lastExposureAt: null,\n visitorSet: new Set<string>(),\n };\n s.exposures++;\n s.visitorSet.add(e.visitorId);\n s.firstExposureAt = s.firstExposureAt === null ? e.ts : Math.min(s.firstExposureAt, e.ts);\n s.lastExposureAt = s.lastExposureAt === null ? e.ts : Math.max(s.lastExposureAt, e.ts);\n map.set(e.experiment, s);\n }\n return [...map.values()].map(({ visitorSet, ...s }) => ({ ...s, visitors: visitorSet.size }));\n },\n };\n}\n","// Shared cases for the attribution rule (./attribution). Every store's tests\n// insert `events` and compare `variantCounts(experiment, goal)`, sorted with\n// `sortCounts`, to `expected`. Plain data so this ships without a test runner.\n\nimport { ATTRIBUTION_SKEW_MS, GOAL_DAILY_CAP, type AttributedCounts } from './attribution';\nimport type { StoreVariantCounts, StoredEvent } from './store';\n\nexport interface ConformanceCase {\n name: string;\n experiment: string;\n goal: string;\n events: StoredEvent[];\n expected: AttributedCounts[];\n /**\n * The cloud decides at ingest in arrival order, so a later-arriving exposure\n * with an earlier ts cannot move a visitor. Cases that depend on that are\n * only for the read-time stores.\n */\n readTimeOnly?: boolean;\n}\n\nconst T = Date.UTC(2026, 0, 10, 12, 0, 0);\nconst DAY = 86_400_000;\nlet seq = 0;\n\nfunction exposure(visitorId: string, variant: string, ts: number, experiment = 'hero'): StoredEvent {\n seq++;\n return { id: `exp_${String(seq).padStart(6, '0')}`, type: 'exposure', experiment, variant, goal: null, visitorId, sessionId: `s_${visitorId}`, ts, url: null, props: null, receivedAt: ts };\n}\nfunction goal(visitorId: string, ts: number, revenue?: unknown, key = 'signup'): StoredEvent {\n seq++;\n return { id: `goal_${String(seq).padStart(6, '0')}`, type: 'goal', experiment: null, variant: null, goal: key, visitorId, sessionId: `s_${visitorId}`, ts, url: null, props: revenue === undefined ? null : { revenue }, receivedAt: ts };\n}\nfunction counts(variant: string, exposures: number, conversions: number, revenueSum = 0, revenueSumSq = 0): AttributedCounts {\n return { variant, exposures, conversions, revenue: revenueSum, revenueSum, revenueSumSq };\n}\n\nexport const attributionConformance: ConformanceCase[] = [\n {\n name: 'a visitor belongs to the variant of their earliest exposure (tie: smallest key)',\n experiment: 'hero',\n goal: 'signup',\n readTimeOnly: true,\n events: [\n exposure('v1', 'control', T + 1000),\n exposure('v1', 'bold', T), // earlier, arrives later\n goal('v1', T + 5000),\n exposure('v2', 'control', T),\n exposure('v2', 'bold', T),\n exposure('v3', 'bold', T),\n exposure('v4', 'control', T),\n ],\n expected: [counts('bold', 3, 1), counts('control', 1, 0)],\n },\n {\n name: 'counts unique visitors, not events',\n experiment: 'hero',\n goal: 'signup',\n events: [exposure('v1', 'control', T), exposure('v1', 'control', T + 10), exposure('v1', 'bold', T + 20), goal('v1', T + 30), goal('v1', T + 40), exposure('v2', 'bold', T)],\n expected: [counts('bold', 1, 0), counts('control', 1, 1)],\n },\n {\n name: 'goals well before the exposure, of other goals or from unexposed visitors do not convert',\n experiment: 'hero',\n goal: 'signup',\n events: [\n exposure('v1', 'control', T),\n goal('v1', T - ATTRIBUTION_SKEW_MS - 1000, 9),\n goal('v1', T + 1000, 9, 'other'),\n exposure('other_exp', 'x', T, 'pricing'),\n goal('nobody', T + 1000, 9),\n goal('other_exp', T + 1000, 9),\n ],\n expected: [counts('control', 1, 0)],\n },\n {\n name: `a goal up to ${ATTRIBUTION_SKEW_MS / 1000} s before the exposure still counts (server vs browser clock)`,\n experiment: 'hero',\n goal: 'signup',\n events: [\n exposure('v1', 'control', T),\n goal('v1', T - ATTRIBUTION_SKEW_MS, 2),\n exposure('v2', 'bold', T),\n goal('v2', T - 30_000, 3),\n exposure('v3', 'bold', T),\n goal('v3', T - ATTRIBUTION_SKEW_MS - 1, 4),\n ],\n expected: [counts('bold', 2, 1, 3, 9), counts('control', 1, 1, 2, 4)],\n },\n {\n name: `at most ${GOAL_DAILY_CAP} of one goal per visitor and UTC day`,\n experiment: 'hero',\n goal: 'signup',\n events: [\n exposure('v1', 'control', T),\n ...Array.from({ length: GOAL_DAILY_CAP + 10 }, (_, i) => goal('v1', T + 1000 + i, 1)),\n ...Array.from({ length: 3 }, (_, i) => goal('v1', T + DAY + i, 1)),\n ],\n expected: [counts('control', 1, 1, GOAL_DAILY_CAP + 3, (GOAL_DAILY_CAP + 3) ** 2)],\n },\n {\n name: 'revenue is summed per visitor; variants report the sum and the sum of squares',\n experiment: 'hero',\n goal: 'signup',\n events: [\n exposure('v1', 'control', T),\n goal('v1', T + 1000, 10),\n goal('v1', T + 2000, 5),\n exposure('v2', 'control', T),\n goal('v2', T + 1000, 20),\n exposure('v3', 'control', T),\n goal('v3', T + 1000, 'lots'),\n exposure('v4', 'control', T),\n exposure('v5', 'bold', T),\n goal('v5', T + 1000, 2.5),\n ],\n expected: [counts('bold', 1, 1, 2.5, 6.25), counts('control', 4, 3, 35, 625)],\n },\n];\n\n/** Sorts by variant and keeps the compared fields, so any store's output can be `toEqual`-ed with `expected`. */\nexport function sortCounts(rows: StoreVariantCounts[]): AttributedCounts[] {\n return rows\n .map((r) => {\n const revenueSum = r.revenueSum ?? r.revenue ?? 0;\n return { variant: r.variant, exposures: r.exposures, conversions: r.conversions, revenue: revenueSum, revenueSum, revenueSumSq: r.reven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IAAI,CAAC,MAAM;AACV,UAAM,aAAa,EAAE,cAAc,EAAE,WAAW;AAChD,WAAO,EAAE,SAAS,EAAE,SAAS,WAAW,EAAE,WAAW,aAAa,EAAE,aAAa,SAAS,YAAY,YAAY,cAAc,EAAE,gBAAgB,EAAE;AAAA,EACtJ,CAAC,EACA,KAAK,CAAC,GAAG,MAAO,EAAE,UAAU,EAAE,UAAU,KAAK,EAAE,UAAU,EAAE,UAAU,IAAI,CAAE;AAChF;","names":["import_core","goal","import_core","DAY_MS","goal","goal"]}
|
package/dist/index.d.cts
CHANGED
|
@@ -191,6 +191,8 @@ interface RawResults {
|
|
|
191
191
|
status: string;
|
|
192
192
|
goal: string | null;
|
|
193
193
|
description: string | null;
|
|
194
|
+
/** Human name; null = show the key. */
|
|
195
|
+
name: string | null;
|
|
194
196
|
/** Declared order: the first variant is the control. */
|
|
195
197
|
variants: RawVariant[];
|
|
196
198
|
metrics?: RawMetric[];
|
|
@@ -204,6 +206,8 @@ interface RawStatusRow {
|
|
|
204
206
|
status: string;
|
|
205
207
|
goal: string | null;
|
|
206
208
|
description: string | null;
|
|
209
|
+
/** Human name; null = show the key. */
|
|
210
|
+
name: string | null;
|
|
207
211
|
exposures: number;
|
|
208
212
|
visitors: number;
|
|
209
213
|
/** Whole days with data, at least 1 once there is any; 0 without data. */
|
package/dist/index.d.ts
CHANGED
|
@@ -191,6 +191,8 @@ interface RawResults {
|
|
|
191
191
|
status: string;
|
|
192
192
|
goal: string | null;
|
|
193
193
|
description: string | null;
|
|
194
|
+
/** Human name; null = show the key. */
|
|
195
|
+
name: string | null;
|
|
194
196
|
/** Declared order: the first variant is the control. */
|
|
195
197
|
variants: RawVariant[];
|
|
196
198
|
metrics?: RawMetric[];
|
|
@@ -204,6 +206,8 @@ interface RawStatusRow {
|
|
|
204
206
|
status: string;
|
|
205
207
|
goal: string | null;
|
|
206
208
|
description: string | null;
|
|
209
|
+
/** Human name; null = show the key. */
|
|
210
|
+
name: string | null;
|
|
207
211
|
exposures: number;
|
|
208
212
|
visitors: number;
|
|
209
213
|
/** Whole days with data, at least 1 once there is any; 0 without data. */
|
package/dist/index.js
CHANGED
|
@@ -48,6 +48,7 @@ async function rawResults(config, store, key, options = {}) {
|
|
|
48
48
|
status: experiment.status,
|
|
49
49
|
goal: goal2,
|
|
50
50
|
description: experiment.description ?? null,
|
|
51
|
+
name: experiment.name ?? null,
|
|
51
52
|
variants: rawVariants(experiment, observed, withRevenue),
|
|
52
53
|
...metrics?.length ? { metrics } : {},
|
|
53
54
|
days: Math.round(span * 10) / 10,
|
|
@@ -61,7 +62,7 @@ async function rawStatusTable(config, store) {
|
|
|
61
62
|
return all.map((exp) => {
|
|
62
63
|
const s = byKey.get(exp.key);
|
|
63
64
|
const days = s?.firstExposureAt && s.lastExposureAt ? Math.max(1, Math.ceil((s.lastExposureAt - s.firstExposureAt) / DAY_MS)) : 0;
|
|
64
|
-
return { experiment: exp.key, kind: exp.kind, status: exp.status, goal: exp.goal, description: exp.description ?? null, exposures: s?.exposures ?? 0, visitors: s?.visitors ?? 0, days };
|
|
65
|
+
return { experiment: exp.key, kind: exp.kind, status: exp.status, goal: exp.goal, description: exp.description ?? null, name: exp.name ?? null, exposures: s?.exposures ?? 0, visitors: s?.visitors ?? 0, days };
|
|
65
66
|
});
|
|
66
67
|
}
|
|
67
68
|
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/handler.ts","../src/raw.ts","../src/validate.ts","../src/nodeAdapter.ts","../src/attribution.ts","../src/store.ts","../src/conformance.ts"],"sourcesContent":["import { isCrawler } from '@splithub/core';\nimport type { SplitHubConfig } from '@splithub/core';\nimport { ANALYSIS_UNAVAILABLE, rawResults, rawStatusTable } from './raw';\nimport type { Store } from './store';\nimport { validateBatch } from './validate';\n\nexport interface HandlerOptions {\n config: SplitHubConfig;\n store: Store;\n /**\n * Protects the read endpoints (`/status`, `/results/:id`). When unset, they\n * are open, which is fine for local development only.\n */\n adminToken?: string;\n /** Allowed origins for CORS. Defaults to same-origin only (no CORS headers). */\n cors?: string[] | '*';\n}\n\n// Crawlers, link previews and headless audits render pages too; their exposures\n// would dilute every variant. Only a positive match counts: an empty UA or a\n// plain HTTP client is let through. The Next middleware forwards the visitor's\n// UA as `x-splithub-ua`, so that header wins over its own fetch's user-agent.\nexport const isBotUserAgent = (ua: string | null | undefined): boolean => isCrawler(ua);\nconst visitorUserAgent = (request: Request): string | null =>\n request.headers.get('x-splithub-ua') ?? request.headers.get('user-agent');\n\nexport type FetchHandler = (request: Request) => Promise<Response>;\n\n/**\n * One handler for ingest and results, mountable at any path:\n *\n * POST {base} → ingest an event batch\n * GET {base}/status → all experiments with exposures, visitors and days\n * GET {base}/results/:id → visitors, conversions, rate (and revenue) per variant\n *\n * Reads are raw counts; verdicts and recommendations are SplitHub Cloud's.\n * GET {base}/health → { ok: true }\n *\n * Works in Next.js route handlers, Remix, Hono, Bun, Deno and Node (via `toNodeListener`).\n */\nexport function createSplitHubHandler(options: HandlerOptions): FetchHandler {\n const { config, store } = options;\n\n const corsHeaders = (request: Request): Record<string, string> => {\n if (!options.cors) return {};\n const origin = request.headers.get('origin') ?? '';\n const allowed = options.cors === '*' ? '*' : options.cors.includes(origin) ? origin : '';\n if (!allowed) return {};\n return {\n 'access-control-allow-origin': allowed,\n 'access-control-allow-methods': 'GET, POST, OPTIONS',\n 'access-control-allow-headers': 'content-type, authorization',\n 'access-control-max-age': '86400',\n };\n };\n\n const json = (request: Request, body: unknown, status = 200): Response =>\n new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json', ...corsHeaders(request) } });\n\n const authorized = (request: Request): boolean => {\n if (!options.adminToken) return true;\n const header = request.headers.get('authorization') ?? '';\n return header === `Bearer ${options.adminToken}`;\n };\n\n return async (request) => {\n const url = new URL(request.url);\n const path = url.pathname.replace(/\\/+$/, '');\n const tail = path.split('/').slice(-2);\n\n if (request.method === 'OPTIONS') return new Response(null, { status: 204, headers: corsHeaders(request) });\n\n if (request.method === 'POST') {\n let body: unknown;\n try {\n body = await request.json();\n } catch {\n return json(request, { error: 'invalid JSON' }, 400);\n }\n const result = validateBatch(body, config.project);\n if (!result.ok) return json(request, { error: result.error }, 400);\n if (isBotUserAgent(visitorUserAgent(request))) return json(request, { ok: true, received: result.events.length, inserted: 0 }, 202);\n const inserted = await store.insertEvents(result.events);\n return json(request, { ok: true, received: result.events.length, inserted }, 202);\n }\n\n if (request.method === 'GET') {\n if (tail[1] === 'health') return json(request, { ok: true, project: config.project });\n if (!authorized(request)) return json(request, { error: 'unauthorized' }, 401);\n if (tail[1] === 'status') return json(request, { project: config.project, experiments: await rawStatusTable(config, store), analysis: ANALYSIS_UNAVAILABLE });\n if (tail[0] === 'results' && tail[1]) {\n const r = await rawResults(config, store, tail[1]);\n return r ? json(request, r) : json(request, { error: `unknown experiment \"${tail[1]}\"` }, 404);\n }\n }\n\n return json(request, { error: 'not found' }, 404);\n };\n}\n","import { getExperiment, HOLDOUT_KEY, holdoutExperiment, type Experiment, type SplitHubConfig } from '@splithub/core';\nimport type { ExperimentSummary, Store, StoreVariantCounts } from './store';\n\nconst DAY_MS = 86_400_000;\n\n/** Self-hosted reads give counts; verdicts and recommendations are computed by SplitHub Cloud. */\nexport const ANALYSIS_UNAVAILABLE = {\n available: false as const,\n message: 'Verdicts, stars and recommendations come with SplitHub Cloud.',\n url: 'https://splithub.io/cloud',\n};\n\nexport interface RawVariant {\n variant: string;\n /** Unique visitors counted in this variant (first exposure decides). */\n visitors: number;\n /** Visitors who reached the goal after their exposure. */\n conversions: number;\n /** conversions / visitors, 0 without visitors. */\n rate: number;\n /** Sum of per-visitor revenue, when the goal carries revenue. */\n revenue?: number;\n /** Sum of squared per-visitor revenue, when the store reports it. */\n revenueSumSq?: number;\n}\n\nexport interface RawMetric {\n metric: string;\n role: 'secondary' | 'guardrail';\n worse?: 'higher' | 'lower';\n variants: RawVariant[];\n}\n\nexport interface RawResults {\n experiment: string;\n kind: string;\n status: string;\n goal: string | null;\n description: string | null;\n /** Declared order: the first variant is the control. */\n variants: RawVariant[];\n metrics?: RawMetric[];\n /** Days between the first and the last exposure, one decimal; 0 without data. */\n days: number;\n analysis: typeof ANALYSIS_UNAVAILABLE;\n}\n\nexport interface RawStatusRow {\n experiment: string;\n kind: string;\n status: string;\n goal: string | null;\n description: string | null;\n exposures: number;\n visitors: number;\n /** Whole days with data, at least 1 once there is any; 0 without data. */\n days: number;\n}\n\n/** An experiment of the config, or the holdout comparison for `__holdout`. */\nexport function resultsExperiment(config: SplitHubConfig, key: string): Experiment | null {\n return getExperiment(config, key) ?? (key === HOLDOUT_KEY ? holdoutExperiment(config) : null);\n}\n\n/** Store rows in the config's order, silent variants as 0. */\nfunction rawVariants(experiment: Experiment, observed: StoreVariantCounts[], withRevenue: boolean): RawVariant[] {\n return experiment.variants.map((v) => {\n const row = observed.find((o) => o.variant === v.key);\n const visitors = row?.exposures ?? 0;\n const conversions = row?.conversions ?? 0;\n const revenue = row?.revenueSum ?? row?.revenue;\n return {\n variant: v.key,\n visitors,\n conversions,\n rate: visitors > 0 ? conversions / visitors : 0,\n ...(withRevenue && revenue !== undefined ? { revenue } : {}),\n ...(withRevenue && row?.revenueSumSq !== undefined ? { revenueSumSq: row.revenueSumSq } : {}),\n };\n });\n}\n\n/** Counts per variant for one experiment, its secondary and guardrail goals included. No statistics. */\nexport async function rawResults(config: SplitHubConfig, store: Store, key: string, options: { summary?: ExperimentSummary | null } = {}): Promise<RawResults | null> {\n const experiment = resultsExperiment(config, key);\n if (!experiment) return null;\n const goal = experiment.goal;\n const observed = goal ? await store.variantCounts(key, goal) : [];\n const goalHasRevenue = Boolean(goal && config.goals.find((g) => g.key === goal)?.revenue);\n const withRevenue = goalHasRevenue || observed.some((o) => (o.revenueSum ?? o.revenue ?? 0) !== 0);\n const summary = options.summary !== undefined ? options.summary : ((await store.summaries()).find((s) => s.experiment === key) ?? null);\n const span = summary?.firstExposureAt != null && summary.lastExposureAt != null ? (summary.lastExposureAt - summary.firstExposureAt) / DAY_MS : 0;\n\n const m = goal ? experiment.metrics : undefined;\n const metrics: RawMetric[] | undefined = m\n ? await Promise.all([\n ...m.secondary.map(async (metric) => ({ metric, role: 'secondary' as const, variants: rawVariants(experiment, await store.variantCounts(key, metric), false) })),\n ...m.guardrails.map(async (g) => ({ metric: g.goal, role: 'guardrail' as const, ...(g.worse ? { worse: g.worse } : {}), variants: rawVariants(experiment, await store.variantCounts(key, g.goal), false) })),\n ])\n : undefined;\n\n return {\n experiment: key,\n kind: experiment.kind,\n status: experiment.status,\n goal,\n description: experiment.description ?? null,\n variants: rawVariants(experiment, observed, withRevenue),\n ...(metrics?.length ? { metrics } : {}),\n days: Math.round(span * 10) / 10,\n analysis: ANALYSIS_UNAVAILABLE,\n };\n}\n\n/** Every experiment with exposures, visitors and days; the holdout once it has visitors. */\nexport async function rawStatusTable(config: SplitHubConfig, store: Store): Promise<RawStatusRow[]> {\n const byKey = new Map<string, ExperimentSummary>((await store.summaries()).map((s) => [s.experiment, s]));\n const holdout = holdoutExperiment(config);\n const all = holdout && byKey.has(HOLDOUT_KEY) ? [...config.experiments, holdout] : config.experiments;\n return all.map((exp) => {\n const s = byKey.get(exp.key);\n const days = s?.firstExposureAt && s.lastExposureAt ? Math.max(1, Math.ceil((s.lastExposureAt - s.firstExposureAt) / DAY_MS)) : 0;\n return { experiment: exp.key, kind: exp.kind, status: exp.status, goal: exp.goal, description: exp.description ?? null, exposures: s?.exposures ?? 0, visitors: s?.visitors ?? 0, days };\n });\n}\n","import { HOLDOUT_KEY, type EventBatch, type SplitHubEvent } from '@splithub/core';\nimport type { StoredEvent } from './store';\n\nconst ID = /^[a-z0-9_-]{8,64}$/i;\nconst KEY = /^[a-z0-9][a-z0-9_-]{0,63}$/;\nconst MAX_EVENTS = 500;\nconst MAX_PROPS_BYTES = 4096;\n/** Reject client timestamps more than this far from the server clock. */\nconst MAX_SKEW_MS = 7 * 24 * 60 * 60 * 1000;\n\nexport type ValidationResult = { ok: true; events: StoredEvent[] } | { ok: false; error: string };\n\n/** `expectedProject` null skips the name check (the caller already identified the project, e.g. by public key). */\nexport function validateBatch(body: unknown, expectedProject: string | null, now = Date.now()): ValidationResult {\n if (!body || typeof body !== 'object') return { ok: false, error: 'body must be a JSON object' };\n const batch = body as Partial<EventBatch>;\n if (typeof batch.project !== 'string') return { ok: false, error: '\"project\" must be a string' };\n if (expectedProject !== null && batch.project !== expectedProject) return { ok: false, error: `unknown project \"${batch.project}\"` };\n if (!Array.isArray(batch.events)) return { ok: false, error: '\"events\" must be an array' };\n if (batch.events.length === 0) return { ok: true, events: [] };\n if (batch.events.length > MAX_EVENTS) return { ok: false, error: `too many events (max ${MAX_EVENTS})` };\n\n const out: StoredEvent[] = [];\n for (const raw of batch.events as Partial<SplitHubEvent>[]) {\n const e = normalize(raw, now);\n if (typeof e === 'string') return { ok: false, error: e };\n out.push(e);\n }\n return { ok: true, events: out };\n}\n\nfunction normalize(e: Partial<SplitHubEvent>, now: number): StoredEvent | string {\n if (!e || typeof e !== 'object') return 'event must be an object';\n if (typeof e.id !== 'string' || !ID.test(e.id)) return 'event.id is invalid';\n if (typeof e.vid !== 'string' || e.vid.length === 0 || e.vid.length > 64) return 'event.vid is invalid';\n if (typeof e.sid !== 'string' || e.sid.length === 0 || e.sid.length > 64) return 'event.sid is invalid';\n if (typeof e.ts !== 'number' || !Number.isFinite(e.ts)) return 'event.ts must be a number';\n const ts = Math.abs(e.ts - now) > MAX_SKEW_MS ? now : Math.round(e.ts);\n const url = typeof e.url === 'string' ? e.url.slice(0, 512) : null;\n\n if (e.type === 'exposure') {\n if (typeof e.exp !== 'string' || !(KEY.test(e.exp) || e.exp === HOLDOUT_KEY)) return 'exposure.exp is invalid';\n if (typeof e.var !== 'string' || !KEY.test(e.var)) return 'exposure.var is invalid';\n return { id: e.id, type: 'exposure', experiment: e.exp, variant: e.var, goal: null, visitorId: e.vid, sessionId: e.sid, ts, url, props: null, receivedAt: now };\n }\n if (e.type === 'goal') {\n if (typeof e.goal !== 'string' || !KEY.test(e.goal)) return 'goal.goal is invalid';\n let props: Record<string, unknown> | null = null;\n if (e.props !== undefined) {\n if (!e.props || typeof e.props !== 'object' || Array.isArray(e.props)) return 'goal.props must be an object';\n if (JSON.stringify(e.props).length > MAX_PROPS_BYTES) return 'goal.props too large';\n props = e.props;\n }\n return { id: e.id, type: 'goal', experiment: null, variant: null, goal: e.goal, visitorId: e.vid, sessionId: e.sid, ts, url, props, receivedAt: now };\n }\n return `unknown event type \"${String((e as { type?: unknown }).type)}\"`;\n}\n","import type { IncomingMessage, ServerResponse } from 'node:http';\nimport type { FetchHandler } from './handler';\n\n/**\n * Adapt a fetch-style handler to Node's `http` / Express / Vite / Connect.\n *\n * http.createServer(toNodeListener(handler))\n * app.use('/api/splithub', toNodeListener(handler))\n * viteServer.middlewares.use('/api/splithub', toNodeListener(handler))\n */\nexport function toNodeListener(handler: FetchHandler): (req: IncomingMessage, res: ServerResponse) => void {\n return (req, res) => {\n void (async () => {\n try {\n const request = await toRequest(req);\n const response = await handler(request);\n res.statusCode = response.status;\n response.headers.forEach((value, key) => res.setHeader(key, value));\n const body = response.body ? Buffer.from(await response.arrayBuffer()) : null;\n res.end(body);\n } catch (error) {\n res.statusCode = 500;\n res.setHeader('content-type', 'application/json');\n res.end(JSON.stringify({ error: error instanceof Error ? error.message : 'internal error' }));\n }\n })();\n };\n}\n\nasync function toRequest(req: IncomingMessage): Promise<Request> {\n const host = req.headers.host ?? 'localhost';\n const proto = (req.headers['x-forwarded-proto'] as string | undefined) ?? 'http';\n // Connect-style mounts strip the prefix into req.url; prefer originalUrl when present.\n const rawUrl = (req as IncomingMessage & { originalUrl?: string }).originalUrl ?? req.url ?? '/';\n const url = new URL(rawUrl, `${proto}://${host}`);\n const headers = new Headers();\n for (const [key, value] of Object.entries(req.headers)) {\n if (Array.isArray(value)) value.forEach((v) => headers.append(key, v));\n else if (typeof value === 'string') headers.set(key, value);\n }\n const method = req.method ?? 'GET';\n // A fresh ArrayBuffer: newer DOM typings accept neither Node's Buffer nor a view over a\n // possibly shared buffer as BodyInit.\n let body: ArrayBuffer | undefined;\n if (method !== 'GET' && method !== 'HEAD') {\n const chunks: Buffer[] = [];\n for await (const chunk of req) chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));\n const all = Buffer.concat(chunks);\n const copy = new Uint8Array(all.byteLength);\n copy.set(all);\n body = copy.buffer;\n }\n return new Request(url, { method, headers, body });\n}\n","// The one attribution rule every SplitHub store follows. The memory store\n// implements it in TypeScript (`attributeVariants`), the SQL stores run the\n// query from `variantCountsSql`, and the cloud applies it at ingest\n// (splithub-go/src/services/projectStore.ts). Change it here and there together.\n//\n// 1. A visitor counts once per experiment, in the variant of their earliest\n// exposure (same ts: smallest variant key).\n// 2. A goal converts that visitor when its ts is at or after the exposure,\n// minus ATTRIBUTION_SKEW_MS: the Next middleware stamps exposures with the\n// server clock while goals carry the browser clock.\n// 3. Goals from visitors who never saw the experiment are ignored.\n// 4. Only the first GOAL_DAILY_CAP events of one goal per visitor and UTC day\n// count (ordered by ts, then id); past that only a loop is talking.\n// 5. Revenue is the sum of numeric `props.revenue` over the counted goals,\n// per visitor; stores report the per-variant sum and sum of squares.\n\n/** How far a goal may precede the exposure it converts, for clock differences between server and browser. */\nexport const ATTRIBUTION_SKEW_MS = 60_000;\n/** Events of one goal from one visitor counted per UTC day. */\nexport const GOAL_DAILY_CAP = 50;\nconst DAY_MS = 86_400_000;\n\n/** Unique exposed and unique converted visitors of one variant. */\nexport interface VariantCounts {\n variant: string;\n exposures: number;\n conversions: number;\n revenue?: number;\n revenueSum?: number;\n revenueSumSq?: number;\n}\n\n/** Per-variant counts every store returns: `revenueSum` / `revenueSumSq` are over per-visitor revenue (non-converted visitors add 0). */\nexport interface AttributedCounts extends VariantCounts {\n revenue: number;\n revenueSum: number;\n revenueSumSq: number;\n}\n\n/** The shape of an event the rule needs. */\nexport interface AttributionEvent {\n id: string;\n type: 'exposure' | 'goal';\n experiment: string | null;\n variant: string | null;\n goal: string | null;\n visitorId: string;\n ts: number;\n props: Record<string, unknown> | null;\n}\n\nexport function revenueOf(props: Record<string, unknown> | null | undefined): number {\n const v = props?.revenue;\n return typeof v === 'number' && Number.isFinite(v) ? v : 0;\n}\n\n/** Reference implementation of the rule over events in memory. */\nexport function attributeVariants(events: Iterable<AttributionEvent>, experiment: string, goal: string): AttributedCounts[] {\n const first = new Map<string, { variant: string; ts: number }>();\n const goals = new Map<string, AttributionEvent[]>(); // visitor + day -> goal events\n for (const e of events) {\n if (e.type === 'exposure') {\n if (e.experiment !== experiment || !e.variant) continue;\n const prev = first.get(e.visitorId);\n if (prev === undefined || e.ts < prev.ts || (e.ts === prev.ts && e.variant < prev.variant)) first.set(e.visitorId, { variant: e.variant, ts: e.ts });\n } else if (e.goal === goal) {\n const key = `${e.visitorId}\\u0000${e.ts - (e.ts % DAY_MS)}`;\n const list = goals.get(key) ?? [];\n list.push(e);\n goals.set(key, list);\n }\n }\n const counted = new Map<string, number[]>(); // visitor -> ts of counted goals\n const revenueByVisitor = new Map<string, number[]>();\n for (const list of goals.values()) {\n list.sort((a, b) => a.ts - b.ts || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));\n for (const g of list.slice(0, GOAL_DAILY_CAP)) {\n (counted.get(g.visitorId) ?? counted.set(g.visitorId, []).get(g.visitorId)!).push(g.ts);\n (revenueByVisitor.get(g.visitorId) ?? revenueByVisitor.set(g.visitorId, []).get(g.visitorId)!).push(revenueOf(g.props));\n }\n }\n const out = new Map<string, AttributedCounts>();\n for (const [visitor, { variant, ts }] of first) {\n const row = out.get(variant) ?? { variant, exposures: 0, conversions: 0, revenue: 0, revenueSum: 0, revenueSumSq: 0 };\n row.exposures++;\n const times = counted.get(visitor) ?? [];\n const revenues = revenueByVisitor.get(visitor) ?? [];\n let converted = false;\n let revenue = 0;\n times.forEach((t, i) => {\n if (t < ts - ATTRIBUTION_SKEW_MS) return;\n converted = true;\n revenue += revenues[i]!;\n });\n if (converted) {\n row.conversions++;\n row.revenueSum += revenue;\n row.revenueSumSq += revenue * revenue;\n row.revenue = row.revenueSum;\n }\n out.set(variant, row);\n }\n return [...out.values()];\n}\n\nexport type SqlDialect = 'sqlite' | 'postgres' | 'mysql';\nexport type AttributionParam = 'experiment' | 'goal' | 'project';\n\nexport interface VariantCountsSqlOptions {\n dialect: SqlDialect;\n /** Events table. Defaults to \"splithub_events\". */\n table?: string;\n /** Column partitioning a shared table by project (adapter-d1); bound from the `project` param. */\n projectColumn?: string;\n}\n\nexport interface VariantCountsSql {\n sql: string;\n /** Names of the values to bind, in placeholder order (Postgres numbers them, so each name appears once). */\n params: AttributionParam[];\n /** Binds values in the right order. */\n bind(values: { experiment: string; goal: string; project?: string }): unknown[];\n}\n\nconst IDENT = /^[a-z_][a-z0-9_]*$/i;\n\nfunction revenueExpr(dialect: SqlDialect, alias: string): string {\n if (dialect === 'postgres') return `CASE WHEN jsonb_typeof(${alias}.props::jsonb -> 'revenue') = 'number' THEN (${alias}.props::jsonb ->> 'revenue')::float8 ELSE 0 END`;\n if (dialect === 'mysql') return `CASE WHEN JSON_TYPE(JSON_EXTRACT(${alias}.props, '$.revenue')) IN ('INTEGER', 'UNSIGNED INTEGER', 'DOUBLE', 'DECIMAL') THEN JSON_EXTRACT(${alias}.props, '$.revenue') + 0 ELSE 0 END`;\n return `CASE WHEN json_type(${alias}.props, '$.revenue') IN ('integer', 'real') THEN json_extract(${alias}.props, '$.revenue') ELSE 0 END`;\n}\n\n/**\n * The attribution query for an events table with the columns of the SplitHub\n * stores (id, type, experiment, variant, goal, visitor_id, ts, props). Returns\n * one row per variant: variant, exposures, conversions, revenue_sum,\n * revenue_sum_sq. Derived tables only, no CTEs or window functions, so the same\n * shape runs on SQLite, D1, Postgres and MySQL 5.7.\n */\nexport function variantCountsSql(options: VariantCountsSqlOptions): VariantCountsSql {\n const { dialect } = options;\n const t = options.table ?? 'splithub_events';\n if (!IDENT.test(t)) throw new Error('[splithub] invalid table name');\n if (options.projectColumn !== undefined && !IDENT.test(options.projectColumn)) throw new Error('[splithub] invalid column name');\n\n const params: AttributionParam[] = [];\n const p = (name: AttributionParam): string => {\n if (dialect === 'postgres') {\n const i = params.indexOf(name);\n if (i >= 0) return `$${i + 1}`;\n params.push(name);\n return `$${params.length}`;\n }\n params.push(name);\n return '?';\n };\n const proj = (alias: string): string => (options.projectColumn ? `${alias}.${options.projectColumn} = ${p('project')} AND ` : '');\n\n // Placeholders are produced in text order, so build the string front to back.\n const fv = `SELECT x.visitor_id, MIN(x.ts) AS first_ts FROM ${t} x WHERE ${proj('x')}x.type = 'exposure' AND x.experiment = ${p('experiment')} GROUP BY x.visitor_id`;\n const fe = `SELECT MIN(e.variant) AS variant, fv.visitor_id, fv.first_ts\n FROM (${fv}) fv\n JOIN ${t} e ON ${proj('e')}e.type = 'exposure' AND e.experiment = ${p('experiment')} AND e.visitor_id = fv.visitor_id AND e.ts = fv.first_ts\n GROUP BY fv.visitor_id, fv.first_ts`;\n const goalJoin = `${proj('g')}g.type = 'goal' AND g.goal = ${p('goal')} AND g.visitor_id = fe.visitor_id AND g.ts >= fe.first_ts - ${ATTRIBUTION_SKEW_MS}\n AND (SELECT COUNT(*) FROM ${t} g2\n WHERE ${proj('g2')}g2.type = 'goal' AND g2.goal = g.goal AND g2.visitor_id = g.visitor_id\n AND g2.ts >= g.ts - (g.ts % ${DAY_MS}) AND (g2.ts < g.ts OR (g2.ts = g.ts AND g2.id < g.id))) < ${GOAL_DAILY_CAP}`;\n const sql = `SELECT v.variant AS variant, COUNT(*) AS exposures, SUM(v.converted) AS conversions,\n COALESCE(SUM(v.revenue), 0) AS revenue_sum, COALESCE(SUM(v.revenue * v.revenue), 0) AS revenue_sum_sq\nFROM (\n SELECT fe.variant, fe.visitor_id,\n CASE WHEN COUNT(g.id) > 0 THEN 1 ELSE 0 END AS converted,\n COALESCE(SUM(${revenueExpr(dialect, 'g')}), 0) AS revenue\n FROM (${fe}) fe\n LEFT JOIN ${t} g ON ${goalJoin}\n GROUP BY fe.variant, fe.visitor_id\n) v\nGROUP BY v.variant`;\n\n return {\n sql,\n params,\n bind(values) {\n return params.map((name) => {\n const v = values[name];\n if (v === undefined) throw new Error(`[splithub] missing \"${name}\" for the attribution query`);\n return v;\n });\n },\n };\n}\n\n/** Turns a row of `variantCountsSql` (numbers may come back as strings from pg / mysql2) into counts. */\nexport function countsFromRow(row: Record<string, unknown>): AttributedCounts {\n const revenueSum = Number(row.revenue_sum ?? 0);\n return {\n variant: String(row.variant),\n exposures: Number(row.exposures ?? 0),\n conversions: Number(row.conversions ?? 0),\n revenue: revenueSum,\n revenueSum,\n revenueSumSq: Number(row.revenue_sum_sq ?? 0),\n };\n}\n","import { attributeVariants, type AttributedCounts } from './attribution';\n\n/** One row in the events table, whatever the backing database. */\nexport interface StoredEvent {\n id: string;\n type: 'exposure' | 'goal';\n experiment: string | null;\n variant: string | null;\n goal: string | null;\n visitorId: string;\n sessionId: string;\n /** Unix ms, as reported by the client. */\n ts: number;\n url: string | null;\n props: Record<string, unknown> | null;\n /** Unix ms, server clock. */\n receivedAt: number;\n /** Request metadata filled by the ingest endpoint (origin host, GeoIP country, UA device/browser). */\n host?: string | null;\n country?: string | null;\n device?: string | null;\n browser?: string | null;\n /** Extra dimensions (SplitHub Cloud, `d1Store({ meta: 'extended' })`): OS, language, geo, referrer, UTM. */\n os?: string | null;\n language?: string | null;\n city?: string | null;\n region?: string | null;\n referrer?: string | null;\n utm_source?: string | null;\n utm_medium?: string | null;\n utm_campaign?: string | null;\n utm_term?: string | null;\n utm_content?: string | null;\n}\n\nexport interface ExperimentSummary {\n experiment: string;\n exposures: number;\n visitors: number;\n firstExposureAt: number | null;\n lastExposureAt: number | null;\n}\n\n/** What `variantCounts` returns. Older custom stores may omit the revenue fields; `revenue` then stands for the sum. */\nexport type StoreVariantCounts = Omit<AttributedCounts, 'revenue' | 'revenueSum' | 'revenueSumSq'> &\n Partial<Pick<AttributedCounts, 'revenue' | 'revenueSum' | 'revenueSumSq'>>;\n\n/**\n * Storage adapter. Implement this against your database to keep all data in\n * your own infrastructure. `variantCounts` follows the rule in `./attribution`\n * (first exposure decides the variant, goals count from 60 s before it, at most\n * 50 of one goal per visitor and day); SQL databases can run `variantCountsSql`.\n */\nexport interface Store {\n /** Insert events, ignoring ids already present. Returns the number inserted. */\n insertEvents(events: StoredEvent[]): Promise<number>;\n /** Unique exposed and converted visitors per variant (any order), with per-visitor revenue sum and sum of squares. */\n variantCounts(experiment: string, goal: string): Promise<StoreVariantCounts[]>;\n summaries(): Promise<ExperimentSummary[]>;\n close?(): Promise<void> | void;\n}\n\n/** In-memory store for tests and quick local runs. Not persistent. */\nexport function createMemoryStore(): Store & { events: StoredEvent[] } {\n const events: StoredEvent[] = [];\n const ids = new Set<string>();\n return {\n events,\n async insertEvents(batch) {\n let n = 0;\n for (const e of batch) {\n if (ids.has(e.id)) continue;\n ids.add(e.id);\n events.push(e);\n n++;\n }\n return n;\n },\n async variantCounts(experiment, goal) {\n return attributeVariants(events, experiment, goal);\n },\n async summaries() {\n const map = new Map<string, ExperimentSummary & { visitorSet: Set<string> }>();\n for (const e of events) {\n if (e.type !== 'exposure' || !e.experiment) continue;\n const s = map.get(e.experiment) ?? {\n experiment: e.experiment,\n exposures: 0,\n visitors: 0,\n firstExposureAt: null,\n lastExposureAt: null,\n visitorSet: new Set<string>(),\n };\n s.exposures++;\n s.visitorSet.add(e.visitorId);\n s.firstExposureAt = s.firstExposureAt === null ? e.ts : Math.min(s.firstExposureAt, e.ts);\n s.lastExposureAt = s.lastExposureAt === null ? e.ts : Math.max(s.lastExposureAt, e.ts);\n map.set(e.experiment, s);\n }\n return [...map.values()].map(({ visitorSet, ...s }) => ({ ...s, visitors: visitorSet.size }));\n },\n };\n}\n","// Shared cases for the attribution rule (./attribution). Every store's tests\n// insert `events` and compare `variantCounts(experiment, goal)`, sorted with\n// `sortCounts`, to `expected`. Plain data so this ships without a test runner.\n\nimport { ATTRIBUTION_SKEW_MS, GOAL_DAILY_CAP, type AttributedCounts } from './attribution';\nimport type { StoreVariantCounts, StoredEvent } from './store';\n\nexport interface ConformanceCase {\n name: string;\n experiment: string;\n goal: string;\n events: StoredEvent[];\n expected: AttributedCounts[];\n /**\n * The cloud decides at ingest in arrival order, so a later-arriving exposure\n * with an earlier ts cannot move a visitor. Cases that depend on that are\n * only for the read-time stores.\n */\n readTimeOnly?: boolean;\n}\n\nconst T = Date.UTC(2026, 0, 10, 12, 0, 0);\nconst DAY = 86_400_000;\nlet seq = 0;\n\nfunction exposure(visitorId: string, variant: string, ts: number, experiment = 'hero'): StoredEvent {\n seq++;\n return { id: `exp_${String(seq).padStart(6, '0')}`, type: 'exposure', experiment, variant, goal: null, visitorId, sessionId: `s_${visitorId}`, ts, url: null, props: null, receivedAt: ts };\n}\nfunction goal(visitorId: string, ts: number, revenue?: unknown, key = 'signup'): StoredEvent {\n seq++;\n return { id: `goal_${String(seq).padStart(6, '0')}`, type: 'goal', experiment: null, variant: null, goal: key, visitorId, sessionId: `s_${visitorId}`, ts, url: null, props: revenue === undefined ? null : { revenue }, receivedAt: ts };\n}\nfunction counts(variant: string, exposures: number, conversions: number, revenueSum = 0, revenueSumSq = 0): AttributedCounts {\n return { variant, exposures, conversions, revenue: revenueSum, revenueSum, revenueSumSq };\n}\n\nexport const attributionConformance: ConformanceCase[] = [\n {\n name: 'a visitor belongs to the variant of their earliest exposure (tie: smallest key)',\n experiment: 'hero',\n goal: 'signup',\n readTimeOnly: true,\n events: [\n exposure('v1', 'control', T + 1000),\n exposure('v1', 'bold', T), // earlier, arrives later\n goal('v1', T + 5000),\n exposure('v2', 'control', T),\n exposure('v2', 'bold', T),\n exposure('v3', 'bold', T),\n exposure('v4', 'control', T),\n ],\n expected: [counts('bold', 3, 1), counts('control', 1, 0)],\n },\n {\n name: 'counts unique visitors, not events',\n experiment: 'hero',\n goal: 'signup',\n events: [exposure('v1', 'control', T), exposure('v1', 'control', T + 10), exposure('v1', 'bold', T + 20), goal('v1', T + 30), goal('v1', T + 40), exposure('v2', 'bold', T)],\n expected: [counts('bold', 1, 0), counts('control', 1, 1)],\n },\n {\n name: 'goals well before the exposure, of other goals or from unexposed visitors do not convert',\n experiment: 'hero',\n goal: 'signup',\n events: [\n exposure('v1', 'control', T),\n goal('v1', T - ATTRIBUTION_SKEW_MS - 1000, 9),\n goal('v1', T + 1000, 9, 'other'),\n exposure('other_exp', 'x', T, 'pricing'),\n goal('nobody', T + 1000, 9),\n goal('other_exp', T + 1000, 9),\n ],\n expected: [counts('control', 1, 0)],\n },\n {\n name: `a goal up to ${ATTRIBUTION_SKEW_MS / 1000} s before the exposure still counts (server vs browser clock)`,\n experiment: 'hero',\n goal: 'signup',\n events: [\n exposure('v1', 'control', T),\n goal('v1', T - ATTRIBUTION_SKEW_MS, 2),\n exposure('v2', 'bold', T),\n goal('v2', T - 30_000, 3),\n exposure('v3', 'bold', T),\n goal('v3', T - ATTRIBUTION_SKEW_MS - 1, 4),\n ],\n expected: [counts('bold', 2, 1, 3, 9), counts('control', 1, 1, 2, 4)],\n },\n {\n name: `at most ${GOAL_DAILY_CAP} of one goal per visitor and UTC day`,\n experiment: 'hero',\n goal: 'signup',\n events: [\n exposure('v1', 'control', T),\n ...Array.from({ length: GOAL_DAILY_CAP + 10 }, (_, i) => goal('v1', T + 1000 + i, 1)),\n ...Array.from({ length: 3 }, (_, i) => goal('v1', T + DAY + i, 1)),\n ],\n expected: [counts('control', 1, 1, GOAL_DAILY_CAP + 3, (GOAL_DAILY_CAP + 3) ** 2)],\n },\n {\n name: 'revenue is summed per visitor; variants report the sum and the sum of squares',\n experiment: 'hero',\n goal: 'signup',\n events: [\n exposure('v1', 'control', T),\n goal('v1', T + 1000, 10),\n goal('v1', T + 2000, 5),\n exposure('v2', 'control', T),\n goal('v2', T + 1000, 20),\n exposure('v3', 'control', T),\n goal('v3', T + 1000, 'lots'),\n exposure('v4', 'control', T),\n exposure('v5', 'bold', T),\n goal('v5', T + 1000, 2.5),\n ],\n expected: [counts('bold', 1, 1, 2.5, 6.25), counts('control', 4, 3, 35, 625)],\n },\n];\n\n/** Sorts by variant and keeps the compared fields, so any store's output can be `toEqual`-ed with `expected`. */\nexport function sortCounts(rows: StoreVariantCounts[]): AttributedCounts[] {\n return rows\n .map((r) => {\n const revenueSum = r.revenueSum ?? r.revenue ?? 0;\n return { variant: r.variant, exposures: r.exposures, conversions: r.conversions, revenue: revenueSum, revenueSum, revenueSumSq: r.revenueSumSq ?? 0 };\n })\n .sort((a, b) => (a.variant < b.variant ? -1 : a.variant > b.variant ? 1 : 0));\n}\n"],"mappings":";AAAA,SAAS,iBAAiB;;;ACA1B,SAAS,eAAe,aAAa,yBAA+D;AAGpG,IAAM,SAAS;AAGR,IAAM,uBAAuB;AAAA,EAClC,WAAW;AAAA,EACX,SAAS;AAAA,EACT,KAAK;AACP;AAkDO,SAAS,kBAAkB,QAAwB,KAAgC;AACxF,SAAO,cAAc,QAAQ,GAAG,MAAM,QAAQ,cAAc,kBAAkB,MAAM,IAAI;AAC1F;AAGA,SAAS,YAAY,YAAwB,UAAgC,aAAoC;AAC/G,SAAO,WAAW,SAAS,IAAI,CAAC,MAAM;AACpC,UAAM,MAAM,SAAS,KAAK,CAAC,MAAM,EAAE,YAAY,EAAE,GAAG;AACpD,UAAM,WAAW,KAAK,aAAa;AACnC,UAAM,cAAc,KAAK,eAAe;AACxC,UAAM,UAAU,KAAK,cAAc,KAAK;AACxC,WAAO;AAAA,MACL,SAAS,EAAE;AAAA,MACX;AAAA,MACA;AAAA,MACA,MAAM,WAAW,IAAI,cAAc,WAAW;AAAA,MAC9C,GAAI,eAAe,YAAY,SAAY,EAAE,QAAQ,IAAI,CAAC;AAAA,MAC1D,GAAI,eAAe,KAAK,iBAAiB,SAAY,EAAE,cAAc,IAAI,aAAa,IAAI,CAAC;AAAA,IAC7F;AAAA,EACF,CAAC;AACH;AAGA,eAAsB,WAAW,QAAwB,OAAc,KAAa,UAAkD,CAAC,GAA+B;AACpK,QAAM,aAAa,kBA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GAAG,GAAG,IAAI,GAAG,CAAC;AAAA,EAC9E;AACF;AAGO,SAAS,WAAW,MAAgD;AACzE,SAAO,KACJ,IAAI,CAAC,MAAM;AACV,UAAM,aAAa,EAAE,cAAc,EAAE,WAAW;AAChD,WAAO,EAAE,SAAS,EAAE,SAAS,WAAW,EAAE,WAAW,aAAa,EAAE,aAAa,SAAS,YAAY,YAAY,cAAc,EAAE,gBAAgB,EAAE;AAAA,EACtJ,CAAC,EACA,KAAK,CAAC,GAAG,MAAO,EAAE,UAAU,EAAE,UAAU,KAAK,EAAE,UAAU,EAAE,UAAU,IAAI,CAAE;AAChF;","names":["goal","HOLDOUT_KEY","DAY_MS","goal","goal"]}
|
|
1
|
+
{"version":3,"sources":["../src/handler.ts","../src/raw.ts","../src/validate.ts","../src/nodeAdapter.ts","../src/attribution.ts","../src/store.ts","../src/conformance.ts"],"sourcesContent":["import { isCrawler } from '@splithub/core';\nimport type { SplitHubConfig } from '@splithub/core';\nimport { ANALYSIS_UNAVAILABLE, rawResults, rawStatusTable } from './raw';\nimport type { Store } from './store';\nimport { validateBatch } from './validate';\n\nexport interface HandlerOptions {\n config: SplitHubConfig;\n store: Store;\n /**\n * Protects the read endpoints (`/status`, `/results/:id`). When unset, they\n * are open, which is fine for local development only.\n */\n adminToken?: string;\n /** Allowed origins for CORS. Defaults to same-origin only (no CORS headers). */\n cors?: string[] | '*';\n}\n\n// Crawlers, link previews and headless audits render pages too; their exposures\n// would dilute every variant. Only a positive match counts: an empty UA or a\n// plain HTTP client is let through. The Next middleware forwards the visitor's\n// UA as `x-splithub-ua`, so that header wins over its own fetch's user-agent.\nexport const isBotUserAgent = (ua: string | null | undefined): boolean => isCrawler(ua);\nconst visitorUserAgent = (request: Request): string | null =>\n request.headers.get('x-splithub-ua') ?? request.headers.get('user-agent');\n\nexport type FetchHandler = (request: Request) => Promise<Response>;\n\n/**\n * One handler for ingest and results, mountable at any path:\n *\n * POST {base} → ingest an event batch\n * GET {base}/status → all experiments with exposures, visitors and days\n * GET {base}/results/:id → visitors, conversions, rate (and revenue) per variant\n *\n * Reads are raw counts; verdicts and recommendations are SplitHub Cloud's.\n * GET {base}/health → { ok: true }\n *\n * Works in Next.js route handlers, Remix, Hono, Bun, Deno and Node (via `toNodeListener`).\n */\nexport function createSplitHubHandler(options: HandlerOptions): FetchHandler {\n const { config, store } = options;\n\n const corsHeaders = (request: Request): Record<string, string> => {\n if (!options.cors) return {};\n const origin = request.headers.get('origin') ?? '';\n const allowed = options.cors === '*' ? '*' : options.cors.includes(origin) ? origin : '';\n if (!allowed) return {};\n return {\n 'access-control-allow-origin': allowed,\n 'access-control-allow-methods': 'GET, POST, OPTIONS',\n 'access-control-allow-headers': 'content-type, authorization',\n 'access-control-max-age': '86400',\n };\n };\n\n const json = (request: Request, body: unknown, status = 200): Response =>\n new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json', ...corsHeaders(request) } });\n\n const authorized = (request: Request): boolean => {\n if (!options.adminToken) return true;\n const header = request.headers.get('authorization') ?? '';\n return header === `Bearer ${options.adminToken}`;\n };\n\n return async (request) => {\n const url = new URL(request.url);\n const path = url.pathname.replace(/\\/+$/, '');\n const tail = path.split('/').slice(-2);\n\n if (request.method === 'OPTIONS') return new Response(null, { status: 204, headers: corsHeaders(request) });\n\n if (request.method === 'POST') {\n let body: unknown;\n try {\n body = await request.json();\n } catch {\n return json(request, { error: 'invalid JSON' }, 400);\n }\n const result = validateBatch(body, config.project);\n if (!result.ok) return json(request, { error: result.error }, 400);\n if (isBotUserAgent(visitorUserAgent(request))) return json(request, { ok: true, received: result.events.length, inserted: 0 }, 202);\n const inserted = await store.insertEvents(result.events);\n return json(request, { ok: true, received: result.events.length, inserted }, 202);\n }\n\n if (request.method === 'GET') {\n if (tail[1] === 'health') return json(request, { ok: true, project: config.project });\n if (!authorized(request)) return json(request, { error: 'unauthorized' }, 401);\n if (tail[1] === 'status') return json(request, { project: config.project, experiments: await rawStatusTable(config, store), analysis: ANALYSIS_UNAVAILABLE });\n if (tail[0] === 'results' && tail[1]) {\n const r = await rawResults(config, store, tail[1]);\n return r ? json(request, r) : json(request, { error: `unknown experiment \"${tail[1]}\"` }, 404);\n }\n }\n\n return json(request, { error: 'not found' }, 404);\n };\n}\n","import { getExperiment, HOLDOUT_KEY, holdoutExperiment, type Experiment, type SplitHubConfig } from '@splithub/core';\nimport type { ExperimentSummary, Store, StoreVariantCounts } from './store';\n\nconst DAY_MS = 86_400_000;\n\n/** Self-hosted reads give counts; verdicts and recommendations are computed by SplitHub Cloud. */\nexport const ANALYSIS_UNAVAILABLE = {\n available: false as const,\n message: 'Verdicts, stars and recommendations come with SplitHub Cloud.',\n url: 'https://splithub.io/cloud',\n};\n\nexport interface RawVariant {\n variant: string;\n /** Unique visitors counted in this variant (first exposure decides). */\n visitors: number;\n /** Visitors who reached the goal after their exposure. */\n conversions: number;\n /** conversions / visitors, 0 without visitors. */\n rate: number;\n /** Sum of per-visitor revenue, when the goal carries revenue. */\n revenue?: number;\n /** Sum of squared per-visitor revenue, when the store reports it. */\n revenueSumSq?: number;\n}\n\nexport interface RawMetric {\n metric: string;\n role: 'secondary' | 'guardrail';\n worse?: 'higher' | 'lower';\n variants: RawVariant[];\n}\n\nexport interface RawResults {\n experiment: string;\n kind: string;\n status: string;\n goal: string | null;\n description: string | null;\n /** Human name; null = show the key. */\n name: string | null;\n /** Declared order: the first variant is the control. */\n variants: RawVariant[];\n metrics?: RawMetric[];\n /** Days between the first and the last exposure, one decimal; 0 without data. */\n days: number;\n analysis: typeof ANALYSIS_UNAVAILABLE;\n}\n\nexport interface RawStatusRow {\n experiment: string;\n kind: string;\n status: string;\n goal: string | null;\n description: string | null;\n /** Human name; null = show the key. */\n name: string | null;\n exposures: number;\n visitors: number;\n /** Whole days with data, at least 1 once there is any; 0 without data. */\n days: number;\n}\n\n/** An experiment of the config, or the holdout comparison for `__holdout`. */\nexport function resultsExperiment(config: SplitHubConfig, key: string): Experiment | null {\n return getExperiment(config, key) ?? (key === HOLDOUT_KEY ? holdoutExperiment(config) : null);\n}\n\n/** Store rows in the config's order, silent variants as 0. */\nfunction rawVariants(experiment: Experiment, observed: StoreVariantCounts[], withRevenue: boolean): RawVariant[] {\n return experiment.variants.map((v) => {\n const row = observed.find((o) => o.variant === v.key);\n const visitors = row?.exposures ?? 0;\n const conversions = row?.conversions ?? 0;\n const revenue = row?.revenueSum ?? row?.revenue;\n return {\n variant: v.key,\n visitors,\n conversions,\n rate: visitors > 0 ? conversions / visitors : 0,\n ...(withRevenue && revenue !== undefined ? { revenue } : {}),\n ...(withRevenue && row?.revenueSumSq !== undefined ? { revenueSumSq: row.revenueSumSq } : {}),\n };\n });\n}\n\n/** Counts per variant for one experiment, its secondary and guardrail goals included. No statistics. */\nexport async function rawResults(config: SplitHubConfig, store: Store, key: string, options: { summary?: ExperimentSummary | null } = {}): Promise<RawResults | null> {\n const experiment = resultsExperiment(config, key);\n if (!experiment) return null;\n const goal = experiment.goal;\n const observed = goal ? await store.variantCounts(key, goal) : [];\n const goalHasRevenue = Boolean(goal && config.goals.find((g) => g.key === goal)?.revenue);\n const withRevenue = goalHasRevenue || observed.some((o) => (o.revenueSum ?? o.revenue ?? 0) !== 0);\n const summary = options.summary !== undefined ? options.summary : ((await store.summaries()).find((s) => s.experiment === key) ?? null);\n const span = summary?.firstExposureAt != null && summary.lastExposureAt != null ? (summary.lastExposureAt - summary.firstExposureAt) / DAY_MS : 0;\n\n const m = goal ? experiment.metrics : undefined;\n const metrics: RawMetric[] | undefined = m\n ? await Promise.all([\n ...m.secondary.map(async (metric) => ({ metric, role: 'secondary' as const, variants: rawVariants(experiment, await store.variantCounts(key, metric), false) })),\n ...m.guardrails.map(async (g) => ({ metric: g.goal, role: 'guardrail' as const, ...(g.worse ? { worse: g.worse } : {}), variants: rawVariants(experiment, await store.variantCounts(key, g.goal), false) })),\n ])\n : undefined;\n\n return {\n experiment: key,\n kind: experiment.kind,\n status: experiment.status,\n goal,\n description: experiment.description ?? null,\n name: experiment.name ?? null,\n variants: rawVariants(experiment, observed, withRevenue),\n ...(metrics?.length ? { metrics } : {}),\n days: Math.round(span * 10) / 10,\n analysis: ANALYSIS_UNAVAILABLE,\n };\n}\n\n/** Every experiment with exposures, visitors and days; the holdout once it has visitors. */\nexport async function rawStatusTable(config: SplitHubConfig, store: Store): Promise<RawStatusRow[]> {\n const byKey = new Map<string, ExperimentSummary>((await store.summaries()).map((s) => [s.experiment, s]));\n const holdout = holdoutExperiment(config);\n const all = holdout && byKey.has(HOLDOUT_KEY) ? [...config.experiments, holdout] : config.experiments;\n return all.map((exp) => {\n const s = byKey.get(exp.key);\n const days = s?.firstExposureAt && s.lastExposureAt ? Math.max(1, Math.ceil((s.lastExposureAt - s.firstExposureAt) / DAY_MS)) : 0;\n return { experiment: exp.key, kind: exp.kind, status: exp.status, goal: exp.goal, description: exp.description ?? null, name: exp.name ?? null, exposures: s?.exposures ?? 0, visitors: s?.visitors ?? 0, days };\n });\n}\n","import { HOLDOUT_KEY, type EventBatch, type SplitHubEvent } from '@splithub/core';\nimport type { StoredEvent } from './store';\n\nconst ID = /^[a-z0-9_-]{8,64}$/i;\nconst KEY = /^[a-z0-9][a-z0-9_-]{0,63}$/;\nconst MAX_EVENTS = 500;\nconst MAX_PROPS_BYTES = 4096;\n/** Reject client timestamps more than this far from the server clock. */\nconst MAX_SKEW_MS = 7 * 24 * 60 * 60 * 1000;\n\nexport type ValidationResult = { ok: true; events: StoredEvent[] } | { ok: false; error: string };\n\n/** `expectedProject` null skips the name check (the caller already identified the project, e.g. by public key). */\nexport function validateBatch(body: unknown, expectedProject: string | null, now = Date.now()): ValidationResult {\n if (!body || typeof body !== 'object') return { ok: false, error: 'body must be a JSON object' };\n const batch = body as Partial<EventBatch>;\n if (typeof batch.project !== 'string') return { ok: false, error: '\"project\" must be a string' };\n if (expectedProject !== null && batch.project !== expectedProject) return { ok: false, error: `unknown project \"${batch.project}\"` };\n if (!Array.isArray(batch.events)) return { ok: false, error: '\"events\" must be an array' };\n if (batch.events.length === 0) return { ok: true, events: [] };\n if (batch.events.length > MAX_EVENTS) return { ok: false, error: `too many events (max ${MAX_EVENTS})` };\n\n const out: StoredEvent[] = [];\n for (const raw of batch.events as Partial<SplitHubEvent>[]) {\n const e = normalize(raw, now);\n if (typeof e === 'string') return { ok: false, error: e };\n out.push(e);\n }\n return { ok: true, events: out };\n}\n\nfunction normalize(e: Partial<SplitHubEvent>, now: number): StoredEvent | string {\n if (!e || typeof e !== 'object') return 'event must be an object';\n if (typeof e.id !== 'string' || !ID.test(e.id)) return 'event.id is invalid';\n if (typeof e.vid !== 'string' || e.vid.length === 0 || e.vid.length > 64) return 'event.vid is invalid';\n if (typeof e.sid !== 'string' || e.sid.length === 0 || e.sid.length > 64) return 'event.sid is invalid';\n if (typeof e.ts !== 'number' || !Number.isFinite(e.ts)) return 'event.ts must be a number';\n const ts = Math.abs(e.ts - now) > MAX_SKEW_MS ? now : Math.round(e.ts);\n const url = typeof e.url === 'string' ? e.url.slice(0, 512) : null;\n\n if (e.type === 'exposure') {\n if (typeof e.exp !== 'string' || !(KEY.test(e.exp) || e.exp === HOLDOUT_KEY)) return 'exposure.exp is invalid';\n if (typeof e.var !== 'string' || !KEY.test(e.var)) return 'exposure.var is invalid';\n return { id: e.id, type: 'exposure', experiment: e.exp, variant: e.var, goal: null, visitorId: e.vid, sessionId: e.sid, ts, url, props: null, receivedAt: now };\n }\n if (e.type === 'goal') {\n if (typeof e.goal !== 'string' || !KEY.test(e.goal)) return 'goal.goal is invalid';\n let props: Record<string, unknown> | null = null;\n if (e.props !== undefined) {\n if (!e.props || typeof e.props !== 'object' || Array.isArray(e.props)) return 'goal.props must be an object';\n if (JSON.stringify(e.props).length > MAX_PROPS_BYTES) return 'goal.props too large';\n props = e.props;\n }\n return { id: e.id, type: 'goal', experiment: null, variant: null, goal: e.goal, visitorId: e.vid, sessionId: e.sid, ts, url, props, receivedAt: now };\n }\n return `unknown event type \"${String((e as { type?: unknown }).type)}\"`;\n}\n","import type { IncomingMessage, ServerResponse } from 'node:http';\nimport type { FetchHandler } from './handler';\n\n/**\n * Adapt a fetch-style handler to Node's `http` / Express / Vite / Connect.\n *\n * http.createServer(toNodeListener(handler))\n * app.use('/api/splithub', toNodeListener(handler))\n * viteServer.middlewares.use('/api/splithub', toNodeListener(handler))\n */\nexport function toNodeListener(handler: FetchHandler): (req: IncomingMessage, res: ServerResponse) => void {\n return (req, res) => {\n void (async () => {\n try {\n const request = await toRequest(req);\n const response = await handler(request);\n res.statusCode = response.status;\n response.headers.forEach((value, key) => res.setHeader(key, value));\n const body = response.body ? Buffer.from(await response.arrayBuffer()) : null;\n res.end(body);\n } catch (error) {\n res.statusCode = 500;\n res.setHeader('content-type', 'application/json');\n res.end(JSON.stringify({ error: error instanceof Error ? error.message : 'internal error' }));\n }\n })();\n };\n}\n\nasync function toRequest(req: IncomingMessage): Promise<Request> {\n const host = req.headers.host ?? 'localhost';\n const proto = (req.headers['x-forwarded-proto'] as string | undefined) ?? 'http';\n // Connect-style mounts strip the prefix into req.url; prefer originalUrl when present.\n const rawUrl = (req as IncomingMessage & { originalUrl?: string }).originalUrl ?? req.url ?? '/';\n const url = new URL(rawUrl, `${proto}://${host}`);\n const headers = new Headers();\n for (const [key, value] of Object.entries(req.headers)) {\n if (Array.isArray(value)) value.forEach((v) => headers.append(key, v));\n else if (typeof value === 'string') headers.set(key, value);\n }\n const method = req.method ?? 'GET';\n // A fresh ArrayBuffer: newer DOM typings accept neither Node's Buffer nor a view over a\n // possibly shared buffer as BodyInit.\n let body: ArrayBuffer | undefined;\n if (method !== 'GET' && method !== 'HEAD') {\n const chunks: Buffer[] = [];\n for await (const chunk of req) chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));\n const all = Buffer.concat(chunks);\n const copy = new Uint8Array(all.byteLength);\n copy.set(all);\n body = copy.buffer;\n }\n return new Request(url, { method, headers, body });\n}\n","// The one attribution rule every SplitHub store follows. The memory store\n// implements it in TypeScript (`attributeVariants`), the SQL stores run the\n// query from `variantCountsSql`, and the cloud applies it at ingest\n// (splithub-go/src/services/projectStore.ts). Change it here and there together.\n//\n// 1. A visitor counts once per experiment, in the variant of their earliest\n// exposure (same ts: smallest variant key).\n// 2. A goal converts that visitor when its ts is at or after the exposure,\n// minus ATTRIBUTION_SKEW_MS: the Next middleware stamps exposures with the\n// server clock while goals carry the browser clock.\n// 3. Goals from visitors who never saw the experiment are ignored.\n// 4. Only the first GOAL_DAILY_CAP events of one goal per visitor and UTC day\n// count (ordered by ts, then id); past that only a loop is talking.\n// 5. Revenue is the sum of numeric `props.revenue` over the counted goals,\n// per visitor; stores report the per-variant sum and sum of squares.\n\n/** How far a goal may precede the exposure it converts, for clock differences between server and browser. */\nexport const ATTRIBUTION_SKEW_MS = 60_000;\n/** Events of one goal from one visitor counted per UTC day. */\nexport const GOAL_DAILY_CAP = 50;\nconst DAY_MS = 86_400_000;\n\n/** Unique exposed and unique converted visitors of one variant. */\nexport interface VariantCounts {\n variant: string;\n exposures: number;\n conversions: number;\n revenue?: number;\n revenueSum?: number;\n revenueSumSq?: number;\n}\n\n/** Per-variant counts every store returns: `revenueSum` / `revenueSumSq` are over per-visitor revenue (non-converted visitors add 0). */\nexport interface AttributedCounts extends VariantCounts {\n revenue: number;\n revenueSum: number;\n revenueSumSq: number;\n}\n\n/** The shape of an event the rule needs. */\nexport interface AttributionEvent {\n id: string;\n type: 'exposure' | 'goal';\n experiment: string | null;\n variant: string | null;\n goal: string | null;\n visitorId: string;\n ts: number;\n props: Record<string, unknown> | null;\n}\n\nexport function revenueOf(props: Record<string, unknown> | null | undefined): number {\n const v = props?.revenue;\n return typeof v === 'number' && Number.isFinite(v) ? v : 0;\n}\n\n/** Reference implementation of the rule over events in memory. */\nexport function attributeVariants(events: Iterable<AttributionEvent>, experiment: string, goal: string): AttributedCounts[] {\n const first = new Map<string, { variant: string; ts: number }>();\n const goals = new Map<string, AttributionEvent[]>(); // visitor + day -> goal events\n for (const e of events) {\n if (e.type === 'exposure') {\n if (e.experiment !== experiment || !e.variant) continue;\n const prev = first.get(e.visitorId);\n if (prev === undefined || e.ts < prev.ts || (e.ts === prev.ts && e.variant < prev.variant)) first.set(e.visitorId, { variant: e.variant, ts: e.ts });\n } else if (e.goal === goal) {\n const key = `${e.visitorId}\\u0000${e.ts - (e.ts % DAY_MS)}`;\n const list = goals.get(key) ?? [];\n list.push(e);\n goals.set(key, list);\n }\n }\n const counted = new Map<string, number[]>(); // visitor -> ts of counted goals\n const revenueByVisitor = new Map<string, number[]>();\n for (const list of goals.values()) {\n list.sort((a, b) => a.ts - b.ts || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));\n for (const g of list.slice(0, GOAL_DAILY_CAP)) {\n (counted.get(g.visitorId) ?? counted.set(g.visitorId, []).get(g.visitorId)!).push(g.ts);\n (revenueByVisitor.get(g.visitorId) ?? revenueByVisitor.set(g.visitorId, []).get(g.visitorId)!).push(revenueOf(g.props));\n }\n }\n const out = new Map<string, AttributedCounts>();\n for (const [visitor, { variant, ts }] of first) {\n const row = out.get(variant) ?? { variant, exposures: 0, conversions: 0, revenue: 0, revenueSum: 0, revenueSumSq: 0 };\n row.exposures++;\n const times = counted.get(visitor) ?? [];\n const revenues = revenueByVisitor.get(visitor) ?? [];\n let converted = false;\n let revenue = 0;\n times.forEach((t, i) => {\n if (t < ts - ATTRIBUTION_SKEW_MS) return;\n converted = true;\n revenue += revenues[i]!;\n });\n if (converted) {\n row.conversions++;\n row.revenueSum += revenue;\n row.revenueSumSq += revenue * revenue;\n row.revenue = row.revenueSum;\n }\n out.set(variant, row);\n }\n return [...out.values()];\n}\n\nexport type SqlDialect = 'sqlite' | 'postgres' | 'mysql';\nexport type AttributionParam = 'experiment' | 'goal' | 'project';\n\nexport interface VariantCountsSqlOptions {\n dialect: SqlDialect;\n /** Events table. Defaults to \"splithub_events\". */\n table?: string;\n /** Column partitioning a shared table by project (adapter-d1); bound from the `project` param. */\n projectColumn?: string;\n}\n\nexport interface VariantCountsSql {\n sql: string;\n /** Names of the values to bind, in placeholder order (Postgres numbers them, so each name appears once). */\n params: AttributionParam[];\n /** Binds values in the right order. */\n bind(values: { experiment: string; goal: string; project?: string }): unknown[];\n}\n\nconst IDENT = /^[a-z_][a-z0-9_]*$/i;\n\nfunction revenueExpr(dialect: SqlDialect, alias: string): string {\n if (dialect === 'postgres') return `CASE WHEN jsonb_typeof(${alias}.props::jsonb -> 'revenue') = 'number' THEN (${alias}.props::jsonb ->> 'revenue')::float8 ELSE 0 END`;\n if (dialect === 'mysql') return `CASE WHEN JSON_TYPE(JSON_EXTRACT(${alias}.props, '$.revenue')) IN ('INTEGER', 'UNSIGNED INTEGER', 'DOUBLE', 'DECIMAL') THEN JSON_EXTRACT(${alias}.props, '$.revenue') + 0 ELSE 0 END`;\n return `CASE WHEN json_type(${alias}.props, '$.revenue') IN ('integer', 'real') THEN json_extract(${alias}.props, '$.revenue') ELSE 0 END`;\n}\n\n/**\n * The attribution query for an events table with the columns of the SplitHub\n * stores (id, type, experiment, variant, goal, visitor_id, ts, props). Returns\n * one row per variant: variant, exposures, conversions, revenue_sum,\n * revenue_sum_sq. Derived tables only, no CTEs or window functions, so the same\n * shape runs on SQLite, D1, Postgres and MySQL 5.7.\n */\nexport function variantCountsSql(options: VariantCountsSqlOptions): VariantCountsSql {\n const { dialect } = options;\n const t = options.table ?? 'splithub_events';\n if (!IDENT.test(t)) throw new Error('[splithub] invalid table name');\n if (options.projectColumn !== undefined && !IDENT.test(options.projectColumn)) throw new Error('[splithub] invalid column name');\n\n const params: AttributionParam[] = [];\n const p = (name: AttributionParam): string => {\n if (dialect === 'postgres') {\n const i = params.indexOf(name);\n if (i >= 0) return `$${i + 1}`;\n params.push(name);\n return `$${params.length}`;\n }\n params.push(name);\n return '?';\n };\n const proj = (alias: string): string => (options.projectColumn ? `${alias}.${options.projectColumn} = ${p('project')} AND ` : '');\n\n // Placeholders are produced in text order, so build the string front to back.\n const fv = `SELECT x.visitor_id, MIN(x.ts) AS first_ts FROM ${t} x WHERE ${proj('x')}x.type = 'exposure' AND x.experiment = ${p('experiment')} GROUP BY x.visitor_id`;\n const fe = `SELECT MIN(e.variant) AS variant, fv.visitor_id, fv.first_ts\n FROM (${fv}) fv\n JOIN ${t} e ON ${proj('e')}e.type = 'exposure' AND e.experiment = ${p('experiment')} AND e.visitor_id = fv.visitor_id AND e.ts = fv.first_ts\n GROUP BY fv.visitor_id, fv.first_ts`;\n const goalJoin = `${proj('g')}g.type = 'goal' AND g.goal = ${p('goal')} AND g.visitor_id = fe.visitor_id AND g.ts >= fe.first_ts - ${ATTRIBUTION_SKEW_MS}\n AND (SELECT COUNT(*) FROM ${t} g2\n WHERE ${proj('g2')}g2.type = 'goal' AND g2.goal = g.goal AND g2.visitor_id = g.visitor_id\n AND g2.ts >= g.ts - (g.ts % ${DAY_MS}) AND (g2.ts < g.ts OR (g2.ts = g.ts AND g2.id < g.id))) < ${GOAL_DAILY_CAP}`;\n const sql = `SELECT v.variant AS variant, COUNT(*) AS exposures, SUM(v.converted) AS conversions,\n COALESCE(SUM(v.revenue), 0) AS revenue_sum, COALESCE(SUM(v.revenue * v.revenue), 0) AS revenue_sum_sq\nFROM (\n SELECT fe.variant, fe.visitor_id,\n CASE WHEN COUNT(g.id) > 0 THEN 1 ELSE 0 END AS converted,\n COALESCE(SUM(${revenueExpr(dialect, 'g')}), 0) AS revenue\n FROM (${fe}) fe\n LEFT JOIN ${t} g ON ${goalJoin}\n GROUP BY fe.variant, fe.visitor_id\n) v\nGROUP BY v.variant`;\n\n return {\n sql,\n params,\n bind(values) {\n return params.map((name) => {\n const v = values[name];\n if (v === undefined) throw new Error(`[splithub] missing \"${name}\" for the attribution query`);\n return v;\n });\n },\n };\n}\n\n/** Turns a row of `variantCountsSql` (numbers may come back as strings from pg / mysql2) into counts. */\nexport function countsFromRow(row: Record<string, unknown>): AttributedCounts {\n const revenueSum = Number(row.revenue_sum ?? 0);\n return {\n variant: String(row.variant),\n exposures: Number(row.exposures ?? 0),\n conversions: Number(row.conversions ?? 0),\n revenue: revenueSum,\n revenueSum,\n revenueSumSq: Number(row.revenue_sum_sq ?? 0),\n };\n}\n","import { attributeVariants, type AttributedCounts } from './attribution';\n\n/** One row in the events table, whatever the backing database. */\nexport interface StoredEvent {\n id: string;\n type: 'exposure' | 'goal';\n experiment: string | null;\n variant: string | null;\n goal: string | null;\n visitorId: string;\n sessionId: string;\n /** Unix ms, as reported by the client. */\n ts: number;\n url: string | null;\n props: Record<string, unknown> | null;\n /** Unix ms, server clock. */\n receivedAt: number;\n /** Request metadata filled by the ingest endpoint (origin host, GeoIP country, UA device/browser). */\n host?: string | null;\n country?: string | null;\n device?: string | null;\n browser?: string | null;\n /** Extra dimensions (SplitHub Cloud, `d1Store({ meta: 'extended' })`): OS, language, geo, referrer, UTM. */\n os?: string | null;\n language?: string | null;\n city?: string | null;\n region?: string | null;\n referrer?: string | null;\n utm_source?: string | null;\n utm_medium?: string | null;\n utm_campaign?: string | null;\n utm_term?: string | null;\n utm_content?: string | null;\n}\n\nexport interface ExperimentSummary {\n experiment: string;\n exposures: number;\n visitors: number;\n firstExposureAt: number | null;\n lastExposureAt: number | null;\n}\n\n/** What `variantCounts` returns. Older custom stores may omit the revenue fields; `revenue` then stands for the sum. */\nexport type StoreVariantCounts = Omit<AttributedCounts, 'revenue' | 'revenueSum' | 'revenueSumSq'> &\n Partial<Pick<AttributedCounts, 'revenue' | 'revenueSum' | 'revenueSumSq'>>;\n\n/**\n * Storage adapter. Implement this against your database to keep all data in\n * your own infrastructure. `variantCounts` follows the rule in `./attribution`\n * (first exposure decides the variant, goals count from 60 s before it, at most\n * 50 of one goal per visitor and day); SQL databases can run `variantCountsSql`.\n */\nexport interface Store {\n /** Insert events, ignoring ids already present. Returns the number inserted. */\n insertEvents(events: StoredEvent[]): Promise<number>;\n /** Unique exposed and converted visitors per variant (any order), with per-visitor revenue sum and sum of squares. */\n variantCounts(experiment: string, goal: string): Promise<StoreVariantCounts[]>;\n summaries(): Promise<ExperimentSummary[]>;\n close?(): Promise<void> | void;\n}\n\n/** In-memory store for tests and quick local runs. Not persistent. */\nexport function createMemoryStore(): Store & { events: StoredEvent[] } {\n const events: StoredEvent[] = [];\n const ids = new Set<string>();\n return {\n events,\n async insertEvents(batch) {\n let n = 0;\n for (const e of batch) {\n if (ids.has(e.id)) continue;\n ids.add(e.id);\n events.push(e);\n n++;\n }\n return n;\n },\n async variantCounts(experiment, goal) {\n return attributeVariants(events, experiment, goal);\n },\n async summaries() {\n const map = new Map<string, ExperimentSummary & { visitorSet: Set<string> }>();\n for (const e of events) {\n if (e.type !== 'exposure' || !e.experiment) continue;\n const s = map.get(e.experiment) ?? {\n experiment: e.experiment,\n exposures: 0,\n visitors: 0,\n firstExposureAt: null,\n lastExposureAt: null,\n visitorSet: new Set<string>(),\n };\n s.exposures++;\n s.visitorSet.add(e.visitorId);\n s.firstExposureAt = s.firstExposureAt === null ? e.ts : Math.min(s.firstExposureAt, e.ts);\n s.lastExposureAt = s.lastExposureAt === null ? e.ts : Math.max(s.lastExposureAt, e.ts);\n map.set(e.experiment, s);\n }\n return [...map.values()].map(({ visitorSet, ...s }) => ({ ...s, visitors: visitorSet.size }));\n },\n };\n}\n","// Shared cases for the attribution rule (./attribution). Every store's tests\n// insert `events` and compare `variantCounts(experiment, goal)`, sorted with\n// `sortCounts`, to `expected`. Plain data so this ships without a test runner.\n\nimport { ATTRIBUTION_SKEW_MS, GOAL_DAILY_CAP, type AttributedCounts } from './attribution';\nimport type { StoreVariantCounts, StoredEvent } from './store';\n\nexport interface ConformanceCase {\n name: string;\n experiment: string;\n goal: string;\n events: StoredEvent[];\n expected: AttributedCounts[];\n /**\n * The cloud decides at ingest in arrival order, so a later-arriving exposure\n * with an earlier ts cannot move a visitor. Cases that depend on that are\n * only for the read-time stores.\n */\n readTimeOnly?: boolean;\n}\n\nconst T = Date.UTC(2026, 0, 10, 12, 0, 0);\nconst DAY = 86_400_000;\nlet seq = 0;\n\nfunction exposure(visitorId: string, variant: string, ts: number, experiment = 'hero'): StoredEvent {\n seq++;\n return { id: `exp_${String(seq).padStart(6, '0')}`, type: 'exposure', experiment, variant, goal: null, visitorId, sessionId: `s_${visitorId}`, ts, url: null, props: null, receivedAt: ts };\n}\nfunction goal(visitorId: string, ts: number, revenue?: unknown, key = 'signup'): StoredEvent {\n seq++;\n return { id: `goal_${String(seq).padStart(6, '0')}`, type: 'goal', experiment: null, variant: null, goal: key, visitorId, sessionId: `s_${visitorId}`, ts, url: null, props: revenue === undefined ? null : { revenue }, receivedAt: ts };\n}\nfunction counts(variant: string, exposures: number, conversions: number, revenueSum = 0, revenueSumSq = 0): AttributedCounts {\n return { variant, exposures, conversions, revenue: revenueSum, revenueSum, revenueSumSq };\n}\n\nexport const attributionConformance: ConformanceCase[] = [\n {\n name: 'a visitor belongs to the variant of their earliest exposure (tie: smallest key)',\n experiment: 'hero',\n goal: 'signup',\n readTimeOnly: true,\n events: [\n exposure('v1', 'control', T + 1000),\n exposure('v1', 'bold', T), // earlier, arrives later\n goal('v1', T + 5000),\n exposure('v2', 'control', T),\n exposure('v2', 'bold', T),\n exposure('v3', 'bold', T),\n exposure('v4', 'control', T),\n ],\n expected: [counts('bold', 3, 1), counts('control', 1, 0)],\n },\n {\n name: 'counts unique visitors, not events',\n experiment: 'hero',\n goal: 'signup',\n events: [exposure('v1', 'control', T), exposure('v1', 'control', T + 10), exposure('v1', 'bold', T + 20), goal('v1', T + 30), goal('v1', T + 40), exposure('v2', 'bold', T)],\n expected: [counts('bold', 1, 0), counts('control', 1, 1)],\n },\n {\n name: 'goals well before the exposure, of other goals or from unexposed visitors do not convert',\n experiment: 'hero',\n goal: 'signup',\n events: [\n exposure('v1', 'control', T),\n goal('v1', T - ATTRIBUTION_SKEW_MS - 1000, 9),\n goal('v1', T + 1000, 9, 'other'),\n exposure('other_exp', 'x', T, 'pricing'),\n goal('nobody', T + 1000, 9),\n goal('other_exp', T + 1000, 9),\n ],\n expected: [counts('control', 1, 0)],\n },\n {\n name: `a goal up to ${ATTRIBUTION_SKEW_MS / 1000} s before the exposure still counts (server vs browser clock)`,\n experiment: 'hero',\n goal: 'signup',\n events: [\n exposure('v1', 'control', T),\n goal('v1', T - ATTRIBUTION_SKEW_MS, 2),\n exposure('v2', 'bold', T),\n goal('v2', T - 30_000, 3),\n exposure('v3', 'bold', T),\n goal('v3', T - ATTRIBUTION_SKEW_MS - 1, 4),\n ],\n expected: [counts('bold', 2, 1, 3, 9), counts('control', 1, 1, 2, 4)],\n },\n {\n name: `at most ${GOAL_DAILY_CAP} of one goal per visitor and UTC day`,\n experiment: 'hero',\n goal: 'signup',\n events: [\n exposure('v1', 'control', T),\n ...Array.from({ length: GOAL_DAILY_CAP + 10 }, (_, i) => goal('v1', T + 1000 + i, 1)),\n ...Array.from({ length: 3 }, (_, i) => goal('v1', T + DAY + i, 1)),\n ],\n expected: [counts('control', 1, 1, GOAL_DAILY_CAP + 3, (GOAL_DAILY_CAP + 3) ** 2)],\n },\n {\n name: 'revenue is summed per visitor; variants report the sum and the sum of squares',\n experiment: 'hero',\n goal: 'signup',\n events: [\n exposure('v1', 'control', T),\n goal('v1', T + 1000, 10),\n goal('v1', T + 2000, 5),\n exposure('v2', 'control', T),\n goal('v2', T + 1000, 20),\n exposure('v3', 'control', T),\n goal('v3', T + 1000, 'lots'),\n exposure('v4', 'control', T),\n exposure('v5', 'bold', T),\n goal('v5', T + 1000, 2.5),\n ],\n expected: [counts('bold', 1, 1, 2.5, 6.25), counts('control', 4, 3, 35, 625)],\n },\n];\n\n/** Sorts by variant and keeps the compared fields, so any store's output can be `toEqual`-ed with `expected`. */\nexport function sortCounts(rows: StoreVariantCounts[]): AttributedCounts[] {\n return rows\n .map((r) => {\n const revenueSum = r.revenueSum ?? r.revenue ?? 0;\n return { variant: r.variant, exposures: r.exposures, conversions: r.conversions, revenue: revenueSum, revenueSum, revenueSumSq: r.revenueSumSq ?? 0 };\n })\n .sort((a, b) => (a.variant < b.variant ? -1 : a.variant > b.variant ? 1 : 0));\n}\n"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CAAC,GAAG,MAAO,EAAE,UAAU,EAAE,UAAU,KAAK,EAAE,UAAU,EAAE,UAAU,IAAI,CAAE;AAChF;","names":["goal","HOLDOUT_KEY","DAY_MS","goal","goal"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@splithub/node",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.0",
|
|
4
4
|
"description": "Run SplitHub on your own server: one handler for events and results, your database behind a small Store interface.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"repository": {
|
|
@@ -28,7 +28,7 @@
|
|
|
28
28
|
"README.md"
|
|
29
29
|
],
|
|
30
30
|
"dependencies": {
|
|
31
|
-
"@splithub/core": "0.
|
|
31
|
+
"@splithub/core": "0.3.0"
|
|
32
32
|
},
|
|
33
33
|
"devDependencies": {
|
|
34
34
|
"@types/node": "^22.9.0",
|