@splithub/next 0.1.9 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{chunk-QQTWQZRA.js → chunk-BH4ACCFH.js} +50 -39
- package/dist/chunk-BH4ACCFH.js.map +1 -0
- package/dist/index.cjs +43 -36
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +3 -4
- package/dist/index.d.ts +3 -4
- package/dist/index.js +1 -1
- package/dist/server.cjs +9 -3
- package/dist/server.cjs.map +1 -1
- package/dist/server.js +8 -4
- package/dist/server.js.map +1 -1
- package/package.json +12 -4
- package/dist/chunk-QQTWQZRA.js.map +0 -1
|
@@ -23,16 +23,20 @@ function clearRemoteMemo() {
|
|
|
23
23
|
// src/middleware.ts
|
|
24
24
|
import {
|
|
25
25
|
applyRemoteOverrides,
|
|
26
|
-
assign,
|
|
27
26
|
CLOUD_ENDPOINT as CLOUD_ENDPOINT2,
|
|
27
|
+
countsForHoldout,
|
|
28
|
+
decideRedirect,
|
|
28
29
|
explainAssignment,
|
|
29
|
-
|
|
30
|
+
HOLDOUT_KEY,
|
|
31
|
+
holdoutGroup,
|
|
30
32
|
isDevEnvironment,
|
|
33
|
+
matchPath,
|
|
31
34
|
newId,
|
|
32
35
|
newVisitorId,
|
|
33
36
|
parseCookies,
|
|
34
37
|
parseForceParam,
|
|
35
38
|
parseUserAgent,
|
|
39
|
+
redirectTarget,
|
|
36
40
|
SDK_VERSION
|
|
37
41
|
} from "@splithub/core";
|
|
38
42
|
import { NextResponse } from "next/server";
|
|
@@ -41,15 +45,12 @@ var ONE_YEAR = 60 * 60 * 24 * 365;
|
|
|
41
45
|
function defaultExclude(pathname) {
|
|
42
46
|
return pathname.startsWith("/_next") || pathname.startsWith("/api/") || /\.[a-z0-9]+$/i.test(pathname);
|
|
43
47
|
}
|
|
44
|
-
function matchPath(pattern, pathname) {
|
|
45
|
-
if (pattern.endsWith("*")) return pathname.startsWith(pattern.slice(0, -1));
|
|
46
|
-
return pattern === pathname || `${pattern}/` === pathname;
|
|
47
|
-
}
|
|
48
48
|
function requestContext(headers, url, visitor) {
|
|
49
49
|
const ua = parseUserAgent(headers.get("user-agent"));
|
|
50
50
|
const country = headers.get("cf-ipcountry") ?? headers.get("x-vercel-ip-country") ?? headers.get("x-country") ?? void 0;
|
|
51
51
|
const region = headers.get("x-vercel-ip-country-region") ?? headers.get("cf-region") ?? void 0;
|
|
52
52
|
const city = headers.get("x-vercel-ip-city") ?? headers.get("cf-ipcity") ?? void 0;
|
|
53
|
+
const timezone = headers.get("x-vercel-ip-timezone") ?? headers.get("cf-timezone") ?? headers.get("x-timezone") ?? void 0;
|
|
53
54
|
return {
|
|
54
55
|
country: country ?? void 0,
|
|
55
56
|
region: region ? decodeURIComponent(region) : void 0,
|
|
@@ -61,6 +62,7 @@ function requestContext(headers, url, visitor) {
|
|
|
61
62
|
referrer: headers.get("referer") ?? void 0,
|
|
62
63
|
url,
|
|
63
64
|
cookies: parseCookies(headers.get("cookie")),
|
|
65
|
+
...timezone ? { timezone } : {},
|
|
64
66
|
...visitor ? { visitor } : {}
|
|
65
67
|
};
|
|
66
68
|
}
|
|
@@ -85,40 +87,49 @@ function splithubMiddleware(baseConfig, options = {}) {
|
|
|
85
87
|
requestHeaders.set(VISITOR_HEADER, visitorId);
|
|
86
88
|
let response = null;
|
|
87
89
|
const cookiesToSet = [];
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
if (
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
90
|
+
let reachedTest = false;
|
|
91
|
+
const decision = decideRedirect(config, pathname, visitorId, context, overrides, (exp, a) => {
|
|
92
|
+
if (countsForHoldout(a)) reachedTest = true;
|
|
93
|
+
explainAssignment(exp, a);
|
|
94
|
+
});
|
|
95
|
+
const cloudDev = config.storage.mode === "cloud" && isDevEnvironment();
|
|
96
|
+
const events = [];
|
|
97
|
+
if (decision) {
|
|
98
|
+
if (decision.to) {
|
|
99
|
+
const target = redirectTarget(decision.to, request.nextUrl.href);
|
|
100
|
+
let url = target;
|
|
101
|
+
if (target.origin === request.nextUrl.origin) {
|
|
102
|
+
const next = request.nextUrl.clone();
|
|
103
|
+
next.pathname = target.pathname;
|
|
104
|
+
next.search = target.search;
|
|
105
|
+
url = next;
|
|
106
|
+
}
|
|
101
107
|
response = NextResponse.rewrite(url, { request: { headers: requestHeaders } });
|
|
102
108
|
}
|
|
103
|
-
const exposureCookie = `sh_x_${experiment
|
|
104
|
-
const
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
109
|
+
const exposureCookie = `sh_x_${decision.experiment}`;
|
|
110
|
+
const record = !cloudDev && (decision.reason === "assigned" || decision.reason === "dev" && config.storage.mode === "self");
|
|
111
|
+
if (trackRedirects && record && request.cookies.get(exposureCookie)?.value !== decision.variant) {
|
|
112
|
+
cookiesToSet.push({ name: exposureCookie, value: decision.variant });
|
|
113
|
+
events.push({ id: newId("e_"), type: "exposure", exp: decision.experiment, var: decision.variant, vid: visitorId, sid: "edge", ts: Date.now(), url: pathname });
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
const group = reachedTest ? holdoutGroup(config, visitorId) : null;
|
|
117
|
+
if (group && trackRedirects && !cloudDev && request.cookies.get(`sh_x_${HOLDOUT_KEY}`)?.value !== group) {
|
|
118
|
+
cookiesToSet.push({ name: `sh_x_${HOLDOUT_KEY}`, value: group });
|
|
119
|
+
events.push({ id: newId("e_"), type: "exposure", exp: HOLDOUT_KEY, var: group, vid: visitorId, sid: "edge", ts: Date.now(), url: pathname });
|
|
120
|
+
}
|
|
121
|
+
if (events.length) {
|
|
122
|
+
const target = ingestTarget(config, request.nextUrl.origin);
|
|
123
|
+
const batch = { project: config.project, sdk: `next/${SDK_VERSION}`, events };
|
|
124
|
+
const headers = { "content-type": "application/json" };
|
|
125
|
+
if (target.key) headers.authorization = `Bearer ${target.key}`;
|
|
126
|
+
const ua = request.headers.get("user-agent");
|
|
127
|
+
if (ua) {
|
|
128
|
+
headers["user-agent"] = ua;
|
|
129
|
+
headers["x-splithub-ua"] = ua;
|
|
120
130
|
}
|
|
121
|
-
|
|
131
|
+
const send = fetch(target.url, { method: "POST", headers, body: JSON.stringify(batch) }).catch(() => void 0);
|
|
132
|
+
if (event?.waitUntil) event.waitUntil(send);
|
|
122
133
|
}
|
|
123
134
|
response ?? (response = NextResponse.next({ request: { headers: requestHeaders } }));
|
|
124
135
|
if (isNewVisitor) {
|
|
@@ -132,9 +143,9 @@ function splithubMiddleware(baseConfig, options = {}) {
|
|
|
132
143
|
export {
|
|
133
144
|
getRemoteOverrides,
|
|
134
145
|
clearRemoteMemo,
|
|
135
|
-
VISITOR_HEADER,
|
|
136
146
|
matchPath,
|
|
147
|
+
VISITOR_HEADER,
|
|
137
148
|
requestContext,
|
|
138
149
|
splithubMiddleware
|
|
139
150
|
};
|
|
140
|
-
//# sourceMappingURL=chunk-
|
|
151
|
+
//# sourceMappingURL=chunk-BH4ACCFH.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/remote.ts","../src/middleware.ts"],"sourcesContent":["import { CLOUD_ENDPOINT, fetchRemoteOverrides, resolveOverridesUrl, REMOTE_TTL_MS, type RemoteOverrides, type SplitHubConfig } from '@splithub/core';\n\ninterface MemoEntry {\n at: number;\n value: RemoteOverrides | null;\n pending: Promise<RemoteOverrides | null> | null;\n}\n\n// Module-level memo: edge isolates and Node servers keep it across requests,\n// so at most one fetch per TTL per public key.\nconst memo = new Map<string, MemoEntry>();\n\nexport interface RemoteOptions {\n ttlMs?: number;\n /** Override the fetch implementation (tests). */\n fetchImpl?: typeof fetch;\n}\n\n/**\n * Live overrides for a cloud-mode config, cached in memory for `ttlMs`\n * (default 60s). Returns null in self mode or when the cloud is unreachable\n * (the config file then applies as-is).\n */\nexport async function getRemoteOverrides(config: SplitHubConfig, options: RemoteOptions = {}): Promise<RemoteOverrides | null> {\n if (config.storage.mode !== 'cloud' || !config.storage.key) return null;\n const ttl = options.ttlMs ?? REMOTE_TTL_MS;\n const url = resolveOverridesUrl(config.storage.endpoint ?? CLOUD_ENDPOINT, config.storage.key);\n const entry = memo.get(url);\n const now = Date.now();\n if (entry && now - entry.at < ttl) return entry.value;\n if (entry?.pending) return entry.value ?? entry.pending;\n\n const pending = fetchRemoteOverrides(url, options.fetchImpl).then((value) => {\n memo.set(url, { at: Date.now(), value: value ?? entry?.value ?? null, pending: null });\n return value ?? entry?.value ?? null;\n });\n memo.set(url, { at: entry?.at ?? 0, value: entry?.value ?? null, pending });\n // Serve stale while revalidating; first call waits.\n return entry ? entry.value : pending;\n}\n\n/** Tests only. */\nexport function clearRemoteMemo(): void {\n memo.clear();\n}\n","import {\n applyRemoteOverrides,\n CLOUD_ENDPOINT,\n countsForHoldout,\n decideRedirect,\n explainAssignment,\n HOLDOUT_KEY,\n holdoutGroup,\n isDevEnvironment,\n matchPath,\n newId,\n newVisitorId,\n parseCookies,\n parseForceParam,\n parseUserAgent,\n redirectTarget,\n SDK_VERSION,\n type EventBatch,\n type ExposureEvent,\n type SplitHubConfig,\n type TargetingContext,\n} from '@splithub/core';\nimport { NextResponse, type NextFetchEvent, type NextRequest } from 'next/server';\nimport { getRemoteOverrides } from './remote';\n\nexport const VISITOR_HEADER = 'x-splithub-vid';\nconst ONE_YEAR = 60 * 60 * 24 * 365;\n\nexport interface MiddlewareOptions {\n /** Return true to skip a path entirely. Defaults to `_next`, `api` and files with an extension. */\n exclude?: (pathname: string) => boolean;\n /** Send exposures for redirect experiments from the edge. Default true. */\n trackRedirects?: boolean;\n /** Apply live overrides from the cloud (cloud mode only). Default true. */\n remote?: boolean;\n}\n\nfunction defaultExclude(pathname: string): boolean {\n return pathname.startsWith('/_next') || pathname.startsWith('/api/') || /\\.[a-z0-9]+$/i.test(pathname);\n}\n\n/** Same rule as sh.js and pageview goals (from `@splithub/core`). */\nexport { matchPath };\n\n/**\n * Targeting context from request headers: Cloudflare / Vercel geo, user agent, language,\n * referrer, cookies. `timezone` (for `hour` / `weekday`) comes from Vercel's\n * `x-vercel-ip-timezone` or a `cf-timezone` / `x-timezone` header you set; without one\n * the flow uses UTC.\n */\nexport function requestContext(headers: Headers, url: string, visitor?: 'new' | 'returning'): TargetingContext {\n const ua = parseUserAgent(headers.get('user-agent'));\n const country = headers.get('cf-ipcountry') ?? headers.get('x-vercel-ip-country') ?? headers.get('x-country') ?? undefined;\n const region = headers.get('x-vercel-ip-country-region') ?? headers.get('cf-region') ?? undefined;\n const city = headers.get('x-vercel-ip-city') ?? headers.get('cf-ipcity') ?? undefined;\n const timezone = headers.get('x-vercel-ip-timezone') ?? headers.get('cf-timezone') ?? headers.get('x-timezone') ?? undefined;\n return {\n country: country ?? undefined,\n region: region ? decodeURIComponent(region) : undefined,\n city: city ? decodeURIComponent(city) : undefined,\n device: ua.device,\n browser: ua.browser,\n os: ua.os,\n language: headers.get('accept-language') ?? undefined,\n referrer: headers.get('referer') ?? undefined,\n url,\n cookies: parseCookies(headers.get('cookie')),\n ...(timezone ? { timezone } : {}),\n ...(visitor ? { visitor } : {}),\n };\n}\n\nfunction ingestTarget(config: SplitHubConfig, origin: string): { url: string; key?: string } {\n if (config.storage.mode === 'self') return { url: new URL(config.storage.endpoint, origin).toString() };\n return { url: config.storage.endpoint ?? CLOUD_ENDPOINT, key: config.storage.key };\n}\n\n/**\n * Next.js middleware:\n * 1. ensures the `sh_vid` visitor cookie, so SSR and the client agree on variants;\n * 2. forwards the visitor id to Server Components via the `x-splithub-vid` header;\n * 3. serves redirect experiments with an invisible rewrite (URL unchanged, no flash);\n * 4. records the redirect exposure from the edge, deduplicated with a cookie.\n *\n * ```ts\n * // middleware.ts\n * import { splithubMiddleware } from '@splithub/next';\n * import config from './splithub.config';\n * export default splithubMiddleware(config);\n * export const config = { matcher: ['/((?!_next|api|.*\\\\..*).*)'] };\n * ```\n */\nexport function splithubMiddleware(baseConfig: SplitHubConfig, options: MiddlewareOptions = {}) {\n const exclude = options.exclude ?? defaultExclude;\n const trackRedirects = options.trackRedirects ?? true;\n const useRemote = options.remote ?? true;\n\n return async function middleware(request: NextRequest, event?: NextFetchEvent): Promise<NextResponse> {\n const pathname = request.nextUrl.pathname;\n if (exclude(pathname)) return NextResponse.next();\n\n const config = useRemote ? applyRemoteOverrides(baseConfig, await getRemoteOverrides(baseConfig)) : baseConfig;\n\n let visitorId = request.cookies.get(config.visitorKey)?.value ?? null;\n const isNewVisitor = !visitorId;\n if (!visitorId) visitorId = newVisitorId();\n\n const overrides = parseForceParam(request.nextUrl.search);\n const context = requestContext(request.headers, request.nextUrl.href, isNewVisitor ? 'new' : 'returning');\n const requestHeaders = new Headers(request.headers);\n requestHeaders.set(VISITOR_HEADER, visitorId);\n\n let response: NextResponse | null = null;\n const cookiesToSet: Array<{ name: string; value: string }> = [];\n\n // The same decision as sh.js; in development, say why a matching test did nothing.\n // A visitor who reaches a running redirect test also joins the holdout comparison (same rule as the SDK).\n let reachedTest = false as boolean;\n const decision = decideRedirect(config, pathname, visitorId, context, overrides, (exp, a) => {\n if (countsForHoldout(a)) reachedTest = true;\n explainAssignment(exp, a);\n });\n // Development never sends to the cloud (the developer is not a visitor); a self-hosted store records it, dev drafts included.\n // Bots never reach here with a variant: assign gives them the control without one.\n const cloudDev = config.storage.mode === 'cloud' && isDevEnvironment();\n const events: ExposureEvent[] = [];\n if (decision) {\n if (decision.to) {\n const target = redirectTarget(decision.to, request.nextUrl.href);\n let url: URL = target;\n if (target.origin === request.nextUrl.origin) {\n // Keep Next's own URL (basePath, locale) and change only what the variant says.\n const next = request.nextUrl.clone();\n next.pathname = target.pathname;\n next.search = target.search;\n url = next;\n }\n response = NextResponse.rewrite(url, { request: { headers: requestHeaders } });\n }\n\n const exposureCookie = `sh_x_${decision.experiment}`;\n const record = !cloudDev && (decision.reason === 'assigned' || (decision.reason === 'dev' && config.storage.mode === 'self'));\n if (trackRedirects && record && request.cookies.get(exposureCookie)?.value !== decision.variant) {\n cookiesToSet.push({ name: exposureCookie, value: decision.variant });\n events.push({ id: newId('e_'), type: 'exposure', exp: decision.experiment, var: decision.variant, vid: visitorId, sid: 'edge', ts: Date.now(), url: pathname });\n }\n }\n const group = reachedTest ? holdoutGroup(config, visitorId) : null;\n if (group && trackRedirects && !cloudDev && request.cookies.get(`sh_x_${HOLDOUT_KEY}`)?.value !== group) {\n cookiesToSet.push({ name: `sh_x_${HOLDOUT_KEY}`, value: group });\n events.push({ id: newId('e_'), type: 'exposure', exp: HOLDOUT_KEY, var: group, vid: visitorId, sid: 'edge', ts: Date.now(), url: pathname });\n }\n if (events.length) {\n const target = ingestTarget(config, request.nextUrl.origin);\n const batch: EventBatch = { project: config.project, sdk: `next/${SDK_VERSION}`, events };\n const headers: Record<string, string> = { 'content-type': 'application/json' };\n if (target.key) headers.authorization = `Bearer ${target.key}`;\n // The visitor's user agent, so the ingest's bot filter judges the visitor, not this server.\n // `x-splithub-ua` too, for runtimes that replace a user-agent set on fetch.\n const ua = request.headers.get('user-agent');\n if (ua) {\n headers['user-agent'] = ua;\n headers['x-splithub-ua'] = ua;\n }\n const send = fetch(target.url, { method: 'POST', headers, body: JSON.stringify(batch) }).catch(() => undefined);\n if (event?.waitUntil) event.waitUntil(send);\n }\n\n response ??= NextResponse.next({ request: { headers: requestHeaders } });\n\n if (isNewVisitor) {\n response.cookies.set(config.visitorKey, visitorId, { maxAge: ONE_YEAR, path: '/', sameSite: 'lax' });\n }\n for (const c of cookiesToSet) response.cookies.set(c.name, c.value, { maxAge: ONE_YEAR, path: '/', sameSite: 'lax' });\n return response;\n };\n}\n"],"mappings":";AAAA,SAAS,gBAAgB,sBAAsB,qBAAqB,qB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,OAAO,KAAK,EAAE,QAAQ,QAAQ,SAAS,MAAM,KAAK,UAAU,KAAK,EAAE,CAAC,EAAE,MAAM,MAAM,MAAS;AAC9G,UAAI,OAAO,UAAW,OAAM,UAAU,IAAI;AAAA,IAC5C;AAEA,4BAAa,aAAa,KAAK,EAAE,SAAS,EAAE,SAAS,eAAe,EAAE,CAAC;AAEvE,QAAI,cAAc;AAChB,eAAS,QAAQ,IAAI,OAAO,YAAY,WAAW,EAAE,QAAQ,UAAU,MAAM,KAAK,UAAU,MAAM,CAAC;AAAA,IACrG;AACA,eAAW,KAAK,aAAc,UAAS,QAAQ,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,QAAQ,UAAU,MAAM,KAAK,UAAU,MAAM,CAAC;AACpH,WAAO;AAAA,EACT;AACF;","names":["CLOUD_ENDPOINT","CLOUD_ENDPOINT"]}
|
package/dist/index.cjs
CHANGED
|
@@ -24,7 +24,7 @@ __export(src_exports, {
|
|
|
24
24
|
clearRemoteMemo: () => clearRemoteMemo,
|
|
25
25
|
defineConfig: () => import_core3.defineConfig,
|
|
26
26
|
getRemoteOverrides: () => getRemoteOverrides,
|
|
27
|
-
matchPath: () => matchPath,
|
|
27
|
+
matchPath: () => import_core2.matchPath,
|
|
28
28
|
splithubMiddleware: () => splithubMiddleware
|
|
29
29
|
});
|
|
30
30
|
module.exports = __toCommonJS(src_exports);
|
|
@@ -61,15 +61,12 @@ var ONE_YEAR = 60 * 60 * 24 * 365;
|
|
|
61
61
|
function defaultExclude(pathname) {
|
|
62
62
|
return pathname.startsWith("/_next") || pathname.startsWith("/api/") || /\.[a-z0-9]+$/i.test(pathname);
|
|
63
63
|
}
|
|
64
|
-
function matchPath(pattern, pathname) {
|
|
65
|
-
if (pattern.endsWith("*")) return pathname.startsWith(pattern.slice(0, -1));
|
|
66
|
-
return pattern === pathname || `${pattern}/` === pathname;
|
|
67
|
-
}
|
|
68
64
|
function requestContext(headers, url, visitor) {
|
|
69
65
|
const ua = (0, import_core2.parseUserAgent)(headers.get("user-agent"));
|
|
70
66
|
const country = headers.get("cf-ipcountry") ?? headers.get("x-vercel-ip-country") ?? headers.get("x-country") ?? void 0;
|
|
71
67
|
const region = headers.get("x-vercel-ip-country-region") ?? headers.get("cf-region") ?? void 0;
|
|
72
68
|
const city = headers.get("x-vercel-ip-city") ?? headers.get("cf-ipcity") ?? void 0;
|
|
69
|
+
const timezone = headers.get("x-vercel-ip-timezone") ?? headers.get("cf-timezone") ?? headers.get("x-timezone") ?? void 0;
|
|
73
70
|
return {
|
|
74
71
|
country: country ?? void 0,
|
|
75
72
|
region: region ? decodeURIComponent(region) : void 0,
|
|
@@ -81,6 +78,7 @@ function requestContext(headers, url, visitor) {
|
|
|
81
78
|
referrer: headers.get("referer") ?? void 0,
|
|
82
79
|
url,
|
|
83
80
|
cookies: (0, import_core2.parseCookies)(headers.get("cookie")),
|
|
81
|
+
...timezone ? { timezone } : {},
|
|
84
82
|
...visitor ? { visitor } : {}
|
|
85
83
|
};
|
|
86
84
|
}
|
|
@@ -105,40 +103,49 @@ function splithubMiddleware(baseConfig, options = {}) {
|
|
|
105
103
|
requestHeaders.set(VISITOR_HEADER, visitorId);
|
|
106
104
|
let response = null;
|
|
107
105
|
const cookiesToSet = [];
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
if (
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
106
|
+
let reachedTest = false;
|
|
107
|
+
const decision = (0, import_core2.decideRedirect)(config, pathname, visitorId, context, overrides, (exp, a) => {
|
|
108
|
+
if ((0, import_core2.countsForHoldout)(a)) reachedTest = true;
|
|
109
|
+
(0, import_core2.explainAssignment)(exp, a);
|
|
110
|
+
});
|
|
111
|
+
const cloudDev = config.storage.mode === "cloud" && (0, import_core2.isDevEnvironment)();
|
|
112
|
+
const events = [];
|
|
113
|
+
if (decision) {
|
|
114
|
+
if (decision.to) {
|
|
115
|
+
const target = (0, import_core2.redirectTarget)(decision.to, request.nextUrl.href);
|
|
116
|
+
let url = target;
|
|
117
|
+
if (target.origin === request.nextUrl.origin) {
|
|
118
|
+
const next = request.nextUrl.clone();
|
|
119
|
+
next.pathname = target.pathname;
|
|
120
|
+
next.search = target.search;
|
|
121
|
+
url = next;
|
|
122
|
+
}
|
|
121
123
|
response = import_server.NextResponse.rewrite(url, { request: { headers: requestHeaders } });
|
|
122
124
|
}
|
|
123
|
-
const exposureCookie = `sh_x_${experiment
|
|
124
|
-
const
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
125
|
+
const exposureCookie = `sh_x_${decision.experiment}`;
|
|
126
|
+
const record = !cloudDev && (decision.reason === "assigned" || decision.reason === "dev" && config.storage.mode === "self");
|
|
127
|
+
if (trackRedirects && record && request.cookies.get(exposureCookie)?.value !== decision.variant) {
|
|
128
|
+
cookiesToSet.push({ name: exposureCookie, value: decision.variant });
|
|
129
|
+
events.push({ id: (0, import_core2.newId)("e_"), type: "exposure", exp: decision.experiment, var: decision.variant, vid: visitorId, sid: "edge", ts: Date.now(), url: pathname });
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
const group = reachedTest ? (0, import_core2.holdoutGroup)(config, visitorId) : null;
|
|
133
|
+
if (group && trackRedirects && !cloudDev && request.cookies.get(`sh_x_${import_core2.HOLDOUT_KEY}`)?.value !== group) {
|
|
134
|
+
cookiesToSet.push({ name: `sh_x_${import_core2.HOLDOUT_KEY}`, value: group });
|
|
135
|
+
events.push({ id: (0, import_core2.newId)("e_"), type: "exposure", exp: import_core2.HOLDOUT_KEY, var: group, vid: visitorId, sid: "edge", ts: Date.now(), url: pathname });
|
|
136
|
+
}
|
|
137
|
+
if (events.length) {
|
|
138
|
+
const target = ingestTarget(config, request.nextUrl.origin);
|
|
139
|
+
const batch = { project: config.project, sdk: `next/${import_core2.SDK_VERSION}`, events };
|
|
140
|
+
const headers = { "content-type": "application/json" };
|
|
141
|
+
if (target.key) headers.authorization = `Bearer ${target.key}`;
|
|
142
|
+
const ua = request.headers.get("user-agent");
|
|
143
|
+
if (ua) {
|
|
144
|
+
headers["user-agent"] = ua;
|
|
145
|
+
headers["x-splithub-ua"] = ua;
|
|
140
146
|
}
|
|
141
|
-
|
|
147
|
+
const send = fetch(target.url, { method: "POST", headers, body: JSON.stringify(batch) }).catch(() => void 0);
|
|
148
|
+
if (event?.waitUntil) event.waitUntil(send);
|
|
142
149
|
}
|
|
143
150
|
response ?? (response = import_server.NextResponse.next({ request: { headers: requestHeaders } }));
|
|
144
151
|
if (isNewVisitor) {
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/middleware.ts","../src/remote.ts"],"sourcesContent":["export { splithubMiddleware, matchPath, VISITOR_HEADER } from './middleware';\nexport type { MiddlewareOptions } from './middleware';\nexport { getRemoteOverrides, clearRemoteMemo } from './remote';\nexport { defineConfig } from '@splithub/core';\nexport type { SplitHubConfig, SplitHubConfigInput } from '@splithub/core';\n","import {\n applyRemoteOverrides,\n assign,\n CLOUD_ENDPOINT,\n explainAssignment,\n isActive,\n isDevEnvironment,\n newId,\n newVisitorId,\n parseCookies,\n parseForceParam,\n parseUserAgent,\n SDK_VERSION,\n type EventBatch,\n type SplitHubConfig,\n type TargetingContext,\n} from '@splithub/core';\nimport { NextResponse, type NextFetchEvent, type NextRequest } from 'next/server';\nimport { getRemoteOverrides } from './remote';\n\nexport const VISITOR_HEADER = 'x-splithub-vid';\nconst ONE_YEAR = 60 * 60 * 24 * 365;\n\nexport interface MiddlewareOptions {\n /** Return true to skip a path entirely. Defaults to `_next`, `api` and files with an extension. */\n exclude?: (pathname: string) => boolean;\n /** Send exposures for redirect experiments from the edge. Default true. */\n trackRedirects?: boolean;\n /** Apply live overrides from the cloud (cloud mode only). Default true. */\n remote?: boolean;\n}\n\nfunction defaultExclude(pathname: string): boolean {\n return pathname.startsWith('/_next') || pathname.startsWith('/api/') || /\\.[a-z0-9]+$/i.test(pathname);\n}\n\n/** `match` is an exact path, or a prefix ending with `*`. */\nexport function matchPath(pattern: string, pathname: string): boolean {\n if (pattern.endsWith('*')) return pathname.startsWith(pattern.slice(0, -1));\n return pattern === pathname || `${pattern}/` === pathname;\n}\n\n/** Targeting context from request headers: Cloudflare / Vercel geo, user agent, language, referrer, cookies. */\nexport function requestContext(headers: Headers, url: string, visitor?: 'new' | 'returning'): TargetingContext {\n const ua = parseUserAgent(headers.get('user-agent'));\n const country = headers.get('cf-ipcountry') ?? headers.get('x-vercel-ip-country') ?? headers.get('x-country') ?? undefined;\n const region = headers.get('x-vercel-ip-country-region') ?? headers.get('cf-region') ?? undefined;\n const city = headers.get('x-vercel-ip-city') ?? headers.get('cf-ipcity') ?? undefined;\n return {\n country: country ?? undefined,\n region: region ? decodeURIComponent(region) : undefined,\n city: city ? decodeURIComponent(city) : undefined,\n device: ua.device,\n browser: ua.browser,\n os: ua.os,\n language: headers.get('accept-language') ?? undefined,\n referrer: headers.get('referer') ?? undefined,\n url,\n cookies: parseCookies(headers.get('cookie')),\n ...(visitor ? { visitor } : {}),\n };\n}\n\nfunction ingestTarget(config: SplitHubConfig, origin: string): { url: string; key?: string } {\n if (config.storage.mode === 'self') return { url: new URL(config.storage.endpoint, origin).toString() };\n return { url: config.storage.endpoint ?? CLOUD_ENDPOINT, key: config.storage.key };\n}\n\n/**\n * Next.js middleware:\n * 1. ensures the `sh_vid` visitor cookie, so SSR and the client agree on variants;\n * 2. forwards the visitor id to Server Components via the `x-splithub-vid` header;\n * 3. serves redirect experiments with an invisible rewrite (URL unchanged, no flash);\n * 4. records the redirect exposure from the edge, deduplicated with a cookie.\n *\n * ```ts\n * // middleware.ts\n * import { splithubMiddleware } from '@splithub/next';\n * import config from './splithub.config';\n * export default splithubMiddleware(config);\n * export const config = { matcher: ['/((?!_next|api|.*\\\\..*).*)'] };\n * ```\n */\nexport function splithubMiddleware(baseConfig: SplitHubConfig, options: MiddlewareOptions = {}) {\n const exclude = options.exclude ?? defaultExclude;\n const trackRedirects = options.trackRedirects ?? true;\n const useRemote = options.remote ?? true;\n\n return async function middleware(request: NextRequest, event?: NextFetchEvent): Promise<NextResponse> {\n const pathname = request.nextUrl.pathname;\n if (exclude(pathname)) return NextResponse.next();\n\n const config = useRemote ? applyRemoteOverrides(baseConfig, await getRemoteOverrides(baseConfig)) : baseConfig;\n\n let visitorId = request.cookies.get(config.visitorKey)?.value ?? null;\n const isNewVisitor = !visitorId;\n if (!visitorId) visitorId = newVisitorId();\n\n const overrides = parseForceParam(request.nextUrl.search);\n const context = requestContext(request.headers, request.nextUrl.href, isNewVisitor ? 'new' : 'returning');\n const requestHeaders = new Headers(request.headers);\n requestHeaders.set(VISITOR_HEADER, visitorId);\n\n let response: NextResponse | null = null;\n const cookiesToSet: Array<{ name: string; value: string }> = [];\n\n for (const experiment of config.experiments) {\n if (experiment.kind !== 'redirect' || !experiment.match || !matchPath(experiment.match, pathname)) continue;\n if (!isActive(config, experiment)) {\n // A redirect test that would have applied here: say why it did not (development only, once).\n explainAssignment(experiment, { experiment: experiment.key, variant: null, reason: 'not_running' });\n continue;\n }\n\n const assignment = assign(config, experiment.key, visitorId, { overrides, context });\n explainAssignment(experiment, assignment);\n const variant = assignment.variant;\n if (!variant?.to) continue;\n\n if (variant.to !== pathname) {\n const url = request.nextUrl.clone();\n url.pathname = variant.to;\n response = NextResponse.rewrite(url, { request: { headers: requestHeaders } });\n }\n\n const exposureCookie = `sh_x_${experiment.key}`;\n // Development never sends to the cloud (the developer is not a visitor); a self-hosted store records it, dev drafts included.\n const cloudDev = config.storage.mode === 'cloud' && isDevEnvironment();\n const record = !cloudDev && (assignment.reason === 'assigned' || (assignment.reason === 'dev' && config.storage.mode === 'self'));\n if (trackRedirects && record && request.cookies.get(exposureCookie)?.value !== variant.key) {\n cookiesToSet.push({ name: exposureCookie, value: variant.key });\n const target = ingestTarget(config, request.nextUrl.origin);\n const batch: EventBatch = {\n project: config.project,\n sdk: `next/${SDK_VERSION}`,\n events: [\n { id: newId('e_'), type: 'exposure', exp: experiment.key, var: variant.key, vid: visitorId, sid: 'edge', ts: Date.now(), url: pathname },\n ],\n };\n const headers: Record<string, string> = { 'content-type': 'application/json' };\n if (target.key) headers.authorization = `Bearer ${target.key}`;\n const send = fetch(target.url, { method: 'POST', headers, body: JSON.stringify(batch) }).catch(() => undefined);\n if (event?.waitUntil) event.waitUntil(send);\n }\n break; // the first matching redirect experiment wins\n }\n\n response ??= NextResponse.next({ request: { headers: requestHeaders } });\n\n if (isNewVisitor) {\n response.cookies.set(config.visitorKey, visitorId, { maxAge: ONE_YEAR, path: '/', sameSite: 'lax' });\n }\n for (const c of cookiesToSet) response.cookies.set(c.name, c.value, { maxAge: ONE_YEAR, path: '/', sameSite: 'lax' });\n return response;\n };\n}\n","import { CLOUD_ENDPOINT, fetchRemoteOverrides, resolveOverridesUrl, REMOTE_TTL_MS, type RemoteOverrides, type SplitHubConfig } from '@splithub/core';\n\ninterface MemoEntry {\n at: number;\n value: RemoteOverrides | null;\n pending: Promise<RemoteOverrides | null> | null;\n}\n\n// Module-level memo: edge isolates and Node servers keep it across requests,\n// so at most one fetch per TTL per public key.\nconst memo = new Map<string, MemoEntry>();\n\nexport interface RemoteOptions {\n ttlMs?: number;\n /** Override the fetch implementation (tests). */\n fetchImpl?: typeof fetch;\n}\n\n/**\n * Live overrides for a cloud-mode config, cached in memory for `ttlMs`\n * (default 60s). Returns null in self mode or when the cloud is unreachable\n * (the config file then applies as-is).\n */\nexport async function getRemoteOverrides(config: SplitHubConfig, options: RemoteOptions = {}): Promise<RemoteOverrides | null> {\n if (config.storage.mode !== 'cloud' || !config.storage.key) return null;\n const ttl = options.ttlMs ?? REMOTE_TTL_MS;\n const url = resolveOverridesUrl(config.storage.endpoint ?? CLOUD_ENDPOINT, config.storage.key);\n const entry = memo.get(url);\n const now = Date.now();\n if (entry && now - entry.at < ttl) return entry.value;\n if (entry?.pending) return entry.value ?? entry.pending;\n\n const pending = fetchRemoteOverrides(url, options.fetchImpl).then((value) => {\n memo.set(url, { at: Date.now(), value: value ?? entry?.value ?? null, pending: null });\n return value ?? entry?.value ?? null;\n });\n memo.set(url, { at: entry?.at ?? 0, value: entry?.value ?? null, pending });\n // Serve stale while revalidating; first call waits.\n return entry ? entry.value : pending;\n}\n\n/** Tests only. */\nexport function clearRemoteMemo(): void {\n memo.clear();\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,IAAAA,eAgBO;AACP,oBAAoE;;;ACjBpE,kBAAoI;AAUpI,IAAM,OAAO,oBAAI,IAAuB;AAaxC,eAAsB,mBAAmB,QAAwB,UAAyB,CAAC,GAAoC;AAC7H,MAAI,OAAO,QAAQ,SAAS,WAAW,CAAC,OAAO,QAAQ,IAAK,QAAO;AACnE,QAAM,MAAM,QAAQ,SAAS;AAC7B,QAAM,UAAM,iCAAoB,OAAO,QAAQ,YAAY,4BAAgB,OAAO,QAAQ,GAAG;AAC7F,QAAM,QAAQ,KAAK,IAAI,GAAG;AAC1B,QAAM,MAAM,KAAK,IAAI;AACrB,MAAI,SAAS,MAAM,MAAM,KAAK,IAAK,QAAO,MAAM;AAChD,MAAI,OAAO,QAAS,QAAO,MAAM,SAAS,MAAM;AAEhD,QAAM,cAAU,kCAAqB,KAAK,QAAQ,SAAS,EAAE,KAAK,CAAC,UAAU;AAC3E,SAAK,IAAI,KAAK,EAAE,IAAI,KAAK,IAAI,GAAG,OAAO,SAAS,OAAO,SAAS,MAAM,SAAS,KAAK,CAAC;AACrF,WAAO,SAAS,OAAO,SAAS;AAAA,EAClC,CAAC;AACD,OAAK,I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AAO,UAAW,OAAM,UAAU,IAAI;AAAA,MAC5C;AACA;AAAA,IACF;AAEA,4BAAa,2BAAa,KAAK,EAAE,SAAS,EAAE,SAAS,eAAe,EAAE,CAAC;AAEvE,QAAI,cAAc;AAChB,eAAS,QAAQ,IAAI,OAAO,YAAY,WAAW,EAAE,QAAQ,UAAU,MAAM,KAAK,UAAU,MAAM,CAAC;AAAA,IACrG;AACA,eAAW,KAAK,aAAc,UAAS,QAAQ,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,QAAQ,UAAU,MAAM,KAAK,UAAU,MAAM,CAAC;AACpH,WAAO;AAAA,EACT;AACF;;;ADxJA,IAAAC,eAA6B;","names":["import_core","import_core"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/middleware.ts","../src/remote.ts"],"sourcesContent":["export { splithubMiddleware, matchPath, VISITOR_HEADER } from './middleware';\nexport type { MiddlewareOptions } from './middleware';\nexport { getRemoteOverrides, clearRemoteMemo } from './remote';\nexport { defineConfig } from '@splithub/core';\nexport type { SplitHubConfig, SplitHubConfigInput } from '@splithub/core';\n","import {\n applyRemoteOverrides,\n CLOUD_ENDPOINT,\n countsForHoldout,\n decideRedirect,\n explainAssignment,\n HOLDOUT_KEY,\n holdoutGroup,\n isDevEnvironment,\n matchPath,\n newId,\n newVisitorId,\n parseCookies,\n parseForceParam,\n parseUserAgent,\n redirectTarget,\n SDK_VERSION,\n type EventBatch,\n type ExposureEvent,\n type SplitHubConfig,\n type TargetingContext,\n} from '@splithub/core';\nimport { NextResponse, type NextFetchEvent, type NextRequest } from 'next/server';\nimport { getRemoteOverrides } from './remote';\n\nexport const VISITOR_HEADER = 'x-splithub-vid';\nconst ONE_YEAR = 60 * 60 * 24 * 365;\n\nexport interface MiddlewareOptions {\n /** Return true to skip a path entirely. Defaults to `_next`, `api` and files with an extension. */\n exclude?: (pathname: string) => boolean;\n /** Send exposures for redirect experiments from the edge. Default true. */\n trackRedirects?: boolean;\n /** Apply live overrides from the cloud (cloud mode only). Default true. */\n remote?: boolean;\n}\n\nfunction defaultExclude(pathname: string): boolean {\n return pathname.startsWith('/_next') || pathname.startsWith('/api/') || /\\.[a-z0-9]+$/i.test(pathname);\n}\n\n/** Same rule as sh.js and pageview goals (from `@splithub/core`). */\nexport { matchPath };\n\n/**\n * Targeting context from request headers: Cloudflare / Vercel geo, user agent, language,\n * referrer, cookies. `timezone` (for `hour` / `weekday`) comes from Vercel's\n * `x-vercel-ip-timezone` or a `cf-timezone` / `x-timezone` header you set; without one\n * the flow uses UTC.\n */\nexport function requestContext(headers: Headers, url: string, visitor?: 'new' | 'returning'): TargetingContext {\n const ua = parseUserAgent(headers.get('user-agent'));\n const country = headers.get('cf-ipcountry') ?? headers.get('x-vercel-ip-country') ?? headers.get('x-country') ?? undefined;\n const region = headers.get('x-vercel-ip-country-region') ?? headers.get('cf-region') ?? undefined;\n const city = headers.get('x-vercel-ip-city') ?? headers.get('cf-ipcity') ?? undefined;\n const timezone = headers.get('x-vercel-ip-timezone') ?? headers.get('cf-timezone') ?? headers.get('x-timezone') ?? undefined;\n return {\n country: country ?? undefined,\n region: region ? decodeURIComponent(region) : undefined,\n city: city ? decodeURIComponent(city) : undefined,\n device: ua.device,\n browser: ua.browser,\n os: ua.os,\n language: headers.get('accept-language') ?? undefined,\n referrer: headers.get('referer') ?? undefined,\n url,\n cookies: parseCookies(headers.get('cookie')),\n ...(timezone ? { timezone } : {}),\n ...(visitor ? { visitor } : {}),\n };\n}\n\nfunction ingestTarget(config: SplitHubConfig, origin: string): { url: string; key?: string } {\n if (config.storage.mode === 'self') return { url: new URL(config.storage.endpoint, origin).toString() };\n return { url: config.storage.endpoint ?? CLOUD_ENDPOINT, key: config.storage.key };\n}\n\n/**\n * Next.js middleware:\n * 1. ensures the `sh_vid` visitor cookie, so SSR and the client agree on variants;\n * 2. forwards the visitor id to Server Components via the `x-splithub-vid` header;\n * 3. serves redirect experiments with an invisible rewrite (URL unchanged, no flash);\n * 4. records the redirect exposure from the edge, deduplicated with a cookie.\n *\n * ```ts\n * // middleware.ts\n * import { splithubMiddleware } from '@splithub/next';\n * import config from './splithub.config';\n * export default splithubMiddleware(config);\n * export const config = { matcher: ['/((?!_next|api|.*\\\\..*).*)'] };\n * ```\n */\nexport function splithubMiddleware(baseConfig: SplitHubConfig, options: MiddlewareOptions = {}) {\n const exclude = options.exclude ?? defaultExclude;\n const trackRedirects = options.trackRedirects ?? true;\n const useRemote = options.remote ?? true;\n\n return async function middleware(request: NextRequest, event?: NextFetchEvent): Promise<NextResponse> {\n const pathname = request.nextUrl.pathname;\n if (exclude(pathname)) return NextResponse.next();\n\n const config = useRemote ? applyRemoteOverrides(baseConfig, await getRemoteOverrides(baseConfig)) : baseConfig;\n\n let visitorId = request.cookies.get(config.visitorKey)?.value ?? null;\n const isNewVisitor = !visitorId;\n if (!visitorId) visitorId = newVisitorId();\n\n const overrides = parseForceParam(request.nextUrl.search);\n const context = requestContext(request.headers, request.nextUrl.href, isNewVisitor ? 'new' : 'returning');\n const requestHeaders = new Headers(request.headers);\n requestHeaders.set(VISITOR_HEADER, visitorId);\n\n let response: NextResponse | null = null;\n const cookiesToSet: Array<{ name: string; value: string }> = [];\n\n // The same decision as sh.js; in development, say why a matching test did nothing.\n // A visitor who reaches a running redirect test also joins the holdout comparison (same rule as the SDK).\n let reachedTest = false as boolean;\n const decision = decideRedirect(config, pathname, visitorId, context, overrides, (exp, a) => {\n if (countsForHoldout(a)) reachedTest = true;\n explainAssignment(exp, a);\n });\n // Development never sends to the cloud (the developer is not a visitor); a self-hosted store records it, dev drafts included.\n // Bots never reach here with a variant: assign gives them the control without one.\n const cloudDev = config.storage.mode === 'cloud' && isDevEnvironment();\n const events: ExposureEvent[] = [];\n if (decision) {\n if (decision.to) {\n const target = redirectTarget(decision.to, request.nextUrl.href);\n let url: URL = target;\n if (target.origin === request.nextUrl.origin) {\n // Keep Next's own URL (basePath, locale) and change only what the variant says.\n const next = request.nextUrl.clone();\n next.pathname = target.pathname;\n next.search = target.search;\n url = next;\n }\n response = NextResponse.rewrite(url, { request: { headers: requestHeaders } });\n }\n\n const exposureCookie = `sh_x_${decision.experiment}`;\n const record = !cloudDev && (decision.reason === 'assigned' || (decision.reason === 'dev' && config.storage.mode === 'self'));\n if (trackRedirects && record && request.cookies.get(exposureCookie)?.value !== decision.variant) {\n cookiesToSet.push({ name: exposureCookie, value: decision.variant });\n events.push({ id: newId('e_'), type: 'exposure', exp: decision.experiment, var: decision.variant, vid: visitorId, sid: 'edge', ts: Date.now(), url: pathname });\n }\n }\n const group = reachedTest ? holdoutGroup(config, visitorId) : null;\n if (group && trackRedirects && !cloudDev && request.cookies.get(`sh_x_${HOLDOUT_KEY}`)?.value !== group) {\n cookiesToSet.push({ name: `sh_x_${HOLDOUT_KEY}`, value: group });\n events.push({ id: newId('e_'), type: 'exposure', exp: HOLDOUT_KEY, var: group, vid: visitorId, sid: 'edge', ts: Date.now(), url: pathname });\n }\n if (events.length) {\n const target = ingestTarget(config, request.nextUrl.origin);\n const batch: EventBatch = { project: config.project, sdk: `next/${SDK_VERSION}`, events };\n const headers: Record<string, string> = { 'content-type': 'application/json' };\n if (target.key) headers.authorization = `Bearer ${target.key}`;\n // The visitor's user agent, so the ingest's bot filter judges the visitor, not this server.\n // `x-splithub-ua` too, for runtimes that replace a user-agent set on fetch.\n const ua = request.headers.get('user-agent');\n if (ua) {\n headers['user-agent'] = ua;\n headers['x-splithub-ua'] = ua;\n }\n const send = fetch(target.url, { method: 'POST', headers, body: JSON.stringify(batch) }).catch(() => undefined);\n if (event?.waitUntil) event.waitUntil(send);\n }\n\n response ??= NextResponse.next({ request: { headers: requestHeaders } });\n\n if (isNewVisitor) {\n response.cookies.set(config.visitorKey, visitorId, { maxAge: ONE_YEAR, path: '/', sameSite: 'lax' });\n }\n for (const c of cookiesToSet) response.cookies.set(c.name, c.value, { maxAge: ONE_YEAR, path: '/', sameSite: 'lax' });\n return response;\n };\n}\n","import { CLOUD_ENDPOINT, fetchRemoteOverrides, resolveOverridesUrl, REMOTE_TTL_MS, type RemoteOverrides, type SplitHubConfig } from '@splithub/core';\n\ninterface MemoEntry {\n at: number;\n value: RemoteOverrides | null;\n pending: Promise<RemoteOverrides | null> | null;\n}\n\n// Module-level memo: edge isolates and Node servers keep it across requests,\n// so at most one fetch per TTL per public key.\nconst memo = new Map<string, MemoEntry>();\n\nexport interface RemoteOptions {\n ttlMs?: number;\n /** Override the fetch implementation (tests). */\n fetchImpl?: typeof fetch;\n}\n\n/**\n * Live overrides for a cloud-mode config, cached in memory for `ttlMs`\n * (default 60s). Returns null in self mode or when the cloud is unreachable\n * (the config file then applies as-is).\n */\nexport async function getRemoteOverrides(config: SplitHubConfig, options: RemoteOptions = {}): Promise<RemoteOverrides | null> {\n if (config.storage.mode !== 'cloud' || !config.storage.key) return null;\n const ttl = options.ttlMs ?? REMOTE_TTL_MS;\n const url = resolveOverridesUrl(config.storage.endpoint ?? CLOUD_ENDPOINT, config.storage.key);\n const entry = memo.get(url);\n const now = Date.now();\n if (entry && now - entry.at < ttl) return entry.value;\n if (entry?.pending) return entry.value ?? entry.pending;\n\n const pending = fetchRemoteOverrides(url, options.fetchImpl).then((value) => {\n memo.set(url, { at: Date.now(), value: value ?? entry?.value ?? null, pending: null });\n return value ?? entry?.value ?? null;\n });\n memo.set(url, { at: entry?.at ?? 0, value: entry?.value ?? null, pending });\n // Serve stale while revalidating; first call waits.\n return entry ? entry.value : pending;\n}\n\n/** Tests only. */\nexport function clearRemoteMemo(): void {\n memo.clear();\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,IAAAA,eAqBO;AACP,oBAAoE;;;ACtBpE,kBAAoI;AAUpI,IAAM,OAAO,oBAAI,IAAuB;AAaxC,eAAsB,mBAAmB,QAAwB,UAAyB,CAAC,GAAoC;AAC7H,MAAI,OAAO,QAAQ,SAAS,WAAW,CAAC,OAAO,QAAQ,IAAK,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eAAW,KAAK,aAAc,UAAS,QAAQ,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,QAAQ,UAAU,MAAM,KAAK,UAAU,MAAM,CAAC;AACpH,WAAO;AAAA,EACT;AACF;;;AD7KA,IAAAC,eAA6B;","names":["import_core","import_core"]}
|
package/dist/index.d.cts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { SplitHubConfig } from '@splithub/core';
|
|
2
|
-
export { SplitHubConfig, SplitHubConfigInput, defineConfig } from '@splithub/core';
|
|
2
|
+
export { SplitHubConfig, SplitHubConfigInput, defineConfig, matchPath } from '@splithub/core';
|
|
3
3
|
import { NextRequest, NextFetchEvent, NextResponse } from 'next/server';
|
|
4
4
|
export { c as clearRemoteMemo, g as getRemoteOverrides } from './remote-D7AfTTCw.cjs';
|
|
5
5
|
|
|
@@ -12,8 +12,7 @@ interface MiddlewareOptions {
|
|
|
12
12
|
/** Apply live overrides from the cloud (cloud mode only). Default true. */
|
|
13
13
|
remote?: boolean;
|
|
14
14
|
}
|
|
15
|
-
|
|
16
|
-
declare function matchPath(pattern: string, pathname: string): boolean;
|
|
15
|
+
|
|
17
16
|
/**
|
|
18
17
|
* Next.js middleware:
|
|
19
18
|
* 1. ensures the `sh_vid` visitor cookie, so SSR and the client agree on variants;
|
|
@@ -31,4 +30,4 @@ declare function matchPath(pattern: string, pathname: string): boolean;
|
|
|
31
30
|
*/
|
|
32
31
|
declare function splithubMiddleware(baseConfig: SplitHubConfig, options?: MiddlewareOptions): (request: NextRequest, event?: NextFetchEvent) => Promise<NextResponse>;
|
|
33
32
|
|
|
34
|
-
export { type MiddlewareOptions, VISITOR_HEADER,
|
|
33
|
+
export { type MiddlewareOptions, VISITOR_HEADER, splithubMiddleware };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { SplitHubConfig } from '@splithub/core';
|
|
2
|
-
export { SplitHubConfig, SplitHubConfigInput, defineConfig } from '@splithub/core';
|
|
2
|
+
export { SplitHubConfig, SplitHubConfigInput, defineConfig, matchPath } from '@splithub/core';
|
|
3
3
|
import { NextRequest, NextFetchEvent, NextResponse } from 'next/server';
|
|
4
4
|
export { c as clearRemoteMemo, g as getRemoteOverrides } from './remote-D7AfTTCw.js';
|
|
5
5
|
|
|
@@ -12,8 +12,7 @@ interface MiddlewareOptions {
|
|
|
12
12
|
/** Apply live overrides from the cloud (cloud mode only). Default true. */
|
|
13
13
|
remote?: boolean;
|
|
14
14
|
}
|
|
15
|
-
|
|
16
|
-
declare function matchPath(pattern: string, pathname: string): boolean;
|
|
15
|
+
|
|
17
16
|
/**
|
|
18
17
|
* Next.js middleware:
|
|
19
18
|
* 1. ensures the `sh_vid` visitor cookie, so SSR and the client agree on variants;
|
|
@@ -31,4 +30,4 @@ declare function matchPath(pattern: string, pathname: string): boolean;
|
|
|
31
30
|
*/
|
|
32
31
|
declare function splithubMiddleware(baseConfig: SplitHubConfig, options?: MiddlewareOptions): (request: NextRequest, event?: NextFetchEvent) => Promise<NextResponse>;
|
|
33
32
|
|
|
34
|
-
export { type MiddlewareOptions, VISITOR_HEADER,
|
|
33
|
+
export { type MiddlewareOptions, VISITOR_HEADER, splithubMiddleware };
|
package/dist/index.js
CHANGED
package/dist/server.cjs
CHANGED
|
@@ -59,6 +59,7 @@ function requestContext(headers2, url, visitor) {
|
|
|
59
59
|
const country = headers2.get("cf-ipcountry") ?? headers2.get("x-vercel-ip-country") ?? headers2.get("x-country") ?? void 0;
|
|
60
60
|
const region = headers2.get("x-vercel-ip-country-region") ?? headers2.get("cf-region") ?? void 0;
|
|
61
61
|
const city = headers2.get("x-vercel-ip-city") ?? headers2.get("cf-ipcity") ?? void 0;
|
|
62
|
+
const timezone = headers2.get("x-vercel-ip-timezone") ?? headers2.get("cf-timezone") ?? headers2.get("x-timezone") ?? void 0;
|
|
62
63
|
return {
|
|
63
64
|
country: country ?? void 0,
|
|
64
65
|
region: region ? decodeURIComponent(region) : void 0,
|
|
@@ -70,6 +71,7 @@ function requestContext(headers2, url, visitor) {
|
|
|
70
71
|
referrer: headers2.get("referer") ?? void 0,
|
|
71
72
|
url,
|
|
72
73
|
cookies: (0, import_core2.parseCookies)(headers2.get("cookie")),
|
|
74
|
+
...timezone ? { timezone } : {},
|
|
73
75
|
...visitor ? { visitor } : {}
|
|
74
76
|
};
|
|
75
77
|
}
|
|
@@ -83,10 +85,14 @@ async function getVisitorId(config) {
|
|
|
83
85
|
return c.get(config.visitorKey)?.value ?? null;
|
|
84
86
|
}
|
|
85
87
|
async function getSplitHub(baseConfig) {
|
|
86
|
-
const [visitorId,
|
|
87
|
-
const config = (0, import_core3.applyRemoteOverrides)(baseConfig,
|
|
88
|
+
const [visitorId, fetched] = await Promise.all([getVisitorId(baseConfig), getRemoteOverrides(baseConfig)]);
|
|
89
|
+
const config = (0, import_core3.applyRemoteOverrides)(baseConfig, fetched);
|
|
88
90
|
const h = await (0, import_headers.headers)();
|
|
89
|
-
const context =
|
|
91
|
+
const context = requestContext(h, h.get("x-url") ?? h.get("referer") ?? "");
|
|
92
|
+
const geo = Object.fromEntries(
|
|
93
|
+
["country", "region", "city", "timezone"].filter((k) => context[k]).map((k) => [k, context[k]])
|
|
94
|
+
);
|
|
95
|
+
const overrides = fetched ? { ...fetched, ctx: geo } : Object.keys(geo).length ? { version: 0, experiments: {}, ctx: geo } : null;
|
|
90
96
|
const control = (key) => (0, import_core3.getExperiment)(config, key)?.variants[0];
|
|
91
97
|
const opts = { context };
|
|
92
98
|
const decide = (key) => {
|
package/dist/server.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/server.ts","../src/remote.ts","../src/middleware.ts"],"sourcesContent":["import { applyRemoteOverrides, assign, explainAssignment, getExperiment, type Assignment, type RemoteOverrides, type SplitHubConfig, type TargetingContext } from '@splithub/core';\nimport { getRemoteOverrides } from './remote';\nimport { cookies, headers } from 'next/headers';\nimport { requestContext, VISITOR_HEADER } from './middleware';\n\nexport { getRemoteOverrides } from './remote';\n\n/**\n * Visitor id for the current request (header set by the middleware, else the\n * cookie). Null when the middleware is not installed and no cookie exists.\n */\nexport async function getVisitorId(config: SplitHubConfig): Promise<string | null> {\n const h = await headers();\n const fromHeader = h.get(VISITOR_HEADER);\n if (fromHeader) return fromHeader;\n const c = await cookies();\n return c.get(config.visitorKey)?.value ?? null;\n}\n\nexport interface ServerSplitHub {\n visitorId: string | null;\n /** Targeting context built from the request headers (geo, device, language, referrer). */\n context: TargetingContext;\n /** Live overrides applied to this request; pass them to <SplitHubNextProvider remoteOverrides={...}> so hydration agrees. */\n overrides: RemoteOverrides | null;\n /** Config with overrides applied. */\n config: SplitHubConfig;\n assignment(experimentKey: string): Assignment;\n /** Variant key; control when unassigned. No exposure is recorded on the server: render `<Exposure id>` from `@splithub/next/client`. */\n variant(experimentKey: string): string;\n value<T = unknown>(experimentKey: string): T;\n}\n\n/**\n * Assignments inside Server Components and Route Handlers:\n *\n * ```tsx\n * const sh = await getSplitHub(config);\n * const title = sh.value<string>('hero-title');\n * ```\n */\nexport async function getSplitHub(baseConfig: SplitHubConfig): Promise<ServerSplitHub> {\n const [visitorId, overrides] = await Promise.all([getVisitorId(baseConfig), getRemoteOverrides(baseConfig)]);\n const config = applyRemoteOverrides(baseConfig, overrides);\n const h = await headers();\n const context: TargetingContext = { ...requestContext(h, h.get('x-url') ?? h.get('referer') ?? ''), ...(overrides?.ctx ?? {}) };\n const control = (key: string) => getExperiment(config, key)?.variants[0];\n const opts = { context };\n // Assign and, in development, explain a surprising result in the terminal.\n const decide = (key: string) => {\n if (!visitorId) return null;\n const a = assign(config, key, visitorId, opts);\n explainAssignment(getExperiment(config, key), a);\n return a;\n };\n return {\n visitorId,\n context,\n overrides,\n config,\n assignment(key) {\n return decide(key) ?? { experiment: key, variant: null, reason: 'not_running' };\n },\n variant(key) {\n const a = decide(key);\n return (a?.variant ?? control(key))?.key ?? 'control';\n },\n value<T>(key: string): T {\n const a = decide(key);\n return (a?.variant ?? control(key))?.value as T;\n },\n };\n}\n","import { CLOUD_ENDPOINT, fetchRemoteOverrides, resolveOverridesUrl, REMOTE_TTL_MS, type RemoteOverrides, type SplitHubConfig } from '@splithub/core';\n\ninterface MemoEntry {\n at: number;\n value: RemoteOverrides | null;\n pending: Promise<RemoteOverrides | null> | null;\n}\n\n// Module-level memo: edge isolates and Node servers keep it across requests,\n// so at most one fetch per TTL per public key.\nconst memo = new Map<string, MemoEntry>();\n\nexport interface RemoteOptions {\n ttlMs?: number;\n /** Override the fetch implementation (tests). */\n fetchImpl?: typeof fetch;\n}\n\n/**\n * Live overrides for a cloud-mode config, cached in memory for `ttlMs`\n * (default 60s). Returns null in self mode or when the cloud is unreachable\n * (the config file then applies as-is).\n */\nexport async function getRemoteOverrides(config: SplitHubConfig, options: RemoteOptions = {}): Promise<RemoteOverrides | null> {\n if (config.storage.mode !== 'cloud' || !config.storage.key) return null;\n const ttl = options.ttlMs ?? REMOTE_TTL_MS;\n const url = resolveOverridesUrl(config.storage.endpoint ?? CLOUD_ENDPOINT, config.storage.key);\n const entry = memo.get(url);\n const now = Date.now();\n if (entry && now - entry.at < ttl) return entry.value;\n if (entry?.pending) return entry.value ?? entry.pending;\n\n const pending = fetchRemoteOverrides(url, options.fetchImpl).then((value) => {\n memo.set(url, { at: Date.now(), value: value ?? entry?.value ?? null, pending: null });\n return value ?? entry?.value ?? null;\n });\n memo.set(url, { at: entry?.at ?? 0, value: entry?.value ?? null, pending });\n // Serve stale while revalidating; first call waits.\n return entry ? entry.value : pending;\n}\n\n/** Tests only. */\nexport function clearRemoteMemo(): void {\n memo.clear();\n}\n","import {\n applyRemoteOverrides,\n assign,\n CLOUD_ENDPOINT,\n explainAssignment,\n isActive,\n isDevEnvironment,\n newId,\n newVisitorId,\n parseCookies,\n parseForceParam,\n parseUserAgent,\n SDK_VERSION,\n type EventBatch,\n type SplitHubConfig,\n type TargetingContext,\n} from '@splithub/core';\nimport { NextResponse, type NextFetchEvent, type NextRequest } from 'next/server';\nimport { getRemoteOverrides } from './remote';\n\nexport const VISITOR_HEADER = 'x-splithub-vid';\nconst ONE_YEAR = 60 * 60 * 24 * 365;\n\nexport interface MiddlewareOptions {\n /** Return true to skip a path entirely. Defaults to `_next`, `api` and files with an extension. */\n exclude?: (pathname: string) => boolean;\n /** Send exposures for redirect experiments from the edge. Default true. */\n trackRedirects?: boolean;\n /** Apply live overrides from the cloud (cloud mode only). Default true. */\n remote?: boolean;\n}\n\nfunction defaultExclude(pathname: string): boolean {\n return pathname.startsWith('/_next') || pathname.startsWith('/api/') || /\\.[a-z0-9]+$/i.test(pathname);\n}\n\n/** `match` is an exact path, or a prefix ending with `*`. */\nexport function matchPath(pattern: string, pathname: string): boolean {\n if (pattern.endsWith('*')) return pathname.startsWith(pattern.slice(0, -1));\n return pattern === pathname || `${pattern}/` === pathname;\n}\n\n/** Targeting context from request headers: Cloudflare / Vercel geo, user agent, language, referrer, cookies. */\nexport function requestContext(headers: Headers, url: string, visitor?: 'new' | 'returning'): TargetingContext {\n const ua = parseUserAgent(headers.get('user-agent'));\n const country = headers.get('cf-ipcountry') ?? headers.get('x-vercel-ip-country') ?? headers.get('x-country') ?? undefined;\n const region = headers.get('x-vercel-ip-country-region') ?? headers.get('cf-region') ?? undefined;\n const city = headers.get('x-vercel-ip-city') ?? headers.get('cf-ipcity') ?? undefined;\n return {\n country: country ?? undefined,\n region: region ? decodeURIComponent(region) : undefined,\n city: city ? decodeURIComponent(city) : undefined,\n device: ua.device,\n browser: ua.browser,\n os: ua.os,\n language: headers.get('accept-language') ?? undefined,\n referrer: headers.get('referer') ?? undefined,\n url,\n cookies: parseCookies(headers.get('cookie')),\n ...(visitor ? { visitor } : {}),\n };\n}\n\nfunction ingestTarget(config: SplitHubConfig, origin: string): { url: string; key?: string } {\n if (config.storage.mode === 'self') return { url: new URL(config.storage.endpoint, origin).toString() };\n return { url: config.storage.endpoint ?? CLOUD_ENDPOINT, key: config.storage.key };\n}\n\n/**\n * Next.js middleware:\n * 1. ensures the `sh_vid` visitor cookie, so SSR and the client agree on variants;\n * 2. forwards the visitor id to Server Components via the `x-splithub-vid` header;\n * 3. serves redirect experiments with an invisible rewrite (URL unchanged, no flash);\n * 4. records the redirect exposure from the edge, deduplicated with a cookie.\n *\n * ```ts\n * // middleware.ts\n * import { splithubMiddleware } from '@splithub/next';\n * import config from './splithub.config';\n * export default splithubMiddleware(config);\n * export const config = { matcher: ['/((?!_next|api|.*\\\\..*).*)'] };\n * ```\n */\nexport function splithubMiddleware(baseConfig: SplitHubConfig, options: MiddlewareOptions = {}) {\n const exclude = options.exclude ?? defaultExclude;\n const trackRedirects = options.trackRedirects ?? true;\n const useRemote = options.remote ?? true;\n\n return async function middleware(request: NextRequest, event?: NextFetchEvent): Promise<NextResponse> {\n const pathname = request.nextUrl.pathname;\n if (exclude(pathname)) return NextResponse.next();\n\n const config = useRemote ? applyRemoteOverrides(baseConfig, await getRemoteOverrides(baseConfig)) : baseConfig;\n\n let visitorId = request.cookies.get(config.visitorKey)?.value ?? null;\n const isNewVisitor = !visitorId;\n if (!visitorId) visitorId = newVisitorId();\n\n const overrides = parseForceParam(request.nextUrl.search);\n const context = requestContext(request.headers, request.nextUrl.href, isNewVisitor ? 'new' : 'returning');\n const requestHeaders = new Headers(request.headers);\n requestHeaders.set(VISITOR_HEADER, visitorId);\n\n let response: NextResponse | null = null;\n const cookiesToSet: Array<{ name: string; value: string }> = [];\n\n for (const experiment of config.experiments) {\n if (experiment.kind !== 'redirect' || !experiment.match || !matchPath(experiment.match, pathname)) continue;\n if (!isActive(config, experiment)) {\n // A redirect test that would have applied here: say why it did not (development only, once).\n explainAssignment(experiment, { experiment: experiment.key, variant: null, reason: 'not_running' });\n continue;\n }\n\n const assignment = assign(config, experiment.key, visitorId, { overrides, context });\n explainAssignment(experiment, assignment);\n const variant = assignment.variant;\n if (!variant?.to) continue;\n\n if (variant.to !== pathname) {\n const url = request.nextUrl.clone();\n url.pathname = variant.to;\n response = NextResponse.rewrite(url, { request: { headers: requestHeaders } });\n }\n\n const exposureCookie = `sh_x_${experiment.key}`;\n // Development never sends to the cloud (the developer is not a visitor); a self-hosted store records it, dev drafts included.\n const cloudDev = config.storage.mode === 'cloud' && isDevEnvironment();\n const record = !cloudDev && (assignment.reason === 'assigned' || (assignment.reason === 'dev' && config.storage.mode === 'self'));\n if (trackRedirects && record && request.cookies.get(exposureCookie)?.value !== variant.key) {\n cookiesToSet.push({ name: exposureCookie, value: variant.key });\n const target = ingestTarget(config, request.nextUrl.origin);\n const batch: EventBatch = {\n project: config.project,\n sdk: `next/${SDK_VERSION}`,\n events: [\n { id: newId('e_'), type: 'exposure', exp: experiment.key, var: variant.key, vid: visitorId, sid: 'edge', ts: Date.now(), url: pathname },\n ],\n };\n const headers: Record<string, string> = { 'content-type': 'application/json' };\n if (target.key) headers.authorization = `Bearer ${target.key}`;\n const send = fetch(target.url, { method: 'POST', headers, body: JSON.stringify(batch) }).catch(() => undefined);\n if (event?.waitUntil) event.waitUntil(send);\n }\n break; // the first matching redirect experiment wins\n }\n\n response ??= NextResponse.next({ request: { headers: requestHeaders } });\n\n if (isNewVisitor) {\n response.cookies.set(config.visitorKey, visitorId, { maxAge: ONE_YEAR, path: '/', sameSite: 'lax' });\n }\n for (const c of cookiesToSet) response.cookies.set(c.name, c.value, { maxAge: ONE_YEAR, path: '/', sameSite: 'lax' });\n return response;\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAAAA,eAAkK;;;ACAlK,kBAAoI;AAUpI,IAAM,OAAO,oBAAI,IAAuB;AAaxC,eAAsB,mBAAmB,QAAwB,UAAyB,CAAC,GAAoC;AAC7H,MAAI,OAAO,QAAQ,SAAS,WAAW,CAAC,OAAO,QAAQ,IAAK,QAAO;AACnE,QAAM,MAAM,QAAQ,SAAS;AAC7B,QAAM,UAAM,iCAAoB,OAAO,QAAQ,YAAY,4BAAgB,OAAO,QAAQ,GAAG;AAC7F,Q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AG,WAAW,QAAQ,GAAG,IAAI,OAAO;AAAA,IAC9C;AAAA,IACA,MAAS,KAAgB;AACvB,YAAM,IAAI,OAAO,GAAG;AACpB,cAAQ,GAAG,WAAW,QAAQ,GAAG,IAAI;AAAA,IACvC;AAAA,EACF;AACF;","names":["import_core","import_core","headers"]}
|
|
1
|
+
{"version":3,"sources":["../src/server.ts","../src/remote.ts","../src/middleware.ts"],"sourcesContent":["import { applyRemoteOverrides, assign, explainAssignment, getExperiment, type Assignment, type RemoteOverrides, type SplitHubConfig, type TargetingContext } from '@splithub/core';\nimport { getRemoteOverrides } from './remote';\nimport { cookies, headers } from 'next/headers';\nimport { requestContext, VISITOR_HEADER } from './middleware';\n\nexport { getRemoteOverrides } from './remote';\n\n/**\n * Visitor id for the current request (header set by the middleware, else the\n * cookie). Null when the middleware is not installed and no cookie exists.\n */\nexport async function getVisitorId(config: SplitHubConfig): Promise<string | null> {\n const h = await headers();\n const fromHeader = h.get(VISITOR_HEADER);\n if (fromHeader) return fromHeader;\n const c = await cookies();\n return c.get(config.visitorKey)?.value ?? null;\n}\n\nexport interface ServerSplitHub {\n visitorId: string | null;\n /** Targeting context built from the request headers (geo, device, language, referrer). */\n context: TargetingContext;\n /** Live overrides applied to this request; pass them to <SplitHubNextProvider remoteOverrides={...}> so hydration agrees. */\n overrides: RemoteOverrides | null;\n /** Config with overrides applied. */\n config: SplitHubConfig;\n assignment(experimentKey: string): Assignment;\n /** Variant key; control when unassigned. No exposure is recorded on the server: render `<Exposure id>` from `@splithub/next/client`. */\n variant(experimentKey: string): string;\n value<T = unknown>(experimentKey: string): T;\n}\n\n/**\n * Assignments inside Server Components and Route Handlers:\n *\n * ```tsx\n * const sh = await getSplitHub(config);\n * const title = sh.value<string>('hero-title');\n * ```\n */\nexport async function getSplitHub(baseConfig: SplitHubConfig): Promise<ServerSplitHub> {\n const [visitorId, fetched] = await Promise.all([getVisitorId(baseConfig), getRemoteOverrides(baseConfig)]);\n const config = applyRemoteOverrides(baseConfig, fetched);\n const h = await headers();\n const context: TargetingContext = requestContext(h, h.get('x-url') ?? h.get('referer') ?? '');\n // The overrides were fetched (and memoized) by this server, so their `ctx` is the server's\n // location, not the visitor's. Hand the browser the visitor's geo from the request headers\n // instead, so the client provider decides geo targeting exactly as this render did.\n const geo = Object.fromEntries(\n (['country', 'region', 'city', 'timezone'] as const).filter((k) => context[k]).map((k) => [k, context[k]])\n ) as NonNullable<RemoteOverrides['ctx']>;\n const overrides: RemoteOverrides | null = fetched ? { ...fetched, ctx: geo } : Object.keys(geo).length ? { version: 0, experiments: {}, ctx: geo } : null;\n const control = (key: string) => getExperiment(config, key)?.variants[0];\n const opts = { context };\n // Assign and, in development, explain a surprising result in the terminal.\n const decide = (key: string) => {\n if (!visitorId) return null;\n const a = assign(config, key, visitorId, opts);\n explainAssignment(getExperiment(config, key), a);\n return a;\n };\n return {\n visitorId,\n context,\n overrides,\n config,\n assignment(key) {\n return decide(key) ?? { experiment: key, variant: null, reason: 'not_running' };\n },\n variant(key) {\n const a = decide(key);\n return (a?.variant ?? control(key))?.key ?? 'control';\n },\n value<T>(key: string): T {\n const a = decide(key);\n return (a?.variant ?? control(key))?.value as T;\n },\n };\n}\n","import { CLOUD_ENDPOINT, fetchRemoteOverrides, resolveOverridesUrl, REMOTE_TTL_MS, type RemoteOverrides, type SplitHubConfig } from '@splithub/core';\n\ninterface MemoEntry {\n at: number;\n value: RemoteOverrides | null;\n pending: Promise<RemoteOverrides | null> | null;\n}\n\n// Module-level memo: edge isolates and Node servers keep it across requests,\n// so at most one fetch per TTL per public key.\nconst memo = new Map<string, MemoEntry>();\n\nexport interface RemoteOptions {\n ttlMs?: number;\n /** Override the fetch implementation (tests). */\n fetchImpl?: typeof fetch;\n}\n\n/**\n * Live overrides for a cloud-mode config, cached in memory for `ttlMs`\n * (default 60s). Returns null in self mode or when the cloud is unreachable\n * (the config file then applies as-is).\n */\nexport async function getRemoteOverrides(config: SplitHubConfig, options: RemoteOptions = {}): Promise<RemoteOverrides | null> {\n if (config.storage.mode !== 'cloud' || !config.storage.key) return null;\n const ttl = options.ttlMs ?? REMOTE_TTL_MS;\n const url = resolveOverridesUrl(config.storage.endpoint ?? CLOUD_ENDPOINT, config.storage.key);\n const entry = memo.get(url);\n const now = Date.now();\n if (entry && now - entry.at < ttl) return entry.value;\n if (entry?.pending) return entry.value ?? entry.pending;\n\n const pending = fetchRemoteOverrides(url, options.fetchImpl).then((value) => {\n memo.set(url, { at: Date.now(), value: value ?? entry?.value ?? null, pending: null });\n return value ?? entry?.value ?? null;\n });\n memo.set(url, { at: entry?.at ?? 0, value: entry?.value ?? null, pending });\n // Serve stale while revalidating; first call waits.\n return entry ? entry.value : pending;\n}\n\n/** Tests only. */\nexport function clearRemoteMemo(): void {\n memo.clear();\n}\n","import {\n applyRemoteOverrides,\n CLOUD_ENDPOINT,\n countsForHoldout,\n decideRedirect,\n explainAssignment,\n HOLDOUT_KEY,\n holdoutGroup,\n isDevEnvironment,\n matchPath,\n newId,\n newVisitorId,\n parseCookies,\n parseForceParam,\n parseUserAgent,\n redirectTarget,\n SDK_VERSION,\n type EventBatch,\n type ExposureEvent,\n type SplitHubConfig,\n type TargetingContext,\n} from '@splithub/core';\nimport { NextResponse, type NextFetchEvent, type NextRequest } from 'next/server';\nimport { getRemoteOverrides } from './remote';\n\nexport const VISITOR_HEADER = 'x-splithub-vid';\nconst ONE_YEAR = 60 * 60 * 24 * 365;\n\nexport interface MiddlewareOptions {\n /** Return true to skip a path entirely. Defaults to `_next`, `api` and files with an extension. */\n exclude?: (pathname: string) => boolean;\n /** Send exposures for redirect experiments from the edge. Default true. */\n trackRedirects?: boolean;\n /** Apply live overrides from the cloud (cloud mode only). Default true. */\n remote?: boolean;\n}\n\nfunction defaultExclude(pathname: string): boolean {\n return pathname.startsWith('/_next') || pathname.startsWith('/api/') || /\\.[a-z0-9]+$/i.test(pathname);\n}\n\n/** Same rule as sh.js and pageview goals (from `@splithub/core`). */\nexport { matchPath };\n\n/**\n * Targeting context from request headers: Cloudflare / Vercel geo, user agent, language,\n * referrer, cookies. `timezone` (for `hour` / `weekday`) comes from Vercel's\n * `x-vercel-ip-timezone` or a `cf-timezone` / `x-timezone` header you set; without one\n * the flow uses UTC.\n */\nexport function requestContext(headers: Headers, url: string, visitor?: 'new' | 'returning'): TargetingContext {\n const ua = parseUserAgent(headers.get('user-agent'));\n const country = headers.get('cf-ipcountry') ?? headers.get('x-vercel-ip-country') ?? headers.get('x-country') ?? undefined;\n const region = headers.get('x-vercel-ip-country-region') ?? headers.get('cf-region') ?? undefined;\n const city = headers.get('x-vercel-ip-city') ?? headers.get('cf-ipcity') ?? undefined;\n const timezone = headers.get('x-vercel-ip-timezone') ?? headers.get('cf-timezone') ?? headers.get('x-timezone') ?? undefined;\n return {\n country: country ?? undefined,\n region: region ? decodeURIComponent(region) : undefined,\n city: city ? decodeURIComponent(city) : undefined,\n device: ua.device,\n browser: ua.browser,\n os: ua.os,\n language: headers.get('accept-language') ?? undefined,\n referrer: headers.get('referer') ?? undefined,\n url,\n cookies: parseCookies(headers.get('cookie')),\n ...(timezone ? { timezone } : {}),\n ...(visitor ? { visitor } : {}),\n };\n}\n\nfunction ingestTarget(config: SplitHubConfig, origin: string): { url: string; key?: string } {\n if (config.storage.mode === 'self') return { url: new URL(config.storage.endpoint, origin).toString() };\n return { url: config.storage.endpoint ?? CLOUD_ENDPOINT, key: config.storage.key };\n}\n\n/**\n * Next.js middleware:\n * 1. ensures the `sh_vid` visitor cookie, so SSR and the client agree on variants;\n * 2. forwards the visitor id to Server Components via the `x-splithub-vid` header;\n * 3. serves redirect experiments with an invisible rewrite (URL unchanged, no flash);\n * 4. records the redirect exposure from the edge, deduplicated with a cookie.\n *\n * ```ts\n * // middleware.ts\n * import { splithubMiddleware } from '@splithub/next';\n * import config from './splithub.config';\n * export default splithubMiddleware(config);\n * export const config = { matcher: ['/((?!_next|api|.*\\\\..*).*)'] };\n * ```\n */\nexport function splithubMiddleware(baseConfig: SplitHubConfig, options: MiddlewareOptions = {}) {\n const exclude = options.exclude ?? defaultExclude;\n const trackRedirects = options.trackRedirects ?? true;\n const useRemote = options.remote ?? true;\n\n return async function middleware(request: NextRequest, event?: NextFetchEvent): Promise<NextResponse> {\n const pathname = request.nextUrl.pathname;\n if (exclude(pathname)) return NextResponse.next();\n\n const config = useRemote ? applyRemoteOverrides(baseConfig, await getRemoteOverrides(baseConfig)) : baseConfig;\n\n let visitorId = request.cookies.get(config.visitorKey)?.value ?? null;\n const isNewVisitor = !visitorId;\n if (!visitorId) visitorId = newVisitorId();\n\n const overrides = parseForceParam(request.nextUrl.search);\n const context = requestContext(request.headers, request.nextUrl.href, isNewVisitor ? 'new' : 'returning');\n const requestHeaders = new Headers(request.headers);\n requestHeaders.set(VISITOR_HEADER, visitorId);\n\n let response: NextResponse | null = null;\n const cookiesToSet: Array<{ name: string; value: string }> = [];\n\n // The same decision as sh.js; in development, say why a matching test did nothing.\n // A visitor who reaches a running redirect test also joins the holdout comparison (same rule as the SDK).\n let reachedTest = false as boolean;\n const decision = decideRedirect(config, pathname, visitorId, context, overrides, (exp, a) => {\n if (countsForHoldout(a)) reachedTest = true;\n explainAssignment(exp, a);\n });\n // Development never sends to the cloud (the developer is not a visitor); a self-hosted store records it, dev drafts included.\n // Bots never reach here with a variant: assign gives them the control without one.\n const cloudDev = config.storage.mode === 'cloud' && isDevEnvironment();\n const events: ExposureEvent[] = [];\n if (decision) {\n if (decision.to) {\n const target = redirectTarget(decision.to, request.nextUrl.href);\n let url: URL = target;\n if (target.origin === request.nextUrl.origin) {\n // Keep Next's own URL (basePath, locale) and change only what the variant says.\n const next = request.nextUrl.clone();\n next.pathname = target.pathname;\n next.search = target.search;\n url = next;\n }\n response = NextResponse.rewrite(url, { request: { headers: requestHeaders } });\n }\n\n const exposureCookie = `sh_x_${decision.experiment}`;\n const record = !cloudDev && (decision.reason === 'assigned' || (decision.reason === 'dev' && config.storage.mode === 'self'));\n if (trackRedirects && record && request.cookies.get(exposureCookie)?.value !== decision.variant) {\n cookiesToSet.push({ name: exposureCookie, value: decision.variant });\n events.push({ id: newId('e_'), type: 'exposure', exp: decision.experiment, var: decision.variant, vid: visitorId, sid: 'edge', ts: Date.now(), url: pathname });\n }\n }\n const group = reachedTest ? holdoutGroup(config, visitorId) : null;\n if (group && trackRedirects && !cloudDev && request.cookies.get(`sh_x_${HOLDOUT_KEY}`)?.value !== group) {\n cookiesToSet.push({ name: `sh_x_${HOLDOUT_KEY}`, value: group });\n events.push({ id: newId('e_'), type: 'exposure', exp: HOLDOUT_KEY, var: group, vid: visitorId, sid: 'edge', ts: Date.now(), url: pathname });\n }\n if (events.length) {\n const target = ingestTarget(config, request.nextUrl.origin);\n const batch: EventBatch = { project: config.project, sdk: `next/${SDK_VERSION}`, events };\n const headers: Record<string, string> = { 'content-type': 'application/json' };\n if (target.key) headers.authorization = `Bearer ${target.key}`;\n // The visitor's user agent, so the ingest's bot filter judges the visitor, not this server.\n // `x-splithub-ua` too, for runtimes that replace a user-agent set on fetch.\n const ua = request.headers.get('user-agent');\n if (ua) {\n headers['user-agent'] = ua;\n headers['x-splithub-ua'] = ua;\n }\n const send = fetch(target.url, { method: 'POST', headers, body: JSON.stringify(batch) }).catch(() => undefined);\n if (event?.waitUntil) event.waitUntil(send);\n }\n\n response ??= NextResponse.next({ request: { headers: requestHeaders } });\n\n if (isNewVisitor) {\n response.cookies.set(config.visitorKey, visitorId, { maxAge: ONE_YEAR, path: '/', sameSite: 'lax' });\n }\n for (const c of cookiesToSet) response.cookies.set(c.name, c.value, { maxAge: ONE_YEAR, path: '/', sameSite: 'lax' });\n return response;\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAAAA,eAAkK;;;ACAlK,kBAAoI;AAUpI,IAAM,OAAO,oBAAI,IAAuB;AAaxC,eAAsB,mBAAmB,QAAwB,UAAyB,CAAC,GAAoC;AAC7H,MAAI,OAAO,QAAQ,SAAS,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AE,SAAS,EAAE,SAAS,GAAG,aAAa,CAAC,GAAG,KAAK,IAAI,IAAI;AACrJ,QAAM,UAAU,CAAC,YAAgB,4BAAc,QAAQ,GAAG,GAAG,SAAS,CAAC;AACvE,QAAM,OAAO,EAAE,QAAQ;AAEvB,QAAM,SAAS,CAAC,QAAgB;AAC9B,QAAI,CAAC,UAAW,QAAO;AACvB,UAAM,QAAI,qBAAO,QAAQ,KAAK,WAAW,IAAI;AAC7C,4CAAkB,4BAAc,QAAQ,GAAG,GAAG,CAAC;AAC/C,WAAO;AAAA,EACT;AACA,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,WAAW,KAAK;AACd,aAAO,OAAO,GAAG,KAAK,EAAE,YAAY,KAAK,SAAS,MAAM,QAAQ,cAAc;AAAA,IAChF;AAAA,IACA,QAAQ,KAAK;AACX,YAAM,IAAI,OAAO,GAAG;AACpB,cAAQ,GAAG,WAAW,QAAQ,GAAG,IAAI,OAAO;AAAA,IAC9C;AAAA,IACA,MAAS,KAAgB;AACvB,YAAM,IAAI,OAAO,GAAG;AACpB,cAAQ,GAAG,WAAW,QAAQ,GAAG,IAAI;AAAA,IACvC;AAAA,EACF;AACF;","names":["import_core","import_core","headers"]}
|
package/dist/server.js
CHANGED
|
@@ -2,7 +2,7 @@ import {
|
|
|
2
2
|
VISITOR_HEADER,
|
|
3
3
|
getRemoteOverrides,
|
|
4
4
|
requestContext
|
|
5
|
-
} from "./chunk-
|
|
5
|
+
} from "./chunk-BH4ACCFH.js";
|
|
6
6
|
|
|
7
7
|
// src/server.ts
|
|
8
8
|
import { applyRemoteOverrides, assign, explainAssignment, getExperiment } from "@splithub/core";
|
|
@@ -15,10 +15,14 @@ async function getVisitorId(config) {
|
|
|
15
15
|
return c.get(config.visitorKey)?.value ?? null;
|
|
16
16
|
}
|
|
17
17
|
async function getSplitHub(baseConfig) {
|
|
18
|
-
const [visitorId,
|
|
19
|
-
const config = applyRemoteOverrides(baseConfig,
|
|
18
|
+
const [visitorId, fetched] = await Promise.all([getVisitorId(baseConfig), getRemoteOverrides(baseConfig)]);
|
|
19
|
+
const config = applyRemoteOverrides(baseConfig, fetched);
|
|
20
20
|
const h = await headers();
|
|
21
|
-
const context =
|
|
21
|
+
const context = requestContext(h, h.get("x-url") ?? h.get("referer") ?? "");
|
|
22
|
+
const geo = Object.fromEntries(
|
|
23
|
+
["country", "region", "city", "timezone"].filter((k) => context[k]).map((k) => [k, context[k]])
|
|
24
|
+
);
|
|
25
|
+
const overrides = fetched ? { ...fetched, ctx: geo } : Object.keys(geo).length ? { version: 0, experiments: {}, ctx: geo } : null;
|
|
22
26
|
const control = (key) => getExperiment(config, key)?.variants[0];
|
|
23
27
|
const opts = { context };
|
|
24
28
|
const decide = (key) => {
|
package/dist/server.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/server.ts"],"sourcesContent":["import { applyRemoteOverrides, assign, explainAssignment, getExperiment, type Assignment, type RemoteOverrides, type SplitHubConfig, type TargetingContext } from '@splithub/core';\nimport { getRemoteOverrides } from './remote';\nimport { cookies, headers } from 'next/headers';\nimport { requestContext, VISITOR_HEADER } from './middleware';\n\nexport { getRemoteOverrides } from './remote';\n\n/**\n * Visitor id for the current request (header set by the middleware, else the\n * cookie). Null when the middleware is not installed and no cookie exists.\n */\nexport async function getVisitorId(config: SplitHubConfig): Promise<string | null> {\n const h = await headers();\n const fromHeader = h.get(VISITOR_HEADER);\n if (fromHeader) return fromHeader;\n const c = await cookies();\n return c.get(config.visitorKey)?.value ?? null;\n}\n\nexport interface ServerSplitHub {\n visitorId: string | null;\n /** Targeting context built from the request headers (geo, device, language, referrer). */\n context: TargetingContext;\n /** Live overrides applied to this request; pass them to <SplitHubNextProvider remoteOverrides={...}> so hydration agrees. */\n overrides: RemoteOverrides | null;\n /** Config with overrides applied. */\n config: SplitHubConfig;\n assignment(experimentKey: string): Assignment;\n /** Variant key; control when unassigned. No exposure is recorded on the server: render `<Exposure id>` from `@splithub/next/client`. */\n variant(experimentKey: string): string;\n value<T = unknown>(experimentKey: string): T;\n}\n\n/**\n * Assignments inside Server Components and Route Handlers:\n *\n * ```tsx\n * const sh = await getSplitHub(config);\n * const title = sh.value<string>('hero-title');\n * ```\n */\nexport async function getSplitHub(baseConfig: SplitHubConfig): Promise<ServerSplitHub> {\n const [visitorId,
|
|
1
|
+
{"version":3,"sources":["../src/server.ts"],"sourcesContent":["import { applyRemoteOverrides, assign, explainAssignment, getExperiment, type Assignment, type RemoteOverrides, type SplitHubConfig, type TargetingContext } from '@splithub/core';\nimport { getRemoteOverrides } from './remote';\nimport { cookies, headers } from 'next/headers';\nimport { requestContext, VISITOR_HEADER } from './middleware';\n\nexport { getRemoteOverrides } from './remote';\n\n/**\n * Visitor id for the current request (header set by the middleware, else the\n * cookie). Null when the middleware is not installed and no cookie exists.\n */\nexport async function getVisitorId(config: SplitHubConfig): Promise<string | null> {\n const h = await headers();\n const fromHeader = h.get(VISITOR_HEADER);\n if (fromHeader) return fromHeader;\n const c = await cookies();\n return c.get(config.visitorKey)?.value ?? null;\n}\n\nexport interface ServerSplitHub {\n visitorId: string | null;\n /** Targeting context built from the request headers (geo, device, language, referrer). */\n context: TargetingContext;\n /** Live overrides applied to this request; pass them to <SplitHubNextProvider remoteOverrides={...}> so hydration agrees. */\n overrides: RemoteOverrides | null;\n /** Config with overrides applied. */\n config: SplitHubConfig;\n assignment(experimentKey: string): Assignment;\n /** Variant key; control when unassigned. No exposure is recorded on the server: render `<Exposure id>` from `@splithub/next/client`. */\n variant(experimentKey: string): string;\n value<T = unknown>(experimentKey: string): T;\n}\n\n/**\n * Assignments inside Server Components and Route Handlers:\n *\n * ```tsx\n * const sh = await getSplitHub(config);\n * const title = sh.value<string>('hero-title');\n * ```\n */\nexport async function getSplitHub(baseConfig: SplitHubConfig): Promise<ServerSplitHub> {\n const [visitorId, fetched] = await Promise.all([getVisitorId(baseConfig), getRemoteOverrides(baseConfig)]);\n const config = applyRemoteOverrides(baseConfig, fetched);\n const h = await headers();\n const context: TargetingContext = requestContext(h, h.get('x-url') ?? h.get('referer') ?? '');\n // The overrides were fetched (and memoized) by this server, so their `ctx` is the server's\n // location, not the visitor's. Hand the browser the visitor's geo from the request headers\n // instead, so the client provider decides geo targeting exactly as this render did.\n const geo = Object.fromEntries(\n (['country', 'region', 'city', 'timezone'] as const).filter((k) => context[k]).map((k) => [k, context[k]])\n ) as NonNullable<RemoteOverrides['ctx']>;\n const overrides: RemoteOverrides | null = fetched ? { ...fetched, ctx: geo } : Object.keys(geo).length ? { version: 0, experiments: {}, ctx: geo } : null;\n const control = (key: string) => getExperiment(config, key)?.variants[0];\n const opts = { context };\n // Assign and, in development, explain a surprising result in the terminal.\n const decide = (key: string) => {\n if (!visitorId) return null;\n const a = assign(config, key, visitorId, opts);\n explainAssignment(getExperiment(config, key), a);\n return a;\n };\n return {\n visitorId,\n context,\n overrides,\n config,\n assignment(key) {\n return decide(key) ?? { experiment: key, variant: null, reason: 'not_running' };\n },\n variant(key) {\n const a = decide(key);\n return (a?.variant ?? control(key))?.key ?? 'control';\n },\n value<T>(key: string): T {\n const a = decide(key);\n return (a?.variant ?? control(key))?.value as T;\n },\n };\n}\n"],"mappings":";;;;;;;AAAA,SAAS,sBAAsB,QAAQ,mBAAmB,qBAAwG;AAElK,SAAS,SAAS,eAAe;AASjC,eAAsB,aAAa,QAAgD;AACjF,QAAM,IAAI,MAAM,QAAQ;AACxB,QAAM,aAAa,EAAE,IAAI,cAAc;AACvC,MAAI,WAAY,QAAO;AACvB,QAAM,IAAI,MAAM,QAAQ;AACxB,SAAO,EAAE,IAAI,OAAO,UAAU,GAAG,SAAS;AAC5C;AAwBA,eAAsB,YAAY,YAAqD;AACrF,QAAM,CAAC,WAAW,OAAO,IAAI,MAAM,QAAQ,IAAI,CAAC,aAAa,UAAU,GAAG,mBAAmB,UAAU,CAAC,CAAC;AACzG,QAAM,SAAS,qBAAqB,YAAY,OAAO;AACvD,QAAM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"0.
|
|
3
|
+
"version": "0.2.0",
|
|
4
4
|
"description": "SplitHub for Next.js: middleware, server components, redirect tests and the route for your own database.",
|
|
5
5
|
"license": "MIT",
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "git+https://github.com/splithub-io/splithub-sdk.git",
|
|
9
|
+
"directory": "packages/next"
|
|
10
|
+
},
|
|
11
|
+
"homepage": "https://splithub.io",
|
|
12
|
+
"bugs": {
|
|
13
|
+
"url": "https://github.com/splithub-io/splithub-sdk/issues"
|
|
14
|
+
},
|
|
6
15
|
"type": "module",
|
|
7
16
|
"main": "./dist/index.cjs",
|
|
8
17
|
"module": "./dist/index.js",
|
|
@@ -34,8 +43,8 @@
|
|
|
34
43
|
"react": ">=18"
|
|
35
44
|
},
|
|
36
45
|
"dependencies": {
|
|
37
|
-
"@splithub/core": "0.
|
|
38
|
-
"@splithub/react": "0.
|
|
46
|
+
"@splithub/core": "0.2.0",
|
|
47
|
+
"@splithub/react": "0.2.0"
|
|
39
48
|
},
|
|
40
49
|
"devDependencies": {
|
|
41
50
|
"@types/react": "^18.3.12",
|
|
@@ -50,7 +59,6 @@
|
|
|
50
59
|
"publishConfig": {
|
|
51
60
|
"access": "public"
|
|
52
61
|
},
|
|
53
|
-
"homepage": "https://splithub.io",
|
|
54
62
|
"scripts": {
|
|
55
63
|
"build": "rimraf dist && tsup",
|
|
56
64
|
"test": "vitest run",
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/remote.ts","../src/middleware.ts"],"sourcesContent":["import { CLOUD_ENDPOINT, fetchRemoteOverrides, resolveOverridesUrl, REMOTE_TTL_MS, type RemoteOverrides, type SplitHubConfig } from '@splithub/core';\n\ninterface MemoEntry {\n at: number;\n value: RemoteOverrides | null;\n pending: Promise<RemoteOverrides | null> | null;\n}\n\n// Module-level memo: edge isolates and Node servers keep it across requests,\n// so at most one fetch per TTL per public key.\nconst memo = new Map<string, MemoEntry>();\n\nexport interface RemoteOptions {\n ttlMs?: number;\n /** Override the fetch implementation (tests). */\n fetchImpl?: typeof fetch;\n}\n\n/**\n * Live overrides for a cloud-mode config, cached in memory for `ttlMs`\n * (default 60s). Returns null in self mode or when the cloud is unreachable\n * (the config file then applies as-is).\n */\nexport async function getRemoteOverrides(config: SplitHubConfig, options: RemoteOptions = {}): Promise<RemoteOverrides | null> {\n if (config.storage.mode !== 'cloud' || !config.storage.key) return null;\n const ttl = options.ttlMs ?? REMOTE_TTL_MS;\n const url = resolveOverridesUrl(config.storage.endpoint ?? CLOUD_ENDPOINT, config.storage.key);\n const entry = memo.get(url);\n const now = Date.now();\n if (entry && now - entry.at < ttl) return entry.value;\n if (entry?.pending) return entry.value ?? entry.pending;\n\n const pending = fetchRemoteOverrides(url, options.fetchImpl).then((value) => {\n memo.set(url, { at: Date.now(), value: value ?? entry?.value ?? null, pending: null });\n return value ?? entry?.value ?? null;\n });\n memo.set(url, { at: entry?.at ?? 0, value: entry?.value ?? null, pending });\n // Serve stale while revalidating; first call waits.\n return entry ? entry.value : pending;\n}\n\n/** Tests only. */\nexport function clearRemoteMemo(): void {\n memo.clear();\n}\n","import {\n applyRemoteOverrides,\n assign,\n CLOUD_ENDPOINT,\n explainAssignment,\n isActive,\n isDevEnvironment,\n newId,\n newVisitorId,\n parseCookies,\n parseForceParam,\n parseUserAgent,\n SDK_VERSION,\n type EventBatch,\n type SplitHubConfig,\n type TargetingContext,\n} from '@splithub/core';\nimport { NextResponse, type NextFetchEvent, type NextRequest } from 'next/server';\nimport { getRemoteOverrides } from './remote';\n\nexport const VISITOR_HEADER = 'x-splithub-vid';\nconst ONE_YEAR = 60 * 60 * 24 * 365;\n\nexport interface MiddlewareOptions {\n /** Return true to skip a path entirely. Defaults to `_next`, `api` and files with an extension. */\n exclude?: (pathname: string) => boolean;\n /** Send exposures for redirect experiments from the edge. Default true. */\n trackRedirects?: boolean;\n /** Apply live overrides from the cloud (cloud mode only). Default true. */\n remote?: boolean;\n}\n\nfunction defaultExclude(pathname: string): boolean {\n return pathname.startsWith('/_next') || pathname.startsWith('/api/') || /\\.[a-z0-9]+$/i.test(pathname);\n}\n\n/** `match` is an exact path, or a prefix ending with `*`. */\nexport function matchPath(pattern: string, pathname: string): boolean {\n if (pattern.endsWith('*')) return pathname.startsWith(pattern.slice(0, -1));\n return pattern === pathname || `${pattern}/` === pathname;\n}\n\n/** Targeting context from request headers: Cloudflare / Vercel geo, user agent, language, referrer, cookies. */\nexport function requestContext(headers: Headers, url: string, visitor?: 'new' | 'returning'): TargetingContext {\n const ua = parseUserAgent(headers.get('user-agent'));\n const country = headers.get('cf-ipcountry') ?? headers.get('x-vercel-ip-country') ?? headers.get('x-country') ?? undefined;\n const region = headers.get('x-vercel-ip-country-region') ?? headers.get('cf-region') ?? undefined;\n const city = headers.get('x-vercel-ip-city') ?? headers.get('cf-ipcity') ?? undefined;\n return {\n country: country ?? undefined,\n region: region ? decodeURIComponent(region) : undefined,\n city: city ? decodeURIComponent(city) : undefined,\n device: ua.device,\n browser: ua.browser,\n os: ua.os,\n language: headers.get('accept-language') ?? undefined,\n referrer: headers.get('referer') ?? undefined,\n url,\n cookies: parseCookies(headers.get('cookie')),\n ...(visitor ? { visitor } : {}),\n };\n}\n\nfunction ingestTarget(config: SplitHubConfig, origin: string): { url: string; key?: string } {\n if (config.storage.mode === 'self') return { url: new URL(config.storage.endpoint, origin).toString() };\n return { url: config.storage.endpoint ?? CLOUD_ENDPOINT, key: config.storage.key };\n}\n\n/**\n * Next.js middleware:\n * 1. ensures the `sh_vid` visitor cookie, so SSR and the client agree on variants;\n * 2. forwards the visitor id to Server Components via the `x-splithub-vid` header;\n * 3. serves redirect experiments with an invisible rewrite (URL unchanged, no flash);\n * 4. records the redirect exposure from the edge, deduplicated with a cookie.\n *\n * ```ts\n * // middleware.ts\n * import { splithubMiddleware } from '@splithub/next';\n * import config from './splithub.config';\n * export default splithubMiddleware(config);\n * export const config = { matcher: ['/((?!_next|api|.*\\\\..*).*)'] };\n * ```\n */\nexport function splithubMiddleware(baseConfig: SplitHubConfig, options: MiddlewareOptions = {}) {\n const exclude = options.exclude ?? defaultExclude;\n const trackRedirects = options.trackRedirects ?? true;\n const useRemote = options.remote ?? true;\n\n return async function middleware(request: NextRequest, event?: NextFetchEvent): Promise<NextResponse> {\n const pathname = request.nextUrl.pathname;\n if (exclude(pathname)) return NextResponse.next();\n\n const config = useRemote ? applyRemoteOverrides(baseConfig, await getRemoteOverrides(baseConfig)) : baseConfig;\n\n let visitorId = request.cookies.get(config.visitorKey)?.value ?? null;\n const isNewVisitor = !visitorId;\n if (!visitorId) visitorId = newVisitorId();\n\n const overrides = parseForceParam(request.nextUrl.search);\n const context = requestContext(request.headers, request.nextUrl.href, isNewVisitor ? 'new' : 'returning');\n const requestHeaders = new Headers(request.headers);\n requestHeaders.set(VISITOR_HEADER, visitorId);\n\n let response: NextResponse | null = null;\n const cookiesToSet: Array<{ name: string; value: string }> = [];\n\n for (const experiment of config.experiments) {\n if (experiment.kind !== 'redirect' || !experiment.match || !matchPath(experiment.match, pathname)) continue;\n if (!isActive(config, experiment)) {\n // A redirect test that would have applied here: say why it did not (development only, once).\n explainAssignment(experiment, { experiment: experiment.key, variant: null, reason: 'not_running' });\n continue;\n }\n\n const assignment = assign(config, experiment.key, visitorId, { overrides, context });\n explainAssignment(experiment, assignment);\n const variant = assignment.variant;\n if (!variant?.to) continue;\n\n if (variant.to !== pathname) {\n const url = request.nextUrl.clone();\n url.pathname = variant.to;\n response = NextResponse.rewrite(url, { request: { headers: requestHeaders } });\n }\n\n const exposureCookie = `sh_x_${experiment.key}`;\n // Development never sends to the cloud (the developer is not a visitor); a self-hosted store records it, dev drafts included.\n const cloudDev = config.storage.mode === 'cloud' && isDevEnvironment();\n const record = !cloudDev && (assignment.reason === 'assigned' || (assignment.reason === 'dev' && config.storage.mode === 'self'));\n if (trackRedirects && record && request.cookies.get(exposureCookie)?.value !== variant.key) {\n cookiesToSet.push({ name: exposureCookie, value: variant.key });\n const target = ingestTarget(config, request.nextUrl.origin);\n const batch: EventBatch = {\n project: config.project,\n sdk: `next/${SDK_VERSION}`,\n events: [\n { id: newId('e_'), type: 'exposure', exp: experiment.key, var: variant.key, vid: visitorId, sid: 'edge', ts: Date.now(), url: pathname },\n ],\n };\n const headers: Record<string, string> = { 'content-type': 'application/json' };\n if (target.key) headers.authorization = `Bearer ${target.key}`;\n const send = fetch(target.url, { method: 'POST', headers, body: JSON.stringify(batch) }).catch(() => undefined);\n if (event?.waitUntil) event.waitUntil(send);\n }\n break; // the first matching redirect experiment wins\n }\n\n response ??= NextResponse.next({ request: { headers: requestHeaders } });\n\n if (isNewVisitor) {\n response.cookies.set(config.visitorKey, visitorId, { maxAge: ONE_YEAR, path: '/', sameSite: 'lax' });\n }\n for (const c of cookiesToSet) response.cookies.set(c.name, c.value, { maxAge: ONE_YEAR, path: '/', sameSite: 'lax' });\n return response;\n };\n}\n"],"mappings":";AAAA,SAAS,gBAAgB,sBAAsB,qBAAqB,qBAAgE;AAUpI,IAAM,OAAO,oBAAI,IAAuB;AAaxC,eAAsB,mBAAmB,QAAwB,UAAyB,CAAC,GAAoC;AAC7H,MAAI,OAAO,QAAQ,SAAS,WAAW,CAAC,OAAO,QAAQ,IAAK,QAAO;AACnE,QAAM,MAAM,QAAQ,SAAS;AAC7B,QAAM,MAAM,oBAAoB,OAAO,QAAQ,YAAY,gBAAgB,OAAO,QAAQ,GAAG;AAC7F,QAAM,QAAQ,KAAK,IAAI,GAAG;AAC1B,QAAM,MAAM,KAAK,IAAI;AACrB,MAAI,SAAS,MAAM,MAAM,KAAK,IAAK,QAAO,MAAM;AAChD,MAAI,OAAO,QAAS,QAAO,MAAM,SAAS,MAAM;AAEhD,QAAM,UAAU,qBAAqB,KAAK,QAAQ,SAAS,EAAE,KAAK,CAAC,UAAU;AAC3E,SAAK,IAAI,KAAK,EAAE,IAAI,KAAK,IAAI,GAAG,OAAO,SAAS,OAAO,SAAS,MAAM,SAAS,KAAK,CAAC;AACrF,W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