@sentientui/core 0.39.1 → 0.40.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunk-KR2X3I7H.mjs +2 -0
- package/dist/chunk-KR2X3I7H.mjs.map +1 -0
- package/dist/chunk-LGXPG6IM.mjs +2 -0
- package/dist/chunk-LGXPG6IM.mjs.map +1 -0
- package/dist/chunk-NBDVEYI5.mjs +2 -0
- package/dist/chunk-NBDVEYI5.mjs.map +1 -0
- package/dist/{index-BAfi7_FG.d.cts → index-Cgiw9NDh.d.cts} +45 -2
- package/dist/{index-DyKtujwf.d.ts → index-DqDG5phU.d.ts} +45 -2
- package/dist/index-consent.js +1 -1
- package/dist/index-consent.js.map +1 -1
- package/dist/index-consent.mjs +1 -1
- package/dist/index-engagement.js.map +1 -1
- package/dist/index-engagement.mjs +1 -1
- package/dist/index-graph.d.cts +4 -4
- package/dist/index-graph.d.ts +4 -4
- 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-local.d.cts +2 -2
- package/dist/index-local.d.ts +2 -2
- package/dist/index-server.d.cts +27 -4
- package/dist/index-server.d.ts +27 -4
- 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-qx4kIL5y.d.cts → session-meta-BG8w53d7.d.cts} +1 -1
- package/dist/{session-meta-BtRtwsHI.d.ts → session-meta-D9Wx2PtC.d.ts} +1 -1
- package/package.json +1 -1
- package/dist/chunk-MKM7TD3L.mjs +0 -2
- package/dist/chunk-MKM7TD3L.mjs.map +0 -1
- package/dist/chunk-QEIHHO3T.mjs +0 -2
- package/dist/chunk-QEIHHO3T.mjs.map +0 -1
- package/dist/chunk-XZRKD2GS.mjs +0 -2
- package/dist/chunk-XZRKD2GS.mjs.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/server.ts","../src/agent-capture.ts"],"sourcesContent":["/**\n * Server-side helpers for SSR variant pre-loading.\n * Pure fetch — no DOM APIs. Safe in Node.js, Edge, and Deno runtimes.\n */\nimport { buildSessionUpsertPayload } from './session-meta.js';\nimport { LEGACY_SESSION_COOKIE_NAME, sessionCookieName } from './storage-key.js';\nimport {\n toWireSlot,\n baselineResultFor,\n baselineSlots,\n type SlotDeclInput,\n type SlotResult,\n} from './slots.js';\n\nimport type { SlotConfigEntry } from './snapshot.js';\nimport type { RenderCaps } from './region-skeleton.js';\nimport type { SitePalette } from './blocks.js';\n\nexport type { SlotDeclInput, SlotResult, SlotConfigEntry, SitePalette };\n\nexport type ServerAssignConfig = {\n /** Public API key (pk_...). */\n apiKey: string;\n /**\n * Base URL of the Sentient API without trailing slash.\n * e.g. 'https://api.yourapp.com/v1'\n */\n baseUrl: string;\n /**\n * Browser origin of your app (e.g. `http://localhost:3001`). Required for `pk_`\n * keys — server-side fetch must send the same `Origin` the API allows.\n */\n origin?: string;\n /**\n * Optional: this project's SECRET key (sk_...), read from a server-only env\n * var. When set, SSR calls also send it as `X-Sentient-Server-Key`, which\n * proves they come from your server: the API then holds them to your plan's\n * per-key limit instead of the 100 requests/min per-IP cap meant for\n * browsers — without it, all SSR traffic from one server address shares that\n * one cap. Never set this in code that ships to the browser; it is ignored\n * (and not sent) when `window` exists.\n */\n serverKey?: string;\n /** From `User-Agent` request header (Next.js `headers()`). */\n userAgent?: string;\n /** From `Referer` request header. */\n referer?: string;\n utmParams?: Record<string, string>;\n /**\n * Ad-platform click IDs (gclid, fbclid, ttclid, …) from the landing URL.\n * Derive both this and `utmParams` with `extractTrackedParams(searchParams)`\n * — the Referer header never carries the landing page's own query string, so\n * without these two fields SSR-minted sessions have no campaign attribution\n * until the client SDK hydrates.\n */\n clickIds?: Record<string, string>;\n /**\n * The landing page's path (no query string). With it the server can tell a\n * paid click to a product page, or a Shopify `/discount/CODE` link, from any\n * other arrival on the FIRST decision of the visit.\n */\n landingPath?: string;\n /**\n * Set true when the request carries a tracking opt-out — `DNT: 1` or\n * `Sec-GPC: 1`. When set, the SSR helpers skip the session upsert and the\n * assign/decide call entirely: the page renders defaults/baseline and no\n * session row is minted for the visitor (audit P4). The client SDK already\n * no-ops for these visitors; this keeps the server from minting a session +\n * assignment on every page view before the client can.\n */\n doNotTrack?: boolean;\n /**\n * Declared persona — the role your app already knows for this visitor\n * (e.g. from your auth context during SSR). Same contract as the client\n * option: must be a vocabulary key; unrecognized values are ignored\n * server-side. Never a user id or email.\n */\n persona?: string;\n /**\n * Milliseconds to wait for the API before returning default variants.\n * Prevents slow/cold API from blocking SSR. Defaults to 1000 — the hot path\n * is served from in-process caches and typically returns in well under\n * 150 ms. The full 1 s budget is only reached on a cold start or an API\n * geographically distant from your SSR host, after which defaults render\n * with no layout shift. Lower it if your API is co-located and warm.\n */\n timeoutMs?: number;\n};\n\n/** Header carrying `serverKey` (apps/api lib/rate-limit.ts SERVER_KEY_HEADER). */\nexport const SERVER_KEY_HEADER = 'X-Sentient-Server-Key';\n\n/** Auth headers for an SSR call: the pk_, its Origin, and the optional server proof. */\nfunction ssrHeaders(config: ServerAssignConfig): Record<string, string> {\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${config.apiKey}`,\n };\n if (config.origin) headers.Origin = config.origin;\n // A secret key must never leave a browser: if this module was bundled\n // client-side by mistake, drop it rather than send it.\n if (config.serverKey && typeof window === 'undefined') headers[SERVER_KEY_HEADER] = config.serverKey;\n return headers;\n}\n\n/** componentId → assigned variantId */\nexport type ServerAssignments = Record<string, string>;\n\ntype AssignResult = { variantId: string; assignmentTtlMs: number; unified?: true };\n\n/** `preloadAssignmentsDetailed`'s answer: the assignments, plus the ids the\n * server handed back as moved to the shared track (only when asked). */\nexport type ServerAssignmentsDetailed = { assignments: ServerAssignments; unified: string[] };\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 return (await preloadAssignmentsDetailed(components, sessionId, config)).assignments;\n}\n\n/**\n * `preloadAssignments`, and also which components were moved onto the shared\n * track. With `opts.unified` each assign says the page can follow such a move:\n * a moved id is then not assigned (nothing is recorded for it) and comes back\n * in `unified`, for the page to render as a slot. Pass those ids to\n * `<AdaptiveProvider initialUnified>`. Without it a moved id is served its\n * frozen result read-only, as for any older SDK.\n */\nexport async function preloadAssignmentsDetailed(\n components: Array<{ id: string; variantIds: string[] }>,\n sessionId: string,\n config: ServerAssignConfig,\n opts?: { unified?: boolean },\n): Promise<ServerAssignmentsDetailed> {\n // Opted-out visitor (DNT/GPC): render defaults, mint no session (audit P4).\n if (config.doNotTrack) return { assignments: {}, unified: [] };\n\n const timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n const headers = ssrHeaders(config);\n\n // Session metadata must match the browser SDK so assign seeds variant_weights\n // under the same segment (not `unknown:unknown`).\n const sessionBody = {\n ...buildSessionUpsertPayload(sessionId, {\n userAgent: config.userAgent,\n referer: config.referer,\n utmParams: config.utmParams,\n clickIds: config.clickIds,\n appOrigin: config.origin,\n landingPath: config.landingPath,\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 {\n method: 'POST',\n headers,\n body: JSON.stringify({ sessionId, componentId: id, variantIds, ...(opts?.unified ? { caps: { unified: true } } : {}) }),\n },\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, unified: opts?.unified === true && body.unified === true };\n }),\n );\n\n const assignments: ServerAssignments = {};\n const unified: string[] = [];\n for (const result of results) {\n if (result.status === 'fulfilled' && result.value) {\n // A moved id's variantId is only its declared baseline, not an\n // assignment: seeding it would settle the page on the frozen run.\n if (result.value.unified) unified.push(result.value.id);\n else assignments[result.value.id] = result.value.variantId;\n }\n }\n return { assignments, unified };\n}\n\n/**\n * Reads the Sentient session cookie from a Next.js `ReadonlyRequestCookies` object\n * (the return value of `cookies()` from `next/headers`), or any object with a\n * `get(name: string)` method. Returns null if the cookie is absent.\n *\n * Pass the project's `apiKey`: the client writes the per-project SUFFIXED name\n * (`sessionCookieName` — see storage-key.ts), so reading only the bare\n * `_snt_uid` missed the cookie on every SSR request for a returning visitor and\n * minted a fresh orphan session each page view (quota inflation, broken sticky\n * assignments and persona continuity). The bare name is still read as a\n * fallback for identities minted before namespacing.\n */\nexport function readSessionCookie(\n cookies: { get(name: string): { value: string } | undefined },\n apiKey?: string,\n): string | null {\n return (\n (apiKey ? cookies.get(sessionCookieName(apiKey))?.value : undefined) ??\n cookies.get(LEGACY_SESSION_COOKIE_NAME)?.value ??\n null\n );\n}\n\nexport type DecideResult = {\n layoutOrder: string[];\n assignments: Record<string, string>;\n /** Slot results keyed by slot id. Baseline-resolved when the API omits/fails them. */\n slots: Record<string, SlotResult>;\n persona: string;\n confidence: number;\n /** Registry mode only: content/ops/blocks for server-defined slots. */\n slotConfig?: Record<string, SlotConfigEntry>;\n /** Registry mode only: site palette for block rendering. */\n palette?: SitePalette;\n /** Registry mode only: site styles the served Redesign arms borrow. */\n vocabulary?: import('./style-vocabulary.js').StyleVocabulary;\n /** The visit's funnel stage, raw — projects with stages on, treated visitors\n * only. Pass it through `exposedStage` before it reaches the page. */\n stage?: string;\n /** The visit's serving context. Never for the page. */\n context?: string;\n /** Requested components moved onto the shared track (only with\n * `unifiedCaps`): not in `assignments`; render each as a slot. */\n unified?: string[];\n};\n\n/**\n * Single-roundtrip SSR call returning layout order, component assignments,\n * and adaptive-slot results. Falls back to default section order + empty\n * assignments + baseline slots if the API is unavailable. A response without\n * a `slots` field means the server predates slots — every declared slot\n * resolves to its baseline (no retry).\n */\nexport async function preloadDecisions(\n params: {\n sections?: string[];\n components: Array<{ id: string; variantIds?: string[] }>;\n slots?: SlotDeclInput[];\n /** 'registry' serves the project's published slot_definitions as if declared\n * (and is the only way slotConfig/palette come back). Default 'request'.\n * Requires `registrySlotIds`: the `<Adaptive id>`s THIS page renders. */\n slotsFrom?: 'request' | 'registry';\n /**\n * Registry mode: decide only these published slot ids. Close-out turns\n * every slot decision into a trial without checking an exposure, so an\n * unscoped registry decide accrues trials — and session-level credit — for\n * every published slot on every page, including ones this page never\n * renders (CONTRACTS §2). Omitting it in registry mode is refused: the\n * call downgrades to request mode with one console.error, rather than\n * silently minting those trials.\n */\n registrySlotIds?: string[];\n /**\n * Registry mode: what each slot on this page can render (CONTRACTS §2).\n * The server has no DOM here, so no fingerprint is sent and a Rewrite arm\n * is assumed to match; a real mismatch is reported from the browser as\n * drift. Declare `forms: false` for slots without an `onFormSubmit`, or a\n * form arm can be drawn that this page will refuse. Default per slot:\n * `{ forms: true, compose: true, ops: false }`.\n */\n renderCaps?: Record<string, Omit<RenderCaps, 'fp'>>;\n /** The page renders a moved (unified) component on the shared track: such\n * ids in `components` come back in `unified` instead of `assignments`,\n * with nothing recorded. Without it they are served the frozen result. */\n unifiedCaps?: boolean;\n },\n sessionId: string,\n config: ServerAssignConfig,\n): Promise<DecideResult> {\n const timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n const declaredSlots = params.slots ?? [];\n let registryIds: string[] | null = null;\n if (params.slotsFrom === 'registry') {\n if (Array.isArray(params.registrySlotIds)) {\n registryIds = params.registrySlotIds;\n } else {\n console.error(\n \"[SentientUI] preloadDecisions: slotsFrom: 'registry' needs registrySlotIds (the <Adaptive id>s this page renders). \" +\n 'An unscoped registry decide records a trial for every published slot on every page; falling back to request mode.',\n );\n }\n }\n const fallback: DecideResult = {\n layoutOrder: params.sections ?? [],\n assignments: {},\n slots: baselineSlots(declaredSlots),\n persona: 'unknown',\n confidence: 0,\n };\n\n // Opted-out visitor (DNT/GPC): baseline layout/slots, mint no session (audit P4).\n if (config.doNotTrack) return fallback;\n\n const headers = ssrHeaders(config);\n\n const sessionBody = {\n ...buildSessionUpsertPayload(sessionId, {\n userAgent: config.userAgent,\n referer: config.referer,\n utmParams: config.utmParams,\n clickIds: config.clickIds,\n appOrigin: config.origin,\n landingPath: config.landingPath,\n }),\n ...(config.persona ? { persona: config.persona } : {}),\n };\n\n try {\n const sessionRes = await fetchWithTimeout(\n `${config.baseUrl}/sessions`,\n { method: 'POST', headers, body: JSON.stringify(sessionBody) },\n timeoutMs,\n );\n if (!sessionRes.ok) {\n const body = await sessionRes.json().catch(() => ({}));\n console.error(`[SentientUI] preloadDecisions: session upsert failed (${sessionRes.status})`, body);\n }\n } catch (err) {\n console.error('[SentientUI] preloadDecisions: session upsert threw', err);\n }\n\n try {\n const res = await fetchWithTimeout(\n `${config.baseUrl}/decide`,\n {\n method: 'POST',\n headers,\n body: JSON.stringify({\n sessionId,\n sections: (params.sections ?? []).map((id) => ({ id })),\n components: params.components,\n ...(declaredSlots.length > 0 ? { slots: declaredSlots.map(toWireSlot) } : {}),\n // bootstrap:false — editor goals and the section map are snippet\n // data the React SDK never reads. An EMPTY id list is meaningful\n // (\"nothing published is on this page\"): zero trials, still a decide.\n ...(registryIds !== null\n ? {\n slotsFrom: 'registry',\n registrySlotIds: registryIds,\n bootstrap: false,\n // Always sent, so the server knows this is an SDK that can\n // render Rewrite arms — no `render` field means legacy.\n render: Object.fromEntries(\n // compose: true — the React SDK (the SSR consumer) renders\n // Redesign trees since native generation phase 2.\n // ops: false — nothing here applies `ops`. Without it an\n // SSR'd <Adaptive id> matching a script-tag component was drawn\n // its ops-only version, rendered the original, and booked a trial.\n registryIds.map((id) => [id, params.renderCaps?.[id] ?? { forms: true, compose: true, ops: false }]),\n ),\n }\n : {}),\n ...(config.persona ? { persona: config.persona } : {}),\n ...(params.unifiedCaps ? { caps: { unified: true } } : {}),\n }),\n },\n timeoutMs,\n );\n if (!res.ok) {\n const body = await res.json().catch(() => ({}));\n console.error(`[SentientUI] preloadDecisions: decide failed (${res.status})`, body);\n return fallback;\n }\n const data = (await res.json()) as {\n layoutOrder?: string[];\n assignments?: Record<string, string>;\n slots?: Record<string, SlotResult>;\n slotConfig?: Record<string, SlotConfigEntry>;\n palette?: SitePalette;\n vocabulary?: import('./style-vocabulary.js').StyleVocabulary;\n persona?: string;\n confidence?: number;\n stage?: unknown;\n context?: unknown;\n unified?: unknown;\n };\n\n const slots: Record<string, SlotResult> = {};\n for (const d of declaredSlots) {\n // `data.slots === undefined` ⇒ server predates slots: baseline, no retry.\n slots[d.id] = data.slots?.[d.id] ?? baselineResultFor(d);\n }\n // Registry mode returns slots the request never declared — union them in\n // (same rule as the browser client), or an SSR page gets results for none\n // of its registry slots.\n for (const [slotId, result] of Object.entries(data.slots ?? {})) {\n if (!(slotId in slots)) slots[slotId] = result;\n }\n\n // Plain-object guard only (readSnapshot's rule): the server total-validated\n // the config at publish; a deep re-validation here would just drift.\n const slotConfigOk =\n data.slotConfig !== undefined && typeof data.slotConfig === 'object' && data.slotConfig !== null && !Array.isArray(data.slotConfig);\n\n return {\n layoutOrder: data.layoutOrder ?? params.sections ?? [],\n assignments: data.assignments ?? {},\n slots,\n persona: data.persona ?? 'unknown',\n confidence: data.confidence ?? 0,\n ...(slotConfigOk ? { slotConfig: data.slotConfig } : {}),\n ...(data.palette ? { palette: data.palette } : {}),\n ...(data.vocabulary ? { vocabulary: data.vocabulary } : {}),\n ...(typeof data.stage === 'string' ? { stage: data.stage } : {}),\n ...(typeof data.context === 'string' ? { context: data.context } : {}),\n ...(params.unifiedCaps && Array.isArray(data.unified)\n ? { unified: data.unified.filter((id): id is string => typeof id === 'string') }\n : {}),\n };\n } catch (err) {\n console.error('[SentientUI] preloadDecisions: decide threw', err);\n return fallback;\n }\n}\n\n/**\n * Fixed namespace for server-goal ids. It is public (it ships in this file), so\n * it adds no secrecy: the id's uniqueness comes from the session id it hashes\n * (see trackServerGoal). Never change it: a retried delivery must map to the\n * same goal id.\n */\nexport const SERVER_GOAL_NAMESPACE = '3d8f5a21-7c64-4b19-8e0a-5f2c91d7b6e3';\n\n/**\n * Pure-JS SHA-1 (FIPS 180-4) for runtimes without Web Crypto: Node 18 (our\n * engines floor is 18.18) has no unflagged `globalThis.crypto`, and without\n * this every server goal there would end 'failed'. @internal: exported for\n * the test vector only; not re-exported from the entry.\n */\nexport function sha1Fallback(data: Uint8Array): Uint8Array {\n const rotl = (x: number, n: number): number => (x << n) | (x >>> (32 - n));\n const len = data.length;\n const padded = new Uint8Array(((len + 8) >> 6) * 64 + 64);\n padded.set(data);\n padded[len] = 0x80;\n const view = new DataView(padded.buffer);\n view.setUint32(padded.length - 8, Math.floor((len * 8) / 0x100000000));\n view.setUint32(padded.length - 4, (len * 8) >>> 0);\n let h0 = 0x67452301, h1 = 0xefcdab89, h2 = 0x98badcfe, h3 = 0x10325476, h4 = 0xc3d2e1f0;\n const w = new Array<number>(80);\n for (let off = 0; off < padded.length; off += 64) {\n for (let i = 0; i < 16; i++) w[i] = view.getUint32(off + i * 4);\n for (let i = 16; i < 80; i++) w[i] = rotl(w[i - 3]! ^ w[i - 8]! ^ w[i - 14]! ^ w[i - 16]!, 1);\n let a = h0, b = h1, c = h2, d = h3, e = h4;\n for (let i = 0; i < 80; i++) {\n const [f, k] =\n i < 20 ? [(b & c) | (~b & d), 0x5a827999]\n : i < 40 ? [b ^ c ^ d, 0x6ed9eba1]\n : i < 60 ? [(b & c) | (b & d) | (c & d), 0x8f1bbcdc]\n : [b ^ c ^ d, 0xca62c1d6];\n const t = (rotl(a, 5) + f! + e + k! + w[i]!) | 0;\n e = d; d = c; c = rotl(b, 30); b = a; a = t;\n }\n h0 = (h0 + a) | 0; h1 = (h1 + b) | 0; h2 = (h2 + c) | 0; h3 = (h3 + d) | 0; h4 = (h4 + e) | 0;\n }\n const out = new Uint8Array(20);\n const ov = new DataView(out.buffer);\n [h0, h1, h2, h3, h4].forEach((v, i) => ov.setUint32(i * 4, v >>> 0));\n return out;\n}\n\n/**\n * RFC-4122 v5 UUID (SHA-1 over namespace bytes + name), via Web Crypto so this\n * file stays free of `node:` imports and `Buffer` (it also hosts the SSR\n * helpers, which run on Edge and Deno). @internal: exported for the test vector.\n */\nexport async function uuidV5(name: string, namespace: string): Promise<string> {\n const hex = namespace.replace(/-/g, '');\n const nsBytes = new Uint8Array(16);\n for (let i = 0; i < 16; i++) nsBytes[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);\n const nameBytes = new TextEncoder().encode(name);\n const input = new Uint8Array(16 + nameBytes.length);\n input.set(nsBytes, 0);\n input.set(nameBytes, 16);\n const subtle = globalThis.crypto?.subtle;\n const h = (subtle ? new Uint8Array(await subtle.digest('SHA-1', input)) : sha1Fallback(input)).slice(0, 16);\n h[6] = (h[6]! & 0x0f) | 0x50;\n h[8] = (h[8]! & 0x3f) | 0x80;\n const x = Array.from(h, (b) => b.toString(16).padStart(2, '0')).join('');\n return `${x.slice(0, 8)}-${x.slice(8, 12)}-${x.slice(12, 16)}-${x.slice(16, 20)}-${x.slice(20, 32)}`;\n}\n\nconst DEFAULT_GOAL_API_BASE = 'https://api.sentient-ui.com/v1';\nconst DEFAULT_GOAL_TIMEOUT_MS = 5000;\n\nexport type TrackServerGoalOptions = {\n /** Project SECRET key (sk_...), from a server-only env var. */\n serverKey: string;\n /** The visitor's session id: `readSessionCookie(cookies, apiKey)` in the same\n * request, or the id you stored from `client.getVisitorId()`. Null/empty\n * means nobody to credit: nothing is sent. */\n sessionId: string | null | undefined;\n /** Goal name, as defined in your project (e.g. 'purchase'). */\n name: string;\n /** Your own id for this conversion (order id, Stripe event id, user id).\n * Calling again with the same session + name + dedupeKey counts once. */\n dedupeKey: string;\n value?: number;\n currency?: string;\n metadata?: Record<string, unknown>;\n /** API base including `/v1`. Defaults to the hosted API. */\n apiBaseUrl?: string;\n fetch?: typeof fetch;\n /** Give up after this many ms. Default 5000. */\n timeoutMs?: number;\n};\n\n/**\n * Records a conversion from your server (route handler, server action,\n * webhook). Never throws; resolves 'recorded', 'skipped_no_visitor' (no\n * session to credit, nothing sent) or 'failed'.\n *\n * Hand-rolling this (cookie, deterministic id, sk_ call) was the only way to\n * count a webhook-confirmed conversion, and few customers would get the dedupe\n * right: a random goal id per attempt counts a retried webhook twice. The id\n * here is derived from session + name + dedupeKey, so replays collapse\n * server-side; dedupeKey is also sent as externalId, which the API dedupes per\n * (project, goal name) on its own.\n */\nexport async function trackServerGoal(\n opts: TrackServerGoalOptions,\n): Promise<'recorded' | 'skipped_no_visitor' | 'failed'> {\n // A secret key must never leave a browser (same rule as ssrHeaders).\n if (typeof window !== 'undefined') {\n console.error('[SentientUI] trackServerGoal is server-only: the secret key was not sent. Call it from a route handler, server action or webhook.');\n return 'failed';\n }\n if (!opts.sessionId) return 'skipped_no_visitor';\n // The id is derived from `${sessionId}:${name}:${dedupeKey}`, so a ':' in the\n // name would let ('a:b','c') and ('a','b:c') collide on one goal id and\n // silently merge two different conversions. Goal names never need one;\n // refuse it.\n if (opts.name.includes(':')) {\n console.error('[SentientUI] trackServerGoal: goal names cannot contain \":\" (nothing was sent).');\n return 'failed';\n }\n const doFetch = opts.fetch ?? fetch;\n const controller = new AbortController();\n let timer: ReturnType<typeof setTimeout> | undefined;\n try {\n const timedOut = new Promise<never>((_, reject) => {\n timer = setTimeout(() => {\n controller.abort();\n reject(new Error('timeout'));\n }, opts.timeoutMs ?? DEFAULT_GOAL_TIMEOUT_MS);\n });\n // Started before the (async) id hash so the budget covers the whole call;\n // the no-op catch keeps an early expiry from being an unhandled rejection.\n timedOut.catch(() => undefined);\n // The session id is part of the hash because goal_events.goal_id is\n // UNIQUE across ALL projects (migration 060) and the insert is a bare ON\n // CONFLICT DO NOTHING: hashed from name + dedupeKey alone, two tenants that\n // both send ('purchase', order #1001) derived the same id, and the second\n // tenant's conversion was silently dropped while this call still returned\n // 'recorded'; anyone with a pk_ could also pre-burn a guessable order id.\n // The session id is an unguessable per-project visitor key, so the id is\n // now unique per tenant. Retry dedupe does not depend on it alone: the\n // dedupeKey also rides as externalId (unique per project + goal name).\n const goalId = await uuidV5(`${opts.sessionId}:${opts.name}:${opts.dedupeKey}`, SERVER_GOAL_NAMESPACE);\n // Raced as well as aborted: a fetch that ignores its signal must still\n // not hold the caller (a webhook handler) past the timeout.\n const res = await Promise.race([\n doFetch(`${(opts.apiBaseUrl ?? DEFAULT_GOAL_API_BASE).replace(/\\/+$/, '')}/goals`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${opts.serverKey}` },\n body: JSON.stringify({\n sessionId: opts.sessionId,\n name: opts.name,\n goalId,\n externalId: opts.dedupeKey,\n ...(opts.value !== undefined ? { value: opts.value } : {}),\n ...(opts.currency !== undefined ? { currency: opts.currency } : {}),\n ...(opts.metadata !== undefined ? { metadata: opts.metadata } : {}),\n }),\n signal: controller.signal,\n }),\n timedOut,\n ]);\n return res.ok ? 'recorded' : 'failed';\n } catch {\n return 'failed';\n } finally {\n if (timer) clearTimeout(timer);\n }\n}\n","// Server-side capture of AI-assistant fetches, for any framework.\n// Spec: docs/superpowers/specs/2026-09-23-server-side-agent-capture-design.md §4.1\n//\n// Assistants that fetch a page without running JavaScript (ChatGPT-User,\n// Claude-User, Perplexity-User, GPTBot, …) never execute the snippet or the\n// React SDK, so only the server that answered can see them. Until this, only\n// Next.js AdaptiveRoot logged them; every other site read \"no AI traffic\",\n// which is wrong rather than empty.\n//\n// OBSERVATION ONLY. Nothing here may change a response based on the user\n// agent: that is cloaking, and SentientUI never claims to adapt serving to\n// agents. These functions return nothing a caller could branch on except\n// \"did this look like an agent\", and log to crawler_requests — never to\n// sessions, never to training, never to billing.\n\nimport { matchedAgentToken } from './session-meta.js';\n\nconst DEFAULT_API_BASE_URL = 'https://api.sentient-ui.com/v1';\n\nexport type AgentCaptureOptions = {\n /** Your public `pk_` key — the same one the snippet uses. */\n apiKey: string;\n /** API base ending in `/v1`. Defaults to the hosted API. */\n baseUrl?: string;\n /** Which capture path saw the fetch. Shown per row on the dashboard. */\n source?: 'middleware' | 'edge' | 'ssr';\n /**\n * REQUIRED on edge runtimes (Vercel Routing Middleware, Cloudflare Workers,\n * Netlify Edge): they cancel outstanding work once the response is\n * returned, so a fire-and-forget request without it is silently dropped.\n * Pass the platform's `waitUntil` (`ctx.waitUntil.bind(ctx)` on Workers,\n * `waitUntil` from `@vercel/functions`). Node servers do not need it.\n */\n waitUntil?: (p: Promise<unknown>) => void;\n /** Injectable for tests. */\n fetchImpl?: typeof fetch;\n};\n\n/** The minimum of a request both the Fetch API `Request` and hand-rolled\n * objects satisfy. */\nexport type CapturableRequest = {\n url: string;\n headers: { get(name: string): string | null };\n};\n\n/** Pathname only: a query string can carry tokens, emails or campaign ids. */\nfunction pathOf(url: string): string {\n try {\n return new URL(url, 'http://localhost').pathname || '/';\n } catch {\n return url.split(/[?#]/, 1)[0] || '/';\n }\n}\n\n/**\n * Low-level sender: posts one agent fetch to `/v1/crawler-events`. Never\n * throws, never blocks. The API re-derives the agent from `userAgent`\n * itself, so `botName` is advisory.\n */\nexport function postAgentFetch(\n entry: { path: string; userAgent: string; botName: string },\n opts: AgentCaptureOptions,\n): void {\n const doFetch = opts.fetchImpl ?? (typeof fetch === 'function' ? fetch : undefined);\n if (!doFetch || !opts.apiKey) return;\n try {\n const p = doFetch(`${opts.baseUrl ?? DEFAULT_API_BASE_URL}/crawler-events`, {\n method: 'POST',\n headers: { 'content-type': 'application/json', authorization: `Bearer ${opts.apiKey}` },\n body: JSON.stringify({\n path: entry.path,\n botName: entry.botName,\n userAgent: entry.userAgent,\n source: opts.source ?? 'middleware',\n }),\n }).catch(() => undefined);\n opts.waitUntil?.(p);\n } catch {\n /* capture must never break the page it is observing */\n }\n}\n\n/**\n * Log this request if its user agent is a known AI assistant or crawler.\n * Works with a Fetch API `Request` (edge runtimes, Hono, Remix / React\n * Router, Astro, SvelteKit) or anything with `url` + `headers.get`.\n *\n * Returns whether the request matched, so a caller can skip its own work;\n * it must NOT be used to serve anything different. Non-matching requests —\n * nearly all of them — make no network call.\n */\nexport function captureAgentRequest(req: CapturableRequest, opts: AgentCaptureOptions): boolean {\n let userAgent = '';\n try {\n userAgent = req.headers.get('user-agent') ?? '';\n } catch {\n return false;\n }\n const botName = matchedAgentToken(userAgent);\n if (!botName) return false;\n postAgentFetch({ path: pathOf(req.url), userAgent, botName }, opts);\n return true;\n}\n\ntype ConnectRequest = {\n url?: string;\n originalUrl?: string;\n headers: Record<string, string | string[] | undefined>;\n};\n\n/**\n * Connect-style middleware (Express, Nitro / Nuxt on Node, Fastify via\n * middie, any `(req, res, next)` stack). Calls `next()` synchronously and\n * logs in the background; it never touches the response.\n */\nexport function sentientAgentMiddleware(\n opts: Omit<AgentCaptureOptions, 'waitUntil' | 'source'>,\n): (req: ConnectRequest, res: unknown, next: (err?: unknown) => void) => void {\n return (req, _res, next) => {\n try {\n const raw = req.headers['user-agent'];\n const ua = Array.isArray(raw) ? raw[0] ?? '' : raw ?? '';\n captureAgentRequest(\n { url: req.originalUrl ?? req.url ?? '/', headers: { get: (n) => (n.toLowerCase() === 'user-agent' ? ua : null) } },\n { ...opts, source: 'middleware' },\n );\n } catch {\n /* never block the request */\n }\n next();\n };\n}\n"],"mappings":"sNA0FO,IAAMA,EAAoB,wBAGjC,SAASC,EAAWC,EAAoD,CACtE,IAAMC,EAAkC,CACtC,eAAgB,mBAChB,cAAe,UAAUD,EAAO,MAAM,EACxC,EACA,OAAIA,EAAO,SAAQC,EAAQ,OAASD,EAAO,QAGvCA,EAAO,WAAa,OAAO,QAAW,cAAaC,EAAQH,CAAiB,EAAIE,EAAO,WACpFC,CACT,CAWA,IAAMC,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,EACAb,EAC4B,CAC5B,OAAQ,MAAMc,EAA2BF,EAAYC,EAAWb,CAAM,GAAG,WAC3E,CAUA,eAAsBc,EACpBF,EACAC,EACAb,EACAe,EACoC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,EAAI,cAAJ,KAAAN,EAAmBM,EAAI,MAAvB,KAAAL,EAA8B,IAAK,QAAS,CAAE,IAAMc,GAAOA,EAAE,YAAY,IAAM,aAAeD,EAAK,IAAM,CAAE,EAClHE,EAAAC,EAAA,GAAKnB,GAAL,CAAW,OAAQ,YAAa,EAClC,CACF,OAAQH,EAAA,CAER,CACAiB,EAAK,CACP,CACF","names":["SERVER_KEY_HEADER","ssrHeaders","config","headers","DEFAULT_TIMEOUT_MS","fetchWithTimeout","url","init","timeoutMs","controller","timer","__spreadProps","__spreadValues","preloadAssignments","components","sessionId","preloadAssignmentsDetailed","opts","_a","sessionBody","buildSessionUpsertPayload","res","body","err","results","id","variantIds","assignments","unified","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","SERVER_GOAL_NAMESPACE","sha1Fallback","rotl","x","n","len","padded","view","h0","h1","h2","h3","h4","w","off","i","a","b","c","e","f","k","t","out","ov","v","uuidV5","name","namespace","hex","nsBytes","nameBytes","input","subtle","h","DEFAULT_GOAL_API_BASE","DEFAULT_GOAL_TIMEOUT_MS","trackServerGoal","doFetch","timedOut","_","reject","goalId","DEFAULT_API_BASE_URL","pathOf","url","e","postAgentFetch","entry","opts","_a","_b","_c","_d","doFetch","p","captureAgentRequest","req","userAgent","botName","matchedAgentToken","sentientAgentMiddleware","_res","next","raw","ua","n","__spreadProps","__spreadValues"]}
|
|
1
|
+
{"version":3,"sources":["../src/server.ts","../src/agent-capture.ts"],"sourcesContent":["/**\n * Server-side helpers for SSR variant pre-loading.\n * Pure fetch — no DOM APIs. Safe in Node.js, Edge, and Deno runtimes.\n */\nimport { buildSessionUpsertPayload } from './session-meta.js';\nimport { LEGACY_SESSION_COOKIE_NAME, sessionCookieName } from './storage-key.js';\nimport {\n toWireSlot,\n baselineResultFor,\n baselineSlots,\n type SlotDeclInput,\n type SlotResult,\n} from './slots.js';\n\nimport type { SlotConfigEntry } from './snapshot.js';\nimport type { RenderCaps } from './region-skeleton.js';\nimport type { SitePalette } from './blocks.js';\n\nexport type { SlotDeclInput, SlotResult, SlotConfigEntry, SitePalette };\n\nexport type ServerAssignConfig = {\n /** Public API key (pk_...). */\n apiKey: string;\n /**\n * Base URL of the Sentient API without trailing slash.\n * e.g. 'https://api.yourapp.com/v1'\n */\n baseUrl: string;\n /**\n * Browser origin of your app (e.g. `http://localhost:3001`). Required for `pk_`\n * keys — server-side fetch must send the same `Origin` the API allows.\n */\n origin?: string;\n /**\n * Optional: this project's SECRET key (sk_...), read from a server-only env\n * var. When set, SSR calls also send it as `X-Sentient-Server-Key`, which\n * proves they come from your server: the API then holds them to your plan's\n * per-key limit instead of the 100 requests/min per-IP cap meant for\n * browsers — without it, all SSR traffic from one server address shares that\n * one cap. Never set this in code that ships to the browser; it is ignored\n * (and not sent) when `window` exists.\n */\n serverKey?: string;\n /** From `User-Agent` request header (Next.js `headers()`). */\n userAgent?: string;\n /** From `Referer` request header. */\n referer?: string;\n utmParams?: Record<string, string>;\n /**\n * Ad-platform click IDs (gclid, fbclid, ttclid, …) from the landing URL.\n * Derive both this and `utmParams` with `extractTrackedParams(searchParams)`\n * — the Referer header never carries the landing page's own query string, so\n * without these two fields SSR-minted sessions have no campaign attribution\n * until the client SDK hydrates.\n */\n clickIds?: Record<string, string>;\n /**\n * The landing page's path (no query string). With it the server can tell a\n * paid click to a product page, or a Shopify `/discount/CODE` link, from any\n * other arrival on the FIRST decision of the visit.\n */\n landingPath?: string;\n /**\n * Set true when the request carries a tracking opt-out — `DNT: 1` or\n * `Sec-GPC: 1`. When set, the SSR helpers skip the session upsert and the\n * assign/decide call entirely: the page renders defaults/baseline and no\n * session row is minted for the visitor (audit P4). The client SDK already\n * no-ops for these visitors; this keeps the server from minting a session +\n * assignment on every page view before the client can.\n */\n doNotTrack?: boolean;\n /**\n * Declared persona — the role your app already knows for this visitor\n * (e.g. from your auth context during SSR). Same contract as the client\n * option: must be a vocabulary key; unrecognized values are ignored\n * server-side. Never a user id or email.\n */\n persona?: string;\n /**\n * Milliseconds to wait for the API before returning default variants.\n * Prevents slow/cold API from blocking SSR. Defaults to 1000 — the hot path\n * is served from in-process caches and typically returns in well under\n * 150 ms. The full 1 s budget is only reached on a cold start or an API\n * geographically distant from your SSR host, after which defaults render\n * with no layout shift. Lower it if your API is co-located and warm.\n */\n timeoutMs?: number;\n};\n\n/** Header carrying `serverKey` (apps/api lib/rate-limit.ts SERVER_KEY_HEADER). */\nexport const SERVER_KEY_HEADER = 'X-Sentient-Server-Key';\n\n/** Auth headers for an SSR call: the pk_, its Origin, and the optional server proof. */\nfunction ssrHeaders(config: ServerAssignConfig): Record<string, string> {\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${config.apiKey}`,\n };\n if (config.origin) headers.Origin = config.origin;\n // A secret key must never leave a browser: if this module was bundled\n // client-side by mistake, drop it rather than send it.\n if (config.serverKey && typeof window === 'undefined') headers[SERVER_KEY_HEADER] = config.serverKey;\n return headers;\n}\n\n/** componentId → assigned variantId */\nexport type ServerAssignments = Record<string, string>;\n\ntype AssignResult = { variantId: string; assignmentTtlMs: number; unified?: true };\n\n/** `preloadAssignmentsDetailed`'s answer: the assignments, plus the ids the\n * server handed back as moved to the shared track (only when asked). */\nexport type ServerAssignmentsDetailed = { assignments: ServerAssignments; unified: string[] };\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 return (await preloadAssignmentsDetailed(components, sessionId, config)).assignments;\n}\n\n/**\n * `preloadAssignments`, and also which components were moved onto the shared\n * track. With `opts.unified` each assign says the page can follow such a move:\n * a moved id is then not assigned (nothing is recorded for it) and comes back\n * in `unified`, for the page to render as a slot. Pass those ids to\n * `<AdaptiveProvider initialUnified>`. Without it a moved id is served its\n * frozen result read-only, as for any older SDK.\n */\nexport async function preloadAssignmentsDetailed(\n components: Array<{ id: string; variantIds: string[] }>,\n sessionId: string,\n config: ServerAssignConfig,\n opts?: { unified?: boolean },\n): Promise<ServerAssignmentsDetailed> {\n // Opted-out visitor (DNT/GPC): render defaults, mint no session (audit P4).\n if (config.doNotTrack) return { assignments: {}, unified: [] };\n\n const timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n const headers = ssrHeaders(config);\n\n // Session metadata must match the browser SDK so assign seeds variant_weights\n // under the same segment (not `unknown:unknown`).\n const sessionBody = {\n ...buildSessionUpsertPayload(sessionId, {\n userAgent: config.userAgent,\n referer: config.referer,\n utmParams: config.utmParams,\n clickIds: config.clickIds,\n appOrigin: config.origin,\n landingPath: config.landingPath,\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 {\n method: 'POST',\n headers,\n body: JSON.stringify({ sessionId, componentId: id, variantIds, ...(opts?.unified ? { caps: { unified: true } } : {}) }),\n },\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, unified: opts?.unified === true && body.unified === true };\n }),\n );\n\n const assignments: ServerAssignments = {};\n const unified: string[] = [];\n for (const result of results) {\n if (result.status === 'fulfilled' && result.value) {\n // A moved id's variantId is only its declared baseline, not an\n // assignment: seeding it would settle the page on the frozen run.\n if (result.value.unified) unified.push(result.value.id);\n else assignments[result.value.id] = result.value.variantId;\n }\n }\n return { assignments, unified };\n}\n\n/**\n * Reads the Sentient session cookie from a Next.js `ReadonlyRequestCookies` object\n * (the return value of `cookies()` from `next/headers`), or any object with a\n * `get(name: string)` method. Returns null if the cookie is absent.\n *\n * Pass the project's `apiKey`: the client writes the per-project SUFFIXED name\n * (`sessionCookieName` — see storage-key.ts), so reading only the bare\n * `_snt_uid` missed the cookie on every SSR request for a returning visitor and\n * minted a fresh orphan session each page view (quota inflation, broken sticky\n * assignments and persona continuity). The bare name is still read as a\n * fallback for identities minted before namespacing.\n */\nexport function readSessionCookie(\n cookies: { get(name: string): { value: string } | undefined },\n apiKey?: string,\n): string | null {\n return (\n (apiKey ? cookies.get(sessionCookieName(apiKey))?.value : undefined) ??\n cookies.get(LEGACY_SESSION_COOKIE_NAME)?.value ??\n null\n );\n}\n\nexport type DecideResult = {\n layoutOrder: string[];\n assignments: Record<string, string>;\n /** Slot results keyed by slot id. Baseline-resolved when the API omits/fails them. */\n slots: Record<string, SlotResult>;\n persona: string;\n confidence: number;\n /** Registry mode only: content/ops/blocks for server-defined slots. */\n slotConfig?: Record<string, SlotConfigEntry>;\n /** Registry mode only: site palette for block rendering. */\n palette?: SitePalette;\n /** Registry mode only: site styles the served Redesign arms borrow. */\n vocabulary?: import('./style-vocabulary.js').StyleVocabulary;\n /** The visit's funnel stage, raw — projects with stages on, treated visitors\n * only. Pass it through `exposedStage` before it reaches the page. */\n stage?: string;\n /** The visit's serving context. Never for the page. */\n context?: string;\n /** Requested components moved onto the shared track (only with\n * `unifiedCaps`): not in `assignments`; render each as a slot. */\n unified?: string[];\n};\n\n/**\n * Single-roundtrip SSR call returning layout order, component assignments,\n * and adaptive-slot results. Falls back to default section order + empty\n * assignments + baseline slots if the API is unavailable. A response without\n * a `slots` field means the server predates slots — every declared slot\n * resolves to its baseline (no retry).\n */\nexport async function preloadDecisions(\n params: {\n sections?: string[];\n components: Array<{ id: string; variantIds?: string[] }>;\n slots?: SlotDeclInput[];\n /** 'registry' serves the project's published slot_definitions as if declared\n * (and is the only way slotConfig/palette come back). Default 'request'.\n * Requires `registrySlotIds`: the `<Adaptive id>`s THIS page renders. */\n slotsFrom?: 'request' | 'registry';\n /**\n * Registry mode: decide only these published slot ids. Close-out turns\n * every slot decision into a trial without checking an exposure, so an\n * unscoped registry decide accrues trials — and session-level credit — for\n * every published slot on every page, including ones this page never\n * renders (CONTRACTS §2). Omitting it in registry mode is refused: the\n * call downgrades to request mode with one console.error, rather than\n * silently minting those trials.\n */\n registrySlotIds?: string[];\n /**\n * Registry mode: what each slot on this page can render (CONTRACTS §2).\n * The server has no DOM here, so no fingerprint is sent and a Rewrite arm\n * is assumed to match; a real mismatch is reported from the browser as\n * drift. Declare `forms: false` for slots without an `onFormSubmit`, or a\n * form arm can be drawn that this page will refuse. Default per slot:\n * `{ forms: true, compose: true, ops: false }`.\n */\n renderCaps?: Record<string, Omit<RenderCaps, 'fp'>>;\n /** The page renders a moved (unified) component on the shared track: such\n * ids in `components` come back in `unified` instead of `assignments`,\n * with nothing recorded. Without it they are served the frozen result. */\n unifiedCaps?: boolean;\n },\n sessionId: string,\n config: ServerAssignConfig,\n): Promise<DecideResult> {\n const timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n const declaredSlots = params.slots ?? [];\n let registryIds: string[] | null = null;\n if (params.slotsFrom === 'registry') {\n if (Array.isArray(params.registrySlotIds)) {\n registryIds = params.registrySlotIds;\n } else {\n console.error(\n \"[SentientUI] preloadDecisions: slotsFrom: 'registry' needs registrySlotIds (the <Adaptive id>s this page renders). \" +\n 'An unscoped registry decide records a trial for every published slot on every page; falling back to request mode.',\n );\n }\n }\n const fallback: DecideResult = {\n layoutOrder: params.sections ?? [],\n assignments: {},\n slots: baselineSlots(declaredSlots),\n persona: 'unknown',\n confidence: 0,\n };\n\n // Opted-out visitor (DNT/GPC): baseline layout/slots, mint no session (audit P4).\n if (config.doNotTrack) return fallback;\n\n const headers = ssrHeaders(config);\n\n const sessionBody = {\n ...buildSessionUpsertPayload(sessionId, {\n userAgent: config.userAgent,\n referer: config.referer,\n utmParams: config.utmParams,\n clickIds: config.clickIds,\n appOrigin: config.origin,\n landingPath: config.landingPath,\n }),\n ...(config.persona ? { persona: config.persona } : {}),\n };\n\n try {\n const sessionRes = await fetchWithTimeout(\n `${config.baseUrl}/sessions`,\n { method: 'POST', headers, body: JSON.stringify(sessionBody) },\n timeoutMs,\n );\n if (!sessionRes.ok) {\n const body = await sessionRes.json().catch(() => ({}));\n console.error(`[SentientUI] preloadDecisions: session upsert failed (${sessionRes.status})`, body);\n }\n } catch (err) {\n console.error('[SentientUI] preloadDecisions: session upsert threw', err);\n }\n\n try {\n const res = await fetchWithTimeout(\n `${config.baseUrl}/decide`,\n {\n method: 'POST',\n headers,\n body: JSON.stringify({\n sessionId,\n sections: (params.sections ?? []).map((id) => ({ id })),\n components: params.components,\n ...(declaredSlots.length > 0 ? { slots: declaredSlots.map(toWireSlot) } : {}),\n // bootstrap:false — editor goals and the section map are snippet\n // data the React SDK never reads. An EMPTY id list is meaningful\n // (\"nothing published is on this page\"): zero trials, still a decide.\n ...(registryIds !== null\n ? {\n slotsFrom: 'registry',\n registrySlotIds: registryIds,\n bootstrap: false,\n // Always sent, so the server knows this is an SDK that can\n // render Rewrite arms — no `render` field means legacy.\n render: Object.fromEntries(\n // compose: true — the React SDK (the SSR consumer) renders\n // Redesign trees since native generation phase 2.\n // ops: false — nothing here applies `ops`. Without it an\n // SSR'd <Adaptive id> matching a script-tag component was drawn\n // its ops-only version, rendered the original, and booked a trial.\n registryIds.map((id) => [id, params.renderCaps?.[id] ?? { forms: true, compose: true, ops: false }]),\n ),\n }\n : {}),\n ...(config.persona ? { persona: config.persona } : {}),\n ...(params.unifiedCaps ? { caps: { unified: true } } : {}),\n }),\n },\n timeoutMs,\n );\n if (!res.ok) {\n const body = await res.json().catch(() => ({}));\n console.error(`[SentientUI] preloadDecisions: decide failed (${res.status})`, body);\n return fallback;\n }\n const data = (await res.json()) as {\n layoutOrder?: string[];\n assignments?: Record<string, string>;\n slots?: Record<string, SlotResult>;\n slotConfig?: Record<string, SlotConfigEntry>;\n palette?: SitePalette;\n vocabulary?: import('./style-vocabulary.js').StyleVocabulary;\n persona?: string;\n confidence?: number;\n stage?: unknown;\n context?: unknown;\n unified?: unknown;\n };\n\n const slots: Record<string, SlotResult> = {};\n for (const d of declaredSlots) {\n // `data.slots === undefined` ⇒ server predates slots: baseline, no retry.\n slots[d.id] = data.slots?.[d.id] ?? baselineResultFor(d);\n }\n // Registry mode returns slots the request never declared — union them in\n // (same rule as the browser client), or an SSR page gets results for none\n // of its registry slots.\n for (const [slotId, result] of Object.entries(data.slots ?? {})) {\n if (!(slotId in slots)) slots[slotId] = result;\n }\n\n // Plain-object guard only (readSnapshot's rule): the server total-validated\n // the config at publish; a deep re-validation here would just drift.\n const slotConfigOk =\n data.slotConfig !== undefined && typeof data.slotConfig === 'object' && data.slotConfig !== null && !Array.isArray(data.slotConfig);\n\n return {\n layoutOrder: data.layoutOrder ?? params.sections ?? [],\n assignments: data.assignments ?? {},\n slots,\n persona: data.persona ?? 'unknown',\n confidence: data.confidence ?? 0,\n ...(slotConfigOk ? { slotConfig: data.slotConfig } : {}),\n ...(data.palette ? { palette: data.palette } : {}),\n ...(data.vocabulary ? { vocabulary: data.vocabulary } : {}),\n ...(typeof data.stage === 'string' ? { stage: data.stage } : {}),\n ...(typeof data.context === 'string' ? { context: data.context } : {}),\n ...(params.unifiedCaps && Array.isArray(data.unified)\n ? { unified: data.unified.filter((id): id is string => typeof id === 'string') }\n : {}),\n };\n } catch (err) {\n console.error('[SentientUI] preloadDecisions: decide threw', err);\n return fallback;\n }\n}\n\n/**\n * Fixed namespace for server-goal ids. It is public (it ships in this file), so\n * it adds no secrecy: the id's uniqueness comes from the session id it hashes\n * (see trackServerGoal). Never change it: a retried delivery must map to the\n * same goal id.\n */\nexport const SERVER_GOAL_NAMESPACE = '3d8f5a21-7c64-4b19-8e0a-5f2c91d7b6e3';\n\n/**\n * Pure-JS SHA-1 (FIPS 180-4) for runtimes without Web Crypto: Node 18 (our\n * engines floor is 18.18) has no unflagged `globalThis.crypto`, and without\n * this every server goal there would end 'failed'. @internal: exported for\n * the test vector only; not re-exported from the entry.\n */\nexport function sha1Fallback(data: Uint8Array): Uint8Array {\n const rotl = (x: number, n: number): number => (x << n) | (x >>> (32 - n));\n const len = data.length;\n const padded = new Uint8Array(((len + 8) >> 6) * 64 + 64);\n padded.set(data);\n padded[len] = 0x80;\n const view = new DataView(padded.buffer);\n view.setUint32(padded.length - 8, Math.floor((len * 8) / 0x100000000));\n view.setUint32(padded.length - 4, (len * 8) >>> 0);\n let h0 = 0x67452301, h1 = 0xefcdab89, h2 = 0x98badcfe, h3 = 0x10325476, h4 = 0xc3d2e1f0;\n const w = new Array<number>(80);\n for (let off = 0; off < padded.length; off += 64) {\n for (let i = 0; i < 16; i++) w[i] = view.getUint32(off + i * 4);\n for (let i = 16; i < 80; i++) w[i] = rotl(w[i - 3]! ^ w[i - 8]! ^ w[i - 14]! ^ w[i - 16]!, 1);\n let a = h0, b = h1, c = h2, d = h3, e = h4;\n for (let i = 0; i < 80; i++) {\n const [f, k] =\n i < 20 ? [(b & c) | (~b & d), 0x5a827999]\n : i < 40 ? [b ^ c ^ d, 0x6ed9eba1]\n : i < 60 ? [(b & c) | (b & d) | (c & d), 0x8f1bbcdc]\n : [b ^ c ^ d, 0xca62c1d6];\n const t = (rotl(a, 5) + f! + e + k! + w[i]!) | 0;\n e = d; d = c; c = rotl(b, 30); b = a; a = t;\n }\n h0 = (h0 + a) | 0; h1 = (h1 + b) | 0; h2 = (h2 + c) | 0; h3 = (h3 + d) | 0; h4 = (h4 + e) | 0;\n }\n const out = new Uint8Array(20);\n const ov = new DataView(out.buffer);\n [h0, h1, h2, h3, h4].forEach((v, i) => ov.setUint32(i * 4, v >>> 0));\n return out;\n}\n\n/**\n * RFC-4122 v5 UUID (SHA-1 over namespace bytes + name), via Web Crypto so this\n * file stays free of `node:` imports and `Buffer` (it also hosts the SSR\n * helpers, which run on Edge and Deno). @internal: exported for the test vector.\n */\nexport async function uuidV5(name: string, namespace: string): Promise<string> {\n const hex = namespace.replace(/-/g, '');\n const nsBytes = new Uint8Array(16);\n for (let i = 0; i < 16; i++) nsBytes[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);\n const nameBytes = new TextEncoder().encode(name);\n const input = new Uint8Array(16 + nameBytes.length);\n input.set(nsBytes, 0);\n input.set(nameBytes, 16);\n const subtle = globalThis.crypto?.subtle;\n const h = (subtle ? new Uint8Array(await subtle.digest('SHA-1', input)) : sha1Fallback(input)).slice(0, 16);\n h[6] = (h[6]! & 0x0f) | 0x50;\n h[8] = (h[8]! & 0x3f) | 0x80;\n const x = Array.from(h, (b) => b.toString(16).padStart(2, '0')).join('');\n return `${x.slice(0, 8)}-${x.slice(8, 12)}-${x.slice(12, 16)}-${x.slice(16, 20)}-${x.slice(20, 32)}`;\n}\n\n// Pure-JS SHA-256 for the same Node-18 gap sha1Fallback covers (no global\n// Web Crypto there, and this file takes no `node:` imports). @internal.\nconst K256 = new Uint32Array([\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,\n]);\nexport function sha256Fallback(data: Uint8Array): Uint8Array {\n const bitLen = data.length * 8;\n const padded = new Uint8Array(Math.ceil((data.length + 9) / 64) * 64);\n padded.set(data);\n padded[data.length] = 0x80;\n const pv = new DataView(padded.buffer);\n pv.setUint32(padded.length - 8, Math.floor(bitLen / 0x100000000));\n pv.setUint32(padded.length - 4, bitLen >>> 0);\n const h = new Uint32Array([0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19]);\n const w = new Uint32Array(64);\n const rotr = (x: number, n: number): number => (x >>> n) | (x << (32 - n));\n for (let off = 0; off < padded.length; off += 64) {\n for (let i = 0; i < 16; i++) w[i] = pv.getUint32(off + i * 4);\n for (let i = 16; i < 64; i++) {\n const s0 = rotr(w[i - 15]!, 7) ^ rotr(w[i - 15]!, 18) ^ (w[i - 15]! >>> 3);\n const s1 = rotr(w[i - 2]!, 17) ^ rotr(w[i - 2]!, 19) ^ (w[i - 2]! >>> 10);\n w[i] = (w[i - 16]! + s0 + w[i - 7]! + s1) | 0;\n }\n let [a, b, c, d, e, f, g, hh] = [h[0]!, h[1]!, h[2]!, h[3]!, h[4]!, h[5]!, h[6]!, h[7]!];\n for (let i = 0; i < 64; i++) {\n const t1 = (hh + (rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25)) + ((e & f) ^ (~e & g)) + K256[i]! + w[i]!) | 0;\n const t2 = ((rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22)) + ((a & b) ^ (a & c) ^ (b & c))) | 0;\n hh = g; g = f; f = e; e = (d + t1) | 0; d = c; c = b; b = a; a = (t1 + t2) | 0;\n }\n h[0] = (h[0]! + a) | 0; h[1] = (h[1]! + b) | 0; h[2] = (h[2]! + c) | 0; h[3] = (h[3]! + d) | 0;\n h[4] = (h[4]! + e) | 0; h[5] = (h[5]! + f) | 0; h[6] = (h[6]! + g) | 0; h[7] = (h[7]! + hh) | 0;\n }\n const out = new Uint8Array(32);\n const ov = new DataView(out.buffer);\n h.forEach((v, i) => ov.setUint32(i * 4, v));\n return out;\n}\n\nfunction hmacSha256Fallback(key: Uint8Array, msg: Uint8Array): Uint8Array {\n const k = new Uint8Array(64);\n k.set(key.length > 64 ? sha256Fallback(key) : key);\n const inner = new Uint8Array(64 + msg.length);\n const outer = new Uint8Array(64 + 32);\n for (let i = 0; i < 64; i++) {\n inner[i] = k[i]! ^ 0x36;\n outer[i] = k[i]! ^ 0x5c;\n }\n inner.set(msg, 64);\n outer.set(sha256Fallback(inner), 64);\n return sha256Fallback(outer);\n}\n\n/** HMAC-SHA256 as hex — Web Crypto when present, else the pure-JS fallback. */\nasync function hmacSha256Hex(key: string, msg: string): Promise<string> {\n const enc = new TextEncoder();\n const k = enc.encode(key);\n const m = enc.encode(msg);\n const subtle = globalThis.crypto?.subtle;\n const mac = subtle\n ? new Uint8Array(await subtle.sign('HMAC', await subtle.importKey('raw', k, { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']), m))\n : hmacSha256Fallback(k, m);\n return Array.from(mac, (b) => b.toString(16).padStart(2, '0')).join('');\n}\n\n/**\n * Verified identify: the `userHash` for `identify(userId, { userHash })`.\n * Compute it on YOUR server (it needs the secret key) and hand it to the page\n * with the user id — `<AdaptiveRoot userId>` from `@sentientui/react/next`\n * does both for you. Once a project sends verified identifies, only verified\n * bindings receive server goals by `userId` and carry a user's portrait\n * across devices: an unsigned identify is any browser's claim.\n *\n * The secret is derived from the secret key, so there is nothing new to\n * configure: `HMAC(sk, 'sentient-identity-v1')`, then `v1.<exp>.` + HMAC(that,\n * `${userId}.${exp}`) — the API stores the same derivation per server key.\n * Valid for `ttlSeconds` (default 24 h, at most 7 days).\n */\nexport async function signUserId(\n userId: string,\n serverKey: string,\n opts?: { ttlSeconds?: number; now?: number },\n): Promise<string> {\n if (typeof window !== 'undefined') {\n console.error('[SentientUI] signUserId is server-only: it needs the secret key. Compute the hash on your server and pass it to identify().');\n return '';\n }\n // The expiry is signed in, so a hash read off a page stops verifying: sign\n // per render (AdaptiveRoot does), not once per user. The API refuses more\n // than 7 days.\n // Clamped to the API's 7-day maximum: a longer TTL would yield a hash that\n // is refused, i.e. an identify that silently stays unverified.\n const exp = Math.floor((opts?.now ?? Date.now()) / 1000) + Math.min(opts?.ttlSeconds ?? 86_400, 7 * 86_400);\n const secret = await hmacSha256Hex(serverKey, 'sentient-identity-v1');\n return `v1.${exp}.${await hmacSha256Hex(secret, `${userId}.${exp}`)}`;\n}\n\nconst DEFAULT_GOAL_API_BASE = 'https://api.sentient-ui.com/v1';\nconst DEFAULT_GOAL_TIMEOUT_MS = 5000;\n\nexport type TrackServerGoalOptions = {\n /** Project SECRET key (sk_...), from a server-only env var. */\n serverKey: string;\n /** The visitor's session id: `readSessionCookie(cookies, apiKey)` in the same\n * request, or the id you stored from `client.getVisitorId()`. Null/empty\n * means nobody to credit: nothing is sent. */\n sessionId?: string | null;\n /** Your own user id, as passed to `client.identify()` in the browser — use it\n * when the backend never sees our visitor id (a webhook, a job, a signup\n * handled on another host). The API credits that user's most recently seen\n * visit in the project; with no such visit nothing is recorded and this\n * resolves 'skipped_no_visitor'. Ignored when `sessionId` is given. */\n userId?: string | null;\n /** Goal name, as defined in your project (e.g. 'purchase'). */\n name: string;\n /** Your own id for this conversion (order id, Stripe event id, user id).\n * Calling again with the same session + name + dedupeKey counts once. */\n dedupeKey: string;\n value?: number;\n currency?: string;\n metadata?: Record<string, unknown>;\n /** API base including `/v1`. Defaults to the hosted API. */\n apiBaseUrl?: string;\n fetch?: typeof fetch;\n /** Give up after this many ms. Default 5000. */\n timeoutMs?: number;\n};\n\n/**\n * Records a conversion from your server (route handler, server action,\n * webhook). Never throws; resolves 'recorded', 'skipped_no_visitor' (no\n * session to credit, nothing sent) or 'failed'.\n *\n * Hand-rolling this (cookie, deterministic id, sk_ call) was the only way to\n * count a webhook-confirmed conversion, and few customers would get the dedupe\n * right: a random goal id per attempt counts a retried webhook twice. The id\n * here is derived from session + name + dedupeKey, so replays collapse\n * server-side; dedupeKey is also sent as externalId, which the API dedupes per\n * (project, goal name) on its own.\n */\nexport async function trackServerGoal(\n opts: TrackServerGoalOptions,\n): Promise<'recorded' | 'skipped_no_visitor' | 'failed'> {\n // A secret key must never leave a browser (same rule as ssrHeaders).\n if (typeof window !== 'undefined') {\n console.error('[SentientUI] trackServerGoal is server-only: the secret key was not sent. Call it from a route handler, server action or webhook.');\n return 'failed';\n }\n const userId = opts.sessionId ? null : (opts.userId || null);\n if (!opts.sessionId && !userId) return 'skipped_no_visitor';\n // The id is derived from `${sessionId}:${name}:${dedupeKey}`, so a ':' in the\n // name would let ('a:b','c') and ('a','b:c') collide on one goal id and\n // silently merge two different conversions. Goal names never need one;\n // refuse it.\n if (opts.name.includes(':')) {\n console.error('[SentientUI] trackServerGoal: goal names cannot contain \":\" (nothing was sent).');\n return 'failed';\n }\n const doFetch = opts.fetch ?? fetch;\n const controller = new AbortController();\n let timer: ReturnType<typeof setTimeout> | undefined;\n try {\n const timedOut = new Promise<never>((_, reject) => {\n timer = setTimeout(() => {\n controller.abort();\n reject(new Error('timeout'));\n }, opts.timeoutMs ?? DEFAULT_GOAL_TIMEOUT_MS);\n });\n // Started before the (async) id hash so the budget covers the whole call;\n // the no-op catch keeps an early expiry from being an unhandled rejection.\n timedOut.catch(() => undefined);\n // The session id is part of the hash because goal_events.goal_id is\n // UNIQUE across ALL projects (migration 060) and the insert is a bare ON\n // CONFLICT DO NOTHING: hashed from name + dedupeKey alone, two tenants that\n // both send ('purchase', order #1001) derived the same id, and the second\n // tenant's conversion was silently dropped while this call still returned\n // 'recorded'; anyone with a pk_ could also pre-burn a guessable order id.\n // The session id is an unguessable per-project visitor key, so the id is\n // now unique per tenant. Retry dedupe does not depend on it alone: the\n // dedupeKey also rides as externalId (unique per project + goal name).\n // A user id is NOT unguessable or unique across tenants (\"42\" exists in\n // every customer's database), so the userId path keys the hash on the\n // secret key too — per-project and never guessable, the property the\n // session id gave the hash above. Rotating the key changes the id; retry\n // dedupe still holds through externalId.\n const goalId = await uuidV5(\n userId === null\n ? `${opts.sessionId}:${opts.name}:${opts.dedupeKey}`\n : `user:${opts.serverKey}:${userId}:${opts.name}:${opts.dedupeKey}`,\n SERVER_GOAL_NAMESPACE,\n );\n // Raced as well as aborted: a fetch that ignores its signal must still\n // not hold the caller (a webhook handler) past the timeout.\n const res = await Promise.race([\n doFetch(`${(opts.apiBaseUrl ?? DEFAULT_GOAL_API_BASE).replace(/\\/+$/, '')}/goals`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${opts.serverKey}` },\n body: JSON.stringify({\n ...(userId === null ? { sessionId: opts.sessionId } : { userId }),\n name: opts.name,\n goalId,\n externalId: opts.dedupeKey,\n ...(opts.value !== undefined ? { value: opts.value } : {}),\n ...(opts.currency !== undefined ? { currency: opts.currency } : {}),\n ...(opts.metadata !== undefined ? { metadata: opts.metadata } : {}),\n }),\n signal: controller.signal,\n }),\n timedOut,\n ]);\n if (res.ok) return 'recorded';\n // 404 visitor_not_found: no visit carries that user id (never identified,\n // or erased) — nobody to credit, the same outcome as no sessionId.\n if (userId !== null && res.status === 404) {\n // The silent version of this was the whole debugging experience of a\n // missing identify: the call \"worked\" and no conversion ever appeared.\n if (process.env.NODE_ENV !== 'production') {\n console.warn(`[SentientUI] trackServerGoal: no visit is linked to userId \"${userId}\" yet, so \"${opts.name}\" was not recorded. Identify the visitor in the browser first (<AdaptiveRoot userId>, or identify(userId, { userHash })) — once a project signs its identifies, only signed visits count.`);\n }\n return 'skipped_no_visitor';\n }\n return 'failed';\n } catch {\n return 'failed';\n } finally {\n if (timer) clearTimeout(timer);\n }\n}\n","// Server-side capture of AI-assistant fetches, for any framework.\n// Spec: docs/superpowers/specs/2026-09-23-server-side-agent-capture-design.md §4.1\n//\n// Assistants that fetch a page without running JavaScript (ChatGPT-User,\n// Claude-User, Perplexity-User, GPTBot, …) never execute the snippet or the\n// React SDK, so only the server that answered can see them. Until this, only\n// Next.js AdaptiveRoot logged them; every other site read \"no AI traffic\",\n// which is wrong rather than empty.\n//\n// OBSERVATION ONLY. Nothing here may change a response based on the user\n// agent: that is cloaking, and SentientUI never claims to adapt serving to\n// agents. These functions return nothing a caller could branch on except\n// \"did this look like an agent\", and log to crawler_requests — never to\n// sessions, never to training, never to billing.\n\nimport { matchedAgentToken } from './session-meta.js';\n\nconst DEFAULT_API_BASE_URL = 'https://api.sentient-ui.com/v1';\n\nexport type AgentCaptureOptions = {\n /** Your public `pk_` key — the same one the snippet uses. */\n apiKey: string;\n /** API base ending in `/v1`. Defaults to the hosted API. */\n baseUrl?: string;\n /** Which capture path saw the fetch. Shown per row on the dashboard. */\n source?: 'middleware' | 'edge' | 'ssr';\n /**\n * REQUIRED on edge runtimes (Vercel Routing Middleware, Cloudflare Workers,\n * Netlify Edge): they cancel outstanding work once the response is\n * returned, so a fire-and-forget request without it is silently dropped.\n * Pass the platform's `waitUntil` (`ctx.waitUntil.bind(ctx)` on Workers,\n * `waitUntil` from `@vercel/functions`). Node servers do not need it.\n */\n waitUntil?: (p: Promise<unknown>) => void;\n /** Injectable for tests. */\n fetchImpl?: typeof fetch;\n};\n\n/** The minimum of a request both the Fetch API `Request` and hand-rolled\n * objects satisfy. */\nexport type CapturableRequest = {\n url: string;\n headers: { get(name: string): string | null };\n};\n\n/** Pathname only: a query string can carry tokens, emails or campaign ids. */\nfunction pathOf(url: string): string {\n try {\n return new URL(url, 'http://localhost').pathname || '/';\n } catch {\n return url.split(/[?#]/, 1)[0] || '/';\n }\n}\n\n/**\n * Low-level sender: posts one agent fetch to `/v1/crawler-events`. Never\n * throws, never blocks. The API re-derives the agent from `userAgent`\n * itself, so `botName` is advisory.\n */\nexport function postAgentFetch(\n entry: { path: string; userAgent: string; botName: string },\n opts: AgentCaptureOptions,\n): void {\n const doFetch = opts.fetchImpl ?? (typeof fetch === 'function' ? fetch : undefined);\n if (!doFetch || !opts.apiKey) return;\n try {\n const p = doFetch(`${opts.baseUrl ?? DEFAULT_API_BASE_URL}/crawler-events`, {\n method: 'POST',\n headers: { 'content-type': 'application/json', authorization: `Bearer ${opts.apiKey}` },\n body: JSON.stringify({\n path: entry.path,\n botName: entry.botName,\n userAgent: entry.userAgent,\n source: opts.source ?? 'middleware',\n }),\n }).catch(() => undefined);\n opts.waitUntil?.(p);\n } catch {\n /* capture must never break the page it is observing */\n }\n}\n\n/**\n * Log this request if its user agent is a known AI assistant or crawler.\n * Works with a Fetch API `Request` (edge runtimes, Hono, Remix / React\n * Router, Astro, SvelteKit) or anything with `url` + `headers.get`.\n *\n * Returns whether the request matched, so a caller can skip its own work;\n * it must NOT be used to serve anything different. Non-matching requests —\n * nearly all of them — make no network call.\n */\nexport function captureAgentRequest(req: CapturableRequest, opts: AgentCaptureOptions): boolean {\n let userAgent = '';\n try {\n userAgent = req.headers.get('user-agent') ?? '';\n } catch {\n return false;\n }\n const botName = matchedAgentToken(userAgent);\n if (!botName) return false;\n postAgentFetch({ path: pathOf(req.url), userAgent, botName }, opts);\n return true;\n}\n\ntype ConnectRequest = {\n url?: string;\n originalUrl?: string;\n headers: Record<string, string | string[] | undefined>;\n};\n\n/**\n * Connect-style middleware (Express, Nitro / Nuxt on Node, Fastify via\n * middie, any `(req, res, next)` stack). Calls `next()` synchronously and\n * logs in the background; it never touches the response.\n */\nexport function sentientAgentMiddleware(\n opts: Omit<AgentCaptureOptions, 'waitUntil' | 'source'>,\n): (req: ConnectRequest, res: unknown, next: (err?: unknown) => void) => void {\n return (req, _res, next) => {\n try {\n const raw = req.headers['user-agent'];\n const ua = Array.isArray(raw) ? raw[0] ?? '' : raw ?? '';\n captureAgentRequest(\n { url: req.originalUrl ?? req.url ?? '/', headers: { get: (n) => (n.toLowerCase() === 'user-agent' ? ua : null) } },\n { ...opts, source: 'middleware' },\n );\n } catch {\n /* never block the request */\n }\n next();\n };\n}\n"],"mappings":"sNA0FO,IAAMA,EAAoB,wBAGjC,SAASC,EAAWC,EAAoD,CACtE,IAAMC,EAAkC,CACtC,eAAgB,mBAChB,cAAe,UAAUD,EAAO,MAAM,EACxC,EACA,OAAIA,EAAO,SAAQC,EAAQ,OAASD,EAAO,QAGvCA,EAAO,WAAa,OAAO,QAAW,cAAaC,EAAQH,CAAiB,EAAIE,EAAO,WACpFC,CACT,CAWA,IAAMC,EAAqB,IAE3B,SAASC,EACPC,EACAC,E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9B,IAAAb,EAAAC,EAAAC,EAuHI,GAAI,CACF,IAAMY,EAAMP,EAAI,QAAQ,YAAY,EAC9BQ,EAAK,MAAM,QAAQD,CAAG,GAAId,EAAAc,EAAI,CAAC,IAAL,KAAAd,EAAU,GAAKc,GAAA,KAAAA,EAAO,GACtDR,EACE,CAAE,KAAKJ,GAAAD,EAAAM,EAAI,cAAJ,KAAAN,EAAmBM,EAAI,MAAvB,KAAAL,EAA8B,IAAK,QAAS,CAAE,IAAMc,GAAOA,EAAE,YAAY,IAAM,aAAeD,EAAK,IAAM,CAAE,EAClHE,EAAAC,EAAA,GAAKnB,GAAL,CAAW,OAAQ,YAAa,EAClC,CACF,OAAQH,EAAA,CAER,CACAiB,EAAK,CACP,CACF","names":["SERVER_KEY_HEADER","ssrHeaders","config","headers","DEFAULT_TIMEOUT_MS","fetchWithTimeout","url","init","timeoutMs","controller","timer","__spreadProps","__spreadValues","preloadAssignments","components","sessionId","preloadAssignmentsDetailed","opts","_a","sessionBody","buildSessionUpsertPayload","res","body","err","results","id","variantIds","assignments","unified","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","SERVER_GOAL_NAMESPACE","sha1Fallback","rotl","x","n","len","padded","view","h0","h1","h2","h3","h4","w","off","i","a","b","c","e","f","k","t","out","ov","v","uuidV5","name","namespace","hex","nsBytes","nameBytes","input","subtle","h","K256","sha256Fallback","bitLen","pv","rotr","s0","s1","g","hh","t1","t2","hmacSha256Fallback","key","msg","inner","outer","hmacSha256Hex","enc","m","mac","signUserId","userId","serverKey","exp","secret","DEFAULT_GOAL_API_BASE","DEFAULT_GOAL_TIMEOUT_MS","trackServerGoal","doFetch","timedOut","_","reject","goalId","DEFAULT_API_BASE_URL","pathOf","url","e","postAgentFetch","entry","opts","_a","_b","_c","_d","doFetch","p","captureAgentRequest","req","userAgent","botName","matchedAgentToken","sentientAgentMiddleware","_res","next","raw","ua","n","__spreadProps","__spreadValues"]}
|
package/dist/index.d.cts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
export { B as BLOCK_ALIGNS, a as BLOCK_EMPHASES, b as BLOCK_FITS, c as BLOCK_GAPS, d as BLOCK_GRID_COLUMNS, e as BLOCK_HEADING_LEVELS, f as BLOCK_JUSTIFIES, g as BLOCK_MAX_WIDTHS, h as BLOCK_PADS, i as BLOCK_RATIOS, j as BLOCK_SIZES, k as BLOCK_SURFACES, l as BLOCK_TEXT_ALIGNS, m as BLOCK_TONES, n as BLOCK_WEIGHTS, o as BadgeBlock, p as BlockAlign, q as BlockEmphasis, r as BlockFit, s as BlockGap, t as BlockJustify, u as BlockMaxWidth, v as BlockNode, w as BlockPad, x as BlockRatio, y as BlockSize, z as BlockSurface, A as BlockTextAlign, C as BlockTone, D as BlockWeight, E as ButtonBlock, F as ComposeArm, G as DividerBlock, H as FORM_FIELD_KINDS, I as FORM_INPUT_TYPES, J as FormBlock, K as FormField, L as GridBlock, M as HeadingBlock, N as ImageBlock, P as LinkBlock, Q as MAX_BLOCK_ARMS, R as MAX_BLOCK_CHILDREN, S as MAX_BLOCK_DEPTH, T as MAX_BLOCK_NODES, U as MAX_BLOCK_TEXT_LEN, V as MAX_FORM_FIELDS, W as MAX_FORM_SELECT_OPTIONS, _ as SiteImage, $ as SitePalette, a0 as SpacerBlock, a1 as StackBlock, a2 as StyleEntry, a3 as StyleRole, a4 as StyleVocabulary, a5 as TextBlock, a6 as containsFormBlock } from './style-vocabulary-Ba_g6_DD.cjs';
|
|
2
|
-
export { A as AssignOptions, a as AssignResult, b as Assignment, d as AuthoredArmReport, C as ComponentGoalOptions, e as ComponentWeightEntry, D as DecideInput, f as DecideOutcome, g as EventType, G as GoalDefinition, h as GoalOptions, j as GraphConfig, k as GraphSnapshot, L as LEGACY_SESSION_COOKIE_NAME, l as LOCAL_MODE_BANNER, M as MicroSignalEmitter, m as MicroSignalType, P as PAGE_SCOPE_RE, n as PROD_KEYLESS_ERROR, Q as QueueConfig, R as REVEAL_MS, p as RevealOptions, S as STAGE_ATTRIBUTE, q as SectionMapEntry, r as SentientClient, s as SentientConfig, t as SentientEvent, u as SessionConfig, v as SessionManager, w as SkeletonReport, x as StageAttributes, W as WeightEntry, _ as _registerConsentUpgradeInit, y as applyNonce, z as attachMicroSignalDetectors, B as cspNonce, F as exposedStage, H as forgetGeneration, I as grantConsent, J as init, K as isDoNotTrackEnabled, N as normalizeUrlPattern, O as pageScopeMatches, T as resetRevealStyles, U as reveal, V as routeKey, Y as sessionCookieName, Z as setCspNonce, $ as setStageAttribute, a0 as urlMatches } from './index-
|
|
3
|
-
export { A as AGENT_INTENTS, a as AgentIntent, C as CLICK_ID_KEYS, b as CompoundLocator, D as DecisionSnapshot, S as SNAPSHOT_STORAGE_KEY_PREFIX, d as SlotConfigEntry, e as SlotDeclInput, f as SlotOps, g as agentIntent, h as agentUaList, i as armOfResult, j as baselineResultFor, k as baselineSlots, m as classifiedAgents, n as deriveSessionSegment, o as detectDeviceClass, p as detectTimeOfDay, q as detectTrafficSource, r as extractTrackedParams, s as matchedAgentToken, t as readSnapshot, u as referrerDomainFromReferer, v as renderPrePaintScript, w as toWireSlot, x as uaTokenMatch, y as writeSnapshot } from './session-meta-
|
|
2
|
+
export { A as AssignOptions, a as AssignResult, b as Assignment, d as AuthoredArmReport, C as ComponentGoalOptions, e as ComponentWeightEntry, D as DecideInput, f as DecideOutcome, g as EventType, G as GoalDefinition, h as GoalOptions, j as GraphConfig, k as GraphSnapshot, L as LEGACY_SESSION_COOKIE_NAME, l as LOCAL_MODE_BANNER, M as MicroSignalEmitter, m as MicroSignalType, P as PAGE_SCOPE_RE, n as PROD_KEYLESS_ERROR, Q as QueueConfig, R as REVEAL_MS, p as RevealOptions, S as STAGE_ATTRIBUTE, q as SectionMapEntry, r as SentientClient, s as SentientConfig, t as SentientEvent, u as SessionConfig, v as SessionManager, w as SkeletonReport, x as StageAttributes, W as WeightEntry, _ as _registerConsentUpgradeInit, y as applyNonce, z as attachMicroSignalDetectors, B as cspNonce, F as exposedStage, H as forgetGeneration, I as grantConsent, J as init, K as isDoNotTrackEnabled, N as normalizeUrlPattern, O as pageScopeMatches, T as resetRevealStyles, U as reveal, V as routeKey, Y as sessionCookieName, Z as setCspNonce, $ as setStageAttribute, a0 as urlMatches } from './index-Cgiw9NDh.cjs';
|
|
3
|
+
export { A as AGENT_INTENTS, a as AgentIntent, C as CLICK_ID_KEYS, b as CompoundLocator, D as DecisionSnapshot, S as SNAPSHOT_STORAGE_KEY_PREFIX, d as SlotConfigEntry, e as SlotDeclInput, f as SlotOps, g as agentIntent, h as agentUaList, i as armOfResult, j as baselineResultFor, k as baselineSlots, m as classifiedAgents, n as deriveSessionSegment, o as detectDeviceClass, p as detectTimeOfDay, q as detectTrafficSource, r as extractTrackedParams, s as matchedAgentToken, t as readSnapshot, u as referrerDomainFromReferer, v as renderPrePaintScript, w as toWireSlot, x as uaTokenMatch, y as writeSnapshot } from './session-meta-BG8w53d7.cjs';
|
|
4
4
|
export { A as ArmEdits, M as MAX_SKELETON_LEAVES, a as MAX_SKELETON_NODES, b as MAX_SKELETON_TEXT, R as RegionSkeleton, c as RenderCaps, S as ServedEdits, d as SkeletonNode, e as SkeletonRole } from './region-skeleton-BRIVB-qf.cjs';
|
|
5
5
|
export { ConsentPreset, ConsentSource, ConsentWatcher, forgetVisitor } from './index-consent.cjs';
|
|
6
6
|
export { SlotResult } from '@sentientui/policy';
|
package/dist/index.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
export { B as BLOCK_ALIGNS, a as BLOCK_EMPHASES, b as BLOCK_FITS, c as BLOCK_GAPS, d as BLOCK_GRID_COLUMNS, e as BLOCK_HEADING_LEVELS, f as BLOCK_JUSTIFIES, g as BLOCK_MAX_WIDTHS, h as BLOCK_PADS, i as BLOCK_RATIOS, j as BLOCK_SIZES, k as BLOCK_SURFACES, l as BLOCK_TEXT_ALIGNS, m as BLOCK_TONES, n as BLOCK_WEIGHTS, o as BadgeBlock, p as BlockAlign, q as BlockEmphasis, r as BlockFit, s as BlockGap, t as BlockJustify, u as BlockMaxWidth, v as BlockNode, w as BlockPad, x as BlockRatio, y as BlockSize, z as BlockSurface, A as BlockTextAlign, C as BlockTone, D as BlockWeight, E as ButtonBlock, F as ComposeArm, G as DividerBlock, H as FORM_FIELD_KINDS, I as FORM_INPUT_TYPES, J as FormBlock, K as FormField, L as GridBlock, M as HeadingBlock, N as ImageBlock, P as LinkBlock, Q as MAX_BLOCK_ARMS, R as MAX_BLOCK_CHILDREN, S as MAX_BLOCK_DEPTH, T as MAX_BLOCK_NODES, U as MAX_BLOCK_TEXT_LEN, V as MAX_FORM_FIELDS, W as MAX_FORM_SELECT_OPTIONS, _ as SiteImage, $ as SitePalette, a0 as SpacerBlock, a1 as StackBlock, a2 as StyleEntry, a3 as StyleRole, a4 as StyleVocabulary, a5 as TextBlock, a6 as containsFormBlock } from './style-vocabulary-Ba_g6_DD.js';
|
|
2
|
-
export { A as AssignOptions, a as AssignResult, b as Assignment, d as AuthoredArmReport, C as ComponentGoalOptions, e as ComponentWeightEntry, D as DecideInput, f as DecideOutcome, g as EventType, G as GoalDefinition, h as GoalOptions, j as GraphConfig, k as GraphSnapshot, L as LEGACY_SESSION_COOKIE_NAME, l as LOCAL_MODE_BANNER, M as MicroSignalEmitter, m as MicroSignalType, P as PAGE_SCOPE_RE, n as PROD_KEYLESS_ERROR, Q as QueueConfig, R as REVEAL_MS, p as RevealOptions, S as STAGE_ATTRIBUTE, q as SectionMapEntry, r as SentientClient, s as SentientConfig, t as SentientEvent, u as SessionConfig, v as SessionManager, w as SkeletonReport, x as StageAttributes, W as WeightEntry, _ as _registerConsentUpgradeInit, y as applyNonce, z as attachMicroSignalDetectors, B as cspNonce, F as exposedStage, H as forgetGeneration, I as grantConsent, J as init, K as isDoNotTrackEnabled, N as normalizeUrlPattern, O as pageScopeMatches, T as resetRevealStyles, U as reveal, V as routeKey, Y as sessionCookieName, Z as setCspNonce, $ as setStageAttribute, a0 as urlMatches } from './index-
|
|
3
|
-
export { A as AGENT_INTENTS, a as AgentIntent, C as CLICK_ID_KEYS, b as CompoundLocator, D as DecisionSnapshot, S as SNAPSHOT_STORAGE_KEY_PREFIX, d as SlotConfigEntry, e as SlotDeclInput, f as SlotOps, g as agentIntent, h as agentUaList, i as armOfResult, j as baselineResultFor, k as baselineSlots, m as classifiedAgents, n as deriveSessionSegment, o as detectDeviceClass, p as detectTimeOfDay, q as detectTrafficSource, r as extractTrackedParams, s as matchedAgentToken, t as readSnapshot, u as referrerDomainFromReferer, v as renderPrePaintScript, w as toWireSlot, x as uaTokenMatch, y as writeSnapshot } from './session-meta-
|
|
2
|
+
export { A as AssignOptions, a as AssignResult, b as Assignment, d as AuthoredArmReport, C as ComponentGoalOptions, e as ComponentWeightEntry, D as DecideInput, f as DecideOutcome, g as EventType, G as GoalDefinition, h as GoalOptions, j as GraphConfig, k as GraphSnapshot, L as LEGACY_SESSION_COOKIE_NAME, l as LOCAL_MODE_BANNER, M as MicroSignalEmitter, m as MicroSignalType, P as PAGE_SCOPE_RE, n as PROD_KEYLESS_ERROR, Q as QueueConfig, R as REVEAL_MS, p as RevealOptions, S as STAGE_ATTRIBUTE, q as SectionMapEntry, r as SentientClient, s as SentientConfig, t as SentientEvent, u as SessionConfig, v as SessionManager, w as SkeletonReport, x as StageAttributes, W as WeightEntry, _ as _registerConsentUpgradeInit, y as applyNonce, z as attachMicroSignalDetectors, B as cspNonce, F as exposedStage, H as forgetGeneration, I as grantConsent, J as init, K as isDoNotTrackEnabled, N as normalizeUrlPattern, O as pageScopeMatches, T as resetRevealStyles, U as reveal, V as routeKey, Y as sessionCookieName, Z as setCspNonce, $ as setStageAttribute, a0 as urlMatches } from './index-DqDG5phU.js';
|
|
3
|
+
export { A as AGENT_INTENTS, a as AgentIntent, C as CLICK_ID_KEYS, b as CompoundLocator, D as DecisionSnapshot, S as SNAPSHOT_STORAGE_KEY_PREFIX, d as SlotConfigEntry, e as SlotDeclInput, f as SlotOps, g as agentIntent, h as agentUaList, i as armOfResult, j as baselineResultFor, k as baselineSlots, m as classifiedAgents, n as deriveSessionSegment, o as detectDeviceClass, p as detectTimeOfDay, q as detectTrafficSource, r as extractTrackedParams, s as matchedAgentToken, t as readSnapshot, u as referrerDomainFromReferer, v as renderPrePaintScript, w as toWireSlot, x as uaTokenMatch, y as writeSnapshot } from './session-meta-D9Wx2PtC.js';
|
|
4
4
|
export { A as ArmEdits, M as MAX_SKELETON_LEAVES, a as MAX_SKELETON_NODES, b as MAX_SKELETON_TEXT, R as RegionSkeleton, c as RenderCaps, S as ServedEdits, d as SkeletonNode, e as SkeletonRole } from './region-skeleton-BRIVB-qf.js';
|
|
5
5
|
export { ConsentPreset, ConsentSource, ConsentWatcher, forgetVisitor } from './index-consent.js';
|
|
6
6
|
export { SlotResult } from '@sentientui/policy';
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var Gn=Object.create;var Le=Object.defineProperty,Un=Object.defineProperties,$n=Object.getOwnPropertyDescriptor,Fn=Object.getOwnPropertyDescriptors,jn=Object.getOwnPropertyNames,rn=Object.getOwnPropertySymbols,Wn=Object.getPrototypeOf,an=Object.prototype.hasOwnProperty,Vn=Object.prototype.propertyIsEnumerable;var sn=(e,t,n)=>t in e?Le(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,A=(e,t)=>{for(var n in t||(t={}))an.call(t,n)&&sn(e,n,t[n]);if(rn)for(var n of rn(t))Vn.call(t,n)&&sn(e,n,t[n]);return e},Se=(e,t)=>Un(e,Fn(t));var Hn=(e,t)=>{for(var n in t)Le(e,n,{get:t[n],enumerable:!0})},ln=(e,t,n,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let p of jn(t))!an.call(e,p)&&p!==n&&Le(e,p,{get:()=>t[p],enumerable:!(i=$n(t,p))||i.enumerable});return e};var zn=(e,t,n)=>(n=e!=null?Gn(Wn(e)):{},ln(t||!e||!e.__esModule?Le(n,"default",{value:e,enumerable:!0}):n,e)),Qn=e=>ln(Le({},"__esModule",{value:!0}),e);var Xo={};Hn(Xo,{AGENT_INTENTS:()=>it,BLOCK_ALIGNS:()=>yo,BLOCK_EMPHASES:()=>ko,BLOCK_FITS:()=>Eo,BLOCK_GAPS:()=>mo,BLOCK_GRID_COLUMNS:()=>_o,BLOCK_HEADING_LEVELS:()=>Io,BLOCK_JUSTIFIES:()=>So,BLOCK_MAX_WIDTHS:()=>Co,BLOCK_PADS:()=>Ro,BLOCK_RATIOS:()=>wo,BLOCK_SIZES:()=>ho,BLOCK_SURFACES:()=>Ao,BLOCK_TEXT_ALIGNS:()=>xo,BLOCK_TONES:()=>vo,BLOCK_WEIGHTS:()=>bo,CLICK_ID_KEYS:()=>Ct,FORM_FIELD_KINDS:()=>To,FORM_INPUT_TYPES:()=>Oo,LEGACY_SESSION_COOKIE_NAME:()=>he,LOCAL_MODE_BANNER:()=>Tt,MAX_BLOCK_ARMS:()=>No,MAX_BLOCK_CHILDREN:()=>Mo,MAX_BLOCK_DEPTH:()=>Lo,MAX_BLOCK_NODES:()=>Bo,MAX_BLOCK_TEXT_LEN:()=>Ko,MAX_FORM_FIELDS:()=>Po,MAX_FORM_SELECT_OPTIONS:()=>Do,MAX_SKELETON_LEAVES:()=>Br,MAX_SKELETON_NODES:()=>Dr,MAX_SKELETON_TEXT:()=>Lr,PAGE_SCOPE_RE:()=>Pt,PROD_KEYLESS_ERROR:()=>ft,REVEAL_MS:()=>Bt,SNAPSHOT_STORAGE_KEY_PREFIX:()=>fe,STAGE_ATTRIBUTE:()=>ct,_registerConsentUpgradeInit:()=>$o,agentIntent:()=>mn,agentUaList:()=>Ge,applyNonce:()=>Je,armOfResult:()=>lt,attachMicroSignalDetectors:()=>Rn,baselineResultFor:()=>Oe,baselineSlots:()=>hn,classifiedAgents:()=>yn,containsFormBlock:()=>_n,cspNonce:()=>wt,deriveSessionSegment:()=>Sn,detectDeviceClass:()=>$e,detectTimeOfDay:()=>We,detectTrafficSource:()=>Fe,exposedStage:()=>dt,extractTrackedParams:()=>at,forgetGeneration:()=>se,forgetVisitor:()=>tt,grantConsent:()=>zo,init:()=>Ln,isDoNotTrackEnabled:()=>Ut,matchedAgentToken:()=>Rt,normalizeUrlPattern:()=>En,pageScopeMatches:()=>xn,readSnapshot:()=>Ie,referrerDomainFromReferer:()=>je,renderPrePaintScript:()=>cn,resetRevealStyles:()=>In,reveal:()=>An,routeKey:()=>Kt,sessionCookieName:()=>_e,setCspNonce:()=>Xe,setStageAttribute:()=>ut,toWireSlot:()=>Ve,uaTokenMatch:()=>Ue,urlMatches:()=>wn,writeSnapshot:()=>Ae});module.exports=Qn(Xo);function ue(e){if(typeof AbortController!="function")return{clear:()=>{}};let t=new AbortController,n=setTimeout(()=>t.abort(),e);return{signal:t.signal,clear:()=>clearTimeout(n)}}function kt(e,t){return new Promise(n=>{let i=setTimeout(()=>n(!1),t),p=()=>{clearTimeout(i),n(!0)};e.then(p,p)})}var xt;function Xe(e){xt=typeof e=="string"&&e!==""?e:void 0}function wt(e=document){if(xt)return xt;try{let t=e.querySelector("script[nonce]");return(t==null?void 0:t.nonce)||(t==null?void 0:t.getAttribute("nonce"))||void 0}catch(t){return}}function Je(e,t=document){let n=wt(t);return n&&e.setAttribute("nonce",n),e}function pe(e){return e?`_${e.slice(0,12)}`:""}var he="_snt_uid";function _e(e){return`${he}${pe(e)}`}var qe="__sntForgetGen",Xn=()=>{try{return window[qe]}catch(e){return}};function Ye(e){var t,n;try{let i=window,p=(t=i[qe])!=null?t:i[qe]={};p[e]=((n=p[e])!=null?n:0)+1}catch(i){}}function se(e){var t,n;return(n=(t=Xn())==null?void 0:t[e])!=null?n:0}var fe="_snt_snap:";var Jn=["low","medium","high"];function Ie(e){try{let t=localStorage.getItem(fe+e);if(!t)return null;let n=JSON.parse(t);if(!n||typeof n!="object"||n.v!==1||typeof n.persona!="string"||typeof n.band!="string"||!Jn.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"||!(Date.now()-n.savedAt<2592e6)||!(n.slotConfig===void 0||typeof n.slotConfig=="object"&&n.slotConfig!==null&&!Array.isArray(n.slotConfig)))return null;let i=n.vocabulary;return i!==void 0&&(typeof i!="object"||i===null||!Array.isArray(i.entries)||!Array.isArray(i.images))&&delete n.vocabulary,n.stage!==void 0&&typeof n.stage!="string"&&delete n.stage,n}catch(t){return null}}function Ae(e,t){try{localStorage.setItem(fe+e,JSON.stringify(t))}catch(n){}}function cn(e,t){return'(function(){try{var N=navigator,W=window;if(N.doNotTrack=="1"||N.doNotTrack=="yes"||W.doNotTrack=="1"||N.msDoNotTrack=="1"||N.globalPrivacyControl)return;var r=localStorage.getItem('+JSON.stringify(fe+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;if(!('+2592e6+">Date.now()-s.savedAt))return;var d=document.documentElement;"+(t!=null&&t.stage?'if(typeof s.stage=="string"&&!d.hasAttribute("data-sentient-stage"))d.setAttribute("data-sentient-stage",s.stage);':"")+'if(d.hasAttribute("data-sentient-persona"))return;d.setAttribute("data-sentient-persona",s.persona);d.setAttribute("data-sentient-confidence",s.band);}catch(e){}})();'}function me(e){return Math.min(6e4,1e3*2**Math.min(e,6))}function Re(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 Ze(e,t){try{let n=localStorage.getItem(e);if(!n)return[];let i=JSON.parse(n);return Array.isArray(i)?(localStorage.removeItem(e),i.slice(-t)):[]}catch(n){return[]}}function Me(e,t,n){try{let i=(()=>{try{let u=localStorage.getItem(n);if(!u)return[];let y=JSON.parse(u);return Array.isArray(y)?y:[]}catch(u){return[]}})(),p=new Map;for(let u of i)p.set(u.id,u);for(let u of e)p.set(u.id,u);localStorage.setItem(n,JSON.stringify([...p.values()].slice(-t)))}catch(i){}}function et(e,t){try{let n=localStorage.getItem(t);if(!n)return;let i=JSON.parse(n);if(!Array.isArray(i))return;let p=new Set(e),u=i.filter(y=>!p.has(y.id));if(u.length===i.length)return;u.length===0?localStorage.removeItem(t):localStorage.setItem(t,JSON.stringify(u))}catch(n){}}var qn=500,Yn=56*1024;function Ne(e){return`_snt_retry_${e.slice(0,12)}`}var Zn={push:()=>{},flush:()=>{},destroy:()=>{}};function dn(e){var O,ee,ie;if(typeof window=="undefined")return Zn;let t=(O=e.flushIntervalMs)!=null?O:5e3,n=(ee=e.maxBatchSize)!=null?ee:20,i=(ie=e.maxRetrySize)!=null?ie:100,p=e.ingestUrl,u=e.apiKey,y=Ne(u),o=!1,f=se(u),a=(...k)=>{!o&&se(u)===f&&Me(...k)},s=[],c=new Set,v=[],T=k=>{for(let B of k)C.delete(B),!c.has(B)&&(c.add(B),v.push(B));for(;v.length>qn;){let B=v.shift();B&&c.delete(B)}et(k,y)},C=new Set,D=()=>{for(;s.length>i;){let k=s.shift();k&&C.delete(k.id)}},M=k=>{c.has(k.id)||C.has(k.id)||(C.add(k.id),s.push(k),D())},V=k=>{for(let B of k)c.has(B.id)||(C.add(B.id),s.push(B));D()},H=Ze(y,i);for(let k of H)M(k);let z=0,X=0,Q=(k,B=!0)=>{if(k.length===0)return;let ge=JSON.stringify(k),be=k.map(oe=>oe.id),te,ke=ue(15e3);try{te=fetch(p,{method:"POST",keepalive:!0,signal:ke.signal,body:ge,headers:{"Content-Type":"application/json",Authorization:`Bearer ${u}`}})}catch(oe){a(k,i,y),V(k),X++,z=Date.now()+me(X);return}Promise.resolve(te).then(ke.clear,ke.clear);let xe=oe=>{if(Re(oe)!=="retry"){if(!oe.ok&&B){let we=k.filter(ae=>ae.eventType!=="pageview");if(we.length>0&&we.length<k.length){T(k.filter(ae=>ae.eventType==="pageview").map(ae=>ae.id)),Q(we,!1);return}}T(be),X=0,z=0;return}a(k,i,y),V(k),X++,z=Date.now()+me(X)};te&&typeof te.then=="function"?te.then(xe).catch(()=>{a(k,i,y),V(k),X++,z=Date.now()+me(X)}):xe(te)},$=typeof TextEncoder!="undefined"?new TextEncoder:null,d=k=>$?$.encode(k).length:k.length,m=k=>{let B=[],ge=2;for(let be of k){let te=d(JSON.stringify(be))+1;if(B.length>0&&ge+te>Yn||B.length>=n)break;B.push(be),ge+=te}return B},h=()=>{try{if(Date.now()<z)return;for(;s.length>0&&!(Date.now()<z);){let k=s.filter(ge=>!c.has(ge.id));if(s.length=0,k.length===0)break;let B=m(k);if(B.length===0)break;B.length<k.length&&s.push(...k.slice(B.length)),Q(B)}}catch(k){}},g=!0,_=null;_=setInterval(()=>{g&&h()},t);let N=()=>{document.visibilityState==="hidden"&&h()},F=()=>{h()};return document.addEventListener("visibilitychange",N),window.addEventListener("pagehide",F),{push(k){M(k),s.length>=n&&h()},flush:h,destroy(k){k!=null&&k.forget&&(o=!0),g=!1,_!==null&&(clearInterval(_),_=null),document.removeEventListener("visibilitychange",N),window.removeEventListener("pagehide",F),h()}}}var eo=200;function Ke(e){return`_snt_goal_retry_${e.slice(0,12)}`}var to={send:()=>{},flush:()=>{},destroy:()=>{}};function un(e){var d,m,h;if(typeof window=="undefined")return to;let t=(d=e.flushIntervalMs)!=null?d:5e3,n=(m=e.maxRetrySize)!=null?m:100,i=(h=e.maxPerFlush)!=null?h:5,p=Ke(e.apiKey),u=!1,y=se(e.apiKey),o=(...g)=>{!u&&se(e.apiKey)===y&&Me(...g)},f=[],a=new Set,s=new Set,c=[],v=0,T=0,C=!1,D=g=>{for(a.delete(g.id),s.has(g.id)||(s.add(g.id),c.push(g.id));c.length>eo;){let _=c.shift();_&&s.delete(_)}et([g.id],p)},M=g=>{o([g],n,p),!s.has(g.id)&&!a.has(g.id)&&(a.add(g.id),f.push(g)),Date.now()>=v&&(T++,v=Date.now()+me(T))},V=g=>{let _,N=ue(15e3);try{_=fetch(e.url,{method:"POST",keepalive:!0,signal:N.signal,body:g.body,headers:e.headers})}catch(O){M(g);return}let F=O=>{var ie;let ee=Re(O);if(ee==="retry"){M(g);return}ee==="dropped"&&((ie=e.onDrop)==null||ie.call(e,g,O.status)),D(g),T=0,v=0};Promise.resolve(_).then(N.clear,N.clear),_&&typeof _.then=="function"?_.then(F).catch(()=>M(g)):F(_)},H=()=>{try{if(C||Date.now()<v)return;let g=0;for(;f.length>0&&g<i&&!(Date.now()<v);){let _=f.shift();a.delete(_.id),!s.has(_.id)&&(g++,V(_))}}catch(g){}},z=Ze(p,n);for(let g of z)a.has(g.id)||(a.add(g.id),f.push(g));z.length>0&&Me(z,n,p);let X=setInterval(H,t),Q=()=>{document.visibilityState==="hidden"&&H()},$=()=>H();return document.addEventListener("visibilitychange",Q),window.addEventListener("pagehide",$),{send(g){if(C){s.has(g.id)||o([g],n,p);return}if(!(s.has(g.id)||a.has(g.id))){if(Date.now()<v){o([g],n,p),a.add(g.id),f.push(g);return}V(g)}},flush:H,destroy(g){g!=null&&g.forget&&(u=!0),clearInterval(X),document.removeEventListener("visibilitychange",Q),window.removeEventListener("pagehide",$),H(),C=!0}}}function tt(e){if(typeof window=="undefined"||!e)return!1;Ye(e);let t=!1,n=_e(e);try{if(new RegExp(`(?:^|; )${n}=`).test(document.cookie)){let y=location.protocol==="https:"?"; Secure":"";document.cookie=`${n}=; max-age=0; SameSite=lax; path=/${y}`,t=!0}}catch(y){}let i=pe(e),p=[n,"_snt_graph_edges",fe+e,Ne(e),Ke(e),`_snt_graph_nodes${i}`],u=[`_snt_asgn${i}_`];for(let y of["localStorage","sessionStorage"])try{let o=window[y];for(let f of p)o.getItem(f)!==null&&(o.removeItem(f),t=!0);for(let f=o.length-1;f>=0;f--){let a=o.key(f);a&&u.some(s=>a.startsWith(s))&&(o.removeItem(a),t=!0)}}catch(o){}try{(new RegExp(`(?:^|; )${he}=[^;]`).test(document.cookie)||localStorage.getItem(he)!==null||sessionStorage.getItem(he)!==null)&&localStorage.setItem(`${he}_tomb${i}`,"1")}catch(y){}return t}function nt(){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)})}var gn="_snt_uid",no=365,Ce="_snt_uid";function oo(){return nt()}function _t(e){try{let t=document.cookie.match(new RegExp(`(?:^|; )${e}=([^;]*)`));return t?decodeURIComponent(t[1]):null}catch(t){return null}}function At(){try{return location.protocol==="https:"?"; Secure":""}catch(e){return""}}function ro(e,t,n){try{document.cookie=`${e}=${encodeURIComponent(t)}; max-age=${n}; SameSite=lax; path=/${At()}`}catch(i){}}function ot(e){try{return localStorage.getItem(e)}catch(t){return null}}function pn(e,t){try{return localStorage.setItem(e,t),!0}catch(n){return!1}}function It(e){try{return sessionStorage.getItem(e)}catch(t){return null}}function so(e,t){try{return sessionStorage.setItem(e,t),!0}catch(n){return!1}}function io(e){try{sessionStorage.removeItem(e)}catch(t){}}function ao(e){try{return document.cookie=`${e}_probe=1; max-age=1; SameSite=lax; path=/${At()}`,document.cookie.indexOf(`${e}_probe=1`)!==-1}catch(t){return!1}}function lo(e){try{localStorage.removeItem(e)}catch(t){}}function co(e){try{document.cookie=`${e}=; max-age=0; SameSite=lax; path=/${At()}`}catch(t){}}var uo={getSessionId:()=>null,isEphemeral:()=>!1,destroy:()=>{}};function rt(e){var C,D,M,V,H,z,X;if(typeof window=="undefined")return uo;let t=pe(e==null?void 0:e.apiKey),n=(C=e==null?void 0:e.cookieName)!=null?C:_e(e==null?void 0:e.apiKey),i=`${Ce}${t}`,p=`${Ce}_tomb${t}`,y=((D=e==null?void 0:e.cookieTTLDays)!=null?D:no)*24*60*60,o=Q=>Q&&Q.length>0?Q:null,f=()=>{var Q,$;return t&&!(e!=null&&e.cookieName)&&ot(p)===null?($=(Q=o(_t(gn)))!=null?Q:o(ot(Ce)))!=null?$:o(It(Ce)):null},a=(X=(z=(H=(V=(M=o(_t(n)))!=null?M:o(ot(i)))!=null?V:o(It(i)))!=null?H:f())!=null?z:o(e==null?void 0:e.ssrSessionId))!=null?X:oo();ro(n,a,y);let s=pn(i,a),c=ao(n),v=s?!1:so(i,a),T=!s&&!c&&!v;return{getSessionId:()=>a,isEphemeral:()=>T,destroy:()=>{a=null,co(n),lo(i),io(i),t&&!(e!=null&&e.cookieName)&&(_t(gn)!==null||ot(Ce)!==null||It(Ce)!==null)&&pn(p,"1")}}}var go=1800*1e3;function st(e,t){return`${encodeURIComponent(e)}:${encodeURIComponent(t)}`}function fn(e=go,t){let n=new Map,i=`_snt_asgn${pe(t)}_`,p=(a,s)=>`${i}${encodeURIComponent(a)}:${encodeURIComponent(s)}`,u=a=>{let s=a.slice(i.length),c=s.indexOf(":");if(c<0)return null;try{return{componentId:decodeURIComponent(s.slice(0,c)),segment:decodeURIComponent(s.slice(c+1))}}catch(v){return null}},y=()=>{try{let a=[];for(let s=0;s<localStorage.length;s++){let c=localStorage.key(s);c!=null&&c.startsWith(i)&&a.push(c)}return a}catch(a){return[]}},o=a=>a.assignedAt+(a.ttlMs&&a.ttlMs>0?a.ttlMs:e)<Date.now();return typeof window!="undefined"&&(()=>{for(let a of y())try{let s=localStorage.getItem(a);if(!s)continue;let c=JSON.parse(s);if(o(c)){localStorage.removeItem(a);continue}let v=u(a);if(!v)continue;n.set(st(v.componentId,v.segment),c)}catch(s){}})(),{get(a,s){let c=n.get(st(a,s));return c?o(c)?(n.delete(st(a,s)),null):c:null},set(a,s,c){let v=st(a,s);n.set(v,c);try{localStorage.setItem(p(a,s),JSON.stringify(c))}catch(T){}},clear(){n.clear();for(let a of y())try{localStorage.removeItem(a)}catch(s){}}}}var Ge=["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 Ue(e){return Rt(e)!==null}function Rt(e){var n;if(!e)return null;let t=e.toLowerCase();return(n=Ge.find(i=>t.includes(i.toLowerCase())))!=null?n:null}var it={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 mn(e){if(!e)return"other";let t=Ge.find(n=>n.toLowerCase()===e.toLowerCase());return t&&it[t]||"other"}function yn(){var t;let e={user:[],search:[],training:[],other:[]};for(let n of Ge)e[(t=it[n])!=null?t:"other"].push(n);return e}function $e(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 Fe(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(p){}let i=n.hostname.toLowerCase();return/(^|\.)(google|bing|duckduckgo|yahoo)\./.test(i)?"search":/(^|\.)(twitter\.com|x\.com|facebook\.com|linkedin\.com|reddit\.com|t\.co)$/.test(i)?"social":"referral"}catch(n){return"direct"}}function je(e){if(!e)return null;try{return new URL(e).hostname}catch(t){return null}}var Ct=["gclid","gbraid","wbraid","fbclid","ttclid","msclkid","twclid","li_fat_id"];function at(e){let t={},n={};try{let i=typeof e=="string"||e instanceof URLSearchParams?new URLSearchParams(e):Object.entries(e).flatMap(([p,u])=>{let y=Array.isArray(u)?u[0]:u;return y===void 0?[]:[[p,y]]});for(let[p,u]of i)p.startsWith("utm_")?p in t||(t[p]=u):Ct.includes(p)&&(p in n||(n[p]=u))}catch(i){}return{utmParams:t,clickIds:n}}function We(e){let t=e.getHours();return t<6?"night":t<12?"morning":t<18?"afternoon":"evening"}function Sn(e){let t=po("__segment__",e);return`${t.deviceClass}:${t.trafficSource}`}function po(e,t){var u,y,o,f,a,s,c,v;let n=(y=(u=t==null?void 0:t.userAgent)==null?void 0:u.trim())!=null?y:"",i=(f=(o=t==null?void 0:t.referer)==null?void 0:o.trim())!=null?f:"",p=(a=t==null?void 0:t.now)!=null?a:new Date;return A({sessionId:e,ephemeral:!1,utmParams:(s=t==null?void 0:t.utmParams)!=null?s:{},clickIds:(c=t==null?void 0:t.clickIds)!=null?c:{},deviceClass:n?$e(n):"desktop",trafficSource:i?Fe(i,t==null?void 0:t.appOrigin):"direct",referrerDomain:je(i),timeOfDay:We(p),dayOfWeek:(v=["sun","mon","tue","wed","thu","fri","sat"][p.getDay()])!=null?v:"sun",automation:(t==null?void 0:t.webdriver)===!0||Ue(n)},t!=null&&t.landingPath?{landingPath:t.landingPath.split(/[?#]/)[0]}:{})}var Te=require("@sentientui/policy");function Ve(e){return A(A(A({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 Oe(e){let t=Ve(e);return(0,Te.slotResultFor)(t,(0,Te.slotBaselineArm)(t))}function hn(e){let t={};for(let n of e)t[n.id]=Oe(n);return t}function lt(e){return typeof e=="string"?e:(0,Te.canonicalArm)(e)}var bn=require("@sentientui/policy"),ct="data-sentient-stage";function dt(e,t){return!t||typeof e!="string"||!(e==="returning"||bn.STAGE_KEYS.includes(e))?null:t!=="detailed"&&(e==="customer"||e==="lapsed")?"returning":e}function ut(e,t=document){try{e?t.documentElement.setAttribute(ct,e):t.documentElement.removeAttribute(ct)}catch(n){}}var Nt=require("@sentientui/policy");var pt=require("@sentientui/policy");var ft="[sentient] No API key configured \u2014 nothing is being learned. Set NEXT_PUBLIC_SENTIENT_API_KEY or pass localMode: true for local development.",Tt="[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.",vn=!1,gt=!1;function fo(){var e;try{return(e=new URLSearchParams(window.location.search).get("sentient_persona"))!=null?e:void 0}catch(t){return}}function kn(e){var a;let t=rt({ssrSessionId:e.ssrSessionId,apiKey:e.apiKey}),n=(a=t.getSessionId())!=null?a:"local",i=fo(),p=import("@sentientui/core/local").then(s=>{let c=s;return c.LOCAL_ENGINE_AVAILABLE?(vn||(vn=!0,console.info(Tt)),c):(gt||(gt=!0,console.error(ft)),null)}).catch(()=>(gt||(gt=!0,console.error(ft)),null)),u=null,y={low:.15,medium:.5,high:.85},o=(()=>{var c;if(e.initialPersona)return A({},e.initialPersona);let s=Ie(e.apiKey||"local");return s?{persona:s.persona,confidence:(c=y[s.band])!=null?c:.15}:null})();function f(s){let c=document.documentElement;c.dataset.sentientPersona===void 0&&(c.dataset.sentientPersona=s.persona,c.dataset.sentientConfidence=(0,pt.confidenceBand)(s.confidence))}return{isLocal:!0,async decide(s){var T,C,D;let c=await p;if(!c)return null;let v=c.createLocalEngine({sessionId:n,forcedPersona:i}).decide(s);return u=Se(A({},v),{layoutOrder:(C=(T=v.layoutOrder)!=null?T:u==null?void 0:u.layoutOrder)!=null?C:null,slots:A(A({},(D=u==null?void 0:u.slots)!=null?D:{}),v.slots)}),Ae(e.apiKey||"local",{v:1,persona:u.persona,band:(0,pt.confidenceBand)(u.confidence),slots:u.slots,layoutOrder:u.layoutOrder,savedAt:Date.now()}),f(v),v},getSlotResult(s){var c,v,T;return(T=(v=u==null?void 0:u.slots[s])!=null?v:(c=e.initialSlots)==null?void 0:c[s])!=null?T:null},getSlotConfig(s){var c,v;return(v=(c=e.initialSlotConfig)==null?void 0:c[s])!=null?v:null},getSitePalette(){var s;return(s=e.initialPalette)!=null?s:null},reportSlots(){},getVisitorId:()=>null,getPersona(){let s=u!=null?u:o;return s?{persona:s.persona,confidence:s.confidence,band:(0,pt.confidenceBand)(s.confidence)}:null},async assign(s,c){var C;let v=await p;return!v||!c||c.length===0?c!=null&&c[0]?{variantId:c[0],assignmentTtlMs:0}:null:{variantId:(C=v.createLocalEngine({sessionId:n,forcedPersona:i}).decide({components:[{id:s,variantIds:c}]}).assignments[s])!=null?C:c[0],assignmentTtlMs:0}},track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},getAssignment:()=>null,fetchWeights:()=>Promise.resolve([]),getGraph:()=>({pageNodes:[],capturedAt:0}),flush:()=>{},dispose:()=>{},destroy:()=>t.destroy()}}var Pt=/^(\*|\/[^\s?#*]*(\/\*)?)$/;function Ot(e){let t=e.split(/[?#]/)[0]||"/";return t.length>1?t.replace(/\/+$/,"")||"/":t}function xn(e,t){if(e===void 0||!Pt.test(e))return!1;if(e==="*")return!0;let n=Ot(t);if(e.endsWith("/*")){let i=Ot(e.slice(0,-2));return n.startsWith(i==="/"?"/":`${i}/`)&&n!==i}return n===Ot(e)}function wn(e,t){if(!e)return!1;if(e==="/")return t==="/";let n=e.endsWith("/")?e.slice(0,-1):e;return t===n||t.startsWith(`${n}/`)}function En(e){if(!/^https?:\/\//i.test(e))return e;try{return new URL(e).pathname||"/"}catch(t){return e}}var mo=["none","sm","md","lg"],yo=["start","center","end","stretch"],So=["start","center","end","between"],ho=["sm","md","lg"],bo=["normal","medium","bold"],vo=["default","muted","accent"],ko=["primary","secondary","ghost"],xo=["left","center","right"],wo=["auto","square","landscape","wide"],Eo=["cover","contain"],_o=[2,3,4],Io=[1,2,3,4],Ao=["default","raised"],Ro=["none","sm","md","lg"],Co=["measure"],To=["input","textarea","select"],Oo=["text","email","number","tel"],Po=5,Do=8,Bo=64,Lo=5,Mo=12,No=4,Ko=500;function _n(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(_n):!1}var Dr=40,Br=120,Lr=300;var Dt="sentient-reveal",Pe="sentient-revealed",Bt=240,mt=!1;function In(){var e;mt=!1,typeof document!="undefined"&&((e=document.getElementById(Dt))==null||e.remove())}function Go(e){if(mt||e.getElementById(Dt)){mt=!0;return}let t=Je(e.createElement("style"),e);t.id=Dt,t.textContent=`@media (prefers-reduced-motion: no-preference){@keyframes ${Pe}{from{opacity:.55;transform:translateY(2px)}to{opacity:1;transform:none}}.${Pe}{animation:${Pe} ${Bt}ms cubic-bezier(.2,.6,.2,1) both}}`,e.head.appendChild(t),mt=!0}function An(e,t={}){var p;let n=(p=t.doc)!=null?p: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;Go(n),e.classList.remove(Pe),e.offsetWidth,e.classList.add(Pe);let i=()=>{e.classList.remove(Pe),e.removeEventListener("animationend",i)};return e.addEventListener("animationend",i),!0}function Rn(e,t,n,i){let p=[];{let o=!1,f=[],a=()=>{if(o)return;let s=Date.now();for(f.push(s);f.length>0&&s-f[0]>500;)f.shift();f.length>=3&&(o=!0,e("rage_click"))};t.addEventListener("click",a),p.push(()=>t.removeEventListener("click",a))}{let u=!1,y=o=>{if(u||!(o.target instanceof Node)||!t.contains(o.target)&&t!==o.target)return;u=!0;let f=typeof window!="undefined"?window.getSelection():null,a=f?f.toString().length:0;e("text_copy",{selectionLength:a})};document.addEventListener("copy",y),p.push(()=>document.removeEventListener("copy",y))}{let u=!1,y=!1,o=null,f=()=>{o!==null&&(clearTimeout(o),o=null)},a=()=>{u||!y||(f(),o=setTimeout(()=>{!u&&y&&(u=!0,e("scroll_hesitation"))},3e3))},s=()=>{f(),a()},c=T=>{for(let C of T)y=C.intersectionRatio>.3,y?a():f()},v=new IntersectionObserver(c,{threshold:[.3]});v.observe(t),window.addEventListener("scroll",s,{passive:!0}),p.push(()=>{v.disconnect(),window.removeEventListener("scroll",s),f()})}if((i==null?void 0:i.tabLoss)!==!1){let u=!1,y=n!=null?n:Date.now(),o=()=>{if(u||document.visibilityState!=="hidden")return;let f=Date.now()-y;f<15e3&&(u=!0,e("tab_loss",{timeOnPage:f}))};document.addEventListener("visibilitychange",o),p.push(()=>document.removeEventListener("visibilitychange",o))}return()=>{for(let u of p)u()}}function Uo(){var e;return typeof process=="undefined"||((e=process.env)==null?void 0:e.NODE_ENV)!=="production"}var On="https://api.sentient-ui.com/v1/events",q=new Map,Pn=null;function $o(e,t){let n=q.get(e);n&&n.upgrade&&(n.reinit=t)}function Fo(e){return"value"in e||"currency"in e||"externalId"in e||"metadata"in e||"weight"in e||"stepIndex"in e}var jo=3;function Lt(){return nt()}function yt(){var e;if(typeof window!="undefined")return((e=window.location)==null?void 0:e.pathname)||void 0}function Wo(){let e=new WeakMap,t=new Map,n=!1,i=(o,f,a)=>{let s=o.get(f);return a===null?s?!0:(o.set(f,new Set),!1):s?s.has(a)?!0:(s.add(a),!1):(o.set(f,new Set([a])),!1)},p=typeof window!="undefined"&&"event"in window,u=()=>{if(!p)return;let o=window.event;return typeof Event=="function"&&o instanceof Event?o:void 0},y=()=>{if(p){Promise.resolve().then(()=>{n=!1,t.clear()});return}let o=!1,f=()=>{o||(o=!0,n=!1,t.clear())};if(setTimeout(f,0),typeof MessageChannel=="function"){let a=new MessageChannel;a.port1.onmessage=()=>{a.port1.close(),a.port2.close(),f()},a.port2.postMessage(0)}};return{firedBefore(o,f){let a=u();if(a){let c=e.get(a);return c||(c=new Map,e.set(a,c)),i(c,o,f)}let s=i(t,o,f);return!s&&!n&&(n=!0,y()),s}}}var Dn=new Set;function Vo(e,t,n){let i=typeof window=="undefined"?null:window.history;if(!i)return()=>{};let p=!1,u,y=()=>{if(p)return;let a=yt();!a||a===u||(u=a,e.track({projectId:t,componentId:"__page__",eventType:"pageview",payload:{}}),n(`${t}:${a}`))},o=[];for(let a of["pushState","replaceState"]){let s=i[a],c=function(...v){let T=s.apply(this,v);return y(),T};i[a]=c,o.push([a,s,c])}window.addEventListener("popstate",y);let f=yt();return f&&Dn.has(`${t}:${f}`)?u=f:y(),()=>{if(!p){p=!0,window.removeEventListener("popstate",y);for(let[a,s,c]of o)i[a]===c&&(i[a]=s)}}}var He={track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},getAssignment:()=>null,assign:()=>Promise.resolve(null),decide:()=>Promise.resolve(null),getSlotResult:()=>null,getSlotConfig:()=>null,getSitePalette:()=>null,reportSlots:()=>{},getPersona:()=>null,getVisitorId:()=>null,fetchWeights:()=>Promise.resolve([]),getGraph:()=>({pageNodes:[],capturedAt:0}),flush:()=>{},dispose:()=>{},destroy:()=>{}};function Ho(){try{return at(window.location.search)}catch(e){return{utmParams:{},clickIds:{}}}}function Bn(e){return e.replace(/\/events\/?$/,"")}function Ut(){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 zo(e){var f;if(typeof window=="undefined")return;let t=e!=null?e:Pn;if(!t){console.warn("[sentient] grantConsent() called before init()");return}let n=q.get(t);if(!n){console.warn("[sentient] grantConsent() called before init()");return}let{config:i,upgrade:p,reinit:u}=n;if(!p){n.upgradeBlockedReason&&console.warn(n.upgradeBlockedReason);return}if(i.respectDoNotTrack!==!1&&Ut())return;let y=(u!=null?u:Ln)(Se(A({},i),{consent:!0}));p(y);let o=(f=q.get(t))==null?void 0:f.dispose;q.set(t,{config:Se(A({},i),{consent:!0}),upgrade:null,dispose:o})}function Qo(e,t){var $;let n=e.preConsentBehavior==="statistical_winner",i=Bn(($=e.ingestUrl)!=null?$:On),p={"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`},u=new Map,y=new Map,o={track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},getAssignment:()=>null,fetchWeights:()=>Promise.resolve([]),assign(d,m,h){if(!n)return Promise.resolve(null);let g=u.get(d);return g?Promise.resolve(g):Gt(y,d,async()=>{try{let _=new URLSearchParams({componentId:d});for(let ee of m!=null?m:[])_.append("variantIds[]",ee);let N=ue(5e3),F;try{let ee=await fetch(`${i}/winner?${_.toString()}`,{headers:p,signal:N.signal});if(!ee.ok)return m!=null&&m[0]?{variantId:m[0],assignmentTtlMs:0}:null;F=await ee.json()}finally{N.clear()}let O={variantId:F.variantId,assignmentTtlMs:0};return u.set(d,O),O}catch(_){return m!=null&&m[0]?{variantId:m[0],assignmentTtlMs:0}:null}})},decide:()=>Promise.resolve(null),getSlotResult:()=>null,getSlotConfig:()=>null,getSitePalette:()=>null,reportSlots:()=>{},getPersona:()=>null,getVisitorId:()=>null,getGraph:()=>({pageNodes:[],capturedAt:0}),flush:()=>{},dispose:()=>{},destroy:()=>{}},f=!1,a=new Set,s=[],c=[],v=[],T=()=>{for(let[,,d]of v.splice(0))d(null);C.length=0},C=[],D=!1,M=()=>{if(f)return;D=!0;let d=q.get(e.apiKey);(d==null?void 0:d.upgrade)===Q&&q.set(e.apiKey,{config:e,upgrade:null,upgradeBlockedReason:"[sentient] grantConsent(): client released before consent; call init() again"})},V=[],H=()=>{setTimeout(()=>{var d;try{(d=V.shift())==null||d(o)}catch(m){}V.length&&H()})},z=d=>{f?V.length?V.push(d):d(o):!t&&!D&&C.length<100?C.push(d):D&&e.debug&&console.warn("[sentient] goal dropped: client released")},X={get gated(){return!f&&!t},get released(){return D&&!f},takeHeld:()=>C.splice(0),track:d=>o.track(d),goal:((d,m,h,g)=>z(_=>_.goal(d,m,h,g))),componentGoal:(d,m,h)=>o.componentGoal(d,m,h),identify:d=>o.identify(d),getAssignment:(d,m)=>o.getAssignment(d,m),isUnified:d=>{var m,h;return(h=(m=o.isUnified)==null?void 0:m.call(o,d))!=null?h:!1},assign:(d,m,h,g,_)=>o.assign(d,m,h,g,_),decide:d=>f?o.decide(d):D||t?Promise.resolve(null):new Promise(m=>v.push([d,Kt(),m])),getSlotResult:d=>o.getSlotResult(d),isSlotDecided:d=>{var m,h;return(h=(m=o.isSlotDecided)==null?void 0:m.call(o,d))!=null?h:!0},getSlotConfig:d=>o.getSlotConfig(d),getSitePalette:()=>o.getSitePalette(),getStyleVocabulary:()=>{var d,m;return(m=(d=o.getStyleVocabulary)==null?void 0:d.call(o))!=null?m:null},reportSlots:(d,m,h,g)=>o.reportSlots(d,m,h,g),reportSkeleton:(d,m)=>{var h;return(h=o.reportSkeleton)==null?void 0:h.call(o,d,m)},reportAgentData:(d,m,h)=>{var g;return(g=o.reportAgentData)==null?void 0:g.call(o,d,m,h)},reportDrift:(d,m,h,g)=>{var _;return(_=o.reportDrift)==null?void 0:_.call(o,d,m,h,g)},requestSlots:(d,m,h)=>{var g;return f?(g=o.requestSlots)==null?void 0:g.call(o,d,m,h):s.push([d,m,h])},decideSlots:d=>{var m;return f?(m=o.decideSlots)==null?void 0:m.call(o,d):c.push(...d)},cancelSlots:d=>{var h;if(f)return(h=o.cancelSlots)==null?void 0:h.call(o,d);let m=new Set(d);for(let g of s)g[0]=g[0].filter(_=>!m.has(_));c=c.filter(g=>!m.has(g.id))},onSlotsChanged:d=>(a.add(d),()=>{a.delete(d)}),getPersona:()=>o.getPersona(),getVisitorId:()=>{var d,m;return(m=(d=o.getVisitorId)==null?void 0:d.call(o))!=null?m:null},fetchWeights:()=>o.fetchWeights(),getGraph:()=>o.getGraph(),flush:()=>o.flush(),dispose:()=>(M(),T(),o.dispose()),destroy:()=>(M(),T(),f?o.destroy():tt(e.apiKey))};function Q(d){var h,g,_;o=d,f=!0,C.length&&(V.push(...C.splice(0)),H());let m=Kt();for(let[N,F,O]of v.splice(0))F!==m?O(null):d.decide(N).then(O,()=>O(null));(h=d.onSlotsChanged)==null||h.call(d,()=>a.forEach(N=>N()));for(let[N,F,O]of s.splice(0))N.length>0&&((g=d.requestSlots)==null||g.call(d,N,F,O));c.length>0&&((_=d.decideSlots)==null||_.call(d,c.splice(0)))}return{proxy:X,setInner:Q}}function Kt(){return typeof location=="undefined"?"":location.pathname+(/^#!?\//.test(location.hash)?location.hash:"")}function Gt(e,t,n){let i=e.get(t);if(i)return i;let p=(async()=>{try{return await n()}finally{e.delete(t)}})();return e.set(t,p),p}function Ln(e){var Vt,Ht,zt,Qt,Xt,Jt,qt,Yt,Zt,en,tn;if(typeof window=="undefined")return He;e.nonce&&Xe(e.nonce),Pn=e.apiKey||"local";let t=q.get(e.apiKey||"local");if(t!=null&&t.dispose)try{t.dispose()}catch(r){}let n=e.respectDoNotTrack!==!1&&Ut(),i=e.consent===!1||n,p=typeof e.apiKey=="string"&&e.apiKey.startsWith("pk_");if(e.localMode===!0||!p&&e.localMode!==!1)return q.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."}),i?He:kn(e);if(i){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."),q.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."}),He;let{proxy:r,setInner:l}=Qo(e,n);return q.set(e.apiKey,{config:e,upgrade:n?null:l}),r}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."),He;if(e.ingestUrl==="")return console.warn("[sentient] init() called with an empty ingestUrl. SDK disabled."),He;let u=(Vt=e.ingestUrl)!=null?Vt:On,y=Date.now(),o=rt({ssrSessionId:e.ssrSessionId,apiKey:e.apiKey}),f=fn(void 0,e.apiKey),a=!1,s=se(e.apiKey),c=()=>!a&&se(e.apiKey)===s,v=new Set((Ht=e.initialUnified)!=null?Ht:[]),T=Se(A({},f),{get:(r,l)=>v.has(r)?null:f.get(r,l),set:(...r)=>{c()&&f.set(...r)}}),C=dn({ingestUrl:u,apiKey:e.apiKey}),D=Bn(u),M={"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`},V=new Set,H=un({url:`${D}/goals`,apiKey:e.apiKey,headers:M,onDrop:(r,l)=>{if(!e.debug){if(V.has(l))return;V.add(l)}console.warn(`[sentient] goal dropped (HTTP ${l}) \u2014 this will not be retried. `+(l===400?"The session was not found: call init() and let the session upsert complete before firing goals.":l===401||l===403?"Check the API key and that this origin is on the project allowlist.":"See the response status for the cause."),r)}}),z=$e((zt=navigator.userAgent)!=null?zt:""),X=window.location.origin,Q=Fe((Qt=document.referrer)!=null?Qt:"",X),$=(Xt=e.sessionSegment)!=null?Xt:`${z}:${Q}`,d=new Map,m=new Map,h=new Map,g=new Set,_=new Map,N=null,F=null,O=null,ee=new Set,ie=new Set,k=new Map,B=new Map,ge=new Set,be=new Set,te=new Set,ke=new Set,xe=null,oe=/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,127}$/,we=new Set,ae=new Set,ze=new Set,De=new Map,St=null,Qe=new Set,Be=new Map,ht=null,Mn=2,$t=new Map,re=!1,Ft=(r,l,S)=>{var b;let I=new Set,R=1;for(let x of r){l.delete(x);let w=((b=$t.get(x))!=null?b:0)+1;$t.set(x,w),w<=Mn&&(I.add(x),w>R&&(R=w))}I.size>0&&setTimeout(()=>{re||S(I)},me(R))},bt=r=>{for(let l of r)h.has(l.id)||h.set(l.id,Oe(l))};if(e.initialSlots)for(let[r,l]of Object.entries(e.initialSlots))h.set(r,l),g.add(r);if(e.initialSlotConfig)for(let[r,l]of Object.entries(e.initialSlotConfig))_.set(r,l);e.initialPalette&&(N=e.initialPalette),e.initialVocabulary&&(F=e.initialVocabulary);let le=Ie(e.apiKey);if(le){for(let[r,l]of Object.entries(le.slots))h.has(r)||h.set(r,l);for(let[r,l]of Object.entries((Jt=le.slotConfig)!=null?Jt:{}))_.has(r)||_.set(r,l);!N&&le.palette&&(N=le.palette),!F&&le.vocabulary&&(F=le.vocabulary)}let jt={low:.15,medium:.5,high:.85};if(e.initialPersona)O=A({},e.initialPersona);else{let r=document.documentElement.dataset;r.sentientPersona?O={persona:r.sentientPersona,confidence:(Yt=jt[(qt=r.sentientConfidence)!=null?qt:"low"])!=null?Yt:.15}:le&&(O={persona:le.persona,confidence:(Zt=jt[le.band])!=null?Zt:.15})}if(e.initialAssignments)for(let[r,l]of Object.entries(e.initialAssignments))T.set(r,$,{variantId:l,assignedAt:Date.now(),segment:$,confidence:1});let ye=Promise.resolve(),Wt=o.getSessionId();if(Wt){let r=je((en=document.referrer)!=null?en:""),{utmParams:l,clickIds:S}=Ho(),I=A(A(A(A({sessionId:Wt,deviceClass:z,trafficSource:Q,referrerDomain:r,utmParams:l,clickIds:S,landingPath:typeof location!="undefined"?location.pathname:void 0,timeOfDay:We(new Date),dayOfWeek:["sun","mon","tue","wed","thu","fri","sat"][new Date().getDay()],ephemeral:o.isEphemeral(),automation:typeof navigator!="undefined"&&navigator.webdriver===!0||Ue((tn=navigator.userAgent)!=null?tn:"")},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}:{}),R=async()=>{for(let b=0;;b++){if(re||!c())return;let x=ue(5e3);try{let w=await fetch(`${D}/sessions`,{method:"POST",keepalive:!0,body:JSON.stringify(I),headers:M,signal:x.signal});if(w.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(w.ok||Re(w)==="dropped")return}catch(w){}finally{x.clear()}if(b>=jo){console.warn("[SentientUI] Could not register the session after retries. Conversions in this visit may not be recorded.");return}await new Promise(w=>setTimeout(w,me(b+1)))}};try{ye=R()}catch(b){}}e.debug&&(console.log("[sentient] initialized",{context:e.context}),window.__sentient={client:null,queue:C});let Nn=Wo(),ve=null,vt=!1,W={goal(r,l={},S=1,I=0){var j,L,Y,ne,Z,J,E;let R=o.getSessionId();if(!R||re||!c())return;let b=Fo(l)?l:{metadata:l},x=[r,(j=b.externalId)!=null?j:"",(L=b.stepIndex)!=null?L:I,(Y=b.weight)!=null?Y:S].join("\0"),w=b.value!==void 0?`${b.value}\0${(ne=b.currency)!=null?ne:""}`:null;if(Nn.firedBefore(x,w)){e.debug&&console.log(`[sentient] goal("${r}") already recorded for this action \u2014 not sent twice`);return}let K=Lt(),P={sessionId:R,name:r,metadata:(Z=b.metadata)!=null?Z:{},weight:(J=b.weight)!=null?J:S,stepIndex:(E=b.stepIndex)!=null?E:I,goalId:K,value:b.value,currency:b.currency,externalId:b.externalId};e.debug&&console.log("[sentient] goal",P);let G={id:K,body:JSON.stringify(P)};ye.then(()=>H.send(G))},componentGoal(r,l,S){var K,P,G;let I=o.getSessionId();if(!I||re||!c())return;let R=T.get(r,$),b=R?null:(K=h.get(r))!=null?K:null;if(!R&&b===null){e.debug&&console.warn(`[sentient] componentGoal("${r}"): no assignment or slot decision yet \u2014 render its <Adaptive>/adaptive hook or call assign()/decide() before recording a goal.`);return}if(!R&&!g.has(r)){e.debug&&console.warn(`[sentient] componentGoal("${r}"): slot not decided this session \u2014 not attributed`);return}let x=R?R.variantId:lt(b),w={id:Lt(),sessionId:I,projectId:e.apiKey,componentId:r,variantId:x,eventType:"goal_achieved",goalType:l,payload:A({reward:(P=S==null?void 0:S.reward)!=null?P:1,goalValue:S==null?void 0:S.value,currency:S==null?void 0:S.currency},(G=S==null?void 0:S.metadata)!=null?G:{}),timestamp:Date.now(),timeInSession:Date.now()-y,path:yt()};e.debug&&console.log("[sentient] componentGoal",w),ye.then(()=>{!re&&c()&&C.push(w)})},identify(r){let l=o.getSessionId();!l||re||!c()||ye.then(()=>{fetch(`${D}/sessions`,{method:"POST",keepalive:!0,body:JSON.stringify({sessionId:l,userId:r,ephemeral:o.isEphemeral()}),headers:M}).catch(()=>{})})},track(r){let l=o.getSessionId();if(!l||re||!c()||r.eventType==="variant_assigned"&&h.get(r.componentId)!==void 0&&!g.has(r.componentId)&&!T.get(r.componentId,$))return;let S=Se(A({path:yt()},r),{id:Lt(),sessionId:l,timestamp:Date.now(),timeInSession:Date.now()-y});e.debug&&console.log("[sentient] track",S),ye.then(()=>C.push(S))},getAssignment(r,l){return T.get(r,l)},isUnified:r=>v.has(r),async assign(r,l,S,I,R){var K;let b=o.getSessionId();if(!b)return null;let x=(R==null?void 0:R.unified)===!0;if(x&&v.has(r))return{variantId:(K=l==null?void 0:l[0])!=null?K:"",assignmentTtlMs:0,unified:!0};let w=T.get(r,$);if(w&&(l!=null&&l.length||w.content!==void 0)){let P=w.ttlMs&&w.ttlMs>0?Math.max(0,w.assignedAt+w.ttlMs-Date.now()):0;return{variantId:w.variantId,assignmentTtlMs:P,content:w.content}}return Gt(d,x?`${r}\0unified`:r,async()=>{if(!await kt(ye,2500)||re||!c())return null;let P=ue(3e4);try{let G={sessionId:b,componentId:r,variantIds:l};I!==void 0?G.agentDataByVariant=I:S!==void 0&&(G.agentData=S),x&&(G.caps={unified:!0});let j=await fetch(`${D}/assign`,{method:"POST",body:JSON.stringify(G),headers:M,signal:P.signal});if(!j.ok)return null;let L=await j.json();return L.unified===!0?x?(v.add(r),{variantId:L.variantId,assignmentTtlMs:0,unified:!0}):null:(T.set(r,$,A({variantId:L.variantId,assignedAt:Date.now(),segment:$,confidence:1,content:L.content},L.assignmentTtlMs&&L.assignmentTtlMs>0?{ttlMs:L.assignmentTtlMs}:{})),L)}catch(G){return null}finally{P.clear()}})},async decide(r){var b,x;let l=o.getSessionId();if(!l)return null;let S=(b=r.slots)!=null?b:[],I={sessionId:l};r.sections&&r.sections.length>0&&(I.sections=r.sections.map(w=>({id:w}))),I.components=(x=r.components)!=null?x:[],S.length>0&&(I.slots=S.map(Ve)),r.slotsFrom==="registry"&&(I.slotsFrom="registry",r.registrySlotIds&&(I.registrySlotIds=r.registrySlotIds),r.bootstrap===!1&&(I.bootstrap=!1),r.render&&Object.keys(r.render).length>0&&(I.render=r.render)),r.v&&(I.v=r.v),typeof r.pp=="number"&&(I.pp=r.pp),e.persona&&(I.persona=e.persona);let R=JSON.stringify(I);return Gt(m,R,async()=>{var K,P,G,j,L,Y,ne,Z;if(!await kt(ye,2500)||re||!c())return bt(S),null;let w=ue(3e4);try{let J=await fetch(`${D}/decide`,{method:"POST",body:R,headers:M,signal:w.signal});if(!J.ok)return bt(S),null;let E=await J.json(),ce=dt(E.stage,e.stageAttributes);e.stageAttributes&&ut(ce);let Ee={};for(let U of S){let de=(K=E.slots)==null?void 0:K[U.id];if(de!==void 0){Ee[U.id]=de,h.set(U.id,de),g.add(U.id);continue}let nn=h.get(U.id);if(nn!==void 0)Ee[U.id]=nn;else{let on=Oe(U);Ee[U.id]=on,h.set(U.id,on)}}if(E.slots)for(let[U,de]of Object.entries(E.slots))U in Ee||(Ee[U]=de,h.set(U,de),g.add(U));let Kn=O!=null&&O.persona!=="unknown";E.persona&&!(E.persona==="unknown"&&Kn)?O={persona:E.persona,confidence:(P=E.confidence)!=null?P:0}:O||(O={persona:"unknown",confidence:0});for(let[U,de]of Object.entries((G=E.assignments)!=null?G:{}))T.set(U,$,{variantId:de,assignedAt:Date.now(),segment:$,confidence:1});if(E.slotConfig)for(let[U,de]of Object.entries(E.slotConfig))_.set(U,de);E.palette&&(N=E.palette),E.vocabulary&&(F=E.vocabulary);for(let U of(j=r.registrySlotIds)!=null?j:[])(L=E.slotConfig)!=null&&L[U]||(_.delete(U),h.delete(U),g.delete(U));return c()&&Ae(e.apiKey,A(A(A(A({v:1,persona:O.persona,band:(0,Nt.confidenceBand)(O.confidence),slots:Object.fromEntries(h),layoutOrder:(Y=E.layoutOrder)!=null?Y:null,savedAt:Date.now()},_.size>0?{slotConfig:Object.fromEntries(_)}:{}),N?{palette:N}:{}),F?{vocabulary:F}:{}),ce?{stage:ce}:{})),A(A(A(A(A(A(A({layoutOrder:(ne=E.layoutOrder)!=null?ne:null,assignments:(Z=E.assignments)!=null?Z:{},slots:Ee,persona:O.persona,confidence:O.confidence},E.slotConfig?{slotConfig:E.slotConfig}:{}),E.goals?{goals:E.goals}:{}),E.sectionMap?{sectionMap:E.sectionMap}:{}),E.palette?{palette:E.palette}:{}),E.vocabulary?{vocabulary:E.vocabulary}:{}),E.stage?{stage:E.stage}:{}),E.context?{context:E.context}:{})}catch(J){return bt(S),null}finally{w.clear()}})},getSlotResult(r){var l;return(l=h.get(r))!=null?l:null},isSlotDecided(r){return g.has(r)},getSlotConfig(r){var l;return(l=_.get(r))!=null?l:null},reportSlots(r,l,S,I){var b;let R={};for(let[x,w]of Object.entries(I!=null?I:{}))for(let K of w){let P=`${x}|${K.key}`;!oe.test(x)||te.has(P)||(te.add(P),((b=R[x])!=null?b:R[x]=[]).push(K))}Object.keys(R).length>0&&fetch(`${D}/slots/observed`,{method:"POST",headers:M,body:JSON.stringify({slotIds:Object.keys(R),authoredArms:R})}).catch(()=>{});for(let x of r)if(!(typeof x!="string"||x.length===0)){if(!oe.test(x)){Uo()&&!we.has(x)&&(we.add(x),console.warn(`[sentient] reportSlots: slot id ${JSON.stringify(x)} 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(!ee.has(x)){ee.add(x),ie.add(x);let w=l==null?void 0:l[x];if(typeof w=="string"){let P=w.replace(/\s+/g," ").trim().slice(0,400);P!==""&&k.set(x,P)}let K=S==null?void 0:S[x];K!==void 0&&B.set(x,K)}}ie.size===0||xe!=null||(xe=setTimeout(()=>{xe=null;let x=[...ie];ie.clear();for(let w=0;w<x.length;w+=20){let K=x.slice(w,w+20),P={},G={};for(let j of K){let L=k.get(j);L!==void 0&&(P[j]=L,k.delete(j));let Y=B.get(j);Y!==void 0&&(G[j]=Y,B.delete(j))}fetch(`${D}/slots/observed`,{method:"POST",headers:M,body:JSON.stringify(A(Se(A(A({slotIds:K},Object.keys(P).length>0?{baselineTexts:P}:{}),Object.keys(G).length>0?{baselineSkeletons:G}:{}),{pagePaths:Object.fromEntries(K.map(j=>[j,location.pathname]))}),Object.keys(P).length>0&&o.getSessionId()?{sessionId:o.getSessionId()}:{}))}).catch(()=>{})}},1e3))},reportSkeleton(r,l){!oe.test(r)||ge.has(r)||(ge.add(r),fetch(`${D}/slots/observed`,{method:"POST",headers:M,body:JSON.stringify({slotIds:[r],baselineSkeletons:{[r]:l}})}).catch(()=>{}))},reportAgentData(r,l,S){let I=`${r}|${l}`;!oe.test(r)||ke.has(I)||(ke.add(I),fetch(`${D}/slots/observed`,{method:"POST",headers:M,body:JSON.stringify(A(A({slotIds:[r],agentData:{[r]:{[l]:S}}},l.startsWith("authored.")?{authoredArms:{[r]:[{key:l.slice(9)}]}}:{}),o.getSessionId()?{sessionId:o.getSessionId()}:{}))}).catch(()=>{}))},reportDrift(r,l,S,I){let R=`${r}|${l}`,b=o.getSessionId();!b||be.has(R)||(be.add(R),fetch(`${D}/slots/drift`,{method:"POST",headers:M,body:JSON.stringify({sessionId:b,reports:[{slotId:r,expectedFp:l,observedFp:S,reason:I}]})}).catch(()=>{}))},requestSlots(r,l,S){var I,R;for(let b of r)ze.has(b)||(ze.add(b),oe.test(b)?De.set(b,{text:l==null?void 0:l[b],render:(I=S==null?void 0:S.render)==null?void 0:I[b],skeleton:(R=S==null?void 0:S.skeletons)==null?void 0:R[b]}):W.reportSlots([b]));De.size===0||St!=null||(St=setTimeout(()=>{St=null;let b=[...De];De.clear();for(let x=0;x<b.length;x+=50){let w=b.slice(x,x+50),K={};for(let[P,G]of w)G.render&&(K[P]=G.render);W.decide({slotsFrom:"registry",registrySlotIds:w.map(([P])=>P),bootstrap:!1,render:K}).then(P=>{var G,j;if(P){let L={},Y={},ne=[];for(let[Z,J]of w){let E=(G=P.slotConfig)==null?void 0:G[Z];if(E){E.needsSkeleton&&J.skeleton&&((j=W.reportSkeleton)==null||j.call(W,Z,J.skeleton));continue}ne.push(Z),J.text&&(L[Z]=J.text),J.skeleton&&(Y[Z]=J.skeleton)}ne.length>0&&W.reportSlots(ne,L,Y)}else Ft(w.map(([L])=>L),ze,L=>{var J;let Y={},ne={},Z={};for(let[E,ce]of w)L.has(E)&&(ce.text&&(Y[E]=ce.text),ce.render&&(ne[E]=ce.render),ce.skeleton&&(Z[E]=ce.skeleton));(J=W.requestSlots)==null||J.call(W,[...L],Y,{render:ne,skeletons:Z})});ae.forEach(L=>L())})}},0))},decideSlots(r){for(let l of r)Qe.has(l.id)||(Qe.add(l.id),Be.set(l.id,l));Be.size===0||ht!=null||(ht=setTimeout(()=>{ht=null;let l=[...Be.values()];Be.clear();for(let S=0;S<l.length;S+=30){let I=l.slice(S,S+30);W.decide({slots:I}).then(R=>{R||Ft(I.map(b=>b.id),Qe,b=>{var x;return(x=W.decideSlots)==null?void 0:x.call(W,I.filter(w=>b.has(w.id)))}),ae.forEach(b=>b())})}},0))},cancelSlots(r){for(let l of r)De.delete(l)&&ze.delete(l),Be.delete(l)&&Qe.delete(l)},onSlotsChanged(r){return ae.add(r),()=>{ae.delete(r)}},getStyleVocabulary(){return F},getSitePalette(){return N},getVisitorId:()=>c()?o.getSessionId():null,getPersona(){return O?{persona:O.persona,confidence:O.confidence,band:(0,Nt.confidenceBand)(O.confidence)}:null},async fetchWeights(){var l;let r=ue(5e3);try{let S=await fetch(`${D}/weights`,{headers:M,signal:r.signal});return S.ok?(l=(await S.json()).components)!=null?l:[]:[]}catch(S){return[]}finally{r.clear()}},getGraph(){return{pageNodes:[],capturedAt:0}},flush(){C.flush(),H.flush()},dispose(){var r;ve==null||ve(),vt=!0,re=!0,C.destroy(),H.destroy(),((r=q.get(e.apiKey))==null?void 0:r.dispose)===W.dispose&&q.delete(e.apiKey),e.debug&&console.log("[sentient] disposed")},destroy(){var r;ve==null||ve(),vt=!0,re=!0,a=!0,Ye(e.apiKey),C.destroy({forget:!0}),H.destroy({forget:!0}),o.destroy(),T.clear(),((r=q.get(e.apiKey))==null?void 0:r.dispose)===W.dispose&&q.delete(e.apiKey);try{localStorage.removeItem(fe+e.apiKey),localStorage.removeItem(Ne(e.apiKey)),localStorage.removeItem(Ke(e.apiKey)),localStorage.removeItem(`_snt_graph_nodes${pe(e.apiKey)}`),localStorage.removeItem("_snt_graph_edges")}catch(l){}e.debug&&console.log("[sentient] destroyed")}};if(q.set(e.apiKey,{config:e,upgrade:null,dispose:W.dispose}),ve=Vo(W,e.apiKey,r=>{ye.then(()=>{vt||Dn.add(r)})}),e.debug){let r=window;r.__sentient&&(r.__sentient.client=W)}return W}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,MAX_SKELETON_LEAVES,MAX_SKELETON_NODES,MAX_SKELETON_TEXT,PAGE_SCOPE_RE,PROD_KEYLESS_ERROR,REVEAL_MS,SNAPSHOT_STORAGE_KEY_PREFIX,STAGE_ATTRIBUTE,_registerConsentUpgradeInit,agentIntent,agentUaList,applyNonce,armOfResult,attachMicroSignalDetectors,baselineResultFor,baselineSlots,classifiedAgents,containsFormBlock,cspNonce,deriveSessionSegment,detectDeviceClass,detectTimeOfDay,detectTrafficSource,exposedStage,extractTrackedParams,forgetGeneration,forgetVisitor,grantConsent,init,isDoNotTrackEnabled,matchedAgentToken,normalizeUrlPattern,pageScopeMatches,readSnapshot,referrerDomainFromReferer,renderPrePaintScript,resetRevealStyles,reveal,routeKey,sessionCookieName,setCspNonce,setStageAttribute,toWireSlot,uaTokenMatch,urlMatches,writeSnapshot});
|
|
1
|
+
"use strict";var Fn=Object.create;var Me=Object.defineProperty,jn=Object.defineProperties,Wn=Object.getOwnPropertyDescriptor,Vn=Object.getOwnPropertyDescriptors,Hn=Object.getOwnPropertyNames,an=Object.getOwnPropertySymbols,zn=Object.getPrototypeOf,cn=Object.prototype.hasOwnProperty,Qn=Object.prototype.propertyIsEnumerable;var ln=(e,t,n)=>t in e?Me(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,A=(e,t)=>{for(var n in t||(t={}))cn.call(t,n)&&ln(e,n,t[n]);if(an)for(var n of an(t))Qn.call(t,n)&&ln(e,n,t[n]);return e},Se=(e,t)=>jn(e,Vn(t));var Xn=(e,t)=>{for(var n in t)Me(e,n,{get:t[n],enumerable:!0})},dn=(e,t,n,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let g of Hn(t))!cn.call(e,g)&&g!==n&&Me(e,g,{get:()=>t[g],enumerable:!(s=Wn(t,g))||s.enumerable});return e};var Jn=(e,t,n)=>(n=e!=null?Fn(zn(e)):{},dn(t||!e||!e.__esModule?Me(n,"default",{value:e,enumerable:!0}):n,e)),qn=e=>dn(Me({},"__esModule",{value:!0}),e);var qo={};Xn(qo,{AGENT_INTENTS:()=>dt,BLOCK_ALIGNS:()=>ho,BLOCK_EMPHASES:()=>wo,BLOCK_FITS:()=>Io,BLOCK_GAPS:()=>So,BLOCK_GRID_COLUMNS:()=>Ao,BLOCK_HEADING_LEVELS:()=>Co,BLOCK_JUSTIFIES:()=>bo,BLOCK_MAX_WIDTHS:()=>Oo,BLOCK_PADS:()=>To,BLOCK_RATIOS:()=>_o,BLOCK_SIZES:()=>vo,BLOCK_SURFACES:()=>Ro,BLOCK_TEXT_ALIGNS:()=>Eo,BLOCK_TONES:()=>xo,BLOCK_WEIGHTS:()=>ko,CLICK_ID_KEYS:()=>Ot,FORM_FIELD_KINDS:()=>Do,FORM_INPUT_TYPES:()=>Po,LEGACY_SESSION_COOKIE_NAME:()=>he,LOCAL_MODE_BANNER:()=>Dt,MAX_BLOCK_ARMS:()=>Go,MAX_BLOCK_CHILDREN:()=>Ko,MAX_BLOCK_DEPTH:()=>No,MAX_BLOCK_NODES:()=>Mo,MAX_BLOCK_TEXT_LEN:()=>Uo,MAX_FORM_FIELDS:()=>Bo,MAX_FORM_SELECT_OPTIONS:()=>Lo,MAX_SKELETON_LEAVES:()=>Gr,MAX_SKELETON_NODES:()=>Kr,MAX_SKELETON_TEXT:()=>Ur,PAGE_SCOPE_RE:()=>Bt,PROD_KEYLESS_ERROR:()=>ht,REVEAL_MS:()=>Mt,SNAPSHOT_STORAGE_KEY_PREFIX:()=>fe,STAGE_ATTRIBUTE:()=>pt,_registerConsentUpgradeInit:()=>jo,agentIntent:()=>hn,agentUaList:()=>Ue,applyNonce:()=>qe,armOfResult:()=>gt,attachMicroSignalDetectors:()=>On,baselineResultFor:()=>De,baselineSlots:()=>kn,classifiedAgents:()=>bn,containsFormBlock:()=>Cn,cspNonce:()=>At,deriveSessionSegment:()=>vn,detectDeviceClass:()=>Fe,detectTimeOfDay:()=>Ve,detectTrafficSource:()=>je,exposedStage:()=>ft,extractTrackedParams:()=>ut,forgetGeneration:()=>se,forgetVisitor:()=>ot,grantConsent:()=>Xo,init:()=>Kn,isDoNotTrackEnabled:()=>Ft,matchedAgentToken:()=>Tt,normalizeUrlPattern:()=>An,pageScopeMatches:()=>_n,readSnapshot:()=>Ie,referrerDomainFromReferer:()=>We,renderPrePaintScript:()=>un,resetRevealStyles:()=>Rn,reveal:()=>Tn,routeKey:()=>Ut,sessionCookieName:()=>_e,setCspNonce:()=>Je,setStageAttribute:()=>mt,toWireSlot:()=>He,uaTokenMatch:()=>$e,urlMatches:()=>In,writeSnapshot:()=>Ae});module.exports=qn(qo);function ue(e){if(typeof AbortController!="function")return{clear:()=>{}};let t=new AbortController,n=setTimeout(()=>t.abort(),e);return{signal:t.signal,clear:()=>clearTimeout(n)}}function _t(e,t){return new Promise(n=>{let s=setTimeout(()=>n(!1),t),g=()=>{clearTimeout(s),n(!0)};e.then(g,g)})}var It;function Je(e){It=typeof e=="string"&&e!==""?e:void 0}function At(e=document){if(It)return It;try{let t=e.querySelector("script[nonce]");return(t==null?void 0:t.nonce)||(t==null?void 0:t.getAttribute("nonce"))||void 0}catch(t){return}}function qe(e,t=document){let n=At(t);return n&&e.setAttribute("nonce",n),e}function pe(e){return e?`_${e.slice(0,12)}`:""}var he="_snt_uid";function _e(e){return`${he}${pe(e)}`}var Ye="__sntForgetGen",Yn=()=>{try{return window[Ye]}catch(e){return}};function Ze(e){var t,n;try{let s=window,g=(t=s[Ye])!=null?t:s[Ye]={};g[e]=((n=g[e])!=null?n:0)+1}catch(s){}}function se(e){var t,n;return(n=(t=Yn())==null?void 0:t[e])!=null?n:0}var fe="_snt_snap:";var Zn=["low","medium","high"];function Ie(e){try{let t=localStorage.getItem(fe+e);if(!t)return null;let n=JSON.parse(t);if(!n||typeof n!="object"||n.v!==1||typeof n.persona!="string"||typeof n.band!="string"||!Zn.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"||!(Date.now()-n.savedAt<2592e6)||!(n.slotConfig===void 0||typeof n.slotConfig=="object"&&n.slotConfig!==null&&!Array.isArray(n.slotConfig)))return null;let s=n.vocabulary;return s!==void 0&&(typeof s!="object"||s===null||!Array.isArray(s.entries)||!Array.isArray(s.images))&&delete n.vocabulary,n.stage!==void 0&&typeof n.stage!="string"&&delete n.stage,n}catch(t){return null}}function Ae(e,t){try{localStorage.setItem(fe+e,JSON.stringify(t))}catch(n){}}function un(e,t){return'(function(){try{var N=navigator,W=window;if(N.doNotTrack=="1"||N.doNotTrack=="yes"||W.doNotTrack=="1"||N.msDoNotTrack=="1"||N.globalPrivacyControl)return;var r=localStorage.getItem('+JSON.stringify(fe+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;if(!('+2592e6+">Date.now()-s.savedAt))return;var d=document.documentElement;"+(t!=null&&t.stage?'if(typeof s.stage=="string"&&!d.hasAttribute("data-sentient-stage"))d.setAttribute("data-sentient-stage",s.stage);':"")+'if(d.hasAttribute("data-sentient-persona"))return;d.setAttribute("data-sentient-persona",s.persona);d.setAttribute("data-sentient-confidence",s.band);}catch(e){}})();'}function me(e){return Math.min(6e4,1e3*2**Math.min(e,6))}function Ce(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 et(e,t){try{let n=localStorage.getItem(e);if(!n)return[];let s=JSON.parse(n);return Array.isArray(s)?(localStorage.removeItem(e),s.slice(-t)):[]}catch(n){return[]}}function Ne(e,t,n){try{let s=(()=>{try{let u=localStorage.getItem(n);if(!u)return[];let S=JSON.parse(u);return Array.isArray(S)?S:[]}catch(u){return[]}})(),g=new Map;for(let u of s)g.set(u.id,u);for(let u of e)g.set(u.id,u);localStorage.setItem(n,JSON.stringify([...g.values()].slice(-t)))}catch(s){}}function tt(e,t){try{let n=localStorage.getItem(t);if(!n)return;let s=JSON.parse(n);if(!Array.isArray(s))return;let g=new Set(e),u=s.filter(S=>!g.has(S.id));if(u.length===s.length)return;u.length===0?localStorage.removeItem(t):localStorage.setItem(t,JSON.stringify(u))}catch(n){}}var eo=500,to=56*1024;function Ke(e){return`_snt_retry_${e.slice(0,12)}`}var no={push:()=>{},flush:()=>{},destroy:()=>{}};function gn(e){var O,ee,ie;if(typeof window=="undefined")return no;let t=(O=e.flushIntervalMs)!=null?O:5e3,n=(ee=e.maxBatchSize)!=null?ee:20,s=(ie=e.maxRetrySize)!=null?ie:100,g=e.ingestUrl,u=e.apiKey,S=Ke(u),o=!1,f=se(u),a=(...k)=>{!o&&se(u)===f&&Ne(...k)},i=[],c=new Set,b=[],R=k=>{for(let B of k)T.delete(B),!c.has(B)&&(c.add(B),b.push(B));for(;b.length>eo;){let B=b.shift();B&&c.delete(B)}tt(k,S)},T=new Set,P=()=>{for(;i.length>s;){let k=i.shift();k&&T.delete(k.id)}},K=k=>{c.has(k.id)||T.has(k.id)||(T.add(k.id),i.push(k),P())},V=k=>{for(let B of k)c.has(B.id)||(T.add(B.id),i.push(B));P()},H=et(S,s);for(let k of H)K(k);let z=0,Q=0,q=(k,B=!0)=>{if(k.length===0)return;let ge=JSON.stringify(k),be=k.map(oe=>oe.id),te,ke=ue(15e3);try{te=fetch(g,{method:"POST",keepalive:!0,signal:ke.signal,body:ge,headers:{"Content-Type":"application/json",Authorization:`Bearer ${u}`}})}catch(oe){a(k,s,S),V(k),Q++,z=Date.now()+me(Q);return}Promise.resolve(te).then(ke.clear,ke.clear);let xe=oe=>{if(Ce(oe)!=="retry"){if(!oe.ok&&B){let we=k.filter(ae=>ae.eventType!=="pageview");if(we.length>0&&we.length<k.length){R(k.filter(ae=>ae.eventType==="pageview").map(ae=>ae.id)),q(we,!1);return}}R(be),Q=0,z=0;return}a(k,s,S),V(k),Q++,z=Date.now()+me(Q)};te&&typeof te.then=="function"?te.then(xe).catch(()=>{a(k,s,S),V(k),Q++,z=Date.now()+me(Q)}):xe(te)},$=typeof TextEncoder!="undefined"?new TextEncoder:null,d=k=>$?$.encode(k).length:k.length,m=k=>{let B=[],ge=2;for(let be of k){let te=d(JSON.stringify(be))+1;if(B.length>0&&ge+te>to||B.length>=n)break;B.push(be),ge+=te}return B},h=()=>{try{if(Date.now()<z)return;for(;i.length>0&&!(Date.now()<z);){let k=i.filter(ge=>!c.has(ge.id));if(i.length=0,k.length===0)break;let B=m(k);if(B.length===0)break;B.length<k.length&&i.push(...k.slice(B.length)),q(B)}}catch(k){}},p=!0,_=null;_=setInterval(()=>{p&&h()},t);let M=()=>{document.visibilityState==="hidden"&&h()},F=()=>{h()};return document.addEventListener("visibilitychange",M),window.addEventListener("pagehide",F),{push(k){K(k),i.length>=n&&h()},flush:h,destroy(k){k!=null&&k.forget&&(o=!0),p=!1,_!==null&&(clearInterval(_),_=null),document.removeEventListener("visibilitychange",M),window.removeEventListener("pagehide",F),h()}}}var oo=200;function Ge(e){return`_snt_goal_retry_${e.slice(0,12)}`}var ro={send:()=>{},flush:()=>{},destroy:()=>{}};function pn(e){var d,m,h;if(typeof window=="undefined")return ro;let t=(d=e.flushIntervalMs)!=null?d:5e3,n=(m=e.maxRetrySize)!=null?m:100,s=(h=e.maxPerFlush)!=null?h:5,g=Ge(e.apiKey),u=!1,S=se(e.apiKey),o=(...p)=>{!u&&se(e.apiKey)===S&&Ne(...p)},f=[],a=new Set,i=new Set,c=[],b=0,R=0,T=!1,P=p=>{for(a.delete(p.id),i.has(p.id)||(i.add(p.id),c.push(p.id));c.length>oo;){let _=c.shift();_&&i.delete(_)}tt([p.id],g)},K=p=>{o([p],n,g),!i.has(p.id)&&!a.has(p.id)&&(a.add(p.id),f.push(p)),Date.now()>=b&&(R++,b=Date.now()+me(R))},V=p=>{let _,M=ue(15e3);try{_=fetch(e.url,{method:"POST",keepalive:!0,signal:M.signal,body:p.body,headers:e.headers})}catch(O){K(p);return}let F=O=>{var ie;let ee=Ce(O);if(ee==="retry"){K(p);return}ee==="dropped"&&((ie=e.onDrop)==null||ie.call(e,p,O.status)),P(p),R=0,b=0};Promise.resolve(_).then(M.clear,M.clear),_&&typeof _.then=="function"?_.then(F).catch(()=>K(p)):F(_)},H=()=>{try{if(T||Date.now()<b)return;let p=0;for(;f.length>0&&p<s&&!(Date.now()<b);){let _=f.shift();a.delete(_.id),!i.has(_.id)&&(p++,V(_))}}catch(p){}},z=et(g,n);for(let p of z)a.has(p.id)||(a.add(p.id),f.push(p));z.length>0&&Ne(z,n,g);let Q=setInterval(H,t),q=()=>{document.visibilityState==="hidden"&&H()},$=()=>H();return document.addEventListener("visibilitychange",q),window.addEventListener("pagehide",$),{send(p){if(T){i.has(p.id)||o([p],n,g);return}if(!(i.has(p.id)||a.has(p.id))){if(Date.now()<b){o([p],n,g),a.add(p.id),f.push(p);return}V(p)}},flush:H,destroy(p){p!=null&&p.forget&&(u=!0),clearInterval(Q),document.removeEventListener("visibilitychange",q),window.removeEventListener("pagehide",$),H(),T=!0}}}function nt(e){let t=(e||"").toLowerCase();if(!t.includes(".")||/^[\d.]+$|:/.test(t))return[];let n=t.split("."),s=[];for(let g=n.length-2;g>=0;g--)s.push(n.slice(g).join("."));return s}function ot(e){if(typeof window=="undefined"||!e)return!1;Ze(e);let t=!1,n=_e(e);try{if(new RegExp(`(?:^|; )${n}=`).test(document.cookie)){let S=location.protocol==="https:"?"; Secure":"";for(let o of["",...nt(location.hostname)])document.cookie=`${n}=; max-age=0; SameSite=lax; path=/${o?`; domain=${o}`:""}${S}`;t=!0}}catch(S){}let s=pe(e),g=[n,"_snt_graph_edges",fe+e,Ke(e),Ge(e),`_snt_graph_nodes${s}`],u=[`_snt_asgn${s}_`];for(let S of["localStorage","sessionStorage"])try{let o=window[S];for(let f of g)o.getItem(f)!==null&&(o.removeItem(f),t=!0);for(let f=o.length-1;f>=0;f--){let a=o.key(f);a&&u.some(i=>a.startsWith(i))&&(o.removeItem(a),t=!0)}}catch(o){}try{(new RegExp(`(?:^|; )${he}=[^;]`).test(document.cookie)||localStorage.getItem(he)!==null||sessionStorage.getItem(he)!==null)&&localStorage.setItem(`${he}_tomb${s}`,"1")}catch(S){}return t}function rt(){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)})}var fn="_snt_uid",so=365,Re="_snt_uid";function io(){return rt()}function Te(e){try{let t=document.cookie.match(new RegExp(`(?:^|; )${e}=([^;]*)`));return t?decodeURIComponent(t[1]):null}catch(t){return null}}function yn(){try{return location.protocol==="https:"?"; Secure":""}catch(e){return""}}function at(e,t,n,s){try{document.cookie=`${e}=${encodeURIComponent(t)}; max-age=${n}; SameSite=lax; path=/${s?`; domain=${s}`:""}${yn()}`}catch(g){}}function st(e){try{return localStorage.getItem(e)}catch(t){return null}}function mn(e,t){try{return localStorage.setItem(e,t),!0}catch(n){return!1}}function Rt(e){try{return sessionStorage.getItem(e)}catch(t){return null}}function ao(e,t){try{return sessionStorage.setItem(e,t),!0}catch(n){return!1}}function lo(e){try{sessionStorage.removeItem(e)}catch(t){}}function co(e){try{return document.cookie=`${e}_probe=1; max-age=1; SameSite=lax; path=/${yn()}`,document.cookie.indexOf(`${e}_probe=1`)!==-1}catch(t){return!1}}function uo(e){try{localStorage.removeItem(e)}catch(t){}}function it(e,t){at(e,"",0,t)}var go={getSessionId:()=>null,isEphemeral:()=>!1,domain:null,destroy:()=>{}};function po(e,t){if(e===!1)return null;if(typeof e=="string")return e.replace(/^\./,"");for(let n of nt(location.hostname))if(at(t,"1",10,n),Te(t)==="1")return it(t,n),n;return null}function lt(e){var V,H,z,Q,q,$,d;if(typeof window=="undefined")return go;let t=pe(e==null?void 0:e.apiKey),n=(V=e==null?void 0:e.cookieName)!=null?V:_e(e==null?void 0:e.apiKey),s=`${Re}${t}`,g=`${Re}_tomb${t}`,S=((H=e==null?void 0:e.cookieTTLDays)!=null?H:so)*24*60*60,o=m=>m&&m.length>0?m:null,f=()=>{var m,h;return t&&!(e!=null&&e.cookieName)&&st(g)===null?(h=(m=o(Te(fn)))!=null?m:o(st(Re)))!=null?h:o(Rt(Re)):null},a=po(e==null?void 0:e.cookieDomain,`${n}_dom`),i=o(Te(n)),c=a?(it(n),o(Te(n))):null,b=(d=($=(q=(Q=(z=c!=null?c:i)!=null?z:o(st(s)))!=null?Q:o(Rt(s)))!=null?q:f())!=null?$:o(e==null?void 0:e.ssrSessionId))!=null?d:io();at(n,b,S,a),a&&Te(n)!==b&&(a=null,at(n,b,S));let R=mn(s,b),T=co(n),P=R?!1:ao(s,b),K=!R&&!T&&!P;return{getSessionId:()=>b,isEphemeral:()=>K,domain:a,destroy:()=>{b=null,it(n),it(n,a),uo(s),lo(s),t&&!(e!=null&&e.cookieName)&&(Te(fn)!==null||st(Re)!==null||Rt(Re)!==null)&&mn(g,"1")}}}var fo=1800*1e3;function ct(e,t){return`${encodeURIComponent(e)}:${encodeURIComponent(t)}`}function Sn(e=fo,t){let n=new Map,s=`_snt_asgn${pe(t)}_`,g=(a,i)=>`${s}${encodeURIComponent(a)}:${encodeURIComponent(i)}`,u=a=>{let i=a.slice(s.length),c=i.indexOf(":");if(c<0)return null;try{return{componentId:decodeURIComponent(i.slice(0,c)),segment:decodeURIComponent(i.slice(c+1))}}catch(b){return null}},S=()=>{try{let a=[];for(let i=0;i<localStorage.length;i++){let c=localStorage.key(i);c!=null&&c.startsWith(s)&&a.push(c)}return a}catch(a){return[]}},o=a=>a.assignedAt+(a.ttlMs&&a.ttlMs>0?a.ttlMs:e)<Date.now();return typeof window!="undefined"&&(()=>{for(let a of S())try{let i=localStorage.getItem(a);if(!i)continue;let c=JSON.parse(i);if(o(c)){localStorage.removeItem(a);continue}let b=u(a);if(!b)continue;n.set(ct(b.componentId,b.segment),c)}catch(i){}})(),{get(a,i){let c=n.get(ct(a,i));return c?o(c)?(n.delete(ct(a,i)),null):c:null},set(a,i,c){let b=ct(a,i);n.set(b,c);try{localStorage.setItem(g(a,i),JSON.stringify(c))}catch(R){}},clear(){n.clear();for(let a of S())try{localStorage.removeItem(a)}catch(i){}}}}var Ue=["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 $e(e){return Tt(e)!==null}function Tt(e){var n;if(!e)return null;let t=e.toLowerCase();return(n=Ue.find(s=>t.includes(s.toLowerCase())))!=null?n:null}var dt={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 hn(e){if(!e)return"other";let t=Ue.find(n=>n.toLowerCase()===e.toLowerCase());return t&&dt[t]||"other"}function bn(){var t;let e={user:[],search:[],training:[],other:[]};for(let n of Ue)e[(t=dt[n])!=null?t:"other"].push(n);return e}function Fe(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 je(e,t,n){if(!e)return"direct";try{let s=new URL(e);if(t)try{if(new URL(t).host===s.host)return"direct"}catch(u){}let g=s.hostname.toLowerCase();return n&&`.${g}`.endsWith(`.${n}`)?"direct":/(^|\.)(google|bing|duckduckgo|yahoo)\./.test(g)?"search":/(^|\.)(twitter\.com|x\.com|facebook\.com|linkedin\.com|reddit\.com|t\.co)$/.test(g)?"social":"referral"}catch(s){return"direct"}}function We(e){if(!e)return null;try{return new URL(e).hostname}catch(t){return null}}var Ot=["gclid","gbraid","wbraid","fbclid","ttclid","msclkid","twclid","li_fat_id"];function ut(e){let t={},n={};try{let s=typeof e=="string"||e instanceof URLSearchParams?new URLSearchParams(e):Object.entries(e).flatMap(([g,u])=>{let S=Array.isArray(u)?u[0]:u;return S===void 0?[]:[[g,S]]});for(let[g,u]of s)g.startsWith("utm_")?g in t||(t[g]=u):Ot.includes(g)&&(g in n||(n[g]=u))}catch(s){}return{utmParams:t,clickIds:n}}function Ve(e){let t=e.getHours();return t<6?"night":t<12?"morning":t<18?"afternoon":"evening"}function vn(e){let t=mo("__segment__",e);return`${t.deviceClass}:${t.trafficSource}`}function mo(e,t){var u,S,o,f,a,i,c,b;let n=(S=(u=t==null?void 0:t.userAgent)==null?void 0:u.trim())!=null?S:"",s=(f=(o=t==null?void 0:t.referer)==null?void 0:o.trim())!=null?f:"",g=(a=t==null?void 0:t.now)!=null?a:new Date;return A({sessionId:e,ephemeral:!1,utmParams:(i=t==null?void 0:t.utmParams)!=null?i:{},clickIds:(c=t==null?void 0:t.clickIds)!=null?c:{},deviceClass:n?Fe(n):"desktop",trafficSource:s?je(s,t==null?void 0:t.appOrigin):"direct",referrerDomain:We(s),timeOfDay:Ve(g),dayOfWeek:(b=["sun","mon","tue","wed","thu","fri","sat"][g.getDay()])!=null?b:"sun",automation:(t==null?void 0:t.webdriver)===!0||$e(n)},t!=null&&t.landingPath?{landingPath:t.landingPath.split(/[?#]/)[0]}:{})}var Oe=require("@sentientui/policy");function He(e){return A(A(A({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 De(e){let t=He(e);return(0,Oe.slotResultFor)(t,(0,Oe.slotBaselineArm)(t))}function kn(e){let t={};for(let n of e)t[n.id]=De(n);return t}function gt(e){return typeof e=="string"?e:(0,Oe.canonicalArm)(e)}var xn=require("@sentientui/policy"),pt="data-sentient-stage";function ft(e,t){return!t||typeof e!="string"||!(e==="returning"||xn.STAGE_KEYS.includes(e))?null:t!=="detailed"&&(e==="customer"||e==="lapsed")?"returning":e}function mt(e,t=document){try{e?t.documentElement.setAttribute(pt,e):t.documentElement.removeAttribute(pt)}catch(n){}}var Gt=require("@sentientui/policy");var St=require("@sentientui/policy");var ht="[sentient] No API key configured \u2014 nothing is being learned. Set NEXT_PUBLIC_SENTIENT_API_KEY or pass localMode: true for local development.",Dt="[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.",wn=!1,yt=!1;function yo(){var e;try{return(e=new URLSearchParams(window.location.search).get("sentient_persona"))!=null?e:void 0}catch(t){return}}function En(e){var a;let t=lt({ssrSessionId:e.ssrSessionId,apiKey:e.apiKey}),n=(a=t.getSessionId())!=null?a:"local",s=yo(),g=import("@sentientui/core/local").then(i=>{let c=i;return c.LOCAL_ENGINE_AVAILABLE?(wn||(wn=!0,console.info(Dt)),c):(yt||(yt=!0,console.error(ht)),null)}).catch(()=>(yt||(yt=!0,console.error(ht)),null)),u=null,S={low:.15,medium:.5,high:.85},o=(()=>{var c;if(e.initialPersona)return A({},e.initialPersona);let i=Ie(e.apiKey||"local");return i?{persona:i.persona,confidence:(c=S[i.band])!=null?c:.15}:null})();function f(i){let c=document.documentElement;c.dataset.sentientPersona===void 0&&(c.dataset.sentientPersona=i.persona,c.dataset.sentientConfidence=(0,St.confidenceBand)(i.confidence))}return{isLocal:!0,async decide(i){var R,T,P;let c=await g;if(!c)return null;let b=c.createLocalEngine({sessionId:n,forcedPersona:s}).decide(i);return u=Se(A({},b),{layoutOrder:(T=(R=b.layoutOrder)!=null?R:u==null?void 0:u.layoutOrder)!=null?T:null,slots:A(A({},(P=u==null?void 0:u.slots)!=null?P:{}),b.slots)}),Ae(e.apiKey||"local",{v:1,persona:u.persona,band:(0,St.confidenceBand)(u.confidence),slots:u.slots,layoutOrder:u.layoutOrder,savedAt:Date.now()}),f(b),b},getSlotResult(i){var c,b,R;return(R=(b=u==null?void 0:u.slots[i])!=null?b:(c=e.initialSlots)==null?void 0:c[i])!=null?R:null},getSlotConfig(i){var c,b;return(b=(c=e.initialSlotConfig)==null?void 0:c[i])!=null?b:null},getSitePalette(){var i;return(i=e.initialPalette)!=null?i:null},reportSlots(){},getVisitorId:()=>null,getPersona(){let i=u!=null?u:o;return i?{persona:i.persona,confidence:i.confidence,band:(0,St.confidenceBand)(i.confidence)}:null},async assign(i,c){var T;let b=await g;return!b||!c||c.length===0?c!=null&&c[0]?{variantId:c[0],assignmentTtlMs:0}:null:{variantId:(T=b.createLocalEngine({sessionId:n,forcedPersona:s}).decide({components:[{id:i,variantIds:c}]}).assignments[i])!=null?T:c[0],assignmentTtlMs:0}},track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},getAssignment:()=>null,fetchWeights:()=>Promise.resolve([]),getGraph:()=>({pageNodes:[],capturedAt:0}),flush:()=>{},dispose:()=>{},destroy:()=>t.destroy()}}var Bt=/^(\*|\/[^\s?#*]*(\/\*)?)$/;function Pt(e){let t=e.split(/[?#]/)[0]||"/";return t.length>1?t.replace(/\/+$/,"")||"/":t}function _n(e,t){if(e===void 0||!Bt.test(e))return!1;if(e==="*")return!0;let n=Pt(t);if(e.endsWith("/*")){let s=Pt(e.slice(0,-2));return n.startsWith(s==="/"?"/":`${s}/`)&&n!==s}return n===Pt(e)}function In(e,t){if(!e)return!1;if(e==="/")return t==="/";let n=e.endsWith("/")?e.slice(0,-1):e;return t===n||t.startsWith(`${n}/`)}function An(e){if(!/^https?:\/\//i.test(e))return e;try{return new URL(e).pathname||"/"}catch(t){return e}}var So=["none","sm","md","lg"],ho=["start","center","end","stretch"],bo=["start","center","end","between"],vo=["sm","md","lg"],ko=["normal","medium","bold"],xo=["default","muted","accent"],wo=["primary","secondary","ghost"],Eo=["left","center","right"],_o=["auto","square","landscape","wide"],Io=["cover","contain"],Ao=[2,3,4],Co=[1,2,3,4],Ro=["default","raised"],To=["none","sm","md","lg"],Oo=["measure"],Do=["input","textarea","select"],Po=["text","email","number","tel"],Bo=5,Lo=8,Mo=64,No=5,Ko=12,Go=4,Uo=500;function Cn(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(Cn):!1}var Kr=40,Gr=120,Ur=300;var Lt="sentient-reveal",Pe="sentient-revealed",Mt=240,bt=!1;function Rn(){var e;bt=!1,typeof document!="undefined"&&((e=document.getElementById(Lt))==null||e.remove())}function $o(e){if(bt||e.getElementById(Lt)){bt=!0;return}let t=qe(e.createElement("style"),e);t.id=Lt,t.textContent=`@media (prefers-reduced-motion: no-preference){@keyframes ${Pe}{from{opacity:.55;transform:translateY(2px)}to{opacity:1;transform:none}}.${Pe}{animation:${Pe} ${Mt}ms cubic-bezier(.2,.6,.2,1) both}}`,e.head.appendChild(t),bt=!0}function Tn(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;$o(n),e.classList.remove(Pe),e.offsetWidth,e.classList.add(Pe);let s=()=>{e.classList.remove(Pe),e.removeEventListener("animationend",s)};return e.addEventListener("animationend",s),!0}function On(e,t,n,s){let g=[];{let o=!1,f=[],a=()=>{if(o)return;let i=Date.now();for(f.push(i);f.length>0&&i-f[0]>500;)f.shift();f.length>=3&&(o=!0,e("rage_click"))};t.addEventListener("click",a),g.push(()=>t.removeEventListener("click",a))}{let u=!1,S=o=>{if(u||!(o.target instanceof Node)||!t.contains(o.target)&&t!==o.target)return;u=!0;let f=typeof window!="undefined"?window.getSelection():null,a=f?f.toString().length:0;e("text_copy",{selectionLength:a})};document.addEventListener("copy",S),g.push(()=>document.removeEventListener("copy",S))}{let u=!1,S=!1,o=null,f=()=>{o!==null&&(clearTimeout(o),o=null)},a=()=>{u||!S||(f(),o=setTimeout(()=>{!u&&S&&(u=!0,e("scroll_hesitation"))},3e3))},i=()=>{f(),a()},c=R=>{for(let T of R)S=T.intersectionRatio>.3,S?a():f()},b=new IntersectionObserver(c,{threshold:[.3]});b.observe(t),window.addEventListener("scroll",i,{passive:!0}),g.push(()=>{b.disconnect(),window.removeEventListener("scroll",i),f()})}if((s==null?void 0:s.tabLoss)!==!1){let u=!1,S=n!=null?n:Date.now(),o=()=>{if(u||document.visibilityState!=="hidden")return;let f=Date.now()-S;f<15e3&&(u=!0,e("tab_loss",{timeOnPage:f}))};document.addEventListener("visibilitychange",o),g.push(()=>document.removeEventListener("visibilitychange",o))}return()=>{for(let u of g)u()}}function Fo(){var e;return typeof process=="undefined"||((e=process.env)==null?void 0:e.NODE_ENV)!=="production"}var Bn="https://api.sentient-ui.com/v1/events",J=new Map,Ln=null;function jo(e,t){let n=J.get(e);n&&n.upgrade&&(n.reinit=t)}function Wo(e){return"value"in e||"currency"in e||"externalId"in e||"metadata"in e||"weight"in e||"stepIndex"in e}var Vo=3;function Nt(){return rt()}function vt(){var e;if(typeof window!="undefined")return((e=window.location)==null?void 0:e.pathname)||void 0}function Ho(){let e=new WeakMap,t=new Map,n=!1,s=(o,f,a)=>{let i=o.get(f);return a===null?i?!0:(o.set(f,new Set),!1):i?i.has(a)?!0:(i.add(a),!1):(o.set(f,new Set([a])),!1)},g=typeof window!="undefined"&&"event"in window,u=()=>{if(!g)return;let o=window.event;return typeof Event=="function"&&o instanceof Event?o:void 0},S=()=>{if(g){Promise.resolve().then(()=>{n=!1,t.clear()});return}let o=!1,f=()=>{o||(o=!0,n=!1,t.clear())};if(setTimeout(f,0),typeof MessageChannel=="function"){let a=new MessageChannel;a.port1.onmessage=()=>{a.port1.close(),a.port2.close(),f()},a.port2.postMessage(0)}};return{firedBefore(o,f){let a=u();if(a){let c=e.get(a);return c||(c=new Map,e.set(a,c)),s(c,o,f)}let i=s(t,o,f);return!i&&!n&&(n=!0,S()),i}}}var Mn=new Set;function zo(e,t,n){let s=typeof window=="undefined"?null:window.history;if(!s)return()=>{};let g=!1,u,S=()=>{if(g)return;let a=vt();!a||a===u||(u=a,e.track({projectId:t,componentId:"__page__",eventType:"pageview",payload:{}}),n(`${t}:${a}`))},o=[];for(let a of["pushState","replaceState"]){let i=s[a],c=function(...b){let R=i.apply(this,b);return S(),R};s[a]=c,o.push([a,i,c])}window.addEventListener("popstate",S);let f=vt();return f&&Mn.has(`${t}:${f}`)?u=f:S(),()=>{if(!g){g=!0,window.removeEventListener("popstate",S);for(let[a,i,c]of o)s[a]===c&&(s[a]=i)}}}var ze={track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},getAssignment:()=>null,assign:()=>Promise.resolve(null),decide:()=>Promise.resolve(null),getSlotResult:()=>null,getSlotConfig:()=>null,getSitePalette:()=>null,reportSlots:()=>{},getPersona:()=>null,getVisitorId:()=>null,fetchWeights:()=>Promise.resolve([]),getGraph:()=>({pageNodes:[],capturedAt:0}),flush:()=>{},dispose:()=>{},destroy:()=>{}};function Qo(){try{return ut(window.location.search)}catch(e){return{utmParams:{},clickIds:{}}}}function Nn(e){return e.replace(/\/events\/?$/,"")}function Ft(){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 Xo(e){var f;if(typeof window=="undefined")return;let t=e!=null?e:Ln;if(!t){console.warn("[sentient] grantConsent() called before init()");return}let n=J.get(t);if(!n){console.warn("[sentient] grantConsent() called before init()");return}let{config:s,upgrade:g,reinit:u}=n;if(!g){n.upgradeBlockedReason&&console.warn(n.upgradeBlockedReason);return}if(s.respectDoNotTrack!==!1&&Ft())return;let S=(u!=null?u:Kn)(Se(A({},s),{consent:!0}));g(S);let o=(f=J.get(t))==null?void 0:f.dispose;J.set(t,{config:Se(A({},s),{consent:!0}),upgrade:null,dispose:o})}function Jo(e,t){var $;let n=e.preConsentBehavior==="statistical_winner",s=Nn(($=e.ingestUrl)!=null?$:Bn),g={"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`},u=new Map,S=new Map,o={track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},getAssignment:()=>null,fetchWeights:()=>Promise.resolve([]),assign(d,m,h){if(!n)return Promise.resolve(null);let p=u.get(d);return p?Promise.resolve(p):$t(S,d,async()=>{try{let _=new URLSearchParams({componentId:d});for(let ee of m!=null?m:[])_.append("variantIds[]",ee);let M=ue(5e3),F;try{let ee=await fetch(`${s}/winner?${_.toString()}`,{headers:g,signal:M.signal});if(!ee.ok)return m!=null&&m[0]?{variantId:m[0],assignmentTtlMs:0}:null;F=await ee.json()}finally{M.clear()}let O={variantId:F.variantId,assignmentTtlMs:0};return u.set(d,O),O}catch(_){return m!=null&&m[0]?{variantId:m[0],assignmentTtlMs:0}:null}})},decide:()=>Promise.resolve(null),getSlotResult:()=>null,getSlotConfig:()=>null,getSitePalette:()=>null,reportSlots:()=>{},getPersona:()=>null,getVisitorId:()=>null,getGraph:()=>({pageNodes:[],capturedAt:0}),flush:()=>{},dispose:()=>{},destroy:()=>{}},f=!1,a=new Set,i=[],c=[],b=[],R=()=>{for(let[,,d]of b.splice(0))d(null);T.length=0},T=[],P=!1,K=()=>{if(f)return;P=!0;let d=J.get(e.apiKey);(d==null?void 0:d.upgrade)===q&&J.set(e.apiKey,{config:e,upgrade:null,upgradeBlockedReason:"[sentient] grantConsent(): client released before consent; call init() again"})},V=[],H=()=>{setTimeout(()=>{var d;try{(d=V.shift())==null||d(o)}catch(m){}V.length&&H()})},z=d=>{f?V.length?V.push(d):d(o):!t&&!P&&T.length<100?T.push(d):P&&e.debug&&console.warn("[sentient] goal dropped: client released")},Q={get gated(){return!f&&!t},get released(){return P&&!f},takeHeld:()=>T.splice(0),track:d=>o.track(d),goal:((d,m,h,p)=>z(_=>_.goal(d,m,h,p))),componentGoal:(d,m,h)=>o.componentGoal(d,m,h),identify:(d,m)=>o.identify(d,m),getAssignment:(d,m)=>o.getAssignment(d,m),isUnified:d=>{var m,h;return(h=(m=o.isUnified)==null?void 0:m.call(o,d))!=null?h:!1},assign:(d,m,h,p,_)=>o.assign(d,m,h,p,_),decide:d=>f?o.decide(d):P||t?Promise.resolve(null):new Promise(m=>b.push([d,Ut(),m])),getSlotResult:d=>o.getSlotResult(d),isSlotDecided:d=>{var m,h;return(h=(m=o.isSlotDecided)==null?void 0:m.call(o,d))!=null?h:!0},getSlotConfig:d=>o.getSlotConfig(d),getSitePalette:()=>o.getSitePalette(),getStyleVocabulary:()=>{var d,m;return(m=(d=o.getStyleVocabulary)==null?void 0:d.call(o))!=null?m:null},reportSlots:(d,m,h,p)=>o.reportSlots(d,m,h,p),reportSkeleton:(d,m)=>{var h;return(h=o.reportSkeleton)==null?void 0:h.call(o,d,m)},reportAgentData:(d,m,h)=>{var p;return(p=o.reportAgentData)==null?void 0:p.call(o,d,m,h)},reportDrift:(d,m,h,p)=>{var _;return(_=o.reportDrift)==null?void 0:_.call(o,d,m,h,p)},requestSlots:(d,m,h)=>{var p;return f?(p=o.requestSlots)==null?void 0:p.call(o,d,m,h):i.push([d,m,h])},decideSlots:d=>{var m;return f?(m=o.decideSlots)==null?void 0:m.call(o,d):c.push(...d)},cancelSlots:d=>{var h;if(f)return(h=o.cancelSlots)==null?void 0:h.call(o,d);let m=new Set(d);for(let p of i)p[0]=p[0].filter(_=>!m.has(_));c=c.filter(p=>!m.has(p.id))},onSlotsChanged:d=>(a.add(d),()=>{a.delete(d)}),getPersona:()=>o.getPersona(),getVisitorId:()=>{var d,m;return(m=(d=o.getVisitorId)==null?void 0:d.call(o))!=null?m:null},fetchWeights:()=>o.fetchWeights(),getGraph:()=>o.getGraph(),flush:()=>o.flush(),dispose:()=>(K(),R(),o.dispose()),destroy:()=>(K(),R(),f?o.destroy():ot(e.apiKey))};function q(d){var h,p,_;o=d,f=!0,T.length&&(V.push(...T.splice(0)),H());let m=Ut();for(let[M,F,O]of b.splice(0))F!==m?O(null):d.decide(M).then(O,()=>O(null));(h=d.onSlotsChanged)==null||h.call(d,()=>a.forEach(M=>M()));for(let[M,F,O]of i.splice(0))M.length>0&&((p=d.requestSlots)==null||p.call(d,M,F,O));c.length>0&&((_=d.decideSlots)==null||_.call(d,c.splice(0)))}return{proxy:Q,setInner:q}}function Ut(){return typeof location=="undefined"?"":location.pathname+(/^#!?\//.test(location.hash)?location.hash:"")}function $t(e,t,n){let s=e.get(t);if(s)return s;let g=(async()=>{try{return await n()}finally{e.delete(t)}})();return e.set(t,g),g}function Kn(e){var zt,Qt,Xt,Jt,qt,Yt,Zt,en,tn,nn,on;if(typeof window=="undefined")return ze;e.nonce&&Je(e.nonce),Ln=e.apiKey||"local";let t=J.get(e.apiKey||"local");if(t!=null&&t.dispose)try{t.dispose()}catch(r){}let n=e.respectDoNotTrack!==!1&&Ft(),s=e.consent===!1||n,g=typeof e.apiKey=="string"&&e.apiKey.startsWith("pk_");if(e.localMode===!0||!g&&e.localMode!==!1)return J.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."}),s?ze:En(e);if(s){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."),J.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."}),ze;let{proxy:r,setInner:l}=Jo(e,n);return J.set(e.apiKey,{config:e,upgrade:n?null:l}),r}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."),ze;if(e.ingestUrl==="")return console.warn("[sentient] init() called with an empty ingestUrl. SDK disabled."),ze;let u=(zt=e.ingestUrl)!=null?zt:Bn,S=Date.now(),o=lt({ssrSessionId:e.ssrSessionId,apiKey:e.apiKey,cookieDomain:e.cookieDomain}),f=Sn(void 0,e.apiKey),a=!1,i=se(e.apiKey),c=()=>!a&&se(e.apiKey)===i,b=new Set((Qt=e.initialUnified)!=null?Qt:[]),R=Se(A({},f),{get:(r,l)=>b.has(r)?null:f.get(r,l),set:(...r)=>{c()&&f.set(...r)}}),T=gn({ingestUrl:u,apiKey:e.apiKey}),P=Nn(u),K={"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`},V=new Set,H=pn({url:`${P}/goals`,apiKey:e.apiKey,headers:K,onDrop:(r,l)=>{if(!e.debug){if(V.has(l))return;V.add(l)}console.warn(`[sentient] goal dropped (HTTP ${l}) \u2014 this will not be retried. `+(l===400?"The session was not found: call init() and let the session upsert complete before firing goals.":l===401||l===403?"Check the API key and that this origin is on the project allowlist.":"See the response status for the cause."),r)}}),z=Fe((Xt=navigator.userAgent)!=null?Xt:""),Q=window.location.origin,q=je((Jt=document.referrer)!=null?Jt:"",Q,o.domain),$=(qt=e.sessionSegment)!=null?qt:`${z}:${q}`,d=new Map,m=new Map,h=new Map,p=new Set,_=new Map,M=null,F=null,O=null,ee=new Set,ie=new Set,k=new Map,B=new Map,ge=new Set,be=new Set,te=new Set,ke=new Set,xe=null,oe=/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,127}$/,we=new Set,ae=new Set,Qe=new Set,Be=new Map,kt=null,Xe=new Set,Le=new Map,xt=null,Gn=2,jt=new Map,re=!1,Wt=(r,l,y)=>{var v;let I=new Set,C=1;for(let x of r){l.delete(x);let w=((v=jt.get(x))!=null?v:0)+1;jt.set(x,w),w<=Gn&&(I.add(x),w>C&&(C=w))}I.size>0&&setTimeout(()=>{re||y(I)},me(C))},wt=r=>{for(let l of r)h.has(l.id)||h.set(l.id,De(l))};if(e.initialSlots)for(let[r,l]of Object.entries(e.initialSlots))h.set(r,l),p.add(r);if(e.initialSlotConfig)for(let[r,l]of Object.entries(e.initialSlotConfig))_.set(r,l);e.initialPalette&&(M=e.initialPalette),e.initialVocabulary&&(F=e.initialVocabulary);let le=Ie(e.apiKey);if(le){for(let[r,l]of Object.entries(le.slots))h.has(r)||h.set(r,l);for(let[r,l]of Object.entries((Yt=le.slotConfig)!=null?Yt:{}))_.has(r)||_.set(r,l);!M&&le.palette&&(M=le.palette),!F&&le.vocabulary&&(F=le.vocabulary)}let Vt={low:.15,medium:.5,high:.85};if(e.initialPersona)O=A({},e.initialPersona);else{let r=document.documentElement.dataset;r.sentientPersona?O={persona:r.sentientPersona,confidence:(en=Vt[(Zt=r.sentientConfidence)!=null?Zt:"low"])!=null?en:.15}:le&&(O={persona:le.persona,confidence:(tn=Vt[le.band])!=null?tn:.15})}if(e.initialAssignments)for(let[r,l]of Object.entries(e.initialAssignments))R.set(r,$,{variantId:l,assignedAt:Date.now(),segment:$,confidence:1});let ye=Promise.resolve(),Ht=o.getSessionId();if(Ht){let r=We((nn=document.referrer)!=null?nn:""),{utmParams:l,clickIds:y}=Qo(),I=A(A(A(A({sessionId:Ht,deviceClass:z,trafficSource:q,referrerDomain:r,utmParams:l,clickIds:y,landingPath:typeof location!="undefined"?location.pathname:void 0,timeOfDay:Ve(new Date),dayOfWeek:["sun","mon","tue","wed","thu","fri","sat"][new Date().getDay()],ephemeral:o.isEphemeral(),automation:typeof navigator!="undefined"&&navigator.webdriver===!0||$e((on=navigator.userAgent)!=null?on:"")},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}:{}),C=async()=>{for(let v=0;;v++){if(re||!c())return;let x=ue(5e3);try{let w=await fetch(`${P}/sessions`,{method:"POST",keepalive:!0,body:JSON.stringify(I),headers:K,signal:x.signal});if(w.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(w.ok||Ce(w)==="dropped")return}catch(w){}finally{x.clear()}if(v>=Vo){console.warn("[SentientUI] Could not register the session after retries. Conversions in this visit may not be recorded.");return}await new Promise(w=>setTimeout(w,me(v+1)))}};try{ye=C()}catch(v){}}e.debug&&(console.log("[sentient] initialized",{context:e.context}),window.__sentient={client:null,queue:T});let Un=Ho(),ve=null,Et=!1,W={goal(r,l={},y=1,I=0){var j,L,Y,ne,Z,X,E;let C=o.getSessionId();if(!C||re||!c())return;let v=Wo(l)?l:{metadata:l},x=[r,(j=v.externalId)!=null?j:"",(L=v.stepIndex)!=null?L:I,(Y=v.weight)!=null?Y:y].join("\0"),w=v.value!==void 0?`${v.value}\0${(ne=v.currency)!=null?ne:""}`:null;if(Un.firedBefore(x,w)){e.debug&&console.log(`[sentient] goal("${r}") already recorded for this action \u2014 not sent twice`);return}let N=Nt(),D={sessionId:C,name:r,metadata:(Z=v.metadata)!=null?Z:{},weight:(X=v.weight)!=null?X:y,stepIndex:(E=v.stepIndex)!=null?E:I,goalId:N,value:v.value,currency:v.currency,externalId:v.externalId};e.debug&&console.log("[sentient] goal",D);let G={id:N,body:JSON.stringify(D)};ye.then(()=>H.send(G))},componentGoal(r,l,y){var N,D,G;let I=o.getSessionId();if(!I||re||!c())return;let C=R.get(r,$),v=C?null:(N=h.get(r))!=null?N:null;if(!C&&v===null){e.debug&&console.warn(`[sentient] componentGoal("${r}"): no assignment or slot decision yet \u2014 render its <Adaptive>/adaptive hook or call assign()/decide() before recording a goal.`);return}if(!C&&!p.has(r)){e.debug&&console.warn(`[sentient] componentGoal("${r}"): slot not decided this session \u2014 not attributed`);return}let x=C?C.variantId:gt(v),w={id:Nt(),sessionId:I,projectId:e.apiKey,componentId:r,variantId:x,eventType:"goal_achieved",goalType:l,payload:A({reward:(D=y==null?void 0:y.reward)!=null?D:1,goalValue:y==null?void 0:y.value,currency:y==null?void 0:y.currency},(G=y==null?void 0:y.metadata)!=null?G:{}),timestamp:Date.now(),timeInSession:Date.now()-S,path:vt()};e.debug&&console.log("[sentient] componentGoal",w),ye.then(()=>{!re&&c()&&T.push(w)})},identify(r,l){let y=o.getSessionId();!y||re||!c()||ye.then(()=>{fetch(`${P}/sessions`,{method:"POST",keepalive:!0,body:JSON.stringify({sessionId:y,userId:r,userHash:l==null?void 0:l.userHash,ephemeral:o.isEphemeral()}),headers:K}).catch(()=>{})})},track(r){let l=o.getSessionId();if(!l||re||!c()||r.eventType==="variant_assigned"&&h.get(r.componentId)!==void 0&&!p.has(r.componentId)&&!R.get(r.componentId,$))return;let y=Se(A({path:vt()},r),{id:Nt(),sessionId:l,timestamp:Date.now(),timeInSession:Date.now()-S});e.debug&&console.log("[sentient] track",y),ye.then(()=>T.push(y))},getAssignment(r,l){return R.get(r,l)},isUnified:r=>b.has(r),async assign(r,l,y,I,C){var N;let v=o.getSessionId();if(!v)return null;let x=(C==null?void 0:C.unified)===!0;if(x&&b.has(r))return{variantId:(N=l==null?void 0:l[0])!=null?N:"",assignmentTtlMs:0,unified:!0};let w=R.get(r,$);if(w&&(l!=null&&l.length||w.content!==void 0)){let D=w.ttlMs&&w.ttlMs>0?Math.max(0,w.assignedAt+w.ttlMs-Date.now()):0;return{variantId:w.variantId,assignmentTtlMs:D,content:w.content}}return $t(d,x?`${r}\0unified`:r,async()=>{if(!await _t(ye,2500)||re||!c())return null;let D=ue(3e4);try{let G={sessionId:v,componentId:r,variantIds:l};I!==void 0?G.agentDataByVariant=I:y!==void 0&&(G.agentData=y),x&&(G.caps={unified:!0});let j=await fetch(`${P}/assign`,{method:"POST",body:JSON.stringify(G),headers:K,signal:D.signal});if(!j.ok)return null;let L=await j.json();return L.unified===!0?x?(b.add(r),{variantId:L.variantId,assignmentTtlMs:0,unified:!0}):null:(R.set(r,$,A({variantId:L.variantId,assignedAt:Date.now(),segment:$,confidence:1,content:L.content},L.assignmentTtlMs&&L.assignmentTtlMs>0?{ttlMs:L.assignmentTtlMs}:{})),L)}catch(G){return null}finally{D.clear()}})},async decide(r){var v,x;let l=o.getSessionId();if(!l)return null;let y=(v=r.slots)!=null?v:[],I={sessionId:l};r.sections&&r.sections.length>0&&(I.sections=r.sections.map(w=>({id:w}))),I.components=(x=r.components)!=null?x:[],y.length>0&&(I.slots=y.map(He)),r.slotsFrom==="registry"&&(I.slotsFrom="registry",r.registrySlotIds&&(I.registrySlotIds=r.registrySlotIds),r.bootstrap===!1&&(I.bootstrap=!1),r.render&&Object.keys(r.render).length>0&&(I.render=r.render)),r.v&&(I.v=r.v),typeof r.pp=="number"&&(I.pp=r.pp),e.persona&&(I.persona=e.persona);let C=JSON.stringify(I);return $t(m,C,async()=>{var N,D,G,j,L,Y,ne,Z;if(!await _t(ye,2500)||re||!c())return wt(y),null;let w=ue(3e4);try{let X=await fetch(`${P}/decide`,{method:"POST",body:C,headers:K,signal:w.signal});if(!X.ok)return wt(y),null;let E=await X.json(),ce=ft(E.stage,e.stageAttributes);e.stageAttributes&&mt(ce);let Ee={};for(let U of y){let de=(N=E.slots)==null?void 0:N[U.id];if(de!==void 0){Ee[U.id]=de,h.set(U.id,de),p.add(U.id);continue}let rn=h.get(U.id);if(rn!==void 0)Ee[U.id]=rn;else{let sn=De(U);Ee[U.id]=sn,h.set(U.id,sn)}}if(E.slots)for(let[U,de]of Object.entries(E.slots))U in Ee||(Ee[U]=de,h.set(U,de),p.add(U));let $n=O!=null&&O.persona!=="unknown";E.persona&&!(E.persona==="unknown"&&$n)?O={persona:E.persona,confidence:(D=E.confidence)!=null?D:0}:O||(O={persona:"unknown",confidence:0});for(let[U,de]of Object.entries((G=E.assignments)!=null?G:{}))R.set(U,$,{variantId:de,assignedAt:Date.now(),segment:$,confidence:1});if(E.slotConfig)for(let[U,de]of Object.entries(E.slotConfig))_.set(U,de);E.palette&&(M=E.palette),E.vocabulary&&(F=E.vocabulary);for(let U of(j=r.registrySlotIds)!=null?j:[])(L=E.slotConfig)!=null&&L[U]||(_.delete(U),h.delete(U),p.delete(U));return c()&&Ae(e.apiKey,A(A(A(A({v:1,persona:O.persona,band:(0,Gt.confidenceBand)(O.confidence),slots:Object.fromEntries(h),layoutOrder:(Y=E.layoutOrder)!=null?Y:null,savedAt:Date.now()},_.size>0?{slotConfig:Object.fromEntries(_)}:{}),M?{palette:M}:{}),F?{vocabulary:F}:{}),ce?{stage:ce}:{})),A(A(A(A(A(A(A({layoutOrder:(ne=E.layoutOrder)!=null?ne:null,assignments:(Z=E.assignments)!=null?Z:{},slots:Ee,persona:O.persona,confidence:O.confidence},E.slotConfig?{slotConfig:E.slotConfig}:{}),E.goals?{goals:E.goals}:{}),E.sectionMap?{sectionMap:E.sectionMap}:{}),E.palette?{palette:E.palette}:{}),E.vocabulary?{vocabulary:E.vocabulary}:{}),E.stage?{stage:E.stage}:{}),E.context?{context:E.context}:{})}catch(X){return wt(y),null}finally{w.clear()}})},getSlotResult(r){var l;return(l=h.get(r))!=null?l:null},isSlotDecided(r){return p.has(r)},getSlotConfig(r){var l;return(l=_.get(r))!=null?l:null},reportSlots(r,l,y,I){var v;let C={};for(let[x,w]of Object.entries(I!=null?I:{}))for(let N of w){let D=`${x}|${N.key}`;!oe.test(x)||te.has(D)||(te.add(D),((v=C[x])!=null?v:C[x]=[]).push(N))}Object.keys(C).length>0&&fetch(`${P}/slots/observed`,{method:"POST",headers:K,body:JSON.stringify({slotIds:Object.keys(C),authoredArms:C})}).catch(()=>{});for(let x of r)if(!(typeof x!="string"||x.length===0)){if(!oe.test(x)){Fo()&&!we.has(x)&&(we.add(x),console.warn(`[sentient] reportSlots: slot id ${JSON.stringify(x)} 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(!ee.has(x)){ee.add(x),ie.add(x);let w=l==null?void 0:l[x];if(typeof w=="string"){let D=w.replace(/\s+/g," ").trim().slice(0,400);D!==""&&k.set(x,D)}let N=y==null?void 0:y[x];N!==void 0&&B.set(x,N)}}ie.size===0||xe!=null||(xe=setTimeout(()=>{xe=null;let x=[...ie];ie.clear();for(let w=0;w<x.length;w+=20){let N=x.slice(w,w+20),D={},G={};for(let j of N){let L=k.get(j);L!==void 0&&(D[j]=L,k.delete(j));let Y=B.get(j);Y!==void 0&&(G[j]=Y,B.delete(j))}fetch(`${P}/slots/observed`,{method:"POST",headers:K,body:JSON.stringify(A(Se(A(A({slotIds:N},Object.keys(D).length>0?{baselineTexts:D}:{}),Object.keys(G).length>0?{baselineSkeletons:G}:{}),{pagePaths:Object.fromEntries(N.map(j=>[j,location.pathname]))}),Object.keys(D).length>0&&o.getSessionId()?{sessionId:o.getSessionId()}:{}))}).catch(()=>{})}},1e3))},reportSkeleton(r,l){!oe.test(r)||ge.has(r)||(ge.add(r),fetch(`${P}/slots/observed`,{method:"POST",headers:K,body:JSON.stringify({slotIds:[r],baselineSkeletons:{[r]:l}})}).catch(()=>{}))},reportAgentData(r,l,y){let I=`${r}|${l}`;!oe.test(r)||ke.has(I)||(ke.add(I),fetch(`${P}/slots/observed`,{method:"POST",headers:K,body:JSON.stringify(A(A({slotIds:[r],agentData:{[r]:{[l]:y}}},l.startsWith("authored.")?{authoredArms:{[r]:[{key:l.slice(9)}]}}:{}),o.getSessionId()?{sessionId:o.getSessionId()}:{}))}).catch(()=>{}))},reportDrift(r,l,y,I){let C=`${r}|${l}`,v=o.getSessionId();!v||be.has(C)||(be.add(C),fetch(`${P}/slots/drift`,{method:"POST",headers:K,body:JSON.stringify({sessionId:v,reports:[{slotId:r,expectedFp:l,observedFp:y,reason:I}]})}).catch(()=>{}))},requestSlots(r,l,y){var I,C;for(let v of r)Qe.has(v)||(Qe.add(v),oe.test(v)?Be.set(v,{text:l==null?void 0:l[v],render:(I=y==null?void 0:y.render)==null?void 0:I[v],skeleton:(C=y==null?void 0:y.skeletons)==null?void 0:C[v]}):W.reportSlots([v]));Be.size===0||kt!=null||(kt=setTimeout(()=>{kt=null;let v=[...Be];Be.clear();for(let x=0;x<v.length;x+=50){let w=v.slice(x,x+50),N={};for(let[D,G]of w)G.render&&(N[D]=G.render);W.decide({slotsFrom:"registry",registrySlotIds:w.map(([D])=>D),bootstrap:!1,render:N}).then(D=>{var G,j;if(D){let L={},Y={},ne=[];for(let[Z,X]of w){let E=(G=D.slotConfig)==null?void 0:G[Z];if(E){E.needsSkeleton&&X.skeleton&&((j=W.reportSkeleton)==null||j.call(W,Z,X.skeleton));continue}ne.push(Z),X.text&&(L[Z]=X.text),X.skeleton&&(Y[Z]=X.skeleton)}ne.length>0&&W.reportSlots(ne,L,Y)}else Wt(w.map(([L])=>L),Qe,L=>{var X;let Y={},ne={},Z={};for(let[E,ce]of w)L.has(E)&&(ce.text&&(Y[E]=ce.text),ce.render&&(ne[E]=ce.render),ce.skeleton&&(Z[E]=ce.skeleton));(X=W.requestSlots)==null||X.call(W,[...L],Y,{render:ne,skeletons:Z})});ae.forEach(L=>L())})}},0))},decideSlots(r){for(let l of r)Xe.has(l.id)||(Xe.add(l.id),Le.set(l.id,l));Le.size===0||xt!=null||(xt=setTimeout(()=>{xt=null;let l=[...Le.values()];Le.clear();for(let y=0;y<l.length;y+=30){let I=l.slice(y,y+30);W.decide({slots:I}).then(C=>{C||Wt(I.map(v=>v.id),Xe,v=>{var x;return(x=W.decideSlots)==null?void 0:x.call(W,I.filter(w=>v.has(w.id)))}),ae.forEach(v=>v())})}},0))},cancelSlots(r){for(let l of r)Be.delete(l)&&Qe.delete(l),Le.delete(l)&&Xe.delete(l)},onSlotsChanged(r){return ae.add(r),()=>{ae.delete(r)}},getStyleVocabulary(){return F},getSitePalette(){return M},getVisitorId:()=>c()?o.getSessionId():null,getPersona(){return O?{persona:O.persona,confidence:O.confidence,band:(0,Gt.confidenceBand)(O.confidence)}:null},async fetchWeights(){var l;let r=ue(5e3);try{let y=await fetch(`${P}/weights`,{headers:K,signal:r.signal});return y.ok?(l=(await y.json()).components)!=null?l:[]:[]}catch(y){return[]}finally{r.clear()}},getGraph(){return{pageNodes:[],capturedAt:0}},flush(){T.flush(),H.flush()},dispose(){var r;ve==null||ve(),Et=!0,re=!0,T.destroy(),H.destroy(),((r=J.get(e.apiKey))==null?void 0:r.dispose)===W.dispose&&J.delete(e.apiKey),e.debug&&console.log("[sentient] disposed")},destroy(){var r;ve==null||ve(),Et=!0,re=!0,a=!0,Ze(e.apiKey),T.destroy({forget:!0}),H.destroy({forget:!0}),o.destroy(),R.clear(),((r=J.get(e.apiKey))==null?void 0:r.dispose)===W.dispose&&J.delete(e.apiKey);try{localStorage.removeItem(fe+e.apiKey),localStorage.removeItem(Ke(e.apiKey)),localStorage.removeItem(Ge(e.apiKey)),localStorage.removeItem(`_snt_graph_nodes${pe(e.apiKey)}`),localStorage.removeItem("_snt_graph_edges")}catch(l){}e.debug&&console.log("[sentient] destroyed")}};if(J.set(e.apiKey,{config:e,upgrade:null,dispose:W.dispose}),ve=zo(W,e.apiKey,r=>{ye.then(()=>{Et||Mn.add(r)})}),e.debug){let r=window;r.__sentient&&(r.__sentient.client=W)}return W}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,MAX_SKELETON_LEAVES,MAX_SKELETON_NODES,MAX_SKELETON_TEXT,PAGE_SCOPE_RE,PROD_KEYLESS_ERROR,REVEAL_MS,SNAPSHOT_STORAGE_KEY_PREFIX,STAGE_ATTRIBUTE,_registerConsentUpgradeInit,agentIntent,agentUaList,applyNonce,armOfResult,attachMicroSignalDetectors,baselineResultFor,baselineSlots,classifiedAgents,containsFormBlock,cspNonce,deriveSessionSegment,detectDeviceClass,detectTimeOfDay,detectTrafficSource,exposedStage,extractTrackedParams,forgetGeneration,forgetVisitor,grantConsent,init,isDoNotTrackEnabled,matchedAgentToken,normalizeUrlPattern,pageScopeMatches,readSnapshot,referrerDomainFromReferer,renderPrePaintScript,resetRevealStyles,reveal,routeKey,sessionCookieName,setCspNonce,setStageAttribute,toWireSlot,uaTokenMatch,urlMatches,writeSnapshot});
|
|
2
2
|
//# sourceMappingURL=index.js.map
|