@sentientui/core 0.29.1 → 0.31.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 +21 -5
- package/dist/chunk-SFNOFZUH.mjs +2 -0
- package/dist/chunk-SFNOFZUH.mjs.map +1 -0
- package/dist/{index-B0PkJoeB.d.cts → index-DErBinAw.d.cts} +68 -3
- package/dist/{index-BIdUwF-v.d.ts → index-DxWcBI5U.d.ts} +68 -3
- package/dist/index-engagement.d.cts +8 -2
- package/dist/index-engagement.d.ts +8 -2
- 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 +21 -5
- package/dist/index-graph.d.ts +21 -5
- 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 +2 -2
- package/dist/index-local.d.ts +2 -2
- package/dist/index-local.js +1 -1
- package/dist/index-local.js.map +1 -1
- package/dist/index-local.mjs +1 -1
- package/dist/index-local.mjs.map +1 -1
- package/dist/index-server.d.cts +14 -3
- package/dist/index-server.d.ts +14 -3
- 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/dist/{session-meta-CY_Luh5i.d.ts → session-meta-DydKfQiR.d.cts} +2 -0
- package/dist/{session-meta-CY_Luh5i.d.cts → session-meta-DydKfQiR.d.ts} +2 -0
- package/llms.txt +4 -4
- package/package.json +2 -2
- package/dist/chunk-HY23LTUY.mjs +0 -2
- package/dist/chunk-HY23LTUY.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"],"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","/** 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 { 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};\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 slotsFrom?: 'request' | 'registry';\n },\n sessionId: string,\n config: ServerAssignConfig,\n): Promise<DecideResult> {\n const timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n const declaredSlots = params.slots ?? [];\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 ...(params.slotsFrom === 'registry' ? { slotsFrom: 'registry' } : {}),\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 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 };\n } catch (err) {\n console.error('[SentientUI] preloadDecisions: decide threw', err);\n return fallback;\n }\n}\n"],"mappings":"4wBAAA,IAAAA,GAAA,GAAAC,GAAAD,GAAA,mBAAAE,EAAA,8BAAAC,EAAA,yBAAAC,EAAA,sBAAAC,EAAA,oBAAAC,EAAA,wBAAAC,EAAA,yBAAAC,EAAA,uBAAAC,EAAA,qBAAAC,EAAA,sBAAAC,EAAA,8BAAAC,IAAA,eAAAC,GAAAb,ICQO,IAAMc,GAAiC,CAC5C,SACA,eACA,gBACA,YACA,cACA,mBACA,gBACA,kBACA,kBACA,oBACA,qBACA,aACA,QACA,YACA,YACA,SACF,EAGO,SAASC,GAAaC,EAA4B,CACvD,OAAOC,GAAkBD,CAAS,IAAM,IAC1C,CAGO,SAASC,GAAkBD,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,EAAE,OAASC,EAAO,KAAM,MAAO,QACtD,OAAQC,EAAA,CAER,CAEF,IAAMC,EAAOF,EAAO,SAAS,YAAY,EACzC,MAAI,yCAAyC,KAAKE,CAAI,EAAU,SAI5D,6EAA6E,KAAKA,CAAI,EAAU,SAC7F,UACT,OAAQD,E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AASR,EAAAO,EAAK,UAAL,KAAAP,EAAgB,UACzB,YAAYC,EAAAM,EAAK,aAAL,KAAAN,EAAmB,GAC3BW,EAAe,CAAE,WAAYL,EAAK,UAAW,EAAI,CAAC,GAClDA,EAAK,QAAU,CAAE,QAASA,EAAK,OAAQ,EAAI,CAAC,EAEpD,OAAS7B,EAAK,CACZ,eAAQ,MAAM,8CAA+CA,CAAG,EACzDyB,CACT,CACF","names":["index_server_exports","__export","CLICK_ID_KEYS","buildSessionUpsertPayload","deriveSessionSegment","detectDeviceClass","detectTimeOfDay","detectTrafficSource","extractTrackedParams","preloadAssignments","preloadDecisions","readSessionCookie","referrerDomainFromReferer","__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","fallback","baselineSlots","sessionRes","toWireSlot","data","slots","d","baselineResultFor","slotId","slotConfigOk"]}
|
|
1
|
+
{"version":3,"sources":["../src/index-server.ts","../src/session-meta.ts","../src/storage-key.ts","../src/slots.ts","../src/server.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","/** 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 { 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};\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 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 ? { slotsFrom: 'registry', registrySlotIds: registryIds, bootstrap: false } : {}),\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 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 };\n } catch (err) {\n console.error('[SentientUI] preloadDecisions: decide threw', err);\n return fallback;\n }\n}\n"],"mappings":"8wBAAA,IAAAA,GAAA,GAAAC,GAAAD,GAAA,mBAAAE,EAAA,8BAAAC,EAAA,yBAAAC,EAAA,sBAAAC,EAAA,oBAAAC,EAAA,wBAAAC,EAAA,yBAAAC,EAAA,uBAAAC,EAAA,qBAAAC,EAAA,sBAAAC,EAAA,8BAAAC,IAAA,eAAAC,GAAAb,ICQO,IAAMc,GAAiC,CAC5C,SACA,eACA,gBACA,YACA,cACA,mBACA,gBACA,kBACA,kBACA,oBACA,qBACA,aACA,QACA,YACA,YACA,SACF,EAGO,SAASC,GAAaC,EAA4B,CACvD,OAAOC,GAAkBD,CAAS,IAAM,IAC1C,CAGO,SAASC,GAAkBD,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,CAC3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C,EAAI,KAAK,EAUvBiC,EAAoC,CAAC,EAC3C,QAAWC,KAAKR,EAEdO,EAAMC,EAAE,EAAE,GAAIf,GAAAD,EAAAc,EAAK,QAAL,YAAAd,EAAagB,EAAE,MAAf,KAAAf,EAAsBgB,EAAkBD,CAAC,EAKzD,OAAW,CAACE,EAAQ7B,CAAM,IAAK,OAAO,SAAQa,EAAAY,EAAK,QAAL,KAAAZ,EAAc,CAAC,CAAC,EACtDgB,KAAUH,IAAQA,EAAMG,CAAM,EAAI7B,GAK1C,IAAM8B,EACJL,EAAK,aAAe,QAAa,OAAOA,EAAK,YAAe,UAAYA,EAAK,aAAe,MAAQ,CAAC,MAAM,QAAQA,EAAK,UAAU,EAEpI,OAAOzC,IAAA,CACL,aAAa+B,GAAAD,EAAAW,EAAK,cAAL,KAAAX,EAAoBJ,EAAO,WAA3B,KAAAK,EAAuC,CAAC,EACrD,aAAaC,EAAAS,EAAK,cAAL,KAAAT,EAAoB,CAAC,EAClC,MAAAU,EACA,SAAST,EAAAQ,EAAK,UAAL,KAAAR,EAAgB,UACzB,YAAYC,EAAAO,EAAK,aAAL,KAAAP,EAAmB,GAC3BY,EAAe,CAAE,WAAYL,EAAK,UAAW,EAAI,CAAC,GAClDA,EAAK,QAAU,CAAE,QAASA,EAAK,OAAQ,EAAI,CAAC,EAEpD,OAAS9B,EAAK,CACZ,eAAQ,MAAM,8CAA+CA,CAAG,EACzD0B,CACT,CACF","names":["index_server_exports","__export","CLICK_ID_KEYS","buildSessionUpsertPayload","deriveSessionSegment","detectDeviceClass","detectTimeOfDay","detectTrafficSource","extractTrackedParams","preloadAssignments","preloadDecisions","readSessionCookie","referrerDomainFromReferer","__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","d","baselineResultFor","slotId","slotConfigOk"]}
|
package/dist/index-server.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{b as T,c as
|
|
1
|
+
import{b as T,c as U,j as M,k as F,l as _,m as K,n as B,o as J,p as q,q as b,r as w,s as j,t as x}from"./chunk-2NVSFI4V.mjs";import{a,b as D}from"./chunk-TMCGHANO.mjs";var E=1e3;function A(s,l,e){let i=new AbortController,n=setTimeout(()=>i.abort(),e);return fetch(s,D(a({},l),{signal:i.signal})).finally(()=>clearTimeout(n))}async function L(s,l,e){var y;if(e.doNotTrack)return{};let i=(y=e.timeoutMs)!=null?y:E,n={"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`};e.origin&&(n.Origin=e.origin);let c=a(a({},b(l,{userAgent:e.userAgent,referer:e.referer,utmParams:e.utmParams,clickIds:e.clickIds,appOrigin:e.origin})),e.persona?{persona:e.persona}:{});try{let t=await A(`${e.baseUrl}/sessions`,{method:"POST",headers:n,body:JSON.stringify(c)},i);if(t.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(!t.ok){let p=await t.json().catch(()=>({}));console.error(`[SentientUI] preloadAssignments: session upsert failed (${t.status})`,p)}}catch(t){console.error("[SentientUI] preloadAssignments: session upsert threw",t)}let m=await Promise.allSettled(s.map(async({id:t,variantIds:p})=>{let u=await A(`${e.baseUrl}/assign`,{method:"POST",headers:n,body:JSON.stringify({sessionId:l,componentId:t,variantIds:p})},i);if(!u.ok){let f=await u.json().catch(()=>({}));return console.error(`[SentientUI] preloadAssignments: assign failed for "${t}" (${u.status})`,f),null}let S=await u.json();return{id:t,variantId:S.variantId}})),g={};for(let t of m)t.status==="fulfilled"&&t.value&&(g[t.value.id]=t.value.variantId);return g}function z(s,l){var e,i,n,c;return(c=(n=l?(e=s.get(U(l)))==null?void 0:e.value:void 0)!=null?n:(i=s.get(T))==null?void 0:i.value)!=null?c:null}async function W(s,l,e){var t,p,u,S,f,h,R,C,v,O,k,P;let i=(t=e.timeoutMs)!=null?t:E,n=(p=s.slots)!=null?p:[],c=null;s.slotsFrom==="registry"&&(Array.isArray(s.registrySlotIds)?c=s.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 m={layoutOrder:(u=s.sections)!=null?u:[],assignments:{},slots:x(n),persona:"unknown",confidence:0};if(e.doNotTrack)return m;let g={"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`};e.origin&&(g.Origin=e.origin);let y=a(a({},b(l,{userAgent:e.userAgent,referer:e.referer,utmParams:e.utmParams,clickIds:e.clickIds,appOrigin:e.origin})),e.persona?{persona:e.persona}:{});try{let o=await A(`${e.baseUrl}/sessions`,{method:"POST",headers:g,body:JSON.stringify(y)},i);if(!o.ok){let r=await o.json().catch(()=>({}));console.error(`[SentientUI] preloadDecisions: session upsert failed (${o.status})`,r)}}catch(o){console.error("[SentientUI] preloadDecisions: session upsert threw",o)}try{let o=await A(`${e.baseUrl}/decide`,{method:"POST",headers:g,body:JSON.stringify(a(a(a({sessionId:l,sections:((S=s.sections)!=null?S:[]).map(d=>({id:d})),components:s.components},n.length>0?{slots:n.map(w)}:{}),c!==null?{slotsFrom:"registry",registrySlotIds:c,bootstrap:!1}:{}),e.persona?{persona:e.persona}:{}))},i);if(!o.ok){let d=await o.json().catch(()=>({}));return console.error(`[SentientUI] preloadDecisions: decide failed (${o.status})`,d),m}let r=await o.json(),I={};for(let d of n)I[d.id]=(h=(f=r.slots)==null?void 0:f[d.id])!=null?h:j(d);for(let[d,N]of Object.entries((R=r.slots)!=null?R:{}))d in I||(I[d]=N);let $=r.slotConfig!==void 0&&typeof r.slotConfig=="object"&&r.slotConfig!==null&&!Array.isArray(r.slotConfig);return a(a({layoutOrder:(v=(C=r.layoutOrder)!=null?C:s.sections)!=null?v:[],assignments:(O=r.assignments)!=null?O:{},slots:I,persona:(k=r.persona)!=null?k:"unknown",confidence:(P=r.confidence)!=null?P:0},$?{slotConfig:r.slotConfig}:{}),r.palette?{palette:r.palette}:{})}catch(o){return console.error("[SentientUI] preloadDecisions: decide threw",o),m}}export{K as CLICK_ID_KEYS,b as buildSessionUpsertPayload,q as deriveSessionSegment,M as detectDeviceClass,J as detectTimeOfDay,F as detectTrafficSource,B as extractTrackedParams,L as preloadAssignments,W as preloadDecisions,z as readSessionCookie,_ as referrerDomainFromReferer};
|
|
2
2
|
//# sourceMappingURL=index-server.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/server.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 { 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};\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 slotsFrom?: 'request' | 'registry';\n },\n sessionId: string,\n config: ServerAssignConfig,\n): Promise<DecideResult> {\n const timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n const declaredSlots = params.slots ?? [];\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 ...(params.slotsFrom === 'registry' ? { slotsFrom: 'registry' } : {}),\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 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 };\n } catch (err) {\n console.error('[SentientUI] preloadDecisions: decide threw', err);\n return fallback;\n }\n}\n"],"mappings":"wKA6EA,IAAMA,EAAqB,IAE3B,SAASC,EACPC,EACAC,EACAC,EACmB,CACnB,IAAMC,EAAa,IAAI,gBACjBC,EAAQ,WAAW,IAAMD,EAAW,MAAM,EAAGD,CAAS,EAC5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A,EAAI,MAAM,IAAKC,CAAI,EAC3E0B,CACT,CACA,IAAMI,EAAQ,MAAM/B,EAAI,KAAK,EAUvBgC,EAAoC,CAAC,EAC3C,QAAWC,KAAKP,EAEdM,EAAMC,EAAE,EAAE,GAAId,GAAAD,EAAAa,EAAK,QAAL,YAAAb,EAAae,EAAE,MAAf,KAAAd,EAAsBe,EAAkBD,CAAC,EAKzD,OAAW,CAACE,EAAQ5B,CAAM,IAAK,OAAO,SAAQa,EAAAW,EAAK,QAAL,KAAAX,EAAc,CAAC,CAAC,EACtDe,KAAUH,IAAQA,EAAMG,CAAM,EAAI5B,GAK1C,IAAM6B,EACJL,EAAK,aAAe,QAAa,OAAOA,EAAK,YAAe,UAAYA,EAAK,aAAe,MAAQ,CAAC,MAAM,QAAQA,EAAK,UAAU,EAEpI,OAAOxC,IAAA,CACL,aAAa+B,GAAAD,EAAAU,EAAK,cAAL,KAAAV,EAAoBJ,EAAO,WAA3B,KAAAK,EAAuC,CAAC,EACrD,aAAaC,EAAAQ,EAAK,cAAL,KAAAR,EAAoB,CAAC,EAClC,MAAAS,EACA,SAASR,EAAAO,EAAK,UAAL,KAAAP,EAAgB,UACzB,YAAYC,EAAAM,EAAK,aAAL,KAAAN,EAAmB,GAC3BW,EAAe,CAAE,WAAYL,EAAK,UAAW,EAAI,CAAC,GAClDA,EAAK,QAAU,CAAE,QAASA,EAAK,OAAQ,EAAI,CAAC,EAEpD,OAAS7B,EAAK,CACZ,eAAQ,MAAM,8CAA+CA,CAAG,EACzDyB,CACT,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","fallback","baselineSlots","sessionRes","toWireSlot","data","slots","d","baselineResultFor","slotId","slotConfigOk"]}
|
|
1
|
+
{"version":3,"sources":["../src/server.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 { 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};\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 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 ? { slotsFrom: 'registry', registrySlotIds: registryIds, bootstrap: false } : {}),\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 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 };\n } catch (err) {\n console.error('[SentientUI] preloadDecisions: decide threw', err);\n return fallback;\n }\n}\n"],"mappings":"wKA6EA,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,CAlH9B,IAAAC,EAoHE,GAAID,EAAO,WAAY,MAAO,CAAC,EAE/B,IAAM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UvBiC,EAAoC,CAAC,EAC3C,QAAW,KAAKP,EAEdO,EAAM,EAAE,EAAE,GAAId,GAAAD,EAAAc,EAAK,QAAL,YAAAd,EAAa,EAAE,MAAf,KAAAC,EAAsBe,EAAkB,CAAC,EAKzD,OAAW,CAACC,EAAQ5B,CAAM,IAAK,OAAO,SAAQa,EAAAY,EAAK,QAAL,KAAAZ,EAAc,CAAC,CAAC,EACtDe,KAAUF,IAAQA,EAAME,CAAM,EAAI5B,GAK1C,IAAM6B,EACJJ,EAAK,aAAe,QAAa,OAAOA,EAAK,YAAe,UAAYA,EAAK,aAAe,MAAQ,CAAC,MAAM,QAAQA,EAAK,UAAU,EAEpI,OAAOzC,IAAA,CACL,aAAa+B,GAAAD,EAAAW,EAAK,cAAL,KAAAX,EAAoBJ,EAAO,WAA3B,KAAAK,EAAuC,CAAC,EACrD,aAAaC,EAAAS,EAAK,cAAL,KAAAT,EAAoB,CAAC,EAClC,MAAAU,EACA,SAAST,EAAAQ,EAAK,UAAL,KAAAR,EAAgB,UACzB,YAAYC,EAAAO,EAAK,aAAL,KAAAP,EAAmB,GAC3BW,EAAe,CAAE,WAAYJ,EAAK,UAAW,EAAI,CAAC,GAClDA,EAAK,QAAU,CAAE,QAASA,EAAK,OAAQ,EAAI,CAAC,EAEpD,OAAS9B,EAAK,CACZ,eAAQ,MAAM,8CAA+CA,CAAG,EACzD0B,CACT,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","baselineResultFor","slotId","slotConfigOk"]}
|
package/dist/index.d.cts
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
export { A as AGENT_INTENTS, a as AgentIntent, B as BLOCK_ALIGNS, b as BLOCK_EMPHASES, c as BLOCK_FITS, d as BLOCK_GAPS, e as BLOCK_GRID_COLUMNS, f as BLOCK_HEADING_LEVELS, g as BLOCK_JUSTIFIES, h as BLOCK_MAX_WIDTHS, i as BLOCK_PADS, j as BLOCK_RATIOS, k as BLOCK_SIZES, l as BLOCK_SURFACES, m as BLOCK_TEXT_ALIGNS, n as BLOCK_TONES, o as BLOCK_WEIGHTS, p as BadgeBlock, q as BlockAlign, r as BlockEmphasis, s as BlockFit, t as BlockGap, u as BlockJustify, v as BlockMaxWidth, w as BlockNode, x as BlockPad, y as BlockRatio, z as BlockSize, C as BlockSurface, D as BlockTextAlign, E as BlockTone, F as BlockWeight, G as ButtonBlock, H as CLICK_ID_KEYS, I as CompoundLocator, J as DecisionSnapshot, K as DividerBlock, L as FORM_FIELD_KINDS, M as FORM_INPUT_TYPES, N as FormBlock, O as FormField, P as GridBlock, Q as HeadingBlock, R as ImageBlock, S as LinkBlock, T as MAX_BLOCK_ARMS, U as MAX_BLOCK_CHILDREN, V as MAX_BLOCK_DEPTH, W as MAX_BLOCK_NODES, X as MAX_BLOCK_TEXT_LEN, Y as MAX_FORM_FIELDS, Z as MAX_FORM_SELECT_OPTIONS, _ as SNAPSHOT_STORAGE_KEY_PREFIX, a0 as SitePalette, a1 as SlotConfigEntry, a2 as SlotDeclInput, a3 as SlotOps, a4 as SpacerBlock, a5 as StackBlock, a6 as TextBlock, a7 as agentIntent, a8 as agentUaList, a9 as armOfResult, aa as baselineResultFor, ab as baselineSlots, ad as classifiedAgents, ae as containsFormBlock, af as deriveSessionSegment, ag as detectDeviceClass, ah as detectTimeOfDay, ai as detectTrafficSource, aj as extractTrackedParams, ak as matchedAgentToken, al as readSnapshot, am as referrerDomainFromReferer, an as renderPrePaintScript, ao as toWireSlot, ap as uaTokenMatch, aq as writeSnapshot } from './session-meta-
|
|
2
|
-
export { A as AssignResult, a as Assignment, C as ComponentGoalOptions, c as ComponentWeightEntry, D as DecideInput, d as DecideOutcome, e as EventType, G as GoalDefinition, f as GoalOptions, h as GraphConfig, i as GraphSnapshot, L as LEGACY_SESSION_COOKIE_NAME, j as LOCAL_MODE_BANNER, M as MicroSignalEmitter, k as MicroSignalType, P as PROD_KEYLESS_ERROR, Q as QueueConfig, R as REVEAL_MS,
|
|
1
|
+
export { A as AGENT_INTENTS, a as AgentIntent, B as BLOCK_ALIGNS, b as BLOCK_EMPHASES, c as BLOCK_FITS, d as BLOCK_GAPS, e as BLOCK_GRID_COLUMNS, f as BLOCK_HEADING_LEVELS, g as BLOCK_JUSTIFIES, h as BLOCK_MAX_WIDTHS, i as BLOCK_PADS, j as BLOCK_RATIOS, k as BLOCK_SIZES, l as BLOCK_SURFACES, m as BLOCK_TEXT_ALIGNS, n as BLOCK_TONES, o as BLOCK_WEIGHTS, p as BadgeBlock, q as BlockAlign, r as BlockEmphasis, s as BlockFit, t as BlockGap, u as BlockJustify, v as BlockMaxWidth, w as BlockNode, x as BlockPad, y as BlockRatio, z as BlockSize, C as BlockSurface, D as BlockTextAlign, E as BlockTone, F as BlockWeight, G as ButtonBlock, H as CLICK_ID_KEYS, I as CompoundLocator, J as DecisionSnapshot, K as DividerBlock, L as FORM_FIELD_KINDS, M as FORM_INPUT_TYPES, N as FormBlock, O as FormField, P as GridBlock, Q as HeadingBlock, R as ImageBlock, S as LinkBlock, T as MAX_BLOCK_ARMS, U as MAX_BLOCK_CHILDREN, V as MAX_BLOCK_DEPTH, W as MAX_BLOCK_NODES, X as MAX_BLOCK_TEXT_LEN, Y as MAX_FORM_FIELDS, Z as MAX_FORM_SELECT_OPTIONS, _ as SNAPSHOT_STORAGE_KEY_PREFIX, a0 as SitePalette, a1 as SlotConfigEntry, a2 as SlotDeclInput, a3 as SlotOps, a4 as SpacerBlock, a5 as StackBlock, a6 as TextBlock, a7 as agentIntent, a8 as agentUaList, a9 as armOfResult, aa as baselineResultFor, ab as baselineSlots, ad as classifiedAgents, ae as containsFormBlock, af as deriveSessionSegment, ag as detectDeviceClass, ah as detectTimeOfDay, ai as detectTrafficSource, aj as extractTrackedParams, ak as matchedAgentToken, al as readSnapshot, am as referrerDomainFromReferer, an as renderPrePaintScript, ao as toWireSlot, ap as uaTokenMatch, aq as writeSnapshot } from './session-meta-DydKfQiR.cjs';
|
|
2
|
+
export { A as AssignResult, a as Assignment, C as ComponentGoalOptions, c as ComponentWeightEntry, D as DecideInput, d as DecideOutcome, e as EventType, G as GoalDefinition, f as GoalOptions, h as GraphConfig, i as GraphSnapshot, L as LEGACY_SESSION_COOKIE_NAME, j as LOCAL_MODE_BANNER, M as MicroSignalEmitter, k as MicroSignalType, P as PAGE_SCOPE_RE, l as PROD_KEYLESS_ERROR, Q as QueueConfig, R as REVEAL_MS, n as RevealOptions, S as SectionMapEntry, o as SentientClient, p as SentientConfig, q as SentientEvent, r as SessionConfig, s as SessionManager, W as WeightEntry, _ as _registerConsentUpgradeInit, t as attachMicroSignalDetectors, u as grantConsent, v as init, w as isDoNotTrackEnabled, x as pageScopeMatches, y as resetRevealStyles, z as reveal, F as sessionCookieName } from './index-DErBinAw.cjs';
|
|
3
3
|
export { SlotResult } from '@sentientui/policy';
|
package/dist/index.d.ts
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
export { A as AGENT_INTENTS, a as AgentIntent, B as BLOCK_ALIGNS, b as BLOCK_EMPHASES, c as BLOCK_FITS, d as BLOCK_GAPS, e as BLOCK_GRID_COLUMNS, f as BLOCK_HEADING_LEVELS, g as BLOCK_JUSTIFIES, h as BLOCK_MAX_WIDTHS, i as BLOCK_PADS, j as BLOCK_RATIOS, k as BLOCK_SIZES, l as BLOCK_SURFACES, m as BLOCK_TEXT_ALIGNS, n as BLOCK_TONES, o as BLOCK_WEIGHTS, p as BadgeBlock, q as BlockAlign, r as BlockEmphasis, s as BlockFit, t as BlockGap, u as BlockJustify, v as BlockMaxWidth, w as BlockNode, x as BlockPad, y as BlockRatio, z as BlockSize, C as BlockSurface, D as BlockTextAlign, E as BlockTone, F as BlockWeight, G as ButtonBlock, H as CLICK_ID_KEYS, I as CompoundLocator, J as DecisionSnapshot, K as DividerBlock, L as FORM_FIELD_KINDS, M as FORM_INPUT_TYPES, N as FormBlock, O as FormField, P as GridBlock, Q as HeadingBlock, R as ImageBlock, S as LinkBlock, T as MAX_BLOCK_ARMS, U as MAX_BLOCK_CHILDREN, V as MAX_BLOCK_DEPTH, W as MAX_BLOCK_NODES, X as MAX_BLOCK_TEXT_LEN, Y as MAX_FORM_FIELDS, Z as MAX_FORM_SELECT_OPTIONS, _ as SNAPSHOT_STORAGE_KEY_PREFIX, a0 as SitePalette, a1 as SlotConfigEntry, a2 as SlotDeclInput, a3 as SlotOps, a4 as SpacerBlock, a5 as StackBlock, a6 as TextBlock, a7 as agentIntent, a8 as agentUaList, a9 as armOfResult, aa as baselineResultFor, ab as baselineSlots, ad as classifiedAgents, ae as containsFormBlock, af as deriveSessionSegment, ag as detectDeviceClass, ah as detectTimeOfDay, ai as detectTrafficSource, aj as extractTrackedParams, ak as matchedAgentToken, al as readSnapshot, am as referrerDomainFromReferer, an as renderPrePaintScript, ao as toWireSlot, ap as uaTokenMatch, aq as writeSnapshot } from './session-meta-
|
|
2
|
-
export { A as AssignResult, a as Assignment, C as ComponentGoalOptions, c as ComponentWeightEntry, D as DecideInput, d as DecideOutcome, e as EventType, G as GoalDefinition, f as GoalOptions, h as GraphConfig, i as GraphSnapshot, L as LEGACY_SESSION_COOKIE_NAME, j as LOCAL_MODE_BANNER, M as MicroSignalEmitter, k as MicroSignalType, P as PROD_KEYLESS_ERROR, Q as QueueConfig, R as REVEAL_MS,
|
|
1
|
+
export { A as AGENT_INTENTS, a as AgentIntent, B as BLOCK_ALIGNS, b as BLOCK_EMPHASES, c as BLOCK_FITS, d as BLOCK_GAPS, e as BLOCK_GRID_COLUMNS, f as BLOCK_HEADING_LEVELS, g as BLOCK_JUSTIFIES, h as BLOCK_MAX_WIDTHS, i as BLOCK_PADS, j as BLOCK_RATIOS, k as BLOCK_SIZES, l as BLOCK_SURFACES, m as BLOCK_TEXT_ALIGNS, n as BLOCK_TONES, o as BLOCK_WEIGHTS, p as BadgeBlock, q as BlockAlign, r as BlockEmphasis, s as BlockFit, t as BlockGap, u as BlockJustify, v as BlockMaxWidth, w as BlockNode, x as BlockPad, y as BlockRatio, z as BlockSize, C as BlockSurface, D as BlockTextAlign, E as BlockTone, F as BlockWeight, G as ButtonBlock, H as CLICK_ID_KEYS, I as CompoundLocator, J as DecisionSnapshot, K as DividerBlock, L as FORM_FIELD_KINDS, M as FORM_INPUT_TYPES, N as FormBlock, O as FormField, P as GridBlock, Q as HeadingBlock, R as ImageBlock, S as LinkBlock, T as MAX_BLOCK_ARMS, U as MAX_BLOCK_CHILDREN, V as MAX_BLOCK_DEPTH, W as MAX_BLOCK_NODES, X as MAX_BLOCK_TEXT_LEN, Y as MAX_FORM_FIELDS, Z as MAX_FORM_SELECT_OPTIONS, _ as SNAPSHOT_STORAGE_KEY_PREFIX, a0 as SitePalette, a1 as SlotConfigEntry, a2 as SlotDeclInput, a3 as SlotOps, a4 as SpacerBlock, a5 as StackBlock, a6 as TextBlock, a7 as agentIntent, a8 as agentUaList, a9 as armOfResult, aa as baselineResultFor, ab as baselineSlots, ad as classifiedAgents, ae as containsFormBlock, af as deriveSessionSegment, ag as detectDeviceClass, ah as detectTimeOfDay, ai as detectTrafficSource, aj as extractTrackedParams, ak as matchedAgentToken, al as readSnapshot, am as referrerDomainFromReferer, an as renderPrePaintScript, ao as toWireSlot, ap as uaTokenMatch, aq as writeSnapshot } from './session-meta-DydKfQiR.js';
|
|
2
|
+
export { A as AssignResult, a as Assignment, C as ComponentGoalOptions, c as ComponentWeightEntry, D as DecideInput, d as DecideOutcome, e as EventType, G as GoalDefinition, f as GoalOptions, h as GraphConfig, i as GraphSnapshot, L as LEGACY_SESSION_COOKIE_NAME, j as LOCAL_MODE_BANNER, M as MicroSignalEmitter, k as MicroSignalType, P as PAGE_SCOPE_RE, l as PROD_KEYLESS_ERROR, Q as QueueConfig, R as REVEAL_MS, n as RevealOptions, S as SectionMapEntry, o as SentientClient, p as SentientConfig, q as SentientEvent, r as SessionConfig, s as SessionManager, W as WeightEntry, _ as _registerConsentUpgradeInit, t as attachMicroSignalDetectors, u as grantConsent, v as init, w as isDoNotTrackEnabled, x as pageScopeMatches, y as resetRevealStyles, z as reveal, F as sessionCookieName } from './index-DxWcBI5U.js';
|
|
3
3
|
export { SlotResult } from '@sentientui/policy';
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var Kt=Object.create;var fe=Object.defineProperty,Gt=Object.defineProperties,Ut=Object.getOwnPropertyDescriptor,Ft=Object.getOwnPropertyDescriptors,$t=Object.getOwnPropertyNames,ut=Object.getOwnPropertySymbols,Wt=Object.getPrototypeOf,gt=Object.prototype.hasOwnProperty,jt=Object.prototype.propertyIsEnumerable;var pt=(e,t,n)=>t in e?fe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,b=(e,t)=>{for(var n in t||(t={}))gt.call(t,n)&&pt(e,n,t[n]);if(ut)for(var n of ut(t))jt.call(t,n)&&pt(e,n,t[n]);return e},oe=(e,t)=>Gt(e,Ft(t));var zt=(e,t)=>{for(var n in t)fe(e,n,{get:t[n],enumerable:!0})},ft=(e,t,n,l)=>{if(t&&typeof t=="object"||typeof t=="function")for(let u of $t(t))!gt.call(e,u)&&u!==n&&fe(e,u,{get:()=>t[u],enumerable:!(l=Ut(t,u))||l.enumerable});return e};var Ht=(e,t,n)=>(n=e!=null?Kt(Wt(e)):{},ft(t||!e||!e.__esModule?fe(n,"default",{value:e,enumerable:!0}):n,e)),Qt=e=>ft(fe({},"__esModule",{value:!0}),e);var Jn={};zt(Jn,{AGENT_INTENTS:()=>Pe,BLOCK_ALIGNS:()=>mn,BLOCK_EMPHASES:()=>xn,BLOCK_FITS:()=>wn,BLOCK_GAPS:()=>fn,BLOCK_GRID_COLUMNS:()=>En,BLOCK_HEADING_LEVELS:()=>Cn,BLOCK_JUSTIFIES:()=>yn,BLOCK_MAX_WIDTHS:()=>An,BLOCK_PADS:()=>_n,BLOCK_RATIOS:()=>bn,BLOCK_SIZES:()=>Sn,BLOCK_SURFACES:()=>In,BLOCK_TEXT_ALIGNS:()=>kn,BLOCK_TONES:()=>vn,BLOCK_WEIGHTS:()=>hn,CLICK_ID_KEYS:()=>He,FORM_FIELD_KINDS:()=>Rn,FORM_INPUT_TYPES:()=>On,LEGACY_SESSION_COOKIE_NAME:()=>Fe,LOCAL_MODE_BANNER:()=>Qe,MAX_BLOCK_ARMS:()=>Mn,MAX_BLOCK_CHILDREN:()=>Dn,MAX_BLOCK_DEPTH:()=>Ln,MAX_BLOCK_NODES:()=>Pn,MAX_BLOCK_TEXT_LEN:()=>Nn,MAX_FORM_FIELDS:()=>Tn,MAX_FORM_SELECT_OPTIONS:()=>Bn,PROD_KEYLESS_ERROR:()=>Ke,REVEAL_MS:()=>Rt,SNAPSHOT_STORAGE_KEY_PREFIX:()=>ne,_registerConsentUpgradeInit:()=>Un,agentIntent:()=>kt,agentUaList:()=>ye,armOfResult:()=>De,attachMicroSignalDetectors:()=>Bt,baselineResultFor:()=>ae,baselineSlots:()=>Et,classifiedAgents:()=>bt,containsFormBlock:()=>At,deriveSessionSegment:()=>wt,detectDeviceClass:()=>he,detectTimeOfDay:()=>ke,detectTrafficSource:()=>ve,extractTrackedParams:()=>Le,grantConsent:()=>Hn,init:()=>Nt,isDoNotTrackEnabled:()=>qe,matchedAgentToken:()=>ze,readSnapshot:()=>le,referrerDomainFromReferer:()=>xe,renderPrePaintScript:()=>Ct,resetRevealStyles:()=>Ot,reveal:()=>Tt,sessionCookieName:()=>_e,toWireSlot:()=>be,uaTokenMatch:()=>Se,writeSnapshot:()=>ce});module.exports=Qt(Jn);function Ie(){try{if(typeof crypto!="undefined"&&typeof crypto.randomUUID=="function")return crypto.randomUUID()}catch(e){}try{if(typeof crypto!="undefined"&&typeof crypto.getRandomValues=="function"){let e=new Uint8Array(16);crypto.getRandomValues(e),e[6]=e[6]&15|64,e[8]=e[8]&63|128;let t="";for(let n=0;n<16;n++)t+=e[n].toString(16).padStart(2,"0"),(n===3||n===5||n===7||n===9)&&(t+="-");return t}}catch(e){}return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})}function me(e){return e?`_${e.slice(0,12)}`:""}var Fe="_snt_uid";function _e(e){return`${Fe}${me(e)}`}var Jt="_snt_uid",Vt=365,Ae="_snt_uid";function Xt(){return Ie()}function mt(e){try{let t=document.cookie.match(new RegExp(`(?:^|; )${e}=([^;]*)`));return t?decodeURIComponent(t[1]):null}catch(t){return null}}function Yt(e,t,n){try{document.cookie=`${e}=${encodeURIComponent(t)}; max-age=${n}; SameSite=strict; path=/`}catch(l){}}function $e(e){try{return localStorage.getItem(e)}catch(t){return null}}function yt(e,t){try{return localStorage.setItem(e,t),!0}catch(n){return!1}}function St(e){try{return sessionStorage.getItem(e)}catch(t){return null}}function qt(e,t){try{return sessionStorage.setItem(e,t),!0}catch(n){return!1}}function Zt(e){try{sessionStorage.removeItem(e)}catch(t){}}function en(e){try{return document.cookie=`${e}_probe=1; max-age=1; SameSite=strict; path=/`,document.cookie.indexOf(`${e}_probe=1`)!==-1}catch(t){return!1}}function tn(e){try{localStorage.removeItem(e)}catch(t){}}function nn(e){try{document.cookie=`${e}=; max-age=0; SameSite=strict; path=/`}catch(t){}}var rn={getSessionId:()=>null,isEphemeral:()=>!1,destroy:()=>{}};function Re(e){var E,P,L,C,U,$,A;if(typeof window=="undefined")return rn;let t=me(e==null?void 0:e.apiKey),n=(E=e==null?void 0:e.cookieName)!=null?E:_e(e==null?void 0:e.apiKey),l=`${Ae}${t}`,u=`${Ae}_tomb${t}`,d=((P=e==null?void 0:e.cookieTTLDays)!=null?P:Vt)*24*60*60,a=O=>O&&O.length>0?O:null,p=()=>{var O,R;return t&&!(e!=null&&e.cookieName)&&$e(u)===null?(R=(O=a(mt(Jt)))!=null?O:a($e(Ae)))!=null?R:a(St(Ae)):null},s=(A=($=(U=(C=(L=a(mt(n)))!=null?L:a($e(l)))!=null?C:a(St(l)))!=null?U:p())!=null?$:a(e==null?void 0:e.ssrSessionId))!=null?A:Xt();Yt(n,s,d);let r=yt(l,s),o=en(n),m=r?!1:qt(l,s),x=!r&&!o&&!m;return{getSessionId:()=>s,isEphemeral:()=>x,destroy:()=>{s=null,nn(n),tn(l),Zt(l),t&&!(e!=null&&e.cookieName)&&yt(u,"1")}}}function Y(e){return Math.min(6e4,1e3*2**Math.min(e,6))}function se(e){if(e.ok===!0)return"delivered";let{status:t}=e;return typeof t!="number"?"retry":t>=200&&t<300?"delivered":t>=400&&t<500&&t!==429?"dropped":"retry"}function Oe(e,t){try{let n=localStorage.getItem(e);if(!n)return[];let l=JSON.parse(n);return Array.isArray(l)?(localStorage.removeItem(e),l.slice(-t)):[]}catch(n){return[]}}function q(e,t,n){try{let l=(()=>{try{let i=localStorage.getItem(n);if(!i)return[];let d=JSON.parse(i);return Array.isArray(d)?d:[]}catch(i){return[]}})(),u=new Map;for(let i of l)u.set(i.id,i);for(let i of e)u.set(i.id,i);localStorage.setItem(n,JSON.stringify([...u.values()].slice(-t)))}catch(l){}}function Te(e,t){try{let n=localStorage.getItem(t);if(!n)return;let l=JSON.parse(n);if(!Array.isArray(l))return;let u=new Set(e),i=l.filter(d=>!u.has(d.id));if(i.length===l.length)return;i.length===0?localStorage.removeItem(t):localStorage.setItem(t,JSON.stringify(i))}catch(n){}}var on=500,sn=56*1024;function We(e){return`_snt_retry_${e.slice(0,12)}`}var an={push:()=>{},flush:()=>{},destroy:()=>{}};function ht(e){var Q,Z,ue;if(typeof window=="undefined")return an;let t=(Q=e.flushIntervalMs)!=null?Q:5e3,n=(Z=e.maxBatchSize)!=null?Z:20,l=(ue=e.maxRetrySize)!=null?ue:100,u=e.ingestUrl,i=e.apiKey,d=We(i),a=[],p=new Set,s=[],r=S=>{for(let v of S)o.delete(v),!p.has(v)&&(p.add(v),s.push(v));for(;s.length>on;){let v=s.shift();v&&p.delete(v)}Te(S,d)},o=new Set,m=()=>{for(;a.length>l;){let S=a.shift();S&&o.delete(S.id)}},x=S=>{p.has(S.id)||o.has(S.id)||(o.add(S.id),a.push(S),m())},E=S=>{for(let v of S)p.has(v.id)||(o.add(v.id),a.push(v));m()},P=Oe(d,l);for(let S of P)x(S);let L=0,C=0,U=(S,v=!0)=>{if(S.length===0)return;let J=JSON.stringify(S),N=S.map(K=>K.id),z;try{z=fetch(u,{method:"POST",keepalive:!0,body:J,headers:{"Content-Type":"application/json",Authorization:`Bearer ${i}`}})}catch(K){q(S,l,d),E(S),C++,L=Date.now()+Y(C);return}let Ee=K=>{if(se(K)!=="retry"){if(!K.ok&&v){let ee=S.filter(F=>F.eventType!=="pageview");if(ee.length>0&&ee.length<S.length){r(S.filter(F=>F.eventType==="pageview").map(F=>F.id)),U(ee,!1);return}}r(N),C=0,L=0;return}q(S,l,d),E(S),C++,L=Date.now()+Y(C)};z instanceof Promise?z.then(Ee).catch(()=>{q(S,l,d),E(S),C++,L=Date.now()+Y(C)}):Ee(z)},$=typeof TextEncoder!="undefined"?new TextEncoder:null,A=S=>$?$.encode(S).length:S.length,O=S=>{let v=[],J=2;for(let N of S){let z=A(JSON.stringify(N))+1;if(v.length>0&&J+z>sn||v.length>=n)break;v.push(N),J+=z}return v},R=()=>{try{if(Date.now()<L)return;for(;a.length>0&&!(Date.now()<L);){let S=a.filter(J=>!p.has(J.id));if(a.length=0,S.length===0)break;let v=O(S);if(v.length===0)break;v.length<S.length&&a.push(...S.slice(v.length)),U(v)}}catch(S){}},f=!0,T=null;T=setInterval(()=>{f&&R()},t);let W=()=>{document.visibilityState==="hidden"&&R()},j=()=>{R()};return document.addEventListener("visibilitychange",W),window.addEventListener("pagehide",j),{push(S){x(S),a.length>=n&&R()},flush:R,destroy(){f=!1,T!==null&&(clearInterval(T),T=null),document.removeEventListener("visibilitychange",W),window.removeEventListener("pagehide",j),R()}}}var ln=200;function je(e){return`_snt_goal_retry_${e.slice(0,12)}`}var cn={send:()=>{},flush:()=>{},destroy:()=>{}};function vt(e){var A,O,R;if(typeof window=="undefined")return cn;let t=(A=e.flushIntervalMs)!=null?A:5e3,n=(O=e.maxRetrySize)!=null?O:100,l=(R=e.maxPerFlush)!=null?R:5,u=je(e.apiKey),i=[],d=new Set,a=new Set,p=[],s=0,r=0,o=!1,m=f=>{for(d.delete(f.id),a.has(f.id)||(a.add(f.id),p.push(f.id));p.length>ln;){let T=p.shift();T&&a.delete(T)}Te([f.id],u)},x=f=>{q([f],n,u),!a.has(f.id)&&!d.has(f.id)&&(d.add(f.id),i.push(f)),Date.now()>=s&&(r++,s=Date.now()+Y(r))},E=f=>{let T;try{T=fetch(e.url,{method:"POST",keepalive:!0,body:f.body,headers:e.headers})}catch(j){x(f);return}let W=j=>{var Z;let Q=se(j);if(Q==="retry"){x(f);return}Q==="dropped"&&((Z=e.onDrop)==null||Z.call(e,f,j.status)),m(f),r=0,s=0};T instanceof Promise?T.then(W).catch(()=>x(f)):W(T)},P=()=>{try{if(o||Date.now()<s)return;let f=0;for(;i.length>0&&f<l&&!(Date.now()<s);){let T=i.shift();d.delete(T.id),!a.has(T.id)&&(f++,E(T))}}catch(f){}},L=Oe(u,n);for(let f of L)d.has(f.id)||(d.add(f.id),i.push(f));L.length>0&&q(L,n,u);let C=setInterval(P,t),U=()=>{document.visibilityState==="hidden"&&P()},$=()=>P();return document.addEventListener("visibilitychange",U),window.addEventListener("pagehide",$),{send(f){if(!o&&!(a.has(f.id)||d.has(f.id))){if(Date.now()<s){q([f],n,u),d.add(f.id),i.push(f);return}E(f)}},flush:P,destroy(){clearInterval(C),document.removeEventListener("visibilitychange",U),window.removeEventListener("pagehide",$),P(),o=!0}}}var dn=1800*1e3;function Be(e,t){return`${encodeURIComponent(e)}:${encodeURIComponent(t)}`}function xt(e=dn,t){let n=new Map,l=`_snt_asgn${me(t)}_`,u=(s,r)=>`${l}${encodeURIComponent(s)}:${encodeURIComponent(r)}`,i=s=>{let r=s.slice(l.length),o=r.indexOf(":");if(o<0)return null;try{return{componentId:decodeURIComponent(r.slice(0,o)),segment:decodeURIComponent(r.slice(o+1))}}catch(m){return null}},d=()=>{try{let s=[];for(let r=0;r<localStorage.length;r++){let o=localStorage.key(r);o!=null&&o.startsWith(l)&&s.push(o)}return s}catch(s){return[]}},a=s=>s.assignedAt+(s.ttlMs&&s.ttlMs>0?s.ttlMs:e)<Date.now();return typeof window!="undefined"&&(()=>{for(let s of d())try{let r=localStorage.getItem(s);if(!r)continue;let o=JSON.parse(r);if(a(o)){localStorage.removeItem(s);continue}let m=i(s);if(!m)continue;n.set(Be(m.componentId,m.segment),o)}catch(r){}})(),{get(s,r){let o=n.get(Be(s,r));return o?a(o)?(n.delete(Be(s,r)),null):o:null},set(s,r,o){let m=Be(s,r);n.set(m,o);try{localStorage.setItem(u(s,r),JSON.stringify(o))}catch(x){}},clear(){n.clear();for(let s of d())try{localStorage.removeItem(s)}catch(r){}}}}var ye=["GPTBot","ChatGPT-User","OAI-SearchBot","ClaudeBot","Claude-User","Claude-SearchBot","PerplexityBot","Perplexity-User","Google-Extended","Applebot-Extended","Meta-ExternalAgent","Bytespider","CCBot","Amazonbot","cohere-ai","Diffbot"];function Se(e){return ze(e)!==null}function ze(e){var n;if(!e)return null;let t=e.toLowerCase();return(n=ye.find(l=>t.includes(l.toLowerCase())))!=null?n:null}var Pe={GPTBot:"training","ChatGPT-User":"user","OAI-SearchBot":"search",ClaudeBot:"training","Claude-User":"user","Claude-SearchBot":"search",PerplexityBot:"search","Perplexity-User":"user","Google-Extended":"training","Applebot-Extended":"training","Meta-ExternalAgent":"training",Bytespider:"training",CCBot:"training",Amazonbot:"other","cohere-ai":"training",Diffbot:"other"};function kt(e){if(!e)return"other";let t=ye.find(n=>n.toLowerCase()===e.toLowerCase());return t&&Pe[t]||"other"}function bt(){var t;let e={user:[],search:[],training:[],other:[]};for(let n of ye)e[(t=Pe[n])!=null?t:"other"].push(n);return e}function he(e){let t=e.toLowerCase();return/ipad|tablet|playbook|kindle|silk/.test(t)?"tablet":/mobi|iphone|ipod|android.*mobile|phone/.test(t)?"mobile":"desktop"}function ve(e,t){if(!e)return"direct";try{let n=new URL(e);if(t)try{if(new URL(t).host===n.host)return"direct"}catch(u){}let l=n.hostname.toLowerCase();return/(^|\.)(google|bing|duckduckgo|yahoo)\./.test(l)?"search":/(^|\.)(twitter\.com|x\.com|facebook\.com|linkedin\.com|reddit\.com|t\.co)$/.test(l)?"social":"referral"}catch(n){return"direct"}}function xe(e){if(!e)return null;try{return new URL(e).hostname}catch(t){return null}}var He=["gclid","gbraid","wbraid","fbclid","ttclid","msclkid","twclid","li_fat_id"];function Le(e){let t={},n={};try{let l=typeof e=="string"||e instanceof URLSearchParams?new URLSearchParams(e):Object.entries(e).flatMap(([u,i])=>{let d=Array.isArray(i)?i[0]:i;return d===void 0?[]:[[u,d]]});for(let[u,i]of l)u.startsWith("utm_")?u in t||(t[u]=i):He.includes(u)&&(u in n||(n[u]=i))}catch(l){}return{utmParams:t,clickIds:n}}function ke(e){let t=e.getHours();return t<6?"night":t<12?"morning":t<18?"afternoon":"evening"}function wt(e){let t=un("__segment__",e);return`${t.deviceClass}:${t.trafficSource}`}function un(e,t){var i,d,a,p,s,r,o,m;let n=(d=(i=t==null?void 0:t.userAgent)==null?void 0:i.trim())!=null?d:"",l=(p=(a=t==null?void 0:t.referer)==null?void 0:a.trim())!=null?p:"",u=(s=t==null?void 0:t.now)!=null?s:new Date;return{sessionId:e,ephemeral:!1,utmParams:(r=t==null?void 0:t.utmParams)!=null?r:{},clickIds:(o=t==null?void 0:t.clickIds)!=null?o:{},deviceClass:n?he(n):"desktop",trafficSource:l?ve(l,t==null?void 0:t.appOrigin):"direct",referrerDomain:xe(l),timeOfDay:ke(u),dayOfWeek:(m=["sun","mon","tue","wed","thu","fri","sat"][u.getDay()])!=null?m:"sun",automation:(t==null?void 0:t.webdriver)===!0||Se(n)}}var ie=require("@sentientui/policy");function be(e){return b(b(b({id:e.id},e.arms?{arms:[...e.arms]}:{}),e.dims?{dims:Object.fromEntries(Object.entries(e.dims).map(([t,n])=>[t,[...n]]))}:{}),e.baseline!==void 0?{baseline:e.baseline}:{})}function ae(e){let t=be(e);return(0,ie.slotResultFor)(t,(0,ie.slotBaselineArm)(t))}function Et(e){let t={};for(let n of e)t[n.id]=ae(n);return t}function De(e){return typeof e=="string"?e:(0,ie.canonicalArm)(e)}var ne="_snt_snap:",pn=["low","medium","high"];function le(e){try{let t=localStorage.getItem(ne+e);if(!t)return null;let n=JSON.parse(t);return!n||typeof n!="object"||n.v!==1||typeof n.persona!="string"||typeof n.band!="string"||!pn.includes(n.band)||typeof n.slots!="object"||n.slots===null||Array.isArray(n.slots)||!(n.layoutOrder===null||Array.isArray(n.layoutOrder))||typeof n.savedAt!="number"||!(n.slotConfig===void 0||typeof n.slotConfig=="object"&&n.slotConfig!==null&&!Array.isArray(n.slotConfig))?null:n}catch(t){return null}}function ce(e,t){try{localStorage.setItem(ne+e,JSON.stringify(t))}catch(n){}}function Ct(e){return"(function(){try{var r=localStorage.getItem("+JSON.stringify(ne+e).replace(/</g,"\\u003c")+');if(!r)return;var s=JSON.parse(r);if(!s||s.v!==1||typeof s.persona!=="string"||typeof s.band!=="string")return;var d=document.documentElement;if(d.hasAttribute("data-sentient-persona"))return;d.setAttribute("data-sentient-persona",s.persona);d.setAttribute("data-sentient-confidence",s.band);}catch(e){}})();'}var Xe=require("@sentientui/policy");var Ne=require("@sentientui/policy");var Ke="[sentient] No API key configured \u2014 nothing is being learned. Set NEXT_PUBLIC_SENTIENT_API_KEY or pass localMode: true for local development.",Qe="[sentient] Local mode \u2014 decisions are simulated on-device and nothing is sent over the network. Add an API key to learn from real traffic.",It=!1,Me=!1;function gn(){var e;try{return(e=new URLSearchParams(window.location.search).get("sentient_persona"))!=null?e:void 0}catch(t){return}}function _t(e){var s;let t=Re({ssrSessionId:e.ssrSessionId,apiKey:e.apiKey}),n=(s=t.getSessionId())!=null?s:"local",l=gn(),u=import("@sentientui/core/local").then(r=>{let o=r;return o.LOCAL_ENGINE_AVAILABLE?(It||(It=!0,console.info(Qe)),o):(Me||(Me=!0,console.error(Ke)),null)}).catch(()=>(Me||(Me=!0,console.error(Ke)),null)),i=null,d={low:.15,medium:.5,high:.85},a=(()=>{var o;if(e.initialPersona)return b({},e.initialPersona);let r=le(e.apiKey||"local");return r?{persona:r.persona,confidence:(o=d[r.band])!=null?o:.15}:null})();function p(r){let o=document.documentElement;o.dataset.sentientPersona===void 0&&(o.dataset.sentientPersona=r.persona,o.dataset.sentientConfidence=(0,Ne.confidenceBand)(r.confidence))}return{isLocal:!0,async decide(r){var x,E,P;let o=await u;if(!o)return null;let m=o.createLocalEngine({sessionId:n,forcedPersona:l}).decide(r);return i=oe(b({},m),{layoutOrder:(E=(x=m.layoutOrder)!=null?x:i==null?void 0:i.layoutOrder)!=null?E:null,slots:b(b({},(P=i==null?void 0:i.slots)!=null?P:{}),m.slots)}),ce(e.apiKey||"local",{v:1,persona:i.persona,band:(0,Ne.confidenceBand)(i.confidence),slots:i.slots,layoutOrder:i.layoutOrder,savedAt:Date.now()}),p(m),m},getSlotResult(r){var o,m,x;return(x=(m=i==null?void 0:i.slots[r])!=null?m:(o=e.initialSlots)==null?void 0:o[r])!=null?x:null},getSlotConfig(r){var o,m;return(m=(o=e.initialSlotConfig)==null?void 0:o[r])!=null?m:null},getSitePalette(){var r;return(r=e.initialPalette)!=null?r:null},reportSlots(){},getPersona(){let r=i!=null?i:a;return r?{persona:r.persona,confidence:r.confidence,band:(0,Ne.confidenceBand)(r.confidence)}:null},async assign(r,o){var E;let m=await u;return!m||!o||o.length===0?o!=null&&o[0]?{variantId:o[0],assignmentTtlMs:0}:null:{variantId:(E=m.createLocalEngine({sessionId:n,forcedPersona:l}).decide({components:[{id:r,variantIds:o}]}).assignments[r])!=null?E:o[0],assignmentTtlMs:0}},track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},getAssignment:()=>null,fetchWeights:()=>Promise.resolve([]),getGraph:()=>({pageNodes:[],capturedAt:0}),dispose:()=>{},destroy:()=>t.destroy()}}var fn=["none","sm","md","lg"],mn=["start","center","end","stretch"],yn=["start","center","end","between"],Sn=["sm","md","lg"],hn=["normal","medium","bold"],vn=["default","muted","accent"],xn=["primary","secondary","ghost"],kn=["left","center","right"],bn=["auto","square","landscape","wide"],wn=["cover","contain"],En=[2,3,4],Cn=[2,3,4],In=["default","raised"],_n=["none","sm","md","lg"],An=["measure"],Rn=["input","textarea","select"],On=["text","email","number","tel"],Tn=5,Bn=8,Pn=64,Ln=5,Dn=12,Mn=4,Nn=500;function At(e){if(e==null||typeof e!="object"||Array.isArray(e))return!1;let t=e;return t.type==="form"?!0:Array.isArray(t.children)?t.children.some(At):!1}var Je="sentient-reveal",de="sentient-revealed",Rt=240,Ge=!1;function Ot(){var e;Ge=!1,typeof document!="undefined"&&((e=document.getElementById(Je))==null||e.remove())}function Kn(e){if(Ge||e.getElementById(Je)){Ge=!0;return}let t=e.createElement("style");t.id=Je,t.textContent=`@media (prefers-reduced-motion: no-preference){@keyframes ${de}{from{opacity:.55;transform:translateY(2px)}to{opacity:1;transform:none}}.${de}{animation:${de} 240ms cubic-bezier(.2,.6,.2,1) both}}`,e.head.appendChild(t),Ge=!0}function Tt(e,t={}){var u;let n=(u=t.doc)!=null?u:typeof document!="undefined"?document:void 0;if(!n||!(e instanceof Element)||(t.arm!==void 0&&e.setAttribute("data-sentient-arm",t.arm),t.persona!==void 0&&e.setAttribute("data-sentient-persona",t.persona),t.previous!==void 0&&t.previous===e.textContent))return!1;Kn(n),e.classList.remove(de),e.offsetWidth,e.classList.add(de);let l=()=>{e.classList.remove(de),e.removeEventListener("animationend",l)};return e.addEventListener("animationend",l),!0}function Bt(e,t,n,l){let u=[];{let a=!1,p=[],s=()=>{if(a)return;let r=Date.now();for(p.push(r);p.length>0&&r-p[0]>500;)p.shift();p.length>=3&&(a=!0,e("rage_click"))};t.addEventListener("click",s),u.push(()=>t.removeEventListener("click",s))}{let i=!1,d=a=>{if(i||!(a.target instanceof Node)||!t.contains(a.target)&&t!==a.target)return;i=!0;let p=typeof window!="undefined"?window.getSelection():null,s=p?p.toString().length:0;e("text_copy",{selectionLength:s})};document.addEventListener("copy",d),u.push(()=>document.removeEventListener("copy",d))}{let i=!1,d=!1,a=null,p=()=>{a!==null&&(clearTimeout(a),a=null)},s=()=>{i||!d||(p(),a=setTimeout(()=>{!i&&d&&(i=!0,e("scroll_hesitation"))},3e3))},r=()=>{p(),s()},o=x=>{for(let E of x)d=E.intersectionRatio>.3,d?s():p()},m=new IntersectionObserver(o,{threshold:[.3]});m.observe(t),window.addEventListener("scroll",r,{passive:!0}),u.push(()=>{m.disconnect(),window.removeEventListener("scroll",r),p()})}if((l==null?void 0:l.tabLoss)!==!1){let i=!1,d=n!=null?n:Date.now(),a=()=>{if(i||document.visibilityState!=="hidden")return;let p=Date.now()-d;p<15e3&&(i=!0,e("tab_loss",{timeOnPage:p}))};document.addEventListener("visibilitychange",a),u.push(()=>document.removeEventListener("visibilitychange",a))}return()=>{for(let i of u)i()}}function Gn(){var e;return typeof process=="undefined"||((e=process.env)==null?void 0:e.NODE_ENV)!=="production"}var Pt="https://api.sentient-ui.com/v1/events",G=new Map,Lt=null;function Un(e,t){let n=G.get(e);n&&n.upgrade&&(n.reinit=t)}function Fn(e){return"value"in e||"currency"in e||"externalId"in e||"metadata"in e||"weight"in e||"stepIndex"in e}var $n=3;function Ve(){return Ie()}function Ue(){var e;if(typeof window!="undefined")return((e=window.location)==null?void 0:e.pathname)||void 0}function Wn(){let e=new WeakMap,t=new Map,n=!1,l=(a,p,s)=>{let r=a.get(p);return s===null?r?!0:(a.set(p,new Set),!1):r?r.has(s)?!0:(r.add(s),!1):(a.set(p,new Set([s])),!1)},u=typeof window!="undefined"&&"event"in window,i=()=>{if(!u)return;let a=window.event;return typeof Event=="function"&&a instanceof Event?a:void 0},d=()=>{if(u){Promise.resolve().then(()=>{n=!1,t.clear()});return}let a=!1,p=()=>{a||(a=!0,n=!1,t.clear())};if(setTimeout(p,0),typeof MessageChannel=="function"){let s=new MessageChannel;s.port1.onmessage=()=>{s.port1.close(),s.port2.close(),p()},s.port2.postMessage(0)}};return{firedBefore(a,p){let s=i();if(s){let o=e.get(s);return o||(o=new Map,e.set(s,o)),l(o,a,p)}let r=l(t,a,p);return!r&&!n&&(n=!0,d()),r}}}var Dt=new Set;function jn(e,t,n){let l=typeof window=="undefined"?null:window.history;if(!l)return()=>{};let u=!1,i,d=()=>{if(u)return;let s=Ue();!s||s===i||(i=s,e.track({projectId:t,componentId:"__page__",eventType:"pageview",payload:{}}),n(`${t}:${s}`))},a=[];for(let s of["pushState","replaceState"]){let r=l[s],o=function(...m){let x=r.apply(this,m);return d(),x};l[s]=o,a.push([s,r,o])}window.addEventListener("popstate",d);let p=Ue();return p&&Dt.has(`${t}:${p}`)?i=p:d(),()=>{if(!u){u=!0,window.removeEventListener("popstate",d);for(let[s,r,o]of a)l[s]===o&&(l[s]=r)}}}var we={track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},getAssignment:()=>null,assign:()=>Promise.resolve(null),decide:()=>Promise.resolve(null),getSlotResult:()=>null,getSlotConfig:()=>null,getSitePalette:()=>null,reportSlots:()=>{},getPersona:()=>null,fetchWeights:()=>Promise.resolve([]),getGraph:()=>({pageNodes:[],capturedAt:0}),dispose:()=>{},destroy:()=>{}};function zn(){try{return Le(window.location.search)}catch(e){return{utmParams:{},clickIds:{}}}}function Mt(e){return e.replace(/\/events\/?$/,"")}function qe(){return typeof navigator!="undefined"&&navigator.globalPrivacyControl===!0?!0:[typeof navigator!="undefined"?navigator.doNotTrack:void 0,typeof window!="undefined"?window.doNotTrack:void 0,typeof navigator!="undefined"?navigator.msDoNotTrack:void 0].some(t=>t==="1"||t==="yes")}function Hn(e){var p;if(typeof window=="undefined")return;let t=e!=null?e:Lt;if(!t){console.warn("[sentient] grantConsent() called before init()");return}let n=G.get(t);if(!n){console.warn("[sentient] grantConsent() called before init()");return}let{config:l,upgrade:u,reinit:i}=n;if(!u){n.upgradeBlockedReason&&console.warn(n.upgradeBlockedReason);return}if(l.respectDoNotTrack!==!1&&qe())return;let d=(i!=null?i:Nt)(oe(b({},l),{consent:!0}));u(d);let a=(p=G.get(t))==null?void 0:p.dispose;G.set(t,{config:oe(b({},l),{consent:!0}),upgrade:null,dispose:a})}function Qn(e){var s;let t=e.preConsentBehavior==="statistical_winner",n=Mt((s=e.ingestUrl)!=null?s:Pt),l={"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`},u=new Map,i=new Map,d={track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},getAssignment:()=>null,fetchWeights:()=>Promise.resolve([]),assign(r,o,m){if(!t)return Promise.resolve(null);let x=u.get(r);return x?Promise.resolve(x):Ye(i,r,async()=>{try{let E=new URLSearchParams({componentId:r});for(let U of o!=null?o:[])E.append("variantIds[]",U);let P=await fetch(`${n}/winner?${E.toString()}`,{headers:l});if(!P.ok)return o!=null&&o[0]?{variantId:o[0],assignmentTtlMs:0}:null;let C={variantId:(await P.json()).variantId,assignmentTtlMs:0};return u.set(r,C),C}catch(E){return o!=null&&o[0]?{variantId:o[0],assignmentTtlMs:0}:null}})},decide:()=>Promise.resolve(null),getSlotResult:()=>null,getSlotConfig:()=>null,getSitePalette:()=>null,reportSlots:()=>{},getPersona:()=>null,getGraph:()=>({pageNodes:[],capturedAt:0}),dispose:()=>{},destroy:()=>{}},a={track:r=>d.track(r),goal:((r,o,m,x)=>d.goal(r,o,m,x)),componentGoal:(r,o,m)=>d.componentGoal(r,o,m),identify:r=>d.identify(r),getAssignment:(r,o)=>d.getAssignment(r,o),assign:(r,o,m,x)=>d.assign(r,o,m,x),decide:r=>d.decide(r),getSlotResult:r=>d.getSlotResult(r),getSlotConfig:r=>d.getSlotConfig(r),getSitePalette:()=>d.getSitePalette(),reportSlots:(r,o)=>d.reportSlots(r,o),getPersona:()=>d.getPersona(),fetchWeights:()=>d.fetchWeights(),getGraph:()=>d.getGraph(),dispose:()=>d.dispose(),destroy:()=>d.destroy()};function p(r){d=r}return{proxy:a,setInner:p}}function Ye(e,t,n){let l=e.get(t);if(l)return l;let u=(async()=>{try{return await n()}finally{e.delete(t)}})();return e.set(t,u),u}function Nt(e){var Ze,et,tt,nt,rt,ot,st,it,at,lt;if(typeof window=="undefined")return we;Lt=e.apiKey||"local";let t=G.get(e.apiKey||"local");if(t!=null&&t.dispose)try{t.dispose()}catch(c){}let n=e.respectDoNotTrack!==!1&&qe(),l=e.consent===!1||n,u=typeof e.apiKey=="string"&&e.apiKey.startsWith("pk_");if(e.localMode===!0||!u&&e.localMode!==!1)return G.set(e.apiKey||"local",{config:e,upgrade:null,upgradeBlockedReason:"[sentient] grantConsent(): this client is keyless/local \u2014 there is no hosted client to upgrade to. Configure a pk_ API key to enable tracking."}),l?we:_t(e);if(l){if(!e.apiKey||!e.apiKey.startsWith("pk_"))return e.preConsentBehavior==="statistical_winner"&&console.warn("[sentient] init() called with an invalid apiKey \u2014 expected a pk_ public key. SDK disabled."),G.set(e.apiKey||"local",{config:e,upgrade:null,upgradeBlockedReason:"[sentient] grantConsent(): the client was initialized with an invalid apiKey (expected a pk_ public key) \u2014 consent cannot enable tracking."}),we;let{proxy:c,setInner:g}=Qn(e);return G.set(e.apiKey,{config:e,upgrade:n?null:g}),c}if(!e.apiKey||!e.apiKey.startsWith("pk_"))return console.warn("[sentient] init() called with an invalid apiKey \u2014 expected a pk_ public key. SDK disabled."),we;if(e.ingestUrl==="")return console.warn("[sentient] init() called with an empty ingestUrl. SDK disabled."),we;let i=(Ze=e.ingestUrl)!=null?Ze:Pt,d=Date.now(),a=Re({ssrSessionId:e.ssrSessionId,apiKey:e.apiKey}),p=xt(void 0,e.apiKey),s=ht({ingestUrl:i,apiKey:e.apiKey}),r=Mt(i),o={"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`},m=new Set,x=vt({url:`${r}/goals`,apiKey:e.apiKey,headers:o,onDrop:(c,g)=>{if(!e.debug){if(m.has(g))return;m.add(g)}console.warn(`[sentient] goal dropped (HTTP ${g}) \u2014 this will not be retried. `+(g===400?"The session was not found: call init() and let the session upsert complete before firing goals.":g===401||g===403?"Check the API key and that this origin is on the project allowlist.":"See the response status for the cause."),c)}}),E=he((et=navigator.userAgent)!=null?et:""),P=window.location.origin,L=ve((tt=document.referrer)!=null?tt:"",P),C=(nt=e.sessionSegment)!=null?nt:`${E}:${L}`,U=new Map,$=new Map,A=new Map,O=new Map,R=null,f=null,T=new Set,W=new Set,j=new Map,Q=null,Z=/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,127}$/,ue=new Set,S=c=>{for(let g of c)A.has(g.id)||A.set(g.id,ae(g))};if(e.initialSlots)for(let[c,g]of Object.entries(e.initialSlots))A.set(c,g);if(e.initialSlotConfig)for(let[c,g]of Object.entries(e.initialSlotConfig))O.set(c,g);e.initialPalette&&(R=e.initialPalette);let v=le(e.apiKey);if(v){for(let[c,g]of Object.entries(v.slots))A.has(c)||A.set(c,g);for(let[c,g]of Object.entries((rt=v.slotConfig)!=null?rt:{}))O.has(c)||O.set(c,g);!R&&v.palette&&(R=v.palette)}let J={low:.15,medium:.5,high:.85};if(e.initialPersona)f=b({},e.initialPersona);else{let c=document.documentElement.dataset;c.sentientPersona?f={persona:c.sentientPersona,confidence:(st=J[(ot=c.sentientConfidence)!=null?ot:"low"])!=null?st:.15}:v&&(f={persona:v.persona,confidence:(it=J[v.band])!=null?it:.15})}if(e.initialAssignments)for(let[c,g]of Object.entries(e.initialAssignments))p.set(c,C,{variantId:g,assignedAt:Date.now(),segment:C,confidence:1});let N=Promise.resolve(),z=a.getSessionId();if(z){let c=xe((at=document.referrer)!=null?at:""),{utmParams:g,clickIds:y}=zn(),k=b(b(b(b({sessionId:z,deviceClass:E,trafficSource:L,referrerDomain:c,utmParams:g,clickIds:y,timeOfDay:ke(new Date),dayOfWeek:["sun","mon","tue","wed","thu","fri","sat"][new Date().getDay()],ephemeral:a.isEphemeral(),automation:typeof navigator!="undefined"&&navigator.webdriver===!0||Se((lt=navigator.userAgent)!=null?lt:"")},e.userId?{userId:e.userId}:{}),e.persona?{persona:e.persona}:{}),e.country?{country:e.country}:{}),e.sdk?{sdk:e.sdk.name,sdkVersion:e.sdk.version}:{}),_=async()=>{for(let h=0;;h++){try{let I=await fetch(`${r}/sessions`,{method:"POST",keepalive:!0,body:JSON.stringify(k),headers:o});if(I.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");return}if(I.ok||se(I)==="dropped")return}catch(I){}if(h>=$n){console.warn("[SentientUI] Could not register the session after retries. Conversions in this visit may not be recorded.");return}await new Promise(I=>setTimeout(I,Y(h+1)))}};try{N=_()}catch(h){}}e.debug&&(console.log("[sentient] initialized",{context:e.context}),window.__sentient={client:null,queue:s});let Ee=Wn(),K=null,ee=!1,F={goal(c,g={},y=1,k=0){var pe,ge,re,w,V,Ce,B;let _=a.getSessionId();if(!_)return;let h=Fn(g)?g:{metadata:g},I=[c,(pe=h.externalId)!=null?pe:"",(ge=h.stepIndex)!=null?ge:k,(re=h.weight)!=null?re:y].join("\0"),D=h.value!==void 0?`${h.value}\0${(w=h.currency)!=null?w:""}`:null;if(Ee.firedBefore(I,D)){e.debug&&console.log(`[sentient] goal("${c}") already recorded for this action \u2014 not sent twice`);return}let M=Ve(),X={sessionId:_,name:c,metadata:(V=h.metadata)!=null?V:{},weight:(Ce=h.weight)!=null?Ce:y,stepIndex:(B=h.stepIndex)!=null?B:k,goalId:M,value:h.value,currency:h.currency,externalId:h.externalId};e.debug&&console.log("[sentient] goal",X);let te={id:M,body:JSON.stringify(X)};N.then(()=>x.send(te))},componentGoal(c,g,y){var M,X,te;let k=a.getSessionId();if(!k)return;let _=p.get(c,C),h=_?null:(M=A.get(c))!=null?M:null;if(!_&&h===null){e.debug&&console.warn(`[sentient] componentGoal("${c}"): no assignment or slot decision yet \u2014 render its <Adaptive>/adaptive hook or call assign()/decide() before recording a goal.`);return}let I=_?_.variantId:De(h),D={id:Ve(),sessionId:k,projectId:e.apiKey,componentId:c,variantId:I,eventType:"goal_achieved",goalType:g,payload:b({reward:(X=y==null?void 0:y.reward)!=null?X:1,goalValue:y==null?void 0:y.value,currency:y==null?void 0:y.currency},(te=y==null?void 0:y.metadata)!=null?te:{}),timestamp:Date.now(),timeInSession:Date.now()-d,path:Ue()};e.debug&&console.log("[sentient] componentGoal",D),N.then(()=>s.push(D))},identify(c){let g=a.getSessionId();g&&N.then(()=>{fetch(`${r}/sessions`,{method:"POST",keepalive:!0,body:JSON.stringify({sessionId:g,userId:c,ephemeral:a.isEphemeral()}),headers:o}).catch(()=>{})})},track(c){let g=a.getSessionId();if(!g)return;let y=oe(b({path:Ue()},c),{id:Ve(),sessionId:g,timestamp:Date.now(),timeInSession:Date.now()-d});e.debug&&console.log("[sentient] track",y),N.then(()=>s.push(y))},getAssignment(c,g){return p.get(c,g)},async assign(c,g,y,k){let _=a.getSessionId();if(!_)return null;let h=p.get(c,C);if(h&&(g!=null&&g.length||h.content!==void 0)){let I=h.ttlMs&&h.ttlMs>0?Math.max(0,h.assignedAt+h.ttlMs-Date.now()):0;return{variantId:h.variantId,assignmentTtlMs:I,content:h.content}}return Ye(U,c,async()=>{await N;try{let I={sessionId:_,componentId:c,variantIds:g};k!==void 0?I.agentDataByVariant=k:y!==void 0&&(I.agentData=y);let D=await fetch(`${r}/assign`,{method:"POST",body:JSON.stringify(I),headers:o});if(!D.ok)return null;let M=await D.json();return p.set(c,C,b({variantId:M.variantId,assignedAt:Date.now(),segment:C,confidence:1,content:M.content},M.assignmentTtlMs&&M.assignmentTtlMs>0?{ttlMs:M.assignmentTtlMs}:{})),M}catch(I){return null}})},async decide(c){var h,I;let g=a.getSessionId();if(!g)return null;let y=(h=c.slots)!=null?h:[],k={sessionId:g};c.sections&&c.sections.length>0&&(k.sections=c.sections.map(D=>({id:D}))),k.components=(I=c.components)!=null?I:[],y.length>0&&(k.slots=y.map(be)),c.slotsFrom==="registry"&&(k.slotsFrom="registry"),c.v&&(k.v=c.v),typeof c.pp=="number"&&(k.pp=c.pp),e.persona&&(k.persona=e.persona);let _=JSON.stringify(k);return Ye($,_,async()=>{var D,M,X,te,pe,ge;await N;try{let re=await fetch(`${r}/decide`,{method:"POST",body:_,headers:o});if(!re.ok)return S(y),null;let w=await re.json(),V={};for(let B of y){let H=(D=w.slots)==null?void 0:D[B.id];if(H!==void 0){V[B.id]=H,A.set(B.id,H);continue}let ct=A.get(B.id);if(ct!==void 0)V[B.id]=ct;else{let dt=ae(B);V[B.id]=dt,A.set(B.id,dt)}}if(w.slots)for(let[B,H]of Object.entries(w.slots))B in V||(V[B]=H,A.set(B,H));let Ce=f!=null&&f.persona!=="unknown";w.persona&&!(w.persona==="unknown"&&Ce)?f={persona:w.persona,confidence:(M=w.confidence)!=null?M:0}:f||(f={persona:"unknown",confidence:0});for(let[B,H]of Object.entries((X=w.assignments)!=null?X:{}))p.set(B,C,{variantId:H,assignedAt:Date.now(),segment:C,confidence:1});if(w.slotConfig)for(let[B,H]of Object.entries(w.slotConfig))O.set(B,H);return w.palette&&(R=w.palette),ce(e.apiKey,b(b({v:1,persona:f.persona,band:(0,Xe.confidenceBand)(f.confidence),slots:Object.fromEntries(A),layoutOrder:(te=w.layoutOrder)!=null?te:null,savedAt:Date.now()},O.size>0?{slotConfig:Object.fromEntries(O)}:{}),R?{palette:R}:{})),b(b(b(b({layoutOrder:(pe=w.layoutOrder)!=null?pe:null,assignments:(ge=w.assignments)!=null?ge:{},slots:V,persona:f.persona,confidence:f.confidence},w.slotConfig?{slotConfig:w.slotConfig}:{}),w.goals?{goals:w.goals}:{}),w.sectionMap?{sectionMap:w.sectionMap}:{}),w.palette?{palette:w.palette}:{})}catch(re){return S(y),null}})},getSlotResult(c){var g;return(g=A.get(c))!=null?g:null},getSlotConfig(c){var g;return(g=O.get(c))!=null?g:null},reportSlots(c,g){for(let y of c)if(!(typeof y!="string"||y.length===0)){if(!Z.test(y)){Gn()&&!ue.has(y)&&(ue.add(y),console.warn(`[sentient] reportSlots: slot id ${JSON.stringify(y)} will not register \u2014 ids must start with a letter or digit and contain only letters, digits, '_' or '-' (max 128 chars): /^[a-zA-Z0-9][a-zA-Z0-9_-]{0,127}$/.`));continue}if(!T.has(y)){T.add(y),W.add(y);let k=g==null?void 0:g[y];if(typeof k=="string"){let _=k.replace(/\s+/g," ").trim().slice(0,400);_!==""&&j.set(y,_)}}}W.size===0||Q!=null||(Q=setTimeout(()=>{Q=null;let y=[...W];W.clear();for(let k=0;k<y.length;k+=20){let _=y.slice(k,k+20),h={};for(let I of _){let D=j.get(I);D!==void 0&&(h[I]=D,j.delete(I))}fetch(`${r}/slots/observed`,{method:"POST",headers:o,body:JSON.stringify(b({slotIds:_},Object.keys(h).length>0?{baselineTexts:h}:{}))}).catch(()=>{})}},1e3))},getSitePalette(){return R},getPersona(){return f?{persona:f.persona,confidence:f.confidence,band:(0,Xe.confidenceBand)(f.confidence)}:null},async fetchWeights(){var c;try{let g=await fetch(`${r}/weights`,{headers:o});return g.ok?(c=(await g.json()).components)!=null?c:[]:[]}catch(g){return[]}},getGraph(){return{pageNodes:[],capturedAt:0}},dispose(){var c;K==null||K(),ee=!0,s.destroy(),x.destroy(),((c=G.get(e.apiKey))==null?void 0:c.dispose)===F.dispose&&G.delete(e.apiKey),e.debug&&console.log("[sentient] disposed")},destroy(){var c;K==null||K(),ee=!0,s.destroy(),x.destroy(),a.destroy(),p.clear(),((c=G.get(e.apiKey))==null?void 0:c.dispose)===F.dispose&&G.delete(e.apiKey);try{localStorage.removeItem(ne+e.apiKey),localStorage.removeItem(We(e.apiKey)),localStorage.removeItem(je(e.apiKey))}catch(g){}e.debug&&console.log("[sentient] destroyed")}};if(G.set(e.apiKey,{config:e,upgrade:null,dispose:F.dispose}),K=jn(F,e.apiKey,c=>{N.then(()=>{ee||Dt.add(c)})}),e.debug){let c=window;c.__sentient&&(c.__sentient.client=F)}return F}0&&(module.exports={AGENT_INTENTS,BLOCK_ALIGNS,BLOCK_EMPHASES,BLOCK_FITS,BLOCK_GAPS,BLOCK_GRID_COLUMNS,BLOCK_HEADING_LEVELS,BLOCK_JUSTIFIES,BLOCK_MAX_WIDTHS,BLOCK_PADS,BLOCK_RATIOS,BLOCK_SIZES,BLOCK_SURFACES,BLOCK_TEXT_ALIGNS,BLOCK_TONES,BLOCK_WEIGHTS,CLICK_ID_KEYS,FORM_FIELD_KINDS,FORM_INPUT_TYPES,LEGACY_SESSION_COOKIE_NAME,LOCAL_MODE_BANNER,MAX_BLOCK_ARMS,MAX_BLOCK_CHILDREN,MAX_BLOCK_DEPTH,MAX_BLOCK_NODES,MAX_BLOCK_TEXT_LEN,MAX_FORM_FIELDS,MAX_FORM_SELECT_OPTIONS,PROD_KEYLESS_ERROR,REVEAL_MS,SNAPSHOT_STORAGE_KEY_PREFIX,_registerConsentUpgradeInit,agentIntent,agentUaList,armOfResult,attachMicroSignalDetectors,baselineResultFor,baselineSlots,classifiedAgents,containsFormBlock,deriveSessionSegment,detectDeviceClass,detectTimeOfDay,detectTrafficSource,extractTrackedParams,grantConsent,init,isDoNotTrackEnabled,matchedAgentToken,readSnapshot,referrerDomainFromReferer,renderPrePaintScript,resetRevealStyles,reveal,sessionCookieName,toWireSlot,uaTokenMatch,writeSnapshot});
|
|
1
|
+
"use strict";var tn=Object.create;var we=Object.defineProperty,nn=Object.defineProperties,on=Object.getOwnPropertyDescriptor,rn=Object.getOwnPropertyDescriptors,sn=Object.getOwnPropertyNames,It=Object.getOwnPropertySymbols,an=Object.getPrototypeOf,Ct=Object.prototype.hasOwnProperty,ln=Object.prototype.propertyIsEnumerable;var _t=(e,t,n)=>t in e?we(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,O=(e,t)=>{for(var n in t||(t={}))Ct.call(t,n)&&_t(e,n,t[n]);if(It)for(var n of It(t))ln.call(t,n)&&_t(e,n,t[n]);return e},de=(e,t)=>nn(e,rn(t));var cn=(e,t)=>{for(var n in t)we(e,n,{get:t[n],enumerable:!0})},Rt=(e,t,n,u)=>{if(t&&typeof t=="object"||typeof t=="function")for(let g of sn(t))!Ct.call(e,g)&&g!==n&&we(e,g,{get:()=>t[g],enumerable:!(u=on(t,g))||u.enumerable});return e};var dn=(e,t,n)=>(n=e!=null?tn(an(e)):{},Rt(t||!e||!e.__esModule?we(n,"default",{value:e,enumerable:!0}):n,e)),un=e=>Rt(we({},"__esModule",{value:!0}),e);var po={};cn(po,{AGENT_INTENTS:()=>Ke,BLOCK_ALIGNS:()=>Pn,BLOCK_EMPHASES:()=>Nn,BLOCK_FITS:()=>Un,BLOCK_GAPS:()=>On,BLOCK_GRID_COLUMNS:()=>Fn,BLOCK_HEADING_LEVELS:()=>$n,BLOCK_JUSTIFIES:()=>Dn,BLOCK_MAX_WIDTHS:()=>zn,BLOCK_PADS:()=>jn,BLOCK_RATIOS:()=>Gn,BLOCK_SIZES:()=>Bn,BLOCK_SURFACES:()=>Wn,BLOCK_TEXT_ALIGNS:()=>Kn,BLOCK_TONES:()=>Mn,BLOCK_WEIGHTS:()=>Ln,CLICK_ID_KEYS:()=>Ze,FORM_FIELD_KINDS:()=>Hn,FORM_INPUT_TYPES:()=>Qn,LEGACY_SESSION_COOKIE_NAME:()=>Je,LOCAL_MODE_BANNER:()=>et,MAX_BLOCK_ARMS:()=>Zn,MAX_BLOCK_CHILDREN:()=>Yn,MAX_BLOCK_DEPTH:()=>qn,MAX_BLOCK_NODES:()=>Xn,MAX_BLOCK_TEXT_LEN:()=>eo,MAX_FORM_FIELDS:()=>Jn,MAX_FORM_SELECT_OPTIONS:()=>Vn,PAGE_SCOPE_RE:()=>nt,PROD_KEYLESS_ERROR:()=>We,REVEAL_MS:()=>jt,SNAPSHOT_STORAGE_KEY_PREFIX:()=>le,_registerConsentUpgradeInit:()=>oo,agentIntent:()=>Lt,agentUaList:()=>ke,armOfResult:()=>Ue,attachMicroSignalDetectors:()=>Qt,baselineResultFor:()=>ge,baselineSlots:()=>Kt,classifiedAgents:()=>Mt,containsFormBlock:()=>Wt,deriveSessionSegment:()=>Nt,detectDeviceClass:()=>Ie,detectTimeOfDay:()=>Re,detectTrafficSource:()=>_e,extractTrackedParams:()=>Ge,grantConsent:()=>co,init:()=>Yt,isDoNotTrackEnabled:()=>at,matchedAgentToken:()=>Ye,pageScopeMatches:()=>$t,readSnapshot:()=>fe,referrerDomainFromReferer:()=>Ce,renderPrePaintScript:()=>Gt,resetRevealStyles:()=>zt,reveal:()=>Ht,sessionCookieName:()=>Pe,toWireSlot:()=>Ae,uaTokenMatch:()=>Ee,writeSnapshot:()=>me});module.exports=un(po);function Oe(){try{if(typeof crypto!="undefined"&&typeof crypto.randomUUID=="function")return crypto.randomUUID()}catch(e){}try{if(typeof crypto!="undefined"&&typeof crypto.getRandomValues=="function"){let e=new Uint8Array(16);crypto.getRandomValues(e),e[6]=e[6]&15|64,e[8]=e[8]&63|128;let t="";for(let n=0;n<16;n++)t+=e[n].toString(16).padStart(2,"0"),(n===3||n===5||n===7||n===9)&&(t+="-");return t}}catch(e){}return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})}function be(e){return e?`_${e.slice(0,12)}`:""}var Je="_snt_uid";function Pe(e){return`${Je}${be(e)}`}var pn="_snt_uid",gn=365,De="_snt_uid";function fn(){return Oe()}function At(e){try{let t=document.cookie.match(new RegExp(`(?:^|; )${e}=([^;]*)`));return t?decodeURIComponent(t[1]):null}catch(t){return null}}function mn(e,t,n){try{document.cookie=`${e}=${encodeURIComponent(t)}; max-age=${n}; SameSite=strict; path=/`}catch(u){}}function Ve(e){try{return localStorage.getItem(e)}catch(t){return null}}function Tt(e,t){try{return localStorage.setItem(e,t),!0}catch(n){return!1}}function Ot(e){try{return sessionStorage.getItem(e)}catch(t){return null}}function yn(e,t){try{return sessionStorage.setItem(e,t),!0}catch(n){return!1}}function Sn(e){try{sessionStorage.removeItem(e)}catch(t){}}function hn(e){try{return document.cookie=`${e}_probe=1; max-age=1; SameSite=strict; path=/`,document.cookie.indexOf(`${e}_probe=1`)!==-1}catch(t){return!1}}function vn(e){try{localStorage.removeItem(e)}catch(t){}}function xn(e){try{document.cookie=`${e}=; max-age=0; SameSite=strict; path=/`}catch(t){}}var wn={getSessionId:()=>null,isEphemeral:()=>!1,destroy:()=>{}};function Be(e){var p,y,k,b,N,G,P;if(typeof window=="undefined")return wn;let t=be(e==null?void 0:e.apiKey),n=(p=e==null?void 0:e.cookieName)!=null?p:Pe(e==null?void 0:e.apiKey),u=`${De}${t}`,g=`${De}_tomb${t}`,i=((y=e==null?void 0:e.cookieTTLDays)!=null?y:gn)*24*60*60,c=L=>L&&L.length>0?L:null,f=()=>{var L,D;return t&&!(e!=null&&e.cookieName)&&Ve(g)===null?(D=(L=c(At(pn)))!=null?L:c(Ve(De)))!=null?D:c(Ot(De)):null},s=(P=(G=(N=(b=(k=c(At(n)))!=null?k:c(Ve(u)))!=null?b:c(Ot(u)))!=null?N:f())!=null?G:c(e==null?void 0:e.ssrSessionId))!=null?P:fn();mn(n,s,i);let r=Tt(u,s),a=hn(n),w=r?!1:yn(u,s),A=!r&&!a&&!w;return{getSessionId:()=>s,isEphemeral:()=>A,destroy:()=>{s=null,xn(n),vn(u),Sn(u),t&&!(e!=null&&e.cookieName)&&Tt(g,"1")}}}function Y(e){return Math.min(6e4,1e3*2**Math.min(e,6))}function ue(e){if(e.ok===!0)return"delivered";let{status:t}=e;return typeof t!="number"?"retry":t>=200&&t<300?"delivered":t>=400&&t<500&&t!==429?"dropped":"retry"}function Le(e,t){try{let n=localStorage.getItem(e);if(!n)return[];let u=JSON.parse(n);return Array.isArray(u)?(localStorage.removeItem(e),u.slice(-t)):[]}catch(n){return[]}}function oe(e,t,n){try{let u=(()=>{try{let l=localStorage.getItem(n);if(!l)return[];let i=JSON.parse(l);return Array.isArray(i)?i:[]}catch(l){return[]}})(),g=new Map;for(let l of u)g.set(l.id,l);for(let l of e)g.set(l.id,l);localStorage.setItem(n,JSON.stringify([...g.values()].slice(-t)))}catch(u){}}function Me(e,t){try{let n=localStorage.getItem(t);if(!n)return;let u=JSON.parse(n);if(!Array.isArray(u))return;let g=new Set(e),l=u.filter(i=>!g.has(i.id));if(l.length===u.length)return;l.length===0?localStorage.removeItem(t):localStorage.setItem(t,JSON.stringify(l))}catch(n){}}var bn=500,kn=56*1024;function Xe(e){return`_snt_retry_${e.slice(0,12)}`}var En={push:()=>{},flush:()=>{},destroy:()=>{}};function Pt(e){var V,X,Se;if(typeof window=="undefined")return En;let t=(V=e.flushIntervalMs)!=null?V:5e3,n=(X=e.maxBatchSize)!=null?X:20,u=(Se=e.maxRetrySize)!=null?Se:100,g=e.ingestUrl,l=e.apiKey,i=Xe(l),c=[],f=new Set,s=[],r=v=>{for(let R of v)a.delete(R),!f.has(R)&&(f.add(R),s.push(R));for(;s.length>bn;){let R=s.shift();R&&f.delete(R)}Me(v,i)},a=new Set,w=()=>{for(;c.length>u;){let v=c.shift();v&&a.delete(v.id)}},A=v=>{f.has(v.id)||a.has(v.id)||(a.add(v.id),c.push(v),w())},p=v=>{for(let R of v)f.has(R.id)||(a.add(R.id),c.push(R));w()},y=Le(i,u);for(let v of y)A(v);let k=0,b=0,N=(v,R=!0)=>{if(v.length===0)return;let j=JSON.stringify(v),Q=v.map(H=>H.id),z;try{z=fetch(g,{method:"POST",keepalive:!0,body:j,headers:{"Content-Type":"application/json",Authorization:`Bearer ${l}`}})}catch(H){oe(v,u,i),p(v),b++,k=Date.now()+Y(b);return}let re=H=>{if(ue(H)!=="retry"){if(!H.ok&&R){let se=v.filter(ie=>ie.eventType!=="pageview");if(se.length>0&&se.length<v.length){r(v.filter(ie=>ie.eventType==="pageview").map(ie=>ie.id)),N(se,!1);return}}r(Q),b=0,k=0;return}oe(v,u,i),p(v),b++,k=Date.now()+Y(b)};z instanceof Promise?z.then(re).catch(()=>{oe(v,u,i),p(v),b++,k=Date.now()+Y(b)}):re(z)},G=typeof TextEncoder!="undefined"?new TextEncoder:null,P=v=>G?G.encode(v).length:v.length,L=v=>{let R=[],j=2;for(let Q of v){let z=P(JSON.stringify(Q))+1;if(R.length>0&&j+z>kn||R.length>=n)break;R.push(Q),j+=z}return R},D=()=>{try{if(Date.now()<k)return;for(;c.length>0&&!(Date.now()<k);){let v=c.filter(j=>!f.has(j.id));if(c.length=0,v.length===0)break;let R=L(v);if(R.length===0)break;R.length<v.length&&c.push(...v.slice(R.length)),N(R)}}catch(v){}},h=!0,I=null;I=setInterval(()=>{h&&D()},t);let Z=()=>{document.visibilityState==="hidden"&&D()},W=()=>{D()};return document.addEventListener("visibilitychange",Z),window.addEventListener("pagehide",W),{push(v){A(v),c.length>=n&&D()},flush:D,destroy(){h=!1,I!==null&&(clearInterval(I),I=null),document.removeEventListener("visibilitychange",Z),window.removeEventListener("pagehide",W),D()}}}var In=200;function qe(e){return`_snt_goal_retry_${e.slice(0,12)}`}var _n={send:()=>{},flush:()=>{},destroy:()=>{}};function Dt(e){var P,L,D;if(typeof window=="undefined")return _n;let t=(P=e.flushIntervalMs)!=null?P:5e3,n=(L=e.maxRetrySize)!=null?L:100,u=(D=e.maxPerFlush)!=null?D:5,g=qe(e.apiKey),l=[],i=new Set,c=new Set,f=[],s=0,r=0,a=!1,w=h=>{for(i.delete(h.id),c.has(h.id)||(c.add(h.id),f.push(h.id));f.length>In;){let I=f.shift();I&&c.delete(I)}Me([h.id],g)},A=h=>{oe([h],n,g),!c.has(h.id)&&!i.has(h.id)&&(i.add(h.id),l.push(h)),Date.now()>=s&&(r++,s=Date.now()+Y(r))},p=h=>{let I;try{I=fetch(e.url,{method:"POST",keepalive:!0,body:h.body,headers:e.headers})}catch(W){A(h);return}let Z=W=>{var X;let V=ue(W);if(V==="retry"){A(h);return}V==="dropped"&&((X=e.onDrop)==null||X.call(e,h,W.status)),w(h),r=0,s=0};I instanceof Promise?I.then(Z).catch(()=>A(h)):Z(I)},y=()=>{try{if(a||Date.now()<s)return;let h=0;for(;l.length>0&&h<u&&!(Date.now()<s);){let I=l.shift();i.delete(I.id),!c.has(I.id)&&(h++,p(I))}}catch(h){}},k=Le(g,n);for(let h of k)i.has(h.id)||(i.add(h.id),l.push(h));k.length>0&&oe(k,n,g);let b=setInterval(y,t),N=()=>{document.visibilityState==="hidden"&&y()},G=()=>y();return document.addEventListener("visibilitychange",N),window.addEventListener("pagehide",G),{send(h){if(!a&&!(c.has(h.id)||i.has(h.id))){if(Date.now()<s){oe([h],n,g),i.add(h.id),l.push(h);return}p(h)}},flush:y,destroy(){clearInterval(b),document.removeEventListener("visibilitychange",N),window.removeEventListener("pagehide",G),y(),a=!0}}}var Cn=1800*1e3;function Ne(e,t){return`${encodeURIComponent(e)}:${encodeURIComponent(t)}`}function Bt(e=Cn,t){let n=new Map,u=`_snt_asgn${be(t)}_`,g=(s,r)=>`${u}${encodeURIComponent(s)}:${encodeURIComponent(r)}`,l=s=>{let r=s.slice(u.length),a=r.indexOf(":");if(a<0)return null;try{return{componentId:decodeURIComponent(r.slice(0,a)),segment:decodeURIComponent(r.slice(a+1))}}catch(w){return null}},i=()=>{try{let s=[];for(let r=0;r<localStorage.length;r++){let a=localStorage.key(r);a!=null&&a.startsWith(u)&&s.push(a)}return s}catch(s){return[]}},c=s=>s.assignedAt+(s.ttlMs&&s.ttlMs>0?s.ttlMs:e)<Date.now();return typeof window!="undefined"&&(()=>{for(let s of i())try{let r=localStorage.getItem(s);if(!r)continue;let a=JSON.parse(r);if(c(a)){localStorage.removeItem(s);continue}let w=l(s);if(!w)continue;n.set(Ne(w.componentId,w.segment),a)}catch(r){}})(),{get(s,r){let a=n.get(Ne(s,r));return a?c(a)?(n.delete(Ne(s,r)),null):a:null},set(s,r,a){let w=Ne(s,r);n.set(w,a);try{localStorage.setItem(g(s,r),JSON.stringify(a))}catch(A){}},clear(){n.clear();for(let s of i())try{localStorage.removeItem(s)}catch(r){}}}}var ke=["GPTBot","ChatGPT-User","OAI-SearchBot","ClaudeBot","Claude-User","Claude-SearchBot","PerplexityBot","Perplexity-User","Google-Extended","Applebot-Extended","Meta-ExternalAgent","Bytespider","CCBot","Amazonbot","cohere-ai","Diffbot"];function Ee(e){return Ye(e)!==null}function Ye(e){var n;if(!e)return null;let t=e.toLowerCase();return(n=ke.find(u=>t.includes(u.toLowerCase())))!=null?n:null}var Ke={GPTBot:"training","ChatGPT-User":"user","OAI-SearchBot":"search",ClaudeBot:"training","Claude-User":"user","Claude-SearchBot":"search",PerplexityBot:"search","Perplexity-User":"user","Google-Extended":"training","Applebot-Extended":"training","Meta-ExternalAgent":"training",Bytespider:"training",CCBot:"training",Amazonbot:"other","cohere-ai":"training",Diffbot:"other"};function Lt(e){if(!e)return"other";let t=ke.find(n=>n.toLowerCase()===e.toLowerCase());return t&&Ke[t]||"other"}function Mt(){var t;let e={user:[],search:[],training:[],other:[]};for(let n of ke)e[(t=Ke[n])!=null?t:"other"].push(n);return e}function Ie(e){let t=e.toLowerCase();return/ipad|tablet|playbook|kindle|silk/.test(t)?"tablet":/mobi|iphone|ipod|android.*mobile|phone/.test(t)?"mobile":"desktop"}function _e(e,t){if(!e)return"direct";try{let n=new URL(e);if(t)try{if(new URL(t).host===n.host)return"direct"}catch(g){}let u=n.hostname.toLowerCase();return/(^|\.)(google|bing|duckduckgo|yahoo)\./.test(u)?"search":/(^|\.)(twitter\.com|x\.com|facebook\.com|linkedin\.com|reddit\.com|t\.co)$/.test(u)?"social":"referral"}catch(n){return"direct"}}function Ce(e){if(!e)return null;try{return new URL(e).hostname}catch(t){return null}}var Ze=["gclid","gbraid","wbraid","fbclid","ttclid","msclkid","twclid","li_fat_id"];function Ge(e){let t={},n={};try{let u=typeof e=="string"||e instanceof URLSearchParams?new URLSearchParams(e):Object.entries(e).flatMap(([g,l])=>{let i=Array.isArray(l)?l[0]:l;return i===void 0?[]:[[g,i]]});for(let[g,l]of u)g.startsWith("utm_")?g in t||(t[g]=l):Ze.includes(g)&&(g in n||(n[g]=l))}catch(u){}return{utmParams:t,clickIds:n}}function Re(e){let t=e.getHours();return t<6?"night":t<12?"morning":t<18?"afternoon":"evening"}function Nt(e){let t=Rn("__segment__",e);return`${t.deviceClass}:${t.trafficSource}`}function Rn(e,t){var l,i,c,f,s,r,a,w;let n=(i=(l=t==null?void 0:t.userAgent)==null?void 0:l.trim())!=null?i:"",u=(f=(c=t==null?void 0:t.referer)==null?void 0:c.trim())!=null?f:"",g=(s=t==null?void 0:t.now)!=null?s:new Date;return{sessionId:e,ephemeral:!1,utmParams:(r=t==null?void 0:t.utmParams)!=null?r:{},clickIds:(a=t==null?void 0:t.clickIds)!=null?a:{},deviceClass:n?Ie(n):"desktop",trafficSource:u?_e(u,t==null?void 0:t.appOrigin):"direct",referrerDomain:Ce(u),timeOfDay:Re(g),dayOfWeek:(w=["sun","mon","tue","wed","thu","fri","sat"][g.getDay()])!=null?w:"sun",automation:(t==null?void 0:t.webdriver)===!0||Ee(n)}}var pe=require("@sentientui/policy");function Ae(e){return O(O(O({id:e.id},e.arms?{arms:[...e.arms]}:{}),e.dims?{dims:Object.fromEntries(Object.entries(e.dims).map(([t,n])=>[t,[...n]]))}:{}),e.baseline!==void 0?{baseline:e.baseline}:{})}function ge(e){let t=Ae(e);return(0,pe.slotResultFor)(t,(0,pe.slotBaselineArm)(t))}function Kt(e){let t={};for(let n of e)t[n.id]=ge(n);return t}function Ue(e){return typeof e=="string"?e:(0,pe.canonicalArm)(e)}var le="_snt_snap:",An=["low","medium","high"];function fe(e){try{let t=localStorage.getItem(le+e);if(!t)return null;let n=JSON.parse(t);return!n||typeof n!="object"||n.v!==1||typeof n.persona!="string"||typeof n.band!="string"||!An.includes(n.band)||typeof n.slots!="object"||n.slots===null||Array.isArray(n.slots)||!(n.layoutOrder===null||Array.isArray(n.layoutOrder))||typeof n.savedAt!="number"||!(n.slotConfig===void 0||typeof n.slotConfig=="object"&&n.slotConfig!==null&&!Array.isArray(n.slotConfig))?null:n}catch(t){return null}}function me(e,t){try{localStorage.setItem(le+e,JSON.stringify(t))}catch(n){}}function Gt(e){return"(function(){try{var r=localStorage.getItem("+JSON.stringify(le+e).replace(/</g,"\\u003c")+');if(!r)return;var s=JSON.parse(r);if(!s||s.v!==1||typeof s.persona!=="string"||typeof s.band!=="string")return;var d=document.documentElement;if(d.hasAttribute("data-sentient-persona"))return;d.setAttribute("data-sentient-persona",s.persona);d.setAttribute("data-sentient-confidence",s.band);}catch(e){}})();'}var st=require("@sentientui/policy");var $e=require("@sentientui/policy");var We="[sentient] No API key configured \u2014 nothing is being learned. Set NEXT_PUBLIC_SENTIENT_API_KEY or pass localMode: true for local development.",et="[sentient] Local mode \u2014 decisions are simulated on-device and nothing is sent over the network. Add an API key to learn from real traffic.",Ut=!1,Fe=!1;function Tn(){var e;try{return(e=new URLSearchParams(window.location.search).get("sentient_persona"))!=null?e:void 0}catch(t){return}}function Ft(e){var s;let t=Be({ssrSessionId:e.ssrSessionId,apiKey:e.apiKey}),n=(s=t.getSessionId())!=null?s:"local",u=Tn(),g=import("@sentientui/core/local").then(r=>{let a=r;return a.LOCAL_ENGINE_AVAILABLE?(Ut||(Ut=!0,console.info(et)),a):(Fe||(Fe=!0,console.error(We)),null)}).catch(()=>(Fe||(Fe=!0,console.error(We)),null)),l=null,i={low:.15,medium:.5,high:.85},c=(()=>{var a;if(e.initialPersona)return O({},e.initialPersona);let r=fe(e.apiKey||"local");return r?{persona:r.persona,confidence:(a=i[r.band])!=null?a:.15}:null})();function f(r){let a=document.documentElement;a.dataset.sentientPersona===void 0&&(a.dataset.sentientPersona=r.persona,a.dataset.sentientConfidence=(0,$e.confidenceBand)(r.confidence))}return{isLocal:!0,async decide(r){var A,p,y;let a=await g;if(!a)return null;let w=a.createLocalEngine({sessionId:n,forcedPersona:u}).decide(r);return l=de(O({},w),{layoutOrder:(p=(A=w.layoutOrder)!=null?A:l==null?void 0:l.layoutOrder)!=null?p:null,slots:O(O({},(y=l==null?void 0:l.slots)!=null?y:{}),w.slots)}),me(e.apiKey||"local",{v:1,persona:l.persona,band:(0,$e.confidenceBand)(l.confidence),slots:l.slots,layoutOrder:l.layoutOrder,savedAt:Date.now()}),f(w),w},getSlotResult(r){var a,w,A;return(A=(w=l==null?void 0:l.slots[r])!=null?w:(a=e.initialSlots)==null?void 0:a[r])!=null?A:null},getSlotConfig(r){var a,w;return(w=(a=e.initialSlotConfig)==null?void 0:a[r])!=null?w:null},getSitePalette(){var r;return(r=e.initialPalette)!=null?r:null},reportSlots(){},getPersona(){let r=l!=null?l:c;return r?{persona:r.persona,confidence:r.confidence,band:(0,$e.confidenceBand)(r.confidence)}:null},async assign(r,a){var p;let w=await g;return!w||!a||a.length===0?a!=null&&a[0]?{variantId:a[0],assignmentTtlMs:0}:null:{variantId:(p=w.createLocalEngine({sessionId:n,forcedPersona:u}).decide({components:[{id:r,variantIds:a}]}).assignments[r])!=null?p:a[0],assignmentTtlMs:0}},track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},getAssignment:()=>null,fetchWeights:()=>Promise.resolve([]),getGraph:()=>({pageNodes:[],capturedAt:0}),dispose:()=>{},destroy:()=>t.destroy()}}var nt=/^(\*|\/[^\s?#*]*(\/\*)?)$/;function tt(e){let t=e.split(/[?#]/)[0]||"/";return t.length>1?t.replace(/\/+$/,"")||"/":t}function $t(e,t){if(e===void 0||!nt.test(e))return!1;if(e==="*")return!0;let n=tt(t);if(e.endsWith("/*")){let u=tt(e.slice(0,-2));return n.startsWith(u==="/"?"/":`${u}/`)&&n!==u}return n===tt(e)}var On=["none","sm","md","lg"],Pn=["start","center","end","stretch"],Dn=["start","center","end","between"],Bn=["sm","md","lg"],Ln=["normal","medium","bold"],Mn=["default","muted","accent"],Nn=["primary","secondary","ghost"],Kn=["left","center","right"],Gn=["auto","square","landscape","wide"],Un=["cover","contain"],Fn=[2,3,4],$n=[2,3,4],Wn=["default","raised"],jn=["none","sm","md","lg"],zn=["measure"],Hn=["input","textarea","select"],Qn=["text","email","number","tel"],Jn=5,Vn=8,Xn=64,qn=5,Yn=12,Zn=4,eo=500;function Wt(e){if(e==null||typeof e!="object"||Array.isArray(e))return!1;let t=e;return t.type==="form"?!0:Array.isArray(t.children)?t.children.some(Wt):!1}var ot="sentient-reveal",ye="sentient-revealed",jt=240,je=!1;function zt(){var e;je=!1,typeof document!="undefined"&&((e=document.getElementById(ot))==null||e.remove())}function to(e){if(je||e.getElementById(ot)){je=!0;return}let t=e.createElement("style");t.id=ot,t.textContent=`@media (prefers-reduced-motion: no-preference){@keyframes ${ye}{from{opacity:.55;transform:translateY(2px)}to{opacity:1;transform:none}}.${ye}{animation:${ye} 240ms cubic-bezier(.2,.6,.2,1) both}}`,e.head.appendChild(t),je=!0}function Ht(e,t={}){var g;let n=(g=t.doc)!=null?g:typeof document!="undefined"?document:void 0;if(!n||!(e instanceof Element)||(t.arm!==void 0&&e.setAttribute("data-sentient-arm",t.arm),t.persona!==void 0&&e.setAttribute("data-sentient-persona",t.persona),t.previous!==void 0&&t.previous===e.textContent))return!1;to(n),e.classList.remove(ye),e.offsetWidth,e.classList.add(ye);let u=()=>{e.classList.remove(ye),e.removeEventListener("animationend",u)};return e.addEventListener("animationend",u),!0}function Qt(e,t,n,u){let g=[];{let c=!1,f=[],s=()=>{if(c)return;let r=Date.now();for(f.push(r);f.length>0&&r-f[0]>500;)f.shift();f.length>=3&&(c=!0,e("rage_click"))};t.addEventListener("click",s),g.push(()=>t.removeEventListener("click",s))}{let l=!1,i=c=>{if(l||!(c.target instanceof Node)||!t.contains(c.target)&&t!==c.target)return;l=!0;let f=typeof window!="undefined"?window.getSelection():null,s=f?f.toString().length:0;e("text_copy",{selectionLength:s})};document.addEventListener("copy",i),g.push(()=>document.removeEventListener("copy",i))}{let l=!1,i=!1,c=null,f=()=>{c!==null&&(clearTimeout(c),c=null)},s=()=>{l||!i||(f(),c=setTimeout(()=>{!l&&i&&(l=!0,e("scroll_hesitation"))},3e3))},r=()=>{f(),s()},a=A=>{for(let p of A)i=p.intersectionRatio>.3,i?s():f()},w=new IntersectionObserver(a,{threshold:[.3]});w.observe(t),window.addEventListener("scroll",r,{passive:!0}),g.push(()=>{w.disconnect(),window.removeEventListener("scroll",r),f()})}if((u==null?void 0:u.tabLoss)!==!1){let l=!1,i=n!=null?n:Date.now(),c=()=>{if(l||document.visibilityState!=="hidden")return;let f=Date.now()-i;f<15e3&&(l=!0,e("tab_loss",{timeOnPage:f}))};document.addEventListener("visibilitychange",c),g.push(()=>document.removeEventListener("visibilitychange",c))}return()=>{for(let l of g)l()}}function no(){var e;return typeof process=="undefined"||((e=process.env)==null?void 0:e.NODE_ENV)!=="production"}var Jt="https://api.sentient-ui.com/v1/events",$=new Map,Vt=null;function oo(e,t){let n=$.get(e);n&&n.upgrade&&(n.reinit=t)}function ro(e){return"value"in e||"currency"in e||"externalId"in e||"metadata"in e||"weight"in e||"stepIndex"in e}var so=3;function rt(){return Oe()}function ze(){var e;if(typeof window!="undefined")return((e=window.location)==null?void 0:e.pathname)||void 0}function io(){let e=new WeakMap,t=new Map,n=!1,u=(c,f,s)=>{let r=c.get(f);return s===null?r?!0:(c.set(f,new Set),!1):r?r.has(s)?!0:(r.add(s),!1):(c.set(f,new Set([s])),!1)},g=typeof window!="undefined"&&"event"in window,l=()=>{if(!g)return;let c=window.event;return typeof Event=="function"&&c instanceof Event?c:void 0},i=()=>{if(g){Promise.resolve().then(()=>{n=!1,t.clear()});return}let c=!1,f=()=>{c||(c=!0,n=!1,t.clear())};if(setTimeout(f,0),typeof MessageChannel=="function"){let s=new MessageChannel;s.port1.onmessage=()=>{s.port1.close(),s.port2.close(),f()},s.port2.postMessage(0)}};return{firedBefore(c,f){let s=l();if(s){let a=e.get(s);return a||(a=new Map,e.set(s,a)),u(a,c,f)}let r=u(t,c,f);return!r&&!n&&(n=!0,i()),r}}}var Xt=new Set;function ao(e,t,n){let u=typeof window=="undefined"?null:window.history;if(!u)return()=>{};let g=!1,l,i=()=>{if(g)return;let s=ze();!s||s===l||(l=s,e.track({projectId:t,componentId:"__page__",eventType:"pageview",payload:{}}),n(`${t}:${s}`))},c=[];for(let s of["pushState","replaceState"]){let r=u[s],a=function(...w){let A=r.apply(this,w);return i(),A};u[s]=a,c.push([s,r,a])}window.addEventListener("popstate",i);let f=ze();return f&&Xt.has(`${t}:${f}`)?l=f:i(),()=>{if(!g){g=!0,window.removeEventListener("popstate",i);for(let[s,r,a]of c)u[s]===a&&(u[s]=r)}}}var Te={track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},getAssignment:()=>null,assign:()=>Promise.resolve(null),decide:()=>Promise.resolve(null),getSlotResult:()=>null,getSlotConfig:()=>null,getSitePalette:()=>null,reportSlots:()=>{},getPersona:()=>null,fetchWeights:()=>Promise.resolve([]),getGraph:()=>({pageNodes:[],capturedAt:0}),dispose:()=>{},destroy:()=>{}};function lo(){try{return Ge(window.location.search)}catch(e){return{utmParams:{},clickIds:{}}}}function qt(e){return e.replace(/\/events\/?$/,"")}function at(){return typeof navigator!="undefined"&&navigator.globalPrivacyControl===!0?!0:[typeof navigator!="undefined"?navigator.doNotTrack:void 0,typeof window!="undefined"?window.doNotTrack:void 0,typeof navigator!="undefined"?navigator.msDoNotTrack:void 0].some(t=>t==="1"||t==="yes")}function co(e){var f;if(typeof window=="undefined")return;let t=e!=null?e:Vt;if(!t){console.warn("[sentient] grantConsent() called before init()");return}let n=$.get(t);if(!n){console.warn("[sentient] grantConsent() called before init()");return}let{config:u,upgrade:g,reinit:l}=n;if(!g){n.upgradeBlockedReason&&console.warn(n.upgradeBlockedReason);return}if(u.respectDoNotTrack!==!1&&at())return;let i=(l!=null?l:Yt)(de(O({},u),{consent:!0}));g(i);let c=(f=$.get(t))==null?void 0:f.dispose;$.set(t,{config:de(O({},u),{consent:!0}),upgrade:null,dispose:c})}function uo(e){var A;let t=e.preConsentBehavior==="statistical_winner",n=qt((A=e.ingestUrl)!=null?A:Jt),u={"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`},g=new Map,l=new Map,i={track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},getAssignment:()=>null,fetchWeights:()=>Promise.resolve([]),assign(p,y,k){if(!t)return Promise.resolve(null);let b=g.get(p);return b?Promise.resolve(b):it(l,p,async()=>{try{let N=new URLSearchParams({componentId:p});for(let D of y!=null?y:[])N.append("variantIds[]",D);let G=await fetch(`${n}/winner?${N.toString()}`,{headers:u});if(!G.ok)return y!=null&&y[0]?{variantId:y[0],assignmentTtlMs:0}:null;let L={variantId:(await G.json()).variantId,assignmentTtlMs:0};return g.set(p,L),L}catch(N){return y!=null&&y[0]?{variantId:y[0],assignmentTtlMs:0}:null}})},decide:()=>Promise.resolve(null),getSlotResult:()=>null,getSlotConfig:()=>null,getSitePalette:()=>null,reportSlots:()=>{},getPersona:()=>null,getGraph:()=>({pageNodes:[],capturedAt:0}),dispose:()=>{},destroy:()=>{}},c=!1,f=new Set,s=[],r=[],a={track:p=>i.track(p),goal:((p,y,k,b)=>i.goal(p,y,k,b)),componentGoal:(p,y,k)=>i.componentGoal(p,y,k),identify:p=>i.identify(p),getAssignment:(p,y)=>i.getAssignment(p,y),assign:(p,y,k,b)=>i.assign(p,y,k,b),decide:p=>i.decide(p),getSlotResult:p=>i.getSlotResult(p),isSlotDecided:p=>{var y,k;return(k=(y=i.isSlotDecided)==null?void 0:y.call(i,p))!=null?k:!0},getSlotConfig:p=>i.getSlotConfig(p),getSitePalette:()=>i.getSitePalette(),reportSlots:(p,y)=>i.reportSlots(p,y),requestSlots:(p,y)=>{var k;return c?(k=i.requestSlots)==null?void 0:k.call(i,p,y):s.push([p,y])},decideSlots:p=>{var y;return c?(y=i.decideSlots)==null?void 0:y.call(i,p):r.push(...p)},cancelSlots:p=>{var k;if(c)return(k=i.cancelSlots)==null?void 0:k.call(i,p);let y=new Set(p);for(let b of s)b[0]=b[0].filter(N=>!y.has(N));r=r.filter(b=>!y.has(b.id))},onSlotsChanged:p=>(f.add(p),()=>{f.delete(p)}),getPersona:()=>i.getPersona(),fetchWeights:()=>i.fetchWeights(),getGraph:()=>i.getGraph(),dispose:()=>i.dispose(),destroy:()=>i.destroy()};function w(p){var y,k,b;i=p,c=!0,(y=p.onSlotsChanged)==null||y.call(p,()=>f.forEach(N=>N()));for(let[N,G]of s.splice(0))N.length>0&&((k=p.requestSlots)==null||k.call(p,N,G));r.length>0&&((b=p.decideSlots)==null||b.call(p,r.splice(0)))}return{proxy:a,setInner:w}}function it(e,t,n){let u=e.get(t);if(u)return u;let g=(async()=>{try{return await n()}finally{e.delete(t)}})();return e.set(t,g),g}function Yt(e){var gt,ft,mt,yt,St,ht,vt,xt,wt,bt;if(typeof window=="undefined")return Te;Vt=e.apiKey||"local";let t=$.get(e.apiKey||"local");if(t!=null&&t.dispose)try{t.dispose()}catch(o){}let n=e.respectDoNotTrack!==!1&&at(),u=e.consent===!1||n,g=typeof e.apiKey=="string"&&e.apiKey.startsWith("pk_");if(e.localMode===!0||!g&&e.localMode!==!1)return $.set(e.apiKey||"local",{config:e,upgrade:null,upgradeBlockedReason:"[sentient] grantConsent(): this client is keyless/local \u2014 there is no hosted client to upgrade to. Configure a pk_ API key to enable tracking."}),u?Te:Ft(e);if(u){if(!e.apiKey||!e.apiKey.startsWith("pk_"))return e.preConsentBehavior==="statistical_winner"&&console.warn("[sentient] init() called with an invalid apiKey \u2014 expected a pk_ public key. SDK disabled."),$.set(e.apiKey||"local",{config:e,upgrade:null,upgradeBlockedReason:"[sentient] grantConsent(): the client was initialized with an invalid apiKey (expected a pk_ public key) \u2014 consent cannot enable tracking."}),Te;let{proxy:o,setInner:d}=uo(e);return $.set(e.apiKey,{config:e,upgrade:n?null:d}),o}if(!e.apiKey||!e.apiKey.startsWith("pk_"))return console.warn("[sentient] init() called with an invalid apiKey \u2014 expected a pk_ public key. SDK disabled."),Te;if(e.ingestUrl==="")return console.warn("[sentient] init() called with an empty ingestUrl. SDK disabled."),Te;let l=(gt=e.ingestUrl)!=null?gt:Jt,i=Date.now(),c=Be({ssrSessionId:e.ssrSessionId,apiKey:e.apiKey}),f=Bt(void 0,e.apiKey),s=Pt({ingestUrl:l,apiKey:e.apiKey}),r=qt(l),a={"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`},w=new Set,A=Dt({url:`${r}/goals`,apiKey:e.apiKey,headers:a,onDrop:(o,d)=>{if(!e.debug){if(w.has(d))return;w.add(d)}console.warn(`[sentient] goal dropped (HTTP ${d}) \u2014 this will not be retried. `+(d===400?"The session was not found: call init() and let the session upsert complete before firing goals.":d===401||d===403?"Check the API key and that this origin is on the project allowlist.":"See the response status for the cause."),o)}}),p=Ie((ft=navigator.userAgent)!=null?ft:""),y=window.location.origin,k=_e((mt=document.referrer)!=null?mt:"",y),b=(yt=e.sessionSegment)!=null?yt:`${p}:${k}`,N=new Map,G=new Map,P=new Map,L=new Set,D=new Map,h=null,I=null,Z=new Set,W=new Set,V=new Map,X=null,Se=/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,127}$/,v=new Set,R=new Set,j=new Set,Q=new Map,z=null,re=new Set,H=new Map,se=null,ie=2,lt=new Map,He=!1,ct=(o,d,m)=>{var S;let x=new Set,_=1;for(let E of o){d.delete(E);let C=((S=lt.get(E))!=null?S:0)+1;lt.set(E,C),C<=ie&&(x.add(E),C>_&&(_=C))}x.size>0&&setTimeout(()=>{He||m(x)},Y(_))},dt=o=>{for(let d of o)P.has(d.id)||P.set(d.id,ge(d))};if(e.initialSlots)for(let[o,d]of Object.entries(e.initialSlots))P.set(o,d),L.add(o);if(e.initialSlotConfig)for(let[o,d]of Object.entries(e.initialSlotConfig))D.set(o,d);e.initialPalette&&(h=e.initialPalette);let ee=fe(e.apiKey);if(ee){for(let[o,d]of Object.entries(ee.slots))P.has(o)||P.set(o,d);for(let[o,d]of Object.entries((St=ee.slotConfig)!=null?St:{}))D.has(o)||D.set(o,d);!h&&ee.palette&&(h=ee.palette)}let ut={low:.15,medium:.5,high:.85};if(e.initialPersona)I=O({},e.initialPersona);else{let o=document.documentElement.dataset;o.sentientPersona?I={persona:o.sentientPersona,confidence:(vt=ut[(ht=o.sentientConfidence)!=null?ht:"low"])!=null?vt:.15}:ee&&(I={persona:ee.persona,confidence:(xt=ut[ee.band])!=null?xt:.15})}if(e.initialAssignments)for(let[o,d]of Object.entries(e.initialAssignments))f.set(o,b,{variantId:d,assignedAt:Date.now(),segment:b,confidence:1});let te=Promise.resolve(),pt=c.getSessionId();if(pt){let o=Ce((wt=document.referrer)!=null?wt:""),{utmParams:d,clickIds:m}=lo(),x=O(O(O(O({sessionId:pt,deviceClass:p,trafficSource:k,referrerDomain:o,utmParams:d,clickIds:m,timeOfDay:Re(new Date),dayOfWeek:["sun","mon","tue","wed","thu","fri","sat"][new Date().getDay()],ephemeral:c.isEphemeral(),automation:typeof navigator!="undefined"&&navigator.webdriver===!0||Ee((bt=navigator.userAgent)!=null?bt:"")},e.userId?{userId:e.userId}:{}),e.persona?{persona:e.persona}:{}),e.country?{country:e.country}:{}),e.sdk?{sdk:e.sdk.name,sdkVersion:e.sdk.version}:{}),_=async()=>{for(let S=0;;S++){try{let E=await fetch(`${r}/sessions`,{method:"POST",keepalive:!0,body:JSON.stringify(x),headers:a});if(E.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");return}if(E.ok||ue(E)==="dropped")return}catch(E){}if(S>=so){console.warn("[SentientUI] Could not register the session after retries. Conversions in this visit may not be recorded.");return}await new Promise(E=>setTimeout(E,Y(S+1)))}};try{te=_()}catch(S){}}e.debug&&(console.log("[sentient] initialized",{context:e.context}),window.__sentient={client:null,queue:s});let Zt=io(),ae=null,Qe=!1,K={goal(o,d={},m=1,x=0){var ne,he,ve,xe,ce,T,q;let _=c.getSessionId();if(!_)return;let S=ro(d)?d:{metadata:d},E=[o,(ne=S.externalId)!=null?ne:"",(he=S.stepIndex)!=null?he:x,(ve=S.weight)!=null?ve:m].join("\0"),C=S.value!==void 0?`${S.value}\0${(xe=S.currency)!=null?xe:""}`:null;if(Zt.firedBefore(E,C)){e.debug&&console.log(`[sentient] goal("${o}") already recorded for this action \u2014 not sent twice`);return}let M=rt(),U={sessionId:_,name:o,metadata:(ce=S.metadata)!=null?ce:{},weight:(T=S.weight)!=null?T:m,stepIndex:(q=S.stepIndex)!=null?q:x,goalId:M,value:S.value,currency:S.currency,externalId:S.externalId};e.debug&&console.log("[sentient] goal",U);let F={id:M,body:JSON.stringify(U)};te.then(()=>A.send(F))},componentGoal(o,d,m){var M,U,F;let x=c.getSessionId();if(!x)return;let _=f.get(o,b),S=_?null:(M=P.get(o))!=null?M:null;if(!_&&S===null){e.debug&&console.warn(`[sentient] componentGoal("${o}"): no assignment or slot decision yet \u2014 render its <Adaptive>/adaptive hook or call assign()/decide() before recording a goal.`);return}if(!_&&!L.has(o)){e.debug&&console.warn(`[sentient] componentGoal("${o}"): slot not decided this session \u2014 not attributed`);return}let E=_?_.variantId:Ue(S),C={id:rt(),sessionId:x,projectId:e.apiKey,componentId:o,variantId:E,eventType:"goal_achieved",goalType:d,payload:O({reward:(U=m==null?void 0:m.reward)!=null?U:1,goalValue:m==null?void 0:m.value,currency:m==null?void 0:m.currency},(F=m==null?void 0:m.metadata)!=null?F:{}),timestamp:Date.now(),timeInSession:Date.now()-i,path:ze()};e.debug&&console.log("[sentient] componentGoal",C),te.then(()=>s.push(C))},identify(o){let d=c.getSessionId();d&&te.then(()=>{fetch(`${r}/sessions`,{method:"POST",keepalive:!0,body:JSON.stringify({sessionId:d,userId:o,ephemeral:c.isEphemeral()}),headers:a}).catch(()=>{})})},track(o){let d=c.getSessionId();if(!d||o.eventType==="variant_assigned"&&P.get(o.componentId)!==void 0&&!L.has(o.componentId)&&!f.get(o.componentId,b))return;let m=de(O({path:ze()},o),{id:rt(),sessionId:d,timestamp:Date.now(),timeInSession:Date.now()-i});e.debug&&console.log("[sentient] track",m),te.then(()=>s.push(m))},getAssignment(o,d){return f.get(o,d)},async assign(o,d,m,x){let _=c.getSessionId();if(!_)return null;let S=f.get(o,b);if(S&&(d!=null&&d.length||S.content!==void 0)){let E=S.ttlMs&&S.ttlMs>0?Math.max(0,S.assignedAt+S.ttlMs-Date.now()):0;return{variantId:S.variantId,assignmentTtlMs:E,content:S.content}}return it(N,o,async()=>{await te;try{let E={sessionId:_,componentId:o,variantIds:d};x!==void 0?E.agentDataByVariant=x:m!==void 0&&(E.agentData=m);let C=await fetch(`${r}/assign`,{method:"POST",body:JSON.stringify(E),headers:a});if(!C.ok)return null;let M=await C.json();return f.set(o,b,O({variantId:M.variantId,assignedAt:Date.now(),segment:b,confidence:1,content:M.content},M.assignmentTtlMs&&M.assignmentTtlMs>0?{ttlMs:M.assignmentTtlMs}:{})),M}catch(E){return null}})},async decide(o){var S,E;let d=c.getSessionId();if(!d)return null;let m=(S=o.slots)!=null?S:[],x={sessionId:d};o.sections&&o.sections.length>0&&(x.sections=o.sections.map(C=>({id:C}))),x.components=(E=o.components)!=null?E:[],m.length>0&&(x.slots=m.map(Ae)),o.slotsFrom==="registry"&&(x.slotsFrom="registry",o.registrySlotIds&&(x.registrySlotIds=o.registrySlotIds),o.bootstrap===!1&&(x.bootstrap=!1)),o.v&&(x.v=o.v),typeof o.pp=="number"&&(x.pp=o.pp),e.persona&&(x.persona=e.persona);let _=JSON.stringify(x);return it(G,_,async()=>{var C,M,U,F,ne,he,ve,xe;await te;try{let ce=await fetch(`${r}/decide`,{method:"POST",body:_,headers:a});if(!ce.ok)return dt(m),null;let T=await ce.json(),q={};for(let B of m){let J=(C=T.slots)==null?void 0:C[B.id];if(J!==void 0){q[B.id]=J,P.set(B.id,J),L.add(B.id);continue}let kt=P.get(B.id);if(kt!==void 0)q[B.id]=kt;else{let Et=ge(B);q[B.id]=Et,P.set(B.id,Et)}}if(T.slots)for(let[B,J]of Object.entries(T.slots))B in q||(q[B]=J,P.set(B,J),L.add(B));let en=I!=null&&I.persona!=="unknown";T.persona&&!(T.persona==="unknown"&&en)?I={persona:T.persona,confidence:(M=T.confidence)!=null?M:0}:I||(I={persona:"unknown",confidence:0});for(let[B,J]of Object.entries((U=T.assignments)!=null?U:{}))f.set(B,b,{variantId:J,assignedAt:Date.now(),segment:b,confidence:1});if(T.slotConfig)for(let[B,J]of Object.entries(T.slotConfig))D.set(B,J);T.palette&&(h=T.palette);for(let B of(F=o.registrySlotIds)!=null?F:[])(ne=T.slotConfig)!=null&&ne[B]||(D.delete(B),P.delete(B),L.delete(B));return me(e.apiKey,O(O({v:1,persona:I.persona,band:(0,st.confidenceBand)(I.confidence),slots:Object.fromEntries(P),layoutOrder:(he=T.layoutOrder)!=null?he:null,savedAt:Date.now()},D.size>0?{slotConfig:Object.fromEntries(D)}:{}),h?{palette:h}:{})),O(O(O(O({layoutOrder:(ve=T.layoutOrder)!=null?ve:null,assignments:(xe=T.assignments)!=null?xe:{},slots:q,persona:I.persona,confidence:I.confidence},T.slotConfig?{slotConfig:T.slotConfig}:{}),T.goals?{goals:T.goals}:{}),T.sectionMap?{sectionMap:T.sectionMap}:{}),T.palette?{palette:T.palette}:{})}catch(ce){return dt(m),null}})},getSlotResult(o){var d;return(d=P.get(o))!=null?d:null},isSlotDecided(o){return L.has(o)},getSlotConfig(o){var d;return(d=D.get(o))!=null?d:null},reportSlots(o,d){for(let m of o)if(!(typeof m!="string"||m.length===0)){if(!Se.test(m)){no()&&!v.has(m)&&(v.add(m),console.warn(`[sentient] reportSlots: slot id ${JSON.stringify(m)} will not register \u2014 ids must start with a letter or digit and contain only letters, digits, '_' or '-' (max 128 chars): /^[a-zA-Z0-9][a-zA-Z0-9_-]{0,127}$/.`));continue}if(!Z.has(m)){Z.add(m),W.add(m);let x=d==null?void 0:d[m];if(typeof x=="string"){let _=x.replace(/\s+/g," ").trim().slice(0,400);_!==""&&V.set(m,_)}}}W.size===0||X!=null||(X=setTimeout(()=>{X=null;let m=[...W];W.clear();for(let x=0;x<m.length;x+=20){let _=m.slice(x,x+20),S={};for(let E of _){let C=V.get(E);C!==void 0&&(S[E]=C,V.delete(E))}fetch(`${r}/slots/observed`,{method:"POST",headers:a,body:JSON.stringify(O({slotIds:_},Object.keys(S).length>0?{baselineTexts:S}:{}))}).catch(()=>{})}},1e3))},requestSlots(o,d){for(let m of o)j.has(m)||(j.add(m),Se.test(m)?Q.set(m,d==null?void 0:d[m]):K.reportSlots([m]));Q.size===0||z!=null||(z=setTimeout(()=>{z=null;let m=[...Q];Q.clear();for(let x=0;x<m.length;x+=50){let _=m.slice(x,x+50);K.decide({slotsFrom:"registry",registrySlotIds:_.map(([S])=>S),bootstrap:!1}).then(S=>{var E;if(S){let C={},M=[];for(let[U,F]of _)(E=S.slotConfig)!=null&&E[U]||(M.push(U),F&&(C[U]=F));M.length>0&&K.reportSlots(M,C)}else ct(_.map(([C])=>C),j,C=>{var U;let M={};for(let[F,ne]of _)C.has(F)&&ne&&(M[F]=ne);(U=K.requestSlots)==null||U.call(K,[...C],M)});R.forEach(C=>C())})}},0))},decideSlots(o){for(let d of o)re.has(d.id)||(re.add(d.id),H.set(d.id,d));H.size===0||se!=null||(se=setTimeout(()=>{se=null;let d=[...H.values()];H.clear();for(let m=0;m<d.length;m+=30){let x=d.slice(m,m+30);K.decide({slots:x}).then(_=>{_||ct(x.map(S=>S.id),re,S=>{var E;return(E=K.decideSlots)==null?void 0:E.call(K,x.filter(C=>S.has(C.id)))}),R.forEach(S=>S())})}},0))},cancelSlots(o){for(let d of o)Q.delete(d)&&j.delete(d),H.delete(d)&&re.delete(d)},onSlotsChanged(o){return R.add(o),()=>{R.delete(o)}},getSitePalette(){return h},getPersona(){return I?{persona:I.persona,confidence:I.confidence,band:(0,st.confidenceBand)(I.confidence)}:null},async fetchWeights(){var o;try{let d=await fetch(`${r}/weights`,{headers:a});return d.ok?(o=(await d.json()).components)!=null?o:[]:[]}catch(d){return[]}},getGraph(){return{pageNodes:[],capturedAt:0}},dispose(){var o;ae==null||ae(),Qe=!0,He=!0,s.destroy(),A.destroy(),((o=$.get(e.apiKey))==null?void 0:o.dispose)===K.dispose&&$.delete(e.apiKey),e.debug&&console.log("[sentient] disposed")},destroy(){var o;ae==null||ae(),Qe=!0,He=!0,s.destroy(),A.destroy(),c.destroy(),f.clear(),((o=$.get(e.apiKey))==null?void 0:o.dispose)===K.dispose&&$.delete(e.apiKey);try{localStorage.removeItem(le+e.apiKey),localStorage.removeItem(Xe(e.apiKey)),localStorage.removeItem(qe(e.apiKey))}catch(d){}e.debug&&console.log("[sentient] destroyed")}};if($.set(e.apiKey,{config:e,upgrade:null,dispose:K.dispose}),ae=ao(K,e.apiKey,o=>{te.then(()=>{Qe||Xt.add(o)})}),e.debug){let o=window;o.__sentient&&(o.__sentient.client=K)}return K}0&&(module.exports={AGENT_INTENTS,BLOCK_ALIGNS,BLOCK_EMPHASES,BLOCK_FITS,BLOCK_GAPS,BLOCK_GRID_COLUMNS,BLOCK_HEADING_LEVELS,BLOCK_JUSTIFIES,BLOCK_MAX_WIDTHS,BLOCK_PADS,BLOCK_RATIOS,BLOCK_SIZES,BLOCK_SURFACES,BLOCK_TEXT_ALIGNS,BLOCK_TONES,BLOCK_WEIGHTS,CLICK_ID_KEYS,FORM_FIELD_KINDS,FORM_INPUT_TYPES,LEGACY_SESSION_COOKIE_NAME,LOCAL_MODE_BANNER,MAX_BLOCK_ARMS,MAX_BLOCK_CHILDREN,MAX_BLOCK_DEPTH,MAX_BLOCK_NODES,MAX_BLOCK_TEXT_LEN,MAX_FORM_FIELDS,MAX_FORM_SELECT_OPTIONS,PAGE_SCOPE_RE,PROD_KEYLESS_ERROR,REVEAL_MS,SNAPSHOT_STORAGE_KEY_PREFIX,_registerConsentUpgradeInit,agentIntent,agentUaList,armOfResult,attachMicroSignalDetectors,baselineResultFor,baselineSlots,classifiedAgents,containsFormBlock,deriveSessionSegment,detectDeviceClass,detectTimeOfDay,detectTrafficSource,extractTrackedParams,grantConsent,init,isDoNotTrackEnabled,matchedAgentToken,pageScopeMatches,readSnapshot,referrerDomainFromReferer,renderPrePaintScript,resetRevealStyles,reveal,sessionCookieName,toWireSlot,uaTokenMatch,writeSnapshot});
|
|
2
2
|
//# sourceMappingURL=index.js.map
|