@sentientui/core 0.31.1 → 0.33.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunk-EVYMV2C6.mjs +2 -0
- package/dist/chunk-EVYMV2C6.mjs.map +1 -0
- package/dist/{index-DErBinAw.d.cts → index-COl_pfNm.d.cts} +14 -1
- package/dist/{index-DxWcBI5U.d.ts → index-CgkImSaM.d.ts} +14 -1
- package/dist/index-engagement.d.cts +45 -1
- package/dist/index-engagement.d.ts +45 -1
- package/dist/index-engagement.js +1 -1
- package/dist/index-engagement.js.map +1 -1
- package/dist/index-engagement.mjs +1 -1
- package/dist/index-engagement.mjs.map +1 -1
- package/dist/index-graph.d.cts +2 -2
- package/dist/index-graph.d.ts +2 -2
- package/dist/index-graph.js +1 -1
- package/dist/index-graph.js.map +1 -1
- package/dist/index-graph.mjs +1 -1
- package/dist/index-local.d.cts +1 -1
- package/dist/index-local.d.ts +1 -1
- package/dist/index-server.d.cts +59 -1
- package/dist/index-server.d.ts +59 -1
- 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 +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1 -1
- package/package.json +1 -1
- package/dist/chunk-SFNOFZUH.mjs +0 -2
- package/dist/chunk-SFNOFZUH.mjs.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/server.ts"],"sourcesContent":["/**\n * Server-side helpers for SSR variant pre-loading.\n * Pure fetch — no DOM APIs. Safe in Node.js, Edge, and Deno runtimes.\n */\nimport { buildSessionUpsertPayload } from './session-meta.js';\nimport { LEGACY_SESSION_COOKIE_NAME, sessionCookieName } from './storage-key.js';\nimport {\n toWireSlot,\n baselineResultFor,\n baselineSlots,\n type SlotDeclInput,\n type SlotResult,\n} from './slots.js';\n\nimport type { SlotConfigEntry } from './snapshot.js';\nimport type { SitePalette } from './blocks.js';\n\nexport type { SlotDeclInput, SlotResult, SlotConfigEntry, SitePalette };\n\nexport type ServerAssignConfig = {\n /** Public API key (pk_...). */\n apiKey: string;\n /**\n * Base URL of the Sentient API without trailing slash.\n * e.g. 'https://api.yourapp.com/v1'\n */\n baseUrl: string;\n /**\n * Browser origin of your app (e.g. `http://localhost:3001`). Required for `pk_`\n * keys — server-side fetch must send the same `Origin` the API allows.\n */\n origin?: string;\n /** From `User-Agent` request header (Next.js `headers()`). */\n userAgent?: string;\n /** From `Referer` request header. */\n referer?: string;\n utmParams?: Record<string, string>;\n /**\n * Ad-platform click IDs (gclid, fbclid, ttclid, …) from the landing URL.\n * Derive both this and `utmParams` with `extractTrackedParams(searchParams)`\n * — the Referer header never carries the landing page's own query string, so\n * without these two fields SSR-minted sessions have no campaign attribution\n * until the client SDK hydrates.\n */\n clickIds?: Record<string, string>;\n /**\n * Set true when the request carries a tracking opt-out — `DNT: 1` or\n * `Sec-GPC: 1`. When set, the SSR helpers skip the session upsert and the\n * assign/decide call entirely: the page renders defaults/baseline and no\n * session row is minted for the visitor (audit P4). The client SDK already\n * no-ops for these visitors; this keeps the server from minting a session +\n * assignment on every page view before the client can.\n */\n doNotTrack?: boolean;\n /**\n * Declared persona — the role your app already knows for this visitor\n * (e.g. from your auth context during SSR). Same contract as the client\n * option: must be a vocabulary key; unrecognized values are ignored\n * server-side. Never a user id or email.\n */\n persona?: string;\n /**\n * Milliseconds to wait for the API before returning default variants.\n * Prevents slow/cold API from blocking SSR. Defaults to 1000 — the hot path\n * is served from in-process caches and typically returns in well under\n * 150 ms. The full 1 s budget is only reached on a cold start or an API\n * geographically distant from your SSR host, after which defaults render\n * with no layout shift. Lower it if your API is co-located and warm.\n */\n timeoutMs?: number;\n};\n\n/** componentId → assigned variantId */\nexport type ServerAssignments = Record<string, string>;\n\ntype AssignResult = { variantId: string; assignmentTtlMs: number };\n\nconst DEFAULT_TIMEOUT_MS = 1000;\n\nfunction fetchWithTimeout(\n url: string,\n init: RequestInit,\n timeoutMs: number,\n): Promise<Response> {\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), timeoutMs);\n return fetch(url, { ...init, signal: controller.signal }).finally(() =>\n clearTimeout(timer),\n );\n}\n\n/**\n * Fetches variant assignments server-side for all listed components.\n * Returns a map suitable for passing as `initialAssignments` to `<AdaptiveProvider>`.\n *\n * Call from Next.js layout, Server Component, or getServerSideProps.\n *\n * @example\n * ```tsx\n * const assignments = await preloadAssignments(\n * [\n * { id: 'hero', variantIds: ['hero-a', 'hero-b'] },\n * { id: 'cta', variantIds: ['cta-short', 'cta-long'] },\n * ],\n * sessionId, // read from cookies() or req.cookies\n * { apiKey: process.env.NEXT_PUBLIC_SENTIENT_API_KEY!, baseUrl: 'https://api.sentient-ui.com/v1' },\n * );\n * return <AdaptiveProvider ... initialAssignments={assignments}>{children}</AdaptiveProvider>;\n * ```\n */\nexport async function preloadAssignments(\n components: Array<{ id: string; variantIds: string[] }>,\n sessionId: string,\n config: ServerAssignConfig,\n): Promise<ServerAssignments> {\n // Opted-out visitor (DNT/GPC): render defaults, mint no session (audit P4).\n if (config.doNotTrack) return {};\n\n const timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${config.apiKey}`,\n };\n if (config.origin) {\n headers.Origin = config.origin;\n }\n\n // Session metadata must match the browser SDK so assign seeds variant_weights\n // under the same segment (not `unknown:unknown`).\n const sessionBody = {\n ...buildSessionUpsertPayload(sessionId, {\n userAgent: config.userAgent,\n referer: config.referer,\n utmParams: config.utmParams,\n clickIds: config.clickIds,\n appOrigin: config.origin,\n }),\n ...(config.persona ? { persona: config.persona } : {}),\n };\n\n try {\n const res = await fetchWithTimeout(\n `${config.baseUrl}/sessions`,\n { method: 'POST', headers, body: JSON.stringify(sessionBody) },\n timeoutMs,\n );\n if (res.status === 402) {\n console.warn(\n '[SentientUI] Session limit exceeded for this project. The bandit will stop learning until the limit resets. Upgrade at sentient-ui.com/pricing',\n );\n } else if (!res.ok) {\n const body = await res.json().catch(() => ({}));\n console.error(`[SentientUI] preloadAssignments: session upsert failed (${res.status})`, body);\n }\n } catch (err) {\n console.error('[SentientUI] preloadAssignments: session upsert threw', err);\n }\n\n const results = await Promise.allSettled(\n components.map(async ({ id, variantIds }) => {\n const res = await fetchWithTimeout(\n `${config.baseUrl}/assign`,\n { method: 'POST', headers, body: JSON.stringify({ sessionId, componentId: id, variantIds }) },\n timeoutMs,\n );\n if (!res.ok) {\n const body = await res.json().catch(() => ({}));\n console.error(`[SentientUI] preloadAssignments: assign failed for \"${id}\" (${res.status})`, body);\n return null;\n }\n const body = (await res.json()) as AssignResult;\n return { id, variantId: body.variantId };\n }),\n );\n\n const assignments: ServerAssignments = {};\n for (const result of results) {\n if (result.status === 'fulfilled' && result.value) {\n assignments[result.value.id] = result.value.variantId;\n }\n }\n return assignments;\n}\n\n/**\n * Reads the Sentient session cookie from a Next.js `ReadonlyRequestCookies` object\n * (the return value of `cookies()` from `next/headers`), or any object with a\n * `get(name: string)` method. Returns null if the cookie is absent.\n *\n * Pass the project's `apiKey`: the client writes the per-project SUFFIXED name\n * (`sessionCookieName` — see storage-key.ts), so reading only the bare\n * `_snt_uid` missed the cookie on every SSR request for a returning visitor and\n * minted a fresh orphan session each page view (quota inflation, broken sticky\n * assignments and persona continuity). The bare name is still read as a\n * fallback for identities minted before namespacing.\n */\nexport function readSessionCookie(\n cookies: { get(name: string): { value: string } | undefined },\n apiKey?: string,\n): string | null {\n return (\n (apiKey ? cookies.get(sessionCookieName(apiKey))?.value : undefined) ??\n cookies.get(LEGACY_SESSION_COOKIE_NAME)?.value ??\n null\n );\n}\n\nexport type DecideResult = {\n layoutOrder: string[];\n assignments: Record<string, string>;\n /** Slot results keyed by slot id. Baseline-resolved when the API omits/fails them. */\n slots: Record<string, SlotResult>;\n persona: string;\n confidence: number;\n /** Registry mode only: content/ops/blocks for server-defined slots. */\n slotConfig?: Record<string, SlotConfigEntry>;\n /** Registry mode only: site palette for block rendering. */\n palette?: SitePalette;\n};\n\n/**\n * Single-roundtrip SSR call returning layout order, component assignments,\n * and adaptive-slot results. Falls back to default section order + empty\n * assignments + baseline slots if the API is unavailable. A response without\n * a `slots` field means the server predates slots — every declared slot\n * resolves to its baseline (no retry).\n */\nexport async function preloadDecisions(\n params: {\n sections?: string[];\n components: Array<{ id: string; variantIds?: string[] }>;\n slots?: SlotDeclInput[];\n /** 'registry' serves the project's published slot_definitions as if declared\n * (and is the only way slotConfig/palette come back). Default 'request'.\n * Requires `registrySlotIds`: the `<Adaptive id>`s THIS page renders. */\n slotsFrom?: 'request' | 'registry';\n /**\n * Registry mode: decide only these published slot ids. Close-out turns\n * every slot decision into a trial without checking an exposure, so an\n * unscoped registry decide accrues trials — and session-level credit — for\n * every published slot on every page, including ones this page never\n * renders (CONTRACTS §2). Omitting it in registry mode is refused: the\n * call downgrades to request mode with one console.error, rather than\n * silently minting those trials.\n */\n registrySlotIds?: string[];\n },\n sessionId: string,\n config: ServerAssignConfig,\n): Promise<DecideResult> {\n const timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n const declaredSlots = params.slots ?? [];\n let registryIds: string[] | null = null;\n if (params.slotsFrom === 'registry') {\n if (Array.isArray(params.registrySlotIds)) {\n registryIds = params.registrySlotIds;\n } else {\n console.error(\n \"[SentientUI] preloadDecisions: slotsFrom: 'registry' needs registrySlotIds (the <Adaptive id>s this page renders). \" +\n 'An unscoped registry decide records a trial for every published slot on every page; falling back to request mode.',\n );\n }\n }\n const fallback: DecideResult = {\n layoutOrder: params.sections ?? [],\n assignments: {},\n slots: baselineSlots(declaredSlots),\n persona: 'unknown',\n confidence: 0,\n };\n\n // Opted-out visitor (DNT/GPC): baseline layout/slots, mint no session (audit P4).\n if (config.doNotTrack) return fallback;\n\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${config.apiKey}`,\n };\n if (config.origin) headers.Origin = config.origin;\n\n const sessionBody = {\n ...buildSessionUpsertPayload(sessionId, {\n userAgent: config.userAgent,\n referer: config.referer,\n utmParams: config.utmParams,\n clickIds: config.clickIds,\n appOrigin: config.origin,\n }),\n ...(config.persona ? { persona: config.persona } : {}),\n };\n\n try {\n const sessionRes = await fetchWithTimeout(\n `${config.baseUrl}/sessions`,\n { method: 'POST', headers, body: JSON.stringify(sessionBody) },\n timeoutMs,\n );\n if (!sessionRes.ok) {\n const body = await sessionRes.json().catch(() => ({}));\n console.error(`[SentientUI] preloadDecisions: session upsert failed (${sessionRes.status})`, body);\n }\n } catch (err) {\n console.error('[SentientUI] preloadDecisions: session upsert threw', err);\n }\n\n try {\n const res = await fetchWithTimeout(\n `${config.baseUrl}/decide`,\n {\n method: 'POST',\n headers,\n body: JSON.stringify({\n sessionId,\n sections: (params.sections ?? []).map((id) => ({ id })),\n components: params.components,\n ...(declaredSlots.length > 0 ? { slots: declaredSlots.map(toWireSlot) } : {}),\n // bootstrap:false — editor goals and the section map are snippet\n // data the React SDK never reads. An EMPTY id list is meaningful\n // (\"nothing published is on this page\"): zero trials, still a decide.\n ...(registryIds !== null ? { slotsFrom: 'registry', registrySlotIds: registryIds, bootstrap: false } : {}),\n ...(config.persona ? { persona: config.persona } : {}),\n }),\n },\n timeoutMs,\n );\n if (!res.ok) {\n const body = await res.json().catch(() => ({}));\n console.error(`[SentientUI] preloadDecisions: decide failed (${res.status})`, body);\n return fallback;\n }\n const data = (await res.json()) as {\n layoutOrder?: string[];\n assignments?: Record<string, string>;\n slots?: Record<string, SlotResult>;\n slotConfig?: Record<string, SlotConfigEntry>;\n palette?: SitePalette;\n persona?: string;\n confidence?: number;\n };\n\n const slots: Record<string, SlotResult> = {};\n for (const d of declaredSlots) {\n // `data.slots === undefined` ⇒ server predates slots: baseline, no retry.\n slots[d.id] = data.slots?.[d.id] ?? baselineResultFor(d);\n }\n // Registry mode returns slots the request never declared — union them in\n // (same rule as the browser client), or an SSR page gets results for none\n // of its registry slots.\n for (const [slotId, result] of Object.entries(data.slots ?? {})) {\n if (!(slotId in slots)) slots[slotId] = result;\n }\n\n // Plain-object guard only (readSnapshot's rule): the server total-validated\n // the config at publish; a deep re-validation here would just drift.\n const slotConfigOk =\n data.slotConfig !== undefined && typeof data.slotConfig === 'object' && data.slotConfig !== null && !Array.isArray(data.slotConfig);\n\n return {\n layoutOrder: data.layoutOrder ?? params.sections ?? [],\n assignments: data.assignments ?? {},\n slots,\n persona: data.persona ?? 'unknown',\n confidence: data.confidence ?? 0,\n ...(slotConfigOk ? { slotConfig: data.slotConfig } : {}),\n ...(data.palette ? { palette: data.palette } : {}),\n };\n } catch (err) {\n console.error('[SentientUI] preloadDecisions: decide threw', err);\n return fallback;\n }\n}\n"],"mappings":"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","names":["DEFAULT_TIMEOUT_MS","fetchWithTimeout","url","init","timeoutMs","controller","timer","__spreadProps","__spreadValues","preloadAssignments","components","sessionId","config","_a","headers","sessionBody","buildSessionUpsertPayload","res","body","err","results","id","variantIds","assignments","result","readSessionCookie","cookies","apiKey","_b","_c","_d","sessionCookieName","LEGACY_SESSION_COOKIE_NAME","preloadDecisions","params","_e","_f","_g","_h","_i","_j","_k","_l","declaredSlots","registryIds","fallback","baselineSlots","sessionRes","toWireSlot","data","slots","baselineResultFor","slotId","slotConfigOk"]}
|
|
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 { SitePalette } from './blocks.js';\n\nexport type { SlotDeclInput, SlotResult, SlotConfigEntry, SitePalette };\n\nexport type ServerAssignConfig = {\n /** Public API key (pk_...). */\n apiKey: string;\n /**\n * Base URL of the Sentient API without trailing slash.\n * e.g. 'https://api.yourapp.com/v1'\n */\n baseUrl: string;\n /**\n * Browser origin of your app (e.g. `http://localhost:3001`). Required for `pk_`\n * keys — server-side fetch must send the same `Origin` the API allows.\n */\n origin?: string;\n /** From `User-Agent` request header (Next.js `headers()`). */\n userAgent?: string;\n /** From `Referer` request header. */\n referer?: string;\n utmParams?: Record<string, string>;\n /**\n * Ad-platform click IDs (gclid, fbclid, ttclid, …) from the landing URL.\n * Derive both this and `utmParams` with `extractTrackedParams(searchParams)`\n * — the Referer header never carries the landing page's own query string, so\n * without these two fields SSR-minted sessions have no campaign attribution\n * until the client SDK hydrates.\n */\n clickIds?: Record<string, string>;\n /**\n * Set true when the request carries a tracking opt-out — `DNT: 1` or\n * `Sec-GPC: 1`. When set, the SSR helpers skip the session upsert and the\n * assign/decide call entirely: the page renders defaults/baseline and no\n * session row is minted for the visitor (audit P4). The client SDK already\n * no-ops for these visitors; this keeps the server from minting a session +\n * assignment on every page view before the client can.\n */\n doNotTrack?: boolean;\n /**\n * Declared persona — the role your app already knows for this visitor\n * (e.g. from your auth context during SSR). Same contract as the client\n * option: must be a vocabulary key; unrecognized values are ignored\n * server-side. Never a user id or email.\n */\n persona?: string;\n /**\n * Milliseconds to wait for the API before returning default variants.\n * Prevents slow/cold API from blocking SSR. Defaults to 1000 — the hot path\n * is served from in-process caches and typically returns in well under\n * 150 ms. The full 1 s budget is only reached on a cold start or an API\n * geographically distant from your SSR host, after which defaults render\n * with no layout shift. Lower it if your API is co-located and warm.\n */\n timeoutMs?: number;\n};\n\n/** componentId → assigned variantId */\nexport type ServerAssignments = Record<string, string>;\n\ntype AssignResult = { variantId: string; assignmentTtlMs: number };\n\nconst DEFAULT_TIMEOUT_MS = 1000;\n\nfunction fetchWithTimeout(\n url: string,\n init: RequestInit,\n timeoutMs: number,\n): Promise<Response> {\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), timeoutMs);\n return fetch(url, { ...init, signal: controller.signal }).finally(() =>\n clearTimeout(timer),\n );\n}\n\n/**\n * Fetches variant assignments server-side for all listed components.\n * Returns a map suitable for passing as `initialAssignments` to `<AdaptiveProvider>`.\n *\n * Call from Next.js layout, Server Component, or getServerSideProps.\n *\n * @example\n * ```tsx\n * const assignments = await preloadAssignments(\n * [\n * { id: 'hero', variantIds: ['hero-a', 'hero-b'] },\n * { id: 'cta', variantIds: ['cta-short', 'cta-long'] },\n * ],\n * sessionId, // read from cookies() or req.cookies\n * { apiKey: process.env.NEXT_PUBLIC_SENTIENT_API_KEY!, baseUrl: 'https://api.sentient-ui.com/v1' },\n * );\n * return <AdaptiveProvider ... initialAssignments={assignments}>{children}</AdaptiveProvider>;\n * ```\n */\nexport async function preloadAssignments(\n components: Array<{ id: string; variantIds: string[] }>,\n sessionId: string,\n config: ServerAssignConfig,\n): Promise<ServerAssignments> {\n // Opted-out visitor (DNT/GPC): render defaults, mint no session (audit P4).\n if (config.doNotTrack) return {};\n\n const timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${config.apiKey}`,\n };\n if (config.origin) {\n headers.Origin = config.origin;\n }\n\n // Session metadata must match the browser SDK so assign seeds variant_weights\n // under the same segment (not `unknown:unknown`).\n const sessionBody = {\n ...buildSessionUpsertPayload(sessionId, {\n userAgent: config.userAgent,\n referer: config.referer,\n utmParams: config.utmParams,\n clickIds: config.clickIds,\n appOrigin: config.origin,\n }),\n ...(config.persona ? { persona: config.persona } : {}),\n };\n\n try {\n const res = await fetchWithTimeout(\n `${config.baseUrl}/sessions`,\n { method: 'POST', headers, body: JSON.stringify(sessionBody) },\n timeoutMs,\n );\n if (res.status === 402) {\n console.warn(\n '[SentientUI] Session limit exceeded for this project. The bandit will stop learning until the limit resets. Upgrade at sentient-ui.com/pricing',\n );\n } else if (!res.ok) {\n const body = await res.json().catch(() => ({}));\n console.error(`[SentientUI] preloadAssignments: session upsert failed (${res.status})`, body);\n }\n } catch (err) {\n console.error('[SentientUI] preloadAssignments: session upsert threw', err);\n }\n\n const results = await Promise.allSettled(\n components.map(async ({ id, variantIds }) => {\n const res = await fetchWithTimeout(\n `${config.baseUrl}/assign`,\n { method: 'POST', headers, body: JSON.stringify({ sessionId, componentId: id, variantIds }) },\n timeoutMs,\n );\n if (!res.ok) {\n const body = await res.json().catch(() => ({}));\n console.error(`[SentientUI] preloadAssignments: assign failed for \"${id}\" (${res.status})`, body);\n return null;\n }\n const body = (await res.json()) as AssignResult;\n return { id, variantId: body.variantId };\n }),\n );\n\n const assignments: ServerAssignments = {};\n for (const result of results) {\n if (result.status === 'fulfilled' && result.value) {\n assignments[result.value.id] = result.value.variantId;\n }\n }\n return assignments;\n}\n\n/**\n * Reads the Sentient session cookie from a Next.js `ReadonlyRequestCookies` object\n * (the return value of `cookies()` from `next/headers`), or any object with a\n * `get(name: string)` method. Returns null if the cookie is absent.\n *\n * Pass the project's `apiKey`: the client writes the per-project SUFFIXED name\n * (`sessionCookieName` — see storage-key.ts), so reading only the bare\n * `_snt_uid` missed the cookie on every SSR request for a returning visitor and\n * minted a fresh orphan session each page view (quota inflation, broken sticky\n * assignments and persona continuity). The bare name is still read as a\n * fallback for identities minted before namespacing.\n */\nexport function readSessionCookie(\n cookies: { get(name: string): { value: string } | undefined },\n apiKey?: string,\n): string | null {\n return (\n (apiKey ? cookies.get(sessionCookieName(apiKey))?.value : undefined) ??\n cookies.get(LEGACY_SESSION_COOKIE_NAME)?.value ??\n null\n );\n}\n\nexport type DecideResult = {\n layoutOrder: string[];\n assignments: Record<string, string>;\n /** Slot results keyed by slot id. Baseline-resolved when the API omits/fails them. */\n slots: Record<string, SlotResult>;\n persona: string;\n confidence: number;\n /** Registry mode only: content/ops/blocks for server-defined slots. */\n slotConfig?: Record<string, SlotConfigEntry>;\n /** Registry mode only: site palette for block rendering. */\n palette?: SitePalette;\n};\n\n/**\n * Single-roundtrip SSR call returning layout order, component assignments,\n * and adaptive-slot results. Falls back to default section order + empty\n * assignments + baseline slots if the API is unavailable. A response without\n * a `slots` field means the server predates slots — every declared slot\n * resolves to its baseline (no retry).\n */\nexport async function preloadDecisions(\n params: {\n sections?: string[];\n components: Array<{ id: string; variantIds?: string[] }>;\n slots?: SlotDeclInput[];\n /** 'registry' serves the project's published slot_definitions as if declared\n * (and is the only way slotConfig/palette come back). Default 'request'.\n * Requires `registrySlotIds`: the `<Adaptive id>`s THIS page renders. */\n slotsFrom?: 'request' | 'registry';\n /**\n * Registry mode: decide only these published slot ids. Close-out turns\n * every slot decision into a trial without checking an exposure, so an\n * unscoped registry decide accrues trials — and session-level credit — for\n * every published slot on every page, including ones this page never\n * renders (CONTRACTS §2). Omitting it in registry mode is refused: the\n * call downgrades to request mode with one console.error, rather than\n * silently minting those trials.\n */\n registrySlotIds?: string[];\n },\n sessionId: string,\n config: ServerAssignConfig,\n): Promise<DecideResult> {\n const timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n const declaredSlots = params.slots ?? [];\n let registryIds: string[] | null = null;\n if (params.slotsFrom === 'registry') {\n if (Array.isArray(params.registrySlotIds)) {\n registryIds = params.registrySlotIds;\n } else {\n console.error(\n \"[SentientUI] preloadDecisions: slotsFrom: 'registry' needs registrySlotIds (the <Adaptive id>s this page renders). \" +\n 'An unscoped registry decide records a trial for every published slot on every page; falling back to request mode.',\n );\n }\n }\n const fallback: DecideResult = {\n layoutOrder: params.sections ?? [],\n assignments: {},\n slots: baselineSlots(declaredSlots),\n persona: 'unknown',\n confidence: 0,\n };\n\n // Opted-out visitor (DNT/GPC): baseline layout/slots, mint no session (audit P4).\n if (config.doNotTrack) return fallback;\n\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${config.apiKey}`,\n };\n if (config.origin) headers.Origin = config.origin;\n\n const sessionBody = {\n ...buildSessionUpsertPayload(sessionId, {\n userAgent: config.userAgent,\n referer: config.referer,\n utmParams: config.utmParams,\n clickIds: config.clickIds,\n appOrigin: config.origin,\n }),\n ...(config.persona ? { persona: config.persona } : {}),\n };\n\n try {\n const sessionRes = await fetchWithTimeout(\n `${config.baseUrl}/sessions`,\n { method: 'POST', headers, body: JSON.stringify(sessionBody) },\n timeoutMs,\n );\n if (!sessionRes.ok) {\n const body = await sessionRes.json().catch(() => ({}));\n console.error(`[SentientUI] preloadDecisions: session upsert failed (${sessionRes.status})`, body);\n }\n } catch (err) {\n console.error('[SentientUI] preloadDecisions: session upsert threw', err);\n }\n\n try {\n const res = await fetchWithTimeout(\n `${config.baseUrl}/decide`,\n {\n method: 'POST',\n headers,\n body: JSON.stringify({\n sessionId,\n sections: (params.sections ?? []).map((id) => ({ id })),\n components: params.components,\n ...(declaredSlots.length > 0 ? { slots: declaredSlots.map(toWireSlot) } : {}),\n // bootstrap:false — editor goals and the section map are snippet\n // data the React SDK never reads. An EMPTY id list is meaningful\n // (\"nothing published is on this page\"): zero trials, still a decide.\n ...(registryIds !== null ? { slotsFrom: 'registry', registrySlotIds: registryIds, bootstrap: false } : {}),\n ...(config.persona ? { persona: config.persona } : {}),\n }),\n },\n timeoutMs,\n );\n if (!res.ok) {\n const body = await res.json().catch(() => ({}));\n console.error(`[SentientUI] preloadDecisions: decide failed (${res.status})`, body);\n return fallback;\n }\n const data = (await res.json()) as {\n layoutOrder?: string[];\n assignments?: Record<string, string>;\n slots?: Record<string, SlotResult>;\n slotConfig?: Record<string, SlotConfigEntry>;\n palette?: SitePalette;\n persona?: string;\n confidence?: number;\n };\n\n const slots: Record<string, SlotResult> = {};\n for (const d of declaredSlots) {\n // `data.slots === undefined` ⇒ server predates slots: baseline, no retry.\n slots[d.id] = data.slots?.[d.id] ?? baselineResultFor(d);\n }\n // Registry mode returns slots the request never declared — union them in\n // (same rule as the browser client), or an SSR page gets results for none\n // of its registry slots.\n for (const [slotId, result] of Object.entries(data.slots ?? {})) {\n if (!(slotId in slots)) slots[slotId] = result;\n }\n\n // Plain-object guard only (readSnapshot's rule): the server total-validated\n // the config at publish; a deep re-validation here would just drift.\n const slotConfigOk =\n data.slotConfig !== undefined && typeof data.slotConfig === 'object' && data.slotConfig !== null && !Array.isArray(data.slotConfig);\n\n return {\n layoutOrder: data.layoutOrder ?? params.sections ?? [],\n assignments: data.assignments ?? {},\n slots,\n persona: data.persona ?? 'unknown',\n confidence: data.confidence ?? 0,\n ...(slotConfigOk ? { slotConfig: data.slotConfig } : {}),\n ...(data.palette ? { palette: data.palette } : {}),\n };\n } catch (err) {\n console.error('[SentientUI] preloadDecisions: decide threw', err);\n return fallback;\n }\n}\n","// 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":"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","names":["DEFAULT_TIMEOUT_MS","fetchWithTimeout","url","init","timeoutMs","controller","timer","__spreadProps","__spreadValues","preloadAssignments","components","sessionId","config","_a","headers","sessionBody","buildSessionUpsertPayload","res","body","err","results","id","variantIds","assignments","result","readSessionCookie","cookies","apiKey","_b","_c","_d","sessionCookieName","LEGACY_SESSION_COOKIE_NAME","preloadDecisions","params","_e","_f","_g","_h","_i","_j","_k","_l","declaredSlots","registryIds","fallback","baselineSlots","sessionRes","toWireSlot","data","slots","d","baselineResultFor","slotId","slotConfigOk","DEFAULT_API_BASE_URL","pathOf","url","e","postAgentFetch","entry","opts","_a","_b","_c","_d","doFetch","p","captureAgentRequest","req","userAgent","botName","matchedAgentToken","sentientAgentMiddleware","_res","next","raw","ua","__spreadProps","__spreadValues"]}
|
package/dist/index.d.cts
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
export { A as AGENT_INTENTS, a as AgentIntent, B as BLOCK_ALIGNS, b as BLOCK_EMPHASES, c as BLOCK_FITS, d as BLOCK_GAPS, e as BLOCK_GRID_COLUMNS, f as BLOCK_HEADING_LEVELS, g as BLOCK_JUSTIFIES, h as BLOCK_MAX_WIDTHS, i as BLOCK_PADS, j as BLOCK_RATIOS, k as BLOCK_SIZES, l as BLOCK_SURFACES, m as BLOCK_TEXT_ALIGNS, n as BLOCK_TONES, o as BLOCK_WEIGHTS, p as BadgeBlock, q as BlockAlign, r as BlockEmphasis, s as BlockFit, t as BlockGap, u as BlockJustify, v as BlockMaxWidth, w as BlockNode, x as BlockPad, y as BlockRatio, z as BlockSize, C as BlockSurface, D as BlockTextAlign, E as BlockTone, F as BlockWeight, G as ButtonBlock, H as CLICK_ID_KEYS, I as CompoundLocator, J as DecisionSnapshot, K as DividerBlock, L as FORM_FIELD_KINDS, M as FORM_INPUT_TYPES, N as FormBlock, O as FormField, P as GridBlock, Q as HeadingBlock, R as ImageBlock, S as LinkBlock, T as MAX_BLOCK_ARMS, U as MAX_BLOCK_CHILDREN, V as MAX_BLOCK_DEPTH, W as MAX_BLOCK_NODES, X as MAX_BLOCK_TEXT_LEN, Y as MAX_FORM_FIELDS, Z as MAX_FORM_SELECT_OPTIONS, _ as SNAPSHOT_STORAGE_KEY_PREFIX, a0 as SitePalette, a1 as SlotConfigEntry, a2 as SlotDeclInput, a3 as SlotOps, a4 as SpacerBlock, a5 as StackBlock, a6 as TextBlock, a7 as agentIntent, a8 as agentUaList, a9 as armOfResult, aa as baselineResultFor, ab as baselineSlots, ad as classifiedAgents, ae as containsFormBlock, af as deriveSessionSegment, ag as detectDeviceClass, ah as detectTimeOfDay, ai as detectTrafficSource, aj as extractTrackedParams, ak as matchedAgentToken, al as readSnapshot, am as referrerDomainFromReferer, an as renderPrePaintScript, ao as toWireSlot, ap as uaTokenMatch, aq as writeSnapshot } from './session-meta-DydKfQiR.cjs';
|
|
2
|
-
export { A as AssignResult, a as Assignment, C as ComponentGoalOptions, c as ComponentWeightEntry, D as DecideInput, d as DecideOutcome, e as EventType, G as GoalDefinition, f as GoalOptions, h as GraphConfig, i as GraphSnapshot, L as LEGACY_SESSION_COOKIE_NAME, j as LOCAL_MODE_BANNER, M as MicroSignalEmitter, k as MicroSignalType, P as PAGE_SCOPE_RE, l as PROD_KEYLESS_ERROR, Q as QueueConfig, R as REVEAL_MS, n as RevealOptions, S as SectionMapEntry, o as SentientClient, p as SentientConfig, q as SentientEvent, r as SessionConfig, s as SessionManager, W as WeightEntry, _ as _registerConsentUpgradeInit, t as attachMicroSignalDetectors, u as grantConsent, v as init, w as isDoNotTrackEnabled, x as pageScopeMatches, y as resetRevealStyles, z as reveal, F as sessionCookieName } from './index-
|
|
2
|
+
export { A as AssignResult, a as Assignment, C as ComponentGoalOptions, c as ComponentWeightEntry, D as DecideInput, d as DecideOutcome, e as EventType, G as GoalDefinition, f as GoalOptions, h as GraphConfig, i as GraphSnapshot, L as LEGACY_SESSION_COOKIE_NAME, j as LOCAL_MODE_BANNER, M as MicroSignalEmitter, k as MicroSignalType, P as PAGE_SCOPE_RE, l as PROD_KEYLESS_ERROR, Q as QueueConfig, R as REVEAL_MS, n as RevealOptions, S as SectionMapEntry, o as SentientClient, p as SentientConfig, q as SentientEvent, r as SessionConfig, s as SessionManager, W as WeightEntry, _ as _registerConsentUpgradeInit, t as attachMicroSignalDetectors, u as grantConsent, v as init, w as isDoNotTrackEnabled, x as pageScopeMatches, y as resetRevealStyles, z as reveal, F as sessionCookieName } from './index-COl_pfNm.cjs';
|
|
3
3
|
export { SlotResult } from '@sentientui/policy';
|
package/dist/index.d.ts
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
export { A as AGENT_INTENTS, a as AgentIntent, B as BLOCK_ALIGNS, b as BLOCK_EMPHASES, c as BLOCK_FITS, d as BLOCK_GAPS, e as BLOCK_GRID_COLUMNS, f as BLOCK_HEADING_LEVELS, g as BLOCK_JUSTIFIES, h as BLOCK_MAX_WIDTHS, i as BLOCK_PADS, j as BLOCK_RATIOS, k as BLOCK_SIZES, l as BLOCK_SURFACES, m as BLOCK_TEXT_ALIGNS, n as BLOCK_TONES, o as BLOCK_WEIGHTS, p as BadgeBlock, q as BlockAlign, r as BlockEmphasis, s as BlockFit, t as BlockGap, u as BlockJustify, v as BlockMaxWidth, w as BlockNode, x as BlockPad, y as BlockRatio, z as BlockSize, C as BlockSurface, D as BlockTextAlign, E as BlockTone, F as BlockWeight, G as ButtonBlock, H as CLICK_ID_KEYS, I as CompoundLocator, J as DecisionSnapshot, K as DividerBlock, L as FORM_FIELD_KINDS, M as FORM_INPUT_TYPES, N as FormBlock, O as FormField, P as GridBlock, Q as HeadingBlock, R as ImageBlock, S as LinkBlock, T as MAX_BLOCK_ARMS, U as MAX_BLOCK_CHILDREN, V as MAX_BLOCK_DEPTH, W as MAX_BLOCK_NODES, X as MAX_BLOCK_TEXT_LEN, Y as MAX_FORM_FIELDS, Z as MAX_FORM_SELECT_OPTIONS, _ as SNAPSHOT_STORAGE_KEY_PREFIX, a0 as SitePalette, a1 as SlotConfigEntry, a2 as SlotDeclInput, a3 as SlotOps, a4 as SpacerBlock, a5 as StackBlock, a6 as TextBlock, a7 as agentIntent, a8 as agentUaList, a9 as armOfResult, aa as baselineResultFor, ab as baselineSlots, ad as classifiedAgents, ae as containsFormBlock, af as deriveSessionSegment, ag as detectDeviceClass, ah as detectTimeOfDay, ai as detectTrafficSource, aj as extractTrackedParams, ak as matchedAgentToken, al as readSnapshot, am as referrerDomainFromReferer, an as renderPrePaintScript, ao as toWireSlot, ap as uaTokenMatch, aq as writeSnapshot } from './session-meta-DydKfQiR.js';
|
|
2
|
-
export { A as AssignResult, a as Assignment, C as ComponentGoalOptions, c as ComponentWeightEntry, D as DecideInput, d as DecideOutcome, e as EventType, G as GoalDefinition, f as GoalOptions, h as GraphConfig, i as GraphSnapshot, L as LEGACY_SESSION_COOKIE_NAME, j as LOCAL_MODE_BANNER, M as MicroSignalEmitter, k as MicroSignalType, P as PAGE_SCOPE_RE, l as PROD_KEYLESS_ERROR, Q as QueueConfig, R as REVEAL_MS, n as RevealOptions, S as SectionMapEntry, o as SentientClient, p as SentientConfig, q as SentientEvent, r as SessionConfig, s as SessionManager, W as WeightEntry, _ as _registerConsentUpgradeInit, t as attachMicroSignalDetectors, u as grantConsent, v as init, w as isDoNotTrackEnabled, x as pageScopeMatches, y as resetRevealStyles, z as reveal, F as sessionCookieName } from './index-
|
|
2
|
+
export { A as AssignResult, a as Assignment, C as ComponentGoalOptions, c as ComponentWeightEntry, D as DecideInput, d as DecideOutcome, e as EventType, G as GoalDefinition, f as GoalOptions, h as GraphConfig, i as GraphSnapshot, L as LEGACY_SESSION_COOKIE_NAME, j as LOCAL_MODE_BANNER, M as MicroSignalEmitter, k as MicroSignalType, P as PAGE_SCOPE_RE, l as PROD_KEYLESS_ERROR, Q as QueueConfig, R as REVEAL_MS, n as RevealOptions, S as SectionMapEntry, o as SentientClient, p as SentientConfig, q as SentientEvent, r as SessionConfig, s as SessionManager, W as WeightEntry, _ as _registerConsentUpgradeInit, t as attachMicroSignalDetectors, u as grantConsent, v as init, w as isDoNotTrackEnabled, x as pageScopeMatches, y as resetRevealStyles, z as reveal, F as sessionCookieName } from './index-CgkImSaM.js';
|
|
3
3
|
export { SlotResult } from '@sentientui/policy';
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var tn=Object.create;var we=Object.defineProperty,nn=Object.defineProperties,on=Object.getOwnPropertyDescriptor,rn=Object.getOwnPropertyDescriptors,sn=Object.getOwnPropertyNames,It=Object.getOwnPropertySymbols,an=Object.getPrototypeOf,Ct=Object.prototype.hasOwnProperty,ln=Object.prototype.propertyIsEnumerable;var _t=(e,t,n)=>t in e?we(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,O=(e,t)=>{for(var n in t||(t={}))Ct.call(t,n)&&_t(e,n,t[n]);if(It)for(var n of It(t))ln.call(t,n)&&_t(e,n,t[n]);return e},de=(e,t)=>nn(e,rn(t));var cn=(e,t)=>{for(var n in t)we(e,n,{get:t[n],enumerable:!0})},Rt=(e,t,n,u)=>{if(t&&typeof t=="object"||typeof t=="function")for(let g of sn(t))!Ct.call(e,g)&&g!==n&&we(e,g,{get:()=>t[g],enumerable:!(u=on(t,g))||u.enumerable});return e};var dn=(e,t,n)=>(n=e!=null?tn(an(e)):{},Rt(t||!e||!e.__esModule?we(n,"default",{value:e,enumerable:!0}):n,e)),un=e=>Rt(we({},"__esModule",{value:!0}),e);var po={};cn(po,{AGENT_INTENTS:()=>Ke,BLOCK_ALIGNS:()=>Pn,BLOCK_EMPHASES:()=>Nn,BLOCK_FITS:()=>Un,BLOCK_GAPS:()=>On,BLOCK_GRID_COLUMNS:()=>Fn,BLOCK_HEADING_LEVELS:()=>$n,BLOCK_JUSTIFIES:()=>Dn,BLOCK_MAX_WIDTHS:()=>zn,BLOCK_PADS:()=>jn,BLOCK_RATIOS:()=>Gn,BLOCK_SIZES:()=>Bn,BLOCK_SURFACES:()=>Wn,BLOCK_TEXT_ALIGNS:()=>Kn,BLOCK_TONES:()=>Mn,BLOCK_WEIGHTS:()=>Ln,CLICK_ID_KEYS:()=>Ze,FORM_FIELD_KINDS:()=>Hn,FORM_INPUT_TYPES:()=>Qn,LEGACY_SESSION_COOKIE_NAME:()=>Je,LOCAL_MODE_BANNER:()=>et,MAX_BLOCK_ARMS:()=>Zn,MAX_BLOCK_CHILDREN:()=>Yn,MAX_BLOCK_DEPTH:()=>qn,MAX_BLOCK_NODES:()=>Xn,MAX_BLOCK_TEXT_LEN:()=>eo,MAX_FORM_FIELDS:()=>Jn,MAX_FORM_SELECT_OPTIONS:()=>Vn,PAGE_SCOPE_RE:()=>nt,PROD_KEYLESS_ERROR:()=>We,REVEAL_MS:()=>jt,SNAPSHOT_STORAGE_KEY_PREFIX:()=>le,_registerConsentUpgradeInit:()=>oo,agentIntent:()=>Lt,agentUaList:()=>ke,armOfResult:()=>Ue,attachMicroSignalDetectors:()=>Qt,baselineResultFor:()=>ge,baselineSlots:()=>Kt,classifiedAgents:()=>Mt,containsFormBlock:()=>Wt,deriveSessionSegment:()=>Nt,detectDeviceClass:()=>Ie,detectTimeOfDay:()=>Re,detectTrafficSource:()=>_e,extractTrackedParams:()=>Ge,grantConsent:()=>co,init:()=>Yt,isDoNotTrackEnabled:()=>at,matchedAgentToken:()=>Ye,pageScopeMatches:()=>$t,readSnapshot:()=>fe,referrerDomainFromReferer:()=>Ce,renderPrePaintScript:()=>Gt,resetRevealStyles:()=>zt,reveal:()=>Ht,sessionCookieName:()=>Pe,toWireSlot:()=>Ae,uaTokenMatch:()=>Ee,writeSnapshot:()=>me});module.exports=un(po);function Oe(){try{if(typeof crypto!="undefined"&&typeof crypto.randomUUID=="function")return crypto.randomUUID()}catch(e){}try{if(typeof crypto!="undefined"&&typeof crypto.getRandomValues=="function"){let e=new Uint8Array(16);crypto.getRandomValues(e),e[6]=e[6]&15|64,e[8]=e[8]&63|128;let t="";for(let n=0;n<16;n++)t+=e[n].toString(16).padStart(2,"0"),(n===3||n===5||n===7||n===9)&&(t+="-");return t}}catch(e){}return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})}function be(e){return e?`_${e.slice(0,12)}`:""}var Je="_snt_uid";function Pe(e){return`${Je}${be(e)}`}var pn="_snt_uid",gn=365,De="_snt_uid";function fn(){return Oe()}function At(e){try{let t=document.cookie.match(new RegExp(`(?:^|; )${e}=([^;]*)`));return t?decodeURIComponent(t[1]):null}catch(t){return null}}function mn(e,t,n){try{document.cookie=`${e}=${encodeURIComponent(t)}; max-age=${n}; SameSite=strict; path=/`}catch(u){}}function Ve(e){try{return localStorage.getItem(e)}catch(t){return null}}function Tt(e,t){try{return localStorage.setItem(e,t),!0}catch(n){return!1}}function Ot(e){try{return sessionStorage.getItem(e)}catch(t){return null}}function yn(e,t){try{return sessionStorage.setItem(e,t),!0}catch(n){return!1}}function Sn(e){try{sessionStorage.removeItem(e)}catch(t){}}function hn(e){try{return document.cookie=`${e}_probe=1; max-age=1; SameSite=strict; path=/`,document.cookie.indexOf(`${e}_probe=1`)!==-1}catch(t){return!1}}function vn(e){try{localStorage.removeItem(e)}catch(t){}}function xn(e){try{document.cookie=`${e}=; max-age=0; SameSite=strict; path=/`}catch(t){}}var wn={getSessionId:()=>null,isEphemeral:()=>!1,destroy:()=>{}};function Be(e){var p,y,k,b,N,G,P;if(typeof window=="undefined")return wn;let t=be(e==null?void 0:e.apiKey),n=(p=e==null?void 0:e.cookieName)!=null?p:Pe(e==null?void 0:e.apiKey),u=`${De}${t}`,g=`${De}_tomb${t}`,i=((y=e==null?void 0:e.cookieTTLDays)!=null?y:gn)*24*60*60,c=L=>L&&L.length>0?L:null,f=()=>{var L,D;return t&&!(e!=null&&e.cookieName)&&Ve(g)===null?(D=(L=c(At(pn)))!=null?L:c(Ve(De)))!=null?D:c(Ot(De)):null},s=(P=(G=(N=(b=(k=c(At(n)))!=null?k:c(Ve(u)))!=null?b:c(Ot(u)))!=null?N:f())!=null?G:c(e==null?void 0:e.ssrSessionId))!=null?P:fn();mn(n,s,i);let r=Tt(u,s),a=hn(n),w=r?!1:yn(u,s),A=!r&&!a&&!w;return{getSessionId:()=>s,isEphemeral:()=>A,destroy:()=>{s=null,xn(n),vn(u),Sn(u),t&&!(e!=null&&e.cookieName)&&Tt(g,"1")}}}function Y(e){return Math.min(6e4,1e3*2**Math.min(e,6))}function ue(e){if(e.ok===!0)return"delivered";let{status:t}=e;return typeof t!="number"?"retry":t>=200&&t<300?"delivered":t>=400&&t<500&&t!==429?"dropped":"retry"}function Le(e,t){try{let n=localStorage.getItem(e);if(!n)return[];let u=JSON.parse(n);return Array.isArray(u)?(localStorage.removeItem(e),u.slice(-t)):[]}catch(n){return[]}}function oe(e,t,n){try{let u=(()=>{try{let l=localStorage.getItem(n);if(!l)return[];let i=JSON.parse(l);return Array.isArray(i)?i:[]}catch(l){return[]}})(),g=new Map;for(let l of u)g.set(l.id,l);for(let l of e)g.set(l.id,l);localStorage.setItem(n,JSON.stringify([...g.values()].slice(-t)))}catch(u){}}function Me(e,t){try{let n=localStorage.getItem(t);if(!n)return;let u=JSON.parse(n);if(!Array.isArray(u))return;let g=new Set(e),l=u.filter(i=>!g.has(i.id));if(l.length===u.length)return;l.length===0?localStorage.removeItem(t):localStorage.setItem(t,JSON.stringify(l))}catch(n){}}var bn=500,kn=56*1024;function Xe(e){return`_snt_retry_${e.slice(0,12)}`}var En={push:()=>{},flush:()=>{},destroy:()=>{}};function Pt(e){var V,X,Se;if(typeof window=="undefined")return En;let t=(V=e.flushIntervalMs)!=null?V:5e3,n=(X=e.maxBatchSize)!=null?X:20,u=(Se=e.maxRetrySize)!=null?Se:100,g=e.ingestUrl,l=e.apiKey,i=Xe(l),c=[],f=new Set,s=[],r=v=>{for(let R of v)a.delete(R),!f.has(R)&&(f.add(R),s.push(R));for(;s.length>bn;){let R=s.shift();R&&f.delete(R)}Me(v,i)},a=new Set,w=()=>{for(;c.length>u;){let v=c.shift();v&&a.delete(v.id)}},A=v=>{f.has(v.id)||a.has(v.id)||(a.add(v.id),c.push(v),w())},p=v=>{for(let R of v)f.has(R.id)||(a.add(R.id),c.push(R));w()},y=Le(i,u);for(let v of y)A(v);let k=0,b=0,N=(v,R=!0)=>{if(v.length===0)return;let j=JSON.stringify(v),Q=v.map(H=>H.id),z;try{z=fetch(g,{method:"POST",keepalive:!0,body:j,headers:{"Content-Type":"application/json",Authorization:`Bearer ${l}`}})}catch(H){oe(v,u,i),p(v),b++,k=Date.now()+Y(b);return}let re=H=>{if(ue(H)!=="retry"){if(!H.ok&&R){let se=v.filter(ie=>ie.eventType!=="pageview");if(se.length>0&&se.length<v.length){r(v.filter(ie=>ie.eventType==="pageview").map(ie=>ie.id)),N(se,!1);return}}r(Q),b=0,k=0;return}oe(v,u,i),p(v),b++,k=Date.now()+Y(b)};z instanceof Promise?z.then(re).catch(()=>{oe(v,u,i),p(v),b++,k=Date.now()+Y(b)}):re(z)},G=typeof TextEncoder!="undefined"?new TextEncoder:null,P=v=>G?G.encode(v).length:v.length,L=v=>{let R=[],j=2;for(let Q of v){let z=P(JSON.stringify(Q))+1;if(R.length>0&&j+z>kn||R.length>=n)break;R.push(Q),j+=z}return R},D=()=>{try{if(Date.now()<k)return;for(;c.length>0&&!(Date.now()<k);){let v=c.filter(j=>!f.has(j.id));if(c.length=0,v.length===0)break;let R=L(v);if(R.length===0)break;R.length<v.length&&c.push(...v.slice(R.length)),N(R)}}catch(v){}},h=!0,I=null;I=setInterval(()=>{h&&D()},t);let Z=()=>{document.visibilityState==="hidden"&&D()},W=()=>{D()};return document.addEventListener("visibilitychange",Z),window.addEventListener("pagehide",W),{push(v){A(v),c.length>=n&&D()},flush:D,destroy(){h=!1,I!==null&&(clearInterval(I),I=null),document.removeEventListener("visibilitychange",Z),window.removeEventListener("pagehide",W),D()}}}var In=200;function qe(e){return`_snt_goal_retry_${e.slice(0,12)}`}var _n={send:()=>{},flush:()=>{},destroy:()=>{}};function Dt(e){var P,L,D;if(typeof window=="undefined")return _n;let t=(P=e.flushIntervalMs)!=null?P:5e3,n=(L=e.maxRetrySize)!=null?L:100,u=(D=e.maxPerFlush)!=null?D:5,g=qe(e.apiKey),l=[],i=new Set,c=new Set,f=[],s=0,r=0,a=!1,w=h=>{for(i.delete(h.id),c.has(h.id)||(c.add(h.id),f.push(h.id));f.length>In;){let I=f.shift();I&&c.delete(I)}Me([h.id],g)},A=h=>{oe([h],n,g),!c.has(h.id)&&!i.has(h.id)&&(i.add(h.id),l.push(h)),Date.now()>=s&&(r++,s=Date.now()+Y(r))},p=h=>{let I;try{I=fetch(e.url,{method:"POST",keepalive:!0,body:h.body,headers:e.headers})}catch(W){A(h);return}let Z=W=>{var X;let V=ue(W);if(V==="retry"){A(h);return}V==="dropped"&&((X=e.onDrop)==null||X.call(e,h,W.status)),w(h),r=0,s=0};I instanceof Promise?I.then(Z).catch(()=>A(h)):Z(I)},y=()=>{try{if(a||Date.now()<s)return;let h=0;for(;l.length>0&&h<u&&!(Date.now()<s);){let I=l.shift();i.delete(I.id),!c.has(I.id)&&(h++,p(I))}}catch(h){}},k=Le(g,n);for(let h of k)i.has(h.id)||(i.add(h.id),l.push(h));k.length>0&&oe(k,n,g);let b=setInterval(y,t),N=()=>{document.visibilityState==="hidden"&&y()},G=()=>y();return document.addEventListener("visibilitychange",N),window.addEventListener("pagehide",G),{send(h){if(!a&&!(c.has(h.id)||i.has(h.id))){if(Date.now()<s){oe([h],n,g),i.add(h.id),l.push(h);return}p(h)}},flush:y,destroy(){clearInterval(b),document.removeEventListener("visibilitychange",N),window.removeEventListener("pagehide",G),y(),a=!0}}}var Cn=1800*1e3;function Ne(e,t){return`${encodeURIComponent(e)}:${encodeURIComponent(t)}`}function Bt(e=Cn,t){let n=new Map,u=`_snt_asgn${be(t)}_`,g=(s,r)=>`${u}${encodeURIComponent(s)}:${encodeURIComponent(r)}`,l=s=>{let r=s.slice(u.length),a=r.indexOf(":");if(a<0)return null;try{return{componentId:decodeURIComponent(r.slice(0,a)),segment:decodeURIComponent(r.slice(a+1))}}catch(w){return null}},i=()=>{try{let s=[];for(let r=0;r<localStorage.length;r++){let a=localStorage.key(r);a!=null&&a.startsWith(u)&&s.push(a)}return s}catch(s){return[]}},c=s=>s.assignedAt+(s.ttlMs&&s.ttlMs>0?s.ttlMs:e)<Date.now();return typeof window!="undefined"&&(()=>{for(let s of i())try{let r=localStorage.getItem(s);if(!r)continue;let a=JSON.parse(r);if(c(a)){localStorage.removeItem(s);continue}let w=l(s);if(!w)continue;n.set(Ne(w.componentId,w.segment),a)}catch(r){}})(),{get(s,r){let a=n.get(Ne(s,r));return a?c(a)?(n.delete(Ne(s,r)),null):a:null},set(s,r,a){let w=Ne(s,r);n.set(w,a);try{localStorage.setItem(g(s,r),JSON.stringify(a))}catch(A){}},clear(){n.clear();for(let s of i())try{localStorage.removeItem(s)}catch(r){}}}}var ke=["GPTBot","ChatGPT-User","OAI-SearchBot","ClaudeBot","Claude-User","Claude-SearchBot","PerplexityBot","Perplexity-User","Google-Extended","Applebot-Extended","Meta-ExternalAgent","Bytespider","CCBot","Amazonbot","cohere-ai","Diffbot"];function Ee(e){return Ye(e)!==null}function Ye(e){var n;if(!e)return null;let t=e.toLowerCase();return(n=ke.find(u=>t.includes(u.toLowerCase())))!=null?n:null}var Ke={GPTBot:"training","ChatGPT-User":"user","OAI-SearchBot":"search",ClaudeBot:"training","Claude-User":"user","Claude-SearchBot":"search",PerplexityBot:"search","Perplexity-User":"user","Google-Extended":"training","Applebot-Extended":"training","Meta-ExternalAgent":"training",Bytespider:"training",CCBot:"training",Amazonbot:"other","cohere-ai":"training",Diffbot:"other"};function Lt(e){if(!e)return"other";let t=ke.find(n=>n.toLowerCase()===e.toLowerCase());return t&&Ke[t]||"other"}function Mt(){var t;let e={user:[],search:[],training:[],other:[]};for(let n of ke)e[(t=Ke[n])!=null?t:"other"].push(n);return e}function Ie(e){let t=e.toLowerCase();return/ipad|tablet|playbook|kindle|silk/.test(t)?"tablet":/mobi|iphone|ipod|android.*mobile|phone/.test(t)?"mobile":"desktop"}function _e(e,t){if(!e)return"direct";try{let n=new URL(e);if(t)try{if(new URL(t).host===n.host)return"direct"}catch(g){}let u=n.hostname.toLowerCase();return/(^|\.)(google|bing|duckduckgo|yahoo)\./.test(u)?"search":/(^|\.)(twitter\.com|x\.com|facebook\.com|linkedin\.com|reddit\.com|t\.co)$/.test(u)?"social":"referral"}catch(n){return"direct"}}function Ce(e){if(!e)return null;try{return new URL(e).hostname}catch(t){return null}}var Ze=["gclid","gbraid","wbraid","fbclid","ttclid","msclkid","twclid","li_fat_id"];function Ge(e){let t={},n={};try{let u=typeof e=="string"||e instanceof URLSearchParams?new URLSearchParams(e):Object.entries(e).flatMap(([g,l])=>{let i=Array.isArray(l)?l[0]:l;return i===void 0?[]:[[g,i]]});for(let[g,l]of u)g.startsWith("utm_")?g in t||(t[g]=l):Ze.includes(g)&&(g in n||(n[g]=l))}catch(u){}return{utmParams:t,clickIds:n}}function Re(e){let t=e.getHours();return t<6?"night":t<12?"morning":t<18?"afternoon":"evening"}function Nt(e){let t=Rn("__segment__",e);return`${t.deviceClass}:${t.trafficSource}`}function Rn(e,t){var l,i,c,f,s,r,a,w;let n=(i=(l=t==null?void 0:t.userAgent)==null?void 0:l.trim())!=null?i:"",u=(f=(c=t==null?void 0:t.referer)==null?void 0:c.trim())!=null?f:"",g=(s=t==null?void 0:t.now)!=null?s:new Date;return{sessionId:e,ephemeral:!1,utmParams:(r=t==null?void 0:t.utmParams)!=null?r:{},clickIds:(a=t==null?void 0:t.clickIds)!=null?a:{},deviceClass:n?Ie(n):"desktop",trafficSource:u?_e(u,t==null?void 0:t.appOrigin):"direct",referrerDomain:Ce(u),timeOfDay:Re(g),dayOfWeek:(w=["sun","mon","tue","wed","thu","fri","sat"][g.getDay()])!=null?w:"sun",automation:(t==null?void 0:t.webdriver)===!0||Ee(n)}}var pe=require("@sentientui/policy");function Ae(e){return O(O(O({id:e.id},e.arms?{arms:[...e.arms]}:{}),e.dims?{dims:Object.fromEntries(Object.entries(e.dims).map(([t,n])=>[t,[...n]]))}:{}),e.baseline!==void 0?{baseline:e.baseline}:{})}function ge(e){let t=Ae(e);return(0,pe.slotResultFor)(t,(0,pe.slotBaselineArm)(t))}function Kt(e){let t={};for(let n of e)t[n.id]=ge(n);return t}function Ue(e){return typeof e=="string"?e:(0,pe.canonicalArm)(e)}var le="_snt_snap:",An=["low","medium","high"];function fe(e){try{let t=localStorage.getItem(le+e);if(!t)return null;let n=JSON.parse(t);return!n||typeof n!="object"||n.v!==1||typeof n.persona!="string"||typeof n.band!="string"||!An.includes(n.band)||typeof n.slots!="object"||n.slots===null||Array.isArray(n.slots)||!(n.layoutOrder===null||Array.isArray(n.layoutOrder))||typeof n.savedAt!="number"||!(n.slotConfig===void 0||typeof n.slotConfig=="object"&&n.slotConfig!==null&&!Array.isArray(n.slotConfig))?null:n}catch(t){return null}}function me(e,t){try{localStorage.setItem(le+e,JSON.stringify(t))}catch(n){}}function Gt(e){return"(function(){try{var r=localStorage.getItem("+JSON.stringify(le+e).replace(/</g,"\\u003c")+');if(!r)return;var s=JSON.parse(r);if(!s||s.v!==1||typeof s.persona!=="string"||typeof s.band!=="string")return;var d=document.documentElement;if(d.hasAttribute("data-sentient-persona"))return;d.setAttribute("data-sentient-persona",s.persona);d.setAttribute("data-sentient-confidence",s.band);}catch(e){}})();'}var st=require("@sentientui/policy");var $e=require("@sentientui/policy");var We="[sentient] No API key configured \u2014 nothing is being learned. Set NEXT_PUBLIC_SENTIENT_API_KEY or pass localMode: true for local development.",et="[sentient] Local mode \u2014 decisions are simulated on-device and nothing is sent over the network. Add an API key to learn from real traffic.",Ut=!1,Fe=!1;function Tn(){var e;try{return(e=new URLSearchParams(window.location.search).get("sentient_persona"))!=null?e:void 0}catch(t){return}}function Ft(e){var s;let t=Be({ssrSessionId:e.ssrSessionId,apiKey:e.apiKey}),n=(s=t.getSessionId())!=null?s:"local",u=Tn(),g=import("@sentientui/core/local").then(r=>{let a=r;return a.LOCAL_ENGINE_AVAILABLE?(Ut||(Ut=!0,console.info(et)),a):(Fe||(Fe=!0,console.error(We)),null)}).catch(()=>(Fe||(Fe=!0,console.error(We)),null)),l=null,i={low:.15,medium:.5,high:.85},c=(()=>{var a;if(e.initialPersona)return O({},e.initialPersona);let r=fe(e.apiKey||"local");return r?{persona:r.persona,confidence:(a=i[r.band])!=null?a:.15}:null})();function f(r){let a=document.documentElement;a.dataset.sentientPersona===void 0&&(a.dataset.sentientPersona=r.persona,a.dataset.sentientConfidence=(0,$e.confidenceBand)(r.confidence))}return{isLocal:!0,async decide(r){var A,p,y;let a=await g;if(!a)return null;let w=a.createLocalEngine({sessionId:n,forcedPersona:u}).decide(r);return l=de(O({},w),{layoutOrder:(p=(A=w.layoutOrder)!=null?A:l==null?void 0:l.layoutOrder)!=null?p:null,slots:O(O({},(y=l==null?void 0:l.slots)!=null?y:{}),w.slots)}),me(e.apiKey||"local",{v:1,persona:l.persona,band:(0,$e.confidenceBand)(l.confidence),slots:l.slots,layoutOrder:l.layoutOrder,savedAt:Date.now()}),f(w),w},getSlotResult(r){var a,w,A;return(A=(w=l==null?void 0:l.slots[r])!=null?w:(a=e.initialSlots)==null?void 0:a[r])!=null?A:null},getSlotConfig(r){var a,w;return(w=(a=e.initialSlotConfig)==null?void 0:a[r])!=null?w:null},getSitePalette(){var r;return(r=e.initialPalette)!=null?r:null},reportSlots(){},getPersona(){let r=l!=null?l:c;return r?{persona:r.persona,confidence:r.confidence,band:(0,$e.confidenceBand)(r.confidence)}:null},async assign(r,a){var p;let w=await g;return!w||!a||a.length===0?a!=null&&a[0]?{variantId:a[0],assignmentTtlMs:0}:null:{variantId:(p=w.createLocalEngine({sessionId:n,forcedPersona:u}).decide({components:[{id:r,variantIds:a}]}).assignments[r])!=null?p:a[0],assignmentTtlMs:0}},track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},getAssignment:()=>null,fetchWeights:()=>Promise.resolve([]),getGraph:()=>({pageNodes:[],capturedAt:0}),dispose:()=>{},destroy:()=>t.destroy()}}var nt=/^(\*|\/[^\s?#*]*(\/\*)?)$/;function tt(e){let t=e.split(/[?#]/)[0]||"/";return t.length>1?t.replace(/\/+$/,"")||"/":t}function $t(e,t){if(e===void 0||!nt.test(e))return!1;if(e==="*")return!0;let n=tt(t);if(e.endsWith("/*")){let u=tt(e.slice(0,-2));return n.startsWith(u==="/"?"/":`${u}/`)&&n!==u}return n===tt(e)}var On=["none","sm","md","lg"],Pn=["start","center","end","stretch"],Dn=["start","center","end","between"],Bn=["sm","md","lg"],Ln=["normal","medium","bold"],Mn=["default","muted","accent"],Nn=["primary","secondary","ghost"],Kn=["left","center","right"],Gn=["auto","square","landscape","wide"],Un=["cover","contain"],Fn=[2,3,4],$n=[2,3,4],Wn=["default","raised"],jn=["none","sm","md","lg"],zn=["measure"],Hn=["input","textarea","select"],Qn=["text","email","number","tel"],Jn=5,Vn=8,Xn=64,qn=5,Yn=12,Zn=4,eo=500;function Wt(e){if(e==null||typeof e!="object"||Array.isArray(e))return!1;let t=e;return t.type==="form"?!0:Array.isArray(t.children)?t.children.some(Wt):!1}var ot="sentient-reveal",ye="sentient-revealed",jt=240,je=!1;function zt(){var e;je=!1,typeof document!="undefined"&&((e=document.getElementById(ot))==null||e.remove())}function to(e){if(je||e.getElementById(ot)){je=!0;return}let t=e.createElement("style");t.id=ot,t.textContent=`@media (prefers-reduced-motion: no-preference){@keyframes ${ye}{from{opacity:.55;transform:translateY(2px)}to{opacity:1;transform:none}}.${ye}{animation:${ye} 240ms cubic-bezier(.2,.6,.2,1) both}}`,e.head.appendChild(t),je=!0}function Ht(e,t={}){var g;let n=(g=t.doc)!=null?g:typeof document!="undefined"?document:void 0;if(!n||!(e instanceof Element)||(t.arm!==void 0&&e.setAttribute("data-sentient-arm",t.arm),t.persona!==void 0&&e.setAttribute("data-sentient-persona",t.persona),t.previous!==void 0&&t.previous===e.textContent))return!1;to(n),e.classList.remove(ye),e.offsetWidth,e.classList.add(ye);let u=()=>{e.classList.remove(ye),e.removeEventListener("animationend",u)};return e.addEventListener("animationend",u),!0}function Qt(e,t,n,u){let g=[];{let c=!1,f=[],s=()=>{if(c)return;let r=Date.now();for(f.push(r);f.length>0&&r-f[0]>500;)f.shift();f.length>=3&&(c=!0,e("rage_click"))};t.addEventListener("click",s),g.push(()=>t.removeEventListener("click",s))}{let l=!1,i=c=>{if(l||!(c.target instanceof Node)||!t.contains(c.target)&&t!==c.target)return;l=!0;let f=typeof window!="undefined"?window.getSelection():null,s=f?f.toString().length:0;e("text_copy",{selectionLength:s})};document.addEventListener("copy",i),g.push(()=>document.removeEventListener("copy",i))}{let l=!1,i=!1,c=null,f=()=>{c!==null&&(clearTimeout(c),c=null)},s=()=>{l||!i||(f(),c=setTimeout(()=>{!l&&i&&(l=!0,e("scroll_hesitation"))},3e3))},r=()=>{f(),s()},a=A=>{for(let p of A)i=p.intersectionRatio>.3,i?s():f()},w=new IntersectionObserver(a,{threshold:[.3]});w.observe(t),window.addEventListener("scroll",r,{passive:!0}),g.push(()=>{w.disconnect(),window.removeEventListener("scroll",r),f()})}if((u==null?void 0:u.tabLoss)!==!1){let l=!1,i=n!=null?n:Date.now(),c=()=>{if(l||document.visibilityState!=="hidden")return;let f=Date.now()-i;f<15e3&&(l=!0,e("tab_loss",{timeOnPage:f}))};document.addEventListener("visibilitychange",c),g.push(()=>document.removeEventListener("visibilitychange",c))}return()=>{for(let l of g)l()}}function no(){var e;return typeof process=="undefined"||((e=process.env)==null?void 0:e.NODE_ENV)!=="production"}var Jt="https://api.sentient-ui.com/v1/events",$=new Map,Vt=null;function oo(e,t){let n=$.get(e);n&&n.upgrade&&(n.reinit=t)}function ro(e){return"value"in e||"currency"in e||"externalId"in e||"metadata"in e||"weight"in e||"stepIndex"in e}var so=3;function rt(){return Oe()}function ze(){var e;if(typeof window!="undefined")return((e=window.location)==null?void 0:e.pathname)||void 0}function io(){let e=new WeakMap,t=new Map,n=!1,u=(c,f,s)=>{let r=c.get(f);return s===null?r?!0:(c.set(f,new Set),!1):r?r.has(s)?!0:(r.add(s),!1):(c.set(f,new Set([s])),!1)},g=typeof window!="undefined"&&"event"in window,l=()=>{if(!g)return;let c=window.event;return typeof Event=="function"&&c instanceof Event?c:void 0},i=()=>{if(g){Promise.resolve().then(()=>{n=!1,t.clear()});return}let c=!1,f=()=>{c||(c=!0,n=!1,t.clear())};if(setTimeout(f,0),typeof MessageChannel=="function"){let s=new MessageChannel;s.port1.onmessage=()=>{s.port1.close(),s.port2.close(),f()},s.port2.postMessage(0)}};return{firedBefore(c,f){let s=l();if(s){let a=e.get(s);return a||(a=new Map,e.set(s,a)),u(a,c,f)}let r=u(t,c,f);return!r&&!n&&(n=!0,i()),r}}}var Xt=new Set;function ao(e,t,n){let u=typeof window=="undefined"?null:window.history;if(!u)return()=>{};let g=!1,l,i=()=>{if(g)return;let s=ze();!s||s===l||(l=s,e.track({projectId:t,componentId:"__page__",eventType:"pageview",payload:{}}),n(`${t}:${s}`))},c=[];for(let s of["pushState","replaceState"]){let r=u[s],a=function(...w){let A=r.apply(this,w);return i(),A};u[s]=a,c.push([s,r,a])}window.addEventListener("popstate",i);let f=ze();return f&&Xt.has(`${t}:${f}`)?l=f:i(),()=>{if(!g){g=!0,window.removeEventListener("popstate",i);for(let[s,r,a]of c)u[s]===a&&(u[s]=r)}}}var Te={track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},getAssignment:()=>null,assign:()=>Promise.resolve(null),decide:()=>Promise.resolve(null),getSlotResult:()=>null,getSlotConfig:()=>null,getSitePalette:()=>null,reportSlots:()=>{},getPersona:()=>null,fetchWeights:()=>Promise.resolve([]),getGraph:()=>({pageNodes:[],capturedAt:0}),dispose:()=>{},destroy:()=>{}};function lo(){try{return Ge(window.location.search)}catch(e){return{utmParams:{},clickIds:{}}}}function qt(e){return e.replace(/\/events\/?$/,"")}function at(){return typeof navigator!="undefined"&&navigator.globalPrivacyControl===!0?!0:[typeof navigator!="undefined"?navigator.doNotTrack:void 0,typeof window!="undefined"?window.doNotTrack:void 0,typeof navigator!="undefined"?navigator.msDoNotTrack:void 0].some(t=>t==="1"||t==="yes")}function co(e){var f;if(typeof window=="undefined")return;let t=e!=null?e:Vt;if(!t){console.warn("[sentient] grantConsent() called before init()");return}let n=$.get(t);if(!n){console.warn("[sentient] grantConsent() called before init()");return}let{config:u,upgrade:g,reinit:l}=n;if(!g){n.upgradeBlockedReason&&console.warn(n.upgradeBlockedReason);return}if(u.respectDoNotTrack!==!1&&at())return;let i=(l!=null?l:Yt)(de(O({},u),{consent:!0}));g(i);let c=(f=$.get(t))==null?void 0:f.dispose;$.set(t,{config:de(O({},u),{consent:!0}),upgrade:null,dispose:c})}function uo(e){var A;let t=e.preConsentBehavior==="statistical_winner",n=qt((A=e.ingestUrl)!=null?A:Jt),u={"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`},g=new Map,l=new Map,i={track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},getAssignment:()=>null,fetchWeights:()=>Promise.resolve([]),assign(p,y,k){if(!t)return Promise.resolve(null);let b=g.get(p);return b?Promise.resolve(b):it(l,p,async()=>{try{let N=new URLSearchParams({componentId:p});for(let D of y!=null?y:[])N.append("variantIds[]",D);let G=await fetch(`${n}/winner?${N.toString()}`,{headers:u});if(!G.ok)return y!=null&&y[0]?{variantId:y[0],assignmentTtlMs:0}:null;let L={variantId:(await G.json()).variantId,assignmentTtlMs:0};return g.set(p,L),L}catch(N){return y!=null&&y[0]?{variantId:y[0],assignmentTtlMs:0}:null}})},decide:()=>Promise.resolve(null),getSlotResult:()=>null,getSlotConfig:()=>null,getSitePalette:()=>null,reportSlots:()=>{},getPersona:()=>null,getGraph:()=>({pageNodes:[],capturedAt:0}),dispose:()=>{},destroy:()=>{}},c=!1,f=new Set,s=[],r=[],a={track:p=>i.track(p),goal:((p,y,k,b)=>i.goal(p,y,k,b)),componentGoal:(p,y,k)=>i.componentGoal(p,y,k),identify:p=>i.identify(p),getAssignment:(p,y)=>i.getAssignment(p,y),assign:(p,y,k,b)=>i.assign(p,y,k,b),decide:p=>i.decide(p),getSlotResult:p=>i.getSlotResult(p),isSlotDecided:p=>{var y,k;return(k=(y=i.isSlotDecided)==null?void 0:y.call(i,p))!=null?k:!0},getSlotConfig:p=>i.getSlotConfig(p),getSitePalette:()=>i.getSitePalette(),reportSlots:(p,y)=>i.reportSlots(p,y),requestSlots:(p,y)=>{var k;return c?(k=i.requestSlots)==null?void 0:k.call(i,p,y):s.push([p,y])},decideSlots:p=>{var y;return c?(y=i.decideSlots)==null?void 0:y.call(i,p):r.push(...p)},cancelSlots:p=>{var k;if(c)return(k=i.cancelSlots)==null?void 0:k.call(i,p);let y=new Set(p);for(let b of s)b[0]=b[0].filter(N=>!y.has(N));r=r.filter(b=>!y.has(b.id))},onSlotsChanged:p=>(f.add(p),()=>{f.delete(p)}),getPersona:()=>i.getPersona(),fetchWeights:()=>i.fetchWeights(),getGraph:()=>i.getGraph(),dispose:()=>i.dispose(),destroy:()=>i.destroy()};function w(p){var y,k,b;i=p,c=!0,(y=p.onSlotsChanged)==null||y.call(p,()=>f.forEach(N=>N()));for(let[N,G]of s.splice(0))N.length>0&&((k=p.requestSlots)==null||k.call(p,N,G));r.length>0&&((b=p.decideSlots)==null||b.call(p,r.splice(0)))}return{proxy:a,setInner:w}}function it(e,t,n){let u=e.get(t);if(u)return u;let g=(async()=>{try{return await n()}finally{e.delete(t)}})();return e.set(t,g),g}function Yt(e){var gt,ft,mt,yt,St,ht,vt,xt,wt,bt;if(typeof window=="undefined")return Te;Vt=e.apiKey||"local";let t=$.get(e.apiKey||"local");if(t!=null&&t.dispose)try{t.dispose()}catch(o){}let n=e.respectDoNotTrack!==!1&&at(),u=e.consent===!1||n,g=typeof e.apiKey=="string"&&e.apiKey.startsWith("pk_");if(e.localMode===!0||!g&&e.localMode!==!1)return $.set(e.apiKey||"local",{config:e,upgrade:null,upgradeBlockedReason:"[sentient] grantConsent(): this client is keyless/local \u2014 there is no hosted client to upgrade to. Configure a pk_ API key to enable tracking."}),u?Te:Ft(e);if(u){if(!e.apiKey||!e.apiKey.startsWith("pk_"))return e.preConsentBehavior==="statistical_winner"&&console.warn("[sentient] init() called with an invalid apiKey \u2014 expected a pk_ public key. SDK disabled."),$.set(e.apiKey||"local",{config:e,upgrade:null,upgradeBlockedReason:"[sentient] grantConsent(): the client was initialized with an invalid apiKey (expected a pk_ public key) \u2014 consent cannot enable tracking."}),Te;let{proxy:o,setInner:d}=uo(e);return $.set(e.apiKey,{config:e,upgrade:n?null:d}),o}if(!e.apiKey||!e.apiKey.startsWith("pk_"))return console.warn("[sentient] init() called with an invalid apiKey \u2014 expected a pk_ public key. SDK disabled."),Te;if(e.ingestUrl==="")return console.warn("[sentient] init() called with an empty ingestUrl. SDK disabled."),Te;let l=(gt=e.ingestUrl)!=null?gt:Jt,i=Date.now(),c=Be({ssrSessionId:e.ssrSessionId,apiKey:e.apiKey}),f=Bt(void 0,e.apiKey),s=Pt({ingestUrl:l,apiKey:e.apiKey}),r=qt(l),a={"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`},w=new Set,A=Dt({url:`${r}/goals`,apiKey:e.apiKey,headers:a,onDrop:(o,d)=>{if(!e.debug){if(w.has(d))return;w.add(d)}console.warn(`[sentient] goal dropped (HTTP ${d}) \u2014 this will not be retried. `+(d===400?"The session was not found: call init() and let the session upsert complete before firing goals.":d===401||d===403?"Check the API key and that this origin is on the project allowlist.":"See the response status for the cause."),o)}}),p=Ie((ft=navigator.userAgent)!=null?ft:""),y=window.location.origin,k=_e((mt=document.referrer)!=null?mt:"",y),b=(yt=e.sessionSegment)!=null?yt:`${p}:${k}`,N=new Map,G=new Map,P=new Map,L=new Set,D=new Map,h=null,I=null,Z=new Set,W=new Set,V=new Map,X=null,Se=/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,127}$/,v=new Set,R=new Set,j=new Set,Q=new Map,z=null,re=new Set,H=new Map,se=null,ie=2,lt=new Map,He=!1,ct=(o,d,m)=>{var S;let x=new Set,_=1;for(let E of o){d.delete(E);let C=((S=lt.get(E))!=null?S:0)+1;lt.set(E,C),C<=ie&&(x.add(E),C>_&&(_=C))}x.size>0&&setTimeout(()=>{He||m(x)},Y(_))},dt=o=>{for(let d of o)P.has(d.id)||P.set(d.id,ge(d))};if(e.initialSlots)for(let[o,d]of Object.entries(e.initialSlots))P.set(o,d),L.add(o);if(e.initialSlotConfig)for(let[o,d]of Object.entries(e.initialSlotConfig))D.set(o,d);e.initialPalette&&(h=e.initialPalette);let ee=fe(e.apiKey);if(ee){for(let[o,d]of Object.entries(ee.slots))P.has(o)||P.set(o,d);for(let[o,d]of Object.entries((St=ee.slotConfig)!=null?St:{}))D.has(o)||D.set(o,d);!h&&ee.palette&&(h=ee.palette)}let ut={low:.15,medium:.5,high:.85};if(e.initialPersona)I=O({},e.initialPersona);else{let o=document.documentElement.dataset;o.sentientPersona?I={persona:o.sentientPersona,confidence:(vt=ut[(ht=o.sentientConfidence)!=null?ht:"low"])!=null?vt:.15}:ee&&(I={persona:ee.persona,confidence:(xt=ut[ee.band])!=null?xt:.15})}if(e.initialAssignments)for(let[o,d]of Object.entries(e.initialAssignments))f.set(o,b,{variantId:d,assignedAt:Date.now(),segment:b,confidence:1});let te=Promise.resolve(),pt=c.getSessionId();if(pt){let o=Ce((wt=document.referrer)!=null?wt:""),{utmParams:d,clickIds:m}=lo(),x=O(O(O(O({sessionId:pt,deviceClass:p,trafficSource:k,referrerDomain:o,utmParams:d,clickIds:m,timeOfDay:Re(new Date),dayOfWeek:["sun","mon","tue","wed","thu","fri","sat"][new Date().getDay()],ephemeral:c.isEphemeral(),automation:typeof navigator!="undefined"&&navigator.webdriver===!0||Ee((bt=navigator.userAgent)!=null?bt:"")},e.userId?{userId:e.userId}:{}),e.persona?{persona:e.persona}:{}),e.country?{country:e.country}:{}),e.sdk?{sdk:e.sdk.name,sdkVersion:e.sdk.version}:{}),_=async()=>{for(let S=0;;S++){try{let E=await fetch(`${r}/sessions`,{method:"POST",keepalive:!0,body:JSON.stringify(x),headers:a});if(E.status===402){console.warn("[SentientUI] Session limit exceeded for this project. The bandit will stop learning until the limit resets. Upgrade at sentient-ui.com/pricing");return}if(E.ok||ue(E)==="dropped")return}catch(E){}if(S>=so){console.warn("[SentientUI] Could not register the session after retries. Conversions in this visit may not be recorded.");return}await new Promise(E=>setTimeout(E,Y(S+1)))}};try{te=_()}catch(S){}}e.debug&&(console.log("[sentient] initialized",{context:e.context}),window.__sentient={client:null,queue:s});let Zt=io(),ae=null,Qe=!1,K={goal(o,d={},m=1,x=0){var ne,he,ve,xe,ce,T,q;let _=c.getSessionId();if(!_)return;let S=ro(d)?d:{metadata:d},E=[o,(ne=S.externalId)!=null?ne:"",(he=S.stepIndex)!=null?he:x,(ve=S.weight)!=null?ve:m].join("\0"),C=S.value!==void 0?`${S.value}\0${(xe=S.currency)!=null?xe:""}`:null;if(Zt.firedBefore(E,C)){e.debug&&console.log(`[sentient] goal("${o}") already recorded for this action \u2014 not sent twice`);return}let M=rt(),U={sessionId:_,name:o,metadata:(ce=S.metadata)!=null?ce:{},weight:(T=S.weight)!=null?T:m,stepIndex:(q=S.stepIndex)!=null?q:x,goalId:M,value:S.value,currency:S.currency,externalId:S.externalId};e.debug&&console.log("[sentient] goal",U);let F={id:M,body:JSON.stringify(U)};te.then(()=>A.send(F))},componentGoal(o,d,m){var M,U,F;let x=c.getSessionId();if(!x)return;let _=f.get(o,b),S=_?null:(M=P.get(o))!=null?M:null;if(!_&&S===null){e.debug&&console.warn(`[sentient] componentGoal("${o}"): no assignment or slot decision yet \u2014 render its <Adaptive>/adaptive hook or call assign()/decide() before recording a goal.`);return}if(!_&&!L.has(o)){e.debug&&console.warn(`[sentient] componentGoal("${o}"): slot not decided this session \u2014 not attributed`);return}let E=_?_.variantId:Ue(S),C={id:rt(),sessionId:x,projectId:e.apiKey,componentId:o,variantId:E,eventType:"goal_achieved",goalType:d,payload:O({reward:(U=m==null?void 0:m.reward)!=null?U:1,goalValue:m==null?void 0:m.value,currency:m==null?void 0:m.currency},(F=m==null?void 0:m.metadata)!=null?F:{}),timestamp:Date.now(),timeInSession:Date.now()-i,path:ze()};e.debug&&console.log("[sentient] componentGoal",C),te.then(()=>s.push(C))},identify(o){let d=c.getSessionId();d&&te.then(()=>{fetch(`${r}/sessions`,{method:"POST",keepalive:!0,body:JSON.stringify({sessionId:d,userId:o,ephemeral:c.isEphemeral()}),headers:a}).catch(()=>{})})},track(o){let d=c.getSessionId();if(!d||o.eventType==="variant_assigned"&&P.get(o.componentId)!==void 0&&!L.has(o.componentId)&&!f.get(o.componentId,b))return;let m=de(O({path:ze()},o),{id:rt(),sessionId:d,timestamp:Date.now(),timeInSession:Date.now()-i});e.debug&&console.log("[sentient] track",m),te.then(()=>s.push(m))},getAssignment(o,d){return f.get(o,d)},async assign(o,d,m,x){let _=c.getSessionId();if(!_)return null;let S=f.get(o,b);if(S&&(d!=null&&d.length||S.content!==void 0)){let E=S.ttlMs&&S.ttlMs>0?Math.max(0,S.assignedAt+S.ttlMs-Date.now()):0;return{variantId:S.variantId,assignmentTtlMs:E,content:S.content}}return it(N,o,async()=>{await te;try{let E={sessionId:_,componentId:o,variantIds:d};x!==void 0?E.agentDataByVariant=x:m!==void 0&&(E.agentData=m);let C=await fetch(`${r}/assign`,{method:"POST",body:JSON.stringify(E),headers:a});if(!C.ok)return null;let M=await C.json();return f.set(o,b,O({variantId:M.variantId,assignedAt:Date.now(),segment:b,confidence:1,content:M.content},M.assignmentTtlMs&&M.assignmentTtlMs>0?{ttlMs:M.assignmentTtlMs}:{})),M}catch(E){return null}})},async decide(o){var S,E;let d=c.getSessionId();if(!d)return null;let m=(S=o.slots)!=null?S:[],x={sessionId:d};o.sections&&o.sections.length>0&&(x.sections=o.sections.map(C=>({id:C}))),x.components=(E=o.components)!=null?E:[],m.length>0&&(x.slots=m.map(Ae)),o.slotsFrom==="registry"&&(x.slotsFrom="registry",o.registrySlotIds&&(x.registrySlotIds=o.registrySlotIds),o.bootstrap===!1&&(x.bootstrap=!1)),o.v&&(x.v=o.v),typeof o.pp=="number"&&(x.pp=o.pp),e.persona&&(x.persona=e.persona);let _=JSON.stringify(x);return it(G,_,async()=>{var C,M,U,F,ne,he,ve,xe;await te;try{let ce=await fetch(`${r}/decide`,{method:"POST",body:_,headers:a});if(!ce.ok)return dt(m),null;let T=await ce.json(),q={};for(let B of m){let J=(C=T.slots)==null?void 0:C[B.id];if(J!==void 0){q[B.id]=J,P.set(B.id,J),L.add(B.id);continue}let kt=P.get(B.id);if(kt!==void 0)q[B.id]=kt;else{let Et=ge(B);q[B.id]=Et,P.set(B.id,Et)}}if(T.slots)for(let[B,J]of Object.entries(T.slots))B in q||(q[B]=J,P.set(B,J),L.add(B));let en=I!=null&&I.persona!=="unknown";T.persona&&!(T.persona==="unknown"&&en)?I={persona:T.persona,confidence:(M=T.confidence)!=null?M:0}:I||(I={persona:"unknown",confidence:0});for(let[B,J]of Object.entries((U=T.assignments)!=null?U:{}))f.set(B,b,{variantId:J,assignedAt:Date.now(),segment:b,confidence:1});if(T.slotConfig)for(let[B,J]of Object.entries(T.slotConfig))D.set(B,J);T.palette&&(h=T.palette);for(let B of(F=o.registrySlotIds)!=null?F:[])(ne=T.slotConfig)!=null&&ne[B]||(D.delete(B),P.delete(B),L.delete(B));return me(e.apiKey,O(O({v:1,persona:I.persona,band:(0,st.confidenceBand)(I.confidence),slots:Object.fromEntries(P),layoutOrder:(he=T.layoutOrder)!=null?he:null,savedAt:Date.now()},D.size>0?{slotConfig:Object.fromEntries(D)}:{}),h?{palette:h}:{})),O(O(O(O({layoutOrder:(ve=T.layoutOrder)!=null?ve:null,assignments:(xe=T.assignments)!=null?xe:{},slots:q,persona:I.persona,confidence:I.confidence},T.slotConfig?{slotConfig:T.slotConfig}:{}),T.goals?{goals:T.goals}:{}),T.sectionMap?{sectionMap:T.sectionMap}:{}),T.palette?{palette:T.palette}:{})}catch(ce){return dt(m),null}})},getSlotResult(o){var d;return(d=P.get(o))!=null?d:null},isSlotDecided(o){return L.has(o)},getSlotConfig(o){var d;return(d=D.get(o))!=null?d:null},reportSlots(o,d){for(let m of o)if(!(typeof m!="string"||m.length===0)){if(!Se.test(m)){no()&&!v.has(m)&&(v.add(m),console.warn(`[sentient] reportSlots: slot id ${JSON.stringify(m)} will not register \u2014 ids must start with a letter or digit and contain only letters, digits, '_' or '-' (max 128 chars): /^[a-zA-Z0-9][a-zA-Z0-9_-]{0,127}$/.`));continue}if(!Z.has(m)){Z.add(m),W.add(m);let x=d==null?void 0:d[m];if(typeof x=="string"){let _=x.replace(/\s+/g," ").trim().slice(0,400);_!==""&&V.set(m,_)}}}W.size===0||X!=null||(X=setTimeout(()=>{X=null;let m=[...W];W.clear();for(let x=0;x<m.length;x+=20){let _=m.slice(x,x+20),S={};for(let E of _){let C=V.get(E);C!==void 0&&(S[E]=C,V.delete(E))}fetch(`${r}/slots/observed`,{method:"POST",headers:a,body:JSON.stringify(O({slotIds:_},Object.keys(S).length>0?{baselineTexts:S}:{}))}).catch(()=>{})}},1e3))},requestSlots(o,d){for(let m of o)j.has(m)||(j.add(m),Se.test(m)?Q.set(m,d==null?void 0:d[m]):K.reportSlots([m]));Q.size===0||z!=null||(z=setTimeout(()=>{z=null;let m=[...Q];Q.clear();for(let x=0;x<m.length;x+=50){let _=m.slice(x,x+50);K.decide({slotsFrom:"registry",registrySlotIds:_.map(([S])=>S),bootstrap:!1}).then(S=>{var E;if(S){let C={},M=[];for(let[U,F]of _)(E=S.slotConfig)!=null&&E[U]||(M.push(U),F&&(C[U]=F));M.length>0&&K.reportSlots(M,C)}else ct(_.map(([C])=>C),j,C=>{var U;let M={};for(let[F,ne]of _)C.has(F)&&ne&&(M[F]=ne);(U=K.requestSlots)==null||U.call(K,[...C],M)});R.forEach(C=>C())})}},0))},decideSlots(o){for(let d of o)re.has(d.id)||(re.add(d.id),H.set(d.id,d));H.size===0||se!=null||(se=setTimeout(()=>{se=null;let d=[...H.values()];H.clear();for(let m=0;m<d.length;m+=30){let x=d.slice(m,m+30);K.decide({slots:x}).then(_=>{_||ct(x.map(S=>S.id),re,S=>{var E;return(E=K.decideSlots)==null?void 0:E.call(K,x.filter(C=>S.has(C.id)))}),R.forEach(S=>S())})}},0))},cancelSlots(o){for(let d of o)Q.delete(d)&&j.delete(d),H.delete(d)&&re.delete(d)},onSlotsChanged(o){return R.add(o),()=>{R.delete(o)}},getSitePalette(){return h},getPersona(){return I?{persona:I.persona,confidence:I.confidence,band:(0,st.confidenceBand)(I.confidence)}:null},async fetchWeights(){var o;try{let d=await fetch(`${r}/weights`,{headers:a});return d.ok?(o=(await d.json()).components)!=null?o:[]:[]}catch(d){return[]}},getGraph(){return{pageNodes:[],capturedAt:0}},dispose(){var o;ae==null||ae(),Qe=!0,He=!0,s.destroy(),A.destroy(),((o=$.get(e.apiKey))==null?void 0:o.dispose)===K.dispose&&$.delete(e.apiKey),e.debug&&console.log("[sentient] disposed")},destroy(){var o;ae==null||ae(),Qe=!0,He=!0,s.destroy(),A.destroy(),c.destroy(),f.clear(),((o=$.get(e.apiKey))==null?void 0:o.dispose)===K.dispose&&$.delete(e.apiKey);try{localStorage.removeItem(le+e.apiKey),localStorage.removeItem(Xe(e.apiKey)),localStorage.removeItem(qe(e.apiKey))}catch(d){}e.debug&&console.log("[sentient] destroyed")}};if($.set(e.apiKey,{config:e,upgrade:null,dispose:K.dispose}),ae=ao(K,e.apiKey,o=>{te.then(()=>{Qe||Xt.add(o)})}),e.debug){let o=window;o.__sentient&&(o.__sentient.client=K)}return K}0&&(module.exports={AGENT_INTENTS,BLOCK_ALIGNS,BLOCK_EMPHASES,BLOCK_FITS,BLOCK_GAPS,BLOCK_GRID_COLUMNS,BLOCK_HEADING_LEVELS,BLOCK_JUSTIFIES,BLOCK_MAX_WIDTHS,BLOCK_PADS,BLOCK_RATIOS,BLOCK_SIZES,BLOCK_SURFACES,BLOCK_TEXT_ALIGNS,BLOCK_TONES,BLOCK_WEIGHTS,CLICK_ID_KEYS,FORM_FIELD_KINDS,FORM_INPUT_TYPES,LEGACY_SESSION_COOKIE_NAME,LOCAL_MODE_BANNER,MAX_BLOCK_ARMS,MAX_BLOCK_CHILDREN,MAX_BLOCK_DEPTH,MAX_BLOCK_NODES,MAX_BLOCK_TEXT_LEN,MAX_FORM_FIELDS,MAX_FORM_SELECT_OPTIONS,PAGE_SCOPE_RE,PROD_KEYLESS_ERROR,REVEAL_MS,SNAPSHOT_STORAGE_KEY_PREFIX,_registerConsentUpgradeInit,agentIntent,agentUaList,armOfResult,attachMicroSignalDetectors,baselineResultFor,baselineSlots,classifiedAgents,containsFormBlock,deriveSessionSegment,detectDeviceClass,detectTimeOfDay,detectTrafficSource,extractTrackedParams,grantConsent,init,isDoNotTrackEnabled,matchedAgentToken,pageScopeMatches,readSnapshot,referrerDomainFromReferer,renderPrePaintScript,resetRevealStyles,reveal,sessionCookieName,toWireSlot,uaTokenMatch,writeSnapshot});
|
|
1
|
+
"use strict";var tn=Object.create;var we=Object.defineProperty,nn=Object.defineProperties,on=Object.getOwnPropertyDescriptor,rn=Object.getOwnPropertyDescriptors,sn=Object.getOwnPropertyNames,It=Object.getOwnPropertySymbols,an=Object.getPrototypeOf,Ct=Object.prototype.hasOwnProperty,ln=Object.prototype.propertyIsEnumerable;var _t=(e,t,n)=>t in e?we(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,O=(e,t)=>{for(var n in t||(t={}))Ct.call(t,n)&&_t(e,n,t[n]);if(It)for(var n of It(t))ln.call(t,n)&&_t(e,n,t[n]);return e},de=(e,t)=>nn(e,rn(t));var cn=(e,t)=>{for(var n in t)we(e,n,{get:t[n],enumerable:!0})},Rt=(e,t,n,u)=>{if(t&&typeof t=="object"||typeof t=="function")for(let g of sn(t))!Ct.call(e,g)&&g!==n&&we(e,g,{get:()=>t[g],enumerable:!(u=on(t,g))||u.enumerable});return e};var dn=(e,t,n)=>(n=e!=null?tn(an(e)):{},Rt(t||!e||!e.__esModule?we(n,"default",{value:e,enumerable:!0}):n,e)),un=e=>Rt(we({},"__esModule",{value:!0}),e);var po={};cn(po,{AGENT_INTENTS:()=>Ke,BLOCK_ALIGNS:()=>Pn,BLOCK_EMPHASES:()=>Nn,BLOCK_FITS:()=>Un,BLOCK_GAPS:()=>On,BLOCK_GRID_COLUMNS:()=>Fn,BLOCK_HEADING_LEVELS:()=>$n,BLOCK_JUSTIFIES:()=>Dn,BLOCK_MAX_WIDTHS:()=>zn,BLOCK_PADS:()=>jn,BLOCK_RATIOS:()=>Gn,BLOCK_SIZES:()=>Bn,BLOCK_SURFACES:()=>Wn,BLOCK_TEXT_ALIGNS:()=>Kn,BLOCK_TONES:()=>Mn,BLOCK_WEIGHTS:()=>Ln,CLICK_ID_KEYS:()=>Ze,FORM_FIELD_KINDS:()=>Hn,FORM_INPUT_TYPES:()=>Qn,LEGACY_SESSION_COOKIE_NAME:()=>Je,LOCAL_MODE_BANNER:()=>et,MAX_BLOCK_ARMS:()=>Zn,MAX_BLOCK_CHILDREN:()=>Yn,MAX_BLOCK_DEPTH:()=>qn,MAX_BLOCK_NODES:()=>Xn,MAX_BLOCK_TEXT_LEN:()=>eo,MAX_FORM_FIELDS:()=>Jn,MAX_FORM_SELECT_OPTIONS:()=>Vn,PAGE_SCOPE_RE:()=>nt,PROD_KEYLESS_ERROR:()=>We,REVEAL_MS:()=>jt,SNAPSHOT_STORAGE_KEY_PREFIX:()=>le,_registerConsentUpgradeInit:()=>oo,agentIntent:()=>Lt,agentUaList:()=>ke,armOfResult:()=>Ue,attachMicroSignalDetectors:()=>Qt,baselineResultFor:()=>ge,baselineSlots:()=>Kt,classifiedAgents:()=>Mt,containsFormBlock:()=>Wt,deriveSessionSegment:()=>Nt,detectDeviceClass:()=>Ie,detectTimeOfDay:()=>Re,detectTrafficSource:()=>_e,extractTrackedParams:()=>Ge,grantConsent:()=>co,init:()=>Yt,isDoNotTrackEnabled:()=>at,matchedAgentToken:()=>Ye,pageScopeMatches:()=>$t,readSnapshot:()=>fe,referrerDomainFromReferer:()=>Ce,renderPrePaintScript:()=>Gt,resetRevealStyles:()=>zt,reveal:()=>Ht,sessionCookieName:()=>Pe,toWireSlot:()=>Ae,uaTokenMatch:()=>Ee,writeSnapshot:()=>me});module.exports=un(po);function Oe(){try{if(typeof crypto!="undefined"&&typeof crypto.randomUUID=="function")return crypto.randomUUID()}catch(e){}try{if(typeof crypto!="undefined"&&typeof crypto.getRandomValues=="function"){let e=new Uint8Array(16);crypto.getRandomValues(e),e[6]=e[6]&15|64,e[8]=e[8]&63|128;let t="";for(let n=0;n<16;n++)t+=e[n].toString(16).padStart(2,"0"),(n===3||n===5||n===7||n===9)&&(t+="-");return t}}catch(e){}return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})}function be(e){return e?`_${e.slice(0,12)}`:""}var Je="_snt_uid";function Pe(e){return`${Je}${be(e)}`}var pn="_snt_uid",gn=365,De="_snt_uid";function fn(){return Oe()}function At(e){try{let t=document.cookie.match(new RegExp(`(?:^|; )${e}=([^;]*)`));return t?decodeURIComponent(t[1]):null}catch(t){return null}}function mn(e,t,n){try{document.cookie=`${e}=${encodeURIComponent(t)}; max-age=${n}; SameSite=strict; path=/`}catch(u){}}function Ve(e){try{return localStorage.getItem(e)}catch(t){return null}}function Tt(e,t){try{return localStorage.setItem(e,t),!0}catch(n){return!1}}function Ot(e){try{return sessionStorage.getItem(e)}catch(t){return null}}function yn(e,t){try{return sessionStorage.setItem(e,t),!0}catch(n){return!1}}function Sn(e){try{sessionStorage.removeItem(e)}catch(t){}}function hn(e){try{return document.cookie=`${e}_probe=1; max-age=1; SameSite=strict; path=/`,document.cookie.indexOf(`${e}_probe=1`)!==-1}catch(t){return!1}}function vn(e){try{localStorage.removeItem(e)}catch(t){}}function xn(e){try{document.cookie=`${e}=; max-age=0; SameSite=strict; path=/`}catch(t){}}var wn={getSessionId:()=>null,isEphemeral:()=>!1,destroy:()=>{}};function Be(e){var p,y,k,b,N,G,P;if(typeof window=="undefined")return wn;let t=be(e==null?void 0:e.apiKey),n=(p=e==null?void 0:e.cookieName)!=null?p:Pe(e==null?void 0:e.apiKey),u=`${De}${t}`,g=`${De}_tomb${t}`,i=((y=e==null?void 0:e.cookieTTLDays)!=null?y:gn)*24*60*60,c=L=>L&&L.length>0?L:null,f=()=>{var L,D;return t&&!(e!=null&&e.cookieName)&&Ve(g)===null?(D=(L=c(At(pn)))!=null?L:c(Ve(De)))!=null?D:c(Ot(De)):null},s=(P=(G=(N=(b=(k=c(At(n)))!=null?k:c(Ve(u)))!=null?b:c(Ot(u)))!=null?N:f())!=null?G:c(e==null?void 0:e.ssrSessionId))!=null?P:fn();mn(n,s,i);let r=Tt(u,s),a=hn(n),w=r?!1:yn(u,s),R=!r&&!a&&!w;return{getSessionId:()=>s,isEphemeral:()=>R,destroy:()=>{s=null,xn(n),vn(u),Sn(u),t&&!(e!=null&&e.cookieName)&&Tt(g,"1")}}}function Y(e){return Math.min(6e4,1e3*2**Math.min(e,6))}function ue(e){if(e.ok===!0)return"delivered";let{status:t}=e;return typeof t!="number"?"retry":t>=200&&t<300?"delivered":t>=400&&t<500&&t!==429?"dropped":"retry"}function Le(e,t){try{let n=localStorage.getItem(e);if(!n)return[];let u=JSON.parse(n);return Array.isArray(u)?(localStorage.removeItem(e),u.slice(-t)):[]}catch(n){return[]}}function oe(e,t,n){try{let u=(()=>{try{let l=localStorage.getItem(n);if(!l)return[];let i=JSON.parse(l);return Array.isArray(i)?i:[]}catch(l){return[]}})(),g=new Map;for(let l of u)g.set(l.id,l);for(let l of e)g.set(l.id,l);localStorage.setItem(n,JSON.stringify([...g.values()].slice(-t)))}catch(u){}}function Me(e,t){try{let n=localStorage.getItem(t);if(!n)return;let u=JSON.parse(n);if(!Array.isArray(u))return;let g=new Set(e),l=u.filter(i=>!g.has(i.id));if(l.length===u.length)return;l.length===0?localStorage.removeItem(t):localStorage.setItem(t,JSON.stringify(l))}catch(n){}}var bn=500,kn=56*1024;function Xe(e){return`_snt_retry_${e.slice(0,12)}`}var En={push:()=>{},flush:()=>{},destroy:()=>{}};function Pt(e){var V,X,Se;if(typeof window=="undefined")return En;let t=(V=e.flushIntervalMs)!=null?V:5e3,n=(X=e.maxBatchSize)!=null?X:20,u=(Se=e.maxRetrySize)!=null?Se:100,g=e.ingestUrl,l=e.apiKey,i=Xe(l),c=[],f=new Set,s=[],r=v=>{for(let A of v)a.delete(A),!f.has(A)&&(f.add(A),s.push(A));for(;s.length>bn;){let A=s.shift();A&&f.delete(A)}Me(v,i)},a=new Set,w=()=>{for(;c.length>u;){let v=c.shift();v&&a.delete(v.id)}},R=v=>{f.has(v.id)||a.has(v.id)||(a.add(v.id),c.push(v),w())},p=v=>{for(let A of v)f.has(A.id)||(a.add(A.id),c.push(A));w()},y=Le(i,u);for(let v of y)R(v);let k=0,b=0,N=(v,A=!0)=>{if(v.length===0)return;let j=JSON.stringify(v),Q=v.map(H=>H.id),z;try{z=fetch(g,{method:"POST",keepalive:!0,body:j,headers:{"Content-Type":"application/json",Authorization:`Bearer ${l}`}})}catch(H){oe(v,u,i),p(v),b++,k=Date.now()+Y(b);return}let re=H=>{if(ue(H)!=="retry"){if(!H.ok&&A){let se=v.filter(ie=>ie.eventType!=="pageview");if(se.length>0&&se.length<v.length){r(v.filter(ie=>ie.eventType==="pageview").map(ie=>ie.id)),N(se,!1);return}}r(Q),b=0,k=0;return}oe(v,u,i),p(v),b++,k=Date.now()+Y(b)};z instanceof Promise?z.then(re).catch(()=>{oe(v,u,i),p(v),b++,k=Date.now()+Y(b)}):re(z)},G=typeof TextEncoder!="undefined"?new TextEncoder:null,P=v=>G?G.encode(v).length:v.length,L=v=>{let A=[],j=2;for(let Q of v){let z=P(JSON.stringify(Q))+1;if(A.length>0&&j+z>kn||A.length>=n)break;A.push(Q),j+=z}return A},D=()=>{try{if(Date.now()<k)return;for(;c.length>0&&!(Date.now()<k);){let v=c.filter(j=>!f.has(j.id));if(c.length=0,v.length===0)break;let A=L(v);if(A.length===0)break;A.length<v.length&&c.push(...v.slice(A.length)),N(A)}}catch(v){}},h=!0,I=null;I=setInterval(()=>{h&&D()},t);let Z=()=>{document.visibilityState==="hidden"&&D()},W=()=>{D()};return document.addEventListener("visibilitychange",Z),window.addEventListener("pagehide",W),{push(v){R(v),c.length>=n&&D()},flush:D,destroy(){h=!1,I!==null&&(clearInterval(I),I=null),document.removeEventListener("visibilitychange",Z),window.removeEventListener("pagehide",W),D()}}}var In=200;function qe(e){return`_snt_goal_retry_${e.slice(0,12)}`}var _n={send:()=>{},flush:()=>{},destroy:()=>{}};function Dt(e){var P,L,D;if(typeof window=="undefined")return _n;let t=(P=e.flushIntervalMs)!=null?P:5e3,n=(L=e.maxRetrySize)!=null?L:100,u=(D=e.maxPerFlush)!=null?D:5,g=qe(e.apiKey),l=[],i=new Set,c=new Set,f=[],s=0,r=0,a=!1,w=h=>{for(i.delete(h.id),c.has(h.id)||(c.add(h.id),f.push(h.id));f.length>In;){let I=f.shift();I&&c.delete(I)}Me([h.id],g)},R=h=>{oe([h],n,g),!c.has(h.id)&&!i.has(h.id)&&(i.add(h.id),l.push(h)),Date.now()>=s&&(r++,s=Date.now()+Y(r))},p=h=>{let I;try{I=fetch(e.url,{method:"POST",keepalive:!0,body:h.body,headers:e.headers})}catch(W){R(h);return}let Z=W=>{var X;let V=ue(W);if(V==="retry"){R(h);return}V==="dropped"&&((X=e.onDrop)==null||X.call(e,h,W.status)),w(h),r=0,s=0};I instanceof Promise?I.then(Z).catch(()=>R(h)):Z(I)},y=()=>{try{if(a||Date.now()<s)return;let h=0;for(;l.length>0&&h<u&&!(Date.now()<s);){let I=l.shift();i.delete(I.id),!c.has(I.id)&&(h++,p(I))}}catch(h){}},k=Le(g,n);for(let h of k)i.has(h.id)||(i.add(h.id),l.push(h));k.length>0&&oe(k,n,g);let b=setInterval(y,t),N=()=>{document.visibilityState==="hidden"&&y()},G=()=>y();return document.addEventListener("visibilitychange",N),window.addEventListener("pagehide",G),{send(h){if(!a&&!(c.has(h.id)||i.has(h.id))){if(Date.now()<s){oe([h],n,g),i.add(h.id),l.push(h);return}p(h)}},flush:y,destroy(){clearInterval(b),document.removeEventListener("visibilitychange",N),window.removeEventListener("pagehide",G),y(),a=!0}}}var Cn=1800*1e3;function Ne(e,t){return`${encodeURIComponent(e)}:${encodeURIComponent(t)}`}function Bt(e=Cn,t){let n=new Map,u=`_snt_asgn${be(t)}_`,g=(s,r)=>`${u}${encodeURIComponent(s)}:${encodeURIComponent(r)}`,l=s=>{let r=s.slice(u.length),a=r.indexOf(":");if(a<0)return null;try{return{componentId:decodeURIComponent(r.slice(0,a)),segment:decodeURIComponent(r.slice(a+1))}}catch(w){return null}},i=()=>{try{let s=[];for(let r=0;r<localStorage.length;r++){let a=localStorage.key(r);a!=null&&a.startsWith(u)&&s.push(a)}return s}catch(s){return[]}},c=s=>s.assignedAt+(s.ttlMs&&s.ttlMs>0?s.ttlMs:e)<Date.now();return typeof window!="undefined"&&(()=>{for(let s of i())try{let r=localStorage.getItem(s);if(!r)continue;let a=JSON.parse(r);if(c(a)){localStorage.removeItem(s);continue}let w=l(s);if(!w)continue;n.set(Ne(w.componentId,w.segment),a)}catch(r){}})(),{get(s,r){let a=n.get(Ne(s,r));return a?c(a)?(n.delete(Ne(s,r)),null):a:null},set(s,r,a){let w=Ne(s,r);n.set(w,a);try{localStorage.setItem(g(s,r),JSON.stringify(a))}catch(R){}},clear(){n.clear();for(let s of i())try{localStorage.removeItem(s)}catch(r){}}}}var ke=["GPTBot","ChatGPT-User","OAI-SearchBot","ClaudeBot","Claude-User","Claude-SearchBot","PerplexityBot","Perplexity-User","Google-Extended","Applebot-Extended","Meta-ExternalAgent","Bytespider","CCBot","Amazonbot","cohere-ai","Diffbot"];function Ee(e){return Ye(e)!==null}function Ye(e){var n;if(!e)return null;let t=e.toLowerCase();return(n=ke.find(u=>t.includes(u.toLowerCase())))!=null?n:null}var Ke={GPTBot:"training","ChatGPT-User":"user","OAI-SearchBot":"search",ClaudeBot:"training","Claude-User":"user","Claude-SearchBot":"search",PerplexityBot:"search","Perplexity-User":"user","Google-Extended":"training","Applebot-Extended":"training","Meta-ExternalAgent":"training",Bytespider:"training",CCBot:"training",Amazonbot:"other","cohere-ai":"training",Diffbot:"other"};function Lt(e){if(!e)return"other";let t=ke.find(n=>n.toLowerCase()===e.toLowerCase());return t&&Ke[t]||"other"}function Mt(){var t;let e={user:[],search:[],training:[],other:[]};for(let n of ke)e[(t=Ke[n])!=null?t:"other"].push(n);return e}function Ie(e){let t=e.toLowerCase();return/ipad|tablet|playbook|kindle|silk/.test(t)?"tablet":/mobi|iphone|ipod|android.*mobile|phone/.test(t)?"mobile":"desktop"}function _e(e,t){if(!e)return"direct";try{let n=new URL(e);if(t)try{if(new URL(t).host===n.host)return"direct"}catch(g){}let u=n.hostname.toLowerCase();return/(^|\.)(google|bing|duckduckgo|yahoo)\./.test(u)?"search":/(^|\.)(twitter\.com|x\.com|facebook\.com|linkedin\.com|reddit\.com|t\.co)$/.test(u)?"social":"referral"}catch(n){return"direct"}}function Ce(e){if(!e)return null;try{return new URL(e).hostname}catch(t){return null}}var Ze=["gclid","gbraid","wbraid","fbclid","ttclid","msclkid","twclid","li_fat_id"];function Ge(e){let t={},n={};try{let u=typeof e=="string"||e instanceof URLSearchParams?new URLSearchParams(e):Object.entries(e).flatMap(([g,l])=>{let i=Array.isArray(l)?l[0]:l;return i===void 0?[]:[[g,i]]});for(let[g,l]of u)g.startsWith("utm_")?g in t||(t[g]=l):Ze.includes(g)&&(g in n||(n[g]=l))}catch(u){}return{utmParams:t,clickIds:n}}function Re(e){let t=e.getHours();return t<6?"night":t<12?"morning":t<18?"afternoon":"evening"}function Nt(e){let t=Rn("__segment__",e);return`${t.deviceClass}:${t.trafficSource}`}function Rn(e,t){var l,i,c,f,s,r,a,w;let n=(i=(l=t==null?void 0:t.userAgent)==null?void 0:l.trim())!=null?i:"",u=(f=(c=t==null?void 0:t.referer)==null?void 0:c.trim())!=null?f:"",g=(s=t==null?void 0:t.now)!=null?s:new Date;return{sessionId:e,ephemeral:!1,utmParams:(r=t==null?void 0:t.utmParams)!=null?r:{},clickIds:(a=t==null?void 0:t.clickIds)!=null?a:{},deviceClass:n?Ie(n):"desktop",trafficSource:u?_e(u,t==null?void 0:t.appOrigin):"direct",referrerDomain:Ce(u),timeOfDay:Re(g),dayOfWeek:(w=["sun","mon","tue","wed","thu","fri","sat"][g.getDay()])!=null?w:"sun",automation:(t==null?void 0:t.webdriver)===!0||Ee(n)}}var pe=require("@sentientui/policy");function Ae(e){return O(O(O({id:e.id},e.arms?{arms:[...e.arms]}:{}),e.dims?{dims:Object.fromEntries(Object.entries(e.dims).map(([t,n])=>[t,[...n]]))}:{}),e.baseline!==void 0?{baseline:e.baseline}:{})}function ge(e){let t=Ae(e);return(0,pe.slotResultFor)(t,(0,pe.slotBaselineArm)(t))}function Kt(e){let t={};for(let n of e)t[n.id]=ge(n);return t}function Ue(e){return typeof e=="string"?e:(0,pe.canonicalArm)(e)}var le="_snt_snap:",An=["low","medium","high"];function fe(e){try{let t=localStorage.getItem(le+e);if(!t)return null;let n=JSON.parse(t);return!n||typeof n!="object"||n.v!==1||typeof n.persona!="string"||typeof n.band!="string"||!An.includes(n.band)||typeof n.slots!="object"||n.slots===null||Array.isArray(n.slots)||!(n.layoutOrder===null||Array.isArray(n.layoutOrder))||typeof n.savedAt!="number"||!(n.slotConfig===void 0||typeof n.slotConfig=="object"&&n.slotConfig!==null&&!Array.isArray(n.slotConfig))?null:n}catch(t){return null}}function me(e,t){try{localStorage.setItem(le+e,JSON.stringify(t))}catch(n){}}function Gt(e){return"(function(){try{var r=localStorage.getItem("+JSON.stringify(le+e).replace(/</g,"\\u003c")+');if(!r)return;var s=JSON.parse(r);if(!s||s.v!==1||typeof s.persona!=="string"||typeof s.band!=="string")return;var d=document.documentElement;if(d.hasAttribute("data-sentient-persona"))return;d.setAttribute("data-sentient-persona",s.persona);d.setAttribute("data-sentient-confidence",s.band);}catch(e){}})();'}var st=require("@sentientui/policy");var $e=require("@sentientui/policy");var We="[sentient] No API key configured \u2014 nothing is being learned. Set NEXT_PUBLIC_SENTIENT_API_KEY or pass localMode: true for local development.",et="[sentient] Local mode \u2014 decisions are simulated on-device and nothing is sent over the network. Add an API key to learn from real traffic.",Ut=!1,Fe=!1;function Tn(){var e;try{return(e=new URLSearchParams(window.location.search).get("sentient_persona"))!=null?e:void 0}catch(t){return}}function Ft(e){var s;let t=Be({ssrSessionId:e.ssrSessionId,apiKey:e.apiKey}),n=(s=t.getSessionId())!=null?s:"local",u=Tn(),g=import("@sentientui/core/local").then(r=>{let a=r;return a.LOCAL_ENGINE_AVAILABLE?(Ut||(Ut=!0,console.info(et)),a):(Fe||(Fe=!0,console.error(We)),null)}).catch(()=>(Fe||(Fe=!0,console.error(We)),null)),l=null,i={low:.15,medium:.5,high:.85},c=(()=>{var a;if(e.initialPersona)return O({},e.initialPersona);let r=fe(e.apiKey||"local");return r?{persona:r.persona,confidence:(a=i[r.band])!=null?a:.15}:null})();function f(r){let a=document.documentElement;a.dataset.sentientPersona===void 0&&(a.dataset.sentientPersona=r.persona,a.dataset.sentientConfidence=(0,$e.confidenceBand)(r.confidence))}return{isLocal:!0,async decide(r){var R,p,y;let a=await g;if(!a)return null;let w=a.createLocalEngine({sessionId:n,forcedPersona:u}).decide(r);return l=de(O({},w),{layoutOrder:(p=(R=w.layoutOrder)!=null?R:l==null?void 0:l.layoutOrder)!=null?p:null,slots:O(O({},(y=l==null?void 0:l.slots)!=null?y:{}),w.slots)}),me(e.apiKey||"local",{v:1,persona:l.persona,band:(0,$e.confidenceBand)(l.confidence),slots:l.slots,layoutOrder:l.layoutOrder,savedAt:Date.now()}),f(w),w},getSlotResult(r){var a,w,R;return(R=(w=l==null?void 0:l.slots[r])!=null?w:(a=e.initialSlots)==null?void 0:a[r])!=null?R:null},getSlotConfig(r){var a,w;return(w=(a=e.initialSlotConfig)==null?void 0:a[r])!=null?w:null},getSitePalette(){var r;return(r=e.initialPalette)!=null?r:null},reportSlots(){},getPersona(){let r=l!=null?l:c;return r?{persona:r.persona,confidence:r.confidence,band:(0,$e.confidenceBand)(r.confidence)}:null},async assign(r,a){var p;let w=await g;return!w||!a||a.length===0?a!=null&&a[0]?{variantId:a[0],assignmentTtlMs:0}:null:{variantId:(p=w.createLocalEngine({sessionId:n,forcedPersona:u}).decide({components:[{id:r,variantIds:a}]}).assignments[r])!=null?p:a[0],assignmentTtlMs:0}},track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},getAssignment:()=>null,fetchWeights:()=>Promise.resolve([]),getGraph:()=>({pageNodes:[],capturedAt:0}),flush:()=>{},dispose:()=>{},destroy:()=>t.destroy()}}var nt=/^(\*|\/[^\s?#*]*(\/\*)?)$/;function tt(e){let t=e.split(/[?#]/)[0]||"/";return t.length>1?t.replace(/\/+$/,"")||"/":t}function $t(e,t){if(e===void 0||!nt.test(e))return!1;if(e==="*")return!0;let n=tt(t);if(e.endsWith("/*")){let u=tt(e.slice(0,-2));return n.startsWith(u==="/"?"/":`${u}/`)&&n!==u}return n===tt(e)}var On=["none","sm","md","lg"],Pn=["start","center","end","stretch"],Dn=["start","center","end","between"],Bn=["sm","md","lg"],Ln=["normal","medium","bold"],Mn=["default","muted","accent"],Nn=["primary","secondary","ghost"],Kn=["left","center","right"],Gn=["auto","square","landscape","wide"],Un=["cover","contain"],Fn=[2,3,4],$n=[2,3,4],Wn=["default","raised"],jn=["none","sm","md","lg"],zn=["measure"],Hn=["input","textarea","select"],Qn=["text","email","number","tel"],Jn=5,Vn=8,Xn=64,qn=5,Yn=12,Zn=4,eo=500;function Wt(e){if(e==null||typeof e!="object"||Array.isArray(e))return!1;let t=e;return t.type==="form"?!0:Array.isArray(t.children)?t.children.some(Wt):!1}var ot="sentient-reveal",ye="sentient-revealed",jt=240,je=!1;function zt(){var e;je=!1,typeof document!="undefined"&&((e=document.getElementById(ot))==null||e.remove())}function to(e){if(je||e.getElementById(ot)){je=!0;return}let t=e.createElement("style");t.id=ot,t.textContent=`@media (prefers-reduced-motion: no-preference){@keyframes ${ye}{from{opacity:.55;transform:translateY(2px)}to{opacity:1;transform:none}}.${ye}{animation:${ye} 240ms cubic-bezier(.2,.6,.2,1) both}}`,e.head.appendChild(t),je=!0}function Ht(e,t={}){var g;let n=(g=t.doc)!=null?g:typeof document!="undefined"?document:void 0;if(!n||!(e instanceof Element)||(t.arm!==void 0&&e.setAttribute("data-sentient-arm",t.arm),t.persona!==void 0&&e.setAttribute("data-sentient-persona",t.persona),t.previous!==void 0&&t.previous===e.textContent))return!1;to(n),e.classList.remove(ye),e.offsetWidth,e.classList.add(ye);let u=()=>{e.classList.remove(ye),e.removeEventListener("animationend",u)};return e.addEventListener("animationend",u),!0}function Qt(e,t,n,u){let g=[];{let c=!1,f=[],s=()=>{if(c)return;let r=Date.now();for(f.push(r);f.length>0&&r-f[0]>500;)f.shift();f.length>=3&&(c=!0,e("rage_click"))};t.addEventListener("click",s),g.push(()=>t.removeEventListener("click",s))}{let l=!1,i=c=>{if(l||!(c.target instanceof Node)||!t.contains(c.target)&&t!==c.target)return;l=!0;let f=typeof window!="undefined"?window.getSelection():null,s=f?f.toString().length:0;e("text_copy",{selectionLength:s})};document.addEventListener("copy",i),g.push(()=>document.removeEventListener("copy",i))}{let l=!1,i=!1,c=null,f=()=>{c!==null&&(clearTimeout(c),c=null)},s=()=>{l||!i||(f(),c=setTimeout(()=>{!l&&i&&(l=!0,e("scroll_hesitation"))},3e3))},r=()=>{f(),s()},a=R=>{for(let p of R)i=p.intersectionRatio>.3,i?s():f()},w=new IntersectionObserver(a,{threshold:[.3]});w.observe(t),window.addEventListener("scroll",r,{passive:!0}),g.push(()=>{w.disconnect(),window.removeEventListener("scroll",r),f()})}if((u==null?void 0:u.tabLoss)!==!1){let l=!1,i=n!=null?n:Date.now(),c=()=>{if(l||document.visibilityState!=="hidden")return;let f=Date.now()-i;f<15e3&&(l=!0,e("tab_loss",{timeOnPage:f}))};document.addEventListener("visibilitychange",c),g.push(()=>document.removeEventListener("visibilitychange",c))}return()=>{for(let l of g)l()}}function no(){var e;return typeof process=="undefined"||((e=process.env)==null?void 0:e.NODE_ENV)!=="production"}var Jt="https://api.sentient-ui.com/v1/events",$=new Map,Vt=null;function oo(e,t){let n=$.get(e);n&&n.upgrade&&(n.reinit=t)}function ro(e){return"value"in e||"currency"in e||"externalId"in e||"metadata"in e||"weight"in e||"stepIndex"in e}var so=3;function rt(){return Oe()}function ze(){var e;if(typeof window!="undefined")return((e=window.location)==null?void 0:e.pathname)||void 0}function io(){let e=new WeakMap,t=new Map,n=!1,u=(c,f,s)=>{let r=c.get(f);return s===null?r?!0:(c.set(f,new Set),!1):r?r.has(s)?!0:(r.add(s),!1):(c.set(f,new Set([s])),!1)},g=typeof window!="undefined"&&"event"in window,l=()=>{if(!g)return;let c=window.event;return typeof Event=="function"&&c instanceof Event?c:void 0},i=()=>{if(g){Promise.resolve().then(()=>{n=!1,t.clear()});return}let c=!1,f=()=>{c||(c=!0,n=!1,t.clear())};if(setTimeout(f,0),typeof MessageChannel=="function"){let s=new MessageChannel;s.port1.onmessage=()=>{s.port1.close(),s.port2.close(),f()},s.port2.postMessage(0)}};return{firedBefore(c,f){let s=l();if(s){let a=e.get(s);return a||(a=new Map,e.set(s,a)),u(a,c,f)}let r=u(t,c,f);return!r&&!n&&(n=!0,i()),r}}}var Xt=new Set;function ao(e,t,n){let u=typeof window=="undefined"?null:window.history;if(!u)return()=>{};let g=!1,l,i=()=>{if(g)return;let s=ze();!s||s===l||(l=s,e.track({projectId:t,componentId:"__page__",eventType:"pageview",payload:{}}),n(`${t}:${s}`))},c=[];for(let s of["pushState","replaceState"]){let r=u[s],a=function(...w){let R=r.apply(this,w);return i(),R};u[s]=a,c.push([s,r,a])}window.addEventListener("popstate",i);let f=ze();return f&&Xt.has(`${t}:${f}`)?l=f:i(),()=>{if(!g){g=!0,window.removeEventListener("popstate",i);for(let[s,r,a]of c)u[s]===a&&(u[s]=r)}}}var Te={track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},getAssignment:()=>null,assign:()=>Promise.resolve(null),decide:()=>Promise.resolve(null),getSlotResult:()=>null,getSlotConfig:()=>null,getSitePalette:()=>null,reportSlots:()=>{},getPersona:()=>null,fetchWeights:()=>Promise.resolve([]),getGraph:()=>({pageNodes:[],capturedAt:0}),flush:()=>{},dispose:()=>{},destroy:()=>{}};function lo(){try{return Ge(window.location.search)}catch(e){return{utmParams:{},clickIds:{}}}}function qt(e){return e.replace(/\/events\/?$/,"")}function at(){return typeof navigator!="undefined"&&navigator.globalPrivacyControl===!0?!0:[typeof navigator!="undefined"?navigator.doNotTrack:void 0,typeof window!="undefined"?window.doNotTrack:void 0,typeof navigator!="undefined"?navigator.msDoNotTrack:void 0].some(t=>t==="1"||t==="yes")}function co(e){var f;if(typeof window=="undefined")return;let t=e!=null?e:Vt;if(!t){console.warn("[sentient] grantConsent() called before init()");return}let n=$.get(t);if(!n){console.warn("[sentient] grantConsent() called before init()");return}let{config:u,upgrade:g,reinit:l}=n;if(!g){n.upgradeBlockedReason&&console.warn(n.upgradeBlockedReason);return}if(u.respectDoNotTrack!==!1&&at())return;let i=(l!=null?l:Yt)(de(O({},u),{consent:!0}));g(i);let c=(f=$.get(t))==null?void 0:f.dispose;$.set(t,{config:de(O({},u),{consent:!0}),upgrade:null,dispose:c})}function uo(e){var R;let t=e.preConsentBehavior==="statistical_winner",n=qt((R=e.ingestUrl)!=null?R:Jt),u={"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`},g=new Map,l=new Map,i={track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},getAssignment:()=>null,fetchWeights:()=>Promise.resolve([]),assign(p,y,k){if(!t)return Promise.resolve(null);let b=g.get(p);return b?Promise.resolve(b):it(l,p,async()=>{try{let N=new URLSearchParams({componentId:p});for(let D of y!=null?y:[])N.append("variantIds[]",D);let G=await fetch(`${n}/winner?${N.toString()}`,{headers:u});if(!G.ok)return y!=null&&y[0]?{variantId:y[0],assignmentTtlMs:0}:null;let L={variantId:(await G.json()).variantId,assignmentTtlMs:0};return g.set(p,L),L}catch(N){return y!=null&&y[0]?{variantId:y[0],assignmentTtlMs:0}:null}})},decide:()=>Promise.resolve(null),getSlotResult:()=>null,getSlotConfig:()=>null,getSitePalette:()=>null,reportSlots:()=>{},getPersona:()=>null,getGraph:()=>({pageNodes:[],capturedAt:0}),flush:()=>{},dispose:()=>{},destroy:()=>{}},c=!1,f=new Set,s=[],r=[],a={track:p=>i.track(p),goal:((p,y,k,b)=>i.goal(p,y,k,b)),componentGoal:(p,y,k)=>i.componentGoal(p,y,k),identify:p=>i.identify(p),getAssignment:(p,y)=>i.getAssignment(p,y),assign:(p,y,k,b)=>i.assign(p,y,k,b),decide:p=>i.decide(p),getSlotResult:p=>i.getSlotResult(p),isSlotDecided:p=>{var y,k;return(k=(y=i.isSlotDecided)==null?void 0:y.call(i,p))!=null?k:!0},getSlotConfig:p=>i.getSlotConfig(p),getSitePalette:()=>i.getSitePalette(),reportSlots:(p,y)=>i.reportSlots(p,y),requestSlots:(p,y)=>{var k;return c?(k=i.requestSlots)==null?void 0:k.call(i,p,y):s.push([p,y])},decideSlots:p=>{var y;return c?(y=i.decideSlots)==null?void 0:y.call(i,p):r.push(...p)},cancelSlots:p=>{var k;if(c)return(k=i.cancelSlots)==null?void 0:k.call(i,p);let y=new Set(p);for(let b of s)b[0]=b[0].filter(N=>!y.has(N));r=r.filter(b=>!y.has(b.id))},onSlotsChanged:p=>(f.add(p),()=>{f.delete(p)}),getPersona:()=>i.getPersona(),fetchWeights:()=>i.fetchWeights(),getGraph:()=>i.getGraph(),flush:()=>i.flush(),dispose:()=>i.dispose(),destroy:()=>i.destroy()};function w(p){var y,k,b;i=p,c=!0,(y=p.onSlotsChanged)==null||y.call(p,()=>f.forEach(N=>N()));for(let[N,G]of s.splice(0))N.length>0&&((k=p.requestSlots)==null||k.call(p,N,G));r.length>0&&((b=p.decideSlots)==null||b.call(p,r.splice(0)))}return{proxy:a,setInner:w}}function it(e,t,n){let u=e.get(t);if(u)return u;let g=(async()=>{try{return await n()}finally{e.delete(t)}})();return e.set(t,g),g}function Yt(e){var gt,ft,mt,yt,St,ht,vt,xt,wt,bt;if(typeof window=="undefined")return Te;Vt=e.apiKey||"local";let t=$.get(e.apiKey||"local");if(t!=null&&t.dispose)try{t.dispose()}catch(o){}let n=e.respectDoNotTrack!==!1&&at(),u=e.consent===!1||n,g=typeof e.apiKey=="string"&&e.apiKey.startsWith("pk_");if(e.localMode===!0||!g&&e.localMode!==!1)return $.set(e.apiKey||"local",{config:e,upgrade:null,upgradeBlockedReason:"[sentient] grantConsent(): this client is keyless/local \u2014 there is no hosted client to upgrade to. Configure a pk_ API key to enable tracking."}),u?Te:Ft(e);if(u){if(!e.apiKey||!e.apiKey.startsWith("pk_"))return e.preConsentBehavior==="statistical_winner"&&console.warn("[sentient] init() called with an invalid apiKey \u2014 expected a pk_ public key. SDK disabled."),$.set(e.apiKey||"local",{config:e,upgrade:null,upgradeBlockedReason:"[sentient] grantConsent(): the client was initialized with an invalid apiKey (expected a pk_ public key) \u2014 consent cannot enable tracking."}),Te;let{proxy:o,setInner:d}=uo(e);return $.set(e.apiKey,{config:e,upgrade:n?null:d}),o}if(!e.apiKey||!e.apiKey.startsWith("pk_"))return console.warn("[sentient] init() called with an invalid apiKey \u2014 expected a pk_ public key. SDK disabled."),Te;if(e.ingestUrl==="")return console.warn("[sentient] init() called with an empty ingestUrl. SDK disabled."),Te;let l=(gt=e.ingestUrl)!=null?gt:Jt,i=Date.now(),c=Be({ssrSessionId:e.ssrSessionId,apiKey:e.apiKey}),f=Bt(void 0,e.apiKey),s=Pt({ingestUrl:l,apiKey:e.apiKey}),r=qt(l),a={"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`},w=new Set,R=Dt({url:`${r}/goals`,apiKey:e.apiKey,headers:a,onDrop:(o,d)=>{if(!e.debug){if(w.has(d))return;w.add(d)}console.warn(`[sentient] goal dropped (HTTP ${d}) \u2014 this will not be retried. `+(d===400?"The session was not found: call init() and let the session upsert complete before firing goals.":d===401||d===403?"Check the API key and that this origin is on the project allowlist.":"See the response status for the cause."),o)}}),p=Ie((ft=navigator.userAgent)!=null?ft:""),y=window.location.origin,k=_e((mt=document.referrer)!=null?mt:"",y),b=(yt=e.sessionSegment)!=null?yt:`${p}:${k}`,N=new Map,G=new Map,P=new Map,L=new Set,D=new Map,h=null,I=null,Z=new Set,W=new Set,V=new Map,X=null,Se=/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,127}$/,v=new Set,A=new Set,j=new Set,Q=new Map,z=null,re=new Set,H=new Map,se=null,ie=2,lt=new Map,He=!1,ct=(o,d,m)=>{var S;let x=new Set,_=1;for(let E of o){d.delete(E);let C=((S=lt.get(E))!=null?S:0)+1;lt.set(E,C),C<=ie&&(x.add(E),C>_&&(_=C))}x.size>0&&setTimeout(()=>{He||m(x)},Y(_))},dt=o=>{for(let d of o)P.has(d.id)||P.set(d.id,ge(d))};if(e.initialSlots)for(let[o,d]of Object.entries(e.initialSlots))P.set(o,d),L.add(o);if(e.initialSlotConfig)for(let[o,d]of Object.entries(e.initialSlotConfig))D.set(o,d);e.initialPalette&&(h=e.initialPalette);let ee=fe(e.apiKey);if(ee){for(let[o,d]of Object.entries(ee.slots))P.has(o)||P.set(o,d);for(let[o,d]of Object.entries((St=ee.slotConfig)!=null?St:{}))D.has(o)||D.set(o,d);!h&&ee.palette&&(h=ee.palette)}let ut={low:.15,medium:.5,high:.85};if(e.initialPersona)I=O({},e.initialPersona);else{let o=document.documentElement.dataset;o.sentientPersona?I={persona:o.sentientPersona,confidence:(vt=ut[(ht=o.sentientConfidence)!=null?ht:"low"])!=null?vt:.15}:ee&&(I={persona:ee.persona,confidence:(xt=ut[ee.band])!=null?xt:.15})}if(e.initialAssignments)for(let[o,d]of Object.entries(e.initialAssignments))f.set(o,b,{variantId:d,assignedAt:Date.now(),segment:b,confidence:1});let te=Promise.resolve(),pt=c.getSessionId();if(pt){let o=Ce((wt=document.referrer)!=null?wt:""),{utmParams:d,clickIds:m}=lo(),x=O(O(O(O({sessionId:pt,deviceClass:p,trafficSource:k,referrerDomain:o,utmParams:d,clickIds:m,timeOfDay:Re(new Date),dayOfWeek:["sun","mon","tue","wed","thu","fri","sat"][new Date().getDay()],ephemeral:c.isEphemeral(),automation:typeof navigator!="undefined"&&navigator.webdriver===!0||Ee((bt=navigator.userAgent)!=null?bt:"")},e.userId?{userId:e.userId}:{}),e.persona?{persona:e.persona}:{}),e.country?{country:e.country}:{}),e.sdk?{sdk:e.sdk.name,sdkVersion:e.sdk.version}:{}),_=async()=>{for(let S=0;;S++){try{let E=await fetch(`${r}/sessions`,{method:"POST",keepalive:!0,body:JSON.stringify(x),headers:a});if(E.status===402){console.warn("[SentientUI] Session limit exceeded for this project. The bandit will stop learning until the limit resets. Upgrade at sentient-ui.com/pricing");return}if(E.ok||ue(E)==="dropped")return}catch(E){}if(S>=so){console.warn("[SentientUI] Could not register the session after retries. Conversions in this visit may not be recorded.");return}await new Promise(E=>setTimeout(E,Y(S+1)))}};try{te=_()}catch(S){}}e.debug&&(console.log("[sentient] initialized",{context:e.context}),window.__sentient={client:null,queue:s});let Zt=io(),ae=null,Qe=!1,K={goal(o,d={},m=1,x=0){var ne,he,ve,xe,ce,T,q;let _=c.getSessionId();if(!_)return;let S=ro(d)?d:{metadata:d},E=[o,(ne=S.externalId)!=null?ne:"",(he=S.stepIndex)!=null?he:x,(ve=S.weight)!=null?ve:m].join("\0"),C=S.value!==void 0?`${S.value}\0${(xe=S.currency)!=null?xe:""}`:null;if(Zt.firedBefore(E,C)){e.debug&&console.log(`[sentient] goal("${o}") already recorded for this action \u2014 not sent twice`);return}let M=rt(),U={sessionId:_,name:o,metadata:(ce=S.metadata)!=null?ce:{},weight:(T=S.weight)!=null?T:m,stepIndex:(q=S.stepIndex)!=null?q:x,goalId:M,value:S.value,currency:S.currency,externalId:S.externalId};e.debug&&console.log("[sentient] goal",U);let F={id:M,body:JSON.stringify(U)};te.then(()=>R.send(F))},componentGoal(o,d,m){var M,U,F;let x=c.getSessionId();if(!x)return;let _=f.get(o,b),S=_?null:(M=P.get(o))!=null?M:null;if(!_&&S===null){e.debug&&console.warn(`[sentient] componentGoal("${o}"): no assignment or slot decision yet \u2014 render its <Adaptive>/adaptive hook or call assign()/decide() before recording a goal.`);return}if(!_&&!L.has(o)){e.debug&&console.warn(`[sentient] componentGoal("${o}"): slot not decided this session \u2014 not attributed`);return}let E=_?_.variantId:Ue(S),C={id:rt(),sessionId:x,projectId:e.apiKey,componentId:o,variantId:E,eventType:"goal_achieved",goalType:d,payload:O({reward:(U=m==null?void 0:m.reward)!=null?U:1,goalValue:m==null?void 0:m.value,currency:m==null?void 0:m.currency},(F=m==null?void 0:m.metadata)!=null?F:{}),timestamp:Date.now(),timeInSession:Date.now()-i,path:ze()};e.debug&&console.log("[sentient] componentGoal",C),te.then(()=>s.push(C))},identify(o){let d=c.getSessionId();d&&te.then(()=>{fetch(`${r}/sessions`,{method:"POST",keepalive:!0,body:JSON.stringify({sessionId:d,userId:o,ephemeral:c.isEphemeral()}),headers:a}).catch(()=>{})})},track(o){let d=c.getSessionId();if(!d||o.eventType==="variant_assigned"&&P.get(o.componentId)!==void 0&&!L.has(o.componentId)&&!f.get(o.componentId,b))return;let m=de(O({path:ze()},o),{id:rt(),sessionId:d,timestamp:Date.now(),timeInSession:Date.now()-i});e.debug&&console.log("[sentient] track",m),te.then(()=>s.push(m))},getAssignment(o,d){return f.get(o,d)},async assign(o,d,m,x){let _=c.getSessionId();if(!_)return null;let S=f.get(o,b);if(S&&(d!=null&&d.length||S.content!==void 0)){let E=S.ttlMs&&S.ttlMs>0?Math.max(0,S.assignedAt+S.ttlMs-Date.now()):0;return{variantId:S.variantId,assignmentTtlMs:E,content:S.content}}return it(N,o,async()=>{await te;try{let E={sessionId:_,componentId:o,variantIds:d};x!==void 0?E.agentDataByVariant=x:m!==void 0&&(E.agentData=m);let C=await fetch(`${r}/assign`,{method:"POST",body:JSON.stringify(E),headers:a});if(!C.ok)return null;let M=await C.json();return f.set(o,b,O({variantId:M.variantId,assignedAt:Date.now(),segment:b,confidence:1,content:M.content},M.assignmentTtlMs&&M.assignmentTtlMs>0?{ttlMs:M.assignmentTtlMs}:{})),M}catch(E){return null}})},async decide(o){var S,E;let d=c.getSessionId();if(!d)return null;let m=(S=o.slots)!=null?S:[],x={sessionId:d};o.sections&&o.sections.length>0&&(x.sections=o.sections.map(C=>({id:C}))),x.components=(E=o.components)!=null?E:[],m.length>0&&(x.slots=m.map(Ae)),o.slotsFrom==="registry"&&(x.slotsFrom="registry",o.registrySlotIds&&(x.registrySlotIds=o.registrySlotIds),o.bootstrap===!1&&(x.bootstrap=!1)),o.v&&(x.v=o.v),typeof o.pp=="number"&&(x.pp=o.pp),e.persona&&(x.persona=e.persona);let _=JSON.stringify(x);return it(G,_,async()=>{var C,M,U,F,ne,he,ve,xe;await te;try{let ce=await fetch(`${r}/decide`,{method:"POST",body:_,headers:a});if(!ce.ok)return dt(m),null;let T=await ce.json(),q={};for(let B of m){let J=(C=T.slots)==null?void 0:C[B.id];if(J!==void 0){q[B.id]=J,P.set(B.id,J),L.add(B.id);continue}let kt=P.get(B.id);if(kt!==void 0)q[B.id]=kt;else{let Et=ge(B);q[B.id]=Et,P.set(B.id,Et)}}if(T.slots)for(let[B,J]of Object.entries(T.slots))B in q||(q[B]=J,P.set(B,J),L.add(B));let en=I!=null&&I.persona!=="unknown";T.persona&&!(T.persona==="unknown"&&en)?I={persona:T.persona,confidence:(M=T.confidence)!=null?M:0}:I||(I={persona:"unknown",confidence:0});for(let[B,J]of Object.entries((U=T.assignments)!=null?U:{}))f.set(B,b,{variantId:J,assignedAt:Date.now(),segment:b,confidence:1});if(T.slotConfig)for(let[B,J]of Object.entries(T.slotConfig))D.set(B,J);T.palette&&(h=T.palette);for(let B of(F=o.registrySlotIds)!=null?F:[])(ne=T.slotConfig)!=null&&ne[B]||(D.delete(B),P.delete(B),L.delete(B));return me(e.apiKey,O(O({v:1,persona:I.persona,band:(0,st.confidenceBand)(I.confidence),slots:Object.fromEntries(P),layoutOrder:(he=T.layoutOrder)!=null?he:null,savedAt:Date.now()},D.size>0?{slotConfig:Object.fromEntries(D)}:{}),h?{palette:h}:{})),O(O(O(O({layoutOrder:(ve=T.layoutOrder)!=null?ve:null,assignments:(xe=T.assignments)!=null?xe:{},slots:q,persona:I.persona,confidence:I.confidence},T.slotConfig?{slotConfig:T.slotConfig}:{}),T.goals?{goals:T.goals}:{}),T.sectionMap?{sectionMap:T.sectionMap}:{}),T.palette?{palette:T.palette}:{})}catch(ce){return dt(m),null}})},getSlotResult(o){var d;return(d=P.get(o))!=null?d:null},isSlotDecided(o){return L.has(o)},getSlotConfig(o){var d;return(d=D.get(o))!=null?d:null},reportSlots(o,d){for(let m of o)if(!(typeof m!="string"||m.length===0)){if(!Se.test(m)){no()&&!v.has(m)&&(v.add(m),console.warn(`[sentient] reportSlots: slot id ${JSON.stringify(m)} will not register \u2014 ids must start with a letter or digit and contain only letters, digits, '_' or '-' (max 128 chars): /^[a-zA-Z0-9][a-zA-Z0-9_-]{0,127}$/.`));continue}if(!Z.has(m)){Z.add(m),W.add(m);let x=d==null?void 0:d[m];if(typeof x=="string"){let _=x.replace(/\s+/g," ").trim().slice(0,400);_!==""&&V.set(m,_)}}}W.size===0||X!=null||(X=setTimeout(()=>{X=null;let m=[...W];W.clear();for(let x=0;x<m.length;x+=20){let _=m.slice(x,x+20),S={};for(let E of _){let C=V.get(E);C!==void 0&&(S[E]=C,V.delete(E))}fetch(`${r}/slots/observed`,{method:"POST",headers:a,body:JSON.stringify(O({slotIds:_},Object.keys(S).length>0?{baselineTexts:S}:{}))}).catch(()=>{})}},1e3))},requestSlots(o,d){for(let m of o)j.has(m)||(j.add(m),Se.test(m)?Q.set(m,d==null?void 0:d[m]):K.reportSlots([m]));Q.size===0||z!=null||(z=setTimeout(()=>{z=null;let m=[...Q];Q.clear();for(let x=0;x<m.length;x+=50){let _=m.slice(x,x+50);K.decide({slotsFrom:"registry",registrySlotIds:_.map(([S])=>S),bootstrap:!1}).then(S=>{var E;if(S){let C={},M=[];for(let[U,F]of _)(E=S.slotConfig)!=null&&E[U]||(M.push(U),F&&(C[U]=F));M.length>0&&K.reportSlots(M,C)}else ct(_.map(([C])=>C),j,C=>{var U;let M={};for(let[F,ne]of _)C.has(F)&&ne&&(M[F]=ne);(U=K.requestSlots)==null||U.call(K,[...C],M)});A.forEach(C=>C())})}},0))},decideSlots(o){for(let d of o)re.has(d.id)||(re.add(d.id),H.set(d.id,d));H.size===0||se!=null||(se=setTimeout(()=>{se=null;let d=[...H.values()];H.clear();for(let m=0;m<d.length;m+=30){let x=d.slice(m,m+30);K.decide({slots:x}).then(_=>{_||ct(x.map(S=>S.id),re,S=>{var E;return(E=K.decideSlots)==null?void 0:E.call(K,x.filter(C=>S.has(C.id)))}),A.forEach(S=>S())})}},0))},cancelSlots(o){for(let d of o)Q.delete(d)&&j.delete(d),H.delete(d)&&re.delete(d)},onSlotsChanged(o){return A.add(o),()=>{A.delete(o)}},getSitePalette(){return h},getPersona(){return I?{persona:I.persona,confidence:I.confidence,band:(0,st.confidenceBand)(I.confidence)}:null},async fetchWeights(){var o;try{let d=await fetch(`${r}/weights`,{headers:a});return d.ok?(o=(await d.json()).components)!=null?o:[]:[]}catch(d){return[]}},getGraph(){return{pageNodes:[],capturedAt:0}},flush(){s.flush(),R.flush()},dispose(){var o;ae==null||ae(),Qe=!0,He=!0,s.destroy(),R.destroy(),((o=$.get(e.apiKey))==null?void 0:o.dispose)===K.dispose&&$.delete(e.apiKey),e.debug&&console.log("[sentient] disposed")},destroy(){var o;ae==null||ae(),Qe=!0,He=!0,s.destroy(),R.destroy(),c.destroy(),f.clear(),((o=$.get(e.apiKey))==null?void 0:o.dispose)===K.dispose&&$.delete(e.apiKey);try{localStorage.removeItem(le+e.apiKey),localStorage.removeItem(Xe(e.apiKey)),localStorage.removeItem(qe(e.apiKey))}catch(d){}e.debug&&console.log("[sentient] destroyed")}};if($.set(e.apiKey,{config:e,upgrade:null,dispose:K.dispose}),ae=ao(K,e.apiKey,o=>{te.then(()=>{Qe||Xt.add(o)})}),e.debug){let o=window;o.__sentient&&(o.__sentient.client=K)}return K}0&&(module.exports={AGENT_INTENTS,BLOCK_ALIGNS,BLOCK_EMPHASES,BLOCK_FITS,BLOCK_GAPS,BLOCK_GRID_COLUMNS,BLOCK_HEADING_LEVELS,BLOCK_JUSTIFIES,BLOCK_MAX_WIDTHS,BLOCK_PADS,BLOCK_RATIOS,BLOCK_SIZES,BLOCK_SURFACES,BLOCK_TEXT_ALIGNS,BLOCK_TONES,BLOCK_WEIGHTS,CLICK_ID_KEYS,FORM_FIELD_KINDS,FORM_INPUT_TYPES,LEGACY_SESSION_COOKIE_NAME,LOCAL_MODE_BANNER,MAX_BLOCK_ARMS,MAX_BLOCK_CHILDREN,MAX_BLOCK_DEPTH,MAX_BLOCK_NODES,MAX_BLOCK_TEXT_LEN,MAX_FORM_FIELDS,MAX_FORM_SELECT_OPTIONS,PAGE_SCOPE_RE,PROD_KEYLESS_ERROR,REVEAL_MS,SNAPSHOT_STORAGE_KEY_PREFIX,_registerConsentUpgradeInit,agentIntent,agentUaList,armOfResult,attachMicroSignalDetectors,baselineResultFor,baselineSlots,classifiedAgents,containsFormBlock,deriveSessionSegment,detectDeviceClass,detectTimeOfDay,detectTrafficSource,extractTrackedParams,grantConsent,init,isDoNotTrackEnabled,matchedAgentToken,pageScopeMatches,readSnapshot,referrerDomainFromReferer,renderPrePaintScript,resetRevealStyles,reveal,sessionCookieName,toWireSlot,uaTokenMatch,writeSnapshot});
|
|
2
2
|
//# sourceMappingURL=index.js.map
|