@splithub/next 0.1.2 → 0.1.3

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.
@@ -25,6 +25,7 @@ import {
25
25
  applyRemoteOverrides,
26
26
  assign,
27
27
  CLOUD_ENDPOINT as CLOUD_ENDPOINT2,
28
+ isActive,
28
29
  newId,
29
30
  newVisitorId,
30
31
  parseCookies,
@@ -83,7 +84,7 @@ function splithubMiddleware(baseConfig, options = {}) {
83
84
  let response = null;
84
85
  const cookiesToSet = [];
85
86
  for (const experiment of config.experiments) {
86
- if (experiment.kind !== "redirect" || experiment.status !== "running" || !experiment.match) continue;
87
+ if (experiment.kind !== "redirect" || !isActive(config, experiment) || !experiment.match) continue;
87
88
  if (!matchPath(experiment.match, pathname)) continue;
88
89
  const assignment = assign(config, experiment.key, visitorId, { overrides, context });
89
90
  const variant = assignment.variant;
@@ -94,7 +95,7 @@ function splithubMiddleware(baseConfig, options = {}) {
94
95
  response = NextResponse.rewrite(url, { request: { headers: requestHeaders } });
95
96
  }
96
97
  const exposureCookie = `sh_x_${experiment.key}`;
97
- if (trackRedirects && assignment.reason === "assigned" && request.cookies.get(exposureCookie)?.value !== variant.key) {
98
+ if (trackRedirects && (assignment.reason === "assigned" || assignment.reason === "dev") && request.cookies.get(exposureCookie)?.value !== variant.key) {
98
99
  cookiesToSet.push({ name: exposureCookie, value: variant.key });
99
100
  const target = ingestTarget(config, request.nextUrl.origin);
100
101
  const batch = {
@@ -128,4 +129,4 @@ export {
128
129
  requestContext,
129
130
  splithubMiddleware
130
131
  };
131
- //# sourceMappingURL=chunk-LD54CWVU.js.map
132
+ //# sourceMappingURL=chunk-62O4MG2L.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 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 if (trackRedirects && (assignment.reason === 'assigned' || assignment.reason === 'dev') && 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,WAAO,SAAS,OAAO,SAAS;AAAA,EAClC,CAAC;AACD,OAAK,IAAI,KAAK,EAAE,IAAI,OAAO,MAAM,GAAG,O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AEvE,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,7 +106,7 @@ 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" || experiment.status !== "running" || !experiment.match) continue;
109
+ if (experiment.kind !== "redirect" || !(0, import_core2.isActive)(config, experiment) || !experiment.match) continue;
110
110
  if (!matchPath(experiment.match, pathname)) continue;
111
111
  const assignment = (0, import_core2.assign)(config, experiment.key, visitorId, { overrides, context });
112
112
  const variant = assignment.variant;
@@ -117,7 +117,7 @@ function splithubMiddleware(baseConfig, options = {}) {
117
117
  response = import_server.NextResponse.rewrite(url, { request: { headers: requestHeaders } });
118
118
  }
119
119
  const exposureCookie = `sh_x_${experiment.key}`;
120
- if (trackRedirects && assignment.reason === "assigned" && request.cookies.get(exposureCookie)?.value !== variant.key) {
120
+ if (trackRedirects && (assignment.reason === "assigned" || assignment.reason === "dev") && request.cookies.get(exposureCookie)?.value !== variant.key) {
121
121
  cookiesToSet.push({ name: exposureCookie, value: variant.key });
122
122
  const target = ingestTarget(config, request.nextUrl.origin);
123
123
  const batch = {
@@ -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 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.status !== 'running' || !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 if (trackRedirects && assignment.reason === 'assigned' && 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,eAaO;AACP,oBAAoE;;;ACdpE,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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S,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;;;AD7IA,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 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 if (trackRedirects && (assignment.reason === 'assigned' || assignment.reason === 'dev') && 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;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1D,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;;;AD9IA,IAAAC,eAA6B;","names":["import_core","import_core"]}
package/dist/index.js CHANGED
@@ -4,7 +4,7 @@ import {
4
4
  getRemoteOverrides,
5
5
  matchPath,
6
6
  splithubMiddleware
7
- } from "./chunk-LD54CWVU.js";
7
+ } from "./chunk-62O4MG2L.js";
8
8
 
9
9
  // src/index.ts
10
10
  import { defineConfig } from "@splithub/core";
@@ -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 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.status !== 'running' || !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 if (trackRedirects && assignment.reason === 'assigned' && 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,eAA+I;;;ACA/I,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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Aa,QAAgD;AACjF,QAAM,IAAI,UAAM,wBAAQ;AACxB,QAAM,aAAa,EAAE,IAAI,cAAc;AACvC,MAAI,WAAY,QAAO;AACvB,QAAM,IAAI,UAAM,wBAAQ;AACxB,SAAO,EAAE,IAAI,OAAO,UAAU,GAAG,SAAS;AAC5C;AAwBA,eAAsB,YAAY,YAAqD;AACrF,QAAM,CAAC,WAAW,SAAS,IAAI,MAAM,QAAQ,IAAI,CAAC,aAAa,UAAU,GAAG,mBAAmB,UAAU,CAAC,CAAC;AAC3G,QAAM,aAAS,mCAAqB,YAAY,SAAS;AACzD,QAAM,IAAI,UAAM,wBAAQ;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;AACvB,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;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, 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 if (trackRedirects && (assignment.reason === 'assigned' || assignment.reason === 'dev') && 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,eAA+I;;;ACA/I,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,MAA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2
  VISITOR_HEADER,
3
3
  getRemoteOverrides,
4
4
  requestContext
5
- } from "./chunk-LD54CWVU.js";
5
+ } from "./chunk-62O4MG2L.js";
6
6
 
7
7
  // src/server.ts
8
8
  import { applyRemoteOverrides, assign, getExperiment } from "@splithub/core";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@splithub/next",
3
- "version": "0.1.2",
3
+ "version": "0.1.3",
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/react": "0.1.2",
38
- "@splithub/core": "0.1.2"
37
+ "@splithub/core": "0.1.3",
38
+ "@splithub/react": "0.1.3"
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 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.status !== 'running' || !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 if (trackRedirects && assignment.reason === 'assigned' && 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;AAUp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