@sentientui/core 0.22.0 → 0.24.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-2NVSFI4V.mjs +2 -0
- package/dist/chunk-2NVSFI4V.mjs.map +1 -0
- package/dist/chunk-EWP6FTHE.mjs +2 -0
- package/dist/chunk-EWP6FTHE.mjs.map +1 -0
- package/dist/chunk-KIP52DUJ.mjs +2 -0
- package/dist/chunk-KIP52DUJ.mjs.map +1 -0
- package/dist/chunk-RL5B6M4G.mjs +2 -0
- package/dist/chunk-RL5B6M4G.mjs.map +1 -0
- package/dist/classify-DYlSjkFP.d.cts +47 -0
- package/dist/classify-DYlSjkFP.d.ts +47 -0
- package/dist/{index-BbrtAtrY.d.ts → index-BjVvN7cU.d.ts} +1 -1
- package/dist/{index-CXxvWxCB.d.cts → index-Cd0gMdJv.d.cts} +1 -1
- package/dist/index-engagement.d.cts +3 -28
- package/dist/index-engagement.d.ts +3 -28
- 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 +14 -4
- package/dist/index-graph.d.ts +14 -4
- package/dist/index-graph.js +1 -1
- package/dist/index-graph.js.map +1 -1
- package/dist/index-graph.mjs +1 -1
- package/dist/index-graph.mjs.map +1 -1
- package/dist/index-local.d.cts +2 -2
- package/dist/index-local.d.ts +2 -2
- package/dist/index-server.d.cts +10 -2
- package/dist/index-server.d.ts +10 -2
- 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-topics.d.cts +21 -0
- package/dist/index-topics.d.ts +21 -0
- package/dist/index-topics.js +2 -0
- package/dist/index-topics.js.map +1 -0
- package/dist/index-topics.mjs +2 -0
- package/dist/index-topics.mjs.map +1 -0
- package/dist/index.d.cts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1 -1
- package/dist/{session-meta-BVvq5RBB.d.cts → session-meta-C-bMqVeq.d.cts} +32 -1
- package/dist/{session-meta-BVvq5RBB.d.ts → session-meta-C-bMqVeq.d.ts} +32 -1
- package/package.json +7 -2
- package/dist/chunk-2RH7I6AP.mjs +0 -2
- package/dist/chunk-2RH7I6AP.mjs.map +0 -1
- package/dist/chunk-CD2A55US.mjs +0 -2
- package/dist/chunk-CD2A55US.mjs.map +0 -1
- package/dist/chunk-QNEYUJJJ.mjs +0 -2
- package/dist/chunk-QNEYUJJJ.mjs.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index-engagement.ts","../src/engagement/classify.ts","../src/index.ts","../src/micro-signals.ts","../src/engagement/capture.ts"],"sourcesContent":["// Lazy engagement entry — loaded on demand (mirrors ./graph) so the lean\n// bundle never carries the section classifier or IntersectionObserver logic.\nexport { startEngagementCapture, type EngagementCaptureOptions } from './engagement/capture';\nexport {\n classifyFeatures,\n classifySection,\n featuresFromElement,\n SEMANTIC_TYPES,\n type SectionFeatures,\n type SemanticType,\n} from './engagement/classify';\n","// Semantic section classification for no-code section capture (Phase 3 §2.4).\n// Pure heuristic: element → one of the graph_nodes semantic_type enum. Mirrors\n// the SDK graph scanner's vocabulary so the persona × section matrix consumes\n// snippet-captured sections unchanged.\n//\n// The classifier is split into a pure feature-based core (classifyFeatures —\n// also used server-side on crawled HTML by the site-audit classification job)\n// and a DOM wrapper (classifySection). Content-based patterns detect\n// pricing/social-proof/trust/comparison from BODY TEXT, so div-soup pages with\n// uninformative ids/classes still classify (persona-coverage spec 2026-07-23).\n\nexport type SemanticType =\n | 'pricing' | 'hero' | 'social_proof' | 'cta' | 'features'\n | 'faq' | 'comparison' | 'trust' | 'navigation' | 'generic';\n\n/** Canonical vocabulary — mirrors the graph_nodes semantic_type CHECK enum. */\nexport const SEMANTIC_TYPES: readonly SemanticType[] = [\n 'pricing', 'hero', 'social_proof', 'cta', 'features',\n 'faq', 'comparison', 'trust', 'navigation', 'generic',\n] as const;\n\n/** Environment-agnostic section features — buildable from a browser Element or\n * a server-parsed node (node-html-parser). */\nexport type SectionFeatures = {\n tag: string; // lowercase tag name\n idClass: string; // `${id} ${className}`\n headingText: string;\n bodyText: string; // normalized text content, first 2000 chars\n actionCount: number;\n textLength: number;\n};\n\n// Ordered most-specific first — the first keyword hit wins.\nconst KEYWORDS: Array<[SemanticType, RegExp]> = [\n ['pricing', /\\b(pricing|price|plans?|subscriptions?|per month|\\/mo|tier)\\b/i],\n ['faq', /\\b(faq|frequently asked|common questions?)\\b/i],\n ['comparison', /\\b(compare|comparison|versus|vs\\.)\\b/i],\n ['social_proof', /\\b(testimonial|reviews?|trusted by|loved by|customers?|logos|rated|case stud)\\b/i],\n ['trust', /\\b(security|guarantee|privacy|compliance|secure|gdpr|soc ?2|encrypt)\\b/i],\n ['features', /\\b(features?|how it works|benefits?|capabilit|what you get)\\b/i],\n];\n\n// Content-evidence patterns — run against bodyText. Ordered most-specific first.\n// Deliberately conservative: pricing needs per-period/plan context next to money\n// so an article mentioning \"$5 million\" stays generic.\nconst CONTENT_PATTERNS: Array<[SemanticType, RegExp]> = [\n ['pricing', /(?:[$€£]\\s?\\d[\\d,.]*\\s*(?:\\/|per\\s)\\s*(?:mo|month|yr|year|seat|user))|(?:\\b(?:starter|basic|pro|growth|premium|enterprise)\\b[^.]{0,60}[$€£]\\s?\\d)/i],\n ['social_proof', /(?:★{2,})|(?:\\b\\d(?:\\.\\d)?\\s*(?:out of|\\/)\\s*5\\b)|(?:\\brated\\b)|(?:[\"“][^\"”]{20,160}[\"”]\\s*[—–-]\\s*[A-Z][a-z]+)/],\n ['trust', /\\b(?:money[- ]back guarantee|refund(?:s)? within|encrypted|soc ?2|iso ?27001|gdpr[- ]compliant|cancel anytime)\\b/i],\n ['comparison', /\\b(?:vs|versus)\\b\\.?[^.!?]{0,80}\\b(?:compare|comparison|plans?|features?|alternative)\\b|\\bhow (?:we|it) compares?\\b/i],\n];\n\nfunction headingText(el: Element): string {\n const h = el.querySelector('h1, h2, h3');\n return (h?.textContent ?? '').slice(0, 160);\n}\n\n/**\n * Pure classification over extracted features. `strong` = keyword or content\n * evidence (trustable enough to auto-apply); `weak` = structural fallback\n * (cta/hero/navigation/generic — capture-worthy but not persona evidence).\n */\nexport function classifyFeatures(f: SectionFeatures): { type: SemanticType; strength: 'strong' | 'weak' } {\n if (f.tag === 'nav' || f.tag === 'footer') return { type: 'navigation', strength: 'weak' };\n const hay = `${f.idClass} ${f.headingText}`.toLowerCase();\n for (const [type, re] of KEYWORDS) {\n if (re.test(hay)) return { type, strength: 'strong' };\n }\n for (const [type, re] of CONTENT_PATTERNS) {\n if (re.test(f.bodyText)) return { type, strength: 'strong' };\n }\n if (f.actionCount >= 1 && f.textLength > 0 && f.textLength < 200) return { type: 'cta', strength: 'weak' };\n if (f.tag === 'header') return { type: 'hero', strength: 'weak' };\n if (/\\b(hero|headline|banner)\\b/i.test(hay)) return { type: 'hero', strength: 'weak' };\n return { type: 'generic', strength: 'weak' };\n}\n\n/** Feature extraction from a live DOM element (browser paths). */\nexport function featuresFromElement(el: Element): SectionFeatures {\n const text = (el.textContent ?? '').replace(/\\s+/g, ' ').trim();\n return {\n tag: el.tagName.toLowerCase(),\n idClass: `${el.id} ${String(el.className ?? '')}`,\n headingText: headingText(el),\n bodyText: text.slice(0, 2000),\n actionCount: el.querySelectorAll('a, button, [role=\"button\"]').length,\n textLength: text.length,\n };\n}\n\n/** Classify a page section into a semantic type (never null — falls back to\n * 'generic' so the caller can still capture attention on it). */\nexport function classifySection(el: Element): SemanticType {\n return classifyFeatures(featuresFromElement(el)).type;\n}\n","import { initSession, type SessionConfig, type SessionManager } from './session';\nimport {\n createEventQueue,\n retryStorageKey,\n type EventQueue,\n type EventType,\n type QueueConfig,\n type SentientEvent,\n} from './queue';\nimport {\n createGoalQueue,\n goalRetryStorageKey,\n type GoalQueue,\n} from './goal-queue';\nimport {\n createAssignmentCache,\n type Assignment,\n} from './cache';\nimport type {\n GraphConfig,\n GraphSnapshot,\n} from './graph';\nimport {\n detectDeviceClass,\n detectTrafficSource,\n detectTimeOfDay,\n referrerDomainFromReferer,\n uaTokenMatch,\n} from './session-meta.js';\nimport {\n toWireSlot,\n baselineResultFor,\n armOfResult,\n type SlotDeclInput,\n type SlotResult,\n} from './slots.js';\nimport { readSnapshot, writeSnapshot, SNAPSHOT_STORAGE_KEY_PREFIX, type SlotConfigEntry, type CompoundLocator } from './snapshot.js';\nimport { confidenceBand } from '@sentientui/policy';\nimport { createLocalModeClient } from './local-mode.js';\nimport { randomUuidV4 } from './uuid.js';\nimport { backoffDelayMs, classifyResponse } from './durable.js';\n\nexport { PROD_KEYLESS_ERROR, LOCAL_MODE_BANNER } from './local-mode.js';\n\n// The one source of truth for the session cookie's name — every out-of-package\n// reader (react devtools, integrator SSR code) must derive the name from this\n// instead of hard-coding `_snt_uid`, which is only the pre-namespacing fallback.\nexport { sessionCookieName, LEGACY_SESSION_COOKIE_NAME } from './storage-key.js';\n\nexport {\n detectDeviceClass,\n detectTrafficSource,\n detectTimeOfDay,\n deriveSessionSegment,\n referrerDomainFromReferer,\n uaTokenMatch,\n matchedAgentToken,\n agentUaList,\n agentIntent,\n classifiedAgents,\n AGENT_INTENTS,\n} from './session-meta.js';\nexport type { AgentIntent } from './session-meta.js';\n\nconst DEFAULT_INGEST_URL = 'https://api.sentient-ui.com/v1/events';\n\n// Keyed by apiKey so multiple init() calls (HMR, multi-project) don't collide.\nconst _clients = new Map<string, {\n config: SentientConfig;\n upgrade: ((c: SentientClient) => void) | null;\n // Why grantConsent() cannot upgrade this entry (keyless/local mode, invalid\n // key). grantConsent() warns with this instead of silently no-oping — a CMP\n // callback wired to it otherwise LOOKED like it worked while nothing ever\n // started tracking. Absent for entries where the silent no-op IS the\n // documented contract (DNT-blocked, already upgraded).\n upgradeBlockedReason?: string;\n // Set by an alternate entry point (the /graph entry) whose gated init\n // deferred extra resources: grantConsent() must re-run THAT entry's init —\n // upgrading through the lean init() produced a post-consent client that\n // never mounted the DOM scanner, silently losing graph capture.\n reinit?: (c: SentientConfig) => SentientClient;\n // Teardown for the live client bound to this key (stops its queue interval +\n // unload listeners). Present only for the full tracking client; the no-op /\n // pre-consent / local entries have nothing to tear down. Called before a\n // re-init for the same key replaces it, so timers/listeners can't leak.\n dispose?: () => void;\n}>();\nlet _lastApiKey: string | null = null;\n\n/**\n * @internal Wires an alternate entry point's init as grantConsent()'s upgrade\n * path for `apiKey`. The /graph entry calls this when its init is gated on\n * consent: without it, grantConsent() upgraded through the LEAN init, so a\n * graph-configured page granted consent but never mounted the scanner (the\n * graph resources exist only in the /graph entry). No-op unless the entry is\n * actually upgradeable — DNT-blocked and local entries register no hook.\n */\nexport function _registerConsentUpgradeInit(\n apiKey: string,\n reinit: (config: SentientConfig) => SentientClient,\n): void {\n const entry = _clients.get(apiKey);\n if (entry && entry.upgrade) entry.reinit = reinit;\n}\n\nexport type SentientConfig = {\n apiKey: string;\n context: 'landing' | 'ecommerce' | 'saas' | 'marketplace';\n /** @internal — not exposed to users; defaults to the hosted SentientUI API. */\n ingestUrl?: string;\n debug?: boolean;\n /**\n * Pre-seeded assignments from `preloadAssignments()` (SSR).\n * Seeds the local cache so `assign()` returns without a network call for\n * listed code variants, guaranteeing server and client render the same\n * variant on first paint. Managed-text components (assign with no\n * variantIds) still fetch once when the seed carries no content.\n */\n initialAssignments?: Record<string, string>;\n /**\n * Segment used for SSR preload (`device:source`). When set with `initialAssignments`,\n * seeds the assignment cache under this key so hydration matches the server bandit row.\n */\n sessionSegment?: string;\n /**\n * Consent gate. When `false`, returns a no-op client and performs no tracking.\n * Defaults to `true`. Re-call `init()` (via `AdaptiveProvider` consent prop) when\n * the user grants or revokes consent mid-session.\n */\n consent?: boolean;\n /**\n * Behavior before consent is granted. `'statistical_winner'` fetches the\n * best-performing variant via `GET /v1/winner` — no session or tracking data\n * is stored. `'control'` (default) shows `variantIds[0]` with no API call.\n * Applies when tracking is gated off — either `consent: false` or an active\n * Do Not Track signal.\n */\n preConsentBehavior?: 'statistical_winner' | 'control';\n /**\n * Whether to honor the browser's Do Not Track (DNT) signal. Defaults to `true`.\n * When `true` and the visitor has DNT enabled, the SDK sets no cookies and\n * sends no tracking data — behaving exactly as `consent: false` (still serving\n * the read-only `preConsentBehavior` winner if configured), and `grantConsent()`\n * will not upgrade it. Set `false` to make your own consent gate authoritative.\n */\n respectDoNotTrack?: boolean;\n userId?: string;\n /**\n * Declared persona — the role your app already knows for this visitor\n * (e.g. 'admin', 'evaluator'). Must be a key in the project's persona\n * vocabulary (dashboard → Settings → Personas); unrecognized values are\n * ignored server-side and surfaced in the dashboard so you can add them.\n * Declared personas are served at full confidence, overriding the inferred\n * one. Keep it a low-cardinality role label — never a user id or email.\n */\n persona?: string;\n /**\n * Session ID generated server-side (from `loadAdaptiveAssignments` / `loadAdaptiveDecision`).\n * When provided, the client adopts this ID on first visit instead of generating a new one,\n * ensuring events and goals are attributed to the same session the server used for assignment.\n */\n ssrSessionId?: string;\n /**\n * ISO 3166-1 alpha-2 country code for the visitor. When provided (e.g. from\n * the `CF-IPCountry` header in a Next.js server component), it is included in\n * the session upsert so country-based segmentation works without client-side\n * geo lookup.\n */\n country?: string;\n /**\n * Pre-seeded slot results from `preloadDecisions()` / `loadAdaptiveDecision()`\n * (SSR). Seeds the local slot state so `getSlotResult()` agrees with the\n * server-rendered markup on first paint.\n */\n initialSlots?: Record<string, SlotResult>;\n /**\n * Persona decided during SSR. Takes priority over the html-attribute\n * adoption and the local snapshot.\n */\n initialPersona?: { persona: string; confidence: number };\n /**\n * Keyless local mode. 'auto' (default) simulates decisions on-device when no\n * valid API key is configured — but only in development builds (the\n * `development` export condition); production bundles physically exclude the\n * engine. `true` forces the local engine regardless of key (escape hatch);\n * `false` restores the silent keyless no-op.\n */\n localMode?: 'auto' | boolean;\n};\n\nexport type AssignResult = { variantId: string; assignmentTtlMs: number; content?: string };\n\nexport type { SlotDeclInput, SlotResult };\nexport { armOfResult, baselineResultFor, baselineSlots, toWireSlot } from './slots.js';\n\nexport {\n SNAPSHOT_STORAGE_KEY_PREFIX,\n readSnapshot,\n writeSnapshot,\n renderPrePaintScript,\n} from './snapshot.js';\nexport type { DecisionSnapshot, SlotConfigEntry, SlotOps, CompoundLocator } from './snapshot.js';\nexport * from './blocks.js';\n\n/** An editor-defined goal delivered with a registry-mode decision, for the\n * snippet to install delegated listeners from. */\nexport type GoalDefinition = {\n goalId: string;\n event: 'click' | 'form_submit' | 'url_reached' | 'scroll_depth';\n locator?: CompoundLocator;\n urlPattern?: string;\n slotId?: string;\n /** scroll_depth only: fraction of the page (0–1] that counts as read. */\n threshold?: number;\n};\n\n/** One served section-classification row (registry mode): where it is on the\n * page (url match + compound locator) and its semantic type. The snippet\n * resolves the locator to build capture's `typeOf` hook. */\nexport type SectionMapEntry = {\n urlMatch: string;\n locator: CompoundLocator;\n type: string;\n};\n\nexport type DecideOutcome = {\n layoutOrder: string[] | null;\n assignments: Record<string, string>;\n slots: Record<string, SlotResult>;\n persona: string;\n confidence: number;\n // Registry mode only: where/what to apply for server-defined slots.\n slotConfig?: Record<string, SlotConfigEntry>;\n // Registry mode only: editor-defined goals to wire up.\n goals?: GoalDefinition[];\n // Registry mode only: served section-classification map the snippet turns\n // into capture's `typeOf` hook.\n sectionMap?: SectionMapEntry[];\n // Registry mode only: derived site palette for Composition Block rendering.\n palette?: import('./blocks.js').SitePalette;\n};\n\nexport type DecideInput = {\n sections?: string[];\n components?: Array<{ id: string; variantIds?: string[] }>;\n slots?: SlotDeclInput[];\n // 'registry' → serve the project's published slot_definitions in addition to\n // any declared slots (registry wins on id collision). Default 'request'.\n slotsFrom?: 'request' | 'registry';\n /**\n * Caller's build version (e.g. the snippet's `__SNIPPET_VERSION__`), sent\n * as `v` on the wire. Additive/best-effort: the server persists it for\n * version-skew reporting (see apps/api decide route) and ignores it\n * entirely on older deployments. Omit if the caller has no version to report.\n */\n v?: string;\n};\n\nexport type WeightEntry = { variantId: string; pulls: number; avgReward: number | null };\nexport type ComponentWeightEntry = { componentId: string; updatedAt: number; variants: WeightEntry[] };\n\n/** Options accepted by goal() (and inherited by componentGoal / the React\n * hooks / the snippet) — one shape everywhere (spec §5). */\nexport type GoalOptions = {\n /** Revenue of this conversion, in the project currency. */\n value?: number;\n /** ISO-4217 code, only when it differs from the project currency. */\n currency?: string;\n /** Merchant order/transaction id — dedupes retries, enables refunds later. */\n externalId?: string;\n /** Extra fields merged into the event payload / goal metadata. */\n metadata?: Record<string, unknown>;\n /** Advanced: partial-credit weight in [0,1] (composite steps). */\n weight?: number;\n /** Advanced: funnel step index (0-based). */\n stepIndex?: number;\n};\n\n/** goal()'s second arg is the options object iff it carries a reserved key;\n * anything else keeps the legacy bare-metadata interpretation. Reserved keys\n * inside legacy metadata were inert on the server, so reinterpretation is the\n * upgrade the sender wanted (spec §5). */\nfunction isGoalOptions(v: Record<string, unknown>): boolean {\n return 'value' in v || 'currency' in v || 'externalId' in v || 'metadata' in v || 'weight' in v || 'stepIndex' in v;\n}\n\nexport type ComponentGoalOptions = GoalOptions & {\n /** Reward credited to the served variant (0–1). Defaults to 1. */\n reward?: number;\n};\n\nexport type SentientClient = {\n track(\n event: Omit<SentientEvent, 'id' | 'sessionId' | 'timestamp' | 'timeInSession'>,\n ): void;\n goal(name: string, options?: GoalOptions): void;\n /** @deprecated positional form — prefer goal(name, options). */\n goal(name: string, metadata?: Record<string, unknown>, weight?: number, stepIndex?: number): void;\n /**\n * Records a conversion attributed to the variant currently served for\n * `componentId`, so it feeds the per-variant CVR funnel. Resolves the served\n * variant from the local assignment cache — no need to pass variantId or\n * projectId. No-ops if the component has not been assigned yet (render its\n * `<Adaptive>`/call `assign()` first). Prefer this over bare `goal()` for\n * variant experiments; `goal()` is session-level only (no component attribution).\n */\n componentGoal(componentId: string, goalType: string, opts?: ComponentGoalOptions): void;\n identify(userId: string): void;\n getAssignment(componentId: string, segment: string): Assignment | null;\n /** Server-side variant assignment. Caches the result locally per (component, segment). */\n assign(componentId: string, variantIds?: string[], agentData?: unknown, agentDataByVariant?: Record<string, unknown>): Promise<AssignResult | null>;\n /**\n * Single-roundtrip decision for layout sections, component variants, and\n * adaptive slots. Awaits the session upsert (like `assign`) so the server\n * never decides for a session row that doesn't exist yet. A response\n * without a `slots` field means the server predates slots — every declared\n * slot resolves to its baseline and no retry is made.\n */\n decide(input: DecideInput): Promise<DecideOutcome | null>;\n /** Slot result served this session (decide result, SSR seed, snapshot, or failure baseline). Null when unknown. */\n getSlotResult(slotId: string): SlotResult | null;\n /** Current persona estimate. Band is always `confidenceBand(confidence)`. Null when nothing is known yet. */\n getPersona(): { persona: string; confidence: number; band: 'low' | 'medium' | 'high' } | null;\n /** Fetches current bandit weights for all components in this project. Used by the provider to keep live-weight polling fresh. */\n fetchWeights(): Promise<ComponentWeightEntry[]>;\n getGraph(): GraphSnapshot;\n /**\n * Routine teardown: stops timers/listeners and flushes pending events, but\n * KEEPS the visitor identity, decision snapshot, and retry bucket. Use for\n * component unmount / re-init (framework providers call this on cleanup).\n */\n dispose(): void;\n /**\n * Consent-revocation / forget-me teardown: everything `dispose()` does,\n * plus deletion of the visitor identity (`_snt_uid`), the decision\n * snapshot, and the persisted retry bucket. The next visit starts as a\n * brand-new visitor.\n */\n destroy(): void;\n /** True when this client is the keyless local-mode client (dev only). */\n readonly isLocal?: boolean;\n};\n\n// SSR preload helpers moved to the `@sentientui/core/server` entry in 0.6.0 so\n// ~200 lines of Node-only fetch logic stop shipping in the browser bundle.\n\nexport { attachMicroSignalDetectors } from './micro-signals.js';\nexport type { MicroSignalEmitter, MicroSignalType } from './micro-signals.js';\n\nexport type {\n SessionConfig,\n SessionManager,\n EventType,\n SentientEvent,\n QueueConfig,\n Assignment,\n GraphSnapshot,\n GraphConfig,\n};\n\n/** Attempts after the first for the session upsert — see upsertSession. */\nconst SESSION_UPSERT_RETRIES = 3;\n\nfunction generateEventId(): string {\n return randomUuidV4();\n}\n\n/**\n * The page an event happened on.\n *\n * `location.pathname` ONLY — never `href` or `search`. Query strings on real\n * sites carry emails, reset tokens, order ids and session ids, and none of that\n * should leave the browser for analytics. The server strips them again\n * (domain/page-path.ts) because a hand-rolled integration can post whatever it\n * likes; this is the first of the two gates, and the one that means the data\n * never travels at all.\n *\n * Undefined outside a browser: during SSR there is no page to name, and an\n * invented one would be wrong for every reader.\n */\nfunction currentPath(): string | undefined {\n if (typeof window === 'undefined') return undefined;\n return window.location?.pathname || undefined;\n}\n\n/**\n * Decides whether a goal() call belongs to a user action already recorded.\n *\n * This used to be a clock: a latch cleared on the next macrotask, so anything\n * inside that window counted as \"the same action\". A clock cannot tell the two\n * cases apart, and it got the expensive one wrong. The window can be JUMPED —\n * a macrotask scheduled to close it runs after any timer already armed, which\n * every real page and every sibling test in a worker has — so a genuinely\n * separate conversion landed in a window that should have shut, and was\n * swallowed rather than queued: gone, with no retry able to rescue it because\n * nothing was ever handed to the queue.\n *\n * So ask the question the clock was approximating. Two nested components\n * reacting to one click are, exactly, two listeners in one event DISPATCH, and\n * the platform already hands us that identity: `window.event` is the same Event\n * object for every listener of one dispatch, a different object for the next\n * click, and undefined outside dispatch entirely. Keying on the event object\n * makes \"one action\" a fact rather than a deadline — no timer to lose a race\n * with, no fake-timer or background-throttle hazard, and no way for a second\n * click to be mistaken for the first however long the page stalls between them.\n *\n * Goals fired outside any dispatch (an effect on mount, a page goal) have no\n * event to key on, and fall back to one SYNCHRONOUS flush — closed on a\n * microtask. That is exact too, and for the same reason the old macrotask\n * window was not: microtasks always drain before the next macrotask, so no\n * pending timer can jump this window. A user cannot perform two actions inside\n * one synchronous block, so anything sharing it is a double-fire, not a repeat.\n *\n * A microtask is deliberately NOT used for the dispatch case: the HTML spec\n * runs a microtask checkpoint between listeners once the JS stack empties, so\n * it would split one click into two and double-count the revenue this collapse\n * exists to protect. That is why the dispatch case keys on the event instead,\n * and why a host without `window.event` keeps the old macrotask window — too\n * loose, but erring toward the old behaviour rather than toward double-counting.\n */\nfunction createActionLatch(): { firedBefore(actionKey: string, valueKey: string | null): boolean } {\n // Per window, per action key: the set of value identities already recorded.\n // An entry with an empty set means a VALUELESS fire was recorded. The split\n // exists because value cannot simply live inside one flat key: an inner\n // component declaring `value: 50` nested in an outer wrapper with the same\n // goal but NO value produced two distinct keys — two rows for one click.\n // Within a window, a valueless fire is absorbed by ANY record of the same\n // action (the valued row already carries the order, and a valueless\n // duplicate would inflate Hits), while a valued fire is collapsed only by an\n // IDENTICAL (value, currency) record — $50 and $70 stay two orders\n // (CONTRACTS §1). A valued fire landing AFTER a valueless one still records:\n // the valueless row has already been handed to the queue (often already on\n // the wire) and cannot be retracted, and losing the money would be the worse\n // error — server-side credit clamps the extra valueless hit at min(1, MAX\n // weight), so the cost is one inflated Hit, not corrupted revenue. Listener\n // order makes the benign ordering the common one: the inner (valued)\n // component's listener runs before the wrapper's in a bubbling dispatch.\n const byEvent = new WeakMap<object, Map<string, Set<string>>>();\n const byFlush = new Map<string, Set<string>>();\n let flushOpen = false;\n\n const alreadyRecorded = (map: Map<string, Set<string>>, actionKey: string, valueKey: string | null): boolean => {\n const values = map.get(actionKey);\n if (valueKey === null) {\n if (values) return true;\n map.set(actionKey, new Set());\n return false;\n }\n if (!values) {\n map.set(actionKey, new Set([valueKey]));\n return false;\n }\n if (values.has(valueKey)) return true;\n values.add(valueKey);\n return false;\n };\n\n // Standardised as Window.event and present in every current browser, but a\n // capability check keeps exotic hosts on the path they have always had.\n const hasWindowEvent = typeof window !== 'undefined' && 'event' in window;\n\n const currentEvent = (): object | undefined => {\n if (!hasWindowEvent) return undefined;\n const ev = (window as unknown as { event?: unknown }).event;\n // Must be a real same-realm Event, not merely an object. Window.event is\n // [Replaceable]: a classic script doing `event = {...}` at top level (an\n // implicit or sloppy global on plenty of host pages) permanently shadows\n // the accessor with a data property. Accepting any object then returned\n // that SAME object forever — its WeakMap entry never died, so every later\n // conversion looked like a re-fire of the first action and ALL repeat\n // conversions were silently dropped for the session. `instanceof Event`\n // cannot be true for such a literal; a cross-realm Event (iframe) fails it\n // too and merely falls back to the flush window, which is safe.\n // (typeof guard: a host with `window` but no Event constructor must fall\n // back, not throw a ReferenceError from inside goal().)\n return typeof Event === 'function' && ev instanceof Event ? ev : undefined;\n };\n\n const closeFlushWindow = (): void => {\n if (hasWindowEvent) {\n // A promise microtask, not queueMicrotask: fake-timer setups can replace\n // queueMicrotask, and this window closing is what keeps repeat\n // conversions from being swallowed.\n void Promise.resolve().then(() => {\n flushOpen = false;\n byFlush.clear();\n });\n return;\n }\n let done = false;\n const clear = (): void => {\n if (done) return;\n done = true;\n flushOpen = false;\n byFlush.clear();\n };\n setTimeout(clear, 0);\n if (typeof MessageChannel === 'function') {\n const ch = new MessageChannel();\n ch.port1.onmessage = () => {\n ch.port1.close();\n ch.port2.close();\n clear();\n };\n ch.port2.postMessage(0);\n }\n };\n\n return {\n firedBefore(actionKey: string, valueKey: string | null): boolean {\n const ev = currentEvent();\n if (ev) {\n let keys = byEvent.get(ev);\n if (!keys) {\n keys = new Map<string, Set<string>>();\n // Keyed weakly: the Map dies with the Event object, so a long session\n // of clicks accumulates nothing.\n byEvent.set(ev, keys);\n }\n return alreadyRecorded(keys, actionKey, valueKey);\n }\n const collapsed = alreadyRecorded(byFlush, actionKey, valueKey);\n if (!collapsed && !flushOpen) {\n flushOpen = true;\n closeFlushWindow();\n }\n return collapsed;\n },\n };\n}\n\n/**\n * Emits one `pageview` per page load and per SPA route change.\n *\n * Patches pushState/replaceState rather than polling: a route change is a\n * discrete event, and polling would either miss fast back-to-back navigations or\n * burn a timer on every page for the entire session. popstate covers\n * back/forward, which history patching does not see.\n *\n * Deduplicates on pathname, because frameworks routinely replaceState several\n * times for one navigation (query/hash updates, scroll restoration) and each\n * would otherwise look like another page in the visitor's journey.\n */\n/** Pages already recorded this page lifetime, keyed project:path. dispose()\n * flushes, so without this a consent-change or StrictMode re-init delivered a\n * second landing pageview for a page the previous client already sent. */\nconst emittedPages = new Set<string>();\n\nfunction startPageviewTracking(\n client: SentientClient,\n projectId: string,\n // Called with the page key after emitting; the caller marks emittedPages only\n // once the event reached a LIVE queue. Marking at emit time instead turned\n // StrictMode's mount→dispose→mount into zero delivered landings: the first\n // mount's event dies in the destroyed queue, and the mark suppressed the\n // second mount's — the one that actually ships.\n markDelivered: (key: string) => void,\n): () => void {\n const h = typeof window === 'undefined' ? null : window.history;\n if (!h) return () => undefined;\n\n // The stop handle exists because init() runs again on every consent change,\n // StrictMode double-invoke and HMR: without it each init wrapped history\n // again and the old wrapper kept emitting through the DISPOSED client, so one\n // navigation produced one pageview per init that ever happened.\n let stopped = false;\n let last: string | undefined;\n const emit = (): void => {\n if (stopped) return;\n const path = currentPath();\n if (!path || path === last) return;\n last = path;\n // '__page__' is a sentinel componentId: the ingest schema requires one, and\n // every component reader filters on variant_id IS NOT NULL or a specific\n // event_type, so it never surfaces as a component.\n client.track({ projectId, componentId: '__page__', eventType: 'pageview', payload: {} });\n markDelivered(`${projectId}:${path}`);\n };\n\n const installed: Array<['pushState' | 'replaceState', History['pushState'], History['pushState']]> = [];\n for (const name of ['pushState', 'replaceState'] as const) {\n const orig = h[name];\n const wrapper = function (this: History, ...a: unknown[]) {\n const r = (orig as (...x: unknown[]) => unknown).apply(this, a);\n emit();\n return r;\n } as History[typeof name];\n h[name] = wrapper;\n installed.push([name, orig, wrapper]);\n }\n window.addEventListener('popstate', emit);\n\n // The landing page itself — once per (project, path) per page lifetime. When\n // it was already sent, `last` is still primed so the next real navigation\n // emits exactly once.\n const landing = currentPath();\n if (landing && emittedPages.has(`${projectId}:${landing}`)) last = landing;\n else emit();\n\n return () => {\n if (stopped) return;\n stopped = true;\n window.removeEventListener('popstate', emit);\n for (const [name, orig, wrapper] of installed) {\n // Restore only while ours is still on top; if something wrapped over it,\n // unhooking would sever their chain — the stopped flag already makes ours\n // a passthrough.\n if (h[name] === wrapper) h[name] = orig;\n }\n };\n}\n\nconst SSR_CLIENT: SentientClient = {\n track: () => undefined,\n goal: () => undefined,\n componentGoal: () => undefined,\n identify: () => undefined,\n getAssignment: () => null,\n assign: () => Promise.resolve(null),\n decide: () => Promise.resolve(null),\n getSlotResult: () => null,\n getPersona: () => null,\n fetchWeights: () => Promise.resolve([]),\n getGraph: () => ({ pageNodes: [], capturedAt: 0 }),\n dispose: () => undefined,\n destroy: () => undefined,\n};\n\nfunction readUtmParams(): Record<string, string> {\n try {\n const out: Record<string, string> = {};\n const sp = new URLSearchParams(window.location.search);\n for (const [k, v] of sp) {\n if (k.startsWith('utm_')) out[k] = v;\n }\n return out;\n } catch {\n return {};\n }\n}\n\nfunction deriveBaseUrl(ingestUrl: string): string {\n return ingestUrl.replace(/\\/events\\/?$/, '');\n}\n\n/**\n * Detects whether the visitor has signalled a tracking opt-out. Honors Global\n * Privacy Control (`navigator.globalPrivacyControl`) — the legally-enforceable\n * CCPA/CPRA signal — as well as Do Not Track (`navigator.doNotTrack`, the legacy\n * `window.doNotTrack` on older Firefox, and `navigator.msDoNotTrack` on old\n * IE/Edge). GPC is a boolean; DNT is opt-out only when explicitly `'1'`/`'yes'`.\n */\nexport function isDoNotTrackEnabled(): boolean {\n // GPC is a boolean flag, checked separately from the DNT string signals.\n if (\n typeof navigator !== 'undefined' &&\n (navigator as unknown as { globalPrivacyControl?: boolean }).globalPrivacyControl === true\n ) {\n return true;\n }\n const signals = [\n typeof navigator !== 'undefined' ? navigator.doNotTrack : undefined,\n typeof window !== 'undefined'\n ? (window as unknown as { doNotTrack?: string | null }).doNotTrack\n : undefined,\n typeof navigator !== 'undefined'\n ? (navigator as unknown as { msDoNotTrack?: string | null }).msDoNotTrack\n : undefined,\n ];\n return signals.some((v) => v === '1' || v === 'yes');\n}\n\n/**\n * Upgrades a pre-consent client (any client created with `consent: false`, in\n * either `preConsentBehavior` mode) to a fully-tracking client, in place and\n * with no page reload. Call this from your consent management platform callback.\n * For React apps, prefer updating the `consent` prop on `<AdaptiveProvider>`.\n * Pass `apiKey` to target a specific project; omit to upgrade the most-recently-initialized client.\n */\nexport function grantConsent(apiKey?: string): void {\n if (typeof window === 'undefined') return;\n\n const key = apiKey ?? _lastApiKey;\n if (!key) {\n console.warn('[sentient] grantConsent() called before init()');\n return;\n }\n\n const entry = _clients.get(key);\n if (!entry) {\n console.warn('[sentient] grantConsent() called before init()');\n return;\n }\n\n const { config, upgrade, reinit } = entry;\n if (!upgrade) {\n // Keyless/local and invalid-key clients register no upgrade hook — there\n // is no hosted client to swap in. This used to return SILENTLY, so a CMP\n // callback wired to grantConsent() looked like it worked while nothing\n // ever started tracking. DNT-blocked and already-upgraded entries carry no\n // reason and stay quiet: for them the no-op is the documented contract.\n if (entry.upgradeBlockedReason) console.warn(entry.upgradeBlockedReason);\n return;\n }\n\n // Honor an active Do Not Track signal — consent cannot override a global opt-out.\n if (config.respectDoNotTrack !== false && isDoNotTrackEnabled()) return;\n\n // Upgrade through the entry point that ran the gated init when one\n // registered itself (see _registerConsentUpgradeInit) — the lean init knows\n // nothing about that entry's extra resources (the /graph scanner).\n const fullClient = (reinit ?? init)({ ...config, consent: true });\n upgrade(fullClient);\n // init() just registered the full client (with its dispose) under `key`.\n // Preserve that dispose so a later re-init/teardown can still tear it down —\n // we only need to clear the upgrade hook now that consent is granted.\n const disposed = _clients.get(key)?.dispose;\n _clients.set(key, { config: { ...config, consent: true }, upgrade: null, dispose: disposed });\n}\n\nfunction createPreConsentProxy(config: SentientConfig): { proxy: SentientClient; setInner: (c: SentientClient) => void } {\n // 'control' (the default) must reach the network zero times before consent.\n // The proxy still exists so grantConsent() has something to upgrade in place\n // — without it, a site wanting no pre-consent traffic could only start\n // tracking by reloading the page.\n const servesWinner = config.preConsentBehavior === 'statistical_winner';\n const baseUrl = deriveBaseUrl(config.ingestUrl ?? DEFAULT_INGEST_URL);\n const authHeaders = {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${config.apiKey}`,\n } as const;\n\n // Pre-consent winners are read-only and render-driven: every mounted\n // component re-calls assign() on every render, and without a result cache or\n // in-flight coalescing each call refired GET /v1/winner — the full client\n // has inflightAssigns for exactly this. Successful winners are cached for\n // the pre-consent phase (the winner is stable, and a flip mid-visit would be\n // a variant flash anyway); failure fallbacks are NOT cached, so a recovering\n // server gets asked again. Both maps die with the proxy on upgrade.\n const winnerCache = new Map<string, AssignResult>();\n const inflightWinners = new Map<string, Promise<AssignResult | null>>();\n\n let inner: SentientClient = {\n track: () => undefined,\n goal: () => undefined,\n componentGoal: () => undefined,\n identify: () => undefined,\n getAssignment: () => null,\n fetchWeights: () => Promise.resolve([]),\n assign(componentId, variantIds, _agentData?) {\n // Control mode: no request. Callers fall back to variantIds[0] through\n // ssrFallback, exactly as they did against the old no-op client.\n if (!servesWinner) return Promise.resolve(null);\n const cached = winnerCache.get(componentId);\n if (cached) return Promise.resolve(cached);\n return coalesce(inflightWinners, componentId, async (): Promise<AssignResult | null> => {\n try {\n const params = new URLSearchParams({ componentId });\n for (const v of variantIds ?? []) params.append('variantIds[]', v);\n const res = await fetch(`${baseUrl}/winner?${params.toString()}`, {\n headers: authHeaders,\n });\n if (!res.ok) return variantIds?.[0] ? { variantId: variantIds[0], assignmentTtlMs: 0 } : null;\n const body = (await res.json()) as { variantId: string };\n const result: AssignResult = { variantId: body.variantId, assignmentTtlMs: 0 };\n winnerCache.set(componentId, result);\n return result;\n } catch {\n return variantIds?.[0] ? { variantId: variantIds[0], assignmentTtlMs: 0 } : null;\n }\n });\n },\n decide: () => Promise.resolve(null),\n getSlotResult: () => null,\n getPersona: () => null,\n getGraph: () => ({ pageNodes: [], capturedAt: 0 }),\n dispose: () => undefined,\n destroy: () => undefined,\n };\n\n const proxy: SentientClient = {\n track: (e) => inner.track(e),\n // Cast: a single arrow can't structurally satisfy the overloaded member;\n // the passthrough forwards both call shapes untouched.\n goal: ((n: string, m?: Record<string, unknown>, w?: number, s?: number) => inner.goal(n, m, w, s)) as SentientClient['goal'],\n componentGoal: (c, g, o) => inner.componentGoal(c, g, o),\n identify: (u) => inner.identify(u),\n getAssignment: (c, s) => inner.getAssignment(c, s),\n assign: (c, v, a, av) => inner.assign(c, v, a, av),\n decide: (i) => inner.decide(i),\n getSlotResult: (s) => inner.getSlotResult(s),\n getPersona: () => inner.getPersona(),\n fetchWeights: () => inner.fetchWeights(),\n getGraph: () => inner.getGraph(),\n dispose: () => inner.dispose(),\n destroy: () => inner.destroy(),\n };\n\n function setInner(fullClient: SentientClient) {\n inner = fullClient;\n }\n\n return { proxy, setInner };\n}\n\n/**\n * Shares one promise among concurrent calls with the same key — assign() and\n * decide() both use this so N same-tick requests (several mounted slots\n * sharing a component id; per-slot lazy decides) cost one roundtrip. The map\n * entry lives exactly as long as the request is in flight: a settled result\n * must NOT serve later calls (a sequential re-request is a fresh decision —\n * caching lives elsewhere), and a failed one must not wedge the key. No\n * `.finally()` — that's ES2018 and this file ships in the es2017 snippet\n * bundle (the SNIP-5 lesson).\n */\nfunction coalesce<T>(inflight: Map<string, Promise<T>>, key: string, run: () => Promise<T>): Promise<T> {\n const hit = inflight.get(key);\n if (hit) return hit;\n const request = (async (): Promise<T> => {\n try {\n return await run();\n } finally {\n inflight.delete(key);\n }\n })();\n inflight.set(key, request);\n return request;\n}\n\n/**\n * Initializes the Sentient client. Returns a no-op client during SSR.\n */\nexport function init(config: SentientConfig): SentientClient {\n if (typeof window === 'undefined') {\n return SSR_CLIENT;\n }\n\n // `|| 'local'`: keyless clients register under the 'local' fallback key\n // below, and `_lastApiKey = ''` is falsy — so a no-arg grantConsent() after\n // a keyless init() warned \"called before init()\" even though init() DID run,\n // instead of resolving that entry (and its blocked-upgrade explanation).\n _lastApiKey = config.apiKey || 'local';\n\n // A re-init for the same key (HMR, consent toggle, provider remount) supersedes\n // the prior client. Dispose it first so its queue's setInterval and\n // visibilitychange/pagehide listeners don't leak — the map only ever held its\n // config, so without this the old client kept flushing forever.\n const prevEntry = _clients.get(config.apiKey || 'local');\n if (prevEntry?.dispose) {\n try {\n prevEntry.dispose();\n } catch {\n /* teardown must never throw on re-init */\n }\n }\n\n // DNT/GPC (a global opt-out) or an explicit `consent: false` must be evaluated\n // BEFORE the local-mode branch: createLocalModeClient() calls initSession()\n // unconditionally, so a gated visitor would otherwise be issued the 365-day\n // `_snt_uid` identity cookie in keyless/local mode (audit P2). DNT/GPC also\n // gates tracking off even when the site passes `consent: true`, and blocks\n // `grantConsent()` from upgrading.\n const dntBlocked = config.respectDoNotTrack !== false && isDoNotTrackEnabled();\n const gated = config.consent === false || dntBlocked;\n\n // Keyless local mode. `localMode: true` forces the local engine (documented\n // escape hatch); 'auto' (default) engages it only when no valid key is\n // present. In production builds `@sentientui/core/local` resolves to a stub\n // and this degrades to a no-op client + one console.error per page load\n // (createLocalModeClient handles that), so no NODE_ENV check is needed here.\n const keyValid = typeof config.apiKey === 'string' && config.apiKey.startsWith('pk_');\n if (config.localMode === true || (!keyValid && config.localMode !== false)) {\n // One registration for both arms (they used to duplicate this set call).\n // upgrade stays null — there is no hosted client to swap in — but the\n // reason lets grantConsent() explain that instead of no-oping silently.\n _clients.set(config.apiKey || 'local', {\n config,\n upgrade: null,\n upgradeBlockedReason:\n '[sentient] grantConsent(): this client is keyless/local — there is no hosted client to upgrade to. Configure a pk_ API key to enable tracking.',\n });\n // A gated visitor must never get the identity cookie. Local mode has no\n // server to serve a statistical winner from, so return a plain no-op.\n if (gated) return SSR_CLIENT;\n return createLocalModeClient(config);\n }\n\n if (gated) {\n if (!config.apiKey || !config.apiKey.startsWith('pk_')) {\n if (config.preConsentBehavior === 'statistical_winner') {\n console.warn('[sentient] init() called with an invalid apiKey — expected a pk_ public key. SDK disabled.');\n }\n // Registered under the same 'local' fallback key the local branch uses:\n // `config.apiKey` here can be '', and a ''-keyed entry was unreachable\n // by a no-arg grantConsent() (falsy `_lastApiKey`), which then wrongly\n // warned \"called before init()\".\n _clients.set(config.apiKey || 'local', {\n config,\n upgrade: null,\n upgradeBlockedReason:\n '[sentient] grantConsent(): the client was initialized with an invalid apiKey (expected a pk_ public key) — consent cannot enable tracking.',\n });\n return SSR_CLIENT;\n }\n // Every gated client gets an upgradeable proxy, not just the winner-serving\n // one — otherwise grantConsent() is silently dead for the 'control' default\n // and the site has to reload to start tracking. Control mode still makes no\n // request; the proxy only exists so consent can swap the inner client.\n const { proxy, setInner } = createPreConsentProxy(config);\n // Under DNT the read-only winner still serves, but consent can never\n // upgrade it to tracking — so drop the upgrade hook.\n _clients.set(config.apiKey, { config, upgrade: dntBlocked ? null : setInner });\n return proxy;\n }\n\n if (!config.apiKey || !config.apiKey.startsWith('pk_')) {\n console.warn('[sentient] init() called with an invalid apiKey — expected a pk_ public key. SDK disabled.');\n return SSR_CLIENT;\n }\n\n if (config.ingestUrl === '') {\n console.warn('[sentient] init() called with an empty ingestUrl. SDK disabled.');\n return SSR_CLIENT;\n }\n\n const resolvedIngestUrl = config.ingestUrl ?? DEFAULT_INGEST_URL;\n\n const sessionStart = Date.now();\n const session = initSession({ ssrSessionId: config.ssrSessionId, apiKey: config.apiKey });\n const assignmentCache = createAssignmentCache(undefined, config.apiKey);\n const eventQueue = createEventQueue({ ingestUrl: resolvedIngestUrl, apiKey: config.apiKey });\n const baseUrl = deriveBaseUrl(resolvedIngestUrl);\n\n const authHeaders = {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${config.apiKey}`,\n } as const;\n\n // Conversions get the same durable transport the event queue has always had:\n // retry with backoff, a cross-reload bucket, dedupe on the server's goalId.\n // One warning per distinct drop status per page load (see onDrop below).\n const warnedDropStatuses = new Set<number>();\n const goalQueue: GoalQueue = createGoalQueue({\n url: `${baseUrl}/goals`,\n apiKey: config.apiKey,\n headers: authHeaders,\n onDrop: (goal, status) => {\n // NOT debug-gated. CONTRACTS §7 says a dropped goal is reported to the\n // developer and never swallowed, but this returned early unless debug was\n // on — so in production a rate-limited or misconfigured project lost every\n // conversion with no signal anywhere. Warn once per (status, page load):\n // enough to be discoverable in a console or an error reporter, quiet\n // enough that a broken integration cannot flood the page.\n if (!config.debug) {\n if (warnedDropStatuses.has(status)) return;\n warnedDropStatuses.add(status);\n }\n console.warn(\n `[sentient] goal dropped (HTTP ${status}) — this will not be retried. ` +\n (status === 400\n ? 'The session was not found: call init() and let the session upsert complete before firing goals.'\n : status === 401 || status === 403\n ? 'Check the API key and that this origin is on the project allowlist.'\n : 'See the response status for the cause.'),\n goal,\n );\n },\n });\n\n const deviceClass = detectDeviceClass(navigator.userAgent ?? '');\n // No window guard here: init() already returned SSR_CLIENT at the top when\n // window is undefined, so the old `typeof window` ternary was dead code.\n const appOrigin = window.location.origin;\n const trafficSource = detectTrafficSource(document.referrer ?? '', appOrigin);\n const sessionSegment =\n config.sessionSegment ?? `${deviceClass}:${trafficSource}`;\n const inflightAssigns = new Map<string, Promise<AssignResult | null>>();\n // Mirrors inflightAssigns for decide(): per-slot lazy-decide patterns (see\n // local-mode's merge comment — one decide({ slots: [decl] }) per mounted\n // slot, all in the same tick) otherwise issue N roundtrips and N snapshot\n // rewrites for one page. Keyed by the full request payload, never just \"a\n // decide is running\": coalescing {slots:[a]} with {slots:[b]} would hand\n // slot b's caller an outcome that never decided b.\n const inflightDecides = new Map<string, Promise<DecideOutcome | null>>();\n\n // --- Adaptive-slot state (decide) ---\n // Results served for this session, keyed by slot id. Written by decide();\n // read by getSlotResult() (Task 3.3) and componentGoal's slot fallback.\n const slotStore = new Map<string, SlotResult>();\n let personaState: { persona: string; confidence: number } | null = null;\n\n // On decide failure every declared slot must still resolve — to its baseline.\n // Never overwrite a previously served result.\n const seedSlotBaselines = (decls: SlotDeclInput[]): void => {\n for (const d of decls) {\n if (!slotStore.has(d.id)) slotStore.set(d.id, baselineResultFor(d));\n }\n };\n\n // Seed slot/persona state. Priority: explicit SSR seeds → snapshot.\n if (config.initialSlots) {\n for (const [slotId, result] of Object.entries(config.initialSlots)) {\n slotStore.set(slotId, result);\n }\n }\n const seedSnapshot = readSnapshot(config.apiKey);\n if (seedSnapshot) {\n for (const [slotId, result] of Object.entries(seedSnapshot.slots)) {\n if (!slotStore.has(slotId)) slotStore.set(slotId, result);\n }\n }\n\n // Band-only persona sources (html attrs, snapshot) become a band-consistent\n // numeric confidence so confidenceBand(confidence) always equals the band.\n const BAND_CONFIDENCE: Record<string, number> = { low: 0.15, medium: 0.5, high: 0.85 };\n if (config.initialPersona) {\n personaState = { ...config.initialPersona };\n } else {\n // Single-writer rule: the inline pre-paint script owns the <html>\n // attributes. The client ADOPTS them as truth and never rewrites them\n // mid-session (next visit's script picks up the new snapshot instead).\n const ds = document.documentElement.dataset;\n if (ds.sentientPersona) {\n personaState = {\n persona: ds.sentientPersona,\n confidence: BAND_CONFIDENCE[ds.sentientConfidence ?? 'low'] ?? 0.15,\n };\n } else if (seedSnapshot) {\n personaState = {\n persona: seedSnapshot.persona,\n confidence: BAND_CONFIDENCE[seedSnapshot.band] ?? 0.15,\n };\n }\n }\n\n // Seed SSR-preloaded assignments into the local cache so assign() finds a\n // cache hit immediately — no network call, no variant flash on hydration.\n if (config.initialAssignments) {\n for (const [componentId, variantId] of Object.entries(config.initialAssignments)) {\n assignmentCache.set(componentId, sessionSegment, {\n variantId,\n assignedAt: Date.now(),\n segment: sessionSegment,\n confidence: 1,\n });\n }\n }\n\n // Upsert session metadata once on init. assign() awaits this promise so\n // the server isn't asked to assign for a session row that doesn't exist yet.\n let sessionReady: Promise<void> = Promise.resolve();\n\n const sessionId = session.getSessionId();\n if (sessionId) {\n const referrerDomain = referrerDomainFromReferer(document.referrer ?? '');\n const sessionBody = {\n sessionId,\n deviceClass,\n trafficSource,\n referrerDomain,\n utmParams: readUtmParams(),\n timeOfDay: detectTimeOfDay(new Date()),\n dayOfWeek: ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'][new Date().getDay()],\n ephemeral: session.isEphemeral(),\n // Likely-automation hint: navigator.webdriver (set under automation\n // control) or a known agent token in the UA. Probabilistic — used for\n // metrics + bandit exclusion server-side, never to change what's served.\n automation:\n (typeof navigator !== 'undefined' && navigator.webdriver === true) ||\n uaTokenMatch(navigator.userAgent ?? ''),\n ...(config.userId ? { userId: config.userId } : {}),\n ...(config.persona ? { persona: config.persona } : {}),\n ...(config.country ? { country: config.country } : {}),\n };\n // The session row is a PRECONDITION for every conversion: /v1/goals answers\n // 400 session_not_found without it, and the durable queue classifies a 4xx\n // as terminal — so a session upsert that fails silently turns every later\n // conversion into a permanent drop. That is not hypothetical: /v1/sessions\n // carries the same per-IP limiter as /v1/goals, so under shared egress\n // (offices, mobile carriers, corporate NAT) the SESSION call 429s first and\n // the goals that follow are dropped for good. Retry it, so a transient\n // failure costs a moment rather than the visit's whole conversion history.\n const upsertSession = async (): Promise<undefined> => {\n for (let attempt = 0; ; attempt++) {\n try {\n const res = await fetch(`${baseUrl}/sessions`, {\n method: 'POST',\n keepalive: true,\n body: JSON.stringify(sessionBody),\n headers: authHeaders,\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 return undefined; // terminal: retrying a quota will not clear it\n }\n if (res.ok || classifyResponse(res) === 'dropped') return undefined;\n } catch {\n /* network failure — same retry path as a 5xx */\n }\n if (attempt >= SESSION_UPSERT_RETRIES) {\n // Say so once: from here every conversion this visit will 400, and\n // that used to be entirely silent.\n console.warn(\n '[SentientUI] Could not register the session after retries. Conversions in this visit may not be recorded.',\n );\n return undefined;\n }\n await new Promise((r) => setTimeout(r, backoffDelayMs(attempt + 1)));\n }\n };\n try {\n sessionReady = upsertSession();\n } catch {\n /* never throw on init */\n }\n }\n\n if (config.debug) {\n console.log('[sentient] initialized', { context: config.context });\n (\n window as unknown as {\n __sentient?: {\n client: SentientClient;\n queue: EventQueue;\n };\n }\n ).__sentient = {\n client: null as unknown as SentientClient,\n queue: eventQueue,\n };\n }\n\n // One user action must record ONE session-level conversion per goal name.\n // Nested components each fire their declared goal on the same click (every\n // <Adaptive>/hook path calls componentGoal() AND goal()), so a hero nested\n // inside a CTA wrapper wrote two goal_events rows for one click: harmless for\n // a weight-1.0 goal (close-out clamps at 1) but a 0.3-weight step summed to\n // 0.6, and the Goals page counts Hits as COUNT(*) either way.\n //\n // The scope is one event dispatch, not one session and no longer one task:\n // see createActionLatch. A session-wide latch would swallow genuine repeat\n // conversions (two purchases in one visit are two conversions), and a\n // time-boxed one did exactly that whenever the box outlived the action.\n // Calls carrying distinct externalIds are never collapsed — those are, by\n // definition, distinct orders.\n const firedThisAction = createActionLatch();\n\n // Set once tracking starts; dispose() and destroy() call it so a replaced\n // client stops watching history instead of emitting forever. The flag records\n // teardown for the delivery-marking below, which runs on a later microtask.\n let stopPageviews: (() => void) | null = null;\n let pageviewsTornDown = false;\n\n const client: SentientClient = {\n goal(name: string, metadataOrOpts: Record<string, unknown> = {}, weight = 1.0, stepIndex = 0) {\n const sid = session.getSessionId();\n if (!sid) return;\n const opts: GoalOptions = isGoalOptions(metadataOrOpts)\n ? (metadataOrOpts as GoalOptions)\n : { metadata: metadataOrOpts };\n // stepIndex and weight are part of the key: funnel steps share a goal\n // name and differ by stepIndex, so collapsing on name alone dropped a\n // step fired in the same handler. Only IDENTICAL calls are one action.\n //\n // value and currency key the payload SEPARATELY (the latch's valueKey),\n // not as more segments of the flat key, and for a costlier reason: they\n // are the money. Flattened out of the key entirely, a $50 order and a\n // $70 order landing in one window collapsed into a single $50 record —\n // the client half of CONTRACTS §1 \"two orders are worth two orders\",\n // which the server already honours (migration 119 records the repeat if\n // it arrives; this is what stopped it arriving). But flattened INTO the\n // key, a valued inner component nested in a valueless wrapper made two\n // keys out of one click — two rows for one order. So the latch compares\n // values only between valued fires ($50 vs $70 stays two records) and\n // lets a valued record absorb a valueless re-fire of the same action\n // (see createActionLatch for the one asymmetric case).\n //\n // NOT metadata: every nested <Adaptive>/hook path stamps its own\n // componentId and variantId in there, so keying on it would make the\n // duplicate this latch exists to collapse look distinct again.\n const actionKey = [\n name,\n opts.externalId ?? '',\n opts.stepIndex ?? stepIndex,\n opts.weight ?? weight,\n ].join('\\0');\n const valueKey = opts.value !== undefined ? `${opts.value}\\0${opts.currency ?? ''}` : null;\n if (firedThisAction.firedBefore(actionKey, valueKey)) {\n if (config.debug) {\n console.log(`[sentient] goal(\"${name}\") already recorded for this action — not sent twice`);\n }\n return;\n }\n const goalId = generateEventId();\n // undefined values vanish at JSON.stringify time, so optional fields\n // need no conditional assembly.\n const body = {\n sessionId: sid,\n name,\n metadata: opts.metadata ?? {},\n weight: opts.weight ?? weight,\n stepIndex: opts.stepIndex ?? stepIndex,\n goalId,\n value: opts.value,\n currency: opts.currency,\n externalId: opts.externalId,\n };\n if (config.debug) {\n console.log('[sentient] goal', body);\n }\n // Serialize once, here: the queued copy must replay byte-identically\n // (same goalId) so a retry dedupes server-side instead of double-counting.\n const payload = { id: goalId, body: JSON.stringify(body) };\n sessionReady.then(() => goalQueue.send(payload));\n },\n\n componentGoal(componentId, goalType, opts) {\n const sid = session.getSessionId();\n if (!sid) return;\n // Variant experiments resolve from the assignment cache; adaptive slots\n // (useAdaptiveTokens / AdaptiveGroup) resolve from the slot state, using\n // the canonical arm string as the attributed variantId.\n const assignment = assignmentCache.get(componentId, sessionSegment);\n const slotResult = assignment ? null : slotStore.get(componentId) ?? null;\n if (!assignment && slotResult === null) {\n if (config.debug) {\n console.warn(\n `[sentient] componentGoal(\"${componentId}\"): no assignment or slot decision yet — render its <Adaptive>/adaptive hook or call assign()/decide() before recording a goal.`,\n );\n }\n return;\n }\n const attributedVariantId = assignment ? assignment.variantId : armOfResult(slotResult!);\n const fullEvent: SentientEvent = {\n id: generateEventId(),\n sessionId: sid,\n projectId: config.apiKey,\n componentId,\n variantId: attributedVariantId,\n eventType: 'goal_achieved',\n goalType,\n // undefined goalValue/currency vanish at JSON.stringify time.\n payload: {\n reward: opts?.reward ?? 1,\n goalValue: opts?.value,\n currency: opts?.currency,\n ...(opts?.metadata ?? {}),\n },\n timestamp: Date.now(),\n timeInSession: Date.now() - sessionStart,\n path: currentPath(),\n };\n if (config.debug) {\n console.log('[sentient] componentGoal', fullEvent);\n }\n sessionReady.then(() => eventQueue.push(fullEvent));\n },\n\n identify(userId) {\n const sid = session.getSessionId();\n if (!sid) return;\n sessionReady.then(() => {\n fetch(`${baseUrl}/sessions`, {\n method: 'POST',\n keepalive: true,\n body: JSON.stringify({ sessionId: sid, userId, ephemeral: session.isEphemeral() }),\n headers: authHeaders,\n }).catch(() => undefined);\n });\n },\n\n track(event) {\n const sessionId = session.getSessionId();\n if (!sessionId) return;\n\n const fullEvent: SentientEvent = {\n // `path` first so an explicit event.path from the caller wins over the\n // ambient one — a server-side or replayed event knows its page better\n // than location does.\n path: currentPath(),\n ...event,\n id: generateEventId(),\n sessionId,\n timestamp: Date.now(),\n timeInSession: Date.now() - sessionStart,\n };\n\n if (config.debug) {\n console.log('[sentient] track', fullEvent);\n }\n\n sessionReady.then(() => eventQueue.push(fullEvent));\n },\n\n getAssignment(componentId, segment) {\n return assignmentCache.get(componentId, segment);\n },\n\n async assign(componentId, variantIds, agentData?, agentDataByVariant?) {\n const sid = session.getSessionId();\n if (!sid) return null;\n\n const cached = assignmentCache.get(componentId, sessionSegment);\n // When variantIds are provided (A/B code variant), a cache hit is always final.\n // When variantIds are absent (managed text component), only hit the cache if content\n // is present — a seed from initialAssignments has no content and must still fetch.\n if (cached && (variantIds?.length || cached.content !== undefined)) {\n // Surface the entry's remaining TTL (server-provided when set) instead of\n // a hardcoded 0, so callers can reason about when a re-assign is due.\n const remainingTtlMs =\n cached.ttlMs && cached.ttlMs > 0\n ? Math.max(0, cached.assignedAt + cached.ttlMs - Date.now())\n : 0;\n return { variantId: cached.variantId, assignmentTtlMs: remainingTtlMs, content: cached.content };\n }\n\n // Coalesce concurrent assigns for the same component (e.g. several\n // mounted slots sharing one id) into a single network request.\n return coalesce(inflightAssigns, componentId, async () => {\n await sessionReady;\n try {\n const body: Record<string, unknown> = { sessionId: sid, componentId, variantIds };\n if (agentDataByVariant !== undefined) body.agentDataByVariant = agentDataByVariant;\n else if (agentData !== undefined) body.agentData = agentData;\n const res = await fetch(`${baseUrl}/assign`, {\n method: 'POST',\n body: JSON.stringify(body),\n headers: authHeaders,\n });\n if (!res.ok) return null;\n const result = (await res.json()) as AssignResult;\n assignmentCache.set(componentId, sessionSegment, {\n variantId: result.variantId,\n assignedAt: Date.now(),\n segment: sessionSegment,\n confidence: 1,\n content: result.content,\n // Honor the server's TTL as this entry's expiry; omit when absent/0\n // so the cache falls back to its default (DEFAULT_TTL_MS).\n ...(result.assignmentTtlMs && result.assignmentTtlMs > 0\n ? { ttlMs: result.assignmentTtlMs }\n : {}),\n });\n return result;\n } catch {\n return null;\n }\n });\n },\n\n async decide(input) {\n const sid = session.getSessionId();\n if (!sid) return null;\n const declared = input.slots ?? [];\n\n const body: Record<string, unknown> = { sessionId: sid };\n if (input.sections && input.sections.length > 0) {\n body.sections = input.sections.map((id) => ({ id }));\n }\n body.components = input.components ?? [];\n if (declared.length > 0) body.slots = declared.map(toWireSlot);\n if (input.slotsFrom === 'registry') body.slotsFrom = 'registry';\n if (input.v) body.v = input.v;\n // Declared persona rides on decide too: SSR-first flows can race the\n // session upsert, and the decide-body value wins for this decision.\n if (config.persona) body.persona = config.persona;\n\n // Coalesce concurrent IDENTICAL decides into one request + one snapshot\n // write, keyed by the serialized wire payload (also reused as the fetch\n // body). Never key on just \"a decide is running\": coalescing {slots:[a]}\n // with {slots:[b]} would hand slot b's caller an outcome that never\n // decided b. The wire projection is a safe key even though toWireSlot\n // strips SDK-only decl fields — the baselines synthesized for omitted\n // slots below go through baselineResultFor, which projects with the\n // same toWireSlot, so identical payloads imply identical outcomes.\n const decideKey = JSON.stringify(body);\n return coalesce(inflightDecides, decideKey, async () => {\n await sessionReady;\n try {\n const res = await fetch(`${baseUrl}/decide`, {\n method: 'POST',\n body: decideKey,\n headers: authHeaders,\n });\n if (!res.ok) {\n seedSlotBaselines(declared);\n return null;\n }\n const data = (await res.json()) as {\n layoutOrder?: string[] | null;\n assignments?: Record<string, string>;\n slots?: Record<string, SlotResult>;\n slotConfig?: Record<string, SlotConfigEntry>;\n goals?: GoalDefinition[];\n sectionMap?: SectionMapEntry[];\n palette?: import('./blocks.js').SitePalette;\n persona?: string;\n confidence?: number;\n };\n\n const slots: Record<string, SlotResult> = {};\n for (const d of declared) {\n // `data.slots === undefined` means the server predates the slots\n // contract: serve the declared baseline everywhere, do NOT retry.\n // (Distinct from `slots: {}`, which also falls back per-slot.)\n const served = data.slots?.[d.id];\n if (served !== undefined) {\n slots[d.id] = served;\n slotStore.set(d.id, served);\n continue;\n }\n // Slot omitted from the response → synthesize a baseline for the\n // RETURN value, but apply the same never-overwrite rule the failure\n // path (seedSlotBaselines) has always had. This success path used\n // to write unconditionally, so a partial response — or a pre-slots\n // server — clobbered SSR-seeded and previously-served results with\n // synthetic baselines.\n const prior = slotStore.get(d.id);\n if (prior !== undefined) {\n slots[d.id] = prior;\n } else {\n const baseline = baselineResultFor(d);\n slots[d.id] = baseline;\n slotStore.set(d.id, baseline);\n }\n }\n // Registry mode: the server returns slots the request never declared.\n // Take them verbatim (classic mode returns only declared slots, so this\n // union is a no-op there — back-compatible). These are real served\n // results, so they may overwrite the store, unlike the baselines above.\n if (data.slots) {\n for (const [slotId, result] of Object.entries(data.slots)) {\n if (!(slotId in slots)) {\n slots[slotId] = result;\n slotStore.set(slotId, result);\n }\n }\n }\n // Only overwrite persona when the response actually carries one, and\n // never downgrade a known persona to 'unknown' — a decide that omits\n // persona (or returns 'unknown') must not clobber a good SSR/snapshot/\n // initialPersona value, and must not persist that regression below.\n const known = personaState != null && personaState.persona !== 'unknown';\n if (data.persona && !(data.persona === 'unknown' && known)) {\n personaState = { persona: data.persona, confidence: data.confidence ?? 0 };\n } else if (!personaState) {\n personaState = { persona: 'unknown', confidence: 0 };\n }\n\n // Seed component assignments so <Adaptive>/assign() agree with this\n // decide (same shape as the initialAssignments seed above).\n for (const [componentId, variantId] of Object.entries(data.assignments ?? {})) {\n assignmentCache.set(componentId, sessionSegment, {\n variantId,\n assignedAt: Date.now(),\n segment: sessionSegment,\n confidence: 1,\n });\n }\n\n // Persist for the next visit's pre-paint (SPA cache-first pattern).\n writeSnapshot(config.apiKey, {\n v: 1,\n persona: personaState.persona,\n band: confidenceBand(personaState.confidence),\n slots: Object.fromEntries(slotStore),\n layoutOrder: data.layoutOrder ?? null,\n savedAt: Date.now(),\n ...(data.slotConfig ? { slotConfig: data.slotConfig } : {}),\n ...(data.palette ? { palette: data.palette } : {}),\n });\n\n return {\n layoutOrder: data.layoutOrder ?? null,\n assignments: data.assignments ?? {},\n slots,\n persona: personaState.persona,\n confidence: personaState.confidence,\n ...(data.slotConfig ? { slotConfig: data.slotConfig } : {}),\n ...(data.goals ? { goals: data.goals } : {}),\n ...(data.sectionMap ? { sectionMap: data.sectionMap } : {}),\n ...(data.palette ? { palette: data.palette } : {}),\n };\n } catch {\n seedSlotBaselines(declared);\n return null;\n }\n });\n },\n\n getSlotResult(slotId) {\n return slotStore.get(slotId) ?? null;\n },\n\n getPersona() {\n if (!personaState) return null;\n return {\n persona: personaState.persona,\n confidence: personaState.confidence,\n band: confidenceBand(personaState.confidence),\n };\n },\n\n async fetchWeights() {\n try {\n const res = await fetch(`${baseUrl}/weights`, { headers: authHeaders });\n if (!res.ok) return [];\n const data = (await res.json()) as { components: ComponentWeightEntry[] };\n return data.components ?? [];\n } catch {\n return [];\n }\n },\n\n getGraph() {\n return { pageNodes: [], capturedAt: 0 };\n },\n\n dispose() {\n // Stops the flush timer and unload listeners (with a final flush) but\n // leaves identity, snapshot, and retry buckets for the next client.\n stopPageviews?.();\n pageviewsTornDown = true;\n eventQueue.destroy();\n goalQueue.destroy();\n // Drop the registry entry so a later re-init doesn't try to dispose an\n // already-torn-down client (and so the map doesn't pin this closure).\n if (_clients.get(config.apiKey)?.dispose === client.dispose) {\n _clients.delete(config.apiKey);\n }\n if (config.debug) {\n console.log('[sentient] disposed');\n }\n },\n\n destroy() {\n stopPageviews?.();\n pageviewsTornDown = true;\n eventQueue.destroy();\n goalQueue.destroy();\n session.destroy();\n // The assignment cache persists in localStorage (`_snt_asgn_*`) with a\n // 30-minute default TTL — left in place, a revoked visitor returning\n // within that window was handed their previous personalized variants\n // back, so forget-me wasn't total.\n assignmentCache.clear();\n if (_clients.get(config.apiKey)?.dispose === client.dispose) {\n _clients.delete(config.apiKey);\n }\n // Forget-me must be total: a surviving decision snapshot would\n // re-personalize the next visit via the pre-paint script, and a\n // persisted retry bucket would re-send events for the deleted identity.\n try {\n localStorage.removeItem(SNAPSHOT_STORAGE_KEY_PREFIX + config.apiKey);\n localStorage.removeItem(retryStorageKey(config.apiKey));\n localStorage.removeItem(goalRetryStorageKey(config.apiKey));\n } catch {\n /* storage unavailable — nothing persisted to remove */\n }\n if (config.debug) {\n console.log('[sentient] destroyed');\n }\n },\n };\n\n _clients.set(config.apiKey, { config, upgrade: null, dispose: client.dispose });\n\n stopPageviews = startPageviewTracking(client, config.apiKey, (key) => {\n // track() defers its enqueue on sessionReady; chaining after it means this\n // runs once the push has happened. If the client was torn down first, the\n // event went into a destroyed queue and never ships — leave the page\n // unmarked so the replacement client's emit is the one that counts.\n void sessionReady.then(() => {\n if (!pageviewsTornDown) emittedPages.add(key);\n });\n });\n\n if (config.debug) {\n const win = window as unknown as { __sentient?: { client: SentientClient } };\n if (win.__sentient) {\n win.__sentient.client = client;\n }\n }\n\n return client;\n}\n","export type MicroSignalEmitter = (\n signalType: 'rage_click' | 'text_copy' | 'scroll_hesitation' | 'tab_loss',\n extra?: Record<string, unknown>,\n) => void;\n\nexport type MicroSignalType = Parameters<MicroSignalEmitter>[0];\n\n/**\n * Attaches passive behavioral detectors to `node`. Calls `emit` when a signal\n * fires. Each signal type fires at most once per call to this function.\n * Returns a cleanup function that removes all listeners.\n */\nexport function attachMicroSignalDetectors(\n emit: MicroSignalEmitter,\n node: Element,\n variantAssignedAt?: number,\n options?: { tabLoss?: boolean },\n): () => void {\n const cleanups: Array<() => void> = [];\n\n // --- Rage click: 3+ clicks within 500ms ---\n {\n const WINDOW_MS = 500;\n const THRESHOLD = 3;\n let firedOnce = false;\n const timestamps: number[] = [];\n\n const onClick = (): void => {\n if (firedOnce) return;\n const now = Date.now();\n timestamps.push(now);\n while (timestamps.length > 0 && now - timestamps[0]! > WINDOW_MS) {\n timestamps.shift();\n }\n if (timestamps.length >= THRESHOLD) {\n firedOnce = true;\n emit('rage_click');\n }\n };\n\n node.addEventListener('click', onClick);\n cleanups.push(() => node.removeEventListener('click', onClick));\n }\n\n // --- Text copy: copy event within node ---\n {\n let firedOnce = false;\n\n const onCopy = (e: Event): void => {\n if (firedOnce) return;\n if (!(e.target instanceof Node)) return;\n if (!node.contains(e.target) && node !== e.target) return;\n firedOnce = true;\n const sel = typeof window !== 'undefined' ? window.getSelection() : null;\n const selectionLength = sel ? sel.toString().length : 0;\n emit('text_copy', { selectionLength });\n };\n\n document.addEventListener('copy', onCopy);\n cleanups.push(() => document.removeEventListener('copy', onCopy));\n }\n\n // --- Scroll hesitation: scroll stops 3s while component visible ---\n {\n let firedOnce = false;\n let isVisible = false;\n let hesitationTimer: ReturnType<typeof setTimeout> | null = null;\n\n const clearHesitation = (): void => {\n if (hesitationTimer !== null) {\n clearTimeout(hesitationTimer);\n hesitationTimer = null;\n }\n };\n\n const startHesitation = (): void => {\n if (firedOnce || !isVisible) return;\n clearHesitation();\n hesitationTimer = setTimeout(() => {\n if (!firedOnce && isVisible) {\n firedOnce = true;\n emit('scroll_hesitation');\n }\n }, 3000);\n };\n\n const onScroll = (): void => {\n clearHesitation();\n startHesitation();\n };\n\n const ioCallback = (entries: IntersectionObserverEntry[]): void => {\n for (const entry of entries) {\n isVisible = entry.intersectionRatio > 0.3;\n if (!isVisible) clearHesitation();\n else startHesitation();\n }\n };\n const io = new IntersectionObserver(ioCallback, { threshold: [0.3] });\n io.observe(node);\n window.addEventListener('scroll', onScroll, { passive: true });\n\n cleanups.push(() => {\n io.disconnect();\n window.removeEventListener('scroll', onScroll);\n clearHesitation();\n });\n }\n\n // --- Tab loss: tab hidden within 15s of variant_assigned ---\n // Document-level (not node-scoped), so callers that attach detectors to many\n // nodes at once (e.g. the snippet's per-option slot signals) can opt out on all\n // but one node to avoid emitting a duplicate tab_loss per node (audit M5).\n if (options?.tabLoss !== false) {\n let firedOnce = false;\n const assignedAt = variantAssignedAt ?? Date.now();\n\n const onVisibility = (): void => {\n if (firedOnce) return;\n if (document.visibilityState !== 'hidden') return;\n const elapsed = Date.now() - assignedAt;\n if (elapsed < 15_000) {\n firedOnce = true;\n emit('tab_loss', { timeOnPage: elapsed });\n }\n };\n\n document.addEventListener('visibilitychange', onVisibility);\n cleanups.push(() => document.removeEventListener('visibilitychange', onVisibility));\n }\n\n return () => {\n for (const c of cleanups) c();\n };\n}\n","import { classifySection, SEMANTIC_TYPES, type SemanticType } from './classify';\nimport { isDoNotTrackEnabled } from '../index.js';\nimport { attachMicroSignalDetectors } from '../micro-signals.js';\n\n// Shared engagement capture (spec 2026-07-22-persona-signal-capture). Detects\n// semantic sections, registers them via /v1/section-map, and records per-section\n// dwell/scroll via IntersectionObserver — emitting the same 'dwell' events the\n// persona pipeline consumes. Used by the React provider (default on) and the\n// no-code snippet. Defense-in-depth: checks DNT internally even though callers\n// gate on consent/DNT too; a missing IntersectionObserver → no-op.\n\ntype CaptureClient = {\n track(event: { projectId: string; componentId: string; eventType: string; payload: Record<string, unknown> }): void;\n};\n\nexport type EngagementCaptureOptions = {\n apiKey: string;\n /** API base, no trailing slash. Defaults to the hosted API. */\n apiBase?: string;\n doc?: Document;\n /**\n * Also attach per-section micro-signal detectors (rage click, text copy,\n * scroll hesitation, tab loss), attributed to the section's `nc-<type>`\n * component. For the no-code snippet, whose pages have no `<Adaptive>`\n * components carrying their own detectors. Default false — the React SDK\n * keeps its per-component detectors and must not double-attach.\n */\n microSignals?: boolean;\n /**\n * Server-served section-map lookup (persona-coverage auto-classification):\n * consulted after explicit `data-sentient-type` markup, before the local\n * heuristic. Return null when the element has no served label.\n */\n typeOf?: (el: Element) => SemanticType | null;\n};\n\nconst SECTION_SELECTOR = 'section, header, footer, nav, main > div, [data-sentient-section]';\n\n/** Bank cadence for visible dwell. Dwell used to leave the page only on\n * visibilitychange/pagehide, and in production that path delivered for ~5-8%\n * of sessions (Bodyshop audit 2026-08-30): a visitor who reads and closes the\n * tab races the unload pipeline, and mobile browsers can kill a page with no\n * lifecycle event at all. The heartbeat caps the loss at one interval. */\nconst HEARTBEAT_MS = 20_000;\n\n/**\n * Pick the elements to observe. Two rules, in order:\n * 1. A candidate that CONTAINS two or more other candidates is a layout\n * wrapper, not a section — drop it. Pages built from bare divs match\n * `main > div` with their page-wide content wrapper; keeping that outer\n * match swallowed every real <section> inside it, collapsing the whole page\n * into one nc-generic component whose intersectionRatio could never exceed\n * viewport-height / page-height (a constant ~0.05 scroll_depth on the\n * audited site). A candidate with exactly one nested candidate (header >\n * nav) is NOT a wrapper — rule 2 keeps the outer one, as before.\n * 2. Of what remains, skip a section nested inside another kept section\n * (avoid double count).\n */\nfunction selectSections(doc: Document): Element[] {\n const candidates = Array.from(doc.querySelectorAll(SECTION_SELECTOR));\n const kept = candidates.filter(\n (el) => candidates.filter((c) => c !== el && el.contains(c)).length < 2,\n );\n return kept.filter((el) => !kept.some((k) => k !== el && k.contains(el)));\n}\n\nfunction registerSections(\n apiKey: string,\n apiBase: string,\n pageUrl: string,\n sections: Array<{ componentId: string; semanticType: SemanticType; source: 'markup' | 'auto' }>,\n): void {\n try {\n void fetch(`${apiBase}/v1/section-map`, {\n method: 'POST',\n keepalive: true,\n headers: { 'content-type': 'application/json', authorization: `Bearer ${apiKey}` },\n body: JSON.stringify({ pageUrl, sections }),\n }).catch(() => undefined);\n } catch {\n /* fail-safe */\n }\n}\n\nconst NOOP = (): void => undefined;\n\nexport function startEngagementCapture(\n client: CaptureClient,\n opts: EngagementCaptureOptions,\n): () => void {\n const doc = opts.doc ?? (typeof document !== 'undefined' ? document : undefined);\n if (!doc || typeof IntersectionObserver === 'undefined') return NOOP;\n if (isDoNotTrackEnabled()) return NOOP;\n // Keyless zero-network contract: capture exists to feed the hosted persona\n // pipeline — with no api key there is nothing to feed, and the section-map\n // registration fetch must never fire. Same validity rule as init() and the\n // graph entry: this used to check truthiness only, so an invalid non-`pk_`\n // (typo'd) key still fired /v1/section-map registration and dwell events\n // into a client that discards everything.\n if (!opts.apiKey || !opts.apiKey.startsWith('pk_')) return NOOP;\n // Normalize so both a ROOT base (`https://api.sentient-ui.com`) and a\n // `/v1`-suffixed base resolve to exactly one `/v1/section-map` — some callers\n // pass the versioned base, which would otherwise produce `/v1/v1/section-map`\n // (a silent 404). Strip trailing slashes, then a single trailing `/v1`.\n const apiBase = (opts.apiBase ?? 'https://api.sentient-ui.com')\n .replace(/\\/+$/, '')\n .replace(/\\/v1$/, '');\n\n const els = selectSections(doc);\n if (els.length === 0) return NOOP;\n\n // Collapse to one component per semantic type per page (the matrix aggregates\n // by semantic type anyway). Per-element precedence: explicit data-sentient-type\n // markup → served section map (opts.typeOf) → local heuristic.\n const componentOf = new Map<Element, string>();\n const types = new Map<string, SemanticType>();\n const sources = new Map<string, 'markup' | 'auto'>();\n for (const el of els) {\n const explicit = el.getAttribute('data-sentient-type');\n const markup = explicit && (SEMANTIC_TYPES as readonly string[]).includes(explicit)\n ? (explicit as SemanticType)\n : null;\n const type = markup ?? opts.typeOf?.(el) ?? classifySection(el);\n const componentId = `nc-${type}`;\n componentOf.set(el, componentId);\n types.set(componentId, type);\n // Markup wins if the same collapsed component gets both provenances.\n if (markup) sources.set(componentId, 'markup');\n else if (!sources.has(componentId)) sources.set(componentId, 'auto');\n }\n\n const pageUrl = (doc.defaultView ?? (typeof window !== 'undefined' ? window : undefined))?.location?.pathname ?? '/';\n registerSections(opts.apiKey, apiBase, pageUrl, [...types.entries()].map(([componentId, semanticType]) => ({\n componentId, semanticType, source: sources.get(componentId) ?? 'auto',\n })));\n\n // Accumulate visible dwell (ms) + max scroll ratio per component. `intersecting`\n // tracks in-viewport state independently of `enterAt` (the running clock) so a\n // tab-hide can pause the clock and a tab-show can resume it for still-visible\n // sections — IntersectionObserver does not re-fire on visibilitychange.\n const state = new Map<string, { ms: number; scroll: number; enterAt: number | null; intersecting: boolean }>();\n const get = (id: string) => {\n let s = state.get(id);\n if (!s) { s = { ms: 0, scroll: 0, enterAt: null, intersecting: false }; state.set(id, s); }\n return s;\n };\n\n const observer = new IntersectionObserver((entries) => {\n for (const entry of entries) {\n const id = componentOf.get(entry.target);\n if (!id) continue;\n const s = get(id);\n if (entry.isIntersecting) {\n s.intersecting = true;\n s.enterAt = Date.now();\n if (entry.intersectionRatio > s.scroll) s.scroll = entry.intersectionRatio;\n } else {\n s.intersecting = false;\n if (s.enterAt != null) { s.ms += Date.now() - s.enterAt; s.enterAt = null; }\n }\n }\n }, { threshold: [0, 0.25, 0.5, 0.75, 1] });\n for (const el of componentOf.keys()) observer.observe(el);\n\n // Bank accumulated dwell and RESET the accumulators (so a later emit can't\n // double-count) WITHOUT disconnecting — a visitor who hides/re-shows the tab\n // or tab-switches keeps being measured. Pauses the running clock; the tab-show\n // handler restarts it for still-visible sections so hidden time isn't counted.\n const emit = (): void => {\n const now = Date.now();\n for (const [id, s] of state) {\n if (s.enterAt != null) { s.ms += now - s.enterAt; s.enterAt = null; }\n if (s.ms <= 0) continue;\n try {\n client.track({\n projectId: opts.apiKey, // SDK convention: server derives the real project from the key\n componentId: id,\n eventType: 'dwell',\n payload: { dwell_time: Math.round(s.ms), scroll_depth: Number(s.scroll.toFixed(2)) },\n });\n } catch {\n /* fail-safe */\n }\n s.ms = 0;\n }\n };\n\n const onVisibility = (): void => {\n if (doc.hidden) {\n emit(); // bank + pause\n } else {\n const now = Date.now(); // resume the clock for sections still on screen\n for (const s of state.values()) if (s.intersecting) s.enterAt = now;\n }\n };\n // A page can be FROZEN into the bfcache rather than torn down. Timers keep\n // firing on restore, and `intersecting` still holds whatever it held at\n // pagehide — so without this the heartbeat kept banking dwell for sections the\n // visitor had scrolled far past, forever, while the observer that could have\n // corrected them had been disconnected. Freeze the clocks instead, and only\n // tear down for real when the page is genuinely going away.\n let frozen = false;\n const onPageHide = (event?: { persisted?: boolean }): void => {\n emit(); // bank whatever is measured either way\n if (event?.persisted) {\n frozen = true; // bfcache: keep the observer, stop counting\n return;\n }\n try { observer.disconnect(); } catch { /* ignore */ }\n };\n const onPageShow = (event?: { persisted?: boolean }): void => {\n if (!event?.persisted || !frozen) return;\n frozen = false;\n // The observer stayed connected, so it will correct `intersecting` for\n // anything that moved. Restart clocks only for what is on screen NOW.\n const now = Date.now();\n for (const s of state.values()) s.enterAt = s.intersecting && !doc.hidden ? now : null;\n };\n doc.addEventListener('visibilitychange', onVisibility);\n const win = doc.defaultView ?? (typeof window !== 'undefined' ? window : undefined);\n win?.addEventListener('pagehide', onPageHide);\n win?.addEventListener('pageshow', onPageShow);\n\n // See HEARTBEAT_MS: bank visible dwell periodically so a hard close (or a\n // mobile page kill) loses at most one interval instead of the whole visit.\n // Hidden tabs skip the emit — their clock is already paused, and an empty\n // state map makes emit a no-op anyway.\n const heartbeat = setInterval(() => {\n if (doc.hidden || frozen) return;\n emit();\n // emit() pauses every running clock and only the tab-show handler restarts\n // them — here the page never went hidden, so restart the clock ourselves\n // or accumulation silently stops after the first heartbeat.\n const now = Date.now();\n for (const s of state.values()) if (s.intersecting) s.enterAt = now;\n }, HEARTBEAT_MS);\n\n // Per-section micro-signal detectors (opt-in; see EngagementCaptureOptions).\n // Attributed to the section's nc-<type> id with no variant — they feed the\n // persona attention fallback and auto-discovery, never rewards.\n const detectorCleanups: Array<() => void> = [];\n if (opts.microSignals) {\n // tab_loss is a single document-level `visibilitychange` signal, so enabling\n // it on every section detector would emit one tab_loss per nc-<type> section\n // on a single tab-hide — attributing one page-level exit to every section\n // (audit M5). Enable it on only the first section so the exit is recorded\n // once, mirroring the per-option path in slot-signals.ts ({ tabLoss: index === 0 }).\n [...componentOf.entries()].forEach(([el, componentId], i) => {\n detectorCleanups.push(\n attachMicroSignalDetectors((signalType, extra = {}) => {\n try {\n client.track({\n projectId: opts.apiKey,\n componentId,\n eventType: 'micro_signal',\n payload: { signalType, ...extra },\n });\n } catch {\n /* fail-safe */\n }\n }, el, undefined, { tabLoss: i === 0 }),\n );\n });\n }\n\n // Cleanup: bank any remaining dwell, then detach everything (provider unmount\n // / consent re-init must not leak observers or listeners).\n return () => {\n emit();\n clearInterval(heartbeat);\n doc.removeEventListener('visibilitychange', onVisibility);\n win?.removeEventListener('pagehide', onPageHide);\n win?.removeEventListener('pageshow', onPageShow);\n for (const c of detectorCleanups) c();\n try { observer.disconnect(); } catch { /* ignore */ }\n };\n}\n"],"mappings":"4rBAAA,IAAAA,GAAA,GAAAC,EAAAD,GAAA,oBAAAE,EAAA,qBAAAC,EAAA,oBAAAC,EAAA,wBAAAC,EAAA,2BAAAC,IAAA,eAAAC,EAAAP,ICgBO,IAAMQ,EAA0C,CACrD,UAAW,OAAQ,eAAgB,MAAO,WAC1C,MAAO,aAAc,QAAS,aAAc,SAC9C,EAcMC,EAA0C,CAC9C,CAAC,UAAW,gEAAgE,EAC5E,CAAC,MAAO,+CAA+C,EACvD,CAAC,aAAc,uCAAuC,EACtD,CAAC,eAAgB,kFAAkF,EACnG,CAAC,QAAS,yEAAyE,EACnF,CAAC,WAAY,gEAAgE,CAC/E,EAKMC,GAAkD,CACtD,CAAC,UAAW,oJAAoJ,EAChK,CAAC,eAAgB,iHAAiH,EAClI,CAAC,QAAS,mHAAmH,EAC7H,CAAC,aAAc,sHAAsH,CACvI,EAEA,SAASC,GAAYC,EAAqB,CApD1C,IAAAC,EAqDE,IAAMC,EAAIF,EAAG,cAAc,YAAY,EACvC,QAAQC,EAAAC,GAAA,YAAAA,EAAG,cAAH,KAAAD,EAAkB,IAAI,MAAM,EAAG,GAAG,CAC5C,CAOO,SAASE,EAAiBC,EAAyE,CACxG,GAAIA,EAAE,MAAQ,OAASA,EAAE,MAAQ,SAAU,MAAO,CAAE,KAAM,aAAc,SAAU,MAAO,EACzF,IAAMC,EAAM,GAAGD,EAAE,OAAO,IAAIA,EAAE,WAAW,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iB,WAAYD,GAMlC,IAAME,EAAY,YAAY,IAAM,CAClC,GAAIpD,EAAI,QAAU+C,EAAQ,OAC1BH,EAAK,EAIL,IAAMC,EAAM,KAAK,IAAI,EACrB,QAAWL,KAAKH,EAAM,OAAO,EAAOG,EAAE,eAAcA,EAAE,QAAUK,EAClE,EAAG/C,EAAY,EAKTuD,EAAsC,CAAC,EAC7C,OAAItC,EAAK,cAMP,CAAC,GAAGY,EAAY,QAAQ,CAAC,EAAE,QAAQ,CAAC,CAACxB,EAAIgC,CAAW,EAAG,IAAM,CAC3DkB,EAAiB,KACfC,EAA2B,CAACC,EAAYC,EAAQ,CAAC,IAAM,CACrD,GAAI,CACF1C,EAAO,MAAM,CACX,UAAWC,EAAK,OAChB,YAAAoB,EACA,UAAW,eACX,QAASsB,EAAA,CAAE,WAAAF,GAAeC,EAC5B,CAAC,CACH,OAAQ7C,GAAA,CAER,CACF,EAAGR,EAAI,OAAW,CAAE,QAAS,IAAM,CAAE,CAAC,CACxC,CACF,CAAC,EAKI,IAAM,CACXyC,EAAK,EACL,cAAcQ,CAAS,EACvBpD,EAAI,oBAAoB,mBAAoB8C,CAAY,EACxDK,GAAA,MAAAA,EAAK,oBAAoB,WAAYH,GACrCG,GAAA,MAAAA,EAAK,oBAAoB,WAAYD,GACrC,QAAW9C,KAAKiD,EAAkBjD,EAAE,EACpC,GAAI,CAAEqC,EAAS,WAAW,CAAG,OAAQ9B,EAAA,CAAe,CACtD,CACF","names":["index_engagement_exports","__export","SEMANTIC_TYPES","classifyFeatures","classifySection","featuresFromElement","startEngagementCapture","__toCommonJS","SEMANTIC_TYPES","KEYWORDS","CONTENT_PATTERNS","headingText","el","_a","h","classifyFeatures","f","hay","type","re","featuresFromElement","_b","text","classifySection","import_policy","attachMicroSignalDetectors","emit","node","variantAssignedAt","options","cleanups","firedOnce","timestamps","onClick","now","onCopy","e","sel","selectionLength","isVisible","hesitationTimer","clearHesitation","startHesitation","onScroll","ioCallback","entries","entry","io","assignedAt","onVisibility","elapsed","c","isDoNotTrackEnabled","v","SECTION_SELECTOR","HEARTBEAT_MS","selectSections","doc","candidates","kept","el","c","k","registerSections","apiKey","apiBase","pageUrl","sections","e","NOOP","startEngagementCapture","client","opts","_a","_b","_c","_d","_e","_f","_g","_h","_i","isDoNotTrackEnabled","els","componentOf","types","sources","explicit","markup","SEMANTIC_TYPES","type","classifySection","componentId","semanticType","state","get","id","s","observer","entries","entry","emit","now","onVisibility","frozen","onPageHide","event","onPageShow","win","heartbeat","detectorCleanups","attachMicroSignalDetectors","signalType","extra","__spreadValues"]}
|
|
1
|
+
{"version":3,"sources":["../src/index-engagement.ts","../src/engagement/classify.ts","../src/index.ts","../src/micro-signals.ts","../src/locator-from-dom.ts","../src/engagement/capture.ts"],"sourcesContent":["// Lazy engagement entry — loaded on demand (mirrors ./graph) so the lean\n// bundle never carries the section classifier or IntersectionObserver logic.\nexport { startEngagementCapture, type EngagementCaptureOptions } from './engagement/capture';\nexport {\n classifyFeatures,\n classifySection,\n featuresFromElement,\n SEMANTIC_TYPES,\n type SectionFeatures,\n type SemanticType,\n} from './engagement/classify';\n","// Semantic section classification for no-code section capture (Phase 3 §2.4).\n// Pure heuristic: element → one of the graph_nodes semantic_type enum. Mirrors\n// the SDK graph scanner's vocabulary so the persona × section matrix consumes\n// snippet-captured sections unchanged.\n//\n// SPLIT (Phase 2b, spec 2026-09-04). This module is the BROWSER-SAFE core:\n// structural rules, the small parent-level keyword table, and the fallbacks.\n// The rich ~40-topic vocabulary lives in ./topics.ts, which only the server\n// imports — shipping it here cost 1.5 KB gzip in every bundle (7% of the\n// always-on snippet) for a layer the browser never reads, since classifySection\n// returns only the parent.\n//\n// Both paths share structuralTopicOf/fallbackTopicOf, so the three fixes below\n// apply identically on client and server; only vocabulary richness differs.\n//\n// Fixes, each reproduced against the shipped classifier before being changed:\n// 1. structural before the converter fallback — `<div class=\"navbar\">` used\n// to become `cta`, because `navigation` was reachable only via tag\n// nav/footer.\n// 2. hero before the converter fallback — the cta rule sat above both hero\n// rules, so a `<header>` with a button and <200 chars could never be hero.\n// 3. tightened pricing/social keywords — `plans?` and `customers?` fired on\n// unrelated copy AND were `strong`, so they auto-applied at confidence 0.9\n// and were never sent to the LLM fallback.\n\nexport type SemanticType =\n | 'pricing' | 'hero' | 'social_proof' | 'cta' | 'features'\n | 'faq' | 'comparison' | 'trust' | 'navigation' | 'generic';\n\nexport type SectionRole = 'converter' | 'persuader' | 'structural';\n\n/** Canonical vocabulary — mirrors the graph_nodes semantic_type CHECK enum. */\nexport const SEMANTIC_TYPES: readonly SemanticType[] = [\n 'pricing', 'hero', 'social_proof', 'cta', 'features',\n 'faq', 'comparison', 'trust', 'navigation', 'generic',\n] as const;\n\nexport type TopicRule = { topic: string; parent: SemanticType; role: SectionRole };\n\n/** Environment-agnostic section features — buildable from a browser Element or\n * a server-parsed node (node-html-parser). */\nexport type SectionFeatures = {\n tag: string; // lowercase tag name\n idClass: string; // `${id} ${className}`\n headingText: string;\n bodyText: string; // normalized text content, first 2000 chars\n actionCount: number;\n textLength: number;\n /** ARIA landmark role, when the element declares one. Optional so every\n * existing caller keeps compiling; a page that uses landmarks gives a\n * high-precision signal for free, which the old classifier ignored — it\n * tested membership of SEMANTIC_TYPES, so only role=\"navigation\" ever hit\n * and role=\"banner\"/\"contentinfo\" were discarded. */\n ariaRole?: string;\n /** schema.org `@type` values found in `<script type=\"application/ld+json\">`\n * INSIDE this section. Highest-precision signal available and free to\n * collect — the crawler already has the HTML. Type-only here; the\n * `@type` → topic table is server-side in ./topics.ts, since the browser\n * never reads the topic layer and the snippet has ~200 bytes of margin. */\n structuredTypes?: string[];\n};\n\n// ARIA landmark → topic. Structural facts, not guesses.\nconst ARIA_TOPIC: Record<string, string> = {\n banner: 'hero',\n navigation: 'navigation',\n contentinfo: 'footer',\n};\n\n/**\n * Structural identification, shared by the browser and server classifiers.\n * Returns a topic name, or null when the section is not structural furniture.\n * Everything matched here is definitive (tag or authored marker), so callers\n * treat it as `strong`.\n */\nexport function structuralTopicOf(f: SectionFeatures): string | null {\n const aria = f.ariaRole ? ARIA_TOPIC[f.ariaRole.toLowerCase()] : undefined;\n if (aria) return aria;\n if (f.tag === 'nav') return 'navigation';\n if (f.tag === 'footer') return 'footer';\n // A page-level <header> IS the banner landmark (HTML-AAM maps it to\n // role=\"banner\", which this function already treats as hero), so it is a\n // structural fact rather than a keyword guess. Without this, a header whose\n // headline happens to contain a content word loses to the keyword table:\n // \"We build brands that move\" scored social_proof and \"Winter collection\"\n // scored features, purely on words inside the hero copy.\n if (f.tag === 'header') return 'hero';\n const hay = `${f.idClass} ${f.headingText}`.toLowerCase();\n if (/\\b(navbar|nav-bar|navigation|site-nav|main-nav|topbar|footer)\\b/.test(hay)) {\n return /footer/.test(hay) ? 'footer' : 'navigation';\n }\n // Explicit authoring marker beats any inferred keyword, and is matched on\n // idClass ONLY: a `<header class=\"hero\">` headlined \"Expert Car Repair\" is a\n // hero, not a services section — but matching \"hero\" in heading text would\n // also catch \"Hero of the story\".\n if (/\\b(hero|masthead|jumbotron)\\b/i.test(f.idClass)) return 'hero';\n return null;\n}\n\n/**\n * Last-resort classification once no keyword or content evidence matched.\n * Hero is checked BEFORE the converter fallback — fix 2 above.\n */\nexport function fallbackTopicOf(f: SectionFeatures): string {\n // `tag === 'header'` is handled in structuralTopicOf, which runs first.\n if (f.actionCount >= 1 && f.textLength > 0 && f.textLength < 200) return 'cta';\n return 'generic';\n}\n\n// Parent-level keyword table for the BROWSER path. Deliberately close to the\n// original size — the rich topic vocabulary is in ./topics.ts. `plans?` now\n// requires adjacent pricing context, and bare `customers?` is gone (it fired on\n// navigation furniture like a \"Customer Service\" footer block).\nconst KEYWORDS: Array<[SemanticType, RegExp]> = [\n ['pricing', /\\b(pricing|price list|per month|\\/mo|subscriptions?)\\b|\\bplans?\\b(?=[^.]{0,40}(from|start|month|year|[$€£]))/i],\n ['faq', /\\bfaq\\b|frequently asked|common questions?/i],\n ['comparison', /\\b(compare|comparison|versus)\\b|\\bvs\\./i],\n ['social_proof', /\\b(reviews?|ratings?|testimonial|brands?|galler(y|ies)|logos)\\b|trusted by|loved by|case stud|what our customers say/i],\n ['trust', /\\b(insurance|warrant(y|ies)|guarantees?|certifi|accredit|security|privacy|compliance|gdpr|encrypt)\\b|why choose|about us|our team/i],\n ['cta', /\\b(book|booking|reserve|appointments?|newsletter|subscribe)\\b|contact us|get in touch|opening hours/i],\n ['features', /\\b(features?|benefits?|capabilit|services?|repairs?|menus?|products?)\\b|how it works|our process|what we (do|offer)|what you get/i],\n];\n\n// Content-evidence patterns — run against bodyText when the heading gave us\n// nothing. Deliberately conservative: pricing needs per-period/plan context next\n// to money so an article mentioning \"$5 million\" stays generic.\nexport const CONTENT_PATTERNS: Array<[SemanticType, RegExp]> = [\n ['pricing', /(?:[$€£]\\s?\\d[\\d,.]*\\s*(?:\\/|per\\s)\\s*(?:mo|month|yr|year|seat|user))|(?:\\b(?:starter|basic|pro|growth|premium|enterprise)\\b[^.]{0,60}[$€£]\\s?\\d)/i],\n ['social_proof', /(?:★{2,})|(?:\\b\\d(?:\\.\\d)?\\s*(?:out of|\\/)\\s*5\\b)|(?:\\brated\\b)|(?:[\"“][^\"”]{20,160}[\"”]\\s*[—–-]\\s*[A-Z][a-z]+)/],\n ['trust', /\\b(?:money[- ]back guarantee|free returns?|returns? within|refund(?:s)? within|encrypted|soc ?2|iso ?27001|gdpr[- ]compliant|cancel anytime)\\b/i],\n ['comparison', /\\b(?:vs|versus)\\b\\.?[^.!?]{0,80}\\b(?:compare|comparison|plans?|features?|alternative)\\b|\\bhow (?:we|it) compares?\\b/i],\n];\n\n/** Parent for the handful of topics the shared structural/fallback helpers\n * emit. The server maps the full vocabulary via CLASSIFIER_TOPICS instead. */\nconst SHARED_TOPIC_PARENT: Record<string, SemanticType> = {\n navigation: 'navigation',\n footer: 'navigation',\n hero: 'hero',\n cta: 'cta',\n generic: 'generic',\n};\n\nfunction headingText(el: Element): string {\n const h = el.querySelector('h1, h2, h3');\n return (h?.textContent ?? '').slice(0, 160);\n}\n\n/**\n * Pure classification over extracted features. `strong` = keyword, content, or\n * structural evidence (trustable enough to auto-apply); `weak` = a fallback\n * guess (hero/cta/generic — capture-worthy but not persona evidence).\n */\nexport function classifyFeatures(f: SectionFeatures): { type: SemanticType; strength: 'strong' | 'weak' } {\n const structural = structuralTopicOf(f);\n if (structural) return { type: SHARED_TOPIC_PARENT[structural] ?? 'generic', strength: 'strong' };\n\n const hay = `${f.idClass} ${f.headingText}`.toLowerCase();\n for (const [type, re] of KEYWORDS) if (re.test(hay)) return { type, strength: 'strong' };\n for (const [type, re] of CONTENT_PATTERNS) if (re.test(f.bodyText)) return { type, strength: 'strong' };\n\n const fb = fallbackTopicOf(f);\n return { type: SHARED_TOPIC_PARENT[fb] ?? 'generic', strength: 'weak' };\n}\n\n/** Feature extraction from a live DOM element (browser paths). */\nexport function featuresFromElement(el: Element): SectionFeatures {\n const text = (el.textContent ?? '').replace(/\\s+/g, ' ').trim();\n const role = el.getAttribute('role');\n return {\n tag: el.tagName.toLowerCase(),\n idClass: `${el.id} ${String(el.className ?? '')}`,\n headingText: headingText(el),\n bodyText: text.slice(0, 2000),\n actionCount: el.querySelectorAll('a, button, [role=\"button\"]').length,\n textLength: text.length,\n ...(role ? { ariaRole: role } : {}),\n };\n}\n\n/** Classify a page section into a semantic type (never null — falls back to\n * 'generic' so the caller can still capture attention on it). */\nexport function classifySection(el: Element): SemanticType {\n return classifyFeatures(featuresFromElement(el)).type;\n}\n","import { initSession, type SessionConfig, type SessionManager } from './session';\nimport {\n createEventQueue,\n retryStorageKey,\n type EventQueue,\n type EventType,\n type QueueConfig,\n type SentientEvent,\n} from './queue';\nimport {\n createGoalQueue,\n goalRetryStorageKey,\n type GoalQueue,\n} from './goal-queue';\nimport {\n createAssignmentCache,\n type Assignment,\n} from './cache';\nimport type {\n GraphConfig,\n GraphSnapshot,\n} from './graph';\nimport {\n detectDeviceClass,\n detectTrafficSource,\n detectTimeOfDay,\n extractTrackedParams,\n referrerDomainFromReferer,\n uaTokenMatch,\n} from './session-meta.js';\nimport {\n toWireSlot,\n baselineResultFor,\n armOfResult,\n type SlotDeclInput,\n type SlotResult,\n} from './slots.js';\nimport { readSnapshot, writeSnapshot, SNAPSHOT_STORAGE_KEY_PREFIX, type SlotConfigEntry, type CompoundLocator } from './snapshot.js';\nimport { confidenceBand } from '@sentientui/policy';\nimport { createLocalModeClient } from './local-mode.js';\nimport { randomUuidV4 } from './uuid.js';\nimport { backoffDelayMs, classifyResponse } from './durable.js';\n\nexport { PROD_KEYLESS_ERROR, LOCAL_MODE_BANNER } from './local-mode.js';\n\n// The one source of truth for the session cookie's name — every out-of-package\n// reader (react devtools, integrator SSR code) must derive the name from this\n// instead of hard-coding `_snt_uid`, which is only the pre-namespacing fallback.\nexport { sessionCookieName, LEGACY_SESSION_COOKIE_NAME } from './storage-key.js';\n\nexport {\n detectDeviceClass,\n detectTrafficSource,\n detectTimeOfDay,\n deriveSessionSegment,\n extractTrackedParams,\n CLICK_ID_KEYS,\n referrerDomainFromReferer,\n uaTokenMatch,\n matchedAgentToken,\n agentUaList,\n agentIntent,\n classifiedAgents,\n AGENT_INTENTS,\n} from './session-meta.js';\nexport type { AgentIntent } from './session-meta.js';\n\nconst DEFAULT_INGEST_URL = 'https://api.sentient-ui.com/v1/events';\n\n// Keyed by apiKey so multiple init() calls (HMR, multi-project) don't collide.\nconst _clients = new Map<string, {\n config: SentientConfig;\n upgrade: ((c: SentientClient) => void) | null;\n // Why grantConsent() cannot upgrade this entry (keyless/local mode, invalid\n // key). grantConsent() warns with this instead of silently no-oping — a CMP\n // callback wired to it otherwise LOOKED like it worked while nothing ever\n // started tracking. Absent for entries where the silent no-op IS the\n // documented contract (DNT-blocked, already upgraded).\n upgradeBlockedReason?: string;\n // Set by an alternate entry point (the /graph entry) whose gated init\n // deferred extra resources: grantConsent() must re-run THAT entry's init —\n // upgrading through the lean init() produced a post-consent client that\n // never mounted the DOM scanner, silently losing graph capture.\n reinit?: (c: SentientConfig) => SentientClient;\n // Teardown for the live client bound to this key (stops its queue interval +\n // unload listeners). Present only for the full tracking client; the no-op /\n // pre-consent / local entries have nothing to tear down. Called before a\n // re-init for the same key replaces it, so timers/listeners can't leak.\n dispose?: () => void;\n}>();\nlet _lastApiKey: string | null = null;\n\n/**\n * @internal Wires an alternate entry point's init as grantConsent()'s upgrade\n * path for `apiKey`. The /graph entry calls this when its init is gated on\n * consent: without it, grantConsent() upgraded through the LEAN init, so a\n * graph-configured page granted consent but never mounted the scanner (the\n * graph resources exist only in the /graph entry). No-op unless the entry is\n * actually upgradeable — DNT-blocked and local entries register no hook.\n */\nexport function _registerConsentUpgradeInit(\n apiKey: string,\n reinit: (config: SentientConfig) => SentientClient,\n): void {\n const entry = _clients.get(apiKey);\n if (entry && entry.upgrade) entry.reinit = reinit;\n}\n\nexport type SentientConfig = {\n apiKey: string;\n context: 'landing' | 'ecommerce' | 'saas' | 'marketplace';\n /** @internal — not exposed to users; defaults to the hosted SentientUI API. */\n ingestUrl?: string;\n debug?: boolean;\n /**\n * Pre-seeded assignments from `preloadAssignments()` (SSR).\n * Seeds the local cache so `assign()` returns without a network call for\n * listed code variants, guaranteeing server and client render the same\n * variant on first paint. Managed-text components (assign with no\n * variantIds) still fetch once when the seed carries no content.\n */\n initialAssignments?: Record<string, string>;\n /**\n * Segment used for SSR preload (`device:source`). When set with `initialAssignments`,\n * seeds the assignment cache under this key so hydration matches the server bandit row.\n */\n sessionSegment?: string;\n /**\n * Consent gate. When `false`, returns a no-op client and performs no tracking.\n * Defaults to `true`. Re-call `init()` (via `AdaptiveProvider` consent prop) when\n * the user grants or revokes consent mid-session.\n */\n consent?: boolean;\n /**\n * Behavior before consent is granted. `'statistical_winner'` fetches the\n * best-performing variant via `GET /v1/winner` — no session or tracking data\n * is stored. `'control'` (default) shows `variantIds[0]` with no API call.\n * Applies when tracking is gated off — either `consent: false` or an active\n * Do Not Track signal.\n */\n preConsentBehavior?: 'statistical_winner' | 'control';\n /**\n * Whether to honor the browser's Do Not Track (DNT) signal. Defaults to `true`.\n * When `true` and the visitor has DNT enabled, the SDK sets no cookies and\n * sends no tracking data — behaving exactly as `consent: false` (still serving\n * the read-only `preConsentBehavior` winner if configured), and `grantConsent()`\n * will not upgrade it. Set `false` to make your own consent gate authoritative.\n */\n respectDoNotTrack?: boolean;\n userId?: string;\n /**\n * Declared persona — the role your app already knows for this visitor\n * (e.g. 'admin', 'evaluator'). Must be a key in the project's persona\n * vocabulary (dashboard → Settings → Personas); unrecognized values are\n * ignored server-side and surfaced in the dashboard so you can add them.\n * Declared personas are served at full confidence, overriding the inferred\n * one. Keep it a low-cardinality role label — never a user id or email.\n */\n persona?: string;\n /**\n * Session ID generated server-side (from `loadAdaptiveAssignments` / `loadAdaptiveDecision`).\n * When provided, the client adopts this ID on first visit instead of generating a new one,\n * ensuring events and goals are attributed to the same session the server used for assignment.\n */\n ssrSessionId?: string;\n /**\n * ISO 3166-1 alpha-2 country code for the visitor. When provided (e.g. from\n * the `CF-IPCountry` header in a Next.js server component), it is included in\n * the session upsert so country-based segmentation works without client-side\n * geo lookup.\n */\n country?: string;\n /**\n * Pre-seeded slot results from `preloadDecisions()` / `loadAdaptiveDecision()`\n * (SSR). Seeds the local slot state so `getSlotResult()` agrees with the\n * server-rendered markup on first paint.\n */\n initialSlots?: Record<string, SlotResult>;\n /**\n * Persona decided during SSR. Takes priority over the html-attribute\n * adoption and the local snapshot.\n */\n initialPersona?: { persona: string; confidence: number };\n /**\n * Keyless local mode. 'auto' (default) simulates decisions on-device when no\n * valid API key is configured — but only in development builds (the\n * `development` export condition); production bundles physically exclude the\n * engine. `true` forces the local engine regardless of key (escape hatch);\n * `false` restores the silent keyless no-op.\n */\n localMode?: 'auto' | boolean;\n};\n\nexport type AssignResult = { variantId: string; assignmentTtlMs: number; content?: string };\n\nexport type { SlotDeclInput, SlotResult };\nexport { armOfResult, baselineResultFor, baselineSlots, toWireSlot } from './slots.js';\n\nexport {\n SNAPSHOT_STORAGE_KEY_PREFIX,\n readSnapshot,\n writeSnapshot,\n renderPrePaintScript,\n} from './snapshot.js';\nexport type { DecisionSnapshot, SlotConfigEntry, SlotOps, CompoundLocator } from './snapshot.js';\nexport * from './blocks.js';\n\n/** An editor-defined goal delivered with a registry-mode decision, for the\n * snippet to install delegated listeners from. */\nexport type GoalDefinition = {\n goalId: string;\n event: 'click' | 'form_submit' | 'url_reached' | 'scroll_depth';\n locator?: CompoundLocator;\n urlPattern?: string;\n slotId?: string;\n /** scroll_depth only: fraction of the page (0–1] that counts as read. */\n threshold?: number;\n};\n\n/** One served section-classification row (registry mode): where it is on the\n * page (url match + compound locator) and its semantic type. The snippet\n * resolves the locator to build capture's `typeOf` hook. */\nexport type SectionMapEntry = {\n urlMatch: string;\n locator: CompoundLocator;\n type: string;\n};\n\nexport type DecideOutcome = {\n layoutOrder: string[] | null;\n assignments: Record<string, string>;\n slots: Record<string, SlotResult>;\n persona: string;\n confidence: number;\n // Registry mode only: where/what to apply for server-defined slots.\n slotConfig?: Record<string, SlotConfigEntry>;\n // Registry mode only: editor-defined goals to wire up.\n goals?: GoalDefinition[];\n // Registry mode only: served section-classification map the snippet turns\n // into capture's `typeOf` hook.\n sectionMap?: SectionMapEntry[];\n // Registry mode only: derived site palette for Composition Block rendering.\n palette?: import('./blocks.js').SitePalette;\n};\n\nexport type DecideInput = {\n sections?: string[];\n components?: Array<{ id: string; variantIds?: string[] }>;\n slots?: SlotDeclInput[];\n // 'registry' → serve the project's published slot_definitions in addition to\n // any declared slots (registry wins on id collision). Default 'request'.\n slotsFrom?: 'request' | 'registry';\n /**\n * Caller's build version (e.g. the snippet's `__SNIPPET_VERSION__`), sent\n * as `v` on the wire. Additive/best-effort: the server persists it for\n * version-skew reporting (see apps/api decide route) and ignores it\n * entirely on older deployments. Omit if the caller has no version to report.\n */\n v?: string;\n};\n\nexport type WeightEntry = { variantId: string; pulls: number; avgReward: number | null };\nexport type ComponentWeightEntry = { componentId: string; updatedAt: number; variants: WeightEntry[] };\n\n/** Options accepted by goal() (and inherited by componentGoal / the React\n * hooks / the snippet) — one shape everywhere (spec §5). */\nexport type GoalOptions = {\n /** Revenue of this conversion, in the project currency. */\n value?: number;\n /** ISO-4217 code, only when it differs from the project currency. */\n currency?: string;\n /** Merchant order/transaction id — dedupes retries, enables refunds later. */\n externalId?: string;\n /** Extra fields merged into the event payload / goal metadata. */\n metadata?: Record<string, unknown>;\n /** Advanced: partial-credit weight in [0,1] (composite steps). */\n weight?: number;\n /** Advanced: funnel step index (0-based). */\n stepIndex?: number;\n};\n\n/** goal()'s second arg is the options object iff it carries a reserved key;\n * anything else keeps the legacy bare-metadata interpretation. Reserved keys\n * inside legacy metadata were inert on the server, so reinterpretation is the\n * upgrade the sender wanted (spec §5). */\nfunction isGoalOptions(v: Record<string, unknown>): boolean {\n return 'value' in v || 'currency' in v || 'externalId' in v || 'metadata' in v || 'weight' in v || 'stepIndex' in v;\n}\n\nexport type ComponentGoalOptions = GoalOptions & {\n /** Reward credited to the served variant (0–1). Defaults to 1. */\n reward?: number;\n};\n\nexport type SentientClient = {\n track(\n event: Omit<SentientEvent, 'id' | 'sessionId' | 'timestamp' | 'timeInSession'>,\n ): void;\n goal(name: string, options?: GoalOptions): void;\n /** @deprecated positional form — prefer goal(name, options). */\n goal(name: string, metadata?: Record<string, unknown>, weight?: number, stepIndex?: number): void;\n /**\n * Records a conversion attributed to the variant currently served for\n * `componentId`, so it feeds the per-variant CVR funnel. Resolves the served\n * variant from the local assignment cache — no need to pass variantId or\n * projectId. No-ops if the component has not been assigned yet (render its\n * `<Adaptive>`/call `assign()` first). Prefer this over bare `goal()` for\n * variant experiments; `goal()` is session-level only (no component attribution).\n */\n componentGoal(componentId: string, goalType: string, opts?: ComponentGoalOptions): void;\n identify(userId: string): void;\n getAssignment(componentId: string, segment: string): Assignment | null;\n /** Server-side variant assignment. Caches the result locally per (component, segment). */\n assign(componentId: string, variantIds?: string[], agentData?: unknown, agentDataByVariant?: Record<string, unknown>): Promise<AssignResult | null>;\n /**\n * Single-roundtrip decision for layout sections, component variants, and\n * adaptive slots. Awaits the session upsert (like `assign`) so the server\n * never decides for a session row that doesn't exist yet. A response\n * without a `slots` field means the server predates slots — every declared\n * slot resolves to its baseline and no retry is made.\n */\n decide(input: DecideInput): Promise<DecideOutcome | null>;\n /** Slot result served this session (decide result, SSR seed, snapshot, or failure baseline). Null when unknown. */\n getSlotResult(slotId: string): SlotResult | null;\n /** Current persona estimate. Band is always `confidenceBand(confidence)`. Null when nothing is known yet. */\n getPersona(): { persona: string; confidence: number; band: 'low' | 'medium' | 'high' } | null;\n /** Fetches current bandit weights for all components in this project. Used by the provider to keep live-weight polling fresh. */\n fetchWeights(): Promise<ComponentWeightEntry[]>;\n getGraph(): GraphSnapshot;\n /**\n * Routine teardown: stops timers/listeners and flushes pending events, but\n * KEEPS the visitor identity, decision snapshot, and retry bucket. Use for\n * component unmount / re-init (framework providers call this on cleanup).\n */\n dispose(): void;\n /**\n * Consent-revocation / forget-me teardown: everything `dispose()` does,\n * plus deletion of the visitor identity (`_snt_uid`), the decision\n * snapshot, and the persisted retry bucket. The next visit starts as a\n * brand-new visitor.\n */\n destroy(): void;\n /** True when this client is the keyless local-mode client (dev only). */\n readonly isLocal?: boolean;\n};\n\n// SSR preload helpers moved to the `@sentientui/core/server` entry in 0.6.0 so\n// ~200 lines of Node-only fetch logic stop shipping in the browser bundle.\n\nexport { attachMicroSignalDetectors } from './micro-signals.js';\nexport type { MicroSignalEmitter, MicroSignalType } from './micro-signals.js';\n\nexport type {\n SessionConfig,\n SessionManager,\n EventType,\n SentientEvent,\n QueueConfig,\n Assignment,\n GraphSnapshot,\n GraphConfig,\n};\n\n/** Attempts after the first for the session upsert — see upsertSession. */\nconst SESSION_UPSERT_RETRIES = 3;\n\nfunction generateEventId(): string {\n return randomUuidV4();\n}\n\n/**\n * The page an event happened on.\n *\n * `location.pathname` ONLY — never `href` or `search`. Query strings on real\n * sites carry emails, reset tokens, order ids and session ids, and none of that\n * should leave the browser for analytics. The server strips them again\n * (domain/page-path.ts) because a hand-rolled integration can post whatever it\n * likes; this is the first of the two gates, and the one that means the data\n * never travels at all.\n *\n * Undefined outside a browser: during SSR there is no page to name, and an\n * invented one would be wrong for every reader.\n */\nfunction currentPath(): string | undefined {\n if (typeof window === 'undefined') return undefined;\n return window.location?.pathname || undefined;\n}\n\n/**\n * Decides whether a goal() call belongs to a user action already recorded.\n *\n * This used to be a clock: a latch cleared on the next macrotask, so anything\n * inside that window counted as \"the same action\". A clock cannot tell the two\n * cases apart, and it got the expensive one wrong. The window can be JUMPED —\n * a macrotask scheduled to close it runs after any timer already armed, which\n * every real page and every sibling test in a worker has — so a genuinely\n * separate conversion landed in a window that should have shut, and was\n * swallowed rather than queued: gone, with no retry able to rescue it because\n * nothing was ever handed to the queue.\n *\n * So ask the question the clock was approximating. Two nested components\n * reacting to one click are, exactly, two listeners in one event DISPATCH, and\n * the platform already hands us that identity: `window.event` is the same Event\n * object for every listener of one dispatch, a different object for the next\n * click, and undefined outside dispatch entirely. Keying on the event object\n * makes \"one action\" a fact rather than a deadline — no timer to lose a race\n * with, no fake-timer or background-throttle hazard, and no way for a second\n * click to be mistaken for the first however long the page stalls between them.\n *\n * Goals fired outside any dispatch (an effect on mount, a page goal) have no\n * event to key on, and fall back to one SYNCHRONOUS flush — closed on a\n * microtask. That is exact too, and for the same reason the old macrotask\n * window was not: microtasks always drain before the next macrotask, so no\n * pending timer can jump this window. A user cannot perform two actions inside\n * one synchronous block, so anything sharing it is a double-fire, not a repeat.\n *\n * A microtask is deliberately NOT used for the dispatch case: the HTML spec\n * runs a microtask checkpoint between listeners once the JS stack empties, so\n * it would split one click into two and double-count the revenue this collapse\n * exists to protect. That is why the dispatch case keys on the event instead,\n * and why a host without `window.event` keeps the old macrotask window — too\n * loose, but erring toward the old behaviour rather than toward double-counting.\n */\nfunction createActionLatch(): { firedBefore(actionKey: string, valueKey: string | null): boolean } {\n // Per window, per action key: the set of value identities already recorded.\n // An entry with an empty set means a VALUELESS fire was recorded. The split\n // exists because value cannot simply live inside one flat key: an inner\n // component declaring `value: 50` nested in an outer wrapper with the same\n // goal but NO value produced two distinct keys — two rows for one click.\n // Within a window, a valueless fire is absorbed by ANY record of the same\n // action (the valued row already carries the order, and a valueless\n // duplicate would inflate Hits), while a valued fire is collapsed only by an\n // IDENTICAL (value, currency) record — $50 and $70 stay two orders\n // (CONTRACTS §1). A valued fire landing AFTER a valueless one still records:\n // the valueless row has already been handed to the queue (often already on\n // the wire) and cannot be retracted, and losing the money would be the worse\n // error — server-side credit clamps the extra valueless hit at min(1, MAX\n // weight), so the cost is one inflated Hit, not corrupted revenue. Listener\n // order makes the benign ordering the common one: the inner (valued)\n // component's listener runs before the wrapper's in a bubbling dispatch.\n const byEvent = new WeakMap<object, Map<string, Set<string>>>();\n const byFlush = new Map<string, Set<string>>();\n let flushOpen = false;\n\n const alreadyRecorded = (map: Map<string, Set<string>>, actionKey: string, valueKey: string | null): boolean => {\n const values = map.get(actionKey);\n if (valueKey === null) {\n if (values) return true;\n map.set(actionKey, new Set());\n return false;\n }\n if (!values) {\n map.set(actionKey, new Set([valueKey]));\n return false;\n }\n if (values.has(valueKey)) return true;\n values.add(valueKey);\n return false;\n };\n\n // Standardised as Window.event and present in every current browser, but a\n // capability check keeps exotic hosts on the path they have always had.\n const hasWindowEvent = typeof window !== 'undefined' && 'event' in window;\n\n const currentEvent = (): object | undefined => {\n if (!hasWindowEvent) return undefined;\n const ev = (window as unknown as { event?: unknown }).event;\n // Must be a real same-realm Event, not merely an object. Window.event is\n // [Replaceable]: a classic script doing `event = {...}` at top level (an\n // implicit or sloppy global on plenty of host pages) permanently shadows\n // the accessor with a data property. Accepting any object then returned\n // that SAME object forever — its WeakMap entry never died, so every later\n // conversion looked like a re-fire of the first action and ALL repeat\n // conversions were silently dropped for the session. `instanceof Event`\n // cannot be true for such a literal; a cross-realm Event (iframe) fails it\n // too and merely falls back to the flush window, which is safe.\n // (typeof guard: a host with `window` but no Event constructor must fall\n // back, not throw a ReferenceError from inside goal().)\n return typeof Event === 'function' && ev instanceof Event ? ev : undefined;\n };\n\n const closeFlushWindow = (): void => {\n if (hasWindowEvent) {\n // A promise microtask, not queueMicrotask: fake-timer setups can replace\n // queueMicrotask, and this window closing is what keeps repeat\n // conversions from being swallowed.\n void Promise.resolve().then(() => {\n flushOpen = false;\n byFlush.clear();\n });\n return;\n }\n let done = false;\n const clear = (): void => {\n if (done) return;\n done = true;\n flushOpen = false;\n byFlush.clear();\n };\n setTimeout(clear, 0);\n if (typeof MessageChannel === 'function') {\n const ch = new MessageChannel();\n ch.port1.onmessage = () => {\n ch.port1.close();\n ch.port2.close();\n clear();\n };\n ch.port2.postMessage(0);\n }\n };\n\n return {\n firedBefore(actionKey: string, valueKey: string | null): boolean {\n const ev = currentEvent();\n if (ev) {\n let keys = byEvent.get(ev);\n if (!keys) {\n keys = new Map<string, Set<string>>();\n // Keyed weakly: the Map dies with the Event object, so a long session\n // of clicks accumulates nothing.\n byEvent.set(ev, keys);\n }\n return alreadyRecorded(keys, actionKey, valueKey);\n }\n const collapsed = alreadyRecorded(byFlush, actionKey, valueKey);\n if (!collapsed && !flushOpen) {\n flushOpen = true;\n closeFlushWindow();\n }\n return collapsed;\n },\n };\n}\n\n/**\n * Emits one `pageview` per page load and per SPA route change.\n *\n * Patches pushState/replaceState rather than polling: a route change is a\n * discrete event, and polling would either miss fast back-to-back navigations or\n * burn a timer on every page for the entire session. popstate covers\n * back/forward, which history patching does not see.\n *\n * Deduplicates on pathname, because frameworks routinely replaceState several\n * times for one navigation (query/hash updates, scroll restoration) and each\n * would otherwise look like another page in the visitor's journey.\n */\n/** Pages already recorded this page lifetime, keyed project:path. dispose()\n * flushes, so without this a consent-change or StrictMode re-init delivered a\n * second landing pageview for a page the previous client already sent. */\nconst emittedPages = new Set<string>();\n\nfunction startPageviewTracking(\n client: SentientClient,\n projectId: string,\n // Called with the page key after emitting; the caller marks emittedPages only\n // once the event reached a LIVE queue. Marking at emit time instead turned\n // StrictMode's mount→dispose→mount into zero delivered landings: the first\n // mount's event dies in the destroyed queue, and the mark suppressed the\n // second mount's — the one that actually ships.\n markDelivered: (key: string) => void,\n): () => void {\n const h = typeof window === 'undefined' ? null : window.history;\n if (!h) return () => undefined;\n\n // The stop handle exists because init() runs again on every consent change,\n // StrictMode double-invoke and HMR: without it each init wrapped history\n // again and the old wrapper kept emitting through the DISPOSED client, so one\n // navigation produced one pageview per init that ever happened.\n let stopped = false;\n let last: string | undefined;\n const emit = (): void => {\n if (stopped) return;\n const path = currentPath();\n if (!path || path === last) return;\n last = path;\n // '__page__' is a sentinel componentId: the ingest schema requires one, and\n // every component reader filters on variant_id IS NOT NULL or a specific\n // event_type, so it never surfaces as a component.\n client.track({ projectId, componentId: '__page__', eventType: 'pageview', payload: {} });\n markDelivered(`${projectId}:${path}`);\n };\n\n const installed: Array<['pushState' | 'replaceState', History['pushState'], History['pushState']]> = [];\n for (const name of ['pushState', 'replaceState'] as const) {\n const orig = h[name];\n const wrapper = function (this: History, ...a: unknown[]) {\n const r = (orig as (...x: unknown[]) => unknown).apply(this, a);\n emit();\n return r;\n } as History[typeof name];\n h[name] = wrapper;\n installed.push([name, orig, wrapper]);\n }\n window.addEventListener('popstate', emit);\n\n // The landing page itself — once per (project, path) per page lifetime. When\n // it was already sent, `last` is still primed so the next real navigation\n // emits exactly once.\n const landing = currentPath();\n if (landing && emittedPages.has(`${projectId}:${landing}`)) last = landing;\n else emit();\n\n return () => {\n if (stopped) return;\n stopped = true;\n window.removeEventListener('popstate', emit);\n for (const [name, orig, wrapper] of installed) {\n // Restore only while ours is still on top; if something wrapped over it,\n // unhooking would sever their chain — the stopped flag already makes ours\n // a passthrough.\n if (h[name] === wrapper) h[name] = orig;\n }\n };\n}\n\nconst SSR_CLIENT: SentientClient = {\n track: () => undefined,\n goal: () => undefined,\n componentGoal: () => undefined,\n identify: () => undefined,\n getAssignment: () => null,\n assign: () => Promise.resolve(null),\n decide: () => Promise.resolve(null),\n getSlotResult: () => null,\n getPersona: () => null,\n fetchWeights: () => Promise.resolve([]),\n getGraph: () => ({ pageNodes: [], capturedAt: 0 }),\n dispose: () => undefined,\n destroy: () => undefined,\n};\n\nfunction readTrackedParams(): {\n utmParams: Record<string, string>;\n clickIds: Record<string, string>;\n} {\n try {\n return extractTrackedParams(window.location.search);\n } catch {\n return { utmParams: {}, clickIds: {} };\n }\n}\n\nfunction deriveBaseUrl(ingestUrl: string): string {\n return ingestUrl.replace(/\\/events\\/?$/, '');\n}\n\n/**\n * Detects whether the visitor has signalled a tracking opt-out. Honors Global\n * Privacy Control (`navigator.globalPrivacyControl`) — the legally-enforceable\n * CCPA/CPRA signal — as well as Do Not Track (`navigator.doNotTrack`, the legacy\n * `window.doNotTrack` on older Firefox, and `navigator.msDoNotTrack` on old\n * IE/Edge). GPC is a boolean; DNT is opt-out only when explicitly `'1'`/`'yes'`.\n */\nexport function isDoNotTrackEnabled(): boolean {\n // GPC is a boolean flag, checked separately from the DNT string signals.\n if (\n typeof navigator !== 'undefined' &&\n (navigator as unknown as { globalPrivacyControl?: boolean }).globalPrivacyControl === true\n ) {\n return true;\n }\n const signals = [\n typeof navigator !== 'undefined' ? navigator.doNotTrack : undefined,\n typeof window !== 'undefined'\n ? (window as unknown as { doNotTrack?: string | null }).doNotTrack\n : undefined,\n typeof navigator !== 'undefined'\n ? (navigator as unknown as { msDoNotTrack?: string | null }).msDoNotTrack\n : undefined,\n ];\n return signals.some((v) => v === '1' || v === 'yes');\n}\n\n/**\n * Upgrades a pre-consent client (any client created with `consent: false`, in\n * either `preConsentBehavior` mode) to a fully-tracking client, in place and\n * with no page reload. Call this from your consent management platform callback.\n * For React apps, prefer updating the `consent` prop on `<AdaptiveProvider>`.\n * Pass `apiKey` to target a specific project; omit to upgrade the most-recently-initialized client.\n */\nexport function grantConsent(apiKey?: string): void {\n if (typeof window === 'undefined') return;\n\n const key = apiKey ?? _lastApiKey;\n if (!key) {\n console.warn('[sentient] grantConsent() called before init()');\n return;\n }\n\n const entry = _clients.get(key);\n if (!entry) {\n console.warn('[sentient] grantConsent() called before init()');\n return;\n }\n\n const { config, upgrade, reinit } = entry;\n if (!upgrade) {\n // Keyless/local and invalid-key clients register no upgrade hook — there\n // is no hosted client to swap in. This used to return SILENTLY, so a CMP\n // callback wired to grantConsent() looked like it worked while nothing\n // ever started tracking. DNT-blocked and already-upgraded entries carry no\n // reason and stay quiet: for them the no-op is the documented contract.\n if (entry.upgradeBlockedReason) console.warn(entry.upgradeBlockedReason);\n return;\n }\n\n // Honor an active Do Not Track signal — consent cannot override a global opt-out.\n if (config.respectDoNotTrack !== false && isDoNotTrackEnabled()) return;\n\n // Upgrade through the entry point that ran the gated init when one\n // registered itself (see _registerConsentUpgradeInit) — the lean init knows\n // nothing about that entry's extra resources (the /graph scanner).\n const fullClient = (reinit ?? init)({ ...config, consent: true });\n upgrade(fullClient);\n // init() just registered the full client (with its dispose) under `key`.\n // Preserve that dispose so a later re-init/teardown can still tear it down —\n // we only need to clear the upgrade hook now that consent is granted.\n const disposed = _clients.get(key)?.dispose;\n _clients.set(key, { config: { ...config, consent: true }, upgrade: null, dispose: disposed });\n}\n\nfunction createPreConsentProxy(config: SentientConfig): { proxy: SentientClient; setInner: (c: SentientClient) => void } {\n // 'control' (the default) must reach the network zero times before consent.\n // The proxy still exists so grantConsent() has something to upgrade in place\n // — without it, a site wanting no pre-consent traffic could only start\n // tracking by reloading the page.\n const servesWinner = config.preConsentBehavior === 'statistical_winner';\n const baseUrl = deriveBaseUrl(config.ingestUrl ?? DEFAULT_INGEST_URL);\n const authHeaders = {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${config.apiKey}`,\n } as const;\n\n // Pre-consent winners are read-only and render-driven: every mounted\n // component re-calls assign() on every render, and without a result cache or\n // in-flight coalescing each call refired GET /v1/winner — the full client\n // has inflightAssigns for exactly this. Successful winners are cached for\n // the pre-consent phase (the winner is stable, and a flip mid-visit would be\n // a variant flash anyway); failure fallbacks are NOT cached, so a recovering\n // server gets asked again. Both maps die with the proxy on upgrade.\n const winnerCache = new Map<string, AssignResult>();\n const inflightWinners = new Map<string, Promise<AssignResult | null>>();\n\n let inner: SentientClient = {\n track: () => undefined,\n goal: () => undefined,\n componentGoal: () => undefined,\n identify: () => undefined,\n getAssignment: () => null,\n fetchWeights: () => Promise.resolve([]),\n assign(componentId, variantIds, _agentData?) {\n // Control mode: no request. Callers fall back to variantIds[0] through\n // ssrFallback, exactly as they did against the old no-op client.\n if (!servesWinner) return Promise.resolve(null);\n const cached = winnerCache.get(componentId);\n if (cached) return Promise.resolve(cached);\n return coalesce(inflightWinners, componentId, async (): Promise<AssignResult | null> => {\n try {\n const params = new URLSearchParams({ componentId });\n for (const v of variantIds ?? []) params.append('variantIds[]', v);\n const res = await fetch(`${baseUrl}/winner?${params.toString()}`, {\n headers: authHeaders,\n });\n if (!res.ok) return variantIds?.[0] ? { variantId: variantIds[0], assignmentTtlMs: 0 } : null;\n const body = (await res.json()) as { variantId: string };\n const result: AssignResult = { variantId: body.variantId, assignmentTtlMs: 0 };\n winnerCache.set(componentId, result);\n return result;\n } catch {\n return variantIds?.[0] ? { variantId: variantIds[0], assignmentTtlMs: 0 } : null;\n }\n });\n },\n decide: () => Promise.resolve(null),\n getSlotResult: () => null,\n getPersona: () => null,\n getGraph: () => ({ pageNodes: [], capturedAt: 0 }),\n dispose: () => undefined,\n destroy: () => undefined,\n };\n\n const proxy: SentientClient = {\n track: (e) => inner.track(e),\n // Cast: a single arrow can't structurally satisfy the overloaded member;\n // the passthrough forwards both call shapes untouched.\n goal: ((n: string, m?: Record<string, unknown>, w?: number, s?: number) => inner.goal(n, m, w, s)) as SentientClient['goal'],\n componentGoal: (c, g, o) => inner.componentGoal(c, g, o),\n identify: (u) => inner.identify(u),\n getAssignment: (c, s) => inner.getAssignment(c, s),\n assign: (c, v, a, av) => inner.assign(c, v, a, av),\n decide: (i) => inner.decide(i),\n getSlotResult: (s) => inner.getSlotResult(s),\n getPersona: () => inner.getPersona(),\n fetchWeights: () => inner.fetchWeights(),\n getGraph: () => inner.getGraph(),\n dispose: () => inner.dispose(),\n destroy: () => inner.destroy(),\n };\n\n function setInner(fullClient: SentientClient) {\n inner = fullClient;\n }\n\n return { proxy, setInner };\n}\n\n/**\n * Shares one promise among concurrent calls with the same key — assign() and\n * decide() both use this so N same-tick requests (several mounted slots\n * sharing a component id; per-slot lazy decides) cost one roundtrip. The map\n * entry lives exactly as long as the request is in flight: a settled result\n * must NOT serve later calls (a sequential re-request is a fresh decision —\n * caching lives elsewhere), and a failed one must not wedge the key. No\n * `.finally()` — that's ES2018 and this file ships in the es2017 snippet\n * bundle (the SNIP-5 lesson).\n */\nfunction coalesce<T>(inflight: Map<string, Promise<T>>, key: string, run: () => Promise<T>): Promise<T> {\n const hit = inflight.get(key);\n if (hit) return hit;\n const request = (async (): Promise<T> => {\n try {\n return await run();\n } finally {\n inflight.delete(key);\n }\n })();\n inflight.set(key, request);\n return request;\n}\n\n/**\n * Initializes the Sentient client. Returns a no-op client during SSR.\n */\nexport function init(config: SentientConfig): SentientClient {\n if (typeof window === 'undefined') {\n return SSR_CLIENT;\n }\n\n // `|| 'local'`: keyless clients register under the 'local' fallback key\n // below, and `_lastApiKey = ''` is falsy — so a no-arg grantConsent() after\n // a keyless init() warned \"called before init()\" even though init() DID run,\n // instead of resolving that entry (and its blocked-upgrade explanation).\n _lastApiKey = config.apiKey || 'local';\n\n // A re-init for the same key (HMR, consent toggle, provider remount) supersedes\n // the prior client. Dispose it first so its queue's setInterval and\n // visibilitychange/pagehide listeners don't leak — the map only ever held its\n // config, so without this the old client kept flushing forever.\n const prevEntry = _clients.get(config.apiKey || 'local');\n if (prevEntry?.dispose) {\n try {\n prevEntry.dispose();\n } catch {\n /* teardown must never throw on re-init */\n }\n }\n\n // DNT/GPC (a global opt-out) or an explicit `consent: false` must be evaluated\n // BEFORE the local-mode branch: createLocalModeClient() calls initSession()\n // unconditionally, so a gated visitor would otherwise be issued the 365-day\n // `_snt_uid` identity cookie in keyless/local mode (audit P2). DNT/GPC also\n // gates tracking off even when the site passes `consent: true`, and blocks\n // `grantConsent()` from upgrading.\n const dntBlocked = config.respectDoNotTrack !== false && isDoNotTrackEnabled();\n const gated = config.consent === false || dntBlocked;\n\n // Keyless local mode. `localMode: true` forces the local engine (documented\n // escape hatch); 'auto' (default) engages it only when no valid key is\n // present. In production builds `@sentientui/core/local` resolves to a stub\n // and this degrades to a no-op client + one console.error per page load\n // (createLocalModeClient handles that), so no NODE_ENV check is needed here.\n const keyValid = typeof config.apiKey === 'string' && config.apiKey.startsWith('pk_');\n if (config.localMode === true || (!keyValid && config.localMode !== false)) {\n // One registration for both arms (they used to duplicate this set call).\n // upgrade stays null — there is no hosted client to swap in — but the\n // reason lets grantConsent() explain that instead of no-oping silently.\n _clients.set(config.apiKey || 'local', {\n config,\n upgrade: null,\n upgradeBlockedReason:\n '[sentient] grantConsent(): this client is keyless/local — there is no hosted client to upgrade to. Configure a pk_ API key to enable tracking.',\n });\n // A gated visitor must never get the identity cookie. Local mode has no\n // server to serve a statistical winner from, so return a plain no-op.\n if (gated) return SSR_CLIENT;\n return createLocalModeClient(config);\n }\n\n if (gated) {\n if (!config.apiKey || !config.apiKey.startsWith('pk_')) {\n if (config.preConsentBehavior === 'statistical_winner') {\n console.warn('[sentient] init() called with an invalid apiKey — expected a pk_ public key. SDK disabled.');\n }\n // Registered under the same 'local' fallback key the local branch uses:\n // `config.apiKey` here can be '', and a ''-keyed entry was unreachable\n // by a no-arg grantConsent() (falsy `_lastApiKey`), which then wrongly\n // warned \"called before init()\".\n _clients.set(config.apiKey || 'local', {\n config,\n upgrade: null,\n upgradeBlockedReason:\n '[sentient] grantConsent(): the client was initialized with an invalid apiKey (expected a pk_ public key) — consent cannot enable tracking.',\n });\n return SSR_CLIENT;\n }\n // Every gated client gets an upgradeable proxy, not just the winner-serving\n // one — otherwise grantConsent() is silently dead for the 'control' default\n // and the site has to reload to start tracking. Control mode still makes no\n // request; the proxy only exists so consent can swap the inner client.\n const { proxy, setInner } = createPreConsentProxy(config);\n // Under DNT the read-only winner still serves, but consent can never\n // upgrade it to tracking — so drop the upgrade hook.\n _clients.set(config.apiKey, { config, upgrade: dntBlocked ? null : setInner });\n return proxy;\n }\n\n if (!config.apiKey || !config.apiKey.startsWith('pk_')) {\n console.warn('[sentient] init() called with an invalid apiKey — expected a pk_ public key. SDK disabled.');\n return SSR_CLIENT;\n }\n\n if (config.ingestUrl === '') {\n console.warn('[sentient] init() called with an empty ingestUrl. SDK disabled.');\n return SSR_CLIENT;\n }\n\n const resolvedIngestUrl = config.ingestUrl ?? DEFAULT_INGEST_URL;\n\n const sessionStart = Date.now();\n const session = initSession({ ssrSessionId: config.ssrSessionId, apiKey: config.apiKey });\n const assignmentCache = createAssignmentCache(undefined, config.apiKey);\n const eventQueue = createEventQueue({ ingestUrl: resolvedIngestUrl, apiKey: config.apiKey });\n const baseUrl = deriveBaseUrl(resolvedIngestUrl);\n\n const authHeaders = {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${config.apiKey}`,\n } as const;\n\n // Conversions get the same durable transport the event queue has always had:\n // retry with backoff, a cross-reload bucket, dedupe on the server's goalId.\n // One warning per distinct drop status per page load (see onDrop below).\n const warnedDropStatuses = new Set<number>();\n const goalQueue: GoalQueue = createGoalQueue({\n url: `${baseUrl}/goals`,\n apiKey: config.apiKey,\n headers: authHeaders,\n onDrop: (goal, status) => {\n // NOT debug-gated. CONTRACTS §7 says a dropped goal is reported to the\n // developer and never swallowed, but this returned early unless debug was\n // on — so in production a rate-limited or misconfigured project lost every\n // conversion with no signal anywhere. Warn once per (status, page load):\n // enough to be discoverable in a console or an error reporter, quiet\n // enough that a broken integration cannot flood the page.\n if (!config.debug) {\n if (warnedDropStatuses.has(status)) return;\n warnedDropStatuses.add(status);\n }\n console.warn(\n `[sentient] goal dropped (HTTP ${status}) — this will not be retried. ` +\n (status === 400\n ? 'The session was not found: call init() and let the session upsert complete before firing goals.'\n : status === 401 || status === 403\n ? 'Check the API key and that this origin is on the project allowlist.'\n : 'See the response status for the cause.'),\n goal,\n );\n },\n });\n\n const deviceClass = detectDeviceClass(navigator.userAgent ?? '');\n // No window guard here: init() already returned SSR_CLIENT at the top when\n // window is undefined, so the old `typeof window` ternary was dead code.\n const appOrigin = window.location.origin;\n const trafficSource = detectTrafficSource(document.referrer ?? '', appOrigin);\n const sessionSegment =\n config.sessionSegment ?? `${deviceClass}:${trafficSource}`;\n const inflightAssigns = new Map<string, Promise<AssignResult | null>>();\n // Mirrors inflightAssigns for decide(): per-slot lazy-decide patterns (see\n // local-mode's merge comment — one decide({ slots: [decl] }) per mounted\n // slot, all in the same tick) otherwise issue N roundtrips and N snapshot\n // rewrites for one page. Keyed by the full request payload, never just \"a\n // decide is running\": coalescing {slots:[a]} with {slots:[b]} would hand\n // slot b's caller an outcome that never decided b.\n const inflightDecides = new Map<string, Promise<DecideOutcome | null>>();\n\n // --- Adaptive-slot state (decide) ---\n // Results served for this session, keyed by slot id. Written by decide();\n // read by getSlotResult() (Task 3.3) and componentGoal's slot fallback.\n const slotStore = new Map<string, SlotResult>();\n let personaState: { persona: string; confidence: number } | null = null;\n\n // On decide failure every declared slot must still resolve — to its baseline.\n // Never overwrite a previously served result.\n const seedSlotBaselines = (decls: SlotDeclInput[]): void => {\n for (const d of decls) {\n if (!slotStore.has(d.id)) slotStore.set(d.id, baselineResultFor(d));\n }\n };\n\n // Seed slot/persona state. Priority: explicit SSR seeds → snapshot.\n if (config.initialSlots) {\n for (const [slotId, result] of Object.entries(config.initialSlots)) {\n slotStore.set(slotId, result);\n }\n }\n const seedSnapshot = readSnapshot(config.apiKey);\n if (seedSnapshot) {\n for (const [slotId, result] of Object.entries(seedSnapshot.slots)) {\n if (!slotStore.has(slotId)) slotStore.set(slotId, result);\n }\n }\n\n // Band-only persona sources (html attrs, snapshot) become a band-consistent\n // numeric confidence so confidenceBand(confidence) always equals the band.\n const BAND_CONFIDENCE: Record<string, number> = { low: 0.15, medium: 0.5, high: 0.85 };\n if (config.initialPersona) {\n personaState = { ...config.initialPersona };\n } else {\n // Single-writer rule: the inline pre-paint script owns the <html>\n // attributes. The client ADOPTS them as truth and never rewrites them\n // mid-session (next visit's script picks up the new snapshot instead).\n const ds = document.documentElement.dataset;\n if (ds.sentientPersona) {\n personaState = {\n persona: ds.sentientPersona,\n confidence: BAND_CONFIDENCE[ds.sentientConfidence ?? 'low'] ?? 0.15,\n };\n } else if (seedSnapshot) {\n personaState = {\n persona: seedSnapshot.persona,\n confidence: BAND_CONFIDENCE[seedSnapshot.band] ?? 0.15,\n };\n }\n }\n\n // Seed SSR-preloaded assignments into the local cache so assign() finds a\n // cache hit immediately — no network call, no variant flash on hydration.\n if (config.initialAssignments) {\n for (const [componentId, variantId] of Object.entries(config.initialAssignments)) {\n assignmentCache.set(componentId, sessionSegment, {\n variantId,\n assignedAt: Date.now(),\n segment: sessionSegment,\n confidence: 1,\n });\n }\n }\n\n // Upsert session metadata once on init. assign() awaits this promise so\n // the server isn't asked to assign for a session row that doesn't exist yet.\n let sessionReady: Promise<void> = Promise.resolve();\n\n const sessionId = session.getSessionId();\n if (sessionId) {\n const referrerDomain = referrerDomainFromReferer(document.referrer ?? '');\n const { utmParams, clickIds } = readTrackedParams();\n const sessionBody = {\n sessionId,\n deviceClass,\n trafficSource,\n referrerDomain,\n utmParams,\n // Ad-platform click IDs (gclid & co). Captured separately from utmParams\n // because Google Ads auto-tagging appends ONLY gclid — without this,\n // paid search with no manual UTM template reported as organic.\n clickIds,\n timeOfDay: detectTimeOfDay(new Date()),\n dayOfWeek: ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'][new Date().getDay()],\n ephemeral: session.isEphemeral(),\n // Likely-automation hint: navigator.webdriver (set under automation\n // control) or a known agent token in the UA. Probabilistic — used for\n // metrics + bandit exclusion server-side, never to change what's served.\n automation:\n (typeof navigator !== 'undefined' && navigator.webdriver === true) ||\n uaTokenMatch(navigator.userAgent ?? ''),\n ...(config.userId ? { userId: config.userId } : {}),\n ...(config.persona ? { persona: config.persona } : {}),\n ...(config.country ? { country: config.country } : {}),\n };\n // The session row is a PRECONDITION for every conversion: /v1/goals answers\n // 400 session_not_found without it, and the durable queue classifies a 4xx\n // as terminal — so a session upsert that fails silently turns every later\n // conversion into a permanent drop. That is not hypothetical: /v1/sessions\n // carries the same per-IP limiter as /v1/goals, so under shared egress\n // (offices, mobile carriers, corporate NAT) the SESSION call 429s first and\n // the goals that follow are dropped for good. Retry it, so a transient\n // failure costs a moment rather than the visit's whole conversion history.\n const upsertSession = async (): Promise<undefined> => {\n for (let attempt = 0; ; attempt++) {\n try {\n const res = await fetch(`${baseUrl}/sessions`, {\n method: 'POST',\n keepalive: true,\n body: JSON.stringify(sessionBody),\n headers: authHeaders,\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 return undefined; // terminal: retrying a quota will not clear it\n }\n if (res.ok || classifyResponse(res) === 'dropped') return undefined;\n } catch {\n /* network failure — same retry path as a 5xx */\n }\n if (attempt >= SESSION_UPSERT_RETRIES) {\n // Say so once: from here every conversion this visit will 400, and\n // that used to be entirely silent.\n console.warn(\n '[SentientUI] Could not register the session after retries. Conversions in this visit may not be recorded.',\n );\n return undefined;\n }\n await new Promise((r) => setTimeout(r, backoffDelayMs(attempt + 1)));\n }\n };\n try {\n sessionReady = upsertSession();\n } catch {\n /* never throw on init */\n }\n }\n\n if (config.debug) {\n console.log('[sentient] initialized', { context: config.context });\n (\n window as unknown as {\n __sentient?: {\n client: SentientClient;\n queue: EventQueue;\n };\n }\n ).__sentient = {\n client: null as unknown as SentientClient,\n queue: eventQueue,\n };\n }\n\n // One user action must record ONE session-level conversion per goal name.\n // Nested components each fire their declared goal on the same click (every\n // <Adaptive>/hook path calls componentGoal() AND goal()), so a hero nested\n // inside a CTA wrapper wrote two goal_events rows for one click: harmless for\n // a weight-1.0 goal (close-out clamps at 1) but a 0.3-weight step summed to\n // 0.6, and the Goals page counts Hits as COUNT(*) either way.\n //\n // The scope is one event dispatch, not one session and no longer one task:\n // see createActionLatch. A session-wide latch would swallow genuine repeat\n // conversions (two purchases in one visit are two conversions), and a\n // time-boxed one did exactly that whenever the box outlived the action.\n // Calls carrying distinct externalIds are never collapsed — those are, by\n // definition, distinct orders.\n const firedThisAction = createActionLatch();\n\n // Set once tracking starts; dispose() and destroy() call it so a replaced\n // client stops watching history instead of emitting forever. The flag records\n // teardown for the delivery-marking below, which runs on a later microtask.\n let stopPageviews: (() => void) | null = null;\n let pageviewsTornDown = false;\n\n const client: SentientClient = {\n goal(name: string, metadataOrOpts: Record<string, unknown> = {}, weight = 1.0, stepIndex = 0) {\n const sid = session.getSessionId();\n if (!sid) return;\n const opts: GoalOptions = isGoalOptions(metadataOrOpts)\n ? (metadataOrOpts as GoalOptions)\n : { metadata: metadataOrOpts };\n // stepIndex and weight are part of the key: funnel steps share a goal\n // name and differ by stepIndex, so collapsing on name alone dropped a\n // step fired in the same handler. Only IDENTICAL calls are one action.\n //\n // value and currency key the payload SEPARATELY (the latch's valueKey),\n // not as more segments of the flat key, and for a costlier reason: they\n // are the money. Flattened out of the key entirely, a $50 order and a\n // $70 order landing in one window collapsed into a single $50 record —\n // the client half of CONTRACTS §1 \"two orders are worth two orders\",\n // which the server already honours (migration 119 records the repeat if\n // it arrives; this is what stopped it arriving). But flattened INTO the\n // key, a valued inner component nested in a valueless wrapper made two\n // keys out of one click — two rows for one order. So the latch compares\n // values only between valued fires ($50 vs $70 stays two records) and\n // lets a valued record absorb a valueless re-fire of the same action\n // (see createActionLatch for the one asymmetric case).\n //\n // NOT metadata: every nested <Adaptive>/hook path stamps its own\n // componentId and variantId in there, so keying on it would make the\n // duplicate this latch exists to collapse look distinct again.\n const actionKey = [\n name,\n opts.externalId ?? '',\n opts.stepIndex ?? stepIndex,\n opts.weight ?? weight,\n ].join('\\0');\n const valueKey = opts.value !== undefined ? `${opts.value}\\0${opts.currency ?? ''}` : null;\n if (firedThisAction.firedBefore(actionKey, valueKey)) {\n if (config.debug) {\n console.log(`[sentient] goal(\"${name}\") already recorded for this action — not sent twice`);\n }\n return;\n }\n const goalId = generateEventId();\n // undefined values vanish at JSON.stringify time, so optional fields\n // need no conditional assembly.\n const body = {\n sessionId: sid,\n name,\n metadata: opts.metadata ?? {},\n weight: opts.weight ?? weight,\n stepIndex: opts.stepIndex ?? stepIndex,\n goalId,\n value: opts.value,\n currency: opts.currency,\n externalId: opts.externalId,\n };\n if (config.debug) {\n console.log('[sentient] goal', body);\n }\n // Serialize once, here: the queued copy must replay byte-identically\n // (same goalId) so a retry dedupes server-side instead of double-counting.\n const payload = { id: goalId, body: JSON.stringify(body) };\n sessionReady.then(() => goalQueue.send(payload));\n },\n\n componentGoal(componentId, goalType, opts) {\n const sid = session.getSessionId();\n if (!sid) return;\n // Variant experiments resolve from the assignment cache; adaptive slots\n // (useAdaptiveTokens / AdaptiveGroup) resolve from the slot state, using\n // the canonical arm string as the attributed variantId.\n const assignment = assignmentCache.get(componentId, sessionSegment);\n const slotResult = assignment ? null : slotStore.get(componentId) ?? null;\n if (!assignment && slotResult === null) {\n if (config.debug) {\n console.warn(\n `[sentient] componentGoal(\"${componentId}\"): no assignment or slot decision yet — render its <Adaptive>/adaptive hook or call assign()/decide() before recording a goal.`,\n );\n }\n return;\n }\n const attributedVariantId = assignment ? assignment.variantId : armOfResult(slotResult!);\n const fullEvent: SentientEvent = {\n id: generateEventId(),\n sessionId: sid,\n projectId: config.apiKey,\n componentId,\n variantId: attributedVariantId,\n eventType: 'goal_achieved',\n goalType,\n // undefined goalValue/currency vanish at JSON.stringify time.\n payload: {\n reward: opts?.reward ?? 1,\n goalValue: opts?.value,\n currency: opts?.currency,\n ...(opts?.metadata ?? {}),\n },\n timestamp: Date.now(),\n timeInSession: Date.now() - sessionStart,\n path: currentPath(),\n };\n if (config.debug) {\n console.log('[sentient] componentGoal', fullEvent);\n }\n sessionReady.then(() => eventQueue.push(fullEvent));\n },\n\n identify(userId) {\n const sid = session.getSessionId();\n if (!sid) return;\n sessionReady.then(() => {\n fetch(`${baseUrl}/sessions`, {\n method: 'POST',\n keepalive: true,\n body: JSON.stringify({ sessionId: sid, userId, ephemeral: session.isEphemeral() }),\n headers: authHeaders,\n }).catch(() => undefined);\n });\n },\n\n track(event) {\n const sessionId = session.getSessionId();\n if (!sessionId) return;\n\n const fullEvent: SentientEvent = {\n // `path` first so an explicit event.path from the caller wins over the\n // ambient one — a server-side or replayed event knows its page better\n // than location does.\n path: currentPath(),\n ...event,\n id: generateEventId(),\n sessionId,\n timestamp: Date.now(),\n timeInSession: Date.now() - sessionStart,\n };\n\n if (config.debug) {\n console.log('[sentient] track', fullEvent);\n }\n\n sessionReady.then(() => eventQueue.push(fullEvent));\n },\n\n getAssignment(componentId, segment) {\n return assignmentCache.get(componentId, segment);\n },\n\n async assign(componentId, variantIds, agentData?, agentDataByVariant?) {\n const sid = session.getSessionId();\n if (!sid) return null;\n\n const cached = assignmentCache.get(componentId, sessionSegment);\n // When variantIds are provided (A/B code variant), a cache hit is always final.\n // When variantIds are absent (managed text component), only hit the cache if content\n // is present — a seed from initialAssignments has no content and must still fetch.\n if (cached && (variantIds?.length || cached.content !== undefined)) {\n // Surface the entry's remaining TTL (server-provided when set) instead of\n // a hardcoded 0, so callers can reason about when a re-assign is due.\n const remainingTtlMs =\n cached.ttlMs && cached.ttlMs > 0\n ? Math.max(0, cached.assignedAt + cached.ttlMs - Date.now())\n : 0;\n return { variantId: cached.variantId, assignmentTtlMs: remainingTtlMs, content: cached.content };\n }\n\n // Coalesce concurrent assigns for the same component (e.g. several\n // mounted slots sharing one id) into a single network request.\n return coalesce(inflightAssigns, componentId, async () => {\n await sessionReady;\n try {\n const body: Record<string, unknown> = { sessionId: sid, componentId, variantIds };\n if (agentDataByVariant !== undefined) body.agentDataByVariant = agentDataByVariant;\n else if (agentData !== undefined) body.agentData = agentData;\n const res = await fetch(`${baseUrl}/assign`, {\n method: 'POST',\n body: JSON.stringify(body),\n headers: authHeaders,\n });\n if (!res.ok) return null;\n const result = (await res.json()) as AssignResult;\n assignmentCache.set(componentId, sessionSegment, {\n variantId: result.variantId,\n assignedAt: Date.now(),\n segment: sessionSegment,\n confidence: 1,\n content: result.content,\n // Honor the server's TTL as this entry's expiry; omit when absent/0\n // so the cache falls back to its default (DEFAULT_TTL_MS).\n ...(result.assignmentTtlMs && result.assignmentTtlMs > 0\n ? { ttlMs: result.assignmentTtlMs }\n : {}),\n });\n return result;\n } catch {\n return null;\n }\n });\n },\n\n async decide(input) {\n const sid = session.getSessionId();\n if (!sid) return null;\n const declared = input.slots ?? [];\n\n const body: Record<string, unknown> = { sessionId: sid };\n if (input.sections && input.sections.length > 0) {\n body.sections = input.sections.map((id) => ({ id }));\n }\n body.components = input.components ?? [];\n if (declared.length > 0) body.slots = declared.map(toWireSlot);\n if (input.slotsFrom === 'registry') body.slotsFrom = 'registry';\n if (input.v) body.v = input.v;\n // Declared persona rides on decide too: SSR-first flows can race the\n // session upsert, and the decide-body value wins for this decision.\n if (config.persona) body.persona = config.persona;\n\n // Coalesce concurrent IDENTICAL decides into one request + one snapshot\n // write, keyed by the serialized wire payload (also reused as the fetch\n // body). Never key on just \"a decide is running\": coalescing {slots:[a]}\n // with {slots:[b]} would hand slot b's caller an outcome that never\n // decided b. The wire projection is a safe key even though toWireSlot\n // strips SDK-only decl fields — the baselines synthesized for omitted\n // slots below go through baselineResultFor, which projects with the\n // same toWireSlot, so identical payloads imply identical outcomes.\n const decideKey = JSON.stringify(body);\n return coalesce(inflightDecides, decideKey, async () => {\n await sessionReady;\n try {\n const res = await fetch(`${baseUrl}/decide`, {\n method: 'POST',\n body: decideKey,\n headers: authHeaders,\n });\n if (!res.ok) {\n seedSlotBaselines(declared);\n return null;\n }\n const data = (await res.json()) as {\n layoutOrder?: string[] | null;\n assignments?: Record<string, string>;\n slots?: Record<string, SlotResult>;\n slotConfig?: Record<string, SlotConfigEntry>;\n goals?: GoalDefinition[];\n sectionMap?: SectionMapEntry[];\n palette?: import('./blocks.js').SitePalette;\n persona?: string;\n confidence?: number;\n };\n\n const slots: Record<string, SlotResult> = {};\n for (const d of declared) {\n // `data.slots === undefined` means the server predates the slots\n // contract: serve the declared baseline everywhere, do NOT retry.\n // (Distinct from `slots: {}`, which also falls back per-slot.)\n const served = data.slots?.[d.id];\n if (served !== undefined) {\n slots[d.id] = served;\n slotStore.set(d.id, served);\n continue;\n }\n // Slot omitted from the response → synthesize a baseline for the\n // RETURN value, but apply the same never-overwrite rule the failure\n // path (seedSlotBaselines) has always had. This success path used\n // to write unconditionally, so a partial response — or a pre-slots\n // server — clobbered SSR-seeded and previously-served results with\n // synthetic baselines.\n const prior = slotStore.get(d.id);\n if (prior !== undefined) {\n slots[d.id] = prior;\n } else {\n const baseline = baselineResultFor(d);\n slots[d.id] = baseline;\n slotStore.set(d.id, baseline);\n }\n }\n // Registry mode: the server returns slots the request never declared.\n // Take them verbatim (classic mode returns only declared slots, so this\n // union is a no-op there — back-compatible). These are real served\n // results, so they may overwrite the store, unlike the baselines above.\n if (data.slots) {\n for (const [slotId, result] of Object.entries(data.slots)) {\n if (!(slotId in slots)) {\n slots[slotId] = result;\n slotStore.set(slotId, result);\n }\n }\n }\n // Only overwrite persona when the response actually carries one, and\n // never downgrade a known persona to 'unknown' — a decide that omits\n // persona (or returns 'unknown') must not clobber a good SSR/snapshot/\n // initialPersona value, and must not persist that regression below.\n const known = personaState != null && personaState.persona !== 'unknown';\n if (data.persona && !(data.persona === 'unknown' && known)) {\n personaState = { persona: data.persona, confidence: data.confidence ?? 0 };\n } else if (!personaState) {\n personaState = { persona: 'unknown', confidence: 0 };\n }\n\n // Seed component assignments so <Adaptive>/assign() agree with this\n // decide (same shape as the initialAssignments seed above).\n for (const [componentId, variantId] of Object.entries(data.assignments ?? {})) {\n assignmentCache.set(componentId, sessionSegment, {\n variantId,\n assignedAt: Date.now(),\n segment: sessionSegment,\n confidence: 1,\n });\n }\n\n // Persist for the next visit's pre-paint (SPA cache-first pattern).\n writeSnapshot(config.apiKey, {\n v: 1,\n persona: personaState.persona,\n band: confidenceBand(personaState.confidence),\n slots: Object.fromEntries(slotStore),\n layoutOrder: data.layoutOrder ?? null,\n savedAt: Date.now(),\n ...(data.slotConfig ? { slotConfig: data.slotConfig } : {}),\n ...(data.palette ? { palette: data.palette } : {}),\n });\n\n return {\n layoutOrder: data.layoutOrder ?? null,\n assignments: data.assignments ?? {},\n slots,\n persona: personaState.persona,\n confidence: personaState.confidence,\n ...(data.slotConfig ? { slotConfig: data.slotConfig } : {}),\n ...(data.goals ? { goals: data.goals } : {}),\n ...(data.sectionMap ? { sectionMap: data.sectionMap } : {}),\n ...(data.palette ? { palette: data.palette } : {}),\n };\n } catch {\n seedSlotBaselines(declared);\n return null;\n }\n });\n },\n\n getSlotResult(slotId) {\n return slotStore.get(slotId) ?? null;\n },\n\n getPersona() {\n if (!personaState) return null;\n return {\n persona: personaState.persona,\n confidence: personaState.confidence,\n band: confidenceBand(personaState.confidence),\n };\n },\n\n async fetchWeights() {\n try {\n const res = await fetch(`${baseUrl}/weights`, { headers: authHeaders });\n if (!res.ok) return [];\n const data = (await res.json()) as { components: ComponentWeightEntry[] };\n return data.components ?? [];\n } catch {\n return [];\n }\n },\n\n getGraph() {\n return { pageNodes: [], capturedAt: 0 };\n },\n\n dispose() {\n // Stops the flush timer and unload listeners (with a final flush) but\n // leaves identity, snapshot, and retry buckets for the next client.\n stopPageviews?.();\n pageviewsTornDown = true;\n eventQueue.destroy();\n goalQueue.destroy();\n // Drop the registry entry so a later re-init doesn't try to dispose an\n // already-torn-down client (and so the map doesn't pin this closure).\n if (_clients.get(config.apiKey)?.dispose === client.dispose) {\n _clients.delete(config.apiKey);\n }\n if (config.debug) {\n console.log('[sentient] disposed');\n }\n },\n\n destroy() {\n stopPageviews?.();\n pageviewsTornDown = true;\n eventQueue.destroy();\n goalQueue.destroy();\n session.destroy();\n // The assignment cache persists in localStorage (`_snt_asgn_*`) with a\n // 30-minute default TTL — left in place, a revoked visitor returning\n // within that window was handed their previous personalized variants\n // back, so forget-me wasn't total.\n assignmentCache.clear();\n if (_clients.get(config.apiKey)?.dispose === client.dispose) {\n _clients.delete(config.apiKey);\n }\n // Forget-me must be total: a surviving decision snapshot would\n // re-personalize the next visit via the pre-paint script, and a\n // persisted retry bucket would re-send events for the deleted identity.\n try {\n localStorage.removeItem(SNAPSHOT_STORAGE_KEY_PREFIX + config.apiKey);\n localStorage.removeItem(retryStorageKey(config.apiKey));\n localStorage.removeItem(goalRetryStorageKey(config.apiKey));\n } catch {\n /* storage unavailable — nothing persisted to remove */\n }\n if (config.debug) {\n console.log('[sentient] destroyed');\n }\n },\n };\n\n _clients.set(config.apiKey, { config, upgrade: null, dispose: client.dispose });\n\n stopPageviews = startPageviewTracking(client, config.apiKey, (key) => {\n // track() defers its enqueue on sessionReady; chaining after it means this\n // runs once the push has happened. If the client was torn down first, the\n // event went into a destroyed queue and never ships — leave the page\n // unmarked so the replacement client's emit is the one that counts.\n void sessionReady.then(() => {\n if (!pageviewsTornDown) emittedPages.add(key);\n });\n });\n\n if (config.debug) {\n const win = window as unknown as { __sentient?: { client: SentientClient } };\n if (win.__sentient) {\n win.__sentient.client = client;\n }\n }\n\n return client;\n}\n","export type MicroSignalEmitter = (\n signalType: 'rage_click' | 'text_copy' | 'scroll_hesitation' | 'tab_loss',\n extra?: Record<string, unknown>,\n) => void;\n\nexport type MicroSignalType = Parameters<MicroSignalEmitter>[0];\n\n/**\n * Attaches passive behavioral detectors to `node`. Calls `emit` when a signal\n * fires. Each signal type fires at most once per call to this function.\n * Returns a cleanup function that removes all listeners.\n */\nexport function attachMicroSignalDetectors(\n emit: MicroSignalEmitter,\n node: Element,\n variantAssignedAt?: number,\n options?: { tabLoss?: boolean },\n): () => void {\n const cleanups: Array<() => void> = [];\n\n // --- Rage click: 3+ clicks within 500ms ---\n {\n const WINDOW_MS = 500;\n const THRESHOLD = 3;\n let firedOnce = false;\n const timestamps: number[] = [];\n\n const onClick = (): void => {\n if (firedOnce) return;\n const now = Date.now();\n timestamps.push(now);\n while (timestamps.length > 0 && now - timestamps[0]! > WINDOW_MS) {\n timestamps.shift();\n }\n if (timestamps.length >= THRESHOLD) {\n firedOnce = true;\n emit('rage_click');\n }\n };\n\n node.addEventListener('click', onClick);\n cleanups.push(() => node.removeEventListener('click', onClick));\n }\n\n // --- Text copy: copy event within node ---\n {\n let firedOnce = false;\n\n const onCopy = (e: Event): void => {\n if (firedOnce) return;\n if (!(e.target instanceof Node)) return;\n if (!node.contains(e.target) && node !== e.target) return;\n firedOnce = true;\n const sel = typeof window !== 'undefined' ? window.getSelection() : null;\n const selectionLength = sel ? sel.toString().length : 0;\n emit('text_copy', { selectionLength });\n };\n\n document.addEventListener('copy', onCopy);\n cleanups.push(() => document.removeEventListener('copy', onCopy));\n }\n\n // --- Scroll hesitation: scroll stops 3s while component visible ---\n {\n let firedOnce = false;\n let isVisible = false;\n let hesitationTimer: ReturnType<typeof setTimeout> | null = null;\n\n const clearHesitation = (): void => {\n if (hesitationTimer !== null) {\n clearTimeout(hesitationTimer);\n hesitationTimer = null;\n }\n };\n\n const startHesitation = (): void => {\n if (firedOnce || !isVisible) return;\n clearHesitation();\n hesitationTimer = setTimeout(() => {\n if (!firedOnce && isVisible) {\n firedOnce = true;\n emit('scroll_hesitation');\n }\n }, 3000);\n };\n\n const onScroll = (): void => {\n clearHesitation();\n startHesitation();\n };\n\n const ioCallback = (entries: IntersectionObserverEntry[]): void => {\n for (const entry of entries) {\n isVisible = entry.intersectionRatio > 0.3;\n if (!isVisible) clearHesitation();\n else startHesitation();\n }\n };\n const io = new IntersectionObserver(ioCallback, { threshold: [0.3] });\n io.observe(node);\n window.addEventListener('scroll', onScroll, { passive: true });\n\n cleanups.push(() => {\n io.disconnect();\n window.removeEventListener('scroll', onScroll);\n clearHesitation();\n });\n }\n\n // --- Tab loss: tab hidden within 15s of variant_assigned ---\n // Document-level (not node-scoped), so callers that attach detectors to many\n // nodes at once (e.g. the snippet's per-option slot signals) can opt out on all\n // but one node to avoid emitting a duplicate tab_loss per node (audit M5).\n if (options?.tabLoss !== false) {\n let firedOnce = false;\n const assignedAt = variantAssignedAt ?? Date.now();\n\n const onVisibility = (): void => {\n if (firedOnce) return;\n if (document.visibilityState !== 'hidden') return;\n const elapsed = Date.now() - assignedAt;\n if (elapsed < 15_000) {\n firedOnce = true;\n emit('tab_loss', { timeOnPage: elapsed });\n }\n };\n\n document.addEventListener('visibilitychange', onVisibility);\n cleanups.push(() => document.removeEventListener('visibilitychange', onVisibility));\n }\n\n return () => {\n for (const c of cleanups) c();\n };\n}\n","import type { CompoundLocator } from './snapshot.js';\n\n// Live-DOM twin of apps/api/src/domain/locator-from-html.ts. The two MUST stay\n// in step: section_key is a hash of this object, so any divergence silently\n// splits one physical section into two identities — a crawl-derived one and a\n// client-derived one — and every per-section number downstream halves.\n// Cross-implementation parity is locked by apps/api/src/domain/locator-parity.test.ts.\nconst STABLE_DATA_ATTRS = ['data-testid', 'data-test', 'data-id', 'data-name', 'data-cy'];\nconst FINGERPRINT_TEXT_MAX = 40;\n\nfunction normalizedText(el: Element): string {\n return (el.textContent ?? '').replace(/\\s+/g, ' ').trim();\n}\n\nfunction fingerprintOf(el: Element): { tag: string; text: string } {\n return {\n tag: el.tagName.toLowerCase(),\n text: normalizedText(el).slice(0, FINGERPRINT_TEXT_MAX),\n };\n}\n\nfunction cssEscape(v: string): string {\n return v.replace(/[\"\\\\\\]]/g, '\\\\$&');\n}\n\nfunction unique(root: ParentNode, selector: string): boolean {\n try {\n return root.querySelectorAll(selector).length === 1;\n } catch {\n return false;\n }\n}\n\n/** Shortest unique selector: tag, tag.class, then parent-qualified, then nth-of-type chain. */\nfunction uniqueSelector(el: Element, root: ParentNode): string | null {\n const tag = el.tagName.toLowerCase();\n if (!tag) return null;\n const classes = (el.getAttribute('class') ?? '').split(/\\s+/).filter((c) => /^[a-zA-Z][\\w-]*$/.test(c));\n const candidates = [tag, ...classes.map((c) => `${tag}.${c}`)];\n for (const c of candidates) if (unique(root, c)) return c;\n const parent = el.parentElement;\n if (parent && (parent as ParentNode) !== root) {\n const parentSel = uniqueSelector(parent, root);\n if (parentSel) {\n for (const c of candidates) {\n const combined = `${parentSel} > ${c}`;\n if (unique(root, combined)) return combined;\n }\n // Element-only children: matches the server's rawTagName filter over\n // childNodes, which excludes text nodes.\n const siblings = Array.from(parent.children).filter((n) => n.tagName.toLowerCase() === tag);\n const idx = siblings.indexOf(el);\n // An nth-of-type selector is only trustworthy when it pairs with a\n // fingerprint that could actually catch drift: if every same-tag sibling\n // has identical text, the node is a true duplicate and the {tag, text}\n // check can never distinguish \"still the right one\" from \"DOM reordered,\n // now pointing at the wrong duplicate\". Refuse it rather than return a\n // false sense of precision.\n const distinguishable = siblings.some((s) => s !== el && normalizedText(s) !== normalizedText(el));\n if (idx >= 0 && distinguishable) {\n const nth = `${parentSel} > ${tag}:nth-of-type(${idx + 1})`;\n if (unique(root, nth)) return nth;\n }\n }\n }\n return null;\n}\n\n/** Build a compound locator for a live DOM element. Returns null when nothing\n * resolves uniquely — the runtime never guesses an identity. */\nexport function locatorFromElement(el: Element, root: ParentNode): CompoundLocator | null {\n const fingerprint = fingerprintOf(el);\n const id = el.getAttribute('id');\n if (id && unique(root, `#${cssEscape(id)}`)) return { v: 1, id, fingerprint };\n for (const name of STABLE_DATA_ATTRS) {\n const value = el.getAttribute(name);\n if (value && unique(root, `[${name}=\"${cssEscape(value)}\"]`)) {\n return { v: 1, dataAttr: { name, value }, fingerprint };\n }\n }\n const selector = uniqueSelector(el, root);\n if (selector) return { v: 1, selector, fingerprint };\n return null;\n}\n","import { classifySection, SEMANTIC_TYPES, type SemanticType } from './classify';\nimport { isDoNotTrackEnabled } from '../index.js';\nimport { attachMicroSignalDetectors } from '../micro-signals.js';\nimport { locatorFromElement } from '../locator-from-dom.js';\n\n// Shared engagement capture (spec 2026-07-22-persona-signal-capture). Detects\n// semantic sections, registers them via /v1/section-map, and records per-section\n// dwell/scroll via IntersectionObserver — emitting the same 'dwell' events the\n// persona pipeline consumes. Used by the React provider (default on) and the\n// no-code snippet. Defense-in-depth: checks DNT internally even though callers\n// gate on consent/DNT too; a missing IntersectionObserver → no-op.\n\ntype CaptureClient = {\n track(event: { projectId: string; componentId: string; eventType: string; payload: Record<string, unknown> }): void;\n};\n\nexport type EngagementCaptureOptions = {\n apiKey: string;\n /** API base, no trailing slash. Defaults to the hosted API. */\n apiBase?: string;\n doc?: Document;\n /**\n * Also attach per-section micro-signal detectors (rage click, text copy,\n * scroll hesitation, tab loss), attributed to the section's `nc-<type>`\n * component. For the no-code snippet, whose pages have no `<Adaptive>`\n * components carrying their own detectors. Default false — the React SDK\n * keeps its per-component detectors and must not double-attach.\n */\n microSignals?: boolean;\n /**\n * Server-served section-map lookup (persona-coverage auto-classification):\n * consulted after explicit `data-sentient-type` markup, before the local\n * heuristic. Return null when the element has no served label.\n */\n typeOf?: (el: Element) => SemanticType | null;\n};\n\nconst SECTION_SELECTOR = 'section, header, footer, nav, main > div, [data-sentient-section]';\n\n/** Bank cadence for visible dwell. Dwell used to leave the page only on\n * visibilitychange/pagehide, and in production that path delivered for ~5-8%\n * of sessions (Bodyshop audit 2026-08-30): a visitor who reads and closes the\n * tab races the unload pipeline, and mobile browsers can kill a page with no\n * lifecycle event at all. The heartbeat caps the loss at one interval. */\nconst HEARTBEAT_MS = 20_000;\n\n/**\n * Pick the elements to observe. Two rules, in order:\n * 1. A candidate that CONTAINS two or more other candidates is a layout\n * wrapper, not a section — drop it. Pages built from bare divs match\n * `main > div` with their page-wide content wrapper; keeping that outer\n * match swallowed every real <section> inside it, collapsing the whole page\n * into one nc-generic component whose intersectionRatio could never exceed\n * viewport-height / page-height (a constant ~0.05 scroll_depth on the\n * audited site). A candidate with exactly one nested candidate (header >\n * nav) is NOT a wrapper — rule 2 keeps the outer one, as before.\n * 2. Of what remains, skip a section nested inside another kept section\n * (avoid double count).\n */\nfunction selectSections(doc: Document): Element[] {\n const candidates = Array.from(doc.querySelectorAll(SECTION_SELECTOR));\n const kept = candidates.filter(\n (el) => candidates.filter((c) => c !== el && el.contains(c)).length < 2,\n );\n return kept.filter((el) => !kept.some((k) => k !== el && k.contains(el)));\n}\n\nfunction registerSections(\n apiKey: string,\n apiBase: string,\n pageUrl: string,\n sections: Array<{\n componentId: string;\n semanticType: SemanticType;\n source: 'markup' | 'auto';\n locator?: unknown;\n }>,\n): void {\n try {\n void fetch(`${apiBase}/v1/section-map`, {\n method: 'POST',\n keepalive: true,\n headers: { 'content-type': 'application/json', authorization: `Bearer ${apiKey}` },\n body: JSON.stringify({ pageUrl, sections }),\n }).catch(() => undefined);\n } catch {\n /* fail-safe */\n }\n}\n\nconst NOOP = (): void => undefined;\n\nexport function startEngagementCapture(\n client: CaptureClient,\n opts: EngagementCaptureOptions,\n): () => void {\n const doc = opts.doc ?? (typeof document !== 'undefined' ? document : undefined);\n if (!doc || typeof IntersectionObserver === 'undefined') return NOOP;\n if (isDoNotTrackEnabled()) return NOOP;\n // Keyless zero-network contract: capture exists to feed the hosted persona\n // pipeline — with no api key there is nothing to feed, and the section-map\n // registration fetch must never fire. Same validity rule as init() and the\n // graph entry: this used to check truthiness only, so an invalid non-`pk_`\n // (typo'd) key still fired /v1/section-map registration and dwell events\n // into a client that discards everything.\n if (!opts.apiKey || !opts.apiKey.startsWith('pk_')) return NOOP;\n // Normalize so both a ROOT base (`https://api.sentient-ui.com`) and a\n // `/v1`-suffixed base resolve to exactly one `/v1/section-map` — some callers\n // pass the versioned base, which would otherwise produce `/v1/v1/section-map`\n // (a silent 404). Strip trailing slashes, then a single trailing `/v1`.\n const apiBase = (opts.apiBase ?? 'https://api.sentient-ui.com')\n .replace(/\\/+$/, '')\n .replace(/\\/v1$/, '');\n\n const els = selectSections(doc);\n if (els.length === 0) return NOOP;\n\n // Collapse to one component per semantic type per page (the matrix aggregates\n // by semantic type anyway). Per-element precedence: explicit data-sentient-type\n // markup → served section map (opts.typeOf) → local heuristic.\n const componentOf = new Map<Element, string>();\n // One entry PER ELEMENT for the section map, even though componentId still\n // collapses by type. The server derives a distinct section_key from each\n // locator, so a page whose bands all classify `generic` still gets one\n // identity per band instead of a single nc-generic covering all of them.\n // Dwell keeps keying on the collapsed componentId — that is unchanged here.\n const entries: Array<{\n componentId: string;\n semanticType: SemanticType;\n source: 'markup' | 'auto';\n locator?: unknown;\n }> = [];\n for (const el of els) {\n const explicit = el.getAttribute('data-sentient-type');\n const markup = explicit && (SEMANTIC_TYPES as readonly string[]).includes(explicit)\n ? (explicit as SemanticType)\n : null;\n const type = markup ?? opts.typeOf?.(el) ?? classifySection(el);\n const componentId = `nc-${type}`;\n componentOf.set(el, componentId);\n // `source` is now per ELEMENT, not per collapsed component. Previously,\n // markup on any one element made the whole collapsed component report as\n // 'markup'; with one row per section the server can record each section's\n // real provenance instead of the most-confident of its siblings'.\n const locator = locatorFromElement(el, doc);\n entries.push({\n componentId,\n semanticType: type,\n source: markup ? 'markup' : 'auto',\n ...(locator ? { locator } : {}),\n });\n }\n\n const pageUrl = (doc.defaultView ?? (typeof window !== 'undefined' ? window : undefined))?.location?.pathname ?? '/';\n registerSections(opts.apiKey, apiBase, pageUrl, entries);\n\n // Accumulate visible dwell (ms) + max scroll ratio per component. `intersecting`\n // tracks in-viewport state independently of `enterAt` (the running clock) so a\n // tab-hide can pause the clock and a tab-show can resume it for still-visible\n // sections — IntersectionObserver does not re-fire on visibilitychange.\n const state = new Map<string, { ms: number; scroll: number; enterAt: number | null; intersecting: boolean }>();\n const get = (id: string) => {\n let s = state.get(id);\n if (!s) { s = { ms: 0, scroll: 0, enterAt: null, intersecting: false }; state.set(id, s); }\n return s;\n };\n\n const observer = new IntersectionObserver((entries) => {\n for (const entry of entries) {\n const id = componentOf.get(entry.target);\n if (!id) continue;\n const s = get(id);\n if (entry.isIntersecting) {\n s.intersecting = true;\n s.enterAt = Date.now();\n if (entry.intersectionRatio > s.scroll) s.scroll = entry.intersectionRatio;\n } else {\n s.intersecting = false;\n if (s.enterAt != null) { s.ms += Date.now() - s.enterAt; s.enterAt = null; }\n }\n }\n }, { threshold: [0, 0.25, 0.5, 0.75, 1] });\n for (const el of componentOf.keys()) observer.observe(el);\n\n // Bank accumulated dwell and RESET the accumulators (so a later emit can't\n // double-count) WITHOUT disconnecting — a visitor who hides/re-shows the tab\n // or tab-switches keeps being measured. Pauses the running clock; the tab-show\n // handler restarts it for still-visible sections so hidden time isn't counted.\n const emit = (): void => {\n const now = Date.now();\n for (const [id, s] of state) {\n if (s.enterAt != null) { s.ms += now - s.enterAt; s.enterAt = null; }\n if (s.ms <= 0) continue;\n try {\n client.track({\n projectId: opts.apiKey, // SDK convention: server derives the real project from the key\n componentId: id,\n eventType: 'dwell',\n payload: { dwell_time: Math.round(s.ms), scroll_depth: Number(s.scroll.toFixed(2)) },\n });\n } catch {\n /* fail-safe */\n }\n s.ms = 0;\n }\n };\n\n const onVisibility = (): void => {\n if (doc.hidden) {\n emit(); // bank + pause\n } else {\n const now = Date.now(); // resume the clock for sections still on screen\n for (const s of state.values()) if (s.intersecting) s.enterAt = now;\n }\n };\n // A page can be FROZEN into the bfcache rather than torn down. Timers keep\n // firing on restore, and `intersecting` still holds whatever it held at\n // pagehide — so without this the heartbeat kept banking dwell for sections the\n // visitor had scrolled far past, forever, while the observer that could have\n // corrected them had been disconnected. Freeze the clocks instead, and only\n // tear down for real when the page is genuinely going away.\n let frozen = false;\n const onPageHide = (event?: { persisted?: boolean }): void => {\n emit(); // bank whatever is measured either way\n if (event?.persisted) {\n frozen = true; // bfcache: keep the observer, stop counting\n return;\n }\n try { observer.disconnect(); } catch { /* ignore */ }\n };\n const onPageShow = (event?: { persisted?: boolean }): void => {\n if (!event?.persisted || !frozen) return;\n frozen = false;\n // The observer stayed connected, so it will correct `intersecting` for\n // anything that moved. Restart clocks only for what is on screen NOW.\n const now = Date.now();\n for (const s of state.values()) s.enterAt = s.intersecting && !doc.hidden ? now : null;\n };\n doc.addEventListener('visibilitychange', onVisibility);\n const win = doc.defaultView ?? (typeof window !== 'undefined' ? window : undefined);\n win?.addEventListener('pagehide', onPageHide);\n win?.addEventListener('pageshow', onPageShow);\n\n // See HEARTBEAT_MS: bank visible dwell periodically so a hard close (or a\n // mobile page kill) loses at most one interval instead of the whole visit.\n // Hidden tabs skip the emit — their clock is already paused, and an empty\n // state map makes emit a no-op anyway.\n const heartbeat = setInterval(() => {\n if (doc.hidden || frozen) return;\n emit();\n // emit() pauses every running clock and only the tab-show handler restarts\n // them — here the page never went hidden, so restart the clock ourselves\n // or accumulation silently stops after the first heartbeat.\n const now = Date.now();\n for (const s of state.values()) if (s.intersecting) s.enterAt = now;\n }, HEARTBEAT_MS);\n\n // Per-section micro-signal detectors (opt-in; see EngagementCaptureOptions).\n // Attributed to the section's nc-<type> id with no variant — they feed the\n // persona attention fallback and auto-discovery, never rewards.\n const detectorCleanups: Array<() => void> = [];\n if (opts.microSignals) {\n // tab_loss is a single document-level `visibilitychange` signal, so enabling\n // it on every section detector would emit one tab_loss per nc-<type> section\n // on a single tab-hide — attributing one page-level exit to every section\n // (audit M5). Enable it on only the first section so the exit is recorded\n // once, mirroring the per-option path in slot-signals.ts ({ tabLoss: index === 0 }).\n [...componentOf.entries()].forEach(([el, componentId], i) => {\n detectorCleanups.push(\n attachMicroSignalDetectors((signalType, extra = {}) => {\n try {\n client.track({\n projectId: opts.apiKey,\n componentId,\n eventType: 'micro_signal',\n payload: { signalType, ...extra },\n });\n } catch {\n /* fail-safe */\n }\n }, el, undefined, { tabLoss: i === 0 }),\n );\n });\n }\n\n // Cleanup: bank any remaining dwell, then detach everything (provider unmount\n // / consent re-init must not leak observers or listeners).\n return () => {\n emit();\n clearInterval(heartbeat);\n doc.removeEventListener('visibilitychange', onVisibility);\n win?.removeEventListener('pagehide', onPageHide);\n win?.removeEventListener('pageshow', onPageShow);\n for (const c of detectorCleanups) c();\n try { observer.disconnect(); } catch { /* ignore */ }\n };\n}\n"],"mappings":"osBAAA,IAAAA,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BH,EAAK,EAIL,IAAMC,EAAM,KAAK,IAAI,EACrB,QAAWJ,KAAKH,EAAM,OAAO,EAAOG,EAAE,eAAcA,EAAE,QAAUI,EAClE,EAAG/C,EAAY,EAKTuD,EAAsC,CAAC,EAC7C,OAAItC,EAAK,cAMP,CAAC,GAAGY,EAAY,QAAQ,CAAC,EAAE,QAAQ,CAAC,CAACxB,EAAI+B,CAAW,EAAGoB,IAAM,CAC3DD,EAAiB,KACfE,EAA2B,CAACC,EAAYC,EAAQ,CAAC,IAAM,CACrD,GAAI,CACF3C,EAAO,MAAM,CACX,UAAWC,EAAK,OAChB,YAAAmB,EACA,UAAW,eACX,QAASG,EAAA,CAAE,WAAAmB,GAAeC,EAC5B,CAAC,CACH,OAAQ9C,EAAA,CAER,CACF,EAAGR,EAAI,OAAW,CAAE,QAASmD,IAAM,CAAE,CAAC,CACxC,CACF,CAAC,EAKI,IAAM,CACXV,EAAK,EACL,cAAcQ,CAAS,EACvBpD,EAAI,oBAAoB,mBAAoB8C,CAAY,EACxDK,GAAA,MAAAA,EAAK,oBAAoB,WAAYH,GACrCG,GAAA,MAAAA,EAAK,oBAAoB,WAAYD,GACrC,QAAW9C,KAAKiD,EAAkBjD,EAAE,EACpC,GAAI,CAAEsC,EAAS,WAAW,CAAG,OAAQ/B,EAAA,CAAe,CACtD,CACF","names":["index_engagement_exports","__export","SEMANTIC_TYPES","classifyFeatures","classifySection","featuresFromElement","startEngagementCapture","__toCommonJS","SEMANTIC_TYPES","ARIA_TOPIC","structuralTopicOf","f","aria","hay","fallbackTopicOf","KEYWORDS","CONTENT_PATTERNS","SHARED_TOPIC_PARENT","headingText","el","_a","h","classifyFeatures","_b","structural","type","re","fb","featuresFromElement","text","role","__spreadValues","classifySection","import_policy","attachMicroSignalDetectors","emit","node","variantAssignedAt","options","cleanups","firedOnce","timestamps","onClick","now","onCopy","e","sel","selectionLength","isVisible","hesitationTimer","clearHesitation","startHesitation","onScroll","ioCallback","entries","entry","io","assignedAt","onVisibility","elapsed","c","isDoNotTrackEnabled","v","STABLE_DATA_ATTRS","normalizedText","el","_a","fingerprintOf","cssEscape","v","unique","root","selector","e","uniqueSelector","tag","classes","c","candidates","parent","parentSel","combined","siblings","n","idx","distinguishable","s","nth","locatorFromElement","fingerprint","id","name","STABLE_DATA_ATTRS","value","SECTION_SELECTOR","HEARTBEAT_MS","selectSections","doc","candidates","kept","el","c","k","registerSections","apiKey","apiBase","pageUrl","sections","e","NOOP","startEngagementCapture","client","opts","_a","_b","_c","_d","_e","_f","_g","_h","_i","isDoNotTrackEnabled","els","componentOf","entries","explicit","markup","SEMANTIC_TYPES","type","classifySection","componentId","locator","locatorFromElement","__spreadValues","state","get","id","s","observer","entry","emit","now","onVisibility","frozen","onPageHide","event","onPageShow","win","heartbeat","detectorCleanups","i","attachMicroSignalDetectors","signalType","extra"]}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{a as
|
|
1
|
+
import{a as B}from"./chunk-KIP52DUJ.mjs";import{a as E,d as j,e as V,f as S}from"./chunk-EWP6FTHE.mjs";import{x as K,z as P}from"./chunk-RL5B6M4G.mjs";import"./chunk-2NVSFI4V.mjs";import{a as v}from"./chunk-TMCGHANO.mjs";var z="section, header, footer, nav, main > div, [data-sentient-section]",H=2e4;function Y(l){let o=Array.from(l.querySelectorAll(z)),r=o.filter(a=>o.filter(c=>c!==a&&a.contains(c)).length<2);return r.filter(a=>!r.some(c=>c!==a&&c.contains(a)))}function q(l,o,r,a){try{fetch(`${o}/v1/section-map`,{method:"POST",keepalive:!0,headers:{"content-type":"application/json",authorization:`Bearer ${l}`},body:JSON.stringify({pageUrl:r,sections:a})}).catch(()=>{})}catch(c){}}var y=()=>{};function J(l,o){var C,O,k,D,_,L,M,N,x;let r=(C=o.doc)!=null?C:typeof document!="undefined"?document:void 0;if(!r||typeof IntersectionObserver=="undefined"||P()||!o.apiKey||!o.apiKey.startsWith("pk_"))return y;let a=((O=o.apiBase)!=null?O:"https://api.sentient-ui.com").replace(/\/+$/,"").replace(/\/v1$/,""),c=Y(r);if(c.length===0)return y;let p=new Map,w=[];for(let e of c){let t=e.getAttribute("data-sentient-type"),n=t&&E.includes(t)?t:null,i=(D=n!=null?n:(k=o.typeOf)==null?void 0:k.call(o,e))!=null?D:S(e),m=`nc-${i}`;p.set(e,m);let h=B(e,r);w.push(v({componentId:m,semanticType:i,source:n?"markup":"auto"},h?{locator:h}:{}))}let F=(N=(M=(L=(_=r.defaultView)!=null?_:typeof window!="undefined"?window:void 0)==null?void 0:L.location)==null?void 0:M.pathname)!=null?N:"/";q(o.apiKey,a,F,w);let d=new Map,R=e=>{let t=d.get(e);return t||(t={ms:0,scroll:0,enterAt:null,intersecting:!1},d.set(e,t)),t},g=new IntersectionObserver(e=>{for(let t of e){let n=p.get(t.target);if(!n)continue;let i=R(n);t.isIntersecting?(i.intersecting=!0,i.enterAt=Date.now(),t.intersectionRatio>i.scroll&&(i.scroll=t.intersectionRatio)):(i.intersecting=!1,i.enterAt!=null&&(i.ms+=Date.now()-i.enterAt,i.enterAt=null))}},{threshold:[0,.25,.5,.75,1]});for(let e of p.keys())g.observe(e);let u=()=>{let e=Date.now();for(let[t,n]of d)if(n.enterAt!=null&&(n.ms+=e-n.enterAt,n.enterAt=null),!(n.ms<=0)){try{l.track({projectId:o.apiKey,componentId:t,eventType:"dwell",payload:{dwell_time:Math.round(n.ms),scroll_depth:Number(n.scroll.toFixed(2))}})}catch(i){}n.ms=0}},A=()=>{if(r.hidden)u();else{let e=Date.now();for(let t of d.values())t.intersecting&&(t.enterAt=e)}},f=!1,T=e=>{if(u(),e!=null&&e.persisted){f=!0;return}try{g.disconnect()}catch(t){}},b=e=>{if(!(e!=null&&e.persisted)||!f)return;f=!1;let t=Date.now();for(let n of d.values())n.enterAt=n.intersecting&&!r.hidden?t:null};r.addEventListener("visibilitychange",A);let s=(x=r.defaultView)!=null?x:typeof window!="undefined"?window:void 0;s==null||s.addEventListener("pagehide",T),s==null||s.addEventListener("pageshow",b);let $=setInterval(()=>{if(r.hidden||f)return;u();let e=Date.now();for(let t of d.values())t.intersecting&&(t.enterAt=e)},H),I=[];return o.microSignals&&[...p.entries()].forEach(([e,t],n)=>{I.push(K((i,m={})=>{try{l.track({projectId:o.apiKey,componentId:t,eventType:"micro_signal",payload:v({signalType:i},m)})}catch(h){}},e,void 0,{tabLoss:n===0}))}),()=>{u(),clearInterval($),r.removeEventListener("visibilitychange",A),s==null||s.removeEventListener("pagehide",T),s==null||s.removeEventListener("pageshow",b);for(let e of I)e();try{g.disconnect()}catch(e){}}}export{E as SEMANTIC_TYPES,j as classifyFeatures,S as classifySection,V as featuresFromElement,J as startEngagementCapture};
|
|
2
2
|
//# sourceMappingURL=index-engagement.mjs.map
|