@splithub/next 0.1.5 → 0.1.7
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-TVPWOCU6.js → chunk-FVZZV6MK.js} +8 -3
- package/dist/chunk-FVZZV6MK.js.map +1 -0
- package/dist/index.cjs +6 -2
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +1 -1
- package/dist/server.cjs +9 -3
- package/dist/server.cjs.map +1 -1
- package/dist/server.js +11 -5
- package/dist/server.js.map +1 -1
- package/package.json +3 -3
- package/dist/chunk-TVPWOCU6.js.map +0 -1
|
@@ -25,6 +25,7 @@ import {
|
|
|
25
25
|
applyRemoteOverrides,
|
|
26
26
|
assign,
|
|
27
27
|
CLOUD_ENDPOINT as CLOUD_ENDPOINT2,
|
|
28
|
+
explainAssignment,
|
|
28
29
|
isActive,
|
|
29
30
|
newId,
|
|
30
31
|
newVisitorId,
|
|
@@ -84,9 +85,13 @@ function splithubMiddleware(baseConfig, options = {}) {
|
|
|
84
85
|
let response = null;
|
|
85
86
|
const cookiesToSet = [];
|
|
86
87
|
for (const experiment of config.experiments) {
|
|
87
|
-
if (experiment.kind !== "redirect" || !
|
|
88
|
-
if (!
|
|
88
|
+
if (experiment.kind !== "redirect" || !experiment.match || !matchPath(experiment.match, pathname)) continue;
|
|
89
|
+
if (!isActive(config, experiment)) {
|
|
90
|
+
explainAssignment(experiment, { experiment: experiment.key, variant: null, reason: "not_running" });
|
|
91
|
+
continue;
|
|
92
|
+
}
|
|
89
93
|
const assignment = assign(config, experiment.key, visitorId, { overrides, context });
|
|
94
|
+
explainAssignment(experiment, assignment);
|
|
90
95
|
const variant = assignment.variant;
|
|
91
96
|
if (!variant?.to) continue;
|
|
92
97
|
if (variant.to !== pathname) {
|
|
@@ -130,4 +135,4 @@ export {
|
|
|
130
135
|
requestContext,
|
|
131
136
|
splithubMiddleware
|
|
132
137
|
};
|
|
133
|
-
//# sourceMappingURL=chunk-
|
|
138
|
+
//# sourceMappingURL=chunk-FVZZV6MK.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 assign,\n CLOUD_ENDPOINT,\n explainAssignment,\n isActive,\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 // A draft shown in development is recorded only by a self-hosted store; the cloud would drop it.\n const record = 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;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UAChB,KAAK,QAAQ,WAAW;AAAA,UACxB,QAAQ;AAAA,YACN,EAAE,IAAI,MAAM,IAAI,GAAG,MAAM,YAAY,KAAK,WAAW,KAAK,KAAK,QAAQ,KAAK,KAAK,WAAW,KAAK,QAAQ,IAAI,KAAK,IAAI,GAAG,KAAK,SAAS;AAAA,UACzI;AAAA,QACF;AACA,cAAM,UAAkC,EAAE,gBAAgB,mBAAmB;AAC7E,YAAI,OAAO,IAAK,SAAQ,gBAAgB,UAAU,OAAO,GAAG;AAC5D,cAAM,OAAO,MAAM,OAAO,KAAK,EAAE,QAAQ,QAAQ,SAAS,MAAM,KAAK,UAAU,KAAK,EAAE,CAAC,EAAE,MAAM,MAAM,MAAS;AAC9G,YAAI,OAAO,UAAW,OAAM,UAAU,IAAI;AAAA,MAC5C;AACA;AAAA,IACF;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
|
@@ -106,9 +106,13 @@ function splithubMiddleware(baseConfig, options = {}) {
|
|
|
106
106
|
let response = null;
|
|
107
107
|
const cookiesToSet = [];
|
|
108
108
|
for (const experiment of config.experiments) {
|
|
109
|
-
if (experiment.kind !== "redirect" || !
|
|
110
|
-
if (!
|
|
109
|
+
if (experiment.kind !== "redirect" || !experiment.match || !matchPath(experiment.match, pathname)) continue;
|
|
110
|
+
if (!(0, import_core2.isActive)(config, experiment)) {
|
|
111
|
+
(0, import_core2.explainAssignment)(experiment, { experiment: experiment.key, variant: null, reason: "not_running" });
|
|
112
|
+
continue;
|
|
113
|
+
}
|
|
111
114
|
const assignment = (0, import_core2.assign)(config, experiment.key, visitorId, { overrides, context });
|
|
115
|
+
(0, import_core2.explainAssignment)(experiment, assignment);
|
|
112
116
|
const variant = assignment.variant;
|
|
113
117
|
if (!variant?.to) continue;
|
|
114
118
|
if (variant.to !== pathname) {
|
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 isActive,\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' || !isActive(config, experiment) || !experiment.match) continue;\n if (!matchPath(experiment.match, pathname)) continue;\n\n const assignment = assign(config, experiment.key, visitorId, { overrides, context });\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 // A draft shown in development is recorded only by a self-hosted store; the cloud would drop it.\n const record = 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;AA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AI,CAAC;AAC9D,cAAM,SAAS,aAAa,QAAQ,QAAQ,QAAQ,MAAM;AAC1D,cAAM,QAAoB;AAAA,UACxB,SAAS,OAAO;AAAA,UAChB,KAAK,QAAQ,wBAAW;AAAA,UACxB,QAAQ;AAAA,YACN,EAAE,QAAI,oBAAM,IAAI,GAAG,MAAM,YAAY,KAAK,WAAW,KAAK,KAAK,QAAQ,KAAK,KAAK,WAAW,KAAK,QAAQ,IAAI,KAAK,IAAI,GAAG,KAAK,SAAS;AAAA,UACzI;AAAA,QACF;AACA,cAAM,UAAkC,EAAE,gBAAgB,mBAAmB;AAC7E,YAAI,OAAO,IAAK,SAAQ,gBAAgB,UAAU,OAAO,GAAG;AAC5D,cAAM,OAAO,MAAM,OAAO,KAAK,EAAE,QAAQ,QAAQ,SAAS,MAAM,KAAK,UAAU,KAAK,EAAE,CAAC,EAAE,MAAM,MAAM,MAAS;AAC9G,YAAI,OAAO,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;;;ADhJA,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 assign,\n CLOUD_ENDPOINT,\n explainAssignment,\n isActive,\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 // A draft shown in development is recorded only by a self-hosted store; the cloud would drop it.\n const record = 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,eAeO;AACP,oBAAoE;;;AChBpE,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,MA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AAK,IAAI,GAAG,KAAK,SAAS;AAAA,UACzI;AAAA,QACF;AACA,cAAM,UAAkC,EAAE,gBAAgB,mBAAmB;AAC7E,YAAI,OAAO,IAAK,SAAQ,gBAAgB,UAAU,OAAO,GAAG;AAC5D,cAAM,OAAO,MAAM,OAAO,KAAK,EAAE,QAAQ,QAAQ,SAAS,MAAM,KAAK,UAAU,KAAK,EAAE,CAAC,EAAE,MAAM,MAAM,MAAS;AAC9G,YAAI,OAAO,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;;;ADtJA,IAAAC,eAA6B;","names":["import_core","import_core"]}
|
package/dist/index.js
CHANGED
package/dist/server.cjs
CHANGED
|
@@ -89,20 +89,26 @@ async function getSplitHub(baseConfig) {
|
|
|
89
89
|
const context = { ...requestContext(h, h.get("x-url") ?? h.get("referer") ?? ""), ...overrides?.ctx ?? {} };
|
|
90
90
|
const control = (key) => (0, import_core3.getExperiment)(config, key)?.variants[0];
|
|
91
91
|
const opts = { context };
|
|
92
|
+
const decide = (key) => {
|
|
93
|
+
if (!visitorId) return null;
|
|
94
|
+
const a = (0, import_core3.assign)(config, key, visitorId, opts);
|
|
95
|
+
(0, import_core3.explainAssignment)((0, import_core3.getExperiment)(config, key), a);
|
|
96
|
+
return a;
|
|
97
|
+
};
|
|
92
98
|
return {
|
|
93
99
|
visitorId,
|
|
94
100
|
context,
|
|
95
101
|
overrides,
|
|
96
102
|
config,
|
|
97
103
|
assignment(key) {
|
|
98
|
-
return
|
|
104
|
+
return decide(key) ?? { experiment: key, variant: null, reason: "not_running" };
|
|
99
105
|
},
|
|
100
106
|
variant(key) {
|
|
101
|
-
const a =
|
|
107
|
+
const a = decide(key);
|
|
102
108
|
return (a?.variant ?? control(key))?.key ?? "control";
|
|
103
109
|
},
|
|
104
110
|
value(key) {
|
|
105
|
-
const a =
|
|
111
|
+
const a = decide(key);
|
|
106
112
|
return (a?.variant ?? control(key))?.value;
|
|
107
113
|
}
|
|
108
114
|
};
|
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, 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 return {\n visitorId,\n context,\n overrides,\n config,\n assignment(key) {\n return visitorId ? assign(config, key, visitorId, opts) : { experiment: key, variant: null, reason: 'not_running' };\n },\n variant(key) {\n const a = visitorId ? assign(config, key, visitorId, opts) : null;\n return (a?.variant ?? control(key))?.key ?? 'control';\n },\n value<T>(key: string): T {\n const a = visitorId ? assign(config, key, visitorId, opts) : null;\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 isActive,\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' || !isActive(config, experiment) || !experiment.match) continue;\n if (!matchPath(experiment.match, pathname)) continue;\n\n const assignment = assign(config, experiment.key, visitorId, { overrides, context });\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 // A draft shown in development is recorded only by a self-hosted store; the cloud would drop it.\n const record = 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"],"m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ACA;AAAA,IACA;AAAA,IACA,WAAW,KAAK;AACd,aAAO,gBAAY,qBAAO,QAAQ,KAAK,WAAW,IAAI,IAAI,EAAE,YAAY,KAAK,SAAS,MAAM,QAAQ,cAAc;AAAA,IACpH;AAAA,IACA,QAAQ,KAAK;AACX,YAAM,IAAI,gBAAY,qBAAO,QAAQ,KAAK,WAAW,IAAI,IAAI;AAC7D,cAAQ,GAAG,WAAW,QAAQ,GAAG,IAAI,OAAO;AAAA,IAC9C;AAAA,IACA,MAAS,KAAgB;AACvB,YAAM,IAAI,gBAAY,qBAAO,QAAQ,KAAK,WAAW,IAAI,IAAI;AAC7D,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, 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 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 // A draft shown in development is recorded only by a self-hosted store; the cloud would drop it.\n const record = 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,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,IAAI,KAAK,EAAE,IAAI,OAAO,MAAM,GAAG,OAAO,OAAO,SAAS,MAAM,QAAQ,CAAC;AAE1E,SAAO,QAAQ,MAAM,QAAQ;AAC/B;;;ADrCA,qBAAiC;;;AEFjC,IAAAC,eAeO;AACP,oBAAoE;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BAAQ;AACxB,QAAM,UAA4B,EAAE,GAAG,eAAe,GAAG,EAAE,IAAI,OAAO,KAAK,EAAE,IAAI,SAAS,KAAK,EAAE,GAAG,GAAI,WAAW,OAAO,CAAC,EAAG;AAC9H,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,10 +2,10 @@ import {
|
|
|
2
2
|
VISITOR_HEADER,
|
|
3
3
|
getRemoteOverrides,
|
|
4
4
|
requestContext
|
|
5
|
-
} from "./chunk-
|
|
5
|
+
} from "./chunk-FVZZV6MK.js";
|
|
6
6
|
|
|
7
7
|
// src/server.ts
|
|
8
|
-
import { applyRemoteOverrides, assign, getExperiment } from "@splithub/core";
|
|
8
|
+
import { applyRemoteOverrides, assign, explainAssignment, getExperiment } from "@splithub/core";
|
|
9
9
|
import { cookies, headers } from "next/headers";
|
|
10
10
|
async function getVisitorId(config) {
|
|
11
11
|
const h = await headers();
|
|
@@ -21,20 +21,26 @@ async function getSplitHub(baseConfig) {
|
|
|
21
21
|
const context = { ...requestContext(h, h.get("x-url") ?? h.get("referer") ?? ""), ...overrides?.ctx ?? {} };
|
|
22
22
|
const control = (key) => getExperiment(config, key)?.variants[0];
|
|
23
23
|
const opts = { context };
|
|
24
|
+
const decide = (key) => {
|
|
25
|
+
if (!visitorId) return null;
|
|
26
|
+
const a = assign(config, key, visitorId, opts);
|
|
27
|
+
explainAssignment(getExperiment(config, key), a);
|
|
28
|
+
return a;
|
|
29
|
+
};
|
|
24
30
|
return {
|
|
25
31
|
visitorId,
|
|
26
32
|
context,
|
|
27
33
|
overrides,
|
|
28
34
|
config,
|
|
29
35
|
assignment(key) {
|
|
30
|
-
return
|
|
36
|
+
return decide(key) ?? { experiment: key, variant: null, reason: "not_running" };
|
|
31
37
|
},
|
|
32
38
|
variant(key) {
|
|
33
|
-
const a =
|
|
39
|
+
const a = decide(key);
|
|
34
40
|
return (a?.variant ?? control(key))?.key ?? "control";
|
|
35
41
|
},
|
|
36
42
|
value(key) {
|
|
37
|
-
const a =
|
|
43
|
+
const a = decide(key);
|
|
38
44
|
return (a?.variant ?? control(key))?.value;
|
|
39
45
|
}
|
|
40
46
|
};
|
package/dist/server.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/server.ts"],"sourcesContent":["import { applyRemoteOverrides, assign, 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 return {\n visitorId,\n context,\n overrides,\n config,\n assignment(key) {\n return
|
|
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, 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"],"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,WA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.1.
|
|
3
|
+
"version": "0.1.7",
|
|
4
4
|
"description": "SplitHub for Next.js: middleware, server components, redirect tests and the route for your own database.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
@@ -34,8 +34,8 @@
|
|
|
34
34
|
"react": ">=18"
|
|
35
35
|
},
|
|
36
36
|
"dependencies": {
|
|
37
|
-
"@splithub/core": "0.1.
|
|
38
|
-
"@splithub/react": "0.1.
|
|
37
|
+
"@splithub/core": "0.1.7",
|
|
38
|
+
"@splithub/react": "0.1.7"
|
|
39
39
|
},
|
|
40
40
|
"devDependencies": {
|
|
41
41
|
"@types/react": "^18.3.12",
|
|
@@ -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 isActive,\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' || !isActive(config, experiment) || !experiment.match) continue;\n if (!matchPath(experiment.match, pathname)) continue;\n\n const assignment = assign(config, experiment.key, visitorId, { overrides, context });\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 // A draft shown in development is recorded only by a self-hosted store; the cloud would drop it.\n const record = 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,mBA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