@sentientui/core 0.35.0 → 0.36.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +51 -12
- package/dist/chunk-735EJYJX.mjs +2 -0
- package/dist/chunk-735EJYJX.mjs.map +1 -0
- package/dist/chunk-DU3AXQHR.mjs +2 -0
- package/dist/chunk-DU3AXQHR.mjs.map +1 -0
- package/dist/chunk-GVKKOUWE.mjs +2 -0
- package/dist/chunk-GVKKOUWE.mjs.map +1 -0
- package/dist/chunk-J5EL7HKC.mjs +2 -0
- package/dist/chunk-J5EL7HKC.mjs.map +1 -0
- package/dist/{index-Dg2gkw_l.d.cts → index-BYOMZ3t-.d.cts} +37 -2
- package/dist/{index-DjbSOAEF.d.ts → index-DEwRTvxc.d.ts} +37 -2
- package/dist/index-consent.d.cts +74 -13
- package/dist/index-consent.d.ts +74 -13
- package/dist/index-consent.js +1 -1
- package/dist/index-consent.js.map +1 -1
- package/dist/index-consent.mjs +1 -1
- package/dist/index-consent.mjs.map +1 -1
- package/dist/index-engagement.js +1 -1
- package/dist/index-engagement.js.map +1 -1
- package/dist/index-engagement.mjs +1 -1
- package/dist/index-engagement.mjs.map +1 -1
- package/dist/index-graph.d.cts +2 -2
- package/dist/index-graph.d.ts +2 -2
- package/dist/index-graph.js +1 -1
- package/dist/index-graph.js.map +1 -1
- package/dist/index-graph.mjs +1 -1
- package/dist/index-graph.mjs.map +1 -1
- package/dist/index-local.d.cts +1 -1
- package/dist/index-local.d.ts +1 -1
- package/dist/index-server.d.cts +10 -0
- package/dist/index-server.d.ts +10 -0
- package/dist/index-server.js +1 -1
- package/dist/index-server.js.map +1 -1
- package/dist/index-server.mjs +1 -1
- package/dist/index-server.mjs.map +1 -1
- package/dist/index.d.cts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1 -1
- package/llms.txt +2 -2
- package/package.json +5 -2
- package/dist/chunk-2NVSFI4V.mjs +0 -2
- package/dist/chunk-2NVSFI4V.mjs.map +0 -1
- package/dist/chunk-EUD4PUKP.mjs +0 -2
- package/dist/chunk-EUD4PUKP.mjs.map +0 -1
package/dist/index-server.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index-server.ts","../src/session-meta.ts","../src/storage-key.ts","../src/slots.ts","../src/server.ts","../src/agent-capture.ts"],"sourcesContent":["/**\n * Server-only entry (`@sentientui/core/server`). SSR preload helpers that are\n * never needed in the browser — kept out of the lean client bundle.\n */\n\nexport { preloadAssignments, readSessionCookie, preloadDecisions } from './server.js';\nexport type { ServerAssignConfig, ServerAssignments, DecideResult, SlotDeclInput, SlotResult } from './server.js';\n\nexport {\n deriveSessionSegment,\n buildSessionUpsertPayload,\n detectDeviceClass,\n detectTrafficSource,\n detectTimeOfDay,\n extractTrackedParams,\n CLICK_ID_KEYS,\n referrerDomainFromReferer,\n} from './session-meta.js';\nexport type { SessionUpsertPayload } from './session-meta.js';\n\n// Server-side AI-assistant capture for any framework (capture spec §4.1).\nexport { captureAgentRequest, sentientAgentMiddleware, postAgentFetch } from './agent-capture.js';\nexport type { AgentCaptureOptions, CapturableRequest } from './agent-capture.js';\n","/** Session metadata helpers (browser + Node). No DOM APIs. */\n\n/**\n * Known AI-agent / crawler user-agent tokens. Matched case-insensitively as\n * substrings. This is maintained data — bot lists move monthly. Used both to\n * flag automation on sessions (agentic browsers that leak a token) and by the\n * server middleware / agent-feed route to identify crawler HTTP reads.\n */\nexport const agentUaList: readonly string[] = [\n 'GPTBot',\n 'ChatGPT-User',\n 'OAI-SearchBot',\n 'ClaudeBot',\n 'Claude-User',\n 'Claude-SearchBot',\n 'PerplexityBot',\n 'Perplexity-User',\n 'Google-Extended',\n 'Applebot-Extended',\n 'Meta-ExternalAgent',\n 'Bytespider',\n 'CCBot',\n 'Amazonbot',\n 'cohere-ai',\n 'Diffbot',\n];\n\n/** True when the user-agent contains a known AI-agent / crawler token. */\nexport function uaTokenMatch(userAgent: string): boolean {\n return matchedAgentToken(userAgent) !== null;\n}\n\n/** The first known agent token found in the user-agent, or null. */\nexport function matchedAgentToken(userAgent: string): string | null {\n if (!userAgent) return null;\n const s = userAgent.toLowerCase();\n return agentUaList.find((token) => s.includes(token.toLowerCase())) ?? null;\n}\n\n/**\n * Purpose category for an agent fetch, inferred from its published user-agent:\n * - `user` — a person asked an assistant to read the page, live (…-User UAs)\n * - `search` — indexing for an AI answer engine (…-SearchBot / SearchBot)\n * - `training` — model-training crawl (GPTBot, ClaudeBot, CCBot, …)\n * - `other` — not clearly AI, or an unknown/new token\n */\nexport type AgentIntent = 'user' | 'search' | 'training' | 'other';\n\n/** Intent per agent token. Maintained beside `agentUaList` — when you add or\n * rename a token above, set its intent here (a unit test enforces coverage). */\nexport const AGENT_INTENTS: Record<string, AgentIntent> = {\n 'GPTBot': 'training',\n 'ChatGPT-User': 'user',\n 'OAI-SearchBot': 'search',\n 'ClaudeBot': 'training',\n 'Claude-User': 'user',\n 'Claude-SearchBot': 'search',\n 'PerplexityBot': 'search',\n 'Perplexity-User': 'user',\n 'Google-Extended': 'training',\n 'Applebot-Extended': 'training',\n 'Meta-ExternalAgent': 'training',\n 'Bytespider': 'training',\n 'CCBot': 'training',\n 'Amazonbot': 'other',\n 'cohere-ai': 'training',\n 'Diffbot': 'other',\n};\n\n/** Intent for a matched bot token (case-insensitive); `other` for null/unknown. */\nexport function agentIntent(botName: string | null): AgentIntent {\n if (!botName) return 'other';\n const hit = agentUaList.find((t) => t.toLowerCase() === botName.toLowerCase());\n return (hit && AGENT_INTENTS[hit]) || 'other';\n}\n\n/** `agentUaList` grouped by intent — the \"which crawlers do you classify?\" reference. */\nexport function classifiedAgents(): Record<AgentIntent, string[]> {\n const out: Record<AgentIntent, string[]> = { user: [], search: [], training: [], other: [] };\n for (const t of agentUaList) out[AGENT_INTENTS[t] ?? 'other'].push(t);\n return out;\n}\n\nexport function detectDeviceClass(userAgent: string): string {\n const s = userAgent.toLowerCase();\n if (/ipad|tablet|playbook|kindle|silk/.test(s)) return 'tablet';\n if (/mobi|iphone|ipod|android.*mobile|phone/.test(s)) return 'mobile';\n return 'desktop';\n}\n\nexport function detectTrafficSource(referrer: string, appOrigin?: string): string {\n if (!referrer) return 'direct';\n try {\n const refUrl = new URL(referrer);\n if (appOrigin) {\n try {\n if (new URL(appOrigin).host === refUrl.host) return 'direct';\n } catch {\n /* ignore invalid appOrigin */\n }\n }\n const host = refUrl.hostname.toLowerCase();\n if (/(^|\\.)(google|bing|duckduckgo|yahoo)\\./.test(host)) return 'search';\n // Anchor to the registrable domain (exact host or a subdomain of it) so\n // hosts like `x.company.com`, `t.company.io` or `linkedinsights.com` are not\n // misclassified as social by an unbounded substring match.\n if (/(^|\\.)(twitter\\.com|x\\.com|facebook\\.com|linkedin\\.com|reddit\\.com|t\\.co)$/.test(host)) return 'social';\n return 'referral';\n } catch {\n return 'direct';\n }\n}\n\nexport function referrerDomainFromReferer(referrer: string): string | null {\n if (!referrer) return null;\n try {\n return new URL(referrer).hostname;\n } catch {\n return null;\n }\n}\n\n/**\n * Ad-platform click-ID query params worth keeping. An ALLOWLIST, unlike the\n * `utm_` prefix match: unknown query keys here are unbounded-cardinality junk\n * (session tokens, cache busters) that would bloat the sessions table, so only\n * the IDs the major ad platforms actually append survive.\n *\n * gclid / gbraid / wbraid — Google Ads auto-tagging (search, YouTube, Display;\n * gbraid/wbraid are the iOS-14 privacy variants)\n * fbclid — Meta (Facebook + Instagram). Appended to EVERY outbound Meta\n * click, paid and organic alike — it identifies the platform, never spend.\n * ttclid — TikTok Ads\n * msclkid — Microsoft Ads (Bing)\n * twclid — X/Twitter Ads\n * li_fat_id — LinkedIn Ads\n */\nexport const CLICK_ID_KEYS: readonly string[] = [\n 'gclid',\n 'gbraid',\n 'wbraid',\n 'fbclid',\n 'ttclid',\n 'msclkid',\n 'twclid',\n 'li_fat_id',\n];\n\n/**\n * Splits a URL query into the attribution params the session upsert carries:\n * every `utm_`-prefixed key, plus allowlisted ad click IDs (CLICK_ID_KEYS).\n * Accepts a raw search string (\"?a=b\" or \"a=b\"), a URLSearchParams, or a\n * Next.js `searchParams` object (whose values may be string arrays — the\n * first occurrence wins, matching URLSearchParams iteration order).\n * Node-safe: no DOM APIs.\n */\nexport function extractTrackedParams(\n search: string | URLSearchParams | Record<string, string | string[] | undefined>,\n): { utmParams: Record<string, string>; clickIds: Record<string, string> } {\n const utmParams: Record<string, string> = {};\n const clickIds: Record<string, string> = {};\n try {\n const entries: Iterable<[string, string]> =\n typeof search === 'string' || search instanceof URLSearchParams\n ? new URLSearchParams(search)\n : Object.entries(search).flatMap(([k, v]): Array<[string, string]> => {\n const first = Array.isArray(v) ? v[0] : v;\n return first === undefined ? [] : [[k, first]];\n });\n for (const [k, v] of entries) {\n // First occurrence wins for duplicates — a repeated gclid in a mangled\n // URL must not let the later value silently replace the real one.\n if (k.startsWith('utm_')) {\n if (!(k in utmParams)) utmParams[k] = v;\n } else if (CLICK_ID_KEYS.includes(k)) {\n if (!(k in clickIds)) clickIds[k] = v;\n }\n }\n } catch {\n /* malformed input → empty attribution, never a throw at init() */\n }\n return { utmParams, clickIds };\n}\n\nexport function detectTimeOfDay(d: Date): string {\n const h = d.getHours();\n if (h < 6) return 'night';\n if (h < 12) return 'morning';\n if (h < 18) return 'afternoon';\n return 'evening';\n}\n\nexport type SessionUpsertPayload = {\n sessionId: string;\n ephemeral: boolean;\n utmParams: Record<string, string>;\n /** Allowlisted ad-platform click IDs from the landing URL (CLICK_ID_KEYS). */\n clickIds: Record<string, string>;\n deviceClass: string;\n trafficSource: string;\n referrerDomain: string | null;\n timeOfDay: string;\n dayOfWeek: string;\n /**\n * True when this session is likely driven by automation — either\n * `navigator.webdriver` was set, or the user-agent carried a known agent\n * token. Probabilistic: a flag for metrics + bandit exclusion, never a gate.\n */\n automation: boolean;\n};\n\n/** Bandit segment key: `<device_class>:<traffic_source>`. */\nexport function deriveSessionSegment(opts?: {\n userAgent?: string;\n referer?: string;\n appOrigin?: string;\n}): string {\n const body = buildSessionUpsertPayload('__segment__', opts);\n return `${body.deviceClass}:${body.trafficSource}`;\n}\n\n/**\n * Builds a session upsert body aligned with the browser SDK so SSR assign uses\n * the same segment key (`device:source`) as the client after hydration.\n */\nexport function buildSessionUpsertPayload(\n sessionId: string,\n opts?: {\n userAgent?: string;\n referer?: string;\n appOrigin?: string;\n utmParams?: Record<string, string>;\n clickIds?: Record<string, string>;\n now?: Date;\n /** `navigator.webdriver` value from the browser, when available. */\n webdriver?: boolean;\n },\n): SessionUpsertPayload {\n const ua = opts?.userAgent?.trim() ?? '';\n const referer = opts?.referer?.trim() ?? '';\n const now = opts?.now ?? new Date();\n return {\n sessionId,\n ephemeral: false,\n utmParams: opts?.utmParams ?? {},\n clickIds: opts?.clickIds ?? {},\n deviceClass: ua ? detectDeviceClass(ua) : 'desktop',\n trafficSource: referer\n ? detectTrafficSource(referer, opts?.appOrigin)\n : 'direct',\n referrerDomain: referrerDomainFromReferer(referer),\n timeOfDay: detectTimeOfDay(now),\n dayOfWeek: ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'][now.getDay()] ?? 'sun',\n automation: opts?.webdriver === true || uaTokenMatch(ua),\n };\n}\n","/**\n * Per-project browser-storage namespace suffix, derived from the public apiKey.\n *\n * Multiple SentientUI projects (different `pk_` keys) can run on the same exact\n * origin. Storage keyed only by name (`_snt_uid`, `_snt_asgn_*`,\n * `_snt_graph_nodes`) would then collide across projects — the visitor id in\n * particular, whose session row is keyed globally server-side, would let one\n * project's traffic land on another's session. Suffixing every browser key with\n * the apiKey prefix isolates projects, matching the queue's existing\n * `_snt_retry_${apiKey.slice(0,12)}` convention.\n *\n * Returns `''` when no apiKey is available (local mode) so keys stay stable\n * there.\n */\nexport function storageSuffix(apiKey?: string): string {\n return apiKey ? `_${apiKey.slice(0, 12)}` : '';\n}\n\n/**\n * The bare, pre-namespacing session cookie name. Still read as a FALLBACK\n * everywhere the suffixed name is read, so visitors who got their identity\n * before per-project namespacing keep it instead of being minted a fresh one.\n */\nexport const LEGACY_SESSION_COOKIE_NAME = '_snt_uid';\n\n/**\n * The one place the session cookie's name is decided. The writer (session.ts)\n * and every reader (core/server.ts SSR helper, graph sync, react devtools) must\n * call THIS — when namespacing landed, the writer moved to the suffixed name\n * while three readers kept the bare `_snt_uid`, so every SSR request for a\n * returning visitor missed the cookie and minted a fresh orphan session (quota\n * inflation, broken sticky assignments and persona continuity), and graph sync\n * sent `sessionId: undefined`. Deriving both sides from one function makes that\n * drift impossible, and index.test.ts pins the reader against the writer.\n */\nexport function sessionCookieName(apiKey?: string): string {\n return `${LEGACY_SESSION_COOKIE_NAME}${storageSuffix(apiKey)}`;\n}\n","/**\n * Slot declaration helpers shared by the browser client (decide) and the\n * server preload path. Pure wrappers over @sentientui/policy.\n */\nimport {\n canonicalArm,\n slotBaselineArm,\n slotResultFor,\n type SlotDecl,\n type SlotResult,\n} from '@sentientui/policy';\n\n/** SDK-facing slot declaration. `dims` accepts readonly arrays (`as const`). */\nexport type SlotDeclInput = {\n id: string;\n arms?: string[];\n dims?: Record<string, readonly string[]>;\n baseline?: string | Record<string, string>;\n};\n\nexport type { SlotResult };\n\n/**\n * Whitelists the wire fields of a slot declaration. Anything an SDK layer\n * attached (goal configs, refs, …) is stripped so it never reaches the zod\n * schema on the API. Also normalizes readonly arrays to mutable ones.\n */\nexport function toWireSlot(d: SlotDeclInput): SlotDecl {\n return {\n id: d.id,\n ...(d.arms ? { arms: [...d.arms] } : {}),\n ...(d.dims\n ? {\n dims: Object.fromEntries(\n Object.entries(d.dims).map(([dim, values]) => [dim, [...values]]),\n ),\n }\n : {}),\n ...(d.baseline !== undefined ? { baseline: d.baseline } : {}),\n };\n}\n\n/** The declared (or default first-declared) baseline result for a slot. */\nexport function baselineResultFor(d: SlotDeclInput): SlotResult {\n const decl = toWireSlot(d);\n return slotResultFor(decl, slotBaselineArm(decl));\n}\n\n/** Baseline results for a whole declaration list, keyed by slot id. */\nexport function baselineSlots(decls: SlotDeclInput[]): Record<string, SlotResult> {\n const out: Record<string, SlotResult> = {};\n for (const d of decls) out[d.id] = baselineResultFor(d);\n return out;\n}\n\n/**\n * Canonical arm string of a slot result: dims results encode as sorted\n * `dim=value` pairs joined with '|'; arms results are the arm id verbatim.\n */\nexport function armOfResult(result: SlotResult): string {\n return typeof result === 'string' ? result : canonicalArm(result);\n}\n","/**\n * Server-side helpers for SSR variant pre-loading.\n * Pure fetch — no DOM APIs. Safe in Node.js, Edge, and Deno runtimes.\n */\nimport { buildSessionUpsertPayload } from './session-meta.js';\nimport { LEGACY_SESSION_COOKIE_NAME, sessionCookieName } from './storage-key.js';\nimport {\n toWireSlot,\n baselineResultFor,\n baselineSlots,\n type SlotDeclInput,\n type SlotResult,\n} from './slots.js';\n\nimport type { SlotConfigEntry } from './snapshot.js';\nimport type { RenderCaps } from './region-skeleton.js';\nimport type { SitePalette } from './blocks.js';\n\nexport type { SlotDeclInput, SlotResult, SlotConfigEntry, SitePalette };\n\nexport type ServerAssignConfig = {\n /** Public API key (pk_...). */\n apiKey: string;\n /**\n * Base URL of the Sentient API without trailing slash.\n * e.g. 'https://api.yourapp.com/v1'\n */\n baseUrl: string;\n /**\n * Browser origin of your app (e.g. `http://localhost:3001`). Required for `pk_`\n * keys — server-side fetch must send the same `Origin` the API allows.\n */\n origin?: string;\n /** From `User-Agent` request header (Next.js `headers()`). */\n userAgent?: string;\n /** From `Referer` request header. */\n referer?: string;\n utmParams?: Record<string, string>;\n /**\n * Ad-platform click IDs (gclid, fbclid, ttclid, …) from the landing URL.\n * Derive both this and `utmParams` with `extractTrackedParams(searchParams)`\n * — the Referer header never carries the landing page's own query string, so\n * without these two fields SSR-minted sessions have no campaign attribution\n * until the client SDK hydrates.\n */\n clickIds?: Record<string, string>;\n /**\n * Set true when the request carries a tracking opt-out — `DNT: 1` or\n * `Sec-GPC: 1`. When set, the SSR helpers skip the session upsert and the\n * assign/decide call entirely: the page renders defaults/baseline and no\n * session row is minted for the visitor (audit P4). The client SDK already\n * no-ops for these visitors; this keeps the server from minting a session +\n * assignment on every page view before the client can.\n */\n doNotTrack?: boolean;\n /**\n * Declared persona — the role your app already knows for this visitor\n * (e.g. from your auth context during SSR). Same contract as the client\n * option: must be a vocabulary key; unrecognized values are ignored\n * server-side. Never a user id or email.\n */\n persona?: string;\n /**\n * Milliseconds to wait for the API before returning default variants.\n * Prevents slow/cold API from blocking SSR. Defaults to 1000 — the hot path\n * is served from in-process caches and typically returns in well under\n * 150 ms. The full 1 s budget is only reached on a cold start or an API\n * geographically distant from your SSR host, after which defaults render\n * with no layout shift. Lower it if your API is co-located and warm.\n */\n timeoutMs?: number;\n};\n\n/** componentId → assigned variantId */\nexport type ServerAssignments = Record<string, string>;\n\ntype AssignResult = { variantId: string; assignmentTtlMs: number };\n\nconst DEFAULT_TIMEOUT_MS = 1000;\n\nfunction fetchWithTimeout(\n url: string,\n init: RequestInit,\n timeoutMs: number,\n): Promise<Response> {\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), timeoutMs);\n return fetch(url, { ...init, signal: controller.signal }).finally(() =>\n clearTimeout(timer),\n );\n}\n\n/**\n * Fetches variant assignments server-side for all listed components.\n * Returns a map suitable for passing as `initialAssignments` to `<AdaptiveProvider>`.\n *\n * Call from Next.js layout, Server Component, or getServerSideProps.\n *\n * @example\n * ```tsx\n * const assignments = await preloadAssignments(\n * [\n * { id: 'hero', variantIds: ['hero-a', 'hero-b'] },\n * { id: 'cta', variantIds: ['cta-short', 'cta-long'] },\n * ],\n * sessionId, // read from cookies() or req.cookies\n * { apiKey: process.env.NEXT_PUBLIC_SENTIENT_API_KEY!, baseUrl: 'https://api.sentient-ui.com/v1' },\n * );\n * return <AdaptiveProvider ... initialAssignments={assignments}>{children}</AdaptiveProvider>;\n * ```\n */\nexport async function preloadAssignments(\n components: Array<{ id: string; variantIds: string[] }>,\n sessionId: string,\n config: ServerAssignConfig,\n): Promise<ServerAssignments> {\n // Opted-out visitor (DNT/GPC): render defaults, mint no session (audit P4).\n if (config.doNotTrack) return {};\n\n const timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${config.apiKey}`,\n };\n if (config.origin) {\n headers.Origin = config.origin;\n }\n\n // Session metadata must match the browser SDK so assign seeds variant_weights\n // under the same segment (not `unknown:unknown`).\n const sessionBody = {\n ...buildSessionUpsertPayload(sessionId, {\n userAgent: config.userAgent,\n referer: config.referer,\n utmParams: config.utmParams,\n clickIds: config.clickIds,\n appOrigin: config.origin,\n }),\n ...(config.persona ? { persona: config.persona } : {}),\n };\n\n try {\n const res = await fetchWithTimeout(\n `${config.baseUrl}/sessions`,\n { method: 'POST', headers, body: JSON.stringify(sessionBody) },\n timeoutMs,\n );\n if (res.status === 402) {\n console.warn(\n '[SentientUI] Session limit exceeded for this project. The bandit will stop learning until the limit resets. Upgrade at sentient-ui.com/pricing',\n );\n } else if (!res.ok) {\n const body = await res.json().catch(() => ({}));\n console.error(`[SentientUI] preloadAssignments: session upsert failed (${res.status})`, body);\n }\n } catch (err) {\n console.error('[SentientUI] preloadAssignments: session upsert threw', err);\n }\n\n const results = await Promise.allSettled(\n components.map(async ({ id, variantIds }) => {\n const res = await fetchWithTimeout(\n `${config.baseUrl}/assign`,\n { method: 'POST', headers, body: JSON.stringify({ sessionId, componentId: id, variantIds }) },\n timeoutMs,\n );\n if (!res.ok) {\n const body = await res.json().catch(() => ({}));\n console.error(`[SentientUI] preloadAssignments: assign failed for \"${id}\" (${res.status})`, body);\n return null;\n }\n const body = (await res.json()) as AssignResult;\n return { id, variantId: body.variantId };\n }),\n );\n\n const assignments: ServerAssignments = {};\n for (const result of results) {\n if (result.status === 'fulfilled' && result.value) {\n assignments[result.value.id] = result.value.variantId;\n }\n }\n return assignments;\n}\n\n/**\n * Reads the Sentient session cookie from a Next.js `ReadonlyRequestCookies` object\n * (the return value of `cookies()` from `next/headers`), or any object with a\n * `get(name: string)` method. Returns null if the cookie is absent.\n *\n * Pass the project's `apiKey`: the client writes the per-project SUFFIXED name\n * (`sessionCookieName` — see storage-key.ts), so reading only the bare\n * `_snt_uid` missed the cookie on every SSR request for a returning visitor and\n * minted a fresh orphan session each page view (quota inflation, broken sticky\n * assignments and persona continuity). The bare name is still read as a\n * fallback for identities minted before namespacing.\n */\nexport function readSessionCookie(\n cookies: { get(name: string): { value: string } | undefined },\n apiKey?: string,\n): string | null {\n return (\n (apiKey ? cookies.get(sessionCookieName(apiKey))?.value : undefined) ??\n cookies.get(LEGACY_SESSION_COOKIE_NAME)?.value ??\n null\n );\n}\n\nexport type DecideResult = {\n layoutOrder: string[];\n assignments: Record<string, string>;\n /** Slot results keyed by slot id. Baseline-resolved when the API omits/fails them. */\n slots: Record<string, SlotResult>;\n persona: string;\n confidence: number;\n /** Registry mode only: content/ops/blocks for server-defined slots. */\n slotConfig?: Record<string, SlotConfigEntry>;\n /** Registry mode only: site palette for block rendering. */\n palette?: SitePalette;\n /** Registry mode only: site styles the served Redesign arms borrow. */\n vocabulary?: import('./style-vocabulary.js').StyleVocabulary;\n};\n\n/**\n * Single-roundtrip SSR call returning layout order, component assignments,\n * and adaptive-slot results. Falls back to default section order + empty\n * assignments + baseline slots if the API is unavailable. A response without\n * a `slots` field means the server predates slots — every declared slot\n * resolves to its baseline (no retry).\n */\nexport async function preloadDecisions(\n params: {\n sections?: string[];\n components: Array<{ id: string; variantIds?: string[] }>;\n slots?: SlotDeclInput[];\n /** 'registry' serves the project's published slot_definitions as if declared\n * (and is the only way slotConfig/palette come back). Default 'request'.\n * Requires `registrySlotIds`: the `<Adaptive id>`s THIS page renders. */\n slotsFrom?: 'request' | 'registry';\n /**\n * Registry mode: decide only these published slot ids. Close-out turns\n * every slot decision into a trial without checking an exposure, so an\n * unscoped registry decide accrues trials — and session-level credit — for\n * every published slot on every page, including ones this page never\n * renders (CONTRACTS §2). Omitting it in registry mode is refused: the\n * call downgrades to request mode with one console.error, rather than\n * silently minting those trials.\n */\n registrySlotIds?: string[];\n /**\n * Registry mode: what each slot on this page can render (CONTRACTS §2).\n * The server has no DOM here, so no fingerprint is sent and a Rewrite arm\n * is assumed to match; a real mismatch is reported from the browser as\n * drift. Declare `forms: false` for slots without an `onFormSubmit`, or a\n * form arm can be drawn that this page will refuse. Default per slot:\n * `{ forms: true, compose: true }`.\n */\n renderCaps?: Record<string, Omit<RenderCaps, 'fp'>>;\n },\n sessionId: string,\n config: ServerAssignConfig,\n): Promise<DecideResult> {\n const timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n const declaredSlots = params.slots ?? [];\n let registryIds: string[] | null = null;\n if (params.slotsFrom === 'registry') {\n if (Array.isArray(params.registrySlotIds)) {\n registryIds = params.registrySlotIds;\n } else {\n console.error(\n \"[SentientUI] preloadDecisions: slotsFrom: 'registry' needs registrySlotIds (the <Adaptive id>s this page renders). \" +\n 'An unscoped registry decide records a trial for every published slot on every page; falling back to request mode.',\n );\n }\n }\n const fallback: DecideResult = {\n layoutOrder: params.sections ?? [],\n assignments: {},\n slots: baselineSlots(declaredSlots),\n persona: 'unknown',\n confidence: 0,\n };\n\n // Opted-out visitor (DNT/GPC): baseline layout/slots, mint no session (audit P4).\n if (config.doNotTrack) return fallback;\n\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${config.apiKey}`,\n };\n if (config.origin) headers.Origin = config.origin;\n\n const sessionBody = {\n ...buildSessionUpsertPayload(sessionId, {\n userAgent: config.userAgent,\n referer: config.referer,\n utmParams: config.utmParams,\n clickIds: config.clickIds,\n appOrigin: config.origin,\n }),\n ...(config.persona ? { persona: config.persona } : {}),\n };\n\n try {\n const sessionRes = await fetchWithTimeout(\n `${config.baseUrl}/sessions`,\n { method: 'POST', headers, body: JSON.stringify(sessionBody) },\n timeoutMs,\n );\n if (!sessionRes.ok) {\n const body = await sessionRes.json().catch(() => ({}));\n console.error(`[SentientUI] preloadDecisions: session upsert failed (${sessionRes.status})`, body);\n }\n } catch (err) {\n console.error('[SentientUI] preloadDecisions: session upsert threw', err);\n }\n\n try {\n const res = await fetchWithTimeout(\n `${config.baseUrl}/decide`,\n {\n method: 'POST',\n headers,\n body: JSON.stringify({\n sessionId,\n sections: (params.sections ?? []).map((id) => ({ id })),\n components: params.components,\n ...(declaredSlots.length > 0 ? { slots: declaredSlots.map(toWireSlot) } : {}),\n // bootstrap:false — editor goals and the section map are snippet\n // data the React SDK never reads. An EMPTY id list is meaningful\n // (\"nothing published is on this page\"): zero trials, still a decide.\n ...(registryIds !== null\n ? {\n slotsFrom: 'registry',\n registrySlotIds: registryIds,\n bootstrap: false,\n // Always sent, so the server knows this is an SDK that can\n // render Rewrite arms — no `render` field means legacy.\n render: Object.fromEntries(\n // compose: true — the React SDK (the SSR consumer) renders\n // Redesign trees since native generation phase 2.\n registryIds.map((id) => [id, params.renderCaps?.[id] ?? { forms: true, compose: true }]),\n ),\n }\n : {}),\n ...(config.persona ? { persona: config.persona } : {}),\n }),\n },\n timeoutMs,\n );\n if (!res.ok) {\n const body = await res.json().catch(() => ({}));\n console.error(`[SentientUI] preloadDecisions: decide failed (${res.status})`, body);\n return fallback;\n }\n const data = (await res.json()) as {\n layoutOrder?: string[];\n assignments?: Record<string, string>;\n slots?: Record<string, SlotResult>;\n slotConfig?: Record<string, SlotConfigEntry>;\n palette?: SitePalette;\n vocabulary?: import('./style-vocabulary.js').StyleVocabulary;\n persona?: string;\n confidence?: number;\n };\n\n const slots: Record<string, SlotResult> = {};\n for (const d of declaredSlots) {\n // `data.slots === undefined` ⇒ server predates slots: baseline, no retry.\n slots[d.id] = data.slots?.[d.id] ?? baselineResultFor(d);\n }\n // Registry mode returns slots the request never declared — union them in\n // (same rule as the browser client), or an SSR page gets results for none\n // of its registry slots.\n for (const [slotId, result] of Object.entries(data.slots ?? {})) {\n if (!(slotId in slots)) slots[slotId] = result;\n }\n\n // Plain-object guard only (readSnapshot's rule): the server total-validated\n // the config at publish; a deep re-validation here would just drift.\n const slotConfigOk =\n data.slotConfig !== undefined && typeof data.slotConfig === 'object' && data.slotConfig !== null && !Array.isArray(data.slotConfig);\n\n return {\n layoutOrder: data.layoutOrder ?? params.sections ?? [],\n assignments: data.assignments ?? {},\n slots,\n persona: data.persona ?? 'unknown',\n confidence: data.confidence ?? 0,\n ...(slotConfigOk ? { slotConfig: data.slotConfig } : {}),\n ...(data.palette ? { palette: data.palette } : {}),\n ...(data.vocabulary ? { vocabulary: data.vocabulary } : {}),\n };\n } catch (err) {\n console.error('[SentientUI] preloadDecisions: decide threw', err);\n return fallback;\n }\n}\n","// Server-side capture of AI-assistant fetches, for any framework.\n// Spec: docs/superpowers/specs/2026-09-23-server-side-agent-capture-design.md §4.1\n//\n// Assistants that fetch a page without running JavaScript (ChatGPT-User,\n// Claude-User, Perplexity-User, GPTBot, …) never execute the snippet or the\n// React SDK, so only the server that answered can see them. Until this, only\n// Next.js AdaptiveRoot logged them; every other site read \"no AI traffic\",\n// which is wrong rather than empty.\n//\n// OBSERVATION ONLY. Nothing here may change a response based on the user\n// agent: that is cloaking, and SentientUI never claims to adapt serving to\n// agents. These functions return nothing a caller could branch on except\n// \"did this look like an agent\", and log to crawler_requests — never to\n// sessions, never to training, never to billing.\n\nimport { matchedAgentToken } from './session-meta.js';\n\nconst DEFAULT_API_BASE_URL = 'https://api.sentient-ui.com/v1';\n\nexport type AgentCaptureOptions = {\n /** Your public `pk_` key — the same one the snippet uses. */\n apiKey: string;\n /** API base ending in `/v1`. Defaults to the hosted API. */\n baseUrl?: string;\n /** Which capture path saw the fetch. Shown per row on the dashboard. */\n source?: 'middleware' | 'edge' | 'ssr';\n /**\n * REQUIRED on edge runtimes (Vercel Routing Middleware, Cloudflare Workers,\n * Netlify Edge): they cancel outstanding work once the response is\n * returned, so a fire-and-forget request without it is silently dropped.\n * Pass the platform's `waitUntil` (`ctx.waitUntil.bind(ctx)` on Workers,\n * `waitUntil` from `@vercel/functions`). Node servers do not need it.\n */\n waitUntil?: (p: Promise<unknown>) => void;\n /** Injectable for tests. */\n fetchImpl?: typeof fetch;\n};\n\n/** The minimum of a request both the Fetch API `Request` and hand-rolled\n * objects satisfy. */\nexport type CapturableRequest = {\n url: string;\n headers: { get(name: string): string | null };\n};\n\n/** Pathname only: a query string can carry tokens, emails or campaign ids. */\nfunction pathOf(url: string): string {\n try {\n return new URL(url, 'http://localhost').pathname || '/';\n } catch {\n return url.split(/[?#]/, 1)[0] || '/';\n }\n}\n\n/**\n * Low-level sender: posts one agent fetch to `/v1/crawler-events`. Never\n * throws, never blocks. The API re-derives the agent from `userAgent`\n * itself, so `botName` is advisory.\n */\nexport function postAgentFetch(\n entry: { path: string; userAgent: string; botName: string },\n opts: AgentCaptureOptions,\n): void {\n const doFetch = opts.fetchImpl ?? (typeof fetch === 'function' ? fetch : undefined);\n if (!doFetch || !opts.apiKey) return;\n try {\n const p = doFetch(`${opts.baseUrl ?? DEFAULT_API_BASE_URL}/crawler-events`, {\n method: 'POST',\n headers: { 'content-type': 'application/json', authorization: `Bearer ${opts.apiKey}` },\n body: JSON.stringify({\n path: entry.path,\n botName: entry.botName,\n userAgent: entry.userAgent,\n source: opts.source ?? 'middleware',\n }),\n }).catch(() => undefined);\n opts.waitUntil?.(p);\n } catch {\n /* capture must never break the page it is observing */\n }\n}\n\n/**\n * Log this request if its user agent is a known AI assistant or crawler.\n * Works with a Fetch API `Request` (edge runtimes, Hono, Remix / React\n * Router, Astro, SvelteKit) or anything with `url` + `headers.get`.\n *\n * Returns whether the request matched, so a caller can skip its own work;\n * it must NOT be used to serve anything different. Non-matching requests —\n * nearly all of them — make no network call.\n */\nexport function captureAgentRequest(req: CapturableRequest, opts: AgentCaptureOptions): boolean {\n let userAgent = '';\n try {\n userAgent = req.headers.get('user-agent') ?? '';\n } catch {\n return false;\n }\n const botName = matchedAgentToken(userAgent);\n if (!botName) return false;\n postAgentFetch({ path: pathOf(req.url), userAgent, botName }, opts);\n return true;\n}\n\ntype ConnectRequest = {\n url?: string;\n originalUrl?: string;\n headers: Record<string, string | string[] | undefined>;\n};\n\n/**\n * Connect-style middleware (Express, Nitro / Nuxt on Node, Fastify via\n * middie, any `(req, res, next)` stack). Calls `next()` synchronously and\n * logs in the background; it never touches the response.\n */\nexport function sentientAgentMiddleware(\n opts: Omit<AgentCaptureOptions, 'waitUntil' | 'source'>,\n): (req: ConnectRequest, res: unknown, next: (err?: unknown) => void) => void {\n return (req, _res, next) => {\n try {\n const raw = req.headers['user-agent'];\n const ua = Array.isArray(raw) ? raw[0] ?? '' : raw ?? '';\n captureAgentRequest(\n { url: req.originalUrl ?? req.url ?? '/', headers: { get: (n) => (n.toLowerCase() === 'user-agent' ? ua : null) } },\n { ...opts, source: 'middleware' },\n );\n } catch {\n /* never block the request */\n }\n next();\n };\n}\n"],"mappings":"kxBAAA,IAAAA,GAAA,GAAAC,GAAAD,GAAA,mBAAAE,EAAA,8BAAAC,EAAA,wBAAAC,EAAA,yBAAAC,EAAA,sBAAAC,EAAA,oBAAAC,EAAA,wBAAAC,EAAA,yBAAAC,EAAA,mBAAAC,EAAA,uBAAAC,EAAA,qBAAAC,GAAA,sBAAAC,EAAA,8BAAAC,EAAA,4BAAAC,KAAA,eAAAC,GAAAhB,ICQO,IAAMiB,GAAiC,CAC5C,SACA,eACA,gBACA,YACA,cACA,mBACA,gBACA,kBACA,kBACA,oBACA,qBACA,aACA,QACA,YACA,YACA,SACF,EAGO,SAASC,GAAaC,EAA4B,CACvD,OAAOC,EAAkBD,CAAS,IAAM,IAC1C,CAGO,SAASC,EAAkBD,EAAkC,CAjCpE,IAAAE,EAkCE,GAAI,CAACF,EAAW,OAAO,KACvB,IAAMG,EAAIH,EAAU,YAAY,EAChC,OAAOE,EAAAJ,GAAY,KAAMM,GAAUD,EAAE,SAASC,EAAM,YAAY,CAAC,CAAC,IAA3D,KAAAF,EAAgE,IACzE,CA8CO,SAASG,EAAkBC,EAA2B,CAC3D,IAAMC,EAAID,EAAU,YAAY,EAChC,MAAI,mCA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L,KAAAf,EAAU,GAAKe,GAAA,KAAAA,EAAO,GACtDR,EACE,CAAE,KAAKL,GAAAD,EAAAO,EAAI,cAAJ,KAAAP,EAAmBO,EAAI,MAAvB,KAAAN,EAA8B,IAAK,QAAS,CAAE,IAAMe,GAAOA,EAAE,YAAY,IAAM,aAAeD,EAAK,IAAM,CAAE,EAClHE,EAAAC,EAAA,GAAKpB,GAAL,CAAW,OAAQ,YAAa,EAClC,CACF,OAAQO,EAAA,CAER,CACAQ,EAAK,CACP,CACF","names":["index_server_exports","__export","CLICK_ID_KEYS","buildSessionUpsertPayload","captureAgentRequest","deriveSessionSegment","detectDeviceClass","detectTimeOfDay","detectTrafficSource","extractTrackedParams","postAgentFetch","preloadAssignments","preloadDecisions","readSessionCookie","referrerDomainFromReferer","sentientAgentMiddleware","__toCommonJS","agentUaList","uaTokenMatch","userAgent","matchedAgentToken","_a","s","token","detectDeviceClass","userAgent","s","detectTrafficSource","referrer","appOrigin","refUrl","e","host","referrerDomainFromReferer","CLICK_ID_KEYS","extractTrackedParams","search","utmParams","clickIds","entries","k","v","first","detectTimeOfDay","d","h","deriveSessionSegment","opts","body","buildSessionUpsertPayload","sessionId","_a","_b","_c","_d","_e","_f","_g","_h","ua","referer","now","uaTokenMatch","storageSuffix","apiKey","LEGACY_SESSION_COOKIE_NAME","sessionCookieName","import_policy","toWireSlot","d","__spreadValues","dim","values","baselineResultFor","decl","baselineSlots","decls","out","DEFAULT_TIMEOUT_MS","fetchWithTimeout","url","init","timeoutMs","controller","timer","__spreadProps","__spreadValues","preloadAssignments","components","sessionId","config","_a","headers","sessionBody","buildSessionUpsertPayload","res","body","err","results","id","variantIds","assignments","result","readSessionCookie","cookies","apiKey","_b","_c","_d","sessionCookieName","LEGACY_SESSION_COOKIE_NAME","preloadDecisions","params","_e","_f","_g","_h","_i","_j","_k","_l","declaredSlots","registryIds","fallback","baselineSlots","sessionRes","toWireSlot","data","slots","baselineResultFor","slotId","slotConfigOk","DEFAULT_API_BASE_URL","pathOf","url","postAgentFetch","entry","opts","_a","_b","_c","_d","doFetch","p","e","captureAgentRequest","req","userAgent","botName","matchedAgentToken","sentientAgentMiddleware","_res","next","raw","ua","n","__spreadProps","__spreadValues"]}
|
|
1
|
+
{"version":3,"sources":["../src/index-server.ts","../src/session-meta.ts","../src/storage-key.ts","../src/slots.ts","../src/server.ts","../src/agent-capture.ts"],"sourcesContent":["/**\n * Server-only entry (`@sentientui/core/server`). SSR preload helpers that are\n * never needed in the browser — kept out of the lean client bundle.\n */\n\nexport { preloadAssignments, readSessionCookie, preloadDecisions } from './server.js';\nexport type { ServerAssignConfig, ServerAssignments, DecideResult, SlotDeclInput, SlotResult } from './server.js';\n\nexport {\n deriveSessionSegment,\n buildSessionUpsertPayload,\n detectDeviceClass,\n detectTrafficSource,\n detectTimeOfDay,\n extractTrackedParams,\n CLICK_ID_KEYS,\n referrerDomainFromReferer,\n} from './session-meta.js';\nexport type { SessionUpsertPayload } from './session-meta.js';\n\n// Server-side AI-assistant capture for any framework (capture spec §4.1).\nexport { captureAgentRequest, sentientAgentMiddleware, postAgentFetch } from './agent-capture.js';\nexport type { AgentCaptureOptions, CapturableRequest } from './agent-capture.js';\n","/** Session metadata helpers (browser + Node). No DOM APIs. */\n\n/**\n * Known AI-agent / crawler user-agent tokens. Matched case-insensitively as\n * substrings. This is maintained data — bot lists move monthly. Used both to\n * flag automation on sessions (agentic browsers that leak a token) and by the\n * server middleware / agent-feed route to identify crawler HTTP reads.\n */\nexport const agentUaList: readonly string[] = [\n 'GPTBot',\n 'ChatGPT-User',\n 'OAI-SearchBot',\n 'ClaudeBot',\n 'Claude-User',\n 'Claude-SearchBot',\n 'PerplexityBot',\n 'Perplexity-User',\n 'Google-Extended',\n 'Applebot-Extended',\n 'Meta-ExternalAgent',\n 'Bytespider',\n 'CCBot',\n 'Amazonbot',\n 'cohere-ai',\n 'Diffbot',\n];\n\n/** True when the user-agent contains a known AI-agent / crawler token. */\nexport function uaTokenMatch(userAgent: string): boolean {\n return matchedAgentToken(userAgent) !== null;\n}\n\n/** The first known agent token found in the user-agent, or null. */\nexport function matchedAgentToken(userAgent: string): string | null {\n if (!userAgent) return null;\n const s = userAgent.toLowerCase();\n return agentUaList.find((token) => s.includes(token.toLowerCase())) ?? null;\n}\n\n/**\n * Purpose category for an agent fetch, inferred from its published user-agent:\n * - `user` — a person asked an assistant to read the page, live (…-User UAs)\n * - `search` — indexing for an AI answer engine (…-SearchBot / SearchBot)\n * - `training` — model-training crawl (GPTBot, ClaudeBot, CCBot, …)\n * - `other` — not clearly AI, or an unknown/new token\n */\nexport type AgentIntent = 'user' | 'search' | 'training' | 'other';\n\n/** Intent per agent token. Maintained beside `agentUaList` — when you add or\n * rename a token above, set its intent here (a unit test enforces coverage). */\nexport const AGENT_INTENTS: Record<string, AgentIntent> = {\n 'GPTBot': 'training',\n 'ChatGPT-User': 'user',\n 'OAI-SearchBot': 'search',\n 'ClaudeBot': 'training',\n 'Claude-User': 'user',\n 'Claude-SearchBot': 'search',\n 'PerplexityBot': 'search',\n 'Perplexity-User': 'user',\n 'Google-Extended': 'training',\n 'Applebot-Extended': 'training',\n 'Meta-ExternalAgent': 'training',\n 'Bytespider': 'training',\n 'CCBot': 'training',\n 'Amazonbot': 'other',\n 'cohere-ai': 'training',\n 'Diffbot': 'other',\n};\n\n/** Intent for a matched bot token (case-insensitive); `other` for null/unknown. */\nexport function agentIntent(botName: string | null): AgentIntent {\n if (!botName) return 'other';\n const hit = agentUaList.find((t) => t.toLowerCase() === botName.toLowerCase());\n return (hit && AGENT_INTENTS[hit]) || 'other';\n}\n\n/** `agentUaList` grouped by intent — the \"which crawlers do you classify?\" reference. */\nexport function classifiedAgents(): Record<AgentIntent, string[]> {\n const out: Record<AgentIntent, string[]> = { user: [], search: [], training: [], other: [] };\n for (const t of agentUaList) out[AGENT_INTENTS[t] ?? 'other'].push(t);\n return out;\n}\n\nexport function detectDeviceClass(userAgent: string): string {\n const s = userAgent.toLowerCase();\n if (/ipad|tablet|playbook|kindle|silk/.test(s)) return 'tablet';\n if (/mobi|iphone|ipod|android.*mobile|phone/.test(s)) return 'mobile';\n return 'desktop';\n}\n\nexport function detectTrafficSource(referrer: string, appOrigin?: string): string {\n if (!referrer) return 'direct';\n try {\n const refUrl = new URL(referrer);\n if (appOrigin) {\n try {\n if (new URL(appOrigin).host === refUrl.host) return 'direct';\n } catch {\n /* ignore invalid appOrigin */\n }\n }\n const host = refUrl.hostname.toLowerCase();\n if (/(^|\\.)(google|bing|duckduckgo|yahoo)\\./.test(host)) return 'search';\n // Anchor to the registrable domain (exact host or a subdomain of it) so\n // hosts like `x.company.com`, `t.company.io` or `linkedinsights.com` are not\n // misclassified as social by an unbounded substring match.\n if (/(^|\\.)(twitter\\.com|x\\.com|facebook\\.com|linkedin\\.com|reddit\\.com|t\\.co)$/.test(host)) return 'social';\n return 'referral';\n } catch {\n return 'direct';\n }\n}\n\nexport function referrerDomainFromReferer(referrer: string): string | null {\n if (!referrer) return null;\n try {\n return new URL(referrer).hostname;\n } catch {\n return null;\n }\n}\n\n/**\n * Ad-platform click-ID query params worth keeping. An ALLOWLIST, unlike the\n * `utm_` prefix match: unknown query keys here are unbounded-cardinality junk\n * (session tokens, cache busters) that would bloat the sessions table, so only\n * the IDs the major ad platforms actually append survive.\n *\n * gclid / gbraid / wbraid — Google Ads auto-tagging (search, YouTube, Display;\n * gbraid/wbraid are the iOS-14 privacy variants)\n * fbclid — Meta (Facebook + Instagram). Appended to EVERY outbound Meta\n * click, paid and organic alike — it identifies the platform, never spend.\n * ttclid — TikTok Ads\n * msclkid — Microsoft Ads (Bing)\n * twclid — X/Twitter Ads\n * li_fat_id — LinkedIn Ads\n */\nexport const CLICK_ID_KEYS: readonly string[] = [\n 'gclid',\n 'gbraid',\n 'wbraid',\n 'fbclid',\n 'ttclid',\n 'msclkid',\n 'twclid',\n 'li_fat_id',\n];\n\n/**\n * Splits a URL query into the attribution params the session upsert carries:\n * every `utm_`-prefixed key, plus allowlisted ad click IDs (CLICK_ID_KEYS).\n * Accepts a raw search string (\"?a=b\" or \"a=b\"), a URLSearchParams, or a\n * Next.js `searchParams` object (whose values may be string arrays — the\n * first occurrence wins, matching URLSearchParams iteration order).\n * Node-safe: no DOM APIs.\n */\nexport function extractTrackedParams(\n search: string | URLSearchParams | Record<string, string | string[] | undefined>,\n): { utmParams: Record<string, string>; clickIds: Record<string, string> } {\n const utmParams: Record<string, string> = {};\n const clickIds: Record<string, string> = {};\n try {\n const entries: Iterable<[string, string]> =\n typeof search === 'string' || search instanceof URLSearchParams\n ? new URLSearchParams(search)\n : Object.entries(search).flatMap(([k, v]): Array<[string, string]> => {\n const first = Array.isArray(v) ? v[0] : v;\n return first === undefined ? [] : [[k, first]];\n });\n for (const [k, v] of entries) {\n // First occurrence wins for duplicates — a repeated gclid in a mangled\n // URL must not let the later value silently replace the real one.\n if (k.startsWith('utm_')) {\n if (!(k in utmParams)) utmParams[k] = v;\n } else if (CLICK_ID_KEYS.includes(k)) {\n if (!(k in clickIds)) clickIds[k] = v;\n }\n }\n } catch {\n /* malformed input → empty attribution, never a throw at init() */\n }\n return { utmParams, clickIds };\n}\n\nexport function detectTimeOfDay(d: Date): string {\n const h = d.getHours();\n if (h < 6) return 'night';\n if (h < 12) return 'morning';\n if (h < 18) return 'afternoon';\n return 'evening';\n}\n\nexport type SessionUpsertPayload = {\n sessionId: string;\n ephemeral: boolean;\n utmParams: Record<string, string>;\n /** Allowlisted ad-platform click IDs from the landing URL (CLICK_ID_KEYS). */\n clickIds: Record<string, string>;\n deviceClass: string;\n trafficSource: string;\n referrerDomain: string | null;\n timeOfDay: string;\n dayOfWeek: string;\n /**\n * True when this session is likely driven by automation — either\n * `navigator.webdriver` was set, or the user-agent carried a known agent\n * token. Probabilistic: a flag for metrics + bandit exclusion, never a gate.\n */\n automation: boolean;\n};\n\n/** Bandit segment key: `<device_class>:<traffic_source>`. */\nexport function deriveSessionSegment(opts?: {\n userAgent?: string;\n referer?: string;\n appOrigin?: string;\n}): string {\n const body = buildSessionUpsertPayload('__segment__', opts);\n return `${body.deviceClass}:${body.trafficSource}`;\n}\n\n/**\n * Builds a session upsert body aligned with the browser SDK so SSR assign uses\n * the same segment key (`device:source`) as the client after hydration.\n */\nexport function buildSessionUpsertPayload(\n sessionId: string,\n opts?: {\n userAgent?: string;\n referer?: string;\n appOrigin?: string;\n utmParams?: Record<string, string>;\n clickIds?: Record<string, string>;\n now?: Date;\n /** `navigator.webdriver` value from the browser, when available. */\n webdriver?: boolean;\n },\n): SessionUpsertPayload {\n const ua = opts?.userAgent?.trim() ?? '';\n const referer = opts?.referer?.trim() ?? '';\n const now = opts?.now ?? new Date();\n return {\n sessionId,\n ephemeral: false,\n utmParams: opts?.utmParams ?? {},\n clickIds: opts?.clickIds ?? {},\n deviceClass: ua ? detectDeviceClass(ua) : 'desktop',\n trafficSource: referer\n ? detectTrafficSource(referer, opts?.appOrigin)\n : 'direct',\n referrerDomain: referrerDomainFromReferer(referer),\n timeOfDay: detectTimeOfDay(now),\n dayOfWeek: ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'][now.getDay()] ?? 'sun',\n automation: opts?.webdriver === true || uaTokenMatch(ua),\n };\n}\n","/**\n * Per-project browser-storage namespace suffix, derived from the public apiKey.\n *\n * Multiple SentientUI projects (different `pk_` keys) can run on the same exact\n * origin. Storage keyed only by name (`_snt_uid`, `_snt_asgn_*`,\n * `_snt_graph_nodes`) would then collide across projects — the visitor id in\n * particular, whose session row is keyed globally server-side, would let one\n * project's traffic land on another's session. Suffixing every browser key with\n * the apiKey prefix isolates projects, matching the queue's existing\n * `_snt_retry_${apiKey.slice(0,12)}` convention.\n *\n * Returns `''` when no apiKey is available (local mode) so keys stay stable\n * there.\n */\nexport function storageSuffix(apiKey?: string): string {\n return apiKey ? `_${apiKey.slice(0, 12)}` : '';\n}\n\n/**\n * The bare, pre-namespacing session cookie name. Still read as a FALLBACK\n * everywhere the suffixed name is read, so visitors who got their identity\n * before per-project namespacing keep it instead of being minted a fresh one.\n */\nexport const LEGACY_SESSION_COOKIE_NAME = '_snt_uid';\n\n/**\n * The one place the session cookie's name is decided. The writer (session.ts)\n * and every reader (core/server.ts SSR helper, graph sync, react devtools) must\n * call THIS — when namespacing landed, the writer moved to the suffixed name\n * while three readers kept the bare `_snt_uid`, so every SSR request for a\n * returning visitor missed the cookie and minted a fresh orphan session (quota\n * inflation, broken sticky assignments and persona continuity), and graph sync\n * sent `sessionId: undefined`. Deriving both sides from one function makes that\n * drift impossible, and index.test.ts pins the reader against the writer.\n */\nexport function sessionCookieName(apiKey?: string): string {\n return `${LEGACY_SESSION_COOKIE_NAME}${storageSuffix(apiKey)}`;\n}\n\n// Forget-me generation per project, on window so every bundle on the page\n// sees it (the snippet and its lazy chunks each carry their own copy of these\n// modules). Every client and queue captures it when created and persists only\n// while it is unchanged: a forget can never be undone by a later grant — the\n// old boolean marker was cleared by the next tracking client, and a paused\n// client's in-flight decide then wrote the forgotten visitor back (grader\n// NEW-1), as could its queues' failed final flush (F8).\nconst GENS = '__sntForgetGen';\ntype GenMap = Record<string, number>;\nconst genMap = (): GenMap | undefined => {\n try {\n return (window as unknown as Record<string, GenMap | undefined>)[GENS];\n } catch {\n return undefined;\n }\n};\nexport function markForgotten(apiKey: string): void {\n try {\n const w = window as unknown as Record<string, GenMap>;\n const m = (w[GENS] ??= {});\n m[apiKey] = (m[apiKey] ?? 0) + 1;\n } catch {\n /* no window */\n }\n}\n/** Bumped by every forget-me for this project in this page. */\nexport function forgetGeneration(apiKey: string): number {\n return genMap()?.[apiKey] ?? 0;\n}\n","/**\n * Slot declaration helpers shared by the browser client (decide) and the\n * server preload path. Pure wrappers over @sentientui/policy.\n */\nimport {\n canonicalArm,\n slotBaselineArm,\n slotResultFor,\n type SlotDecl,\n type SlotResult,\n} from '@sentientui/policy';\n\n/** SDK-facing slot declaration. `dims` accepts readonly arrays (`as const`). */\nexport type SlotDeclInput = {\n id: string;\n arms?: string[];\n dims?: Record<string, readonly string[]>;\n baseline?: string | Record<string, string>;\n};\n\nexport type { SlotResult };\n\n/**\n * Whitelists the wire fields of a slot declaration. Anything an SDK layer\n * attached (goal configs, refs, …) is stripped so it never reaches the zod\n * schema on the API. Also normalizes readonly arrays to mutable ones.\n */\nexport function toWireSlot(d: SlotDeclInput): SlotDecl {\n return {\n id: d.id,\n ...(d.arms ? { arms: [...d.arms] } : {}),\n ...(d.dims\n ? {\n dims: Object.fromEntries(\n Object.entries(d.dims).map(([dim, values]) => [dim, [...values]]),\n ),\n }\n : {}),\n ...(d.baseline !== undefined ? { baseline: d.baseline } : {}),\n };\n}\n\n/** The declared (or default first-declared) baseline result for a slot. */\nexport function baselineResultFor(d: SlotDeclInput): SlotResult {\n const decl = toWireSlot(d);\n return slotResultFor(decl, slotBaselineArm(decl));\n}\n\n/** Baseline results for a whole declaration list, keyed by slot id. */\nexport function baselineSlots(decls: SlotDeclInput[]): Record<string, SlotResult> {\n const out: Record<string, SlotResult> = {};\n for (const d of decls) out[d.id] = baselineResultFor(d);\n return out;\n}\n\n/**\n * Canonical arm string of a slot result: dims results encode as sorted\n * `dim=value` pairs joined with '|'; arms results are the arm id verbatim.\n */\nexport function armOfResult(result: SlotResult): string {\n return typeof result === 'string' ? result : canonicalArm(result);\n}\n","/**\n * Server-side helpers for SSR variant pre-loading.\n * Pure fetch — no DOM APIs. Safe in Node.js, Edge, and Deno runtimes.\n */\nimport { buildSessionUpsertPayload } from './session-meta.js';\nimport { LEGACY_SESSION_COOKIE_NAME, sessionCookieName } from './storage-key.js';\nimport {\n toWireSlot,\n baselineResultFor,\n baselineSlots,\n type SlotDeclInput,\n type SlotResult,\n} from './slots.js';\n\nimport type { SlotConfigEntry } from './snapshot.js';\nimport type { RenderCaps } from './region-skeleton.js';\nimport type { SitePalette } from './blocks.js';\n\nexport type { SlotDeclInput, SlotResult, SlotConfigEntry, SitePalette };\n\nexport type ServerAssignConfig = {\n /** Public API key (pk_...). */\n apiKey: string;\n /**\n * Base URL of the Sentient API without trailing slash.\n * e.g. 'https://api.yourapp.com/v1'\n */\n baseUrl: string;\n /**\n * Browser origin of your app (e.g. `http://localhost:3001`). Required for `pk_`\n * keys — server-side fetch must send the same `Origin` the API allows.\n */\n origin?: string;\n /**\n * Optional: this project's SECRET key (sk_...), read from a server-only env\n * var. When set, SSR calls also send it as `X-Sentient-Server-Key`, which\n * proves they come from your server: the API then holds them to your plan's\n * per-key limit instead of the 100 requests/min per-IP cap meant for\n * browsers — without it, all SSR traffic from one server address shares that\n * one cap. Never set this in code that ships to the browser; it is ignored\n * (and not sent) when `window` exists.\n */\n serverKey?: string;\n /** From `User-Agent` request header (Next.js `headers()`). */\n userAgent?: string;\n /** From `Referer` request header. */\n referer?: string;\n utmParams?: Record<string, string>;\n /**\n * Ad-platform click IDs (gclid, fbclid, ttclid, …) from the landing URL.\n * Derive both this and `utmParams` with `extractTrackedParams(searchParams)`\n * — the Referer header never carries the landing page's own query string, so\n * without these two fields SSR-minted sessions have no campaign attribution\n * until the client SDK hydrates.\n */\n clickIds?: Record<string, string>;\n /**\n * Set true when the request carries a tracking opt-out — `DNT: 1` or\n * `Sec-GPC: 1`. When set, the SSR helpers skip the session upsert and the\n * assign/decide call entirely: the page renders defaults/baseline and no\n * session row is minted for the visitor (audit P4). The client SDK already\n * no-ops for these visitors; this keeps the server from minting a session +\n * assignment on every page view before the client can.\n */\n doNotTrack?: boolean;\n /**\n * Declared persona — the role your app already knows for this visitor\n * (e.g. from your auth context during SSR). Same contract as the client\n * option: must be a vocabulary key; unrecognized values are ignored\n * server-side. Never a user id or email.\n */\n persona?: string;\n /**\n * Milliseconds to wait for the API before returning default variants.\n * Prevents slow/cold API from blocking SSR. Defaults to 1000 — the hot path\n * is served from in-process caches and typically returns in well under\n * 150 ms. The full 1 s budget is only reached on a cold start or an API\n * geographically distant from your SSR host, after which defaults render\n * with no layout shift. Lower it if your API is co-located and warm.\n */\n timeoutMs?: number;\n};\n\n/** Header carrying `serverKey` (apps/api lib/rate-limit.ts SERVER_KEY_HEADER). */\nexport const SERVER_KEY_HEADER = 'X-Sentient-Server-Key';\n\n/** Auth headers for an SSR call: the pk_, its Origin, and the optional server proof. */\nfunction ssrHeaders(config: ServerAssignConfig): Record<string, string> {\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${config.apiKey}`,\n };\n if (config.origin) headers.Origin = config.origin;\n // A secret key must never leave a browser: if this module was bundled\n // client-side by mistake, drop it rather than send it.\n if (config.serverKey && typeof window === 'undefined') headers[SERVER_KEY_HEADER] = config.serverKey;\n return headers;\n}\n\n/** componentId → assigned variantId */\nexport type ServerAssignments = Record<string, string>;\n\ntype AssignResult = { variantId: string; assignmentTtlMs: number };\n\nconst DEFAULT_TIMEOUT_MS = 1000;\n\nfunction fetchWithTimeout(\n url: string,\n init: RequestInit,\n timeoutMs: number,\n): Promise<Response> {\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), timeoutMs);\n return fetch(url, { ...init, signal: controller.signal }).finally(() =>\n clearTimeout(timer),\n );\n}\n\n/**\n * Fetches variant assignments server-side for all listed components.\n * Returns a map suitable for passing as `initialAssignments` to `<AdaptiveProvider>`.\n *\n * Call from Next.js layout, Server Component, or getServerSideProps.\n *\n * @example\n * ```tsx\n * const assignments = await preloadAssignments(\n * [\n * { id: 'hero', variantIds: ['hero-a', 'hero-b'] },\n * { id: 'cta', variantIds: ['cta-short', 'cta-long'] },\n * ],\n * sessionId, // read from cookies() or req.cookies\n * { apiKey: process.env.NEXT_PUBLIC_SENTIENT_API_KEY!, baseUrl: 'https://api.sentient-ui.com/v1' },\n * );\n * return <AdaptiveProvider ... initialAssignments={assignments}>{children}</AdaptiveProvider>;\n * ```\n */\nexport async function preloadAssignments(\n components: Array<{ id: string; variantIds: string[] }>,\n sessionId: string,\n config: ServerAssignConfig,\n): Promise<ServerAssignments> {\n // Opted-out visitor (DNT/GPC): render defaults, mint no session (audit P4).\n if (config.doNotTrack) return {};\n\n const timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n const headers = ssrHeaders(config);\n\n // Session metadata must match the browser SDK so assign seeds variant_weights\n // under the same segment (not `unknown:unknown`).\n const sessionBody = {\n ...buildSessionUpsertPayload(sessionId, {\n userAgent: config.userAgent,\n referer: config.referer,\n utmParams: config.utmParams,\n clickIds: config.clickIds,\n appOrigin: config.origin,\n }),\n ...(config.persona ? { persona: config.persona } : {}),\n };\n\n try {\n const res = await fetchWithTimeout(\n `${config.baseUrl}/sessions`,\n { method: 'POST', headers, body: JSON.stringify(sessionBody) },\n timeoutMs,\n );\n if (res.status === 402) {\n console.warn(\n '[SentientUI] Session limit exceeded for this project. The bandit will stop learning until the limit resets. Upgrade at sentient-ui.com/pricing',\n );\n } else if (!res.ok) {\n const body = await res.json().catch(() => ({}));\n console.error(`[SentientUI] preloadAssignments: session upsert failed (${res.status})`, body);\n }\n } catch (err) {\n console.error('[SentientUI] preloadAssignments: session upsert threw', err);\n }\n\n const results = await Promise.allSettled(\n components.map(async ({ id, variantIds }) => {\n const res = await fetchWithTimeout(\n `${config.baseUrl}/assign`,\n { method: 'POST', headers, body: JSON.stringify({ sessionId, componentId: id, variantIds }) },\n timeoutMs,\n );\n if (!res.ok) {\n const body = await res.json().catch(() => ({}));\n console.error(`[SentientUI] preloadAssignments: assign failed for \"${id}\" (${res.status})`, body);\n return null;\n }\n const body = (await res.json()) as AssignResult;\n return { id, variantId: body.variantId };\n }),\n );\n\n const assignments: ServerAssignments = {};\n for (const result of results) {\n if (result.status === 'fulfilled' && result.value) {\n assignments[result.value.id] = result.value.variantId;\n }\n }\n return assignments;\n}\n\n/**\n * Reads the Sentient session cookie from a Next.js `ReadonlyRequestCookies` object\n * (the return value of `cookies()` from `next/headers`), or any object with a\n * `get(name: string)` method. Returns null if the cookie is absent.\n *\n * Pass the project's `apiKey`: the client writes the per-project SUFFIXED name\n * (`sessionCookieName` — see storage-key.ts), so reading only the bare\n * `_snt_uid` missed the cookie on every SSR request for a returning visitor and\n * minted a fresh orphan session each page view (quota inflation, broken sticky\n * assignments and persona continuity). The bare name is still read as a\n * fallback for identities minted before namespacing.\n */\nexport function readSessionCookie(\n cookies: { get(name: string): { value: string } | undefined },\n apiKey?: string,\n): string | null {\n return (\n (apiKey ? cookies.get(sessionCookieName(apiKey))?.value : undefined) ??\n cookies.get(LEGACY_SESSION_COOKIE_NAME)?.value ??\n null\n );\n}\n\nexport type DecideResult = {\n layoutOrder: string[];\n assignments: Record<string, string>;\n /** Slot results keyed by slot id. Baseline-resolved when the API omits/fails them. */\n slots: Record<string, SlotResult>;\n persona: string;\n confidence: number;\n /** Registry mode only: content/ops/blocks for server-defined slots. */\n slotConfig?: Record<string, SlotConfigEntry>;\n /** Registry mode only: site palette for block rendering. */\n palette?: SitePalette;\n /** Registry mode only: site styles the served Redesign arms borrow. */\n vocabulary?: import('./style-vocabulary.js').StyleVocabulary;\n};\n\n/**\n * Single-roundtrip SSR call returning layout order, component assignments,\n * and adaptive-slot results. Falls back to default section order + empty\n * assignments + baseline slots if the API is unavailable. A response without\n * a `slots` field means the server predates slots — every declared slot\n * resolves to its baseline (no retry).\n */\nexport async function preloadDecisions(\n params: {\n sections?: string[];\n components: Array<{ id: string; variantIds?: string[] }>;\n slots?: SlotDeclInput[];\n /** 'registry' serves the project's published slot_definitions as if declared\n * (and is the only way slotConfig/palette come back). Default 'request'.\n * Requires `registrySlotIds`: the `<Adaptive id>`s THIS page renders. */\n slotsFrom?: 'request' | 'registry';\n /**\n * Registry mode: decide only these published slot ids. Close-out turns\n * every slot decision into a trial without checking an exposure, so an\n * unscoped registry decide accrues trials — and session-level credit — for\n * every published slot on every page, including ones this page never\n * renders (CONTRACTS §2). Omitting it in registry mode is refused: the\n * call downgrades to request mode with one console.error, rather than\n * silently minting those trials.\n */\n registrySlotIds?: string[];\n /**\n * Registry mode: what each slot on this page can render (CONTRACTS §2).\n * The server has no DOM here, so no fingerprint is sent and a Rewrite arm\n * is assumed to match; a real mismatch is reported from the browser as\n * drift. Declare `forms: false` for slots without an `onFormSubmit`, or a\n * form arm can be drawn that this page will refuse. Default per slot:\n * `{ forms: true, compose: true }`.\n */\n renderCaps?: Record<string, Omit<RenderCaps, 'fp'>>;\n },\n sessionId: string,\n config: ServerAssignConfig,\n): Promise<DecideResult> {\n const timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n const declaredSlots = params.slots ?? [];\n let registryIds: string[] | null = null;\n if (params.slotsFrom === 'registry') {\n if (Array.isArray(params.registrySlotIds)) {\n registryIds = params.registrySlotIds;\n } else {\n console.error(\n \"[SentientUI] preloadDecisions: slotsFrom: 'registry' needs registrySlotIds (the <Adaptive id>s this page renders). \" +\n 'An unscoped registry decide records a trial for every published slot on every page; falling back to request mode.',\n );\n }\n }\n const fallback: DecideResult = {\n layoutOrder: params.sections ?? [],\n assignments: {},\n slots: baselineSlots(declaredSlots),\n persona: 'unknown',\n confidence: 0,\n };\n\n // Opted-out visitor (DNT/GPC): baseline layout/slots, mint no session (audit P4).\n if (config.doNotTrack) return fallback;\n\n const headers = ssrHeaders(config);\n\n const sessionBody = {\n ...buildSessionUpsertPayload(sessionId, {\n userAgent: config.userAgent,\n referer: config.referer,\n utmParams: config.utmParams,\n clickIds: config.clickIds,\n appOrigin: config.origin,\n }),\n ...(config.persona ? { persona: config.persona } : {}),\n };\n\n try {\n const sessionRes = await fetchWithTimeout(\n `${config.baseUrl}/sessions`,\n { method: 'POST', headers, body: JSON.stringify(sessionBody) },\n timeoutMs,\n );\n if (!sessionRes.ok) {\n const body = await sessionRes.json().catch(() => ({}));\n console.error(`[SentientUI] preloadDecisions: session upsert failed (${sessionRes.status})`, body);\n }\n } catch (err) {\n console.error('[SentientUI] preloadDecisions: session upsert threw', err);\n }\n\n try {\n const res = await fetchWithTimeout(\n `${config.baseUrl}/decide`,\n {\n method: 'POST',\n headers,\n body: JSON.stringify({\n sessionId,\n sections: (params.sections ?? []).map((id) => ({ id })),\n components: params.components,\n ...(declaredSlots.length > 0 ? { slots: declaredSlots.map(toWireSlot) } : {}),\n // bootstrap:false — editor goals and the section map are snippet\n // data the React SDK never reads. An EMPTY id list is meaningful\n // (\"nothing published is on this page\"): zero trials, still a decide.\n ...(registryIds !== null\n ? {\n slotsFrom: 'registry',\n registrySlotIds: registryIds,\n bootstrap: false,\n // Always sent, so the server knows this is an SDK that can\n // render Rewrite arms — no `render` field means legacy.\n render: Object.fromEntries(\n // compose: true — the React SDK (the SSR consumer) renders\n // Redesign trees since native generation phase 2.\n registryIds.map((id) => [id, params.renderCaps?.[id] ?? { forms: true, compose: true }]),\n ),\n }\n : {}),\n ...(config.persona ? { persona: config.persona } : {}),\n }),\n },\n timeoutMs,\n );\n if (!res.ok) {\n const body = await res.json().catch(() => ({}));\n console.error(`[SentientUI] preloadDecisions: decide failed (${res.status})`, body);\n return fallback;\n }\n const data = (await res.json()) as {\n layoutOrder?: string[];\n assignments?: Record<string, string>;\n slots?: Record<string, SlotResult>;\n slotConfig?: Record<string, SlotConfigEntry>;\n palette?: SitePalette;\n vocabulary?: import('./style-vocabulary.js').StyleVocabulary;\n persona?: string;\n confidence?: number;\n };\n\n const slots: Record<string, SlotResult> = {};\n for (const d of declaredSlots) {\n // `data.slots === undefined` ⇒ server predates slots: baseline, no retry.\n slots[d.id] = data.slots?.[d.id] ?? baselineResultFor(d);\n }\n // Registry mode returns slots the request never declared — union them in\n // (same rule as the browser client), or an SSR page gets results for none\n // of its registry slots.\n for (const [slotId, result] of Object.entries(data.slots ?? {})) {\n if (!(slotId in slots)) slots[slotId] = result;\n }\n\n // Plain-object guard only (readSnapshot's rule): the server total-validated\n // the config at publish; a deep re-validation here would just drift.\n const slotConfigOk =\n data.slotConfig !== undefined && typeof data.slotConfig === 'object' && data.slotConfig !== null && !Array.isArray(data.slotConfig);\n\n return {\n layoutOrder: data.layoutOrder ?? params.sections ?? [],\n assignments: data.assignments ?? {},\n slots,\n persona: data.persona ?? 'unknown',\n confidence: data.confidence ?? 0,\n ...(slotConfigOk ? { slotConfig: data.slotConfig } : {}),\n ...(data.palette ? { palette: data.palette } : {}),\n ...(data.vocabulary ? { vocabulary: data.vocabulary } : {}),\n };\n } catch (err) {\n console.error('[SentientUI] preloadDecisions: decide threw', err);\n return fallback;\n }\n}\n","// Server-side capture of AI-assistant fetches, for any framework.\n// Spec: docs/superpowers/specs/2026-09-23-server-side-agent-capture-design.md §4.1\n//\n// Assistants that fetch a page without running JavaScript (ChatGPT-User,\n// Claude-User, Perplexity-User, GPTBot, …) never execute the snippet or the\n// React SDK, so only the server that answered can see them. Until this, only\n// Next.js AdaptiveRoot logged them; every other site read \"no AI traffic\",\n// which is wrong rather than empty.\n//\n// OBSERVATION ONLY. Nothing here may change a response based on the user\n// agent: that is cloaking, and SentientUI never claims to adapt serving to\n// agents. These functions return nothing a caller could branch on except\n// \"did this look like an agent\", and log to crawler_requests — never to\n// sessions, never to training, never to billing.\n\nimport { matchedAgentToken } from './session-meta.js';\n\nconst DEFAULT_API_BASE_URL = 'https://api.sentient-ui.com/v1';\n\nexport type AgentCaptureOptions = {\n /** Your public `pk_` key — the same one the snippet uses. */\n apiKey: string;\n /** API base ending in `/v1`. Defaults to the hosted API. */\n baseUrl?: string;\n /** Which capture path saw the fetch. Shown per row on the dashboard. */\n source?: 'middleware' | 'edge' | 'ssr';\n /**\n * REQUIRED on edge runtimes (Vercel Routing Middleware, Cloudflare Workers,\n * Netlify Edge): they cancel outstanding work once the response is\n * returned, so a fire-and-forget request without it is silently dropped.\n * Pass the platform's `waitUntil` (`ctx.waitUntil.bind(ctx)` on Workers,\n * `waitUntil` from `@vercel/functions`). Node servers do not need it.\n */\n waitUntil?: (p: Promise<unknown>) => void;\n /** Injectable for tests. */\n fetchImpl?: typeof fetch;\n};\n\n/** The minimum of a request both the Fetch API `Request` and hand-rolled\n * objects satisfy. */\nexport type CapturableRequest = {\n url: string;\n headers: { get(name: string): string | null };\n};\n\n/** Pathname only: a query string can carry tokens, emails or campaign ids. */\nfunction pathOf(url: string): string {\n try {\n return new URL(url, 'http://localhost').pathname || '/';\n } catch {\n return url.split(/[?#]/, 1)[0] || '/';\n }\n}\n\n/**\n * Low-level sender: posts one agent fetch to `/v1/crawler-events`. Never\n * throws, never blocks. The API re-derives the agent from `userAgent`\n * itself, so `botName` is advisory.\n */\nexport function postAgentFetch(\n entry: { path: string; userAgent: string; botName: string },\n opts: AgentCaptureOptions,\n): void {\n const doFetch = opts.fetchImpl ?? (typeof fetch === 'function' ? fetch : undefined);\n if (!doFetch || !opts.apiKey) return;\n try {\n const p = doFetch(`${opts.baseUrl ?? DEFAULT_API_BASE_URL}/crawler-events`, {\n method: 'POST',\n headers: { 'content-type': 'application/json', authorization: `Bearer ${opts.apiKey}` },\n body: JSON.stringify({\n path: entry.path,\n botName: entry.botName,\n userAgent: entry.userAgent,\n source: opts.source ?? 'middleware',\n }),\n }).catch(() => undefined);\n opts.waitUntil?.(p);\n } catch {\n /* capture must never break the page it is observing */\n }\n}\n\n/**\n * Log this request if its user agent is a known AI assistant or crawler.\n * Works with a Fetch API `Request` (edge runtimes, Hono, Remix / React\n * Router, Astro, SvelteKit) or anything with `url` + `headers.get`.\n *\n * Returns whether the request matched, so a caller can skip its own work;\n * it must NOT be used to serve anything different. Non-matching requests —\n * nearly all of them — make no network call.\n */\nexport function captureAgentRequest(req: CapturableRequest, opts: AgentCaptureOptions): boolean {\n let userAgent = '';\n try {\n userAgent = req.headers.get('user-agent') ?? '';\n } catch {\n return false;\n }\n const botName = matchedAgentToken(userAgent);\n if (!botName) return false;\n postAgentFetch({ path: pathOf(req.url), userAgent, botName }, opts);\n return true;\n}\n\ntype ConnectRequest = {\n url?: string;\n originalUrl?: string;\n headers: Record<string, string | string[] | undefined>;\n};\n\n/**\n * Connect-style middleware (Express, Nitro / Nuxt on Node, Fastify via\n * middie, any `(req, res, next)` stack). Calls `next()` synchronously and\n * logs in the background; it never touches the response.\n */\nexport function sentientAgentMiddleware(\n opts: Omit<AgentCaptureOptions, 'waitUntil' | 'source'>,\n): (req: ConnectRequest, res: unknown, next: (err?: unknown) => void) => void {\n return (req, _res, next) => {\n try {\n const raw = req.headers['user-agent'];\n const ua = Array.isArray(raw) ? raw[0] ?? '' : raw ?? '';\n captureAgentRequest(\n { url: req.originalUrl ?? req.url ?? '/', headers: { get: (n) => (n.toLowerCase() === 'user-agent' ? ua : null) } },\n { ...opts, source: 'middleware' },\n );\n } catch {\n /* never block the request */\n }\n next();\n };\n}\n"],"mappings":"kxBAAA,IAAAA,GAAA,GAAAC,GAAAD,GAAA,mBAAAE,EAAA,8BAAAC,EAAA,wBAAAC,EAAA,yBAAAC,EAAA,sBAAAC,EAAA,oBAAAC,EAAA,wBAAAC,EAAA,yBAAAC,EAAA,mBAAAC,EAAA,uBAAAC,EAAA,qBAAAC,GAAA,sBAAAC,GAAA,8BAAAC,EAAA,4BAAAC,KAAA,eAAAC,GAAAhB,ICQO,IAAMiB,GAAiC,CAC5C,SACA,eACA,gBACA,YACA,cACA,mBACA,gBACA,kBACA,kBACA,oBACA,qBACA,aACA,QACA,YACA,YACA,SACF,EAGO,SAASC,GAAaC,EAA4B,CACvD,OAAOC,EAAkBD,CAAS,IAAM,IAC1C,CAGO,SAASC,EAAkBD,EAAkC,CAjCpE,IAAAE,EAkCE,GAAI,CAACF,EAAW,OAAO,KACvB,IAAMG,EAAIH,EAAU,YAAY,EAChC,OAAOE,EAAAJ,GAAY,KAAMM,GAAUD,EAAE,SAASC,EAAM,YAAY,CAAC,CAAC,IAA3D,KAAAF,EAAgE,IACzE,CA8CO,SAASG,EAAkBC,EAA2B,CAC3D,IAAMC,EAAID,EAAU,YAAY,EAChC,MAAI,mCAAmC,KAAKC,CAAC,EAAU,SACnD,yCAAyC,KAAKA,CAAC,EAAU,SACtD,SACT,CAEO,SAASC,EAAoBC,EAAkBC,EAA4B,CAChF,GAAI,CAACD,EAAU,MAAO,SACtB,GAAI,CACF,IAAME,EAAS,IAAI,IAAIF,CAAQ,EAC/B,GAAIC,EACF,GAAI,CACF,GAAI,IAAI,IAAIA,CAAS,EA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,GAAOA,EAAE,YAAY,IAAM,aAAeD,EAAK,IAAM,CAAE,EAClHE,EAAAC,EAAA,GAAKpB,GAAL,CAAW,OAAQ,YAAa,EAClC,CACF,OAAQO,EAAA,CAER,CACAQ,EAAK,CACP,CACF","names":["index_server_exports","__export","CLICK_ID_KEYS","buildSessionUpsertPayload","captureAgentRequest","deriveSessionSegment","detectDeviceClass","detectTimeOfDay","detectTrafficSource","extractTrackedParams","postAgentFetch","preloadAssignments","preloadDecisions","readSessionCookie","referrerDomainFromReferer","sentientAgentMiddleware","__toCommonJS","agentUaList","uaTokenMatch","userAgent","matchedAgentToken","_a","s","token","detectDeviceClass","userAgent","s","detectTrafficSource","referrer","appOrigin","refUrl","e","host","referrerDomainFromReferer","CLICK_ID_KEYS","extractTrackedParams","search","utmParams","clickIds","entries","k","v","first","detectTimeOfDay","d","h","deriveSessionSegment","opts","body","buildSessionUpsertPayload","sessionId","_a","_b","_c","_d","_e","_f","_g","_h","ua","referer","now","uaTokenMatch","storageSuffix","apiKey","LEGACY_SESSION_COOKIE_NAME","sessionCookieName","import_policy","toWireSlot","d","__spreadValues","dim","values","baselineResultFor","decl","baselineSlots","decls","out","SERVER_KEY_HEADER","ssrHeaders","config","headers","DEFAULT_TIMEOUT_MS","fetchWithTimeout","url","init","timeoutMs","controller","timer","__spreadProps","__spreadValues","preloadAssignments","components","sessionId","_a","sessionBody","buildSessionUpsertPayload","res","body","err","results","id","variantIds","assignments","result","readSessionCookie","cookies","apiKey","_b","_c","_d","sessionCookieName","LEGACY_SESSION_COOKIE_NAME","preloadDecisions","params","_e","_f","_g","_h","_i","_j","_k","_l","declaredSlots","registryIds","fallback","baselineSlots","sessionRes","toWireSlot","data","slots","baselineResultFor","slotId","slotConfigOk","DEFAULT_API_BASE_URL","pathOf","url","postAgentFetch","entry","opts","_a","_b","_c","_d","doFetch","p","e","captureAgentRequest","req","userAgent","botName","matchedAgentToken","sentientAgentMiddleware","_res","next","raw","ua","n","__spreadProps","__spreadValues"]}
|
package/dist/index-server.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{c as j,g as L,h as B,i as J,j as V,k as Y,l as z,m as H,n as R,o as E,p as N,q as _}from"./chunk-735EJYJX.mjs";import{b as D,c as T}from"./chunk-J5EL7HKC.mjs";import{a as c,b}from"./chunk-TMCGHANO.mjs";var W="X-Sentient-Server-Key";function K(t){let r={"Content-Type":"application/json",Authorization:`Bearer ${t.apiKey}`};return t.origin&&(r.Origin=t.origin),t.serverKey&&typeof window=="undefined"&&(r[W]=t.serverKey),r}var $=1e3;function v(t,r,e){let o=new AbortController,s=setTimeout(()=>o.abort(),e);return fetch(t,b(c({},r),{signal:o.signal})).finally(()=>clearTimeout(s))}async function G(t,r,e){var m;if(e.doNotTrack)return{};let o=(m=e.timeoutMs)!=null?m:$,s=K(e),a=c(c({},R(r,{userAgent:e.userAgent,referer:e.referer,utmParams:e.utmParams,clickIds:e.clickIds,appOrigin:e.origin})),e.persona?{persona:e.persona}:{});try{let n=await v(`${e.baseUrl}/sessions`,{method:"POST",headers:s,body:JSON.stringify(a)},o);if(n.status===402)console.warn("[SentientUI] Session limit exceeded for this project. The bandit will stop learning until the limit resets. Upgrade at sentient-ui.com/pricing");else if(!n.ok){let y=await n.json().catch(()=>({}));console.error(`[SentientUI] preloadAssignments: session upsert failed (${n.status})`,y)}}catch(n){console.error("[SentientUI] preloadAssignments: session upsert threw",n)}let p=await Promise.allSettled(t.map(async({id:n,variantIds:y})=>{let g=await v(`${e.baseUrl}/assign`,{method:"POST",headers:s,body:JSON.stringify({sessionId:r,componentId:n,variantIds:y})},o);if(!g.ok){let S=await g.json().catch(()=>({}));return console.error(`[SentientUI] preloadAssignments: assign failed for "${n}" (${g.status})`,S),null}let f=await g.json();return{id:n,variantId:f.variantId}})),l={};for(let n of p)n.status==="fulfilled"&&n.value&&(l[n.value.id]=n.value.variantId);return l}function X(t,r){var e,o,s,a;return(a=(s=r?(e=t.get(T(r)))==null?void 0:e.value:void 0)!=null?s:(o=t.get(D))==null?void 0:o.value)!=null?a:null}async function Q(t,r,e){var n,y,g,f,S,C,I,w,O,U,k,P;let o=(n=e.timeoutMs)!=null?n:$,s=(y=t.slots)!=null?y:[],a=null;t.slotsFrom==="registry"&&(Array.isArray(t.registrySlotIds)?a=t.registrySlotIds:console.error("[SentientUI] preloadDecisions: slotsFrom: 'registry' needs registrySlotIds (the <Adaptive id>s this page renders). An unscoped registry decide records a trial for every published slot on every page; falling back to request mode."));let p={layoutOrder:(g=t.sections)!=null?g:[],assignments:{},slots:_(s),persona:"unknown",confidence:0};if(e.doNotTrack)return p;let l=K(e),m=c(c({},R(r,{userAgent:e.userAgent,referer:e.referer,utmParams:e.utmParams,clickIds:e.clickIds,appOrigin:e.origin})),e.persona?{persona:e.persona}:{});try{let d=await v(`${e.baseUrl}/sessions`,{method:"POST",headers:l,body:JSON.stringify(m)},o);if(!d.ok){let i=await d.json().catch(()=>({}));console.error(`[SentientUI] preloadDecisions: session upsert failed (${d.status})`,i)}}catch(d){console.error("[SentientUI] preloadDecisions: session upsert threw",d)}try{let d=await v(`${e.baseUrl}/decide`,{method:"POST",headers:l,body:JSON.stringify(c(c(c({sessionId:r,sections:((f=t.sections)!=null?f:[]).map(u=>({id:u})),components:t.components},s.length>0?{slots:s.map(E)}:{}),a!==null?{slotsFrom:"registry",registrySlotIds:a,bootstrap:!1,render:Object.fromEntries(a.map(u=>{var A,x;return[u,(x=(A=t.renderCaps)==null?void 0:A[u])!=null?x:{forms:!0,compose:!0}]}))}:{}),e.persona?{persona:e.persona}:{}))},o);if(!d.ok){let u=await d.json().catch(()=>({}));return console.error(`[SentientUI] preloadDecisions: decide failed (${d.status})`,u),p}let i=await d.json(),h={};for(let u of s)h[u.id]=(C=(S=i.slots)==null?void 0:S[u.id])!=null?C:N(u);for(let[u,A]of Object.entries((I=i.slots)!=null?I:{}))u in h||(h[u]=A);let q=i.slotConfig!==void 0&&typeof i.slotConfig=="object"&&i.slotConfig!==null&&!Array.isArray(i.slotConfig);return c(c(c({layoutOrder:(O=(w=i.layoutOrder)!=null?w:t.sections)!=null?O:[],assignments:(U=i.assignments)!=null?U:{},slots:h,persona:(k=i.persona)!=null?k:"unknown",confidence:(P=i.confidence)!=null?P:0},q?{slotConfig:i.slotConfig}:{}),i.palette?{palette:i.palette}:{}),i.vocabulary?{vocabulary:i.vocabulary}:{})}catch(d){return console.error("[SentientUI] preloadDecisions: decide threw",d),p}}var Z="https://api.sentient-ui.com/v1";function ee(t){try{return new URL(t,"http://localhost").pathname||"/"}catch(r){return t.split(/[?#]/,1)[0]||"/"}}function F(t,r){var o,s,a,p;let e=(o=r.fetchImpl)!=null?o:typeof fetch=="function"?fetch:void 0;if(!(!e||!r.apiKey))try{let l=e(`${(s=r.baseUrl)!=null?s:Z}/crawler-events`,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${r.apiKey}`},body:JSON.stringify({path:t.path,botName:t.botName,userAgent:t.userAgent,source:(a=r.source)!=null?a:"middleware"})}).catch(()=>{});(p=r.waitUntil)==null||p.call(r,l)}catch(l){}}function M(t,r){var s;let e="";try{e=(s=t.headers.get("user-agent"))!=null?s:""}catch(a){return!1}let o=j(e);return o?(F({path:ee(t.url),userAgent:e,botName:o},r),!0):!1}function te(t){return(r,e,o)=>{var s,a,p;try{let l=r.headers["user-agent"],m=Array.isArray(l)?(s=l[0])!=null?s:"":l!=null?l:"";M({url:(p=(a=r.originalUrl)!=null?a:r.url)!=null?p:"/",headers:{get:n=>n.toLowerCase()==="user-agent"?m:null}},b(c({},t),{source:"middleware"}))}catch(l){}o()}}export{V as CLICK_ID_KEYS,R as buildSessionUpsertPayload,M as captureAgentRequest,H as deriveSessionSegment,L as detectDeviceClass,z as detectTimeOfDay,B as detectTrafficSource,Y as extractTrackedParams,F as postAgentFetch,G as preloadAssignments,Q as preloadDecisions,X as readSessionCookie,J as referrerDomainFromReferer,te as sentientAgentMiddleware};
|
|
2
2
|
//# sourceMappingURL=index-server.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/server.ts","../src/agent-capture.ts"],"sourcesContent":["/**\n * Server-side helpers for SSR variant pre-loading.\n * Pure fetch — no DOM APIs. Safe in Node.js, Edge, and Deno runtimes.\n */\nimport { buildSessionUpsertPayload } from './session-meta.js';\nimport { LEGACY_SESSION_COOKIE_NAME, sessionCookieName } from './storage-key.js';\nimport {\n toWireSlot,\n baselineResultFor,\n baselineSlots,\n type SlotDeclInput,\n type SlotResult,\n} from './slots.js';\n\nimport type { SlotConfigEntry } from './snapshot.js';\nimport type { RenderCaps } from './region-skeleton.js';\nimport type { SitePalette } from './blocks.js';\n\nexport type { SlotDeclInput, SlotResult, SlotConfigEntry, SitePalette };\n\nexport type ServerAssignConfig = {\n /** Public API key (pk_...). */\n apiKey: string;\n /**\n * Base URL of the Sentient API without trailing slash.\n * e.g. 'https://api.yourapp.com/v1'\n */\n baseUrl: string;\n /**\n * Browser origin of your app (e.g. `http://localhost:3001`). Required for `pk_`\n * keys — server-side fetch must send the same `Origin` the API allows.\n */\n origin?: string;\n /** From `User-Agent` request header (Next.js `headers()`). */\n userAgent?: string;\n /** From `Referer` request header. */\n referer?: string;\n utmParams?: Record<string, string>;\n /**\n * Ad-platform click IDs (gclid, fbclid, ttclid, …) from the landing URL.\n * Derive both this and `utmParams` with `extractTrackedParams(searchParams)`\n * — the Referer header never carries the landing page's own query string, so\n * without these two fields SSR-minted sessions have no campaign attribution\n * until the client SDK hydrates.\n */\n clickIds?: Record<string, string>;\n /**\n * Set true when the request carries a tracking opt-out — `DNT: 1` or\n * `Sec-GPC: 1`. When set, the SSR helpers skip the session upsert and the\n * assign/decide call entirely: the page renders defaults/baseline and no\n * session row is minted for the visitor (audit P4). The client SDK already\n * no-ops for these visitors; this keeps the server from minting a session +\n * assignment on every page view before the client can.\n */\n doNotTrack?: boolean;\n /**\n * Declared persona — the role your app already knows for this visitor\n * (e.g. from your auth context during SSR). Same contract as the client\n * option: must be a vocabulary key; unrecognized values are ignored\n * server-side. Never a user id or email.\n */\n persona?: string;\n /**\n * Milliseconds to wait for the API before returning default variants.\n * Prevents slow/cold API from blocking SSR. Defaults to 1000 — the hot path\n * is served from in-process caches and typically returns in well under\n * 150 ms. The full 1 s budget is only reached on a cold start or an API\n * geographically distant from your SSR host, after which defaults render\n * with no layout shift. Lower it if your API is co-located and warm.\n */\n timeoutMs?: number;\n};\n\n/** componentId → assigned variantId */\nexport type ServerAssignments = Record<string, string>;\n\ntype AssignResult = { variantId: string; assignmentTtlMs: number };\n\nconst DEFAULT_TIMEOUT_MS = 1000;\n\nfunction fetchWithTimeout(\n url: string,\n init: RequestInit,\n timeoutMs: number,\n): Promise<Response> {\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), timeoutMs);\n return fetch(url, { ...init, signal: controller.signal }).finally(() =>\n clearTimeout(timer),\n );\n}\n\n/**\n * Fetches variant assignments server-side for all listed components.\n * Returns a map suitable for passing as `initialAssignments` to `<AdaptiveProvider>`.\n *\n * Call from Next.js layout, Server Component, or getServerSideProps.\n *\n * @example\n * ```tsx\n * const assignments = await preloadAssignments(\n * [\n * { id: 'hero', variantIds: ['hero-a', 'hero-b'] },\n * { id: 'cta', variantIds: ['cta-short', 'cta-long'] },\n * ],\n * sessionId, // read from cookies() or req.cookies\n * { apiKey: process.env.NEXT_PUBLIC_SENTIENT_API_KEY!, baseUrl: 'https://api.sentient-ui.com/v1' },\n * );\n * return <AdaptiveProvider ... initialAssignments={assignments}>{children}</AdaptiveProvider>;\n * ```\n */\nexport async function preloadAssignments(\n components: Array<{ id: string; variantIds: string[] }>,\n sessionId: string,\n config: ServerAssignConfig,\n): Promise<ServerAssignments> {\n // Opted-out visitor (DNT/GPC): render defaults, mint no session (audit P4).\n if (config.doNotTrack) return {};\n\n const timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${config.apiKey}`,\n };\n if (config.origin) {\n headers.Origin = config.origin;\n }\n\n // Session metadata must match the browser SDK so assign seeds variant_weights\n // under the same segment (not `unknown:unknown`).\n const sessionBody = {\n ...buildSessionUpsertPayload(sessionId, {\n userAgent: config.userAgent,\n referer: config.referer,\n utmParams: config.utmParams,\n clickIds: config.clickIds,\n appOrigin: config.origin,\n }),\n ...(config.persona ? { persona: config.persona } : {}),\n };\n\n try {\n const res = await fetchWithTimeout(\n `${config.baseUrl}/sessions`,\n { method: 'POST', headers, body: JSON.stringify(sessionBody) },\n timeoutMs,\n );\n if (res.status === 402) {\n console.warn(\n '[SentientUI] Session limit exceeded for this project. The bandit will stop learning until the limit resets. Upgrade at sentient-ui.com/pricing',\n );\n } else if (!res.ok) {\n const body = await res.json().catch(() => ({}));\n console.error(`[SentientUI] preloadAssignments: session upsert failed (${res.status})`, body);\n }\n } catch (err) {\n console.error('[SentientUI] preloadAssignments: session upsert threw', err);\n }\n\n const results = await Promise.allSettled(\n components.map(async ({ id, variantIds }) => {\n const res = await fetchWithTimeout(\n `${config.baseUrl}/assign`,\n { method: 'POST', headers, body: JSON.stringify({ sessionId, componentId: id, variantIds }) },\n timeoutMs,\n );\n if (!res.ok) {\n const body = await res.json().catch(() => ({}));\n console.error(`[SentientUI] preloadAssignments: assign failed for \"${id}\" (${res.status})`, body);\n return null;\n }\n const body = (await res.json()) as AssignResult;\n return { id, variantId: body.variantId };\n }),\n );\n\n const assignments: ServerAssignments = {};\n for (const result of results) {\n if (result.status === 'fulfilled' && result.value) {\n assignments[result.value.id] = result.value.variantId;\n }\n }\n return assignments;\n}\n\n/**\n * Reads the Sentient session cookie from a Next.js `ReadonlyRequestCookies` object\n * (the return value of `cookies()` from `next/headers`), or any object with a\n * `get(name: string)` method. Returns null if the cookie is absent.\n *\n * Pass the project's `apiKey`: the client writes the per-project SUFFIXED name\n * (`sessionCookieName` — see storage-key.ts), so reading only the bare\n * `_snt_uid` missed the cookie on every SSR request for a returning visitor and\n * minted a fresh orphan session each page view (quota inflation, broken sticky\n * assignments and persona continuity). The bare name is still read as a\n * fallback for identities minted before namespacing.\n */\nexport function readSessionCookie(\n cookies: { get(name: string): { value: string } | undefined },\n apiKey?: string,\n): string | null {\n return (\n (apiKey ? cookies.get(sessionCookieName(apiKey))?.value : undefined) ??\n cookies.get(LEGACY_SESSION_COOKIE_NAME)?.value ??\n null\n );\n}\n\nexport type DecideResult = {\n layoutOrder: string[];\n assignments: Record<string, string>;\n /** Slot results keyed by slot id. Baseline-resolved when the API omits/fails them. */\n slots: Record<string, SlotResult>;\n persona: string;\n confidence: number;\n /** Registry mode only: content/ops/blocks for server-defined slots. */\n slotConfig?: Record<string, SlotConfigEntry>;\n /** Registry mode only: site palette for block rendering. */\n palette?: SitePalette;\n /** Registry mode only: site styles the served Redesign arms borrow. */\n vocabulary?: import('./style-vocabulary.js').StyleVocabulary;\n};\n\n/**\n * Single-roundtrip SSR call returning layout order, component assignments,\n * and adaptive-slot results. Falls back to default section order + empty\n * assignments + baseline slots if the API is unavailable. A response without\n * a `slots` field means the server predates slots — every declared slot\n * resolves to its baseline (no retry).\n */\nexport async function preloadDecisions(\n params: {\n sections?: string[];\n components: Array<{ id: string; variantIds?: string[] }>;\n slots?: SlotDeclInput[];\n /** 'registry' serves the project's published slot_definitions as if declared\n * (and is the only way slotConfig/palette come back). Default 'request'.\n * Requires `registrySlotIds`: the `<Adaptive id>`s THIS page renders. */\n slotsFrom?: 'request' | 'registry';\n /**\n * Registry mode: decide only these published slot ids. Close-out turns\n * every slot decision into a trial without checking an exposure, so an\n * unscoped registry decide accrues trials — and session-level credit — for\n * every published slot on every page, including ones this page never\n * renders (CONTRACTS §2). Omitting it in registry mode is refused: the\n * call downgrades to request mode with one console.error, rather than\n * silently minting those trials.\n */\n registrySlotIds?: string[];\n /**\n * Registry mode: what each slot on this page can render (CONTRACTS §2).\n * The server has no DOM here, so no fingerprint is sent and a Rewrite arm\n * is assumed to match; a real mismatch is reported from the browser as\n * drift. Declare `forms: false` for slots without an `onFormSubmit`, or a\n * form arm can be drawn that this page will refuse. Default per slot:\n * `{ forms: true, compose: true }`.\n */\n renderCaps?: Record<string, Omit<RenderCaps, 'fp'>>;\n },\n sessionId: string,\n config: ServerAssignConfig,\n): Promise<DecideResult> {\n const timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n const declaredSlots = params.slots ?? [];\n let registryIds: string[] | null = null;\n if (params.slotsFrom === 'registry') {\n if (Array.isArray(params.registrySlotIds)) {\n registryIds = params.registrySlotIds;\n } else {\n console.error(\n \"[SentientUI] preloadDecisions: slotsFrom: 'registry' needs registrySlotIds (the <Adaptive id>s this page renders). \" +\n 'An unscoped registry decide records a trial for every published slot on every page; falling back to request mode.',\n );\n }\n }\n const fallback: DecideResult = {\n layoutOrder: params.sections ?? [],\n assignments: {},\n slots: baselineSlots(declaredSlots),\n persona: 'unknown',\n confidence: 0,\n };\n\n // Opted-out visitor (DNT/GPC): baseline layout/slots, mint no session (audit P4).\n if (config.doNotTrack) return fallback;\n\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${config.apiKey}`,\n };\n if (config.origin) headers.Origin = config.origin;\n\n const sessionBody = {\n ...buildSessionUpsertPayload(sessionId, {\n userAgent: config.userAgent,\n referer: config.referer,\n utmParams: config.utmParams,\n clickIds: config.clickIds,\n appOrigin: config.origin,\n }),\n ...(config.persona ? { persona: config.persona } : {}),\n };\n\n try {\n const sessionRes = await fetchWithTimeout(\n `${config.baseUrl}/sessions`,\n { method: 'POST', headers, body: JSON.stringify(sessionBody) },\n timeoutMs,\n );\n if (!sessionRes.ok) {\n const body = await sessionRes.json().catch(() => ({}));\n console.error(`[SentientUI] preloadDecisions: session upsert failed (${sessionRes.status})`, body);\n }\n } catch (err) {\n console.error('[SentientUI] preloadDecisions: session upsert threw', err);\n }\n\n try {\n const res = await fetchWithTimeout(\n `${config.baseUrl}/decide`,\n {\n method: 'POST',\n headers,\n body: JSON.stringify({\n sessionId,\n sections: (params.sections ?? []).map((id) => ({ id })),\n components: params.components,\n ...(declaredSlots.length > 0 ? { slots: declaredSlots.map(toWireSlot) } : {}),\n // bootstrap:false — editor goals and the section map are snippet\n // data the React SDK never reads. An EMPTY id list is meaningful\n // (\"nothing published is on this page\"): zero trials, still a decide.\n ...(registryIds !== null\n ? {\n slotsFrom: 'registry',\n registrySlotIds: registryIds,\n bootstrap: false,\n // Always sent, so the server knows this is an SDK that can\n // render Rewrite arms — no `render` field means legacy.\n render: Object.fromEntries(\n // compose: true — the React SDK (the SSR consumer) renders\n // Redesign trees since native generation phase 2.\n registryIds.map((id) => [id, params.renderCaps?.[id] ?? { forms: true, compose: true }]),\n ),\n }\n : {}),\n ...(config.persona ? { persona: config.persona } : {}),\n }),\n },\n timeoutMs,\n );\n if (!res.ok) {\n const body = await res.json().catch(() => ({}));\n console.error(`[SentientUI] preloadDecisions: decide failed (${res.status})`, body);\n return fallback;\n }\n const data = (await res.json()) as {\n layoutOrder?: string[];\n assignments?: Record<string, string>;\n slots?: Record<string, SlotResult>;\n slotConfig?: Record<string, SlotConfigEntry>;\n palette?: SitePalette;\n vocabulary?: import('./style-vocabulary.js').StyleVocabulary;\n persona?: string;\n confidence?: number;\n };\n\n const slots: Record<string, SlotResult> = {};\n for (const d of declaredSlots) {\n // `data.slots === undefined` ⇒ server predates slots: baseline, no retry.\n slots[d.id] = data.slots?.[d.id] ?? baselineResultFor(d);\n }\n // Registry mode returns slots the request never declared — union them in\n // (same rule as the browser client), or an SSR page gets results for none\n // of its registry slots.\n for (const [slotId, result] of Object.entries(data.slots ?? {})) {\n if (!(slotId in slots)) slots[slotId] = result;\n }\n\n // Plain-object guard only (readSnapshot's rule): the server total-validated\n // the config at publish; a deep re-validation here would just drift.\n const slotConfigOk =\n data.slotConfig !== undefined && typeof data.slotConfig === 'object' && data.slotConfig !== null && !Array.isArray(data.slotConfig);\n\n return {\n layoutOrder: data.layoutOrder ?? params.sections ?? [],\n assignments: data.assignments ?? {},\n slots,\n persona: data.persona ?? 'unknown',\n confidence: data.confidence ?? 0,\n ...(slotConfigOk ? { slotConfig: data.slotConfig } : {}),\n ...(data.palette ? { palette: data.palette } : {}),\n ...(data.vocabulary ? { vocabulary: data.vocabulary } : {}),\n };\n } catch (err) {\n console.error('[SentientUI] preloadDecisions: decide threw', err);\n return fallback;\n }\n}\n","// Server-side capture of AI-assistant fetches, for any framework.\n// Spec: docs/superpowers/specs/2026-09-23-server-side-agent-capture-design.md §4.1\n//\n// Assistants that fetch a page without running JavaScript (ChatGPT-User,\n// Claude-User, Perplexity-User, GPTBot, …) never execute the snippet or the\n// React SDK, so only the server that answered can see them. Until this, only\n// Next.js AdaptiveRoot logged them; every other site read \"no AI traffic\",\n// which is wrong rather than empty.\n//\n// OBSERVATION ONLY. Nothing here may change a response based on the user\n// agent: that is cloaking, and SentientUI never claims to adapt serving to\n// agents. These functions return nothing a caller could branch on except\n// \"did this look like an agent\", and log to crawler_requests — never to\n// sessions, never to training, never to billing.\n\nimport { matchedAgentToken } from './session-meta.js';\n\nconst DEFAULT_API_BASE_URL = 'https://api.sentient-ui.com/v1';\n\nexport type AgentCaptureOptions = {\n /** Your public `pk_` key — the same one the snippet uses. */\n apiKey: string;\n /** API base ending in `/v1`. Defaults to the hosted API. */\n baseUrl?: string;\n /** Which capture path saw the fetch. Shown per row on the dashboard. */\n source?: 'middleware' | 'edge' | 'ssr';\n /**\n * REQUIRED on edge runtimes (Vercel Routing Middleware, Cloudflare Workers,\n * Netlify Edge): they cancel outstanding work once the response is\n * returned, so a fire-and-forget request without it is silently dropped.\n * Pass the platform's `waitUntil` (`ctx.waitUntil.bind(ctx)` on Workers,\n * `waitUntil` from `@vercel/functions`). Node servers do not need it.\n */\n waitUntil?: (p: Promise<unknown>) => void;\n /** Injectable for tests. */\n fetchImpl?: typeof fetch;\n};\n\n/** The minimum of a request both the Fetch API `Request` and hand-rolled\n * objects satisfy. */\nexport type CapturableRequest = {\n url: string;\n headers: { get(name: string): string | null };\n};\n\n/** Pathname only: a query string can carry tokens, emails or campaign ids. */\nfunction pathOf(url: string): string {\n try {\n return new URL(url, 'http://localhost').pathname || '/';\n } catch {\n return url.split(/[?#]/, 1)[0] || '/';\n }\n}\n\n/**\n * Low-level sender: posts one agent fetch to `/v1/crawler-events`. Never\n * throws, never blocks. The API re-derives the agent from `userAgent`\n * itself, so `botName` is advisory.\n */\nexport function postAgentFetch(\n entry: { path: string; userAgent: string; botName: string },\n opts: AgentCaptureOptions,\n): void {\n const doFetch = opts.fetchImpl ?? (typeof fetch === 'function' ? fetch : undefined);\n if (!doFetch || !opts.apiKey) return;\n try {\n const p = doFetch(`${opts.baseUrl ?? DEFAULT_API_BASE_URL}/crawler-events`, {\n method: 'POST',\n headers: { 'content-type': 'application/json', authorization: `Bearer ${opts.apiKey}` },\n body: JSON.stringify({\n path: entry.path,\n botName: entry.botName,\n userAgent: entry.userAgent,\n source: opts.source ?? 'middleware',\n }),\n }).catch(() => undefined);\n opts.waitUntil?.(p);\n } catch {\n /* capture must never break the page it is observing */\n }\n}\n\n/**\n * Log this request if its user agent is a known AI assistant or crawler.\n * Works with a Fetch API `Request` (edge runtimes, Hono, Remix / React\n * Router, Astro, SvelteKit) or anything with `url` + `headers.get`.\n *\n * Returns whether the request matched, so a caller can skip its own work;\n * it must NOT be used to serve anything different. Non-matching requests —\n * nearly all of them — make no network call.\n */\nexport function captureAgentRequest(req: CapturableRequest, opts: AgentCaptureOptions): boolean {\n let userAgent = '';\n try {\n userAgent = req.headers.get('user-agent') ?? '';\n } catch {\n return false;\n }\n const botName = matchedAgentToken(userAgent);\n if (!botName) return false;\n postAgentFetch({ path: pathOf(req.url), userAgent, botName }, opts);\n return true;\n}\n\ntype ConnectRequest = {\n url?: string;\n originalUrl?: string;\n headers: Record<string, string | string[] | undefined>;\n};\n\n/**\n * Connect-style middleware (Express, Nitro / Nuxt on Node, Fastify via\n * middie, any `(req, res, next)` stack). Calls `next()` synchronously and\n * logs in the background; it never touches the response.\n */\nexport function sentientAgentMiddleware(\n opts: Omit<AgentCaptureOptions, 'waitUntil' | 'source'>,\n): (req: ConnectRequest, res: unknown, next: (err?: unknown) => void) => void {\n return (req, _res, next) => {\n try {\n const raw = req.headers['user-agent'];\n const ua = Array.isArray(raw) ? raw[0] ?? '' : raw ?? '';\n captureAgentRequest(\n { url: req.originalUrl ?? req.url ?? '/', headers: { get: (n) => (n.toLowerCase() === 'user-agent' ? ua : null) } },\n { ...opts, source: 'middleware' },\n );\n } catch {\n /* never block the request */\n }\n next();\n };\n}\n"],"mappings":"oLA8EA,IAAMA,EAAqB,IAE3B,SAASC,EACPC,EACAC,EACAC,EACmB,CACnB,IAAMC,EAAa,IAAI,gBACjBC,EAAQ,WAAW,IAAMD,EAAW,MAAM,EAAGD,CAAS,EAC5D,OAAO,MAAMF,EAAKK,EAAAC,EAAA,GAAKL,GAAL,CAAW,OAAQE,EAAW,MAAO,EAAC,EAAE,QAAQ,IAChE,aAAaC,CAAK,CACpB,CACF,CAqBA,eAAsBG,EACpBC,EACAC,EACAC,EAC4B,CAnH9B,IAAAC,EAqHE,GAAID,EAAO,WAAY,MAAO,CAAC,EAE/B,IAAMR,GAAYS,EAAAD,EAAO,YAAP,KAAAC,EAAoBb,EAChCc,EAAkC,CACtC,eAAgB,mBAChB,cAAe,UAAUF,EAAO,MAAM,EACxC,EACIA,EAAO,SACTE,EAAQ,OAASF,EAAO,QAK1B,IAAMG,EAAcP,IAAA,GACfQ,EAA0BL,EAAW,CACtC,UAAWC,EAAO,UAClB,QAASA,EAAO,QAChB,UAAWA,EAAO,UAClB,SAAUA,EAAO,SACjB,UAAWA,EAAO,MACpB,CAAC,GACGA,EAAO,QAAU,CAAE,QAASA,EAAO,OAAQ,EAAI,CAAC,GAGtD,GAAI,CACF,IAAMK,EAAM,MAAMhB,EAChB,GAAGW,EAAO,OAAO,YACjB,CAAE,OAAQ,OAAQ,QAAAE,EAAS,KAAM,KAAK,UAAUC,CAAW,CAAE,EAC7DX,CACF,EACA,GAAIa,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AWA,EAAM,UACjB,QAAQI,EAAAH,EAAK,SAAL,KAAAG,EAAe,YACzB,CAAC,CACH,CAAC,EAAE,MAAM,IAAG,EAAY,GACxBC,EAAAJ,EAAK,YAAL,MAAAI,EAAA,KAAAJ,EAAiBM,EACnB,OAAQT,EAAA,CAER,CACF,CAWO,SAASU,EAAoBC,EAAwBR,EAAoC,CA3FhG,IAAAC,EA4FE,IAAIQ,EAAY,GAChB,GAAI,CACFA,GAAYR,EAAAO,EAAI,QAAQ,IAAI,YAAY,IAA5B,KAAAP,EAAiC,EAC/C,OAAQJ,EAAA,CACN,MAAO,EACT,CACA,IAAMa,EAAUC,EAAkBF,CAAS,EAC3C,OAAKC,GACLZ,EAAe,CAAE,KAAMH,EAAOa,EAAI,GAAG,EAAG,UAAAC,EAAW,QAAAC,CAAQ,EAAGV,CAAI,EAC3D,IAFc,EAGvB,CAaO,SAASY,EACdZ,EAC4E,CAC5E,MAAO,CAACQ,EAAKK,EAAMC,IAAS,CAtH9B,IAAAb,EAAAC,EAAAC,EAuHI,GAAI,CACF,IAAMY,EAAMP,EAAI,QAAQ,YAAY,EAC9BQ,EAAK,MAAM,QAAQD,CAAG,GAAId,EAAAc,EAAI,CAAC,IAAL,KAAAd,EAAU,GAAKc,GAAA,KAAAA,EAAO,GACtDR,EACE,CAAE,KAAKJ,GAAAD,EAAAM,EAAI,cAAJ,KAAAN,EAAmBM,EAAI,MAAvB,KAAAL,EAA8B,IAAK,QAAS,CAAE,IAAM,GAAO,EAAE,YAAY,IAAM,aAAea,EAAK,IAAM,CAAE,EAClHC,EAAAC,EAAA,GAAKlB,GAAL,CAAW,OAAQ,YAAa,EAClC,CACF,OAAQH,EAAA,CAER,CACAiB,EAAK,CACP,CACF","names":["DEFAULT_TIMEOUT_MS","fetchWithTimeout","url","init","timeoutMs","controller","timer","__spreadProps","__spreadValues","preloadAssignments","components","sessionId","config","_a","headers","sessionBody","buildSessionUpsertPayload","res","body","err","results","id","variantIds","assignments","result","readSessionCookie","cookies","apiKey","_b","_c","_d","sessionCookieName","LEGACY_SESSION_COOKIE_NAME","preloadDecisions","params","_e","_f","_g","_h","_i","_j","_k","_l","declaredSlots","registryIds","fallback","baselineSlots","sessionRes","toWireSlot","data","slots","d","baselineResultFor","slotId","slotConfigOk","DEFAULT_API_BASE_URL","pathOf","url","e","postAgentFetch","entry","opts","_a","_b","_c","_d","doFetch","p","captureAgentRequest","req","userAgent","botName","matchedAgentToken","sentientAgentMiddleware","_res","next","raw","ua","__spreadProps","__spreadValues"]}
|
|
1
|
+
{"version":3,"sources":["../src/server.ts","../src/agent-capture.ts"],"sourcesContent":["/**\n * Server-side helpers for SSR variant pre-loading.\n * Pure fetch — no DOM APIs. Safe in Node.js, Edge, and Deno runtimes.\n */\nimport { buildSessionUpsertPayload } from './session-meta.js';\nimport { LEGACY_SESSION_COOKIE_NAME, sessionCookieName } from './storage-key.js';\nimport {\n toWireSlot,\n baselineResultFor,\n baselineSlots,\n type SlotDeclInput,\n type SlotResult,\n} from './slots.js';\n\nimport type { SlotConfigEntry } from './snapshot.js';\nimport type { RenderCaps } from './region-skeleton.js';\nimport type { SitePalette } from './blocks.js';\n\nexport type { SlotDeclInput, SlotResult, SlotConfigEntry, SitePalette };\n\nexport type ServerAssignConfig = {\n /** Public API key (pk_...). */\n apiKey: string;\n /**\n * Base URL of the Sentient API without trailing slash.\n * e.g. 'https://api.yourapp.com/v1'\n */\n baseUrl: string;\n /**\n * Browser origin of your app (e.g. `http://localhost:3001`). Required for `pk_`\n * keys — server-side fetch must send the same `Origin` the API allows.\n */\n origin?: string;\n /**\n * Optional: this project's SECRET key (sk_...), read from a server-only env\n * var. When set, SSR calls also send it as `X-Sentient-Server-Key`, which\n * proves they come from your server: the API then holds them to your plan's\n * per-key limit instead of the 100 requests/min per-IP cap meant for\n * browsers — without it, all SSR traffic from one server address shares that\n * one cap. Never set this in code that ships to the browser; it is ignored\n * (and not sent) when `window` exists.\n */\n serverKey?: string;\n /** From `User-Agent` request header (Next.js `headers()`). */\n userAgent?: string;\n /** From `Referer` request header. */\n referer?: string;\n utmParams?: Record<string, string>;\n /**\n * Ad-platform click IDs (gclid, fbclid, ttclid, …) from the landing URL.\n * Derive both this and `utmParams` with `extractTrackedParams(searchParams)`\n * — the Referer header never carries the landing page's own query string, so\n * without these two fields SSR-minted sessions have no campaign attribution\n * until the client SDK hydrates.\n */\n clickIds?: Record<string, string>;\n /**\n * Set true when the request carries a tracking opt-out — `DNT: 1` or\n * `Sec-GPC: 1`. When set, the SSR helpers skip the session upsert and the\n * assign/decide call entirely: the page renders defaults/baseline and no\n * session row is minted for the visitor (audit P4). The client SDK already\n * no-ops for these visitors; this keeps the server from minting a session +\n * assignment on every page view before the client can.\n */\n doNotTrack?: boolean;\n /**\n * Declared persona — the role your app already knows for this visitor\n * (e.g. from your auth context during SSR). Same contract as the client\n * option: must be a vocabulary key; unrecognized values are ignored\n * server-side. Never a user id or email.\n */\n persona?: string;\n /**\n * Milliseconds to wait for the API before returning default variants.\n * Prevents slow/cold API from blocking SSR. Defaults to 1000 — the hot path\n * is served from in-process caches and typically returns in well under\n * 150 ms. The full 1 s budget is only reached on a cold start or an API\n * geographically distant from your SSR host, after which defaults render\n * with no layout shift. Lower it if your API is co-located and warm.\n */\n timeoutMs?: number;\n};\n\n/** Header carrying `serverKey` (apps/api lib/rate-limit.ts SERVER_KEY_HEADER). */\nexport const SERVER_KEY_HEADER = 'X-Sentient-Server-Key';\n\n/** Auth headers for an SSR call: the pk_, its Origin, and the optional server proof. */\nfunction ssrHeaders(config: ServerAssignConfig): Record<string, string> {\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${config.apiKey}`,\n };\n if (config.origin) headers.Origin = config.origin;\n // A secret key must never leave a browser: if this module was bundled\n // client-side by mistake, drop it rather than send it.\n if (config.serverKey && typeof window === 'undefined') headers[SERVER_KEY_HEADER] = config.serverKey;\n return headers;\n}\n\n/** componentId → assigned variantId */\nexport type ServerAssignments = Record<string, string>;\n\ntype AssignResult = { variantId: string; assignmentTtlMs: number };\n\nconst DEFAULT_TIMEOUT_MS = 1000;\n\nfunction fetchWithTimeout(\n url: string,\n init: RequestInit,\n timeoutMs: number,\n): Promise<Response> {\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), timeoutMs);\n return fetch(url, { ...init, signal: controller.signal }).finally(() =>\n clearTimeout(timer),\n );\n}\n\n/**\n * Fetches variant assignments server-side for all listed components.\n * Returns a map suitable for passing as `initialAssignments` to `<AdaptiveProvider>`.\n *\n * Call from Next.js layout, Server Component, or getServerSideProps.\n *\n * @example\n * ```tsx\n * const assignments = await preloadAssignments(\n * [\n * { id: 'hero', variantIds: ['hero-a', 'hero-b'] },\n * { id: 'cta', variantIds: ['cta-short', 'cta-long'] },\n * ],\n * sessionId, // read from cookies() or req.cookies\n * { apiKey: process.env.NEXT_PUBLIC_SENTIENT_API_KEY!, baseUrl: 'https://api.sentient-ui.com/v1' },\n * );\n * return <AdaptiveProvider ... initialAssignments={assignments}>{children}</AdaptiveProvider>;\n * ```\n */\nexport async function preloadAssignments(\n components: Array<{ id: string; variantIds: string[] }>,\n sessionId: string,\n config: ServerAssignConfig,\n): Promise<ServerAssignments> {\n // Opted-out visitor (DNT/GPC): render defaults, mint no session (audit P4).\n if (config.doNotTrack) return {};\n\n const timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n const headers = ssrHeaders(config);\n\n // Session metadata must match the browser SDK so assign seeds variant_weights\n // under the same segment (not `unknown:unknown`).\n const sessionBody = {\n ...buildSessionUpsertPayload(sessionId, {\n userAgent: config.userAgent,\n referer: config.referer,\n utmParams: config.utmParams,\n clickIds: config.clickIds,\n appOrigin: config.origin,\n }),\n ...(config.persona ? { persona: config.persona } : {}),\n };\n\n try {\n const res = await fetchWithTimeout(\n `${config.baseUrl}/sessions`,\n { method: 'POST', headers, body: JSON.stringify(sessionBody) },\n timeoutMs,\n );\n if (res.status === 402) {\n console.warn(\n '[SentientUI] Session limit exceeded for this project. The bandit will stop learning until the limit resets. Upgrade at sentient-ui.com/pricing',\n );\n } else if (!res.ok) {\n const body = await res.json().catch(() => ({}));\n console.error(`[SentientUI] preloadAssignments: session upsert failed (${res.status})`, body);\n }\n } catch (err) {\n console.error('[SentientUI] preloadAssignments: session upsert threw', err);\n }\n\n const results = await Promise.allSettled(\n components.map(async ({ id, variantIds }) => {\n const res = await fetchWithTimeout(\n `${config.baseUrl}/assign`,\n { method: 'POST', headers, body: JSON.stringify({ sessionId, componentId: id, variantIds }) },\n timeoutMs,\n );\n if (!res.ok) {\n const body = await res.json().catch(() => ({}));\n console.error(`[SentientUI] preloadAssignments: assign failed for \"${id}\" (${res.status})`, body);\n return null;\n }\n const body = (await res.json()) as AssignResult;\n return { id, variantId: body.variantId };\n }),\n );\n\n const assignments: ServerAssignments = {};\n for (const result of results) {\n if (result.status === 'fulfilled' && result.value) {\n assignments[result.value.id] = result.value.variantId;\n }\n }\n return assignments;\n}\n\n/**\n * Reads the Sentient session cookie from a Next.js `ReadonlyRequestCookies` object\n * (the return value of `cookies()` from `next/headers`), or any object with a\n * `get(name: string)` method. Returns null if the cookie is absent.\n *\n * Pass the project's `apiKey`: the client writes the per-project SUFFIXED name\n * (`sessionCookieName` — see storage-key.ts), so reading only the bare\n * `_snt_uid` missed the cookie on every SSR request for a returning visitor and\n * minted a fresh orphan session each page view (quota inflation, broken sticky\n * assignments and persona continuity). The bare name is still read as a\n * fallback for identities minted before namespacing.\n */\nexport function readSessionCookie(\n cookies: { get(name: string): { value: string } | undefined },\n apiKey?: string,\n): string | null {\n return (\n (apiKey ? cookies.get(sessionCookieName(apiKey))?.value : undefined) ??\n cookies.get(LEGACY_SESSION_COOKIE_NAME)?.value ??\n null\n );\n}\n\nexport type DecideResult = {\n layoutOrder: string[];\n assignments: Record<string, string>;\n /** Slot results keyed by slot id. Baseline-resolved when the API omits/fails them. */\n slots: Record<string, SlotResult>;\n persona: string;\n confidence: number;\n /** Registry mode only: content/ops/blocks for server-defined slots. */\n slotConfig?: Record<string, SlotConfigEntry>;\n /** Registry mode only: site palette for block rendering. */\n palette?: SitePalette;\n /** Registry mode only: site styles the served Redesign arms borrow. */\n vocabulary?: import('./style-vocabulary.js').StyleVocabulary;\n};\n\n/**\n * Single-roundtrip SSR call returning layout order, component assignments,\n * and adaptive-slot results. Falls back to default section order + empty\n * assignments + baseline slots if the API is unavailable. A response without\n * a `slots` field means the server predates slots — every declared slot\n * resolves to its baseline (no retry).\n */\nexport async function preloadDecisions(\n params: {\n sections?: string[];\n components: Array<{ id: string; variantIds?: string[] }>;\n slots?: SlotDeclInput[];\n /** 'registry' serves the project's published slot_definitions as if declared\n * (and is the only way slotConfig/palette come back). Default 'request'.\n * Requires `registrySlotIds`: the `<Adaptive id>`s THIS page renders. */\n slotsFrom?: 'request' | 'registry';\n /**\n * Registry mode: decide only these published slot ids. Close-out turns\n * every slot decision into a trial without checking an exposure, so an\n * unscoped registry decide accrues trials — and session-level credit — for\n * every published slot on every page, including ones this page never\n * renders (CONTRACTS §2). Omitting it in registry mode is refused: the\n * call downgrades to request mode with one console.error, rather than\n * silently minting those trials.\n */\n registrySlotIds?: string[];\n /**\n * Registry mode: what each slot on this page can render (CONTRACTS §2).\n * The server has no DOM here, so no fingerprint is sent and a Rewrite arm\n * is assumed to match; a real mismatch is reported from the browser as\n * drift. Declare `forms: false` for slots without an `onFormSubmit`, or a\n * form arm can be drawn that this page will refuse. Default per slot:\n * `{ forms: true, compose: true }`.\n */\n renderCaps?: Record<string, Omit<RenderCaps, 'fp'>>;\n },\n sessionId: string,\n config: ServerAssignConfig,\n): Promise<DecideResult> {\n const timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n const declaredSlots = params.slots ?? [];\n let registryIds: string[] | null = null;\n if (params.slotsFrom === 'registry') {\n if (Array.isArray(params.registrySlotIds)) {\n registryIds = params.registrySlotIds;\n } else {\n console.error(\n \"[SentientUI] preloadDecisions: slotsFrom: 'registry' needs registrySlotIds (the <Adaptive id>s this page renders). \" +\n 'An unscoped registry decide records a trial for every published slot on every page; falling back to request mode.',\n );\n }\n }\n const fallback: DecideResult = {\n layoutOrder: params.sections ?? [],\n assignments: {},\n slots: baselineSlots(declaredSlots),\n persona: 'unknown',\n confidence: 0,\n };\n\n // Opted-out visitor (DNT/GPC): baseline layout/slots, mint no session (audit P4).\n if (config.doNotTrack) return fallback;\n\n const headers = ssrHeaders(config);\n\n const sessionBody = {\n ...buildSessionUpsertPayload(sessionId, {\n userAgent: config.userAgent,\n referer: config.referer,\n utmParams: config.utmParams,\n clickIds: config.clickIds,\n appOrigin: config.origin,\n }),\n ...(config.persona ? { persona: config.persona } : {}),\n };\n\n try {\n const sessionRes = await fetchWithTimeout(\n `${config.baseUrl}/sessions`,\n { method: 'POST', headers, body: JSON.stringify(sessionBody) },\n timeoutMs,\n );\n if (!sessionRes.ok) {\n const body = await sessionRes.json().catch(() => ({}));\n console.error(`[SentientUI] preloadDecisions: session upsert failed (${sessionRes.status})`, body);\n }\n } catch (err) {\n console.error('[SentientUI] preloadDecisions: session upsert threw', err);\n }\n\n try {\n const res = await fetchWithTimeout(\n `${config.baseUrl}/decide`,\n {\n method: 'POST',\n headers,\n body: JSON.stringify({\n sessionId,\n sections: (params.sections ?? []).map((id) => ({ id })),\n components: params.components,\n ...(declaredSlots.length > 0 ? { slots: declaredSlots.map(toWireSlot) } : {}),\n // bootstrap:false — editor goals and the section map are snippet\n // data the React SDK never reads. An EMPTY id list is meaningful\n // (\"nothing published is on this page\"): zero trials, still a decide.\n ...(registryIds !== null\n ? {\n slotsFrom: 'registry',\n registrySlotIds: registryIds,\n bootstrap: false,\n // Always sent, so the server knows this is an SDK that can\n // render Rewrite arms — no `render` field means legacy.\n render: Object.fromEntries(\n // compose: true — the React SDK (the SSR consumer) renders\n // Redesign trees since native generation phase 2.\n registryIds.map((id) => [id, params.renderCaps?.[id] ?? { forms: true, compose: true }]),\n ),\n }\n : {}),\n ...(config.persona ? { persona: config.persona } : {}),\n }),\n },\n timeoutMs,\n );\n if (!res.ok) {\n const body = await res.json().catch(() => ({}));\n console.error(`[SentientUI] preloadDecisions: decide failed (${res.status})`, body);\n return fallback;\n }\n const data = (await res.json()) as {\n layoutOrder?: string[];\n assignments?: Record<string, string>;\n slots?: Record<string, SlotResult>;\n slotConfig?: Record<string, SlotConfigEntry>;\n palette?: SitePalette;\n vocabulary?: import('./style-vocabulary.js').StyleVocabulary;\n persona?: string;\n confidence?: number;\n };\n\n const slots: Record<string, SlotResult> = {};\n for (const d of declaredSlots) {\n // `data.slots === undefined` ⇒ server predates slots: baseline, no retry.\n slots[d.id] = data.slots?.[d.id] ?? baselineResultFor(d);\n }\n // Registry mode returns slots the request never declared — union them in\n // (same rule as the browser client), or an SSR page gets results for none\n // of its registry slots.\n for (const [slotId, result] of Object.entries(data.slots ?? {})) {\n if (!(slotId in slots)) slots[slotId] = result;\n }\n\n // Plain-object guard only (readSnapshot's rule): the server total-validated\n // the config at publish; a deep re-validation here would just drift.\n const slotConfigOk =\n data.slotConfig !== undefined && typeof data.slotConfig === 'object' && data.slotConfig !== null && !Array.isArray(data.slotConfig);\n\n return {\n layoutOrder: data.layoutOrder ?? params.sections ?? [],\n assignments: data.assignments ?? {},\n slots,\n persona: data.persona ?? 'unknown',\n confidence: data.confidence ?? 0,\n ...(slotConfigOk ? { slotConfig: data.slotConfig } : {}),\n ...(data.palette ? { palette: data.palette } : {}),\n ...(data.vocabulary ? { vocabulary: data.vocabulary } : {}),\n };\n } catch (err) {\n console.error('[SentientUI] preloadDecisions: decide threw', err);\n return fallback;\n }\n}\n","// Server-side capture of AI-assistant fetches, for any framework.\n// Spec: docs/superpowers/specs/2026-09-23-server-side-agent-capture-design.md §4.1\n//\n// Assistants that fetch a page without running JavaScript (ChatGPT-User,\n// Claude-User, Perplexity-User, GPTBot, …) never execute the snippet or the\n// React SDK, so only the server that answered can see them. Until this, only\n// Next.js AdaptiveRoot logged them; every other site read \"no AI traffic\",\n// which is wrong rather than empty.\n//\n// OBSERVATION ONLY. Nothing here may change a response based on the user\n// agent: that is cloaking, and SentientUI never claims to adapt serving to\n// agents. These functions return nothing a caller could branch on except\n// \"did this look like an agent\", and log to crawler_requests — never to\n// sessions, never to training, never to billing.\n\nimport { matchedAgentToken } from './session-meta.js';\n\nconst DEFAULT_API_BASE_URL = 'https://api.sentient-ui.com/v1';\n\nexport type AgentCaptureOptions = {\n /** Your public `pk_` key — the same one the snippet uses. */\n apiKey: string;\n /** API base ending in `/v1`. Defaults to the hosted API. */\n baseUrl?: string;\n /** Which capture path saw the fetch. Shown per row on the dashboard. */\n source?: 'middleware' | 'edge' | 'ssr';\n /**\n * REQUIRED on edge runtimes (Vercel Routing Middleware, Cloudflare Workers,\n * Netlify Edge): they cancel outstanding work once the response is\n * returned, so a fire-and-forget request without it is silently dropped.\n * Pass the platform's `waitUntil` (`ctx.waitUntil.bind(ctx)` on Workers,\n * `waitUntil` from `@vercel/functions`). Node servers do not need it.\n */\n waitUntil?: (p: Promise<unknown>) => void;\n /** Injectable for tests. */\n fetchImpl?: typeof fetch;\n};\n\n/** The minimum of a request both the Fetch API `Request` and hand-rolled\n * objects satisfy. */\nexport type CapturableRequest = {\n url: string;\n headers: { get(name: string): string | null };\n};\n\n/** Pathname only: a query string can carry tokens, emails or campaign ids. */\nfunction pathOf(url: string): string {\n try {\n return new URL(url, 'http://localhost').pathname || '/';\n } catch {\n return url.split(/[?#]/, 1)[0] || '/';\n }\n}\n\n/**\n * Low-level sender: posts one agent fetch to `/v1/crawler-events`. Never\n * throws, never blocks. The API re-derives the agent from `userAgent`\n * itself, so `botName` is advisory.\n */\nexport function postAgentFetch(\n entry: { path: string; userAgent: string; botName: string },\n opts: AgentCaptureOptions,\n): void {\n const doFetch = opts.fetchImpl ?? (typeof fetch === 'function' ? fetch : undefined);\n if (!doFetch || !opts.apiKey) return;\n try {\n const p = doFetch(`${opts.baseUrl ?? DEFAULT_API_BASE_URL}/crawler-events`, {\n method: 'POST',\n headers: { 'content-type': 'application/json', authorization: `Bearer ${opts.apiKey}` },\n body: JSON.stringify({\n path: entry.path,\n botName: entry.botName,\n userAgent: entry.userAgent,\n source: opts.source ?? 'middleware',\n }),\n }).catch(() => undefined);\n opts.waitUntil?.(p);\n } catch {\n /* capture must never break the page it is observing */\n }\n}\n\n/**\n * Log this request if its user agent is a known AI assistant or crawler.\n * Works with a Fetch API `Request` (edge runtimes, Hono, Remix / React\n * Router, Astro, SvelteKit) or anything with `url` + `headers.get`.\n *\n * Returns whether the request matched, so a caller can skip its own work;\n * it must NOT be used to serve anything different. Non-matching requests —\n * nearly all of them — make no network call.\n */\nexport function captureAgentRequest(req: CapturableRequest, opts: AgentCaptureOptions): boolean {\n let userAgent = '';\n try {\n userAgent = req.headers.get('user-agent') ?? '';\n } catch {\n return false;\n }\n const botName = matchedAgentToken(userAgent);\n if (!botName) return false;\n postAgentFetch({ path: pathOf(req.url), userAgent, botName }, opts);\n return true;\n}\n\ntype ConnectRequest = {\n url?: string;\n originalUrl?: string;\n headers: Record<string, string | string[] | undefined>;\n};\n\n/**\n * Connect-style middleware (Express, Nitro / Nuxt on Node, Fastify via\n * middie, any `(req, res, next)` stack). Calls `next()` synchronously and\n * logs in the background; it never touches the response.\n */\nexport function sentientAgentMiddleware(\n opts: Omit<AgentCaptureOptions, 'waitUntil' | 'source'>,\n): (req: ConnectRequest, res: unknown, next: (err?: unknown) => void) => void {\n return (req, _res, next) => {\n try {\n const raw = req.headers['user-agent'];\n const ua = Array.isArray(raw) ? raw[0] ?? '' : raw ?? '';\n captureAgentRequest(\n { url: req.originalUrl ?? req.url ?? '/', headers: { get: (n) => (n.toLowerCase() === 'user-agent' ? ua : null) } },\n { ...opts, source: 'middleware' },\n );\n } catch {\n /* never block the request */\n }\n next();\n };\n}\n"],"mappings":"iNAoFO,IAAMA,EAAoB,wBAGjC,SAASC,EAAWC,EAAoD,CACtE,IAAMC,EAAkC,CACtC,eAAgB,mBAChB,cAAe,UAAUD,EAAO,MAAM,EACxC,EACA,O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AAMa,EAAUC,EAAkBF,CAAS,EAC3C,OAAKC,GACLZ,EAAe,CAAE,KAAMH,GAAOa,EAAI,GAAG,EAAG,UAAAC,EAAW,QAAAC,CAAQ,EAAGV,CAAI,EAC3D,IAFc,EAGvB,CAaO,SAASY,GACdZ,EAC4E,CAC5E,MAAO,CAACQ,EAAKK,EAAMC,IAAS,CAtH9B,IAAAb,EAAAC,EAAAC,EAuHI,GAAI,CACF,IAAMY,EAAMP,EAAI,QAAQ,YAAY,EAC9BQ,EAAK,MAAM,QAAQD,CAAG,GAAId,EAAAc,EAAI,CAAC,IAAL,KAAAd,EAAU,GAAKc,GAAA,KAAAA,EAAO,GACtDR,EACE,CAAE,KAAKJ,GAAAD,EAAAM,EAAI,cAAJ,KAAAN,EAAmBM,EAAI,MAAvB,KAAAL,EAA8B,IAAK,QAAS,CAAE,IAAM,GAAO,EAAE,YAAY,IAAM,aAAea,EAAK,IAAM,CAAE,EAClHC,EAAAC,EAAA,GAAKlB,GAAL,CAAW,OAAQ,YAAa,EAClC,CACF,OAAQH,EAAA,CAER,CACAiB,EAAK,CACP,CACF","names":["SERVER_KEY_HEADER","ssrHeaders","config","headers","DEFAULT_TIMEOUT_MS","fetchWithTimeout","url","init","timeoutMs","controller","timer","__spreadProps","__spreadValues","preloadAssignments","components","sessionId","_a","sessionBody","buildSessionUpsertPayload","res","body","err","results","id","variantIds","assignments","result","readSessionCookie","cookies","apiKey","_b","_c","_d","sessionCookieName","LEGACY_SESSION_COOKIE_NAME","preloadDecisions","params","_e","_f","_g","_h","_i","_j","_k","_l","declaredSlots","registryIds","fallback","baselineSlots","sessionRes","toWireSlot","data","slots","d","baselineResultFor","slotId","slotConfigOk","DEFAULT_API_BASE_URL","pathOf","url","e","postAgentFetch","entry","opts","_a","_b","_c","_d","doFetch","p","captureAgentRequest","req","userAgent","botName","matchedAgentToken","sentientAgentMiddleware","_res","next","raw","ua","__spreadProps","__spreadValues"]}
|
package/dist/index.d.cts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
export { B as BLOCK_ALIGNS, a as BLOCK_EMPHASES, b as BLOCK_FITS, c as BLOCK_GAPS, d as BLOCK_GRID_COLUMNS, e as BLOCK_HEADING_LEVELS, f as BLOCK_JUSTIFIES, g as BLOCK_MAX_WIDTHS, h as BLOCK_PADS, i as BLOCK_RATIOS, j as BLOCK_SIZES, k as BLOCK_SURFACES, l as BLOCK_TEXT_ALIGNS, m as BLOCK_TONES, n as BLOCK_WEIGHTS, o as BadgeBlock, p as BlockAlign, q as BlockEmphasis, r as BlockFit, s as BlockGap, t as BlockJustify, u as BlockMaxWidth, v as BlockNode, w as BlockPad, x as BlockRatio, y as BlockSize, z as BlockSurface, A as BlockTextAlign, C as BlockTone, D as BlockWeight, E as ButtonBlock, F as ComposeArm, G as DividerBlock, H as FORM_FIELD_KINDS, I as FORM_INPUT_TYPES, J as FormBlock, K as FormField, L as GridBlock, M as HeadingBlock, N as ImageBlock, P as LinkBlock, Q as MAX_BLOCK_ARMS, R as MAX_BLOCK_CHILDREN, S as MAX_BLOCK_DEPTH, T as MAX_BLOCK_NODES, U as MAX_BLOCK_TEXT_LEN, V as MAX_FORM_FIELDS, W as MAX_FORM_SELECT_OPTIONS, _ as SiteImage, $ as SitePalette, a0 as SpacerBlock, a1 as StackBlock, a2 as StyleEntry, a3 as StyleRole, a4 as StyleVocabulary, a5 as TextBlock, a6 as containsFormBlock } from './style-vocabulary-Ba_g6_DD.cjs';
|
|
2
|
-
export { A as AssignResult, a as Assignment, c as AuthoredArmReport, C as ComponentGoalOptions, d as ComponentWeightEntry, D as DecideInput, e as DecideOutcome, f as EventType, G as GoalDefinition, g as GoalOptions, i as GraphConfig, j as GraphSnapshot, L as LEGACY_SESSION_COOKIE_NAME, k as LOCAL_MODE_BANNER, M as MicroSignalEmitter, l as MicroSignalType, P as PAGE_SCOPE_RE, m as PROD_KEYLESS_ERROR, Q as QueueConfig, R as REVEAL_MS, o as RevealOptions, S as SectionMapEntry, p as SentientClient, q as SentientConfig, r as SentientEvent, s as SessionConfig, t as SessionManager, u as SkeletonReport, W as WeightEntry, _ as _registerConsentUpgradeInit, v as
|
|
2
|
+
export { A as AssignResult, a as Assignment, c as AuthoredArmReport, C as ComponentGoalOptions, d as ComponentWeightEntry, D as DecideInput, e as DecideOutcome, f as EventType, G as GoalDefinition, g as GoalOptions, i as GraphConfig, j as GraphSnapshot, L as LEGACY_SESSION_COOKIE_NAME, k as LOCAL_MODE_BANNER, M as MicroSignalEmitter, l as MicroSignalType, P as PAGE_SCOPE_RE, m as PROD_KEYLESS_ERROR, Q as QueueConfig, R as REVEAL_MS, o as RevealOptions, S as SectionMapEntry, p as SentientClient, q as SentientConfig, r as SentientEvent, s as SessionConfig, t as SessionManager, u as SkeletonReport, W as WeightEntry, _ as _registerConsentUpgradeInit, v as applyNonce, w as attachMicroSignalDetectors, x as cspNonce, y as forgetGeneration, z as grantConsent, B as init, F as isDoNotTrackEnabled, H as pageScopeMatches, I as resetRevealStyles, J as reveal, K as routeKey, O as sessionCookieName, T as setCspNonce } from './index-BYOMZ3t-.cjs';
|
|
3
3
|
export { A as AGENT_INTENTS, a as AgentIntent, C as CLICK_ID_KEYS, b as CompoundLocator, D as DecisionSnapshot, S as SNAPSHOT_STORAGE_KEY_PREFIX, d as SlotConfigEntry, e as SlotDeclInput, f as SlotOps, g as agentIntent, h as agentUaList, i as armOfResult, j as baselineResultFor, k as baselineSlots, m as classifiedAgents, n as deriveSessionSegment, o as detectDeviceClass, p as detectTimeOfDay, q as detectTrafficSource, r as extractTrackedParams, s as matchedAgentToken, t as readSnapshot, u as referrerDomainFromReferer, v as renderPrePaintScript, w as toWireSlot, x as uaTokenMatch, y as writeSnapshot } from './session-meta-CJwAWbJr.cjs';
|
|
4
4
|
export { A as ArmEdits, M as MAX_SKELETON_LEAVES, a as MAX_SKELETON_NODES, b as MAX_SKELETON_TEXT, R as RegionSkeleton, c as RenderCaps, S as ServedEdits, d as SkeletonNode, e as SkeletonRole } from './region-skeleton-D2ahkcbe.cjs';
|
|
5
|
-
export { ConsentPreset, ConsentSource, ConsentWatcher } from './index-consent.cjs';
|
|
5
|
+
export { ConsentPreset, ConsentSource, ConsentWatcher, forgetVisitor } from './index-consent.cjs';
|
|
6
6
|
export { SlotResult } from '@sentientui/policy';
|
package/dist/index.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
export { B as BLOCK_ALIGNS, a as BLOCK_EMPHASES, b as BLOCK_FITS, c as BLOCK_GAPS, d as BLOCK_GRID_COLUMNS, e as BLOCK_HEADING_LEVELS, f as BLOCK_JUSTIFIES, g as BLOCK_MAX_WIDTHS, h as BLOCK_PADS, i as BLOCK_RATIOS, j as BLOCK_SIZES, k as BLOCK_SURFACES, l as BLOCK_TEXT_ALIGNS, m as BLOCK_TONES, n as BLOCK_WEIGHTS, o as BadgeBlock, p as BlockAlign, q as BlockEmphasis, r as BlockFit, s as BlockGap, t as BlockJustify, u as BlockMaxWidth, v as BlockNode, w as BlockPad, x as BlockRatio, y as BlockSize, z as BlockSurface, A as BlockTextAlign, C as BlockTone, D as BlockWeight, E as ButtonBlock, F as ComposeArm, G as DividerBlock, H as FORM_FIELD_KINDS, I as FORM_INPUT_TYPES, J as FormBlock, K as FormField, L as GridBlock, M as HeadingBlock, N as ImageBlock, P as LinkBlock, Q as MAX_BLOCK_ARMS, R as MAX_BLOCK_CHILDREN, S as MAX_BLOCK_DEPTH, T as MAX_BLOCK_NODES, U as MAX_BLOCK_TEXT_LEN, V as MAX_FORM_FIELDS, W as MAX_FORM_SELECT_OPTIONS, _ as SiteImage, $ as SitePalette, a0 as SpacerBlock, a1 as StackBlock, a2 as StyleEntry, a3 as StyleRole, a4 as StyleVocabulary, a5 as TextBlock, a6 as containsFormBlock } from './style-vocabulary-Ba_g6_DD.js';
|
|
2
|
-
export { A as AssignResult, a as Assignment, c as AuthoredArmReport, C as ComponentGoalOptions, d as ComponentWeightEntry, D as DecideInput, e as DecideOutcome, f as EventType, G as GoalDefinition, g as GoalOptions, i as GraphConfig, j as GraphSnapshot, L as LEGACY_SESSION_COOKIE_NAME, k as LOCAL_MODE_BANNER, M as MicroSignalEmitter, l as MicroSignalType, P as PAGE_SCOPE_RE, m as PROD_KEYLESS_ERROR, Q as QueueConfig, R as REVEAL_MS, o as RevealOptions, S as SectionMapEntry, p as SentientClient, q as SentientConfig, r as SentientEvent, s as SessionConfig, t as SessionManager, u as SkeletonReport, W as WeightEntry, _ as _registerConsentUpgradeInit, v as
|
|
2
|
+
export { A as AssignResult, a as Assignment, c as AuthoredArmReport, C as ComponentGoalOptions, d as ComponentWeightEntry, D as DecideInput, e as DecideOutcome, f as EventType, G as GoalDefinition, g as GoalOptions, i as GraphConfig, j as GraphSnapshot, L as LEGACY_SESSION_COOKIE_NAME, k as LOCAL_MODE_BANNER, M as MicroSignalEmitter, l as MicroSignalType, P as PAGE_SCOPE_RE, m as PROD_KEYLESS_ERROR, Q as QueueConfig, R as REVEAL_MS, o as RevealOptions, S as SectionMapEntry, p as SentientClient, q as SentientConfig, r as SentientEvent, s as SessionConfig, t as SessionManager, u as SkeletonReport, W as WeightEntry, _ as _registerConsentUpgradeInit, v as applyNonce, w as attachMicroSignalDetectors, x as cspNonce, y as forgetGeneration, z as grantConsent, B as init, F as isDoNotTrackEnabled, H as pageScopeMatches, I as resetRevealStyles, J as reveal, K as routeKey, O as sessionCookieName, T as setCspNonce } from './index-DEwRTvxc.js';
|
|
3
3
|
export { A as AGENT_INTENTS, a as AgentIntent, C as CLICK_ID_KEYS, b as CompoundLocator, D as DecisionSnapshot, S as SNAPSHOT_STORAGE_KEY_PREFIX, d as SlotConfigEntry, e as SlotDeclInput, f as SlotOps, g as agentIntent, h as agentUaList, i as armOfResult, j as baselineResultFor, k as baselineSlots, m as classifiedAgents, n as deriveSessionSegment, o as detectDeviceClass, p as detectTimeOfDay, q as detectTrafficSource, r as extractTrackedParams, s as matchedAgentToken, t as readSnapshot, u as referrerDomainFromReferer, v as renderPrePaintScript, w as toWireSlot, x as uaTokenMatch, y as writeSnapshot } from './session-meta-CKXcaBjt.js';
|
|
4
4
|
export { A as ArmEdits, M as MAX_SKELETON_LEAVES, a as MAX_SKELETON_NODES, b as MAX_SKELETON_TEXT, R as RegionSkeleton, c as RenderCaps, S as ServedEdits, d as SkeletonNode, e as SkeletonRole } from './region-skeleton-D2ahkcbe.js';
|
|
5
|
-
export { ConsentPreset, ConsentSource, ConsentWatcher } from './index-consent.js';
|
|
5
|
+
export { ConsentPreset, ConsentSource, ConsentWatcher, forgetVisitor } from './index-consent.js';
|
|
6
6
|
export { SlotResult } from '@sentientui/policy';
|