@sentientui/react 0.42.4 → 0.43.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +38 -1
- package/dist/index.d.cts +13 -1
- package/dist/index.d.ts +13 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +2 -2
- package/dist/index.mjs.map +1 -1
- package/dist/next/adaptive-root.d.ts +13 -1
- package/dist/next/adaptive-root.js +2 -2
- package/dist/next/adaptive-root.js.map +1 -1
- package/dist/server.d.cts +7 -0
- package/dist/server.d.ts +7 -0
- package/dist/server.js +1 -1
- package/dist/server.js.map +1 -1
- package/dist/server.mjs +1 -1
- package/dist/server.mjs.map +1 -1
- package/dist/testing/react.js +1 -1
- package/dist/testing/react.js.map +1 -1
- package/dist/testing/react.mjs +1 -1
- package/dist/testing/react.mjs.map +1 -1
- package/llms.txt +5 -0
- package/package.json +3 -3
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/provider.tsx","../src/weights-store.ts","../src/preview-mode.ts","../src/override-events.ts","../src/devtools-config.ts","../src/adaptive-shared.ts","../src/devtools-registry.ts","../src/sdk-version.ts","../src/devtools-slot-config-overrides.ts","../src/devtools-slot-overrides.ts","../src/hash-param.ts","../src/editor-session.ts","../src/cell-preview.ts","../src/style-capture.ts","../src/adaptive.tsx","../src/use-variant-component.ts","../src/use-assignment.ts","../src/dev-override.ts","../src/adaptive-slot.tsx","../src/use-slot-config.ts","../src/blocks-render.tsx","../src/slot-text.ts","../src/adaptive-text.tsx","../src/use-adaptive-goal.ts","../src/use-page-goal.ts","../src/use-goal.ts","../src/persona-script.tsx","../src/use-adaptive-tokens.ts","../src/use-slot-result.ts","../src/use-adaptive.ts","../src/adaptive-group.tsx","../src/segment.ts","../src/agent-feed.ts","../src/index.ts"],"sourcesContent":["'use client';\n\ndeclare const process: { env?: { NODE_ENV?: string } } | undefined;\n\n// `type JSX` from react, not the global namespace removed in @types/react@19\n// (peers allow react >=18) — see adaptive-text.tsx.\nimport {\n createContext,\n useContext,\n useEffect,\n useMemo,\n useRef,\n useState,\n useSyncExternalStore,\n type JSX,\n type ReactNode,\n} from 'react';\nimport {\n deriveSessionSegment,\n init,\n type ConsentSource,\n type SentientClient,\n type SentientConfig,\n type SitePalette,\n type SlotConfigEntry,\n type StyleVocabulary,\n type StageAttributes,\n type SlotResult,\n} from '@sentientui/core';\nimport type { SemanticType } from '@sentientui/core/engagement';\nimport { update as updateWeightsStore, type ComponentWeights } from './weights-store.js';\nimport { getPreviewMode, subscribePreview, createPreviewClient } from './preview-mode.js';\nimport { subscribeOverridesChanged } from './override-events.js';\nimport { publishDevtoolsConfig } from './devtools-config.js';\nimport { registerSections } from './devtools-registry.js';\nimport { isDevBuild } from './adaptive-shared.js';\nimport { SDK_IDENT } from './sdk-version.js';\nimport { maybeStartCellPreview } from './cell-preview.js';\nimport { maybeCaptureStyles } from './style-capture.js';\n\n/**\n * Feeds browser globals into core's `deriveSessionSegment` so the cache key\n * used by `useAssignment` always matches the key `assign()` writes under.\n * Before this, the context defaulted to 'desktop:direct' while core used the\n * detected segment — a systematic cache miss for every integration that\n * didn't pass `sessionSegment` explicitly. The derivation itself lives in\n * core (audit REACT-14): a hand-mirrored `${device}:${source}` copy here\n * drifted independently of the key core writes, which is the cache-miss bug\n * all over again, one refactor later.\n */\nfunction deriveDefaultSegment(): string {\n if (typeof window === 'undefined') return 'desktop:direct';\n try {\n return deriveSessionSegment({\n userAgent: navigator.userAgent ?? '',\n referer: document.referrer ?? '',\n appOrigin: window.location.origin,\n });\n } catch {\n return 'desktop:direct';\n }\n}\n\nconst DEFAULT_API_BASE_URL = 'https://api.sentient-ui.com/v1';\n\n/** How to render adaptive slots during SSR when assignments are not preloaded. */\nexport type SsrFallback = 'first' | 'none';\n\ntype AdaptiveContextValue = {\n client: SentientClient | null;\n // The publishable API key (pk_…). Historically named `projectId` because the\n // API uses it as the project identifier on the wire, but it is the API key,\n // not the project UUID. Field renamed for clarity.\n apiKey: string;\n initialAssignments: Record<string, string>;\n /** Components an SSR preload found moved onto the shared track. */\n initialUnified: readonly string[];\n sessionSegment: string;\n ssrFallback: SsrFallback;\n onAssignment: ((componentId: string, variantId: string) => void) | undefined;\n initialLayoutOrder: string[] | null;\n initialSlots: Record<string, SlotResult>;\n initialSlotConfig: Record<string, SlotConfigEntry>;\n initialPalette: SitePalette | null;\n initialVocabulary: StyleVocabulary | null;\n initialPersona: { persona: string; confidence: number } | null;\n apiBaseUrl: string;\n debug: boolean;\n};\n\nconst AdaptiveContext = createContext<AdaptiveContextValue>({\n client: null,\n apiKey: '',\n initialAssignments: {},\n initialUnified: [],\n sessionSegment: 'desktop:direct',\n ssrFallback: 'first',\n onAssignment: undefined,\n initialLayoutOrder: null,\n initialSlots: {},\n initialSlotConfig: {},\n initialPalette: null,\n initialVocabulary: null,\n initialPersona: null,\n apiBaseUrl: DEFAULT_API_BASE_URL,\n debug: false,\n});\n\nexport type AdaptiveProviderProps = {\n apiKey: string;\n /**\n * @deprecated Unused — the project's type is set in the dashboard. Safe to omit.\n * Still accepted (and forwarded to core, which ignores it) so existing code compiles.\n */\n context?: SentientConfig['context'];\n debug?: boolean;\n /**\n * SSR-preloaded assignments from `preloadAssignments()` / `loadAdaptiveAssignments()`.\n * Passed through to `useAssignment` as synchronous initial state so crawlers and\n * the first paint see real content (recommended for SEO).\n */\n initialAssignments?: Record<string, string>;\n /**\n * Component ids the SSR preload found moved onto the shared track (the\n * `unified` of `loadAdaptiveAssignments()` / `loadAdaptiveDecision()`;\n * `<AdaptiveRoot>` passes it for you). A variants-only `<Adaptive>` with one\n * of these ids renders on the shared track from the server HTML on, and an\n * assignment cached before the move is ignored.\n */\n initialUnified?: string[];\n /**\n * Bandit segment from SSR (`device:source`). Keeps cache, assign, and worker\n * weights on one row — must match `loadAdaptiveAssignments` / session upsert.\n */\n sessionSegment?: string;\n /**\n * @deprecated Use `clientOnly` on the component; the default behaviour renders\n * the first variant.\n *\n * When no `initialAssignments` exist for a component, `'first'` renders\n * `variantIds[0]` in server HTML (safe default for SEO); `'none'` renders\n * nothing until the client resolves. Still accepted with that exact behaviour\n * so existing trees don't change. Deprecated because it was a provider-wide\n * switch for a per-component decision (`clientOnly` already expresses it), and\n * it only ever reached `<Adaptive variants>` / `useAssignment` — `useAdaptive`\n * falls back to the first key regardless, and AdaptiveText, generated-version\n * `<Adaptive>` and slots never read it, so it read broader than it was.\n * @default 'first'\n */\n ssrFallback?: SsrFallback;\n /**\n * Consent gate. When `false` the SDK is not initialised and no events are\n * sent. Flip to `true` (e.g. after the user accepts the cookie banner) to\n * initialise and begin tracking.\n */\n consent?: boolean;\n /**\n * Where to read the visitor's consent decision from, so the SDK can gate and\n * un-gate itself instead of the host app wiring `grantConsent()` by hand.\n *\n * Keep your own banner or CMP — this only tells us how to observe it. The\n * provider reads the source on mount, re-reads it whenever `event` fires, and\n * initialises the moment it grants. Nothing is requested and no cookie is set\n * until then, and there is no page reload.\n *\n * Because the provider owns the whole lifecycle there is no ordering rule to\n * get right: pass this instead of managing `consent` yourself.\n *\n * @example // cookie written by your own banner\n * consentFrom={{ cookie: 'cookie_consent', value: 'accepted', event: 'consent-decided' }}\n * @example // a supported consent platform (reads its API, events and cookie)\n * consentFrom=\"cookiebot\" // or 'onetrust' | 'cookieyes' | 'tcf' | 'google-consent-mode'\n * consentFrom={{ cmp: 'onetrust', group: 'C0004' }}\n * @example // any other CMP with a JS API\n * consentFrom={{ check: () => window.myCmp?.analytics === true, event: 'mycmp:changed' }}\n */\n consentFrom?: ConsentSource;\n /**\n * Behavior before consent is granted. Pass `'statistical_winner'` to serve the\n * best-performing variant via `GET /v1/winner` with zero tracking while the\n * consent banner is showing. Requires `consent: false`.\n * @see SentientConfig.preConsentBehavior\n */\n preConsentBehavior?: 'statistical_winner' | 'control';\n /**\n * Honor the browser's Do Not Track signal. Defaults to `true`: when DNT is\n * enabled the SDK sets no cookies and sends no tracking data (overriding\n * `consent: true`). Set `false` to make your own consent gate authoritative.\n * @see SentientConfig.respectDoNotTrack\n */\n respectDoNotTrack?: boolean;\n /**\n * Called once per component the first time a variant is resolved for that\n * component in this session. Use to forward assignments to your own analytics\n * (Mixpanel, PostHog, Segment, etc.) without having to wrap `useAssignment`.\n */\n onAssignment?: (componentId: string, variantId: string) => void;\n /**\n * SSR-preloaded section order from `loadAdaptiveDecision()`.\n * Pass the `layoutOrder` field from `DecideResult`. When set,\n * `useLayoutOrder()` returns this on first render so there is no layout shift.\n */\n initialLayoutOrder?: string[] | null;\n /**\n * The section ids the app declares as reorderable, independent of any\n * decision. `AdaptiveRoot` forwards its `sections` prop here.\n *\n * Devtools reads this to offer layout previewing: a page whose decision was\n * gated by consent, or timed out, has no `initialLayoutOrder`, and registering\n * only that left the layout panel empty in exactly the situation you reach for\n * it — running the site locally before accepting a cookie banner.\n */\n declaredSections?: string[];\n /**\n * What each section IS, keyed by its `data-sentient-id`:\n * `{ about: 'trust', contact: 'cta' }`. Optional — sections are classified\n * from their content — but the classifier reads a section with little\n * signal-bearing copy (an \"About us\" band, a contact form) as `generic`, and\n * a `generic` section is ordered the same for every persona. Declare the\n * ones it gets wrong; any section with a `data-sentient-id` can appear here,\n * reorderable or not. Wins over legacy `data-sentient-type` markup.\n */\n sectionTypes?: Readonly<Partial<Record<string, SemanticType>>>;\n /**\n * SSR-preloaded slot results from `loadAdaptiveDecision()` (the `slots`\n * field of its result). Guarantees `useAdaptiveTokens`/`AdaptiveGroup`\n * render the decided arm in server HTML — zero flicker, hydration-safe.\n */\n initialSlots?: Record<string, SlotResult>;\n /**\n * SSR-preloaded registry slot config from `loadAdaptiveDecision()` (the\n * `slotConfig` field of its result, registry mode). Lets `AdaptiveSlot`\n * render server-authored content/blocks in server HTML — zero flicker.\n */\n initialSlotConfig?: Record<string, SlotConfigEntry>;\n /** SSR-preloaded site palette (`palette` field of `loadAdaptiveDecision()`'s\n * registry-mode result) for block rendering. */\n initialPalette?: SitePalette;\n /** SSR-preloaded site styles (`vocabulary` field of `loadAdaptiveDecision()`'s\n * registry-mode result) that served Redesign arms borrow. */\n initialVocabulary?: StyleVocabulary;\n /**\n * Persona decided during SSR (`persona` + `confidence` fields of\n * `loadAdaptiveDecision()`'s result). Adopted by the core client;\n * rendered into html attributes only by `SentientPersonaScript`.\n */\n initialPersona?: { persona: string; confidence: number };\n /**\n * Base URL of the Sentient API (no trailing slash). Read by the devtools\n * panel for /v1/explain and by future client helpers. Defaults to the\n * hosted API.\n */\n apiBaseUrl?: string;\n /**\n * Session ID generated during SSR (the `sessionId` field returned by\n * `loadAdaptiveAssignments` / `loadAdaptiveDecision`). When provided and no\n * existing session cookie or localStorage entry is found, the client adopts\n * this ID so events and goals are attributed to the same session the server\n * used for variant assignment.\n */\n ssrSessionId?: string;\n /**\n * Where the visitor cookie lives. By default it is shared on the site's\n * registrable domain (auto-detected), so `example.com` and\n * `app.example.com` running the same project key count one visitor and one\n * journey. `false` keeps it on this host only; a string names the domain.\n */\n cookieDomain?: string | false;\n /**\n * The signed-in user: identifies the visitor once per client. Pass the\n * server-signed `userHash` (`signUserId` from `@sentientui/core/server`,\n * or let `<AdaptiveRoot userId>` do it) to make it a VERIFIED identify —\n * required for server goals by `userId` once a project signs its identifies.\n */\n identity?: { userId: string; userHash?: string };\n /**\n * ISO 3166-1 alpha-2 country code. Pass the value of the `CF-IPCountry`\n * header from your Next.js server component to populate country on landing\n * sessions without client-side geo lookup.\n */\n country?: 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. Served at full\n * confidence, overriding the inferred persona. Stable for the session —\n * like `country`, changing it after init is ignored (decisions are locked\n * per visit); remount the provider to apply a new value.\n */\n persona?: string;\n /**\n * Opt-in theme hook: put the visitor's funnel stage on\n * `<html data-sentient-stage>` so CSS can make deterministic per-stage\n * changes (hide the first-order discount from people who have bought).\n * Projects with stages turned on only; never for the control group.\n * `true` exposes `new`, `browsing`, `carted` and `returning` (has bought\n * here); `'detailed'` splits `returning` into `customer` and `lapsed`. Any\n * script on the page can read it, which is why detail is a second opt-in.\n * How the visitor arrived (ads, emails) is never written to the page.\n * `AdaptiveRoot` also writes it in the server HTML.\n */\n stageAttributes?: StageAttributes;\n /**\n * Keyless local mode. 'auto' (default) simulates decisions on-device in\n * development builds when no valid API key is configured; `true` forces the\n * local engine; `false` restores the silent keyless no-op.\n * @see SentientConfig.localMode\n */\n localMode?: 'auto' | boolean;\n /**\n * DOM graph scanning + page-structure sync. ON by default: the provider\n * dynamically loads `@sentientui/core/graph` and uses its graph-capable\n * `init()` for the single client, so the SDK scans your page structure,\n * auto-detects semantic sections, and syncs them to power personas and the\n * dashboard graph page. Pass `false` to keep the lean bundle only.\n */\n enableGraph?: boolean;\n /**\n * Include captured heading / DOM text in graph sync payloads. OFF by default.\n * Only applies when graph scanning is enabled (`enableGraph` not `false`).\n */\n captureDomText?: boolean;\n /**\n * Behavioral engagement capture (per-section dwell/scroll + semantic section\n * registration) powering personas. ON by default — pass `false` to disable.\n * Never runs for a DNT/GPC or consent-gated visitor (no client → no capture).\n */\n engagement?: boolean;\n /**\n * CSP nonce for the <style> the SDK injects (the adaptation reveal), so a\n * nonce-based CSP needs no `style-src 'unsafe-inline'`. `AdaptiveRoot`\n * forwards its own `nonce`. Defaults to the nonce of a script on the page.\n */\n nonce?: string;\n children: ReactNode;\n};\n\n/** Once per page load — StrictMode and route-level providers remount. */\nlet warnedNoConsentGate = false;\n\n/** Projects whose consent source has answered (non-null) in this page load.\n * Module-level, not per mount: a remounted provider (route-level placement,\n * a cached RSC payload on Back) or a changed consentFrom started over and fell\n * back to AdaptiveRoot's stale request-time consent={true} (review R11 #1). */\nconst answeredThisPage = new Set<string>();\n\n/**\n * Watches a {@link AdaptiveProviderProps.consentFrom} source and reports whether\n * it currently grants consent. Returns false (and subscribes to nothing) when no\n * source is configured.\n */\nfunction useConsentSource(\n source: AdaptiveProviderProps['consentFrom'],\n apiKey: string,\n onRefused: () => void,\n): { granted: boolean | null; refused: boolean } {\n const onRefusedRef = useRef(onRefused);\n onRefusedRef.current = onRefused;\n const [granted, setGranted] = useState<boolean | null>(null);\n const [refused, setRefused] = useState(false);\n\n // The source is usually an inline object literal, so its identity changes\n // every render. Read it through a ref and key the effect on a stable string,\n // otherwise the listener would be torn down and re-added on every render.\n const sourceRef = useRef(source);\n sourceRef.current = source;\n const key =\n source === undefined\n ? ''\n : typeof source === 'string'\n ? source\n : JSON.stringify({\n ...source,\n check: typeof (source as { check?: unknown }).check,\n refused: typeof (source as { refused?: unknown }).refused,\n });\n\n useEffect(() => {\n const s = sourceRef.current;\n if (s === undefined || typeof window === 'undefined') return;\n // Symmetric: every signal re-reads the source both ways, so a CMP\n // \"withdrawn\" decision later in the visit re-gates the SDK (the old shape\n // latched true and stopped listening). Payloads are never trusted.\n // The watcher is its own core entry, loaded only by pages that configure\n // a consent source; until it arrives the state stays \"unknown\" (gated,\n // or the server's read).\n let stop: (() => void) | undefined;\n let cancelled = false;\n void import('@sentientui/core/consent').then(({ consentWatcher, forgetVisitor }) => {\n if (cancelled) return;\n const watcher = consentWatcher(\n // Both predicates through the ref: an inline `refused` closing over\n // state was frozen at the first render, so a later \"no\" never\n // forgot the visitor (review R7 #4).\n typeof s === 'object' && s.cmp === undefined && s.check\n ? {\n ...s,\n check: () => (sourceRef.current as { check: () => boolean }).check(),\n ...(s.refused ? { refused: () => (sourceRef.current as { refused?: () => boolean }).refused?.() === true } : {}),\n }\n : s,\n );\n // A recorded refusal forgets the visitor even when no tracking client\n // exists to destroy — a \"no\" given where the SDK wasn't watching (a CMP\n // settings page, checkout) otherwise left the 365-day id and the\n // decision snapshot in place for good (audit N2). refused() is false for\n // \"not loaded yet\" and \"banner up\", so a consented visitor is never\n // wiped by a slow CMP.\n let wasRefused = false;\n // Once the platform has answered in this page view, \"no answer\" again\n // (a custom banner's reset deleting its cookie) reads false — a pause.\n // As null it fell back to the server's request-time read, so a visitor\n // who withdrew under AdaptiveRoot's consent={true} was tracked again\n // under a fresh identity (grader N10-1). See answeredThisPage.\n const update = (): void => {\n // Never while the source reads granted (a custom `refused` that\n // disagrees with its own `check`): that would wipe a tracked visitor.\n const r = watcher.refused() && watcher.read() !== true;\n // On a change only: Consent Mode calls back on every dataLayer push.\n if (r && !wasRefused) {\n forgetVisitor(apiKey);\n onRefusedRef.current();\n }\n wasRefused = r;\n setRefused(r);\n const g = watcher.read();\n if (g !== null) answeredThisPage.add(apiKey);\n setGranted(g ?? (answeredThisPage.has(apiKey) ? false : null));\n };\n update();\n stop = watcher.subscribe(update);\n });\n return () => {\n cancelled = true;\n stop?.();\n };\n }, [key, apiKey]);\n\n return { granted, refused };\n}\n\n/**\n * Initialises the Sentient core SDK in a useEffect (SSR-safe) and exposes the\n * client via React context. Re-initialises when consent changes.\n */\nexport function AdaptiveProvider(props: AdaptiveProviderProps): JSX.Element {\n const [client, setClient] = useState<SentientClient | null>(null);\n // Derived once per mount: identical to what core init() computes, so cache\n // reads (context segment) and cache writes (core segment) always agree.\n const [sessionSegment] = useState(() => props.sessionSegment ?? deriveDefaultSegment());\n // Devtools preview: when on, expose an event-suppressing client so previewing\n // variants/personas writes nothing. Off by default (inert in production).\n const [previewOn, setPreviewOn] = useState(getPreviewMode());\n useEffect(() => subscribePreview(() => setPreviewOn(getPreviewMode())), []);\n // On-site cell preview (dashboard \"Preview on your site\" link). No-ops\n // without both URL params; forces the previewed arm through the override\n // channel AdaptiveSlot already renders exposure-free.\n useEffect(() => {\n maybeStartCellPreview(props.apiBaseUrl);\n // Any editor-token session also samples the site's styles for Redesign\n // (React sites never load the snippet editor that does it elsewhere).\n maybeCaptureStyles(props.apiBaseUrl);\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n // When a consentFrom source is configured it owns the gate: start closed and\n // open only once the source grants. An explicit consent={true} (e.g. resolved\n // from the cookie on the server by AdaptiveRoot) short-circuits it, so a\n // returning visitor isn't gated waiting for a client-side re-read.\n // The browser source decides as soon as it knows (true OR false). Until then\n // (null: CMP not loaded yet) the server's read stands. The old\n // `props.consent === true || sourceGranted` let a server-side grant override\n // a mid-visit revocation for the rest of the page view.\n // Declared ahead of useConsentSource (which must call it): the refs it\n // clears are created further down.\n const dropHeldRef = useRef<() => void>(() => undefined);\n const source = useConsentSource(props.consentFrom, props.apiKey, () => dropHeldRef.current());\n // The server's read stands only until the browser source has answered in\n // this page load — also across remounts, before the watcher reloads.\n const consent = props.consentFrom\n ? (source.granted ?? (answeredThisPage.has(props.apiKey) ? false : props.consent === true))\n : props.consent;\n // Whether a `false` means \"forget the visitor\" or only \"stop for now\". An\n // explicit consent={false} is the site's own revocation; from a platform,\n // only a recorded refusal forgets — a consented visitor reopening the TCF\n // banner reads false too and was fully forgotten (review M2).\n const forgetOnFalse = props.consentFrom ? source.refused : true;\n const forgetRef = useRef(forgetOnFalse);\n forgetRef.current = forgetOnFalse;\n\n // The live client mirrored outside React state, so teardown can reach it\n // without a side effect inside a setState updater: React double-invokes\n // updaters in StrictMode dev (they must be pure), so `prev?.destroy()` inside\n // setClient ran twice — and could run during a render that never commits.\n const clientRef = useRef<SentientClient | null>(null);\n // Whether clientRef holds a TRACKING client (created with consent not false).\n // A revocation must forget that client's visitor; a pre-consent proxy has\n // nothing to forget.\n const trackingRef = useRef(false);\n // Conversions a gated client held (goal() before the consent source\n // answered), taken from it on teardown and handed to the next client: React\n // replaces the gated client on a grant instead of upgrading it in place, so\n // they were discarded with it (grader F2).\n const heldRef = useRef<Array<(c: SentientClient) => void>>([]);\n // A recorded refusal drops held conversions — ours and the gated client's —\n // so a later accept in the same page view can't send them (grader F-R1:\n // the effect is keyed on `consent`, which stays false from \"unknown\" to\n // \"refused\", so nothing else runs on the refusal).\n // The gated client is RELEASED, not just drained: draining left it holding,\n // so a goal fired after the refusal was held again and sent on a later\n // accept (grader R8 NEW-2). dispose() on a gated proxy drops its held calls,\n // answers its decides with null and holds nothing more; its read-only\n // winner (preConsentBehavior) keeps serving until the next consent change.\n // Latched too, until the next grant: a gated client created AFTER the\n // refusal — the re-init when a tracked visitor refuses, or the /graph\n // client landing after a boot-time refusal — was never released, so its\n // held goals reached the tracking client on a later accept (grader R9-1).\n const refusedRef = useRef(false);\n dropHeldRef.current = () => {\n heldRef.current = [];\n refusedRef.current = true;\n const c = clientRef.current;\n if (c?.gated) c.dispose();\n else c?.takeHeld?.();\n };\n\n useEffect(() => {\n // Revocation (a tracking client → consent false): forget the visitor —\n // identity cookie, assignment cache, decision snapshot, retry buckets —\n // via the ref, in the effect body (see clientRef above). This used to run\n // only without preConsentBehavior; with 'statistical_winner' the previous\n // run's cleanup merely dispose()d, so a withdrawn visitor kept the 365-day\n // cookie and their snapshot re-personalized the next page load.\n // (Only a forgetting revocation destroys; a pause was already disposed by\n // the previous run's cleanup, which keeps the identity.)\n if (forgetRef.current && consent === false) heldRef.current = [];\n if (consent === false && trackingRef.current) {\n if (forgetRef.current) clientRef.current?.destroy();\n clientRef.current = null;\n trackingRef.current = false;\n }\n if (consent === false && !props.preConsentBehavior) {\n if (forgetRef.current) clientRef.current?.destroy();\n clientRef.current = null;\n setClient(null);\n return;\n }\n const tracking = consent !== false;\n if (tracking) refusedRef.current = false;\n // A gated client born after a refusal is released at once (see refusedRef).\n const adopt = (c: SentientClient): void => {\n if (!tracking && refusedRef.current && c.gated) c.dispose();\n };\n\n const config = {\n apiKey: props.apiKey,\n context: props.context,\n debug: props.debug,\n initialAssignments: props.initialAssignments,\n initialUnified: props.initialUnified,\n sessionSegment,\n consent,\n preConsentBehavior: props.preConsentBehavior,\n respectDoNotTrack: props.respectDoNotTrack,\n ssrSessionId: props.ssrSessionId,\n cookieDomain: props.cookieDomain,\n country: props.country,\n persona: props.persona,\n stageAttributes: props.stageAttributes,\n localMode: props.localMode,\n initialSlots: props.initialSlots,\n initialSlotConfig: props.initialSlotConfig,\n initialPalette: props.initialPalette,\n initialVocabulary: props.initialVocabulary,\n initialPersona: props.initialPersona,\n ingestUrl: props.apiBaseUrl ? `${props.apiBaseUrl.replace(/\\/$/, '')}/events` : undefined,\n nonce: props.nonce,\n // Declare which SDK (and which release) is driving this client, so the\n // dashboard can tell the project when it is running an old one. A React\n // install cannot self-update the way the snippet's CDN tag does, so this\n // nudge is the only update path there is.\n ...(SDK_IDENT ? { sdk: SDK_IDENT } : {}),\n };\n\n // Track the client created by this effect run so cleanup destroys exactly\n // the right one, and so a late-resolving dynamic import can bail if the\n // effect was already torn down (unmount / consent change).\n let cancelled = false;\n let created: SentientClient | null = null;\n let stopEngagement: (() => void) | null = null;\n\n // Engagement capture (default ON): per-section dwell/scroll + semantic\n // section registration, lazy-loaded so the lean bundle stays lean. Only for\n // a TRACKING client: with preConsentBehavior a gated visitor still gets a\n // (pre-consent proxy) client, and capture used to start on it — POSTing\n // /v1/section-map and attaching collectors while consent was false. The\n // capture module re-checks DNT internally.\n // Replay held conversions: sent by a tracking client, re-held by a gated one.\n // Each in its own task, like core's replay: one task would put them in\n // one latch window and collapse repeat conversions into one.\n const handOff = (c: SentientClient): void => {\n for (const call of heldRef.current.splice(0)) {\n setTimeout(() => {\n // Replaced before this task ran (unmount, another consent flip):\n // back into the stash for the next client, never into a disposed\n // one's dead queue (review R7 #6).\n if (clientRef.current !== c) {\n // …unless a refusal landed in between: it dropped the stash,\n // and pushing back revived the goal for a later accept\n // (review R10 #2).\n if (!refusedRef.current) heldRef.current.push(call);\n return;\n }\n try {\n call(c);\n } catch {\n /* one bad call never blocks the rest */\n }\n }, 0);\n }\n };\n\n const startEngagement = (c: SentientClient): void => {\n if (props.engagement === false || !tracking) return;\n void import('@sentientui/core/engagement').then(({ startEngagementCapture }) => {\n if (cancelled) return;\n stopEngagement = startEngagementCapture(c, {\n apiKey: props.apiKey,\n sectionTypes: props.sectionTypes,\n apiBase: props.apiBaseUrl ? props.apiBaseUrl.replace(/\\/$/, '') : undefined,\n });\n });\n };\n\n if (props.enableGraph !== false) {\n // Graph scanning is the default — load the graph entry dynamically so the\n // scanner never lands in the lean bundle. The provider still creates ONE\n // client (graph-capable). Pass enableGraph={false} for the lean client.\n void import('@sentientui/core/graph').then(({ init: initGraph }) => {\n if (cancelled) return;\n created = initGraph({\n ...config,\n graph: true,\n captureDomText: props.captureDomText === true,\n sectionTypes: props.sectionTypes,\n });\n adopt(created);\n clientRef.current = created;\n trackingRef.current = tracking;\n handOff(created);\n setClient(created);\n startEngagement(created);\n });\n } else {\n created = init(config);\n adopt(created);\n clientRef.current = created;\n trackingRef.current = tracking;\n handOff(created);\n setClient(created);\n startEngagement(created);\n }\n\n return () => {\n cancelled = true;\n stopEngagement?.();\n heldRef.current = heldRef.current.concat(created?.takeHeld?.() ?? []);\n // dispose, not destroy: effect cleanup runs on unmount, StrictMode's\n // dev double-invoke, and consent re-init — the visitor identity must\n // survive all of those. Full destroy() happens only on the explicit\n // consent-revocation branch above.\n created?.dispose();\n };\n // Re-init when consent changes — whether that came from the prop or from a\n // consentFrom source granting. Other props (incl. enableGraph) are\n // intentionally stable for a session.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [consent]);\n\n // Poll /v1/weights every 60 s so long-lived sessions see updated bandit weights\n // without a page reload. useAssignment subscribers react via weights-store.\n useEffect(() => {\n if (!client) return;\n let cancelled = false;\n const poll = async (): Promise<void> => {\n if (cancelled) return;\n let entries;\n try {\n entries = await client.fetchWeights();\n } catch {\n // Network/transient error: skip this cycle and retry on the next\n // interval. Swallowed deliberately so a failed poll never surfaces as\n // an unhandled rejection.\n return;\n }\n if (cancelled) return;\n for (const entry of entries) {\n const weights: ComponentWeights = {\n componentId: entry.componentId,\n updatedAt: entry.updatedAt,\n variants: entry.variants.map((v) => ({\n variantId: v.variantId,\n pulls: v.pulls,\n avgReward: v.avgReward ?? 0,\n })),\n };\n updateWeightsStore(entry.componentId, weights);\n }\n };\n void poll();\n const timerId = setInterval(() => void poll(), 60_000);\n return () => {\n cancelled = true;\n clearInterval(timerId);\n };\n }, [client]);\n\n const ssrFallback = props.ssrFallback ?? 'first';\n // Strip a trailing slash so consumers (devtools /explain, useAdaptiveApiBaseUrl)\n // build URLs the same way the core client does (it strips before appending\n // /events and /section-map) — otherwise an apiBaseUrl ending in \"/\" yields a\n // double slash like \".../v1//explain\".\n const apiBaseUrl = (props.apiBaseUrl ?? DEFAULT_API_BASE_URL).replace(/\\/$/, '');\n\n // The init effect above re-runs only on `props.consent`: apiKey / context /\n // country / apiBaseUrl are captured once and are deliberately stable for the\n // session, so changing them at runtime silently no-ops. That silence is\n // surprising — warn (dev only) when one actually changes value after init, so\n // the no-op is visible. To apply a new value, remount the provider (e.g. a\n // changing React `key`).\n const frozenConfigRef = useRef<{\n apiKey: string;\n // Optional since `context` was deprecated: undefined → undefined compares\n // equal under Object.is, so omitting it never trips the warning below.\n context: SentientConfig['context'] | undefined;\n country: string | undefined;\n persona: string | undefined;\n apiBaseUrl: string;\n } | null>(null);\n useEffect(() => {\n if (typeof process !== 'undefined' && process.env?.NODE_ENV === 'production') return;\n const current = { apiKey: props.apiKey, context: props.context, country: props.country, persona: props.persona, apiBaseUrl };\n const prev = frozenConfigRef.current;\n frozenConfigRef.current = current;\n if (prev === null) return; // first run: capture the frozen baseline, nothing to compare\n for (const key of ['apiKey', 'context', 'country', 'persona', 'apiBaseUrl'] as const) {\n if (!Object.is(prev[key], current[key])) {\n console.warn(\n `[sentient] AdaptiveProvider: \\`${key}\\` changed after initialisation, but the SDK client is stable for the session and only re-inits on \\`consent\\` — the new value is ignored. Remount the provider (e.g. via a changing \\`key\\` prop) to apply it.`,\n );\n }\n }\n }, [props.apiKey, props.context, props.country, props.persona, apiBaseUrl]);\n\n // Publish devtools config through window: the /devtools entry is a separate\n // bundle and cannot read this provider's context instance. Dev-only.\n useEffect(() => {\n if (typeof process !== 'undefined' && process.env?.NODE_ENV === 'production') return;\n publishDevtoolsConfig({\n apiKey: props.apiKey,\n apiBaseUrl,\n isLocal: client?.isLocal === true,\n });\n }, [client, props.apiKey, apiBaseUrl]);\n\n // identify() is an upsert: once per client and user, never per render. A\n // consent grant makes a new client, which identifies again — the gated one\n // dropped it.\n const identityUser = props.identity?.userId;\n const identityHash = props.identity?.userHash;\n useEffect(() => {\n if (client && identityUser) client.identify(identityUser, { userHash: identityHash });\n }, [client, identityUser, identityHash]);\n\n // Sections registry for devtools /v1/explain + local simulation. The decided\n // order wins when there is one (it is what the page is actually rendering);\n // the declared list is the fallback so the layout panel still knows what is\n // reorderable when no decision arrived.\n useEffect(() => {\n const decided = props.initialLayoutOrder;\n if (decided && decided.length > 0) {\n registerSections(decided);\n return;\n }\n if (props.declaredSections && props.declaredSections.length > 0) {\n registerSections(props.declaredSections);\n }\n }, [props.initialLayoutOrder, props.declaredSections]);\n\n // Dev-only: tracking is on by default, so an install that never wires a\n // consent gate tracks EU visitors from the first paint without anyone\n // having decided that (audit S6). Say so once, with the one-line fix.\n useEffect(() => {\n if (!isDevBuild() || props.consent !== undefined || props.consentFrom !== undefined) return;\n if (warnedNoConsentGate) return;\n warnedNoConsentGate = true;\n console.warn(\n '[SentientUI] No consent gate: every visitor is tracked from first paint. Pass consentFrom=\"<your CMP>\" ' +\n '(or consent={true} to silence). https://sentient-ui.com/docs#consent',\n );\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n // Dev-only: a declared section with no `data-sentient-id=\"<id>\"` element is\n // invisible to the DOM graph scanner, so the server never learns its semantic\n // type and every persona gets the identity order — the layout looks \"on\" but\n // can never personalize (found on a real site 2026-09-05: nine declared\n // sections, zero graph rows, one bandit arm). Warn once with the exact fix\n // rather than leaving the integration silently inert.\n useEffect(() => {\n if (!isDevBuild()) return;\n const declared = props.declaredSections;\n if (!declared || declared.length === 0 || typeof document === 'undefined') return;\n const present = new Set(\n Array.from(document.querySelectorAll('[data-sentient-id]'), (el) =>\n el.getAttribute('data-sentient-id'),\n ),\n );\n const missing = declared.filter((id) => !present.has(id));\n if (missing.length > 0) {\n console.warn(\n `[SentientUI] Declared section${missing.length > 1 ? 's' : ''} ${missing\n .map((id) => `\"${id}\"`)\n .join(', ')} ${missing.length > 1 ? 'have' : 'has'} no matching ` +\n 'data-sentient-id element, so the layout engine cannot learn what ' +\n 'they are and will serve the same order to every persona. Add ' +\n 'data-sentient-id=\"<sectionId>\" to each section\\'s element.',\n );\n }\n }, [props.declaredSections]);\n\n // The client exposed to consumers — wrapped to suppress events while previewing.\n const exposedClient = useMemo(\n () => (client && previewOn ? createPreviewClient(client) : client),\n [client, previewOn],\n );\n\n // Memoized so unrelated parent re-renders don't cascade through every\n // useSentient / useAssignment consumer via a fresh context object.\n const value = useMemo<AdaptiveContextValue>(\n () => ({\n client: exposedClient,\n apiKey: props.apiKey,\n initialAssignments: props.initialAssignments ?? {},\n initialUnified: props.initialUnified ?? NO_UNIFIED,\n sessionSegment,\n ssrFallback,\n onAssignment: props.onAssignment,\n initialLayoutOrder: props.initialLayoutOrder ?? null,\n initialSlots: props.initialSlots ?? {},\n initialSlotConfig: props.initialSlotConfig ?? {},\n initialPalette: props.initialPalette ?? null,\n initialVocabulary: props.initialVocabulary ?? null,\n initialPersona: props.initialPersona ?? null,\n apiBaseUrl,\n debug: props.debug ?? false,\n }),\n [\n exposedClient,\n props.apiKey,\n props.initialAssignments,\n props.initialUnified,\n sessionSegment,\n ssrFallback,\n props.onAssignment,\n props.initialLayoutOrder,\n props.initialSlots,\n props.initialSlotConfig,\n props.initialPalette,\n props.initialVocabulary,\n props.initialPersona,\n apiBaseUrl,\n props.debug,\n ],\n );\n\n return (\n <AdaptiveContext.Provider value={value}>\n {props.children}\n </AdaptiveContext.Provider>\n );\n}\n\n/**\n * Returns the SentientClient, or null until the provider has finished\n * initialising on the client.\n */\nexport function useSentient(): SentientClient | null {\n return useContext(AdaptiveContext).client;\n}\n\n/** Internal: publishable API key carried alongside the client. */\nexport function useAdaptiveApiKey(): string {\n return useContext(AdaptiveContext).apiKey;\n}\n\n/** Internal: SSR-preloaded assignments for hydration-safe first render. */\nexport function useInitialAssignments(): Record<string, string> {\n return useContext(AdaptiveContext).initialAssignments;\n}\n\nconst NO_UNIFIED: readonly string[] = [];\n\n/** Internal. Ids the SSR preload found moved onto the shared track. */\nexport function useInitialUnified(): readonly string[] {\n return useContext(AdaptiveContext).initialUnified;\n}\n\n/** The `device:source` segment this provider decides and caches under —\n * the SSR value when one was passed, else derived once per mount. */\nexport function useSessionSegment(): string {\n return useContext(AdaptiveContext).sessionSegment;\n}\n\n/** Internal: SSR fallback strategy when a slot has no preloaded assignment. */\nexport function useSsrFallback(): SsrFallback {\n return useContext(AdaptiveContext).ssrFallback;\n}\n\n/** Internal: forwarding hook for consumer analytics integration. */\nexport function useOnAssignment(): ((componentId: string, variantId: string) => void) | undefined {\n return useContext(AdaptiveContext).onAssignment;\n}\n\n/** Internal: debug flag from the provider config, for dev-only diagnostic logging. */\nexport function useDebug(): boolean {\n return useContext(AdaptiveContext).debug;\n}\n\n/**\n * Returns the persona-specific section order from SSR, or null when no\n * sections were declared on AdaptiveRoot or reliability is below threshold.\n * Devtools/testing can force it via `window.__sentient_layout_override`;\n * consumers re-render when the devtools notifies an override change.\n */\nexport function useLayoutOrder(): string[] | null {\n const contextOrder = useContext(AdaptiveContext).initialLayoutOrder;\n const override = useSyncExternalStore(\n subscribeOverridesChanged,\n () =>\n typeof window === 'undefined'\n ? null\n : ((window as unknown as { __sentient_layout_override?: string[] })\n .__sentient_layout_override ?? null),\n () => null,\n );\n return override ?? contextOrder;\n}\n\n/** Internal: SSR-preloaded slot results for hydration-safe first render. */\nexport function useInitialSlots(): Record<string, SlotResult> {\n return useContext(AdaptiveContext).initialSlots;\n}\n\n/** Internal: SSR-decided persona carried alongside the client. */\nexport function useInitialPersona(): { persona: string; confidence: number } | null {\n return useContext(AdaptiveContext).initialPersona;\n}\n\n/** Internal: SSR-preloaded registry slot config for hydration-safe AdaptiveSlot. */\nexport function useInitialSlotConfig(): Record<string, SlotConfigEntry> {\n return useContext(AdaptiveContext).initialSlotConfig;\n}\n\n/** Internal: SSR-preloaded site palette for block rendering. */\nexport function useInitialPalette(): SitePalette | null {\n return useContext(AdaptiveContext).initialPalette;\n}\n\n/** Internal: SSR-preloaded site styles for Redesign rendering. */\nexport function useInitialVocabulary(): StyleVocabulary | null {\n return useContext(AdaptiveContext).initialVocabulary;\n}\n\n/** Internal: configured API base URL (devtools fetches /v1/explain against this, never a relative URL). */\nexport function useAdaptiveApiBaseUrl(): string {\n return useContext(AdaptiveContext).apiBaseUrl;\n}\n","/** Per-component weights store with isolated subscriptions. */\n\nexport type VariantWeight = {\n variantId: string;\n pulls: number;\n avgReward: number;\n};\n\nexport type ComponentWeights = {\n componentId: string;\n variants: VariantWeight[];\n updatedAt: number;\n};\n\ntype Listener = (weights: ComponentWeights) => void;\n\nconst store = new Map<string, ComponentWeights>();\nconst listeners = new Map<string, Set<Listener>>();\n\n/**\n * Subscribes a listener to a single component. Returns an unsubscribe function.\n * Updates to other components never trigger this listener.\n */\nexport function subscribe(componentId: string, cb: Listener): () => void {\n let set = listeners.get(componentId);\n if (!set) {\n set = new Set();\n listeners.set(componentId, set);\n }\n set.add(cb);\n return () => {\n set!.delete(cb);\n if (set!.size === 0) listeners.delete(componentId);\n };\n}\n\n/**\n * Replaces the weights for a component and notifies only that component's\n * subscribers.\n */\nexport function update(componentId: string, weights: ComponentWeights): void {\n store.set(componentId, weights);\n const set = listeners.get(componentId);\n if (!set) return;\n for (const cb of set) {\n try {\n cb(weights);\n } catch {\n /* never throw to other listeners */\n }\n }\n}\n\n/**\n * Returns the latest known weights for a component, or null if none seen.\n */\nexport function getWeights(componentId: string): ComponentWeights | null {\n return store.get(componentId) ?? null;\n}\n\n/** Test-only: wipe the entire store. */\nexport function _resetWeightsStore(): void {\n store.clear();\n listeners.clear();\n}\n","import type { SentientClient } from '@sentientui/core';\n\ntype PreviewState = { on: boolean; listeners: Set<() => void> };\nconst ssrFallback: PreviewState = { on: false, listeners: new Set() };\n\n// Window-backed: the /devtools entry (a separate bundle) toggles preview mode\n// and the provider (main bundle) must observe it.\nfunction state(): PreviewState {\n if (typeof window === 'undefined') return ssrFallback;\n const w = window as unknown as { __sentient_preview?: PreviewState };\n if (!w.__sentient_preview) w.__sentient_preview = { on: false, listeners: new Set() };\n return w.__sentient_preview;\n}\n\nexport function setPreviewMode(on: boolean): void {\n const s = state();\n if (s.on === on) return;\n s.on = on;\n for (const fn of s.listeners) fn();\n}\n\nexport function getPreviewMode(): boolean {\n return state().on;\n}\n\nexport function subscribePreview(fn: () => void): () => void {\n const listeners = state().listeners;\n listeners.add(fn);\n return () => {\n listeners.delete(fn);\n };\n}\n\n/**\n * Wraps a client so it writes nothing: reads pass through, all emitters no-op.\n * Used while previewing variants/personas so no `variant_assigned`, goal, or\n * session events are sent.\n */\nexport function createPreviewClient(inner: SentientClient): SentientClient {\n return {\n isLocal: inner.isLocal,\n track: () => undefined,\n goal: () => undefined,\n componentGoal: () => undefined,\n identify: () => undefined,\n fetchWeights: () => Promise.resolve([]),\n getAssignment: (componentId, segment) => inner.getAssignment(componentId, segment),\n isUnified: (componentId) => inner.isUnified?.(componentId) ?? false,\n assign: (componentId, variantIds, agentData, agentDataByVariant, opts) =>\n inner.assign(componentId, variantIds, agentData, agentDataByVariant, opts),\n // Reads pass through; decide is a write (slot decisions persist server-side)\n // so preview mode never issues it.\n decide: () => Promise.resolve(null),\n getSlotResult: (slotId) => inner.getSlotResult(slotId),\n getSlotConfig: (slotId) => inner.getSlotConfig(slotId),\n getSitePalette: () => inner.getSitePalette(),\n reportSlots: (ids) => inner.reportSlots(ids),\n getPersona: () => inner.getPersona(),\n getGraph: () => inner.getGraph(),\n flush: () => inner.flush(),\n dispose: () => inner.dispose(),\n destroy: () => inner.destroy(),\n };\n}\n","/**\n * Cross-bundle re-render bus for devtools overrides. The main entry and the\n * /devtools entry are separate bundles, so state and notifications go through\n * window (a version counter + a DOM event) — never module-local state.\n */\nconst EVENT = 'sentient:overrides-changed';\n\ntype VersionWindow = Window & { __sentient_overrides_version?: number };\n\nexport function getOverridesVersion(): number {\n if (typeof window === 'undefined') return 0;\n return (window as VersionWindow).__sentient_overrides_version ?? 0;\n}\n\nexport function notifyOverridesChanged(): void {\n if (typeof window === 'undefined') return;\n const w = window as VersionWindow;\n w.__sentient_overrides_version = (w.__sentient_overrides_version ?? 0) + 1;\n window.dispatchEvent(new Event(EVENT));\n}\n\nexport function subscribeOverridesChanged(fn: () => void): () => void {\n if (typeof window === 'undefined') return () => undefined;\n window.addEventListener(EVENT, fn);\n return () => window.removeEventListener(EVENT, fn);\n}\n","/** Provider → devtools config handoff. Window-backed: the /devtools entry is a\n * separate bundle and cannot share the provider's React context instance. */\nexport type DevtoolsConfig = {\n apiKey: string;\n apiBaseUrl: string;\n isLocal: boolean;\n};\n\ntype ConfigWindow = Window & { __sentient_devtools_config?: DevtoolsConfig };\n\nexport function publishDevtoolsConfig(config: DevtoolsConfig): void {\n if (typeof window === 'undefined') return;\n (window as ConfigWindow).__sentient_devtools_config = config;\n}\n\nexport function readDevtoolsConfig(): DevtoolsConfig | null {\n if (typeof window === 'undefined') return null;\n return (window as ConfigWindow).__sentient_devtools_config ?? null;\n}\n","import type { GoalName } from './goal-names.js';\nimport type { SentientClient } from '@sentientui/core';\n\ndeclare const process: { env?: { NODE_ENV?: string } } | undefined;\n\n/**\n * True unless NODE_ENV is 'production'. Never `process?.env` — optional\n * chaining still throws ReferenceError on an undeclared global, and browsers\n * without a bundler shim (raw esbuild, vanilla script tags) have no `process`.\n */\nexport function isDevBuild(): boolean {\n return typeof process === 'undefined' || process.env?.NODE_ENV !== 'production';\n}\n\n/**\n * The element `<Adaptive>` renders around its content (audit S17: it was\n * always a `<div>`, which is invalid inside a `<ul>`, a `<p>` or a table row\n * and broke `display: grid` children). Intrinsic tags only: the wrapper is\n * what exposure, goals and micro-signals observe, so it must be a real box —\n * `display: contents` would give IntersectionObserver nothing to measure.\n */\nexport type AdaptiveElement =\n | 'div' | 'section' | 'article' | 'aside' | 'header' | 'footer' | 'main' | 'nav'\n | 'span' | 'li' | 'figure' | 'form' | 'label' | 'td' | 'th';\n\nexport type ScrollDepthGoal = { type: 'scroll_depth'; threshold: number; value?: number };\nexport type ClickGoal = { type: 'click'; selector?: string; value?: number };\nexport type FormSubmitGoal = { type: 'form_submit'; value?: number };\nexport type CompositeGoal = { type: 'composite'; all: GoalConfig[] };\nexport type WeightedStep = { goal: GoalConfig; name: GoalName; weight: number };\nexport type WeightedCompositeGoal = { type: 'weighted_composite'; steps: WeightedStep[] };\nexport type GoalConfig = ScrollDepthGoal | ClickGoal | FormSubmitGoal | CompositeGoal | WeightedCompositeGoal;\n\nexport function normalizeGoal(goal: string | GoalConfig): GoalConfig {\n if (typeof goal === 'string') return { type: 'click' };\n return goal;\n}\n\n/** The goalType label events are recorded under (named goal or config type). */\nexport function goalLabelOf(goal: string | GoalConfig): string {\n return typeof goal === 'string' ? goal : goal.type;\n}\n\n/** Static revenue value declared on a simple goal config, if any. Composites\n * carry no value (weights and values don't mix — spec §9.4); dynamic values\n * go through the imperative hooks. */\nexport function goalValueOf(goal: string | GoalConfig): number | undefined {\n if (typeof goal === 'string') return undefined;\n if (goal.type === 'click' || goal.type === 'form_submit' || goal.type === 'scroll_depth') {\n return goal.value;\n }\n return undefined;\n}\n\n/**\n * Collapses scroll-depth goal fires that belong to one observation moment.\n *\n * Two nested Adaptive components sharing one scroll_depth goal label attach two\n * SEPARATE IntersectionObservers (they observe different container nodes), and\n * one scroll can satisfy both. The platform delivers all IntersectionObserver\n * notifications for that moment within one task, but runs a microtask\n * checkpoint between the two callback invocations (\"clean up after running\n * script\" fires whenever the JS stack empties — including between separate UA\n * callback invocations in the same task). Core's action latch closes its\n * non-dispatch window on a microtask precisely so a genuine repeat conversion\n * can never be swallowed by a stale window — which means that checkpoint SPLITS\n * the two observer callbacks into two windows, and the goal double-records.\n *\n * So the collapse for this one double-fire lives here, at the layer that knows\n * both fires are scroll-driven, instead of widening core's window for every\n * caller. The scope is one task — the very clock core abandoned — and that is\n * safe HERE for the reason it was wrong there: core's window could be jumped\n * because ANY code (an already-armed timer on the page) can call goal(), so a\n * genuinely separate conversion could land inside a window that outlived its\n * action. Every caller of this gate is an IntersectionObserver callback; timers\n * never consult it, and a genuinely separate scroll fire arrives in a later\n * rendering-update task. Worst case, an implausibly delayed close collapses two\n * same-label, same-value scroll fires — exactly the collapse this gate exists\n * to perform — never a differently-valued or click-driven conversion.\n */\nconst scrollFiredThisTask = new Set<string>();\nlet scrollGateClearArmed = false;\n\nexport function scrollFireCollapsedThisTask(key: string): boolean {\n if (scrollFiredThisTask.has(key)) return true;\n scrollFiredThisTask.add(key);\n if (!scrollGateClearArmed) {\n scrollGateClearArmed = true;\n const clear = (): void => {\n scrollGateClearArmed = false;\n scrollFiredThisTask.clear();\n };\n // MessageChannel over setTimeout when available: fake-timer test setups\n // freeze setTimeout, which would latch the gate open and swallow every\n // later scroll goal (the same hazard core's old clearNextTask named).\n // Both are macrotasks, so either closes the window after this task.\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 } else {\n setTimeout(clear, 0);\n }\n }\n return false;\n}\n\nfunction isClickableTarget(el: EventTarget | null): boolean {\n if (!(el instanceof Element)) return false;\n const tag = el.tagName.toLowerCase();\n if (tag === 'a' || tag === 'button') return true;\n const role = el.getAttribute('role');\n return role === 'button';\n}\n\nfunction findClickable(start: Element, container: Element, selector?: string): boolean {\n if (selector) {\n try {\n let cursor: Element | null = start;\n while (cursor && cursor !== container) {\n if (cursor.matches(selector)) return true;\n cursor = cursor.parentElement;\n }\n } catch {\n // Invalid CSS selector — treat as no match rather than breaking all click handlers.\n }\n return false;\n }\n let cursor: Element | null = start;\n while (cursor && cursor !== container) {\n if (isClickableTarget(cursor)) return true;\n cursor = cursor.parentElement;\n }\n return false;\n}\n\nexport type GoalHandlers = {\n /** Primary goal completion. Latch-once semantics are the CALLER's job. */\n fireGoal: () => void;\n /** Weighted-composite step completion (already deduped per step here). */\n fireStep: (name: string, weight: number, stepIndex: number) => void;\n};\n\n/**\n * Attaches the goal-detection listeners `<Adaptive>`'s container uses —\n * click / form_submit / scroll_depth, composite (all-of), and\n * weighted_composite (independent steps). Returns the cleanup function.\n * Extracted from adaptive.tsx so useAdaptive / useAdaptiveTokens /\n * AdaptiveGroup wire the SAME machinery instead of duplicating it.\n *\n * `scrollDedupeKey` is the goal LABEL: nested instances sharing a label and\n * satisfied by one scroll moment are one user action, whatever value each\n * instance declares, so scroll-driven fires collapse per label — see\n * scrollFireCollapsedThisTask. (The inner instance's observer is created first\n * and its callback delivered first, so when an inner valued goal nests in a\n * valueless wrapper, the valued fire is the one that wins the gate.)\n * Click/submit fires never consult it: those share a real event dispatch,\n * which core's action latch already collapses on.\n */\nexport function attachGoalListeners(\n node: Element,\n goal: GoalConfig,\n handlers: GoalHandlers,\n scrollDedupeKey?: string,\n): () => void {\n // --- Weighted composite: each step fires independently as it completes ---\n if (goal.type === 'weighted_composite') {\n const firedSteps = new Set<number>();\n const wcCleanups: Array<() => void> = [];\n\n goal.steps.forEach(({ goal: sub, name: stepName, weight: stepWeight }, idx) => {\n // viaScroll: a step completed by an IntersectionObserver callback runs the\n // same nested-instance double-fire risk as a plain scroll_depth goal (the\n // microtask checkpoint between two observers' callbacks splits core's\n // window), so it goes through the task gate under its own step identity.\n const fireStep = (viaScroll = false): void => {\n if (firedSteps.has(idx)) return;\n if (\n viaScroll &&\n scrollDedupeKey !== undefined &&\n scrollFireCollapsedThisTask(`step\\0${stepName}\\0${stepWeight}\\0${idx}`)\n ) {\n return;\n }\n firedSteps.add(idx);\n handlers.fireStep(stepName, stepWeight, idx);\n };\n\n if (sub.type === 'click') {\n const onClick = (e: Event): void => {\n const target = e.target;\n if (!(target instanceof Element)) return;\n if (!findClickable(target, node, sub.selector)) return;\n fireStep();\n };\n node.addEventListener('click', onClick);\n wcCleanups.push(() => node.removeEventListener('click', onClick));\n return;\n }\n\n if (sub.type === 'form_submit') {\n const onSubmit = (e: Event): void => {\n if (!(e.target instanceof HTMLFormElement)) return;\n if (!node.contains(e.target)) return;\n fireStep();\n };\n node.addEventListener('submit', onSubmit);\n wcCleanups.push(() => node.removeEventListener('submit', onSubmit));\n return;\n }\n\n if (sub.type === 'scroll_depth') {\n const threshold = Math.max(0, Math.min(1, sub.threshold));\n const io = new IntersectionObserver(\n (entries) => {\n for (const entry of entries) {\n if (entry.intersectionRatio >= threshold) {\n fireStep(true);\n io.disconnect();\n break;\n }\n }\n },\n { threshold: [threshold] },\n );\n io.observe(node);\n wcCleanups.push(() => io.disconnect());\n }\n });\n\n return () => {\n for (const c of wcCleanups) c();\n };\n }\n // --- End weighted composite ---\n\n const subgoals: GoalConfig[] = goal.type === 'composite' ? goal.all : [goal];\n const remaining = new Set<number>(subgoals.map((_, i) => i));\n // The scroll gate is consulted only at the moment a goal actually FIRES from\n // a scroll callback — never when a scroll merely completes one subgoal of a\n // still-open composite. Consulting it early would claim the key for an\n // instance that fires nothing, suppressing the nested instance that would\n // have fired, and the conversion would be lost outright.\n const fireViaScroll = (): void => {\n if (scrollDedupeKey !== undefined && scrollFireCollapsedThisTask(scrollDedupeKey)) return;\n handlers.fireGoal();\n };\n const checkComposite = (idx: number, viaScroll = false): void => {\n remaining.delete(idx);\n if (remaining.size !== 0) return;\n if (viaScroll) fireViaScroll();\n else handlers.fireGoal();\n };\n\n const cleanups: Array<() => void> = [];\n\n subgoals.forEach((sub, idx) => {\n if (sub.type === 'click') {\n const onClick = (e: Event): void => {\n const target = e.target;\n if (!(target instanceof Element)) return;\n if (!findClickable(target, node, sub.selector)) return;\n if (goal.type === 'composite') checkComposite(idx);\n else handlers.fireGoal();\n };\n node.addEventListener('click', onClick);\n cleanups.push(() => node.removeEventListener('click', onClick));\n return;\n }\n\n if (sub.type === 'form_submit') {\n const onSubmit = (e: Event): void => {\n if (!(e.target instanceof HTMLFormElement)) return;\n if (!node.contains(e.target)) return;\n if (goal.type === 'composite') checkComposite(idx);\n else handlers.fireGoal();\n };\n node.addEventListener('submit', onSubmit);\n cleanups.push(() => node.removeEventListener('submit', onSubmit));\n return;\n }\n\n if (sub.type === 'scroll_depth') {\n const threshold = Math.max(0, Math.min(1, sub.threshold));\n const io = new IntersectionObserver(\n (entries) => {\n for (const entry of entries) {\n if (entry.intersectionRatio >= threshold) {\n if (goal.type === 'composite') checkComposite(idx, true);\n else fireViaScroll();\n io.disconnect();\n break;\n }\n }\n },\n { threshold: [threshold] },\n );\n io.observe(node);\n cleanups.push(() => io.disconnect());\n return;\n }\n });\n\n return () => {\n for (const c of cleanups) c();\n };\n}\n\n/**\n * Funnel declaration (spec §7.4): one steps-declaration per funnel per page\n * load; membership is per component and idempotent server-side, so re-sends\n * are harmless but avoided. Only a weighted_composite carries steps — a plain\n * goal declares membership only (the funnel must exist server-side already).\n */\nconst declaredFunnels = new Set<string>();\nconst declaredMemberships = new Set<string>();\n\n/** Test-only: clears the page-load dedup sets. */\nexport function __resetFunnelDeclarations(): void {\n declaredFunnels.clear();\n declaredMemberships.clear();\n}\n\n/**\n * The funnel a weighted composite declares when no `funnel` prop names one.\n * Composites and funnels are one model: without this, a composite on its own\n * was credited the SUM of its steps' weights while the same steps under a\n * `funnel` prop earned the furthest step reached — two rewards for one\n * journey, picked by whether a prop was present. Deterministic from the\n * component id so every page and visit lands on the same funnel; the\n * `-steps` suffix keeps it off ids a human is likely to author (a human funnel\n * with the id would otherwise absorb the component as a member).\n */\nexport function compositeFunnelId(componentId: string): string {\n const slug = componentId.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 100);\n // A lossy slug (\"Hero CTA\" and \"hero_cta\" both → \"hero-cta\") gets a short\n // hash of the raw id so two components never share one funnel.\n if (slug && slug === componentId) return `${slug}-steps`;\n let h = 5381;\n for (let i = 0; i < componentId.length; i++) h = ((h << 5) + h + componentId.charCodeAt(i)) >>> 0;\n return `${slug || 'component'}-${h.toString(36)}-steps`;\n}\n\nconst MAX_FUNNEL_STEPS = 12;\n\n/**\n * A composite's steps as a funnel declaration the server will ACCEPT\n * (funnel-declare parseSteps + validateFunnelSteps). A rejected declaration is\n * silent and leaves the component off the funnel, back on the summed-steps\n * reward — so instead of sending something invalid: weights clamp to [0, 1];\n * a repeated name, a name the server can't take as a goal id (empty, > 128,\n * the reserved `funnel:` prefix) and anything past 12 steps are skipped.\n *\n * Steps are then ORDERED BY WEIGHT, lowest first. A composite's steps were\n * never ordered — each was credited on its own and summed — so the weight is\n * the only statement of which step matters most. Keeping the listed order made\n * a low-value step listed last the funnel's completion (full credit) and the\n * real conversion an intermediate step: the objective, inverted. The sort is\n * stable, so equal weights keep their listed order. Dev builds say when any of\n * this changed what was written.\n */\nexport function compositeFunnelSteps(componentId: string, goal: WeightedCompositeGoal): Array<{ goalId: string; weight: number }> {\n const seen = new Set<string>();\n const steps: Array<{ goalId: string; weight: number }> = [];\n for (const s of goal.steps) {\n const n = s.name;\n if (!n || n.length > 128 || n.startsWith('funnel:') || seen.has(n) || steps.length === MAX_FUNNEL_STEPS) continue;\n seen.add(n);\n steps.push({ goalId: n, weight: Math.min(1, Math.max(0, s.weight || 0)) });\n }\n const ordered = [...steps].sort((a, b) => a.weight - b.weight);\n // Bundle budget: one message for every adjustment, not one per kind.\n if ((steps.length < goal.steps.length || ordered.some((s, i) => s !== steps[i])) && isDevBuild()) {\n console.warn(`[SentientUI] \"${componentId}\": weighted_composite steps adjusted for its funnel (skipped invalid/repeated/over-12 steps, or ordered by weight)`);\n }\n return ordered;\n}\n\n/**\n * Declares the component's funnel: the explicit `funnel` prop, else — for a\n * weighted composite — its own derived funnel (compositeFunnelId). Anything\n * else declares nothing.\n */\nexport function maybeDeclareFunnel(\n client: SentientClient,\n apiKey: string,\n componentId: string,\n explicitFunnelId: string | undefined,\n goal: GoalConfig | null,\n): void {\n const composite = goal?.type === 'weighted_composite' ? goal : null;\n const funnelId = explicitFunnelId ?? (composite ? compositeFunnelId(componentId) : undefined);\n if (!funnelId) return;\n const memberKey = `${funnelId}|${componentId}`;\n if (declaredMemberships.has(memberKey)) return;\n declaredMemberships.add(memberKey);\n // Counted AFTER cleaning: a composite whose steps dedupe to one is a single\n // goal, not a funnel (the server needs 2+, and rejecting it would leave the\n // component on the summed rule).\n const steps = composite && !declaredFunnels.has(funnelId) ? compositeFunnelSteps(componentId, composite) : null;\n const withSteps = steps !== null && steps.length >= 2;\n if (withSteps) declaredFunnels.add(funnelId);\n if (!withSteps && explicitFunnelId === undefined) return; // nothing a derived funnel could join\n client.track({\n projectId: apiKey,\n componentId,\n eventType: 'funnel_declared',\n payload: withSteps ? { funnelId, steps } : { funnelId },\n });\n}\n\n/**\n * Records the `variant_assigned` exposure event.\n */\nexport function trackExposure(\n client: SentientClient,\n apiKey: string,\n componentId: string,\n variantId: string,\n): void {\n client.track({\n projectId: apiKey,\n componentId,\n variantId,\n eventType: 'variant_assigned',\n payload: {},\n });\n}\n","import { isDevBuild } from './adaptive-shared.js';\n\nexport type RegisteredComponent = { id: string; variantIds: string[]; goal?: string };\nexport type RegisteredSlot = {\n id: string;\n arms?: string[];\n dims?: Record<string, readonly string[]>;\n};\n\ntype RegistryState = {\n components: Map<string, RegisteredComponent>;\n slots: Map<string, RegisteredSlot>;\n sections: string[];\n listeners: Set<() => void>;\n /** Bumped on every mutation so `useSyncExternalStore` can read a stable, comparable snapshot. */\n version: number;\n};\n\n// Shared through a window global: the main entry and the /devtools entry are\n// separate bundles, each with its own copy of this module — module-local\n// state would give the devtools an always-empty registry in published apps.\nconst ssrFallback: RegistryState = {\n components: new Map(),\n slots: new Map(),\n sections: [],\n listeners: new Set(),\n version: 0,\n};\n\nfunction state(): RegistryState {\n if (typeof window === 'undefined') return ssrFallback;\n const w = window as unknown as { __sentient_registry?: RegistryState };\n if (!w.__sentient_registry) {\n w.__sentient_registry = {\n components: new Map(),\n slots: new Map(),\n sections: [],\n listeners: new Set(),\n version: 0,\n };\n }\n return w.__sentient_registry;\n}\n\nfunction emit(): void {\n // Bump BEFORE notifying so a useSyncExternalStore consumer re-reading its\n // snapshot inside the notification sees the new value and re-renders.\n state().version += 1;\n for (const fn of state().listeners) fn();\n}\n\n// The registry exists solely to feed the opt-in devtools panel, which is a\n// dev-only surface. In a production build there is no panel reading it, so\n// every register call is dead work plus a `window.__sentient_registry`\n// footprint on the customer's page. Short-circuit to a noop in production —\n// every <Adaptive>/useAdaptive/slot mount calls one of these.\nconst NOOP_UNREGISTER = (): void => undefined;\n\n/** Register (or re-register) a component. Returns an unregister function. */\nexport function registerComponent(c: RegisteredComponent): () => void {\n if (!isDevBuild()) return NOOP_UNREGISTER;\n state().components.set(c.id, c);\n emit();\n return () => {\n state().components.delete(c.id);\n emit();\n };\n}\n\n/** Register (or re-register) a slot declaration. Returns an unregister function. */\nexport function registerSlot(s: RegisteredSlot): () => void {\n if (!isDevBuild()) return NOOP_UNREGISTER;\n state().slots.set(s.id, s);\n emit();\n return () => {\n state().slots.delete(s.id);\n emit();\n };\n}\n\n/** Register the page's declared section ids (from AdaptiveRoot/provider). */\nexport function registerSections(sections: string[]): void {\n if (!isDevBuild()) return;\n state().sections = [...sections];\n emit();\n}\n\nexport function getRegistered(): RegisteredComponent[] {\n return [...state().components.values()];\n}\n\nexport function getRegisteredSlots(): RegisteredSlot[] {\n return [...state().slots.values()];\n}\n\nexport function getRegisteredSections(): string[] {\n return [...state().sections];\n}\n\nexport function subscribeRegistry(fn: () => void): () => void {\n const listeners = state().listeners;\n listeners.add(fn);\n return () => {\n listeners.delete(fn);\n };\n}\n\n/** Monotonic snapshot for `useSyncExternalStore` — changes on every registry mutation. */\nexport function getRegistryVersion(): number {\n return state().version;\n}\n","/**\n * This package's released build version, injected by tsup's `define` from\n * package.json (see tsup.config.ts) so the version inside a published bundle\n * can never drift from the version on npm. Mirrors the snippet's\n * `__SNIPPET_VERSION__`.\n *\n * Why the React SDK reports a version at all: unlike the snippet, it is a\n * build-time npm dependency, so it CANNOT self-update — a customer on an old\n * release stays there until they run an install. Telling them they're behind is\n * the only remedy available, and the dashboard can only tell them if the\n * running bundle says what it is.\n */\ndeclare const __REACT_SDK_VERSION__: string;\n\nexport const version: string =\n typeof __REACT_SDK_VERSION__ !== 'undefined' ? __REACT_SDK_VERSION__ : '0.0.0-dev';\n\n/**\n * The identity handed to core's session upsert, or undefined for a dev build.\n * The '0.0.0-dev' sentinel (unit tests, or any build without tsup's define)\n * passes the server's semver validation and would be persisted as the\n * project's SDK version, leaving the dashboard permanently claiming the\n * project is behind — the same trap the snippet documents as audit M12.\n */\nexport const SDK_IDENT: { name: string; version: string } | undefined =\n version !== '0.0.0-dev' ? { name: 'react', version } : undefined;\n","import type { SlotConfigEntry, StyleVocabulary } from '@sentientui/core';\n\n/**\n * Slot-CONFIG override store — the channel `useSlotConfig` reads (AdaptiveSlot).\n * Separate from `__sentient_slot_overrides` (which forces the slot RESULT — the\n * arm): forcing an arm alone can't test AdaptiveSlot's rendering, because the\n * content/blocks live in the config entry. Window-backed so the /devtools and\n * /testing bundles and the main bundle share one store.\n */\nfunction store(): Record<string, SlotConfigEntry> {\n const w = window as unknown as { __sentient_slot_config_overrides?: Record<string, SlotConfigEntry> };\n if (!w.__sentient_slot_config_overrides) w.__sentient_slot_config_overrides = {};\n return w.__sentient_slot_config_overrides;\n}\n\n/** Force `slotId`'s config entry — read by `useSlotConfig`. */\nexport function setSlotConfigOverride(slotId: string, entry: SlotConfigEntry): void {\n store()[slotId] = entry;\n}\n\n/** Site styles for forced configs (the on-site preview of a redesigned\n * section): the decision that would normally carry them never ran. */\nexport function setVocabularyOverride(v: StyleVocabulary | null): void {\n (window as unknown as { __sentient_vocabulary_override?: StyleVocabulary | null }).__sentient_vocabulary_override = v;\n}\n\nexport function getVocabularyOverride(): StyleVocabulary | null {\n if (typeof window === 'undefined') return null;\n return (window as unknown as { __sentient_vocabulary_override?: StyleVocabulary | null }).__sentient_vocabulary_override ?? null;\n}\n\nexport function clearSlotConfigOverride(slotId: string): void {\n delete store()[slotId];\n}\n\nexport function getSlotConfigOverrides(): Record<string, SlotConfigEntry> {\n return { ...store() };\n}\n","import type { SlotResult } from '@sentientui/core';\n\n/**\n * Slot-override store — the channel `useSlotResult` reads (`useAdaptiveTokens` /\n * `AdaptiveGroup`). Separate from `__sentient_overrides` (variant components):\n * a slot result is a token object (`{ tone: 'urgent' }`) or an arm string\n * (`'social_first'`), never a bare variant id. Window-backed so the /devtools\n * bundle and the main bundle share one store.\n */\nfunction store(): Record<string, SlotResult> {\n const w = window as unknown as { __sentient_slot_overrides?: Record<string, SlotResult> };\n if (!w.__sentient_slot_overrides) w.__sentient_slot_overrides = {};\n return w.__sentient_slot_overrides;\n}\n\n/** Force `slotId` to resolve to `result` — read by `useSlotResult`. */\nexport function setSlotOverride(slotId: string, result: SlotResult): void {\n store()[slotId] = result;\n}\n\nexport function clearSlotOverride(slotId: string): void {\n delete store()[slotId];\n}\n\nexport function getSlotOverrides(): Record<string, SlotResult> {\n return { ...store() };\n}\n","// Credentials the dashboard hands the site (`sentient_preview_token`, the\n// editor's one-time `sentient_editor_code`) ride the URL FRAGMENT, which is\n// never sent over the network — no server/CDN log, no Referer (grades C13, E1).\n//\n// The fragment is also where hash-routed sites keep their route (grade E2).\n// The first version wrote `#sentient_preview_token=…` over the whole hash, so a\n// preview of `/#/pricing` opened the home route instead. The dashboard now\n// APPENDS the param (appendHashParam in apps/dashboard/app/lib/hash-param.ts):\n// '' → #name=v\n// '/pricing' → #/pricing?name=v (routers read it as a query param, so\n// '/p?x=1' → #/p?x=1&name=v the route still matches pre-strip)\n// and this takes it back out, restoring the site's own hash EXACTLY — or\n// removing the '#' altogether when the site had none. Twin of\n// packages/snippet/src/hash-param.ts (the snippet cannot import this package\n// and vice versa); keep the two in step — both suites run the same cases.\nexport function takeHashParam(name: string): string | null {\n let v: string | null = null;\n try {\n const h = location.hash.slice(1);\n const m = RegExp('(^|[?&])' + name + '=([^&]*)').exec(h);\n if (m) {\n // Taken BEFORE the rewrite: an opaque-origin frame may refuse\n // replaceState, and the value is still ours to use. Base64url, so no\n // decoding (the dashboard never percent-encodes it).\n v = m[2]!;\n let after = h.slice(m.index + m[0].length);\n // '?name=v&rest' / 'name=v&rest': the next param inherits the separator.\n if (m[1] != '&' && after[0] == '&') after = m[1] + after.slice(1);\n const rest = h.slice(0, m.index) + after;\n // replaceState, not location.hash=: no hashchange, so a hash router does\n // not re-route mid-boot; history.state kept so its entry key survives.\n history.replaceState(history.state, '', rest ? '#' + rest : location.pathname + location.search);\n }\n } catch {\n /* fail-safe */\n }\n return v;\n}\n","// The operator's editor session on a React site (dashboard \"Preview on your\n// site\", \"Refresh from page\", style capture). The dashboard sends a one-time\n// code in the URL FRAGMENT (#sentient_editor_code=, grade E1) — never the\n// token itself, which as `?sentient_editor=` reached server/CDN logs,\n// analytics page URLs and Referer headers, and can publish. This trades the\n// code for the token (POST /v1/editor/exchange; the API checks the Origin is\n// the project's own) and keeps the token in sessionStorage only.\n//\n// Memoised: cell preview, region refresh and style capture all ask, but the\n// code is single use — a second exchange would be refused and whichever\n// caller lost the race would report an \"expired\" link that was fine.\nimport { takeHashParam } from './hash-param.js';\n\n// Same key as the snippet's cache, so both SDKs agree on \"this tab is in an\n// editor session\" if a page ever carries both.\nconst TOKEN_KEY = '__snt_editor_token';\n\nexport type EditorSession = { token: string; fresh: boolean };\ntype Outcome = EditorSession | { error: number } | null;\n\nlet pending: Promise<Outcome> | null = null;\nlet active = false;\n\n/** Synchronous: did editorSession() find a code or a cached token? Lets a\n * caller refuse to act on a bare URL param (a visitor, not an operator)\n * without waiting for the exchange — the old token-in-query check was sync. */\nexport function editorSessionActive(): boolean {\n return active;\n}\n\nfunction cached(): string | null {\n try {\n return sessionStorage.getItem(TOKEN_KEY);\n } catch {\n return null;\n }\n}\n\n/**\n * The editor token for this page view: exchanged from a fresh fragment code\n * (`fresh: true`), else the one cached earlier in this tab. `{ error }` is a\n * refused exchange (401 = expired/used, anything else = couldn't load); null\n * means this is not an editor session at all.\n */\nexport function editorSession(apiBase: string): Promise<Outcome> {\n if (pending) return pending;\n const code = typeof window === 'undefined' ? null : takeHashParam('sentient_editor_code');\n if (!code) {\n const t = typeof window === 'undefined' ? null : cached();\n active = !!t;\n pending = Promise.resolve(t ? { token: t, fresh: false } : null);\n return pending;\n }\n active = true;\n pending = fetch(`${apiBase}/editor/exchange`, {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify({ code }),\n })\n .then(async (res): Promise<Outcome> => {\n const token = res.ok ? ((await res.json()) as { token?: string }).token : undefined;\n if (!token) return { error: res.ok ? 500 : res.status };\n try {\n sessionStorage.setItem(TOKEN_KEY, token);\n } catch {\n /* the session still works for this page view */\n }\n return { token, fresh: true };\n })\n .catch((): Outcome => ({ error: 0 }));\n return pending;\n}\n\n/** End the session (Exit preview): a reload is a normal visit again. */\nexport function endEditorSession(): void {\n try {\n sessionStorage.removeItem(TOKEN_KEY);\n } catch {\n /* fail-safe */\n }\n}\n\n/** Test hook. */\nexport function resetEditorSessionForTests(): void {\n pending = null;\n active = false;\n}\n","// On-site preview for generated versions (the dashboard's \"Preview on your\n// site\" link): ?sentient_preview_cell=<slotId>~<persona>#sentient_editor_code=…\n// (a one-time code exchanged for the editor token — editor-session.ts, E1)\n// fetches the square's PENDING (review) or live arm through the editor-token\n// API and forces it through the devtools override channel — which AdaptiveSlot\n// already renders IN PLACE, with the page's real CSS, and WITHOUT recording an\n// exposure ('override' source is excluded from tracking by design). A floating\n// bar names what is being previewed and offers Exit.\n//\n// Deliberately framework-light: the bar is plain DOM (no React tree to mount\n// into), and everything no-ops without both params, so normal visitors pay\n// one URLSearchParams read.\nimport { setSlotConfigOverride, setVocabularyOverride } from './devtools-slot-config-overrides.js';\nimport { setSlotOverride } from './devtools-slot-overrides.js';\nimport { notifyOverridesChanged } from './override-events.js';\nimport { editorSession, editorSessionActive, endEditorSession } from './editor-session.js';\nimport type { ComposeArm, StyleVocabulary } from '@sentientui/core';\n\nconst PARAM_CELL = 'sentient_preview_cell';\nconst PARAM_REFRESH = 'sentient_refresh_region';\nconst BAR_ID = 'sentient-cell-preview-bar';\nconst PREVIEW_ARM = '__preview__';\n\ntype CellPreviewResponse = {\n status: 'review' | 'live';\n slotName: string;\n personaDisplay: string;\n content: string | null;\n blocks: unknown | null;\n edits?: unknown;\n skeletonFp?: string;\n leafToNode?: number[];\n compose?: unknown;\n vocabulary?: StyleVocabulary;\n};\n\n// \"Refresh from page\" (spec 2026-09-23 §4.2): the operator says the region\n// changed. The capture runs INSIDE the AdaptiveSlot — only it holds the\n// children the element-tree parity check needs — so this module just forces\n// the original to show and leaves the request here for the slot to take.\n// `session` is a promise: the token arrives by exchange after this module ran,\n// but the slot's capture effect may run first and only once — holding the\n// promise lets it take the request now and post when the token lands.\ntype RegionRefresh = { slotId: string; session: ReturnType<typeof editorSession>; base: string };\nlet pendingRefresh: RegionRefresh | null = null;\n\n/** The refresh this page was opened for, if it targets `slotId`. Taken once. */\nexport function takeRegionRefresh(slotId: string): RegionRefresh | null {\n if (pendingRefresh?.slotId !== slotId) return null;\n const r = pendingRefresh;\n pendingRefresh = null;\n return r;\n}\n\n/** Post a trusted skeleton and tell the operator how it went. */\nexport function submitRegionRefresh(r: RegionRefresh, body: Record<string, unknown>): void {\n void r.session\n .then((s) => {\n if (!s || !('token' in s)) throw new Error('no editor session');\n return fetch(`${r.base}/editor/region-skeleton`, {\n method: 'POST',\n headers: { authorization: `Bearer ${s.token}`, 'content-type': 'application/json' },\n body: JSON.stringify({ slotId: r.slotId, ...body }),\n });\n })\n .then((res) =>\n mountBar(res.ok ? 'Region refreshed — you can regenerate its versions now.' : 'Couldn’t refresh this region — reopen the link from your dashboard.'),\n )\n .catch(() => mountBar('Couldn’t refresh this region — check your connection and reopen the link from your dashboard.'));\n}\n\n/** Start the on-site cell preview when the URL asks for one. Idempotent. */\nexport function maybeStartCellPreview(apiBaseUrl?: string): void {\n if (typeof window === 'undefined' || typeof document === 'undefined') return;\n if (document.getElementById(BAR_ID)) return;\n let cell: string | null;\n let refresh: string | null;\n try {\n const params = new URLSearchParams(window.location.search);\n cell = params.get(PARAM_CELL);\n refresh = params.get(PARAM_REFRESH);\n } catch {\n return;\n }\n if (!cell && !refresh) return;\n const base = (apiBaseUrl ?? 'https://api.sentient-ui.com/v1').replace(/\\/$/, '');\n const session = editorSession(base);\n // Only an operator's session acts on these params; a visitor who lands on a\n // shared ?sentient_refresh_region= URL gets the normal page.\n if (!editorSessionActive()) return;\n if (refresh) {\n pendingRefresh = { slotId: refresh, session, base };\n // Force the original: a served version on screen is not the region.\n // 'override' records no exposure, so the refresh visit is never a trial.\n setSlotConfigOverride(refresh, { kind: 'arms' });\n setSlotOverride(refresh, PREVIEW_ARM);\n notifyOverridesChanged();\n return;\n }\n if (!cell) return;\n const sep = cell.lastIndexOf('~');\n if (sep <= 0) return;\n const slotId = cell.slice(0, sep);\n const persona = cell.slice(sep + 1);\n\n void session\n .then((s) => {\n // No code and nothing cached: a bare param, not an editor session.\n if (!s) return null;\n if (!('token' in s)) {\n mountBar(s.error === 401\n ? 'This preview link has expired — reopen it from your dashboard.'\n : 'Couldn’t load this preview — reopen it from your dashboard.');\n return null;\n }\n return fetch(`${base}/editor/cell-preview?slotId=${encodeURIComponent(slotId)}&persona=${encodeURIComponent(persona)}`, {\n headers: { authorization: `Bearer ${s.token}` },\n });\n })\n .then(async (res) => {\n if (!res) return;\n if (!res.ok) {\n mountBar(res.status === 401\n ? 'This preview link has expired — reopen it from your dashboard.'\n : 'Couldn’t load this preview — reopen it from your dashboard.');\n return;\n }\n const data = (await res.json()) as CellPreviewResponse;\n if (data.vocabulary && Array.isArray(data.vocabulary.entries)) setVocabularyOverride(data.vocabulary);\n if (data.compose != null) {\n setSlotConfigOverride(slotId, { kind: 'arms', compose: { [PREVIEW_ARM]: data.compose as ComposeArm } });\n setSlotOverride(slotId, PREVIEW_ARM);\n } else if (data.edits != null && typeof data.skeletonFp === 'string' && Array.isArray(data.leafToNode)) {\n setSlotConfigOverride(slotId, { kind: 'arms', edits: { edits: data.edits as never, fp: data.skeletonFp, leafToNode: data.leafToNode } });\n setSlotOverride(slotId, PREVIEW_ARM);\n } else if (data.blocks != null) {\n setSlotConfigOverride(slotId, { kind: 'arms', blocks: { [PREVIEW_ARM]: data.blocks } } as never);\n setSlotOverride(slotId, PREVIEW_ARM);\n } else if (data.content != null) {\n setSlotConfigOverride(slotId, { kind: 'arms', content: data.content });\n setSlotOverride(slotId, PREVIEW_ARM);\n } else {\n mountBar('Nothing to preview in that square yet.');\n return;\n }\n notifyOverridesChanged();\n mountBar(\n `Previewing “${data.slotName}” for ${data.personaDisplay}${data.status === 'review' ? ' — waiting for your approval' : ''}. Nothing is being tracked.`,\n );\n // Bring the slot into view once it re-renders with the forced arm.\n setTimeout(() => {\n try {\n document.querySelector(`[data-sentient-slot=\"${slotId}\"]`)?.scrollIntoView({ block: 'center' });\n } catch {\n /* older browsers */\n }\n }, 300);\n })\n .catch(() => mountBar('Couldn’t load this preview — check your connection and reopen it from your dashboard.'));\n}\n\nfunction mountBar(text: string): void {\n if (document.getElementById(BAR_ID)) return;\n const bar = document.createElement('div');\n bar.id = BAR_ID;\n Object.assign(bar.style, {\n position: 'fixed', bottom: '16px', left: '50%', transform: 'translateX(-50%)', zIndex: '2147483647',\n display: 'flex', alignItems: 'center', gap: '10px', padding: '10px 14px', borderRadius: '12px',\n maxWidth: '90vw', background: '#111827', color: '#fff', font: '13px system-ui, sans-serif',\n border: '1px solid rgba(139,92,246,0.6)', boxShadow: '0 10px 34px rgba(0,0,0,0.45)',\n } satisfies Partial<CSSStyleDeclaration>);\n const label = document.createElement('span');\n label.textContent = text;\n const exit = document.createElement('button');\n exit.textContent = 'Exit preview';\n Object.assign(exit.style, {\n padding: '4px 10px', borderRadius: '999px', border: '1px solid rgba(255,255,255,0.35)',\n background: 'transparent', color: '#fff', font: '12px system-ui, sans-serif', cursor: 'pointer',\n } satisfies Partial<CSSStyleDeclaration>);\n exit.onclick = () => {\n endEditorSession();\n const url = new URL(window.location.href);\n url.searchParams.delete(PARAM_CELL);\n url.searchParams.delete(PARAM_REFRESH);\n window.location.assign(url.toString());\n };\n bar.append(label, exit);\n (document.body ?? document.documentElement).append(bar);\n}\n","// Style-vocabulary capture for React installs (native generation phase 2).\n// React sites never load the snippet editor, so without this a React project\n// (Bodyshop) would only ever get the crawler's colorless guess. Runs ONLY when\n// this page load exchanged a fresh editor code (#sentient_editor_code=, see\n// editor-session.ts), i.e. when an operator opened the page from the dashboard\n// — never for visitors, and not on every later page of a cached session. The\n// sampler is a separate core subpath, dynamically imported, so the normal\n// bundle pays nothing.\nimport { editorSession, resetEditorSessionForTests } from './editor-session.js';\n\nlet started = false;\n\nexport function maybeCaptureStyles(apiBaseUrl?: string): void {\n if (started || typeof window === 'undefined') return;\n started = true;\n const base = (apiBaseUrl ?? 'https://api.sentient-ui.com/v1').replace(/\\/$/, '');\n void editorSession(base).then((session) => {\n if (!session || !('token' in session) || !session.fresh) return;\n capture(base, session.token);\n });\n}\n\nfunction capture(base: string, token: string): void {\n // After load + 1s, so client-rendered heroes exist before we look.\n const run = (): void => {\n window.setTimeout(() => {\n void import('@sentientui/core/style-sample')\n .then(({ sampleStyleVocabulary }) =>\n fetch(`${base}/editor/style-vocabulary`, {\n method: 'POST',\n headers: { authorization: `Bearer ${token}`, 'content-type': 'application/json' },\n body: JSON.stringify(sampleStyleVocabulary(document)),\n }),\n )\n .catch(() => undefined);\n }, 1000);\n };\n if (document.readyState === 'complete') run();\n else window.addEventListener('load', run, { once: true });\n}\n\n/** Test hook. */\nexport function resetStyleCaptureForTests(): void {\n started = false;\n resetEditorSessionForTests();\n}\n","'use client';\n\n// `type JSX` from react, not the global namespace removed in @types/react@19\n// (peers allow react >=18) — see adaptive-text.tsx.\nimport { memo, useCallback, useEffect, useState, type JSX, type ReactNode, type Ref } from 'react';\nimport type { GoalName } from './goal-names.js';\nimport { useVariantComponent, type MicroSignalGoals } from './use-variant-component.js';\nimport { AdaptiveSlot, type AdaptiveSlotProps } from './adaptive-slot.js';\nimport { useInitialUnified, useSentient } from './provider.js';\n\nexport type {\n ScrollDepthGoal,\n ClickGoal,\n FormSubmitGoal,\n CompositeGoal,\n WeightedStep,\n WeightedCompositeGoal,\n GoalConfig,\n} from './adaptive-shared.js';\nimport { isDevBuild, type AdaptiveElement, type GoalConfig } from './adaptive-shared.js';\n\nexport type { MicroSignalGoalConfig, MicroSignalGoals } from './use-variant-component.js';\nexport type { AdaptiveElement } from './adaptive-shared.js';\n\n/** `<Adaptive>` with variants written in code — each key an arm, first key the control. */\nexport type AdaptiveVariantsProps = {\n id: string;\n variants: Record<string, ReactNode>;\n /** Your original. With `variants` AND children the component is a hybrid:\n * your hand-written versions, your original and dashboard-generated\n * versions compete in one experiment (spec 2026-09-23 §7). Without\n * children, `variants` keeps the variants-only experiment it always had. */\n children?: ReactNode;\n goal: GoalName | GoalConfig;\n /**\n * Funnel this component serves (stable funnel id, e.g. \"checkout\" —\n * shown on the dashboard's Funnels tab). Declares membership to the server;\n * a weighted_composite goal also declares the funnel's ordered steps, so a\n * code-first funnel appears in the dashboard without opening it. The\n * optimizer then trains this component on journey progress: small credit for\n * intermediate steps, full (or revenue-scaled) credit at completion.\n */\n funnel?: string;\n /**\n * When a passive micro-signal fires on this component, also record a named goal.\n * Use for inferred goals surfaced in the dashboard (e.g. rage_click → 'confused_by_hero').\n */\n microSignalGoals?: MicroSignalGoals;\n /** Wrapper element. @default 'div' */\n as?: AdaptiveElement;\n /** Class for the wrapper element. */\n className?: string;\n /**\n * When true, renders nothing during SSR and before client hydration.\n * Use when you cannot pass `initialAssignments` and prefer a blank slot over\n * a hydration mismatch. Tradeoff: minor CLS on first paint.\n */\n clientOnly?: boolean;\n /**\n * Variant-specific structured data for AI agent consumption via /sentient.json and\n * GET /v1/agent/layout. Keyed by variant ID — only the assigned variant's entry is stored,\n * so agents see only the content currently being served to visitors.\n *\n * Prefer this over `agentData` when variants have meaningfully different content.\n *\n * Captured at MOUNT: this value is read once, when the component's assignment\n * is requested, and is intentionally not part of the assign effect's deps.\n * Changing it after mount does not re-send it — pass the final value on first\n * render (e.g. from SSR/loader data, not a value that streams in later).\n */\n agentDataByVariant?: Record<string, unknown>;\n /**\n * @deprecated Use agentDataByVariant for variant-specific content. Stored as-is for the assigned variant.\n *\n * Captured at MOUNT (see `agentDataByVariant`): changing it after mount has no\n * effect on what is sent for the assignment.\n */\n agentData?: unknown;\n};\n\n/**\n * `<Adaptive>` without `variants`: the children are your original, and the\n * versions come from the dashboard (generated per visitor type, no redeploy).\n */\nexport type AdaptiveGeneratedProps = Omit<AdaptiveSlotProps, 'children'> & {\n children: ReactNode;\n variants?: undefined;\n};\n\nexport type AdaptiveProps = AdaptiveVariantsProps | AdaptiveGeneratedProps;\n\nfunction AdaptiveImpl(props: AdaptiveVariantsProps & { onUnified?: () => void }): JSX.Element | null {\n // Exposure, funnel, goal listeners, cursor + micro-signals all live in the\n // engine shared with useAdaptive, so a gate added for one applies to both.\n const { client, variantId, content, ref } = useVariantComponent(props.id, props.variants, {\n goal: props.goal,\n funnel: props.funnel,\n microSignalGoals: props.microSignalGoals,\n agentData: props.agentData,\n agentDataByVariant: props.agentDataByVariant,\n cursorSignal: true,\n onUnified: props.onUnified,\n });\n const [mounted, setMounted] = useState(false);\n useEffect(() => { setMounted(true); }, []);\n\n // Decorative slots: empty in SSR HTML and until the client has mounted.\n const Tag = props.as ?? 'div';\n if (props.clientOnly && (!mounted || !client)) return null;\n if (!variantId) return null;\n\n const jsxContent = props.variants[variantId] ?? null;\n const managedContent = jsxContent === null ? content : null;\n\n if (isDevBuild() && jsxContent === null && managedContent === null) {\n console.warn(\n `[sentient] <Adaptive id=\"${props.id}\"> was assigned variant \"${variantId}\" but no matching key exists in props.variants.` +\n ` If this is a dashboard-managed text variant, use <AdaptiveText id=\"${props.id}\"> instead.`,\n );\n }\n\n return (\n <Tag ref={ref as Ref<never>} className={props.className} data-sentient-id={props.id} data-sentient-variant={variantId}>\n {jsxContent ?? managedContent}\n </Tag>\n );\n}\n\n/**\n * Skips re-render only when nothing the output depends on has changed. The\n * variant node values must be compared, not just their keys: the assigned\n * `variantId` is stable, so if we compared keys alone, dynamic content inside a\n * variant (e.g. `<Price value={price}/>`) would render once and then freeze when\n * `price` changes. Elements are compared by reference — a caller that recreates\n * variant JSX on every render re-renders every time (correct), while stable/\n * memoized elements keep the optimization.\n */\nconst AdaptiveVariants = memo(AdaptiveImpl, (prev, next) => {\n if (prev.id !== next.id) return false;\n // Serialize only when the goal reference actually changed — a stable/memoized\n // goal (the common case) skips the stringify entirely.\n if (prev.goal !== next.goal && JSON.stringify(prev.goal) !== JSON.stringify(next.goal)) return false;\n if (prev.microSignalGoals !== next.microSignalGoals) return false;\n // `funnel` feeds the funnel-declaration effect: omitting it here swallowed a\n // funnel added or changed after first render (the memo skipped the re-render\n // that would have re-run the declaration).\n if (prev.funnel !== next.funnel) return false;\n if (prev.clientOnly !== next.clientOnly) return false;\n if (prev.as !== next.as || prev.className !== next.className) return false;\n if (prev.agentData !== next.agentData) return false;\n if (prev.agentDataByVariant !== next.agentDataByVariant) return false;\n if (prev.onUnified !== next.onUnified) return false;\n if (prev.variants === next.variants) return true;\n const prevKeys = Object.keys(prev.variants);\n const nextKeys = Object.keys(next.variants);\n if (prevKeys.length !== nextKeys.length) return false;\n return prevKeys.every((k) => k in next.variants && Object.is(prev.variants[k], next.variants[k]));\n});\n\n/**\n * One component, two ways to fill it. Without `variants`, the children are the\n * original and SentientUI serves dashboard-generated versions (the slot path —\n * what `<AdaptiveSlot>` was). With `variants`, the arms are the JSX you wrote.\n * The two stay separate optimizers underneath (slot_decisions vs the variant\n * bandit, CONTRACTS §1–§2); only the API is shared. Switching a mounted element\n * between modes remounts it, which is the honest behaviour: it becomes a\n * different experiment.\n */\nexport function Adaptive(props: AdaptiveProps): JSX.Element | null {\n if (props.variants === undefined) return <AdaptiveSlot {...props} />;\n const v = props as AdaptiveVariantsProps;\n if (v.children != null) {\n // Hybrid: authored arms + your original + generated versions on ONE slot\n // ledger — never the variant bandit too, which would book two trials per\n // impression (CONTRACTS §2). funnel, microSignalGoals, agentData,\n // agentDataByVariant and clientOnly carry over: the slot path implements\n // each, so a hand-written component keeps them when it gains children.\n const { variants, ...slotProps } = v;\n return <AdaptiveSlot {...(slotProps as Omit<AdaptiveSlotProps, 'variants'>)} children={v.children} variants={variants} />;\n }\n // Variants only: the variant ledger — unless the operator migrated this id.\n // Moving it is the operator's Migrate action, never an SDK upgrade (§7.5);\n // the SDK only follows it (ruling C1).\n return <AdaptiveVariantsOrUnified {...v} />;\n}\n\n/**\n * A variants-only `<Adaptive>`: the variant experiment it always ran, until\n * /v1/assign answers `unified: true` for its id (the operator migrated it —\n * CONTRACTS §2 \"A unified component is a slot\"). From then on it renders\n * through the slot path: its keys are the authored versions, it has no\n * children, so the FIRST key is the control (exactly as variantIds[0] is in\n * variants mode), and generated versions can join it. Without this an upgraded\n * page kept asking for a frozen variant experiment and learned nothing.\n *\n * It may already know before asking (ruling C20): an SSR preload lists the\n * moved ids (`initialUnified`, so the server HTML is already the slot path —\n * AdaptiveRoot `components`, the hero), or the client learned it earlier this\n * page. Then the variant path never mounts: an assignment cached before the\n * move would otherwise settle it, render a frozen variant and expose it.\n *\n * Only this component asks with the cap: useAdaptive has no slot path, so it\n * keeps being served the frozen run read-only (it warns in dev).\n */\nfunction AdaptiveVariantsOrUnified(props: AdaptiveVariantsProps): JSX.Element | null {\n // Keyed on the id: a mounted element whose id changes is a different\n // component, and must ask again rather than inherit the old answer.\n const [unifiedId, setUnifiedId] = useState<string | null>(null);\n const { id } = props;\n const onUnified = useCallback(() => setUnifiedId(id), [id]);\n const client = useSentient();\n // initialUnified is in the SSR render and the first client render alike;\n // the client only exists after hydration, so neither can mismatch.\n const known = useInitialUnified().includes(id) || client?.isUnified?.(id) === true;\n if (unifiedId !== id && !known) return <AdaptiveVariants {...props} onUnified={onUnified} />;\n const { variants, children: _children, ...rest } = props;\n const first = Object.keys(variants)[0];\n return (\n <AdaptiveSlot\n {...(rest as Omit<AdaptiveSlotProps, 'variants' | 'children'>)}\n variants={variants}\n variantsOnly\n >\n {first !== undefined ? variants[first] : null}\n </AdaptiveSlot>\n );\n}\n","import type { GoalName } from './goal-names.js';\nimport { useCallback, useEffect, useMemo, useRef, useState, type RefObject } from 'react';\nimport { attachMicroSignalDetectors, type MicroSignalType, type SentientClient } from '@sentientui/core';\nimport { useAdaptiveApiKey, useSentient } from './provider.js';\nimport { useAssignment } from './use-assignment.js';\nimport { registerComponent } from './devtools-registry.js';\nimport {\n attachGoalListeners,\n goalLabelOf,\n goalValueOf,\n maybeDeclareFunnel,\n normalizeGoal,\n trackExposure,\n type GoalConfig,\n} from './adaptive-shared.js';\n\n/** Maps a detected micro-signal to a named session goal (`client.goal`). */\nexport type MicroSignalGoalConfig = GoalName | { name: GoalName; weight?: number; stepIndex?: number };\nexport type MicroSignalGoals = Partial<Record<MicroSignalType, MicroSignalGoalConfig>>;\n\nexport type VariantComponentOptions = {\n goal: string | GoalConfig | undefined;\n funnel?: string;\n microSignalGoals?: MicroSignalGoals;\n agentData?: unknown;\n agentDataByVariant?: Record<string, unknown>;\n /** Emit `cursor_signal` after 800 ms of continuous hover (<Adaptive> only). */\n cursorSignal?: boolean;\n /** <Adaptive> only: called when the server says this id was migrated onto\n * the shared track (see useAssignment). Without it the hook never sends the\n * unified cap — useAdaptive has no slot path to move to. */\n onUnified?: () => void;\n};\n\nexport type VariantComponentState = {\n client: SentientClient | null;\n variantIds: string[];\n /** Null until useAssignment has any variant (e.g. SSR with ssrFallback 'none'). */\n variantId: string | null;\n content: string | null;\n settled: boolean;\n isOverride: boolean;\n goalLabel: string;\n /** Callback ref — attach to the element exposure/goals/micro-signals bind to. */\n ref: (el: HTMLElement | null) => void;\n nodeRef: RefObject<HTMLElement | null>;\n};\n\n/**\n * The measurement engine shared by `<Adaptive variants>` and `useAdaptive`:\n * assignment, devtools registration, exposure, funnel declaration, goal\n * listeners and micro-signal detectors.\n *\n * It exists because the two used to carry copies of these effects and drifted:\n * the hook's micro-signal effect lost the `settled` gate <Adaptive> had, so a\n * rage-click during the interim-baseline window recorded a micro_signal on an\n * arm that was never served, and the hook silently had no `microSignalGoals`.\n * Every gate below now applies to both callers at once.\n */\nexport function useVariantComponent(\n id: string,\n variants: Record<string, unknown>,\n opts: VariantComponentOptions,\n): VariantComponentState {\n const client = useSentient();\n const apiKey = useAdaptiveApiKey();\n // Freeze the variant-id array on the KEY SET, not the object identity: an\n // inline `variants={{...}}` literal is a fresh object every render, so keying\n // on the object churned a new array each commit — re-running the register\n // effect and unregistering+re-registering the component on every render.\n // Same convention as AdaptiveGroup / useAdaptiveTokens.\n const variantKey = Object.keys(variants).join('\\u0000');\n // eslint-disable-next-line react-hooks/exhaustive-deps\n const variantIds = useMemo(() => Object.keys(variants), [variantKey]);\n const { variantId, content, isOverride = false, settled } = useAssignment(\n id,\n variantIds,\n opts.agentData,\n opts.agentDataByVariant,\n opts.onUnified ? { onUnified: opts.onUnified } : undefined,\n );\n\n // Callback ref + state, not a plain useRef: useAdaptive's bind target is the\n // caller's element and may attach after (or be swapped out from under) the\n // first commit — a useRef read inside effects never re-runs them, so\n // listeners stayed on a detached node or never attached.\n const [node, setNode] = useState<HTMLElement | null>(null);\n const nodeRef = useRef<HTMLElement | null>(null);\n const ref = useCallback((el: HTMLElement | null) => {\n nodeRef.current = el;\n setNode(el);\n }, []);\n\n const rawGoal = opts.goal;\n const goalKey = typeof rawGoal === 'string' ? rawGoal : JSON.stringify(rawGoal);\n // Missing-goal misuse fails SOFT (callers may throw in dev first): an\n // unconditional goalLabelOf(undefined) crashed the whole prod render on\n // `undefined.type`. Serve and expose the variant, wire no goal.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n const goal = useMemo(() => (rawGoal ? normalizeGoal(rawGoal) : null), [goalKey]);\n const goalLabel = rawGoal ? goalLabelOf(rawGoal) : '';\n\n // Register with the devtools registry so the dev widget can list this\n // component + its variants. Inert in production; cleanup unregisters.\n useEffect(() => registerComponent({ id, variantIds, goal: goalLabel }), [id, variantIds, goalLabel]);\n\n // Exposure: variant_assigned exactly once per (component, variant) mount.\n const exposedRef = useRef<string | null>(null);\n useEffect(() => {\n // A forced variant is a dev/test view, not a real exposure — recording it\n // would train the bandit on the override. Same gate on every tracking\n // effect below (\"no events recorded, weights unchanged\").\n if (isOverride) return;\n // Only expose a SETTLED assignment. On the CSR path the served variant\n // resolves in two steps (interim baseline variantIds[0] → bandit choice);\n // tracking the interim would accrue a phantom baseline exposure that can\n // never convert.\n if (!settled) return;\n if (!client || !variantId || !apiKey || !node) return;\n if (exposedRef.current === variantId) return;\n exposedRef.current = variantId;\n trackExposure(client, apiKey, id, variantId);\n }, [client, variantId, apiKey, id, node, isOverride, settled]);\n\n // Goal latches reset when the variant or goal changes.\n const goalFiredRef = useRef(false);\n const microGoalFiredRef = useRef<Set<MicroSignalType>>(new Set());\n useEffect(() => {\n goalFiredRef.current = false;\n microGoalFiredRef.current = new Set();\n }, [variantId, goal]);\n\n // Declare funnel membership (and, for weighted composites, the funnel's\n // steps) once per page load. Same settle/override gates as the exposure —\n // a forced dev view must not declare anything. A weighted composite with no\n // `funnel` declares its own (compositeFunnelId).\n const funnel = opts.funnel;\n useEffect(() => {\n if (isOverride || !settled) return;\n if (!client || !goal) return;\n maybeDeclareFunnel(client, apiKey, id, funnel, goal);\n }, [client, apiKey, id, funnel, goal, isOverride, settled]);\n\n // cursor_signal after 800 ms of continuous hover.\n const cursorSignal = opts.cursorSignal === true;\n useEffect(() => {\n if (!cursorSignal || isOverride) return;\n // Same settle gate as the exposure: before assign() resolves, variantId is\n // the interim baseline placeholder — a hover then would attribute a\n // cursor_signal to an arm that was never really served.\n if (!settled) return;\n if (!client || !variantId || !node) return;\n\n let timerId: ReturnType<typeof setTimeout> | null = null;\n let hoverStart = 0;\n const onEnter = (): void => {\n hoverStart = Date.now();\n timerId = setTimeout(() => {\n client.track({\n projectId: apiKey,\n componentId: id,\n variantId,\n eventType: 'cursor_signal',\n payload: { hoverDuration: Date.now() - hoverStart },\n });\n timerId = null;\n }, 800);\n };\n const onLeave = (): void => {\n if (timerId !== null) {\n clearTimeout(timerId);\n timerId = null;\n }\n };\n node.addEventListener('mouseenter', onEnter);\n node.addEventListener('mouseleave', onLeave);\n return () => {\n node.removeEventListener('mouseenter', onEnter);\n node.removeEventListener('mouseleave', onLeave);\n if (timerId !== null) clearTimeout(timerId);\n };\n }, [cursorSignal, client, variantId, apiKey, id, node, isOverride, settled]);\n\n // Micro-signal detectors — rage click, text copy, scroll hesitation, tab loss.\n // The mapping is read through a ref and the effect is keyed on its CONTENT:\n // attachMicroSignalDetectors latches each signal once per attach, so keying\n // on identity re-attached on every render for an inline `microSignalGoals`\n // literal (the natural way to call useAdaptive), resetting those latches and\n // re-emitting the same micro_signal repeatedly.\n const microSignalGoalsRef = useRef(opts.microSignalGoals);\n microSignalGoalsRef.current = opts.microSignalGoals;\n const microKey = opts.microSignalGoals ? JSON.stringify(opts.microSignalGoals) : '';\n useEffect(() => {\n if (isOverride) return;\n // Gate on settle too (like the exposure): during the pre-assign() window\n // variantId is the interim baseline placeholder, so a rage-click / tab-loss\n // would record a micro_signal — and fire a mapped named goal — attributed\n // to an arm that was never really served. useAdaptive lacked this gate\n // before the two paths shared this hook.\n if (!settled) return;\n if (!client || !variantId || !node) return;\n const assignedAt = Date.now();\n return attachMicroSignalDetectors(\n (signalType, extra = {}) => {\n client.track({\n projectId: apiKey,\n componentId: id,\n variantId,\n eventType: 'micro_signal',\n payload: { signalType, ...extra },\n });\n\n const mapping = microSignalGoalsRef.current?.[signalType];\n if (!mapping || microGoalFiredRef.current.has(signalType)) return;\n microGoalFiredRef.current.add(signalType);\n const name = typeof mapping === 'string' ? mapping : mapping.name;\n const weight = typeof mapping === 'string' ? 1.0 : (mapping.weight ?? 1.0);\n const stepIndex = typeof mapping === 'string' ? 0 : (mapping.stepIndex ?? 0);\n // Explicit options form: `extra` is arbitrary micro-signal data, so it\n // must land in metadata and never be mistaken for GoalOptions keys.\n client.goal(name, { metadata: { signalType, ...extra }, weight, stepIndex });\n },\n node,\n assignedAt,\n );\n }, [client, variantId, apiKey, id, node, microKey, isOverride, settled]);\n\n // Goal listeners (shared machinery — see adaptive-shared.ts).\n useEffect(() => {\n if (isOverride) return;\n // Same settle gate as the exposure: before assign() resolves, variantId is\n // the interim baseline placeholder, which never recorded an impression — a\n // conversion in that window would attribute to an arm with zero exposures\n // and corrupt its stats.\n if (!settled) return;\n if (!client || !variantId || !node || !goal) return;\n\n // A static `value` on the goal config rides on BOTH writes (the component-\n // attributed event and the session funnel record) so read-time dedup never\n // picks a valueless row. Steps carry weights, never values (spec §9.4).\n const declaredValue = goalValueOf(goal);\n return attachGoalListeners(node, goal, {\n fireGoal: () => {\n if (goalFiredRef.current) return;\n goalFiredRef.current = true;\n client.track({\n projectId: apiKey,\n componentId: id,\n variantId,\n eventType: 'goal_achieved',\n goalType: goalLabel,\n payload: { reward: 1.0, ...(declaredValue !== undefined ? { goalValue: declaredValue } : {}) },\n });\n client.goal(goalLabel, {\n metadata: { componentId: id, variantId },\n weight: 1.0,\n stepIndex: 0,\n ...(declaredValue !== undefined ? { value: declaredValue } : {}),\n });\n },\n fireStep: (name, weight, stepIndex) => {\n client.track({\n projectId: apiKey,\n componentId: id,\n variantId,\n eventType: 'goal_achieved',\n goalType: name,\n payload: { reward: weight },\n });\n client.goal(name, { metadata: {}, weight, stepIndex });\n },\n }, goalLabel);\n }, [client, variantId, apiKey, id, node, goal, goalLabel, isOverride, settled]);\n\n return { client, variantIds, variantId, content, settled, isOverride, goalLabel, ref, nodeRef };\n}\n","import { useEffect, useRef, useState, useSyncExternalStore } from 'react';\nimport { type AssignResult } from '@sentientui/core';\n// The degraded-fallback pick lives in @sentientui/policy so its shrinkage\n// formula is single-sourced with the pinned statistics (audit REACT-14 — a\n// local copy here was a third shrinkage variant nobody replayed).\nimport { pickFromWeights } from '@sentientui/policy';\nimport { useSentient, useInitialAssignments, useSessionSegment, useSsrFallback, useOnAssignment, useDebug } from './provider.js';\nimport { subscribe, getWeights } from './weights-store.js';\nimport { subscribeOverridesChanged } from './override-events.js';\nimport { getDevOverride } from './dev-override.js';\n\nexport type AssignmentState = {\n variantId: string | null;\n /** Populated when the assigned variant is a dashboard-managed text variant. */\n content: string | null;\n isLoading: boolean;\n /**\n * True once `variantId` reflects a REAL decision — an SSR preload, the local\n * assignment cache, a server `assign()`, live bandit weights, or a dev\n * override — rather than the interim `variantIds[0]` placeholder shown while a\n * decision is still in flight. Exposure tracking MUST gate on this: emitting\n * `variant_assigned` for the placeholder accrues a phantom baseline\n * impression that can never convert and dilutes that arm's CVR.\n */\n settled: boolean;\n /**\n * True while a dev override (?sentient_variant= / window.__sentient_overrides)\n * is forcing this variant. Consumers must suppress ALL tracking while set —\n * the override contract is \"no events recorded, weights unchanged\".\n */\n isOverride?: boolean;\n};\n\n/**\n * Returns a sticky variant assignment for a component.\n *\n * @deprecated Since 0.13.0 — use {@link useAdaptive} instead. `useAssignment`\n * only SELECTS a variant; it wires no exposure tracking, no goal listeners,\n * and no micro-signals, so components using it directly accumulate no\n * learning signal. It keeps working (it is `useAdaptive`'s internal\n * selection engine) but will move to internal-only in 1.0.0.\n *\n * First render reads the local SDK cache; if empty, falls back to a\n * deterministic default and asynchronously calls `/v1/assign`. The server\n * picks the actual variant via Thompson Sampling and the result replaces the fallback\n * on the next render. Subsequent paints read synchronously from cache —\n * no flicker, no loading state after first paint.\n */\nexport function useAssignment(\n componentId: string,\n variantIds: string[],\n agentData?: unknown,\n agentDataByVariant?: Record<string, unknown>,\n /** `onUnified`: the caller can render this component on the shared track.\n * The assign then carries the unified cap, and a `unified` answer calls this\n * INSTEAD of settling — it is not an assignment, and settling on its\n * placeholder would expose that variant on a frozen ledger. */\n opts?: { onUnified?: () => void },\n): AssignmentState {\n const initialAssignments = useInitialAssignments();\n const ssrFallback = useSsrFallback();\n const client = useSentient();\n const segment = useSessionSegment();\n const onAssignment = useOnAssignment();\n const debug = useDebug();\n const assignmentReportedRef = useRef<string | null>(null);\n\n // Dev override (URL ?sentient_variant=componentId:variantId or\n // window.__sentient_overrides[componentId]) read through useSyncExternalStore:\n // - server snapshot is null (no window), so SSR renders the un-forced variant;\n // - the client snapshot reads the override, and React reconciles the two\n // across hydration WITHOUT a mismatch (this is exactly what the hook is for);\n // - unlike a post-mount flip it is already correct on a remount / CSR-nav, so\n // a forced variant never leaks an interim assign() or exposure before the\n // override applies.\n // It also re-renders when the devtools/scenario helpers bump the override bus.\n const devOverride = useSyncExternalStore(\n subscribeOverridesChanged,\n () => getDevOverride(componentId),\n () => null,\n );\n const overrideVariant = devOverride && variantIds.includes(devOverride) ? devOverride : null;\n const overrideLoggedRef = useRef<string | null>(null);\n // Diagnostic log for an active dev override — effect, never render body, and\n // gated behind the provider's debug flag so it stays silent in production.\n useEffect(() => {\n if (!debug) return;\n if (!overrideVariant) return;\n if (overrideLoggedRef.current === overrideVariant) return;\n overrideLoggedRef.current = overrideVariant;\n console.info(`[sentient] override active: ${componentId} -> ${overrideVariant}`);\n }, [debug, overrideVariant, componentId]);\n\n // Lazy initializer: this selection logic (URLSearchParams parse via the\n // override read above, cache + weights Map lookups) runs ONCE on mount, not\n // on every render. React only uses a useState initializer's value on first\n // render, so computing it eagerly each render was pure waste on every\n // <Adaptive>/useAdaptive re-render. Mirrors AdaptiveText's lazy seeds.\n const [state, setState] = useState<AssignmentState>((): AssignmentState => {\n if (overrideVariant) {\n return { variantId: overrideVariant, content: null, isLoading: false, settled: true };\n }\n // SSR / pre-hydration: no client yet. Use initialAssignments if provided so\n // the server and client first render agree on the same variant (no mismatch).\n if (!client) {\n const preloaded = initialAssignments[componentId];\n if (preloaded && variantIds.includes(preloaded)) {\n // Server-decided — a real assignment, safe to expose.\n return { variantId: preloaded, content: null, isLoading: false, settled: true };\n }\n if (ssrFallback === 'first' && variantIds.length > 0) {\n // SEO placeholder shown until the client resolves a real decision — NOT\n // settled, so no exposure fires for this interim baseline.\n return { variantId: variantIds[0], content: null, isLoading: false, settled: false };\n }\n return { variantId: null, content: null, isLoading: true, settled: false };\n }\n const cached = client.getAssignment(componentId, segment);\n // Allow cached managed variants (content present) even if not in variantIds.\n if (cached && (variantIds.includes(cached.variantId) || cached.content)) {\n return { variantId: cached.variantId, content: cached.content ?? null, isLoading: false, settled: true };\n }\n const weights = getWeights(componentId);\n if (weights) {\n const chosen = pickFromWeights(weights.variants, variantIds);\n if (chosen) return { variantId: chosen, content: null, isLoading: false, settled: true };\n }\n // Interim placeholder while the async assign() below is in flight — not a\n // real decision yet, so it stays unsettled and emits no exposure.\n return { variantId: variantIds[0] ?? null, content: null, isLoading: false, settled: false };\n });\n\n // Helper: call onAssignment at most once per resolved variant.\n const reportAssignment = (variantId: string): void => {\n if (!onAssignment) return;\n if (assignmentReportedRef.current === variantId) return;\n assignmentReportedRef.current = variantId;\n onAssignment(componentId, variantId);\n };\n\n // As soon as the client is ready, unblock the UI immediately with variantIds[0]\n // (or a cached value) so the component never stays invisible while assign is\n // in-flight. The async assign call below then swaps to the bandit-chosen variant.\n useEffect(() => {\n if (overrideVariant) return;\n if (!client) return;\n const cached = client.getAssignment(componentId, segment);\n if (cached && (variantIds.includes(cached.variantId) || cached.content)) {\n setState({ variantId: cached.variantId, content: cached.content ?? null, isLoading: false, settled: true });\n reportAssignment(cached.variantId);\n return;\n }\n // Weights-resolved initializer pick: the useState initializer above can\n // settle on a variant chosen from cached bandit weights but, being\n // render-phase, it cannot call onAssignment — so weights-resolved variants\n // never reported while the cache/assign paths always did. Report it here;\n // the pick is recomputed (deterministic for the same store contents) so a\n // settled state from any OTHER source is left alone.\n const weights = getWeights(componentId);\n if (weights && state.settled && state.variantId && state.variantId === pickFromWeights(weights.variants, variantIds)) {\n reportAssignment(state.variantId);\n return;\n }\n setState((prev) => prev.variantId ? prev : { variantId: variantIds[0] ?? null, content: null, isLoading: false, settled: false });\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [overrideVariant, client, componentId, segment]);\n\n // Ask the server for a real assignment when we have a client but no cached one.\n useEffect(() => {\n if (overrideVariant) return;\n if (!client) return;\n const cached = client.getAssignment(componentId, segment);\n if (cached && variantIds.includes(cached.variantId)) return;\n\n // A late answer is still swapped in. Declining it (audit S9's deadline)\n // would not avoid a trial: /v1/assign records the exposure server-side at\n // draw time, so a declined arm was booked as shown while the page showed\n // the placeholder. Bounding lateness happens before the request instead\n // (core's SESSION_WAIT_MS: an assign that would start late isn't sent).\n let cancelled = false;\n const onUnified = opts?.onUnified;\n const request = onUnified\n ? client.assign(componentId, variantIds, agentData, agentDataByVariant, { unified: true })\n : client.assign(componentId, variantIds, agentData, agentDataByVariant);\n void request.then((result: AssignResult | null) => {\n if (cancelled) return;\n if (!result) return;\n if (result.unified === true) {\n onUnified?.();\n return;\n }\n // Allow the result if it's a known code variant OR a managed text variant (has content).\n if (!variantIds.includes(result.variantId) && !result.content) return;\n setState({ variantId: result.variantId, content: result.content ?? null, isLoading: false, settled: true });\n reportAssignment(result.variantId);\n });\n return () => { cancelled = true; };\n // variantIds intentionally excluded — changing variants mid-mount is unsupported\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [overrideVariant, client, componentId, segment]);\n\n // Live weight updates from the dashboard SSE stream (when wired).\n useEffect(() => {\n if (overrideVariant) return;\n if (!client) return;\n return subscribe(componentId, (weights) => {\n const cached = client.getAssignment(componentId, segment);\n if (cached && (variantIds.includes(cached.variantId) || cached.content)) {\n setState({ variantId: cached.variantId, content: cached.content ?? null, isLoading: false, settled: true });\n reportAssignment(cached.variantId);\n return;\n }\n const chosen = pickFromWeights(weights.variants, variantIds);\n if (chosen) {\n setState({ variantId: chosen, content: null, isLoading: false, settled: true });\n // A live-subscription pick is as real an assignment as assign()'s\n // result — without this report, onAssignment fired late or never for\n // weights-resolved variants (reportAssignment dedupes per variant).\n reportAssignment(chosen);\n }\n });\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [overrideVariant, client, componentId, segment]);\n\n if (overrideVariant) {\n return { variantId: overrideVariant, content: null, isLoading: false, settled: true, isOverride: true };\n }\n\n return state;\n}\n","declare global {\n interface Window {\n __sentient_overrides?: Record<string, string>;\n }\n}\n\n/**\n * Reads a forced variant for a component from the dev-override channels:\n * `window.__sentient_overrides[id]` (devtools panel, `applyScenario`, the\n * Playwright/Cypress helpers) or the `?sentient_variant=id:variant` URL param\n * (repeatable for multiple components). Returns `null` in non-browser envs.\n *\n * Callers MUST read this POST-MOUNT (never in the render body): it touches\n * `window.location`, which is absent on the server, so reading it during render\n * diverges the SSR output from the client's first render and throws a hydration\n * mismatch on any SSR page carrying `?sentient_variant=`.\n */\nexport function getDevOverride(componentId: string): string | null {\n if (typeof window === 'undefined') return null;\n const global = window.__sentient_overrides?.[componentId];\n if (global) return global;\n // This runs as a useSyncExternalStore getSnapshot (once or twice per render\n // pass, per adaptive component), so skip the URLSearchParams parse entirely on\n // the overwhelmingly common no-query-string page.\n if (!window.location.search) return null;\n try {\n const params = new URLSearchParams(window.location.search);\n for (const raw of params.getAll('sentient_variant')) {\n // sentient_variant=componentId:variantId (repeatable for multiple components)\n const sep = raw.indexOf(':');\n if (sep === -1) continue;\n if (raw.slice(0, sep) === componentId) return raw.slice(sep + 1);\n }\n } catch {\n /* non-browser env */\n }\n return null;\n}\n","'use client';\nimport type { GoalName } from './goal-names.js';\nimport { useEffect, useMemo, useRef, useState, useSyncExternalStore, type JSX, type ReactNode, type Ref } from 'react';\nimport { attachMicroSignalDetectors, containsFormBlock, reveal, type RenderCaps, type SkeletonReport } from '@sentientui/core';\nimport type { MicroSignalGoals } from './use-variant-component.js';\nimport { captureRegionSkeleton } from '@sentientui/core/region';\nimport { useAdaptiveApiKey, useSentient } from './provider.js';\nimport { useSlotConfig } from './use-slot-config.js';\nimport { renderBlocks, renderCompose } from './blocks-render.js';\nimport { annotateSkeletonForReact, applyEdits, countTextLeaves, reactFingerprint, substituteSlotText } from './slot-text.js';\nimport {\n attachGoalListeners,\n goalLabelOf,\n goalValueOf,\n isDevBuild,\n maybeDeclareFunnel,\n normalizeGoal,\n trackExposure,\n type AdaptiveElement,\n type GoalConfig,\n} from './adaptive-shared.js';\nimport { registerComponent, registerSlot } from './devtools-registry.js';\nimport { submitRegionRefresh, takeRegionRefresh } from './cell-preview.js';\nimport { subscribeOverridesChanged } from './override-events.js';\nimport { getDevOverride } from './dev-override.js';\n\n// Warn once per slot id per page lifetime, not per render.\nconst warnedFormSlots = new Set<string>();\nconst warnedOpaqueSlots = new Set<string>();\nconst warnedBlockedSlots = new Set<string>();\n\nexport type AdaptiveSlotProps = {\n id: string;\n /** Baseline JSX — holdout, unknown personas, empty cells, every error path. */\n children: ReactNode;\n /** Hand-written versions (a hybrid <Adaptive>): each key is an arm the\n * server may draw alongside your original and the generated versions, in\n * one experiment (spec 2026-09-23 §7). */\n variants?: Record<string, ReactNode>;\n /** Receives form values when a generated form arm submits. Without it, form\n * arms fall back to children entirely. Values never reach Sentient. */\n onFormSubmit?: (values: Record<string, string>) => void;\n /** Optional goal attached to the container (click/scroll/composite), same\n * shape as AdaptiveGroup's. Form arms fire their own submitGoal regardless. */\n goal?: GoalName | GoalConfig;\n className?: string;\n /** Wrapper element. @default 'div' */\n as?: AdaptiveElement;\n /** On first registration the SDK sends the region's rendered text (capped at\n * 400 chars) so dashboard-generated versions are grounded in what they\n * replace. Set false for a slot wrapping personalized or account content —\n * the text of THIS region is all that is ever read, never the page. */\n reportBaselineText?: boolean;\n /** Funnel this component serves (stable funnel id). Same meaning as on a\n * variants-only `<Adaptive>`: declares membership (and, for a\n * weighted_composite goal, the funnel's steps) once per page load. */\n funnel?: string;\n /** Also record a named goal when a passive micro-signal fires here (e.g.\n * rage_click → 'confused_by_hero'). Recorded only for a served arm, and\n * credited to the component like `goal`. */\n microSignalGoals?: MicroSignalGoals;\n /** Render nothing during SSR and before client hydration. */\n clientOnly?: boolean;\n /** Per-arm structured data for AI agents, keyed by the authored key for a\n * hand-written arm and by arm id for a generated one. Only the served arm's\n * entry is sent. Captured at MOUNT, like on a variants-only `<Adaptive>`. */\n agentDataByVariant?: Record<string, unknown>;\n /** @deprecated Use agentDataByVariant. Sent for any served arm that has no\n * entry of its own. Captured at MOUNT. */\n agentData?: unknown;\n /** @internal Set by `<Adaptive variants>` (no children) once the server says\n * its id was migrated onto the shared track. `children` is then the FIRST\n * variant, not an original: the page tells decide it has no children, so\n * the first authored key is the control and the 'baseline' arm — which\n * would render that same first variant under another id — is never drawn. */\n variantsOnly?: boolean;\n};\n\n/**\n * @deprecated Use `<Adaptive id=\"…\">{children}</Adaptive>` — `<Adaptive>`\n * without `variants` is this component. Kept exported because the package is\n * published; it will not be removed in a minor release.\n *\n * A region whose content the server may replace with a named arm — a copy\n * string or a validated Composition Block tree (registry slot config). The\n * children are the founder's baseline: they render untouched for holdout\n * traffic, unserved slots, and every error path, so the worst case is always\n * \"nothing changed\" (spec 2026-09-08 empty-cell-generation §3).\n */\nconst AUTHORED_PREFIX = 'authored.';\n\nexport function AdaptiveSlot({\n id,\n children,\n variants,\n onFormSubmit,\n goal,\n className,\n as: Tag = 'div',\n reportBaselineText = true,\n funnel,\n microSignalGoals,\n clientOnly,\n agentDataByVariant,\n agentData,\n variantsOnly = false,\n}: AdaptiveSlotProps): JSX.Element | null {\n const client = useSentient();\n const apiKey = useAdaptiveApiKey();\n const nodeRef = useRef<HTMLElement | null>(null);\n // clientOnly renders nothing in SSR HTML and until a client exists. Every\n // effect that binds to the wrapper element lists `hidden` in its deps: they\n // ran once against a null node on the first commit and, without it, never\n // re-ran when the wrapper appeared — a clientOnly slot with no goal wiring.\n const [mounted, setMounted] = useState(false);\n useEffect(() => { setMounted(true); }, []);\n const hidden = clientOnly === true && (!mounted || !client);\n // What this region can render (CONTRACTS §2), from the element tree so it\n // is known before any DOM exists. No reachable text → a fingerprint no real\n // skeleton has: no Rewrite arm can land here, so none may be drawn.\n const childFp = useMemo(() => reactFingerprint(children), [children]);\n // A hybrid declares its authored keys on every decide: the server draws\n // `authored.<key>` only for keys this page has, so a key removed in a deploy\n // simply leaves the arm space (and a sticky visitor re-decides).\n const authoredKey = variants ? Object.keys(variants).join('|') : '';\n const caps = useMemo<RenderCaps>(\n () => ({\n fp: childFp ?? '0000000000000000',\n forms: !!onFormSubmit,\n // This SDK renders Redesign trees (`like` + compose), so the server may\n // draw them for this page (CONTRACTS §2).\n compose: true,\n content: countTextLeaves(children) === 1,\n // React never applies `ops`. Without this, an <Adaptive id> matching a\n // script-tag component was drawn its ops version, rendered the original,\n // and booked a trial for a version nobody saw.\n ops: false,\n ...(authoredKey !== '' ? { authored: authoredKey.split('|'), children: !variantsOnly } : {}),\n }),\n [childFp, children, onFormSubmit, authoredKey, variantsOnly],\n );\n // The region's skeleton, read from the DOM while it shows the developer's\n // children. Tied to the ELEMENT TREE by a parity check: edits are addressed\n // by leaf order, so if the tree and the DOM disagree the region is\n // unaddressable rather than edited in the wrong place.\n const captureSkeleton = (): SkeletonReport | null => {\n const el = nodeRef.current;\n if (!el || !reportBaselineText) return null;\n const cap = captureRegionSkeleton(el);\n if (!cap.skeleton) return { status: cap.reason };\n // A region wrapping a component (`<Adaptive><CtaButtons /></Adaptive>`, the\n // usual React shape) fails the parity check: the element tree can't see\n // text a component renders. It used to be reported unaddressable with no\n // skeleton at all, which blocked Redesign too — the Bodyshop CTA. The DOM\n // capture still describes the region, so send it marked non-editable:\n // Redesign replaces the whole region and needs no addressing, and this\n // page's fingerprint (childFp) never matches it, so no Rewrite arm can be\n // drawn here either way.\n return (\n annotateSkeletonForReact(cap.skeleton, children) ?? {\n ...cap.skeleton,\n editable: false,\n nodes: cap.skeleton.nodes.map((n) => ({ ...n, restylable: false })),\n }\n );\n };\n // Any <Adaptive> with `variants` answers the variant dev-override channels:\n // ?sentient_variant=id:key, __sentient_overrides (devtools, the\n // Playwright/Cypress helpers).\n // - Moved variants-only components (ruling C24): without this, moving a\n // component broke every test that forced one of its variants.\n // - Hybrids with children (ruling C27): the sentient-ui.com hero ignored\n // ?sentient_variant= and kept deciding and crediting. Meanwhile\n // useAdaptiveGoal, which does read the override, dropped its goals. The\n // preview and the recording disagreed.\n // How a forced key maps to an arm:\n // - a `variants` key → `authored.<key>`;\n // - `baseline` → the original (hybrids only; variants-only has none);\n // - any other key → the control. An override is still active, so this\n // stays a silent preview, as useAdaptiveGoal treats it.\n // The server snapshot is null, so SSR never reads window (see dev-override.ts).\n const forcedKey = useSyncExternalStore(\n subscribeOverridesChanged,\n () => (variants ? getDevOverride(id) : null),\n () => null,\n );\n const forcedArm = forcedKey === null || !variants\n ? null\n : Object.prototype.hasOwnProperty.call(variants, forcedKey)\n ? `${AUTHORED_PREFIX}${forcedKey}`\n : variantsOnly\n ? `${AUTHORED_PREFIX}${Object.keys(variants)[0]}`\n : 'baseline';\n const { config, arm, palette, vocabulary, source } = useSlotConfig(id, {\n forcedArm,\n // Only ever read when the slot is unserved — at that moment the wrapper\n // contains exactly the baseline children this slot exists to replace.\n baselineText: reportBaselineText ? () => nodeRef.current?.textContent ?? null : undefined,\n render: () => caps,\n skeleton: captureSkeleton,\n defer: hidden,\n });\n\n const tree = arm !== '' ? config?.blocks?.[arm] : undefined;\n // A Redesign arm: a composed section borrowing the site's own class lists.\n const composed = arm !== '' ? config?.compose?.[arm] : undefined;\n // A form tree without a handler is refused WHOLE (children render instead):\n // dropping just the form node would show a section minus its call-to-action —\n // looks live, converts nothing. Same rule the snippet applies.\n const formBlocked =\n ((tree !== undefined && containsFormBlock(tree)) || (composed !== undefined && containsFormBlock(composed.tree))) && !onFormSubmit;\n\n useEffect(() => {\n if (!formBlocked || !isDevBuild() || warnedFormSlots.has(id)) return;\n warnedFormSlots.add(id);\n console.warn(\n `[sentient] AdaptiveSlot \"${id}\" was served a form arm but has no onFormSubmit handler — ` +\n `rendering its baseline children instead. Pass onFormSubmit to render generated forms.`,\n );\n }, [formBlocked, id]);\n\n const fireFormGoal = (goalName: string): void => {\n if (!client || source === 'override') return;\n // componentGoal credits the optimizer (arm resolved from slot state);\n // goal() writes the session funnel record — the slot-goal shape\n // (use-adaptive-tokens). Field values are NOT on either write. A seeded\n // (not-yet-decided) arm keeps the session goal — the visitor did convert —\n // but not the arm credit: close-out would hand it to whichever arm this\n // session's decide draws afterwards.\n if (source !== 'seeded') client.componentGoal(id, goalName);\n client.goal(goalName, { metadata: { componentId: id, arm }, weight: 1.0, stepIndex: 0 });\n };\n\n // Precedence: served arm's block tree, else served content string, else the\n // developer's children. content/blocks are mutually exclusive on purpose —\n // the snippet's \"content overwrites blocks' textContent\" ordering hazard\n // (apply.ts) must not be reproduced here.\n let body: ReactNode = children;\n // True when the served arm never reaches the page: the form gate refused\n // its tree, renderBlocks returned root-level null (unknown ROOT node from a\n // newer server), or its copy had no text in children to land on. The\n // children shown then are a fallback,\n // not an assignment — the exposure gate below reads this so the arm is not\n // charged an impression it could never convert on.\n let armBlocked = false;\n const authoredArm = arm.startsWith(AUTHORED_PREFIX) ? arm.slice(AUTHORED_PREFIX.length) : null;\n if (config?.blocked === 'variant_history') {\n // Held back server-side: this id's trials live on the variant ledger until\n // the operator migrates it. Nothing was decided; nothing is exposed.\n armBlocked = true;\n } else if (authoredArm !== null) {\n // A served authored arm renders the developer's own JSX. The server only\n // draws keys this page declared, so a miss is an SSR/preload race — render\n // the original and don't expose.\n if (variants && Object.prototype.hasOwnProperty.call(variants, authoredArm)) body = variants[authoredArm];\n else armBlocked = true;\n } else if (composed !== undefined) {\n const rendered = formBlocked ? null : renderCompose(composed, { palette, vocabulary, onFormSubmit, onFormGoal: fireFormGoal });\n if (rendered === null) armBlocked = true;\n else body = rendered;\n } else if (tree !== undefined) {\n const rendered = formBlocked ? null : renderBlocks(tree, { palette, vocabulary, onFormSubmit, onFormGoal: fireFormGoal });\n if (rendered === null) armBlocked = true;\n else body = rendered;\n } else if (config?.edits !== undefined && source !== 'none') {\n // A Rewrite arm: new words (and swaps, hides, reorders) applied to the\n // developer's own elements. Written against a skeleton fingerprint; if the\n // children no longer match it, the edits would land on the wrong element.\n const e = config.edits;\n const placed = e.fp === childFp ? applyEdits(children, e.edits, e.leafToNode) : null;\n if (placed === null) armBlocked = true;\n else body = placed;\n } else if (config?.content !== undefined && source !== 'none') {\n // The copy goes INSIDE the developer's markup (slot-text.ts) — assigning\n // the string to body replaced a styled <button> with bare text.\n const placed = substituteSlotText(children, config.content);\n if (placed === null) armBlocked = true;\n else body = placed;\n }\n const textBlocked =\n armBlocked && tree === undefined && composed === undefined && config?.edits === undefined && authoredArm === null && config?.blocked === undefined;\n\n // Dev: say why a hybrid shows its original instead of experimenting.\n useEffect(() => {\n if (config?.blocked !== 'variant_history' || !isDevBuild() || warnedBlockedSlots.has(id)) return;\n warnedBlockedSlots.add(id);\n console.warn(\n `[sentient] <Adaptive id=\"${id}\"> has results from its earlier variants experiment, so it is showing your ` +\n `original until you migrate it: Matrix → Components → \"${id}\" → Migrate. Deploying code never switches an experiment.`,\n );\n }, [config?.blocked, id]);\n\n // What an authored arm rendered, for the dashboard's arm list and to ground\n // generation in the versions the team wrote (spec §7.4). Core dedupes per\n // (slot, key); the skeleton is parity-checked against that arm's JSX.\n const authoredOnScreen = authoredArm !== null && !armBlocked ? authoredArm : null;\n useEffect(() => {\n if (!authoredOnScreen || !reportBaselineText || !client) return;\n const el = nodeRef.current;\n if (!el) return;\n const cap = captureRegionSkeleton(el);\n const sk = cap.skeleton ? annotateSkeletonForReact(cap.skeleton, variants?.[authoredOnScreen]) : null;\n const text = el.textContent?.trim();\n client.reportSlots([], undefined, undefined, {\n [id]: [{ key: authoredOnScreen, ...(text ? { text } : {}), ...(sk ? { skeleton: sk } : {}) }],\n });\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [authoredOnScreen, client, id, hidden]);\n\n // A served Rewrite arm this page couldn't apply. The decide normally\n // excludes it up front (the page sends its fingerprint), so this fires for\n // SSR preloads, which have no DOM to fingerprint. Enough distinct visitors\n // reporting it suspend the stale skeleton's arms server-side. Previews\n // ('override') and snapshot seeds ('seeded') are not this session's draw.\n const editsDrift = armBlocked && config?.edits !== undefined && (source === 'preloaded' || source === 'client');\n useEffect(() => {\n if (!editsDrift || !config?.edits) return;\n // `client` in deps: it lands after the provider's init effect, and the\n // core dedupes per (slot, fingerprint), so a re-run never double-reports.\n client?.reportDrift?.(id, config.edits.fp, childFp, config.edits.fp === childFp ? 'unaddressable' : 'fp_mismatch');\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [editsDrift, id, childFp, client]);\n\n // A published slot the server has no skeleton for (registered before\n // skeletons existed): fill it from this page, once, while the DOM shows the\n // developer's children and not an arm's rendering of them.\n const showsChildren = body === children;\n useEffect(() => {\n if (!config?.needsSkeleton || !showsChildren) return;\n const sk = captureSkeleton();\n if (sk) client?.reportSkeleton?.(id, sk);\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [config?.needsSkeleton, showsChildren, id, client, hidden]);\n\n // \"Refresh from page\" (operator, editor-token link): the trusted overwrite.\n // The preview module forced the original on screen; capture it here, where\n // the element-tree parity check can run, and post it.\n useEffect(() => {\n if (!showsChildren) return;\n const r = takeRegionRefresh(id);\n if (!r) return;\n const sk = captureSkeleton();\n submitRegionRefresh(r, sk && 'status' in sk ? { status: sk.status } : { skeleton: sk });\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [id, showsChildren, hidden]);\n\n useEffect(() => {\n if (!textBlocked || !isDevBuild() || warnedOpaqueSlots.has(id)) return;\n warnedOpaqueSlots.add(id);\n console.warn(\n `[sentient] <Adaptive id=\"${id}\"> was served a text version, but its children have several separate ` +\n `texts or none Sentient can reach — rendering the original instead. Regenerate the version (new ` +\n `versions edit each text in place), or put a single text inline.`,\n );\n }, [textBlocked, id]);\n\n // Devtools slot registry — arms come from the config's block map (the only\n // arm list the client can see for a registry slot). A slot is NOT a\n // component: registering it as one writes the wrong override channel.\n const armsKey = config?.blocks ? Object.keys(config.blocks).sort().join('|') : '';\n // An <Adaptive> with `variants` answers the VARIANT override channel (see\n // forcedKey above), so it is listed as a component whose buttons write that\n // channel: `baseline` (hybrids only) plus each written key. Registering it as\n // a slot instead showed sentient-ui.com's hero_cta_v4 with no buttons at all\n // (2026-11-02) — a hybrid's written versions are never in a config's blocks.\n const devVariantIds = variants ? [...(variantsOnly ? [] : ['baseline']), ...authoredKey.split('|')].join('|') : '';\n useEffect(() => {\n if (devVariantIds !== '') return registerComponent({ id, variantIds: devVariantIds.split('|') });\n return registerSlot({ id, arms: armsKey === '' ? undefined : armsKey.split('|') });\n }, [id, armsKey, devVariantIds]);\n\n // Exposure — once per (slot, arm). 'none' means the slot was never served\n // (children baseline): recording it would accrue a phantom impression that\n // can never convert. A forced arm ('override') is a preview, not an\n // exposure — same contract as useAdaptiveTokens. armBlocked is the same\n // phantom from the other direction: the arm was served but never rendered\n // (form gate, unknown root block, copy with nowhere to land), so an exposure here would let\n // the bandit permanently bury the arm on this install for a rendering\n // failure. No baseline exposure is reported either — decide didn't assign\n // baseline, the children are just the fail-safe. 'seeded' (last visit's\n // snapshot, not yet decided this session) renders for pre-paint parity but\n // has no slot_decisions row: exposing it trained an arm the server never\n // served this session, then exposed a second arm when the decide landed.\n const exposedArmRef = useRef<string | null>(null);\n useEffect(() => {\n if (!client || source === 'none' || source === 'seeded' || source === 'override' || arm === '' || armBlocked) return;\n if (exposedArmRef.current === arm) return;\n exposedArmRef.current = arm;\n trackExposure(client, apiKey, id, arm);\n }, [client, apiKey, id, arm, source, armBlocked]);\n\n // Optional container goal (click/scroll/composite) — slot-goal shape.\n //\n // Two writes, two different gates, because they answer different questions.\n //\n // `componentGoal` credits an ARM. It is suppressed whenever no arm earned\n // the conversion — nothing decided ('none'), decided-but-not-yet-confirmed\n // ('seeded'), or a served tree that never reached the page (armBlocked) —\n // because a goal stamped with the served arm would let close-out's\n // first-pass reconciliation (goal_achieved counts as an implied exposure,\n // CONTRACTS §2) re-mint the very phantom impression the exposure gate\n // suppressed, plus credit the arm for baseline's conversion.\n //\n // `goal` writes the SESSION funnel record, which is about the visitor, not\n // the arm. It fires whenever a real visitor converts. This effect used to\n // share the exposure gate and record NEITHER, which silently deleted the\n // conversion: measured on prod 2026-09-22 (Bodyshop Manchester), an\n // <Adaptive> switched from `variants` to generated mode registers a DRAFT\n // slot, sits at source 'none' until someone publishes a version, and its CTA\n // recorded nothing for five days while the funnel read 0%. `fireFormGoal`\n // above already makes exactly this split for a seeded arm; the container\n // goal disagreeing with it thirty lines away was the bug.\n //\n // 'override' is the one source that still records NOTHING: a forced arm is a\n // devtools/test preview, and a conversion nobody made must not reach either\n // write.\n //\n // When the arm is not creditable the session record carries NO arm either:\n // '' is the same shape an undecided slot already writes, and stamping the\n // arm the visitor never saw would re-introduce the attribution through the\n // metadata after the componentGoal write had been suppressed.\n const armCreditable = source !== 'none' && source !== 'seeded' && !armBlocked;\n const goalArm = armCreditable ? arm : '';\n const goalKey = goal === undefined ? null : typeof goal === 'string' ? goal : JSON.stringify(goal);\n useEffect(() => {\n if (!client || !goal || source === 'override') return;\n const node = nodeRef.current;\n if (!node) return;\n const label = goalLabelOf(goal);\n const declaredValue = goalValueOf(goal);\n let fired = false;\n return attachGoalListeners(\n node,\n normalizeGoal(goal),\n {\n fireGoal: () => {\n if (fired) return;\n fired = true;\n if (armCreditable) {\n if (declaredValue !== undefined) client.componentGoal(id, label, { value: declaredValue });\n else client.componentGoal(id, label);\n }\n client.goal(label, {\n metadata: { componentId: id, arm: goalArm },\n weight: 1.0,\n stepIndex: 0,\n ...(declaredValue !== undefined ? { value: declaredValue } : {}),\n });\n },\n fireStep: (name, weight, stepIndex) => {\n if (armCreditable) client.componentGoal(id, name, { reward: weight });\n client.goal(name, { metadata: { componentId: id, arm: goalArm }, weight, stepIndex });\n },\n },\n label,\n );\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [client, id, goalKey, arm, source, armBlocked, armCreditable, goalArm, hidden]);\n\n // Funnel membership — the declaration is about the COMPONENT, not an arm, so\n // it needs no served arm (an unpublished component still belongs to its\n // funnel); a forced preview must not declare anything, as on the variants\n // path. Needs a goal: the declaration carries the goal's steps. A weighted\n // composite with no `funnel` declares its own (compositeFunnelId).\n const goalConfig = useMemo(\n () => (goal ? normalizeGoal(goal) : null),\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [goalKey],\n );\n useEffect(() => {\n if (source === 'override' || !client || !goalConfig) return;\n maybeDeclareFunnel(client, apiKey, id, funnel, goalConfig);\n }, [client, apiKey, id, funnel, goalConfig, source]);\n\n // Passive micro-signals → optional named goal. Gated on armCreditable like\n // the container goal: before an arm is served (or when it never rendered) a\n // rage-click would record a micro_signal against an arm nobody saw. The\n // mapping is read through a ref and keyed on its CONTENT — an inline literal\n // is a new object every render, and re-attaching resets the detectors'\n // once-per-attach latches (the same bug use-variant-component fixed).\n const microRef = useRef(microSignalGoals);\n microRef.current = microSignalGoals;\n // Latched for the COMPONENT's lifetime, not per attach: an arm change\n // re-attaches the detectors, and a per-attach latch let one visitor fire the\n // same mapped goal once per arm (use-variant-component latches per variant\n // for the same reason it must not double-fire).\n const microFiredRef = useRef<Set<string>>(new Set());\n const microKey = microSignalGoals ? JSON.stringify(microSignalGoals) : '';\n useEffect(() => {\n if (!client || source === 'override' || !armCreditable || arm === '') return;\n const node = nodeRef.current;\n if (!node) return;\n return attachMicroSignalDetectors(\n (signalType, extra = {}) => {\n client.track({\n projectId: apiKey,\n componentId: id,\n variantId: arm,\n eventType: 'micro_signal',\n payload: { signalType, ...extra },\n });\n const mapping = microRef.current?.[signalType];\n if (!mapping || microFiredRef.current.has(signalType)) return;\n microFiredRef.current.add(signalType);\n const name = typeof mapping === 'string' ? mapping : mapping.name;\n const weight = typeof mapping === 'string' ? 1.0 : (mapping.weight ?? 1.0);\n const stepIndex = typeof mapping === 'string' ? 0 : (mapping.stepIndex ?? 0);\n // Session goal ONLY, as on the variants path. componentGoal on a slot\n // feeds computeSlotCredit (closeout), so a rage click would reward the\n // version that was on screen — a scoring bug, not parity.\n client.goal(name, { metadata: { componentId: id, arm, signalType, ...extra }, weight, stepIndex });\n },\n node,\n Date.now(),\n );\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [client, apiKey, id, arm, source, armCreditable, microKey, hidden]);\n\n // Agent data for the SERVED arm only (agents see what visitors see). A\n // hand-written arm is looked up by its authored key — the key the developer\n // wrote — and any other arm by its id. With agentDataByVariant given it alone decides (an\n // arm missing from it sends nothing, as /v1/assign); agentData alone is the\n // shorthand for every served arm.\n // Read through refs: captured at mount, like the variants path.\n const agentRef = useRef({ agentData, agentDataByVariant });\n agentRef.current = { agentData, agentDataByVariant };\n const agentSentRef = useRef<string | null>(null);\n useEffect(() => {\n if (!client || source === 'override' || !armCreditable || arm === '') return;\n if (agentSentRef.current === arm) return;\n const { agentData: fallback, agentDataByVariant: byArm } = agentRef.current;\n const lookup = authoredArm ?? arm;\n // As /v1/assign: when agentDataByVariant is given it ALONE decides; an arm\n // missing from it sends nothing (agentData is only the no-map shorthand).\n const data = byArm !== undefined ? (Object.prototype.hasOwnProperty.call(byArm, lookup) ? byArm[lookup] : undefined) : fallback;\n if (data === undefined) return;\n agentSentRef.current = arm;\n client.reportAgentData?.(id, arm, data);\n }, [client, id, arm, armCreditable, authoredArm, source]);\n\n // The adaptation reveal. Fires only when the ARM CHANGES after mount — an\n // SSR-rendered slot arrives with its arm already in the HTML, so the page was\n // always that way and animating it would be theatre on every page load. The\n // cases this does catch are the ones a visitor should notice: a client-side\n // decide resolving, and a persona upgrade re-deciding on a return visit.\n const revealedArm = useRef<string | null>(null);\n useEffect(() => {\n const node = nodeRef.current;\n if (!node) return;\n // First observation is the mounted state, whatever it is — record and stop.\n if (revealedArm.current === null) {\n revealedArm.current = arm;\n return;\n }\n if (revealedArm.current === arm) return;\n revealedArm.current = arm;\n // `previous` is deliberately omitted: React has already swapped the\n // children by the time this effect runs, so the pre-change text is gone and\n // the arm change is itself the evidence that something changed. The arm is\n // not passed either — `dataProps` already stamps `data-sentient-arm`, and\n // writing it twice would let the two drift.\n reveal(node);\n }, [arm, hidden]);\n\n const dataProps = useMemo(\n () => ({ 'data-sentient-slot': id, ...(arm !== '' ? { 'data-sentient-arm': arm } : {}) }),\n [id, arm],\n );\n\n if (hidden) return null;\n\n return (\n <Tag ref={nodeRef as Ref<never>} className={className} {...dataProps}>\n {body}\n </Tag>\n );\n}\n","import { useCallback, useEffect, useRef, useSyncExternalStore } from 'react';\nimport { armOfResult, type RenderCaps, type SitePalette, type SkeletonReport, type SlotConfigEntry, type SlotResult, type StyleVocabulary } from '@sentientui/core';\nimport { useInitialPalette, useInitialSlotConfig, useInitialSlots, useInitialVocabulary, useSentient } from './provider.js';\nimport { subscribeOverridesChanged } from './override-events.js';\nimport { getVocabularyOverride } from './devtools-slot-config-overrides.js';\nimport { isDevBuild } from './adaptive-shared.js';\n\n// Warn once per slot id per page lifetime, not per render.\nconst warnedUnservedSlots = new Set<string>();\n// One shared object: a fresh one per render would read as a config change.\nconst FORCED_ARM_CONFIG: SlotConfigEntry = { kind: 'arms' };\n\ndeclare global {\n interface Window {\n /** Test/devtools forcing: slot id → forced config entry (applyScenario sets this). */\n __sentient_slot_config_overrides?: Record<string, SlotConfigEntry>;\n }\n}\n\nexport type SlotConfigResolution = {\n config: SlotConfigEntry | null;\n /** Served arm for the slot ('' when unknown). */\n arm: string;\n palette: SitePalette | null;\n /** Site styles served Redesign arms borrow (SSR seed, else the client's). */\n vocabulary: StyleVocabulary | null;\n /**\n * `client` = decided for this session; `seeded` = the core holds config\n * from an earlier visit's snapshot that this session has not decided yet.\n * Seeded config renders (pre-paint parity) but is not exposed or credited —\n * there is no slot_decisions row for it until requestSlots answers.\n */\n source: 'override' | 'preloaded' | 'client' | 'seeded' | 'none';\n};\n\n/**\n * Internal. Resolves the registry slot config AdaptiveSlot renders, synchronously:\n * test/devtools override → SSR-preloaded `initialSlotConfig` → core client state\n * (registry decide, snapshot seed) → none (render baseline children).\n * Purely read-side: exposure/goal wiring belongs to AdaptiveSlot.\n */\nexport function useSlotConfig(\n slotId: string,\n opts?: {\n /** Read the region's rendered baseline text at registration time (only\n * called when the slot is unserved and about to self-register). Kept in\n * a ref so an inline arrow never re-fires the effect. */\n baselineText?: () => string | null;\n /** What this mounted slot can render (CONTRACTS §2) — sent with the\n * scoped decide so the server never draws an arm the page would refuse. */\n render?: () => RenderCaps;\n /** Capture the region's skeleton. Only called while the wrapper shows the\n * developer's children — never an arm's rendering of them. */\n skeleton?: () => SkeletonReport | null;\n /** Hold the request until false. A clientOnly slot has no wrapper element on\n * its first commit, so asking then sent no baseline text or skeleton — and\n * the ask is deduped forever per id, so they were never sent. */\n defer?: boolean;\n /** A forced arm from the VARIANT dev-override channel, already mapped to\n * its arm id (`authored.<key>`) — a migrated variants-only <Adaptive>\n * (ruling C24). Resolves as source 'override': rendered, never exposed,\n * never decided, exactly like a forced slot config. */\n forcedArm?: string | null;\n },\n): SlotConfigResolution {\n const client = useSentient();\n const baselineTextRef = useRef(opts?.baselineText);\n baselineTextRef.current = opts?.baselineText;\n const renderRef = useRef(opts?.render);\n renderRef.current = opts?.render;\n const skeletonRef = useRef(opts?.skeleton);\n skeletonRef.current = opts?.skeleton;\n const initialSlots = useInitialSlots();\n const initialSlotConfig = useInitialSlotConfig();\n const initialPalette = useInitialPalette();\n const initialVocabulary = useInitialVocabulary();\n\n // Same useSyncExternalStore discipline as useSlotResult: the server snapshot\n // returns undefined so SSR HTML and the pre-hydration client render agree\n // even when a Playwright/Cypress mock wrote the override before hydration.\n // The snapshot returns the stored object by reference (stable until the\n // override bus notifies), so it passes React's Object.is caching check.\n const overrideConfig = useSyncExternalStore(\n subscribeOverridesChanged,\n () => (typeof window !== 'undefined' ? window.__sentient_slot_config_overrides?.[slotId] : undefined),\n () => undefined,\n );\n const overrideResult = useSyncExternalStore(\n subscribeOverridesChanged,\n () => (typeof window !== 'undefined' ? window.__sentient_slot_overrides?.[slotId] : undefined),\n () => undefined,\n );\n\n const armOf = (r: SlotResult | null | undefined): string => (r == null ? '' : armOfResult(r));\n\n // Re-render when the client's slot state changes — a mounted-slot decide\n // (requestSlots) answers after first paint. Values are still read below;\n // these two hooks only make React notice the change. Both snapshots are\n // stable between notifications (stored object by reference / arm string).\n const subscribeSlots = useCallback(\n (cb: () => void) => client?.onSlotsChanged?.(cb) ?? (() => undefined),\n [client],\n );\n useSyncExternalStore(subscribeSlots, () => client?.getSlotConfig(slotId) ?? null, () => null);\n useSyncExternalStore(subscribeSlots, () => armOf(client?.getSlotResult(slotId)), () => '');\n\n const preloaded = overrideConfig === undefined ? initialSlotConfig[slotId] : undefined;\n const fromClient =\n overrideConfig === undefined && preloaded === undefined && client ? client.getSlotConfig(slotId) : null;\n\n const palette = initialPalette ?? client?.getSitePalette() ?? null;\n const vocabulary = initialVocabulary ?? client?.getStyleVocabulary?.() ?? null;\n\n // No local-mode decide here, deliberately: the local engine has no registry\n // concept — decide({ slotsFrom: 'registry' }) ran the whole engine once per\n // mounted slot and could never produce a slotConfig (local getSlotConfig\n // reads only the initialSlotConfig SSR seed). Local slots resolve\n // synchronously from that seed or fall through to children; the dev warning\n // below says so instead of burning an engine run per mount.\n\n const resolution: SlotConfigResolution = (() => {\n if (overrideConfig !== undefined) {\n return { config: overrideConfig, arm: armOf(overrideResult), palette, vocabulary: getVocabularyOverride() ?? vocabulary, source: 'override' };\n }\n if (opts?.forcedArm) {\n return { config: FORCED_ARM_CONFIG, arm: opts.forcedArm, palette, vocabulary, source: 'override' };\n }\n if (preloaded !== undefined) {\n return { config: preloaded, arm: armOf(initialSlots[slotId] ?? client?.getSlotResult(slotId)), palette, vocabulary, source: 'preloaded' };\n }\n if (fromClient !== null) {\n const decided = client?.isSlotDecided ? client.isSlotDecided(slotId) : true;\n return {\n config: fromClient,\n arm: armOf(client?.getSlotResult(slotId) ?? initialSlots[slotId]),\n palette,\n vocabulary,\n source: decided ? 'client' : 'seeded',\n };\n }\n return { config: null, arm: '', palette, vocabulary, source: 'none' };\n })();\n\n // Keyed clients ask the server for THIS mounted slot: one decide scoped to\n // the ids actually on the page (batched per commit), which also registers it\n // as a draft when nothing is published. This used to be registration only —\n // no client-side registry decide existed, so outside an SSR registry preload\n // (which AdaptiveRoot never did) a slot rendered its children forever and\n // never served a generated version. Snapshot-seeded ('client') slots still\n // ask: the snapshot is the last visit's answer, and this session needs its\n // own decision (or to learn the slot was unpublished). Preloaded and forced\n // slots already have this session's answer.\n const deferred = opts?.defer === true;\n const settled = resolution.source === 'preloaded' || resolution.source === 'override';\n useEffect(() => {\n if (!client || client.isLocal === true || settled || deferred) return;\n // Children are on screen only while unserved — that is the only moment the\n // wrapper's text is the baseline generation should be grounded in.\n const unserved = resolution.source === 'none';\n const text = unserved ? baselineTextRef.current?.() ?? null : null;\n const texts = text != null && text !== '' ? { [slotId]: text } : undefined;\n const caps = renderRef.current?.();\n const skeleton = unserved ? skeletonRef.current?.() ?? null : null;\n // Trailing arguments only when there is something to send: hand-rolled\n // clients and older cores see exactly the call they always did.\n const extras = {\n ...(caps ? { render: { [slotId]: caps } } : {}),\n ...(skeleton ? { skeletons: { [slotId]: skeleton } } : {}),\n };\n const hasExtras = Object.keys(extras).length > 0;\n if (client.requestSlots) {\n if (hasExtras) client.requestSlots([slotId], texts, extras);\n else if (texts) client.requestSlots([slotId], texts);\n else client.requestSlots([slotId]);\n } else if (unserved) {\n if (skeleton) client.reportSlots([slotId], texts ?? {}, { [slotId]: skeleton });\n else if (texts) client.reportSlots([slotId], texts);\n else client.reportSlots([slotId]);\n }\n // Unmounted before the batch was sent (redirecting route, StrictMode\n // probe): withdraw it — a slot that is not on the page is not a trial.\n return () => client.cancelSlots?.([slotId]);\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [client, settled, resolution.source, slotId, deferred]);\n\n // Dev-only: local/keyless mode has no registry, so an unserved slot renders\n // its children all session and looks identical to a healthy holdout.\n useEffect(() => {\n if (!isDevBuild() || client?.isLocal !== true || resolution.source !== 'none') return;\n if (warnedUnservedSlots.has(slotId)) return;\n warnedUnservedSlots.add(slotId);\n console.warn(\n `[sentient] <Adaptive id=\"${slotId}\"> is rendering its baseline children: in local/keyless mode ` +\n `<Adaptive> serves ONLY what you pass as \\`initialSlotConfig\\` (there is no registry to decide from). ` +\n `Pass initialSlotConfig/initialSlots to <AdaptiveProvider> to preview arms locally.`,\n );\n }, [client, resolution.source, slotId]);\n\n return resolution;\n}\n","import { cloneElement, Fragment, type CSSProperties, type JSX } from 'react';\nimport type { BlockNode, ComposeArm, FormBlock, SitePalette, StyleVocabulary } from '@sentientui/core';\n\n/** A block's href/src, or undefined unless absolute https or a site-relative\n * path — the rule the server validates (twin of the snippet's `safeBlockUrl`\n * in ops.ts). The renderer is the last line: a stale config or a bypassed\n * validator must not render `javascript:` into an <a> (audit S14). React\n * itself only warns on `javascript:` URLs; it does not block them. */\nfunction safeBlockUrl(v: unknown): string | undefined {\n // Whitespace/control chars rejected: browsers strip tab/newline, so\n // `/\\t/evil.example` would become `//evil.example`.\n return typeof v === 'string' && !/[\\s\\x00-\\x1f\\\\]/.test(v) && (/^https:\\/\\//i.test(v) || (v[0] === '/' && v[1] !== '/')) ? v : undefined;\n}\n\n// React Composition Block renderer (spec 2026-09-08 empty-cell-generation §3).\n// JSX from typed props ONLY — no dangerouslySetInnerHTML exists on this path,\n// preserving the \"no HTML ever accepted\" security property. The server has\n// total-validated every tree before publish; render still fail-safes per node\n// (an unknown type from a NEWER server renders nothing rather than throwing,\n// so a version-skewed bundle degrades to a partial arm, never a broken page —\n// the same contract packages/snippet/src/blocks.ts pins in its tests).\n\n// Token → CSS maps, ported verbatim from packages/snippet/src/blocks.ts:31-38.\n// The drift-pin test in @sentientui/core blocks.test.ts is what keeps the three\n// parties (server validator, snippet renderer, this file) agreeing.\nconst GAP: Record<string, string> = { none: '0', sm: '8px', md: '16px', lg: '24px' };\nconst FLEX_POS: Record<string, string> = { start: 'flex-start', center: 'center', end: 'flex-end', stretch: 'stretch', between: 'space-between' };\nconst FONT_SIZE: Record<string, string> = { sm: '0.875em', md: '1em', lg: '1.25em' };\nconst HEADING_SIZE: Record<string, string> = { sm: '1.25em', md: '1.5em', lg: '2em' };\nconst BTN_PAD: Record<string, string> = { sm: '6px 14px', md: '10px 20px', lg: '14px 28px' };\nconst SPACER: Record<string, string> = { sm: '8px', md: '16px', lg: '32px' };\nconst RATIO: Record<string, string> = { square: '1 / 1', landscape: '4 / 3', wide: '16 / 9' };\nconst WEIGHT: Record<string, string> = { normal: '400', medium: '500', bold: '700' };\n\nexport type RenderBlocksOptions = {\n palette: SitePalette | null;\n /** The site styles a Redesign tree borrows (native generation phase 2). */\n vocabulary?: StyleVocabulary | null;\n /** Absent handler = form trees must not reach this function (AdaptiveSlot gates). */\n onFormSubmit?: (values: Record<string, string>) => void;\n /** Fired with the form's submitGoal when a rendered form submits. */\n onFormGoal?: (goal: string) => void;\n};\n\nfunction toneStyles(tone: string | undefined, palette: SitePalette | null): CSSProperties {\n // Brand tokens when the palette carries them; the original neutral\n // fallbacks otherwise, so pre-token palettes render exactly as before.\n return {\n ...(tone === 'muted' ? (palette?.muted ? { color: palette.muted } : { opacity: 0.7 }) : {}),\n ...(tone === 'accent' ? { fontWeight: 600, ...(palette?.accent ? { color: palette.accent } : {}) } : {}),\n };\n}\n\nfunction buttonStyle(emphasis: string, palette: SitePalette | null, size?: string): CSSProperties {\n // Mirrors the snippet's button case (blocks.ts): palette tokens when\n // available, neutral inherit-first defaults otherwise. Secondary/ghost\n // resolve to the ACCENT — before brand tokens they rendered in\n // currentColor/inherit, which made every non-primary button look like\n // body text on brand-heavy sites.\n const accent = palette?.accent;\n return {\n display: 'inline-block',\n padding: BTN_PAD[size ?? 'md'] ?? BTN_PAD['md'],\n borderRadius: palette?.radius ?? '8px',\n font: 'inherit',\n ...(size ? { fontSize: FONT_SIZE[size] } : {}),\n textDecoration: emphasis === 'ghost' ? 'underline' : 'none',\n cursor: 'pointer',\n background: emphasis === 'primary' ? (palette?.primaryBg ?? '#111827') : 'transparent',\n color:\n emphasis === 'primary'\n ? (palette?.primaryText ?? '#ffffff')\n : (accent ?? 'inherit'),\n border: emphasis === 'secondary' ? `1px solid ${accent ?? 'currentColor'}` : 'none',\n };\n}\n\nfunction FormNode({ node, opts }: { node: FormBlock; opts: RenderBlocksOptions }): JSX.Element {\n const emphasis = node.emphasis ?? 'primary';\n const fieldStyle: CSSProperties = {\n padding: '8px 10px',\n font: 'inherit',\n border: `1px solid ${opts.palette?.border ?? 'currentColor'}`,\n borderRadius: opts.palette?.radius ?? '8px',\n };\n return (\n <form\n onSubmit={(e) => {\n e.preventDefault();\n const data = new FormData(e.currentTarget);\n const values: Record<string, string> = {};\n for (const f of node.fields) values[f.name] = String(data.get(f.name) ?? '');\n // Goal first: the conversion must be credited even if the site's own\n // handler throws — their bug must not cost them the learning signal.\n // Values go ONLY to the site's handler, never into any tracked payload.\n opts.onFormGoal?.(node.submitGoal);\n try {\n opts.onFormSubmit?.(values);\n } catch {\n /* site handler error is theirs to see in their own console */\n }\n }}\n style={{ display: 'flex', flexDirection: 'column', gap: '12px' }}\n >\n {node.fields.map((f) => (\n <label key={f.name} style={{ display: 'flex', flexDirection: 'column', gap: '4px', font: 'inherit' }}>\n {f.label}\n {f.kind === 'textarea' ? (\n <textarea name={f.name} required={f.required} placeholder={f.placeholder} rows={3} style={fieldStyle} />\n ) : f.kind === 'select' ? (\n <select name={f.name} required={f.required} style={fieldStyle}>\n {(f.options ?? []).map((o) => (\n <option key={o} value={o}>\n {o}\n </option>\n ))}\n </select>\n ) : (\n <input\n name={f.name}\n type={f.inputType ?? 'text'}\n required={f.required}\n placeholder={f.placeholder}\n style={fieldStyle}\n />\n )}\n </label>\n ))}\n <button type=\"submit\" style={buttonStyle(emphasis, opts.palette)}>\n {node.submitLabel}\n </button>\n </form>\n );\n}\n\n/** Render one validated block tree as JSX. Null for anything unrenderable — fail-safe. */\n/** The site's own class list for a node that borrows one, or undefined —\n * then the node renders with palette styling exactly as before (a dropped\n * vocabulary entry degrades, never blanks). */\nfunction classOf(node: BlockNode, opts: RenderBlocksOptions): string | undefined {\n const like = (node as { like?: string }).like;\n return like ? opts.vocabulary?.entries.find((e) => e.id === like)?.classes : undefined;\n}\n\n/** The measured text colour of a borrowed style whose class list doesn't set\n * one (StyleEntry.computed.inheritsColor) — applied to the element, or it\n * inherits whatever colour its new surroundings have. */\nfunction inheritedColor(like: string | undefined, opts: RenderBlocksOptions): string | undefined {\n const e = like ? opts.vocabulary?.entries.find((x) => x.id === like) : undefined;\n return e?.computed.inheritsColor ? e.computed.color : undefined;\n}\n\nexport function renderBlocks(node: BlockNode, opts: RenderBlocksOptions): JSX.Element | null {\n const el = renderOwn(node, opts);\n const color = inheritedColor((node as { like?: string }).like, opts);\n return el && color ? cloneElement(el, { style: { ...((el.props as { style?: CSSProperties }).style ?? {}), color } }) : el;\n}\n\nfunction renderOwn(node: BlockNode, opts: RenderBlocksOptions): JSX.Element | null {\n try {\n // A borrowed class list is the site's own styling: when it resolves, the\n // node keeps only LAYOUT styles (flex/grid/gap/pad/align, image fit,\n // measure) and none of the palette paint — colors, borders, radius and\n // type come from the site's CSS.\n const cls = classOf(node, opts);\n switch (node.type) {\n case 'stack': {\n // Same unknown-token fallback as the grid below (audit SNIP-11).\n const gap = GAP[node.gap ?? 'md'] ?? GAP['md'];\n // Rung 1: pad reuses the GAP scale; a raised stack with no pad\n // defaults to md (a zero-padding card is a design bug, not a choice).\n // Mirrors packages/snippet/src/blocks.ts — the drift-pin test is what\n // keeps the two renderers agreeing on these literals.\n const raised = node.surface === 'raised' && !cls;\n const pad = node.pad ?? (raised ? 'md' : undefined);\n return (\n <div\n {...(cls ? { className: cls } : {})}\n style={{\n display: 'flex',\n flexDirection: node.direction,\n gap,\n ...(node.align ? { alignItems: FLEX_POS[node.align] } : {}),\n ...(node.justify ? { justifyContent: FLEX_POS[node.justify] } : {}),\n ...(node.wrap ? { flexWrap: 'wrap' } : {}),\n ...(pad ? { padding: GAP[pad] ?? GAP['md'] } : {}),\n ...(raised\n ? {\n ...(opts.palette?.surface ? { background: opts.palette.surface } : {}),\n ...(opts.palette?.surface && opts.palette?.surfaceText ? { color: opts.palette.surfaceText } : {}),\n border: `1px solid ${opts.palette?.border ?? 'currentColor'}`,\n borderRadius: opts.palette?.radius ?? '8px',\n }\n : {}),\n }}\n >\n {(node.children ?? []).map((child, i) => {\n const rendered = renderBlocks(child, opts);\n return rendered === null ? null : <Fragment key={i}>{rendered}</Fragment>;\n })}\n </div>\n );\n }\n case 'grid': {\n // Responsive by construction — identical template to the snippet\n // (blocks.ts:84): auto-fit collapses on narrow screens, the calc()\n // floor keeps each item at an exact 1/columns share on wide ones.\n const gap = GAP[node.gap ?? 'md'] ?? GAP['md']!;\n return (\n <div\n {...(cls ? { className: cls } : {})}\n style={{\n display: 'grid',\n gridTemplateColumns: `repeat(auto-fit, minmax(max(200px, calc((100% - ${node.columns - 1} * ${gap}) / ${node.columns})), 1fr))`,\n gap,\n ...(node.align ? { alignItems: FLEX_POS[node.align] } : {}),\n ...(node.pad ? { padding: GAP[node.pad] ?? GAP['md'] } : {}),\n }}\n >\n {(node.children ?? []).map((child, i) => {\n const rendered = renderBlocks(child, opts);\n return rendered === null ? null : <Fragment key={i}>{rendered}</Fragment>;\n })}\n </div>\n );\n }\n case 'text':\n if (cls) {\n return (\n <p className={cls} style={node.maxWidth === 'measure' ? { maxWidth: '65ch' } : undefined}>\n {node.value}\n </p>\n );\n }\n return (\n <p\n style={{\n margin: 0,\n ...(node.size ? { fontSize: FONT_SIZE[node.size] } : {}),\n ...(node.weight ? { fontWeight: WEIGHT[node.weight] } : {}),\n ...(node.align ? { textAlign: node.align } : {}),\n ...(node.maxWidth === 'measure' ? { maxWidth: '65ch' } : {}),\n ...toneStyles(node.tone, opts.palette),\n }}\n >\n {node.value}\n </p>\n );\n case 'heading': {\n const Tag = `h${node.level}` as 'h1' | 'h2' | 'h3' | 'h4';\n if (cls) {\n return (\n <Tag className={cls} style={node.maxWidth === 'measure' ? { maxWidth: '65ch' } : undefined}>\n {node.value}\n </Tag>\n );\n }\n return (\n <Tag\n style={{\n margin: 0,\n fontSize: HEADING_SIZE[node.size ?? 'md'],\n ...(node.align ? { textAlign: node.align } : {}),\n ...(node.maxWidth === 'measure' ? { maxWidth: '65ch' } : {}),\n }}\n >\n {node.value}\n </Tag>\n );\n }\n case 'button': {\n const emphasis = node.emphasis ?? 'primary';\n return (\n <a\n href={safeBlockUrl(node.href)}\n {...(node.tag ? { 'data-sentient-tag': node.tag } : {})}\n {...(cls ? { className: cls } : { style: buttonStyle(emphasis, opts.palette, node.size) })}\n >\n {node.label}\n </a>\n );\n }\n case 'link':\n return (\n <a\n href={safeBlockUrl(node.href)}\n {...(node.tag ? { 'data-sentient-tag': node.tag } : {})}\n {...(cls ? { className: cls } : { style: { color: 'inherit', textDecoration: 'underline' } })}\n >\n {node.label}\n </a>\n );\n case 'image':\n return (\n <img\n src={safeBlockUrl(node.src)}\n alt={node.alt}\n {...(cls ? { className: cls } : {})}\n style={{\n display: 'block',\n maxWidth: '100%',\n ...(node.ratio && node.ratio !== 'auto' ? { aspectRatio: RATIO[node.ratio], width: '100%' } : {}),\n ...(node.fit ? { objectFit: node.fit } : {}),\n }}\n />\n );\n case 'badge':\n if (cls) return <span className={cls}>{node.value}</span>;\n return (\n <span\n style={{\n display: 'inline-block',\n padding: '2px 10px',\n borderRadius: '999px',\n fontSize: '0.75em',\n border: `1px solid ${opts.palette?.border ?? 'currentColor'}`,\n ...toneStyles(node.tone, opts.palette),\n }}\n >\n {node.value}\n </span>\n );\n case 'spacer':\n return <div style={{ height: SPACER[node.size] ?? SPACER['md'] }} />;\n case 'divider':\n // <hr> for semantics; border-top (not the default inset border) so the\n // hairline matches form fields and badges in the palette border color.\n return (\n <hr\n style={{\n border: 'none',\n borderTop: `1px solid ${opts.palette?.border ?? 'currentColor'}`,\n margin: 0,\n width: '100%',\n }}\n />\n );\n case 'form':\n return <FormNode node={node} opts={opts} />;\n default:\n return null; // newer-server node type — skip, never throw\n }\n } catch {\n return null; // fail-safe\n }\n}\n\n/**\n * A Redesign (compose) arm: the tree, painted on a site section/card surface\n * when its style resolves. Null when the tree's root can't render (a newer\n * server's node type) — the caller treats that like a blocked blocks arm.\n */\nexport function renderCompose(compose: ComposeArm, opts: RenderBlocksOptions): JSX.Element | null {\n const body = renderBlocks(compose.tree, opts);\n if (body === null) return null;\n const surface = compose.surface?.like ? opts.vocabulary?.entries.find((e) => e.id === compose.surface!.like)?.classes : undefined;\n const color = inheritedColor(compose.surface?.like, opts);\n return surface ? <div className={surface} {...(color ? { style: { color } } : {})}>{body}</div> : body;\n}\n","import { cloneElement, isValidElement, type ReactElement, type ReactNode } from 'react';\nimport type { ArmEdits, RegionSkeleton } from '@sentientui/core';\nimport { normalizeLeafText, skeletonFingerprint } from '@sentientui/core/region';\n\n// A served content arm is COPY, not a component. AdaptiveSlot used to render\n// it as `body = config.content` — the developer's children thrown away whole —\n// so an <Adaptive> wrapping a styled <button> served a bare string in a div:\n// the site's button, its classes and its icon all gone (observed on Bodyshop,\n// 2026-09-23; the generated arm was never approved because it looked broken).\n// The copy has to land INSIDE the element the developer wrote.\n//\n// Stricter than the snippet's `applyContentText` fallback (textContent on the\n// target): React has no target element to keep, only the developer's tree.\n// - exactly one visible text leaf → only that leaf changes; every element,\n// class, icon and sibling around it survives.\n// - anything else (zero leaves, or several) → null. Several leaves means the\n// region has structure one string cannot fill (Bodyshop's two buttons\n// flattened into a sentence, 2026-09-23); zero means the text lives where\n// the tree can't see it (`label={…}`, i18n components). The caller renders\n// children and — since phase 1 — declares the region unable to render\n// content arms (RenderCaps.content = false), so none is ever drawn.\n\nfunction isTextLeaf(node: ReactNode): node is string | number {\n return (typeof node === 'string' && node.trim() !== '') || typeof node === 'number';\n}\n\nfunction childrenOf(el: ReactElement): ReactNode {\n const props = el.props as { children?: ReactNode; dangerouslySetInnerHTML?: unknown };\n // Raw HTML is opaque to the tree walk — its text is not a leaf we can swap,\n // and descending into `children` beside it would find nothing anyway.\n if (props.dangerouslySetInnerHTML != null) return undefined;\n return props.children;\n}\n\nexport function countTextLeaves(node: ReactNode): number {\n if (isTextLeaf(node)) return 1;\n if (Array.isArray(node)) return node.reduce<number>((n, c) => n + countTextLeaves(c as ReactNode), 0);\n if (isValidElement(node)) return countTextLeaves(childrenOf(node));\n return 0;\n}\n\n/** Re-parent children onto a clone. Arrays are spread as separate arguments —\n * the same shape JSX's static children have — so unkeyed siblings the\n * developer wrote don't start raising key warnings just because we cloned. */\nfunction withChildren(el: ReactElement, children: ReactNode): ReactElement {\n return Array.isArray(children) ? cloneElement(el, undefined, ...(children as ReactNode[])) : cloneElement(el, undefined, children);\n}\n\nfunction replaceOnlyLeaf(node: ReactNode, text: string): ReactNode {\n if (isTextLeaf(node)) return text;\n if (Array.isArray(node)) return node.map((c) => replaceOnlyLeaf(c as ReactNode, text));\n if (isValidElement(node)) {\n const inner = childrenOf(node);\n // Untouched subtrees keep their identity — no clone, no remount.\n if (countTextLeaves(inner) === 0) return node;\n return withChildren(node, replaceOnlyLeaf(inner, text));\n }\n return node;\n}\n\n/**\n * The developer's children with a content arm's copy placed inside them, or\n * null when the region doesn't have exactly one text to replace (see above).\n */\nexport function substituteSlotText(children: ReactNode, text: string): ReactNode | null {\n return countTextLeaves(children) === 1 ? replaceOnlyLeaf(children, text) : null;\n}\n\n// ── Per-node edits (spec 2026-09-23 §4.5, Rewrite) ──────────────────────────\n// A generated `edits` arm names nodes of the region skeleton the DOM capture\n// produced. React applies it over the ELEMENT TREE, not the DOM, so SSR and\n// hydration render the same thing. The bridge is the leaf order: the capture\n// only reports a skeleton when the tree's text leaves equal the DOM's\n// (annotateSkeletonForReact), so leaf i here is leaf i there, and\n// `leafToNode[i]` says which node owns it.\n\n// A position in the tree: array indices, and 'c' for \"into this element's\n// children\". An element's path is always followed by 'c' in its leaves' paths.\ntype Step = number | 'c';\ntype Path = Step[];\n\ntype TreeIndex = {\n leafPaths: Path[];\n texts: string[];\n elements: Map<string, ReactElement>;\n};\n\nconst keyOf = (p: Path): string => p.join('/');\n\nfunction indexTree(node: ReactNode, path: Path, out: TreeIndex): void {\n if (isTextLeaf(node)) {\n out.leafPaths.push(path);\n out.texts.push(normalizeLeafText(String(node)));\n return;\n }\n if (Array.isArray(node)) {\n node.forEach((c, i) => indexTree(c as ReactNode, [...path, i], out));\n return;\n }\n if (isValidElement(node)) {\n out.elements.set(keyOf(path), node);\n indexTree(childrenOf(node), [...path, 'c'], out);\n }\n}\n\nfunction buildIndex(children: ReactNode): TreeIndex {\n const idx: TreeIndex = { leafPaths: [], texts: [], elements: new Map() };\n indexTree(children, [], idx);\n return idx;\n}\n\nexport function reactLeafTexts(children: ReactNode): string[] {\n return buildIndex(children).texts;\n}\n\n/** Same value as the DOM capture's `fp` when parity holds — computable at\n * decide time from the tree alone, before any DOM exists. */\nexport function reactFingerprint(children: ReactNode): string | null {\n const t = reactLeafTexts(children);\n return t.length === 0 ? null : skeletonFingerprint(t);\n}\n\n/** Paths of every element that encloses the leaf, outermost first. */\nfunction enclosingElements(leaf: Path): Path[] {\n const out: Path[] = [];\n leaf.forEach((s, i) => {\n if (s === 'c') out.push(leaf.slice(0, i));\n });\n return out;\n}\n\n/** Owner of each node: the deepest element enclosing all of its leaves, or\n * null when a leaf sits directly at the root (no element to hide/restyle). */\nfunction nodeOwners(idx: TreeIndex, leafToNode: number[]): Array<Path | null> {\n const count = leafToNode.reduce((m, n) => Math.max(m, n + 1), 0);\n const owners: Array<Path | null> = [];\n for (let k = 0; k < count; k++) {\n const lists = leafToNode.flatMap((n, i) => (n === k ? [enclosingElements(idx.leafPaths[i]!)] : []));\n if (lists.length === 0) {\n owners.push(null);\n continue;\n }\n let common = lists[0]!;\n for (const l of lists.slice(1)) {\n const keys = new Set(l.map(keyOf));\n common = common.filter((p) => keys.has(keyOf(p)));\n }\n owners.push(common.length > 0 ? common[common.length - 1]! : null);\n }\n return owners;\n}\n\nfunction classNameOf(el: ReactElement | undefined): string | undefined {\n const c = (el?.props as { className?: unknown } | undefined)?.className;\n return typeof c === 'string' ? c : undefined;\n}\n\n/**\n * The skeleton with React's view of it applied, or null when the tree and the\n * DOM disagree (a composite that adds, drops or reorders text; `label={…}`\n * props; i18n components) — edits addressed by leaf order would then land on\n * the wrong element, so the region is reported unaddressable instead.\n */\nexport function annotateSkeletonForReact(skeleton: RegionSkeleton, children: ReactNode): RegionSkeleton | null {\n const idx = buildIndex(children);\n if (idx.texts.length !== skeleton.leaves.length || idx.texts.some((t, i) => t !== skeleton.leaves[i])) return null;\n const owners = nodeOwners(idx, skeleton.leafToNode);\n const nodes = skeleton.nodes.map((n, k) => {\n const owner = owners[k];\n const el = owner ? idx.elements.get(keyOf(owner)) : undefined;\n // A host element always takes className; a composite only visibly when it\n // was handed one (it may not forward an unknown prop).\n const restylable = !!el && (typeof el.type === 'string' || classNameOf(el) !== undefined);\n return { ...n, restylable };\n });\n return { ...skeleton, nodes };\n}\n\n/**\n * The developer's children with a Rewrite arm applied, or null when this tree\n * can't take it (leaf count moved since the skeleton, an owner that can't be\n * hidden/restyled/reordered). Null means the caller renders children — and\n * the page declared its fingerprint at decide time, so a mismatch is normally\n * excluded before the draw rather than discovered here.\n */\nexport function applyEdits(children: ReactNode, edits: ArmEdits, leafToNode: number[]): ReactNode | null {\n const idx = buildIndex(children);\n if (idx.leafPaths.length !== leafToNode.length) return null;\n const nodeCount = leafToNode.reduce((m, n) => Math.max(m, n + 1), 0);\n for (const k of Object.keys(edits.nodes)) {\n if (!/^\\d+$/.test(k) || Number(k) >= nodeCount) return null;\n }\n const owners = nodeOwners(idx, leafToNode);\n const firstLeaf = new Map<number, number>();\n leafToNode.forEach((n, i) => {\n if (!firstLeaf.has(n)) firstLeaf.set(n, i);\n });\n const leafAt = new Map(idx.leafPaths.map((p, i) => [keyOf(p), i]));\n\n const hidden = new Set<string>();\n const restyle = new Map<string, string>();\n let failed = false;\n for (const [ks, e] of Object.entries(edits.nodes)) {\n const k = Number(ks);\n const owner = owners[k];\n if (e.hidden) {\n if (!owner) failed = true;\n else hidden.add(keyOf(owner));\n }\n if (e.like !== undefined) {\n const src = owners[e.like];\n const target = owner ? idx.elements.get(keyOf(owner)) : undefined;\n const cls = src ? classNameOf(idx.elements.get(keyOf(src))) : undefined;\n if (!owner || cls === undefined || classNameOf(target) === undefined) failed = true;\n else restyle.set(keyOf(owner), cls);\n }\n }\n // order[g]: node indices in their new order. Applied at the array that holds\n // all of the group's owners as direct entries.\n const pendingOrders = new Map<string, number[]>(Object.entries(edits.order ?? {}));\n\n const rebuild = (node: ReactNode, path: Path): ReactNode => {\n if (isTextLeaf(node)) {\n const i = leafAt.get(keyOf(path));\n if (i === undefined) return node;\n const k = leafToNode[i]!;\n const text = edits.nodes[String(k)]?.text;\n if (text === undefined) return node;\n return firstLeaf.get(k) === i ? text : '';\n }\n if (Array.isArray(node)) {\n const out = node.map((c, i) => rebuild(c as ReactNode, [...path, i]));\n for (const [g, perm] of pendingOrders) {\n const positions = perm.map((k) => {\n const o = owners[k];\n if (!o || o.length !== path.length + 1 || keyOf(o.slice(0, -1)) !== keyOf(path)) return -1;\n return o[o.length - 1] as number;\n });\n if (positions.some((p) => p < 0)) continue;\n const slots = [...positions].sort((a, b) => a - b);\n const before = [...out];\n slots.forEach((slot, m) => {\n out[slot] = before[positions[m]!];\n });\n pendingOrders.delete(g);\n }\n return out;\n }\n if (isValidElement(node)) {\n const key = keyOf(path);\n if (hidden.has(key)) return null;\n const inner = childrenOf(node);\n // Untouched subtrees keep their identity — no clone, no remount.\n if (countTextLeaves(inner) === 0) return node;\n const rebuilt = rebuild(inner, [...path, 'c']);\n const cls = restyle.get(key);\n const props = cls !== undefined ? { className: cls } : undefined;\n return Array.isArray(rebuilt)\n ? cloneElement(node, props, ...(rebuilt as ReactNode[]))\n : cloneElement(node, props, rebuilt);\n }\n return node;\n };\n\n const out = rebuild(children, []);\n if (failed || pendingOrders.size > 0) return null;\n return out;\n}\n","'use client';\n\n// `type JSX` comes from react, not the global namespace: @types/react@19\n// removed the global JSX while the peer range allows react >=18, so a bare\n// `JSX.*` in the public d.ts fails to resolve for React 19 consumers.\nimport { useEffect, useMemo, useRef, useState, useSyncExternalStore, type ElementType, type JSX } from 'react';\nimport type { GoalName } from './goal-names.js';\nimport type { AssignResult } from '@sentientui/core';\nimport { useSentient, useAdaptiveApiKey, useOnAssignment, useSessionSegment } from './provider.js';\nimport { attachGoalListeners, goalValueOf, isDevBuild, maybeDeclareFunnel, normalizeGoal, type GoalConfig } from './adaptive-shared.js';\nimport { getDevOverride } from './dev-override.js';\nimport { subscribeOverridesChanged } from './override-events.js';\n\n\nexport type AdaptiveTextProps = {\n id: string;\n default: string;\n component?: keyof JSX.IntrinsicElements;\n className?: string;\n /**\n * Optional conversion goal to optimize this copy toward. Without it, the\n * variant is served and logged but never scored — the copy rotates and never\n * learns. Provide a goal (a name string or a GoalConfig) to make the optimizer\n * attribute conversions to the winning wording, exactly like `<Adaptive>`.\n */\n goal?: GoalName | GoalConfig;\n};\n\n/**\n * Dashboard-managed copy for a single element. The variants are **text only** —\n * they change the wording, never the CSS, markup, or layout of the element\n * (managed variants created from the dashboard/MCP carry text, nothing else).\n * For anything structural — style, markup shape, position — write the change in\n * code with `<Adaptive>` (any JSX per variant) or use adaptive slots on no-code\n * sites. Pass `goal` to make the managed copy optimizable (see below).\n */\nexport function AdaptiveText({\n id,\n default: defaultText,\n component: Tag = 'span',\n className,\n goal: goalProp,\n}: AdaptiveTextProps) {\n const client = useSentient();\n const apiKey = useAdaptiveApiKey();\n const onAssignment = useOnAssignment();\n const segment = useSessionSegment();\n const trackedRef = useRef<string | null>(null);\n const nodeRef = useRef<HTMLElement | null>(null);\n\n // Dev override parity with <Adaptive>/useAdaptive: honor\n // ?sentient_variant=id:variant and window.__sentient_overrides (devtools,\n // applyScenario, Playwright/Cypress). A forced variant is a preview — it\n // suppresses the network assign, exposure, and goals (\"no events recorded,\n // weights unchanged\"). Read through useSyncExternalStore (server snapshot\n // null → no hydration mismatch on a ?sentient_variant= page; client snapshot\n // synchronous → no interim assign() before the override applies on remount).\n const override = useSyncExternalStore(\n subscribeOverridesChanged,\n () => getDevOverride(id),\n () => null,\n );\n\n // Seed from cache synchronously so remounts don't flash back to defaultText.\n const [text, setText] = useState<string | null>(() =>\n client?.getAssignment(id, segment)?.content ?? null\n );\n const [variantId, setVariantId] = useState<string | null>(() =>\n client?.getAssignment(id, segment)?.variantId ?? null\n );\n\n useEffect(() => {\n if (override) return; // forced variant — no network assign\n if (!client) return;\n const cached = client.getAssignment(id, segment);\n if (cached?.content !== undefined) {\n // Content already cached — skip the network assign, but DO sync it into\n // state. The client normally arrives AFTER mount (the provider inits it\n // in an effect), so the useState seeds above ran against a null client;\n // early-returning here left text/variantId null, and a returning visitor\n // rendered defaultText all session with no exposure ever recorded. The\n // sync makes the exposure effect below fire variant_assigned (and\n // onAssignment) exactly like the fresh-assign path; when the seeds\n // already caught the cache, these setters are no-op re-renders.\n setVariantId(cached.variantId);\n setText(cached.content);\n return;\n }\n\n let cancelled = false;\n void client.assign(id).then((result: AssignResult | null) => {\n if (cancelled) return;\n if (!result) {\n if (isDevBuild()) {\n console.warn(`[sentient] <AdaptiveText id=\"${id}\"> assignment failed — showing default text.`);\n }\n return;\n }\n setVariantId(result.variantId);\n if (result.content) setText(result.content);\n });\n return () => {\n cancelled = true;\n };\n }, [client, id, segment, override]);\n\n useEffect(() => {\n if (override) return; // forced variant records no exposure\n if (!client || !variantId || !apiKey) return;\n if (trackedRef.current === variantId) return;\n trackedRef.current = variantId;\n client.track({\n projectId: apiKey,\n componentId: id,\n variantId,\n eventType: 'variant_assigned',\n payload: {},\n });\n onAssignment?.(id, variantId);\n }, [client, variantId, apiKey, id, onAssignment, override]);\n\n // Optional goal attribution (opt-in) — mirrors <Adaptive>. Without a goal the\n // copy is served but never scored.\n const goalKey = goalProp === undefined ? '' : typeof goalProp === 'string' ? goalProp : JSON.stringify(goalProp);\n const goal = useMemo(() => (goalProp === undefined ? null : normalizeGoal(goalProp)), [goalKey]);\n const goalLabel = goalProp === undefined ? null : typeof goalProp === 'string' ? goalProp : goal!.type;\n const goalFiredRef = useRef(false);\n\n useEffect(() => {\n goalFiredRef.current = false;\n }, [variantId, goalKey]);\n\n // A weighted composite here is a funnel like everywhere else; without this\n // declaration the copy was credited the SUM of its steps (no `funnel` prop\n // exists on AdaptiveText, so it never joined one).\n useEffect(() => {\n if (override || !client || !apiKey) return;\n maybeDeclareFunnel(client, apiKey, id, undefined, goal);\n }, [client, apiKey, id, goal, override]);\n\n useEffect(() => {\n if (override) return; // forced variant records no goals\n if (!client || !variantId || !apiKey || !goal || !goalLabel) return;\n const node = nodeRef.current;\n if (!node) return;\n // A static goal-config value rides on both writes (spec §5).\n const declaredValue = goalValueOf(goal);\n return attachGoalListeners(node, goal, {\n fireGoal: () => {\n if (goalFiredRef.current) return;\n goalFiredRef.current = true;\n client.track({\n projectId: apiKey,\n componentId: id,\n variantId,\n eventType: 'goal_achieved',\n goalType: goalLabel,\n payload: { reward: 1.0, ...(declaredValue !== undefined ? { goalValue: declaredValue } : {}) },\n });\n client.goal(goalLabel, {\n metadata: { componentId: id, variantId },\n weight: 1.0,\n stepIndex: 0,\n ...(declaredValue !== undefined ? { value: declaredValue } : {}),\n });\n },\n fireStep: (name, weight, stepIndex) => {\n client.track({\n projectId: apiKey,\n componentId: id,\n variantId,\n eventType: 'goal_achieved',\n goalType: name,\n payload: { reward: weight },\n });\n client.goal(name, { metadata: {}, weight, stepIndex });\n },\n });\n }, [client, variantId, apiKey, id, goal, goalLabel, override]);\n\n // Under a forced override, show the override variant's managed copy only if\n // it happens to be cached (managed text lives server-side, so an arbitrary\n // forced variant has no client-available copy) — otherwise fall back to the\n // default. Without an override this is just the assigned/default text.\n let displayText = text ?? defaultText;\n if (override) {\n const cached = client?.getAssignment(id, segment);\n displayText = cached && cached.variantId === override ? (cached.content ?? defaultText) : defaultText;\n }\n\n // Cast to ElementType so a single ref callback works across every intrinsic\n // tag without exploding into the full HTML/SVG ref union.\n const Component = Tag as ElementType;\n return (\n <Component ref={(el: HTMLElement | null) => { nodeRef.current = el; }} className={className}>\n {displayText}\n </Component>\n );\n}\n","import type { GoalName } from './goal-names.js';\nimport { useCallback, useRef } from 'react';\nimport type { ComponentGoalOptions, GoalOptions } from '@sentientui/core';\nimport { useSentient } from './provider.js';\nimport { getDevOverride } from './dev-override.js';\n\nexport interface FireGoalOptions extends ComponentGoalOptions {\n /**\n * Record this goal at most once per mounted component, however many times the\n * callback is invoked. Use it for conversions that are a state, not an action\n * — \"reached step 3\", \"form validated\", an effect that may re-run — where a\n * second record is double counting rather than a second conversion.\n *\n * Leave it off for genuine repeat actions (each click of \"add to cart\" is its\n * own conversion). The latch is per goal type and lives for the lifetime of\n * the component holding the callback, so a remount can record again.\n */\n once?: boolean;\n}\n\nexport type FireGoal = (goalType: GoalName, opts?: FireGoalOptions) => void;\n\n/**\n * The session goal record's options, from a conversion's options. One builder\n * for every hook that records a goal (this one, usePageGoal, useGoal): each\n * built the same object inline, and the React bundle has a byte budget.\n * Revenue fields are passed only when set, so a valueless call stays valueless.\n */\nexport function goalOptionsOf(opts?: ComponentGoalOptions): GoalOptions {\n return {\n metadata: opts?.metadata ?? {},\n weight: opts?.reward ?? 1.0,\n stepIndex: 0,\n ...(opts?.value !== undefined ? { value: opts.value } : {}),\n ...(opts?.currency !== undefined ? { currency: opts.currency } : {}),\n ...(opts?.externalId !== undefined ? { externalId: opts.externalId } : {}),\n };\n}\n\n/**\n * Returns a `fireGoal(goalType, opts?)` callback that records a conversion\n * attributed to the variant currently served for `componentId` — so it shows\n * up in the per-variant CVR funnel with no manual variantId/projectId plumbing.\n *\n * The served variant is resolved from the SDK's assignment cache (the same one\n * `<Adaptive id={componentId}>` populates), so render that component before\n * firing. Use this for imperative handlers (click, form submit, custom events);\n * for purely declarative goals prefer `<Adaptive goal={...}>`.\n *\n * Each call records one bandit reward event AND one session goal-funnel record.\n * It has no cross-call latch, so a component that *also* declares a matching\n * `<Adaptive goal>` (or fires this on every click) records one conversion per\n * call — keep goal labels unique per conversion so counts aren't inflated.\n *\n * @example\n * const fireContact = useAdaptiveGoal('hero_headline');\n * <button onClick={() => fireContact('hero_contact', { metadata: { method } })}>Call</button>\n */\nexport function useAdaptiveGoal(componentId: string): FireGoal {\n const client = useSentient();\n // Goal types already recorded through this callback, for `once`. A ref, not\n // state: latching must not re-render, and the set has to survive the callback\n // being recreated when the client arrives (consent granted mid-session).\n const firedOnce = useRef<Set<string>>(new Set());\n return useCallback<FireGoal>(\n (goalType, opts) => {\n // A forced variant (?sentient_variant= / window.__sentient_overrides) is a\n // dev/QA preview, not real traffic. Recording a goal would credit the\n // bandit and pollute the session funnel for the overridden arm — breaking\n // the \"no events recorded, weights unchanged\" override contract that\n // <Adaptive>, useAdaptive.fireGoal, and the declarative path all honor.\n // Read post-mount (inside the callback), never in a render body.\n // Checked BEFORE the `once` latch: a preview must not consume the one\n // record a real conversion is entitled to after the override clears.\n if (getDevOverride(componentId)) return;\n if (opts?.once) {\n if (firedOnce.current.has(goalType)) return;\n firedOnce.current.add(goalType);\n }\n // componentGoal credits the bandit (arm resolved from the assignment\n // cache); goal() writes the session-level conversion funnel record. A\n // declared <Adaptive goal> fires both — a manual conversion for the same\n // component must too, or it shows up in per-variant CVR but never in the\n // session goal funnel. Revenue fields ride on both writes so read-time\n // dedup never picks a valueless row (spec §5).\n client?.componentGoal(componentId, goalType, opts);\n client?.goal(goalType, goalOptionsOf(opts));\n },\n [client, componentId],\n );\n}\n","import type { GoalName } from './goal-names.js';\nimport { useEffect, useRef } from 'react';\nimport type { ComponentGoalOptions } from '@sentientui/core';\nimport { useSentient } from './provider.js';\nimport { goalOptionsOf, useAdaptiveGoal } from './use-adaptive-goal.js';\n\nexport interface PageGoalOptions extends ComponentGoalOptions {\n /**\n * Credit the arrival to the variant currently served for this component —\n * typically the CTA on the page the visitor came FROM. The served variant is\n * read from the assignment cache, which is localStorage-backed, so the credit\n * survives the navigation. Omit for a session-level goal with no per-variant\n * attribution.\n */\n componentId?: string;\n}\n\n/**\n * Records `goalName` once, when a page or route is reached.\n *\n * Use this for funnel steps that are a *destination* rather than a click:\n * reaching /pricing, landing on a signup form, opening a checkout. Arrival is\n * the better signal — it survives the navigation that a click goal can lose,\n * and it also counts visitors who arrived from the nav, a search result or a\n * shared link, none of whom clicked the CTA being measured.\n *\n * Two things this handles that hand-rolling `useAdaptiveGoal` in an effect does\n * not, both of which fail silently:\n *\n * - **Fires once per mount.** A hand-rolled effect re-runs — React's\n * double-invoked effects in development, or the client arriving — and\n * records the arrival again unless you pass `useAdaptiveGoal`'s `once`.\n * (Both latches are per mounted component: a remount records again.)\n * - **Waits for consent.** Under a consent gate the client does not exist when\n * the page mounts, and a visitor who accepts a moment later would lose the\n * goal entirely — `once` would even spend its latch on that dropped call.\n * The arrival is held until the SDK is running, then sent.\n *\n * Safe during SSR (effects do not run on the server) and a no-op without a\n * provider above it.\n *\n * @example\n * // Credit reaching the pricing page to whichever hero CTA sent them.\n * usePageGoal('pricing_view', { componentId: 'hero_cta' });\n *\n * @example\n * // Session-level only — no component to attribute it to.\n * usePageGoal('docs_view');\n */\nexport function usePageGoal(goalName: GoalName, opts: PageGoalOptions = {}): void {\n const { componentId, ...goalOpts } = opts;\n const client = useSentient();\n // Called unconditionally (rules of hooks); only used when componentId is set.\n // It carries the dev-override contract — a forced variant records nothing —\n // so component-attributed arrivals inherit it for free.\n const fireComponentGoal = useAdaptiveGoal(componentId ?? '');\n const fired = useRef(false);\n // Callers pass an object literal, so `goalOpts` has a new identity every\n // render. Keeping it in a ref keeps it out of the dep array without making\n // the effect re-run (the latch would ignore it anyway).\n const optsRef = useRef(goalOpts);\n optsRef.current = goalOpts;\n\n useEffect(() => {\n // Not into a consent-gated client (preConsentBehavior): React replaces it\n // with a new tracking client on grant, so a goal fired now would go\n // nowhere while spending the latch — the arrival was lost for every\n // visitor who accepted after landing (grader NEW-1). The effect re-runs\n // when the tracking client arrives.\n if (!client || fired.current || client.gated) return;\n fired.current = true;\n if (componentId) {\n fireComponentGoal(goalName, optsRef.current);\n return;\n }\n client.goal(goalName, goalOptionsOf(optsRef.current));\n }, [client, componentId, goalName, fireComponentGoal]);\n}\n","import type { GoalName } from './goal-names.js';\nimport { useCallback, useEffect, useRef } from 'react';\nimport type { SentientClient } from '@sentientui/core';\nimport { useAdaptiveApiKey, useSentient } from './provider.js';\nimport { goalOptionsOf, useAdaptiveGoal, type FireGoalOptions } from './use-adaptive-goal.js';\nimport { isDevBuild } from './adaptive-shared.js';\n\nexport interface UseGoalOptions {\n /**\n * Make this the project's main goal — the one experiments optimize and\n * results are measured on. Change which hook carries it and deploy to change\n * the main goal; no dashboard visit needed.\n *\n * It moves the main goal only when the declared goal CHANGES, so a main goal\n * picked in the dashboard sticks until your code declares a different one.\n * From localhost it only sets a main goal when the project has none. Every\n * change is in the project's activity log. Declare it in ONE place: two\n * different `primary` goals on a page are a mistake, and only the first counts.\n */\n primary?: boolean;\n /**\n * Also credit the conversion to the version currently served for this\n * component (same as `useAdaptiveGoal(componentId)`). Omit for a goal that\n * belongs to the visit, not to one component.\n */\n componentId?: string;\n}\n\n/** Records the goal. Options are per conversion: a value, an order id, `once`. */\nexport type FireNamedGoal = (opts?: FireGoalOptions) => void;\n\n// What this page load has already declared, per API key. A declaration is a\n// definition, not telemetry: once per page is all the server needs (it keeps\n// the steady state at zero writes itself), and every mount of a component\n// holding the hook re-running it would be one event per render tree.\nconst declared = new Set<string>();\nconst primaryByKey = new Map<string, string>();\n\n/** Test-only: clears the page-load declaration state. */\nexport function __resetGoalDeclarations(): void {\n declared.clear();\n primaryByKey.clear();\n}\n\nfunction declareGoal(client: SentientClient, apiKey: string, name: string, primary: boolean): void {\n let asPrimary = primary;\n if (primary) {\n const existing = primaryByKey.get(apiKey);\n if (existing && existing !== name) {\n // Two main goals on one page: whichever mounts first would win per page,\n // and the server would see them alternate. Keep the first and say so,\n // rather than let the main goal depend on render order.\n if (isDevBuild()) {\n console.warn(`[SentientUI] useGoal('${name}'): '${existing}' is already primary on this page`);\n }\n asPrimary = false;\n } else {\n primaryByKey.set(apiKey, name);\n }\n }\n const key = `${apiKey}|${name}|${asPrimary ? 'primary' : ''}`;\n if (declared.has(key)) return;\n declared.add(key);\n client.track({\n projectId: apiKey,\n componentId: '__session__',\n eventType: 'goal_declared',\n payload: asPrimary ? { goalId: name, primary: true } : { goalId: name },\n });\n}\n\n/**\n * A goal your site records — declared where it happens, and fired from there.\n *\n * Declaring it is what makes it show in the dashboard straight away, at an\n * honest 0, before anyone has completed it. `primary: true` makes it the\n * project's main goal. The returned function records one conversion.\n *\n * @example\n * const signup = useGoal('signup', { primary: true });\n * <form onSubmit={() => signup()}>…</form>\n *\n * @example\n * // A revenue goal, credited to the hero version that was showing.\n * const purchase = useGoal('purchase', { componentId: 'hero_cta' });\n * purchase({ value: order.total, externalId: order.id });\n */\nexport function useGoal(name: GoalName, options: UseGoalOptions = {}): FireNamedGoal {\n const { primary = false, componentId } = options;\n const client = useSentient();\n const apiKey = useAdaptiveApiKey();\n // Called unconditionally (rules of hooks); used only with componentId. It\n // carries the dev-override contract — a forced version records nothing.\n const fireComponentGoal = useAdaptiveGoal(componentId ?? '');\n const firedOnce = useRef(false);\n\n useEffect(() => {\n // Not into a consent-gated client: React swaps in a tracking client on\n // grant, the effect re-runs with it, and the declaration goes out then.\n if (!client || client.gated || !apiKey) return;\n declareGoal(client, apiKey, name, primary);\n }, [client, apiKey, name, primary]);\n\n return useCallback<FireNamedGoal>(\n (opts) => {\n if (opts?.once) {\n if (firedOnce.current) return;\n firedOnce.current = true;\n }\n if (componentId) {\n fireComponentGoal(name, opts);\n return;\n }\n client?.goal(name, goalOptionsOf(opts));\n },\n [client, componentId, fireComponentGoal, name],\n );\n}\n","// `type JSX` from react, not the global namespace removed in @types/react@19\n// (peers allow react >=18) — see adaptive-text.tsx.\nimport type { JSX } from 'react';\nimport { renderPrePaintScript, type StageAttributes } from '@sentientui/core';\nimport { confidenceBand } from '@sentientui/policy';\n\nexport type SentientPersonaScriptProps = {\n /** Publishable API key — selects the localStorage snapshot in the fallback path. */\n apiKey: string;\n /**\n * CSP nonce for the inline pre-paint script. Pass the same nonce your\n * `Content-Security-Policy` `script-src` allows (e.g. from Next.js middleware).\n * Required for strict CSP deployments that block `'unsafe-inline'`.\n */\n nonce?: string;\n /**\n * SSR-decided persona (from `loadAdaptiveDecision`). When present the\n * script embeds the literal values; when absent it reads the local\n * decision snapshot (SPA / return-visit path).\n */\n persona?: { persona: string; confidence: number } | null;\n /**\n * The same consent gate you give the provider. With `consent={false}`, or a\n * `consentFrom` source and no `consent={true}`, nothing is rendered: the\n * fallback reads the stored decision from the visitor's device, and that\n * must wait for consent (grader F3). `AdaptiveRoot` handles this for you.\n */\n consent?: boolean;\n consentFrom?: unknown;\n /**\n * Opt-in `data-sentient-stage` (see `AdaptiveProviderProps.stageAttributes`).\n * With a server decision, pass the value to write as `stage` (already\n * coarsened — `exposedStage` from `@sentientui/core`); without one the\n * script copies the stage the visitor's last decide stored.\n */\n stageAttributes?: StageAttributes;\n /** The stage value to write, from this request's decide; null writes none. */\n stage?: string | null;\n};\n\n/** JSON string literal that is also safe inside an inline <script> element. */\nfunction inlineJsString(value: string): string {\n return JSON.stringify(value).replace(/</g, '\\\\u003c');\n}\n\n/** Exported for tests. Builds the inline JS (concatenation only — no backticks). */\nexport function personaScriptBody(props: SentientPersonaScriptProps): string {\n if (props.persona) {\n return (\n '(function(){try{var d=document.documentElement;' +\n // The stage first, with its own single-writer check: an already-set\n // persona must not stop it. Only a value this request's decide gave.\n (props.stage\n ? 'if(!d.hasAttribute(\"data-sentient-stage\"))d.setAttribute(\"data-sentient-stage\",' + inlineJsString(props.stage) + ');'\n : '') +\n 'if(d.hasAttribute(\"data-sentient-persona\"))return;' +\n 'd.setAttribute(\"data-sentient-persona\",' + inlineJsString(props.persona.persona) + ');' +\n 'd.setAttribute(\"data-sentient-confidence\",' + inlineJsString(confidenceBand(props.persona.confidence)) + ');' +\n '}catch(e){}})();'\n );\n }\n return renderPrePaintScript(props.apiKey, props.stageAttributes ? { stage: true } : undefined);\n}\n\n/**\n * Single writer of the Rung-1a `<html>` attributes\n * (`data-sentient-persona`, `data-sentient-confidence`), executed pre-paint.\n *\n * `AdaptiveRoot` renders this automatically as its first child. For Pages\n * Router / Remix, render it yourself in `_document` / the root layout.\n *\n * IMPORTANT (install docs): add `suppressHydrationWarning` to your `<html>`\n * element — this script mutates documentElement before React hydrates it\n * (the same pattern next-themes uses). The client SDK adopts the attributes\n * as truth and never rewrites them mid-session.\n */\nexport function SentientPersonaScript(props: SentientPersonaScriptProps): JSX.Element | null {\n // A server-decided persona is not a storage read, so it always renders.\n if (!props.persona && (props.consent === false || (props.consentFrom !== undefined && props.consent !== true))) return null;\n return (\n <script\n data-sentient-persona-script=\"\"\n nonce={props.nonce}\n dangerouslySetInnerHTML={{ __html: personaScriptBody(props) }}\n />\n );\n}\n","import type { GoalName } from './goal-names.js';\nimport { useEffect, useMemo, useRef } from 'react';\nimport type { SlotDeclInput } from '@sentientui/core';\nimport { validateSlotDecl } from '@sentientui/policy';\nimport { useAdaptiveApiKey, useSentient } from './provider.js';\nimport { useSlotResult } from './use-slot-result.js';\nimport { registerSlot } from './devtools-registry.js';\nimport {\n attachGoalListeners,\n goalLabelOf,\n goalValueOf,\n isDevBuild,\n maybeDeclareFunnel,\n normalizeGoal,\n trackExposure,\n type GoalConfig,\n} from './adaptive-shared.js';\n\nexport type UseAdaptiveTokensOptions = {\n goal?: GoalName | GoalConfig;\n /** Funnel this slot serves (stable funnel id, e.g. \"checkout\") — same\n * declaration semantics as <Adaptive funnel=\"...\">. */\n funnel?: string;\n};\nexport type UseAdaptiveTokensResult = {\n tokens: Record<string, string>;\n /** Spread on the slot's element: `data-<dim>` per dim + `data-sentient-slot`. */\n props: Record<string, string>;\n};\n\n// Warn once per slot id per page lifetime — not per render.\nconst warnedTokenSlots = new Set<string>();\n\nfunction cssEscape(value: string): string {\n if (typeof CSS !== 'undefined' && typeof CSS.escape === 'function') return CSS.escape(value);\n // Fallback for environments without CSS.escape: the value is interpolated\n // inside a double-quoted attribute selector (`[data-sentient-slot=\"…\"]`), so\n // both the backslash and the closing quote must be escaped — the old\n // quote-only escape let a slot id containing `\\` break out of the selector\n // (and an unescaped `\"` in a since-fixed path could match the wrong node).\n return value.replace(/[\\\\\"]/g, '\\\\$&');\n}\n\n/**\n * Rung 1b — adaptive design tokens. Declares a bounded token space; the\n * optimizer picks per persona; values apply as element-scoped data\n * attributes so they serialize through SSR markup (zero flicker,\n * hydration-safe). First value of each dim = baseline.\n *\n * ```tsx\n * const t = useAdaptiveTokens('hero', { tone: ['calm', 'urgent'] });\n * return <section {...t.props} className=\"hero\">…</section>;\n * // CSS: .hero[data-tone=\"urgent\"] .cta { … }\n * ```\n */\nexport function useAdaptiveTokens(\n id: string,\n dims: Record<string, readonly string[]>,\n opts?: UseAdaptiveTokensOptions,\n): UseAdaptiveTokensResult {\n const client = useSentient();\n const apiKey = useAdaptiveApiKey();\n\n // Freeze the declaration on the DIMS SIGNATURE, not the object identity: an\n // inline `dims={{...}}` literal is a fresh object each render, so keying on it\n // would churn a new decl every commit. A stringified signature is stable\n // across renders for the same dims yet updates if the declared space changes\n // (same convention as <Adaptive> / useAdaptive / AdaptiveGroup). A slot's\n // declared space is normally fixed for the session.\n const dimsKey = JSON.stringify(dims);\n // eslint-disable-next-line react-hooks/exhaustive-deps\n const decl = useMemo<SlotDeclInput>(() => ({ id, dims }), [id, dimsKey]);\n const { result, arm, source } = useSlotResult(id, decl);\n const tokens = useMemo<Record<string, string>>(\n () => (typeof result === 'string' ? {} : result),\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [arm],\n );\n\n if (isDevBuild() && !warnedTokenSlots.has(id)) {\n // Added UNCONDITIONALLY: the id used to be added only on the warn branches,\n // so a VALID declaration re-ran validateSlotDecl plus the combination-space\n // product on every dev render for the page's whole lifetime.\n warnedTokenSlots.add(id);\n const validity = validateSlotDecl({\n id,\n dims: Object.fromEntries(Object.entries(dims).map(([k, v]) => [k, [...v]])),\n });\n const space = Object.values(dims).reduce((n, values) => n * values.length, 1);\n if (!validity.ok) {\n console.warn(\n `[sentient] useAdaptiveTokens(\"${id}\"): invalid declaration — ${validity.reason}. Serving baseline.`,\n );\n } else if (space > 4) {\n console.warn(\n `[sentient] useAdaptiveTokens(\"${id}\") declares ${space} combinations — more than the recommended 4. Each extra combination needs more traffic to learn; consider fewer dims/values.`,\n );\n }\n }\n\n const goalKey =\n opts?.goal === undefined ? null : typeof opts.goal === 'string' ? opts.goal : JSON.stringify(opts.goal);\n\n // Devtools slot registry — the declared dims space drives both persona\n // simulation and the panel's per-dim override buttons. A slot is NOT a\n // component: registering it as one produced buttons that wrote the wrong\n // override channel (`__sentient_overrides` instead of `__sentient_slot_overrides`).\n // eslint-disable-next-line react-hooks/exhaustive-deps\n useEffect(() => registerSlot({ id, dims }), [id]);\n\n // Exposure — the slot equivalent of <Adaptive>'s variant_assigned event,\n // once per (slot, arm). variantId = canonical arm string.\n const exposedArmRef = useRef<string | null>(null);\n useEffect(() => {\n // Don't expose an unresolved baseline: a `baseline` source means the slot\n // was never decided (interim local decide, or a keyed client with no SSR\n // preload). Recording it accrues a phantom baseline impression that can\n // never convert. Once a real arm resolves (source flips to preloaded/\n // client) the exposure fires for that arm.\n // A forced arm (`override`, from devtools/tests) is a preview, not a real\n // exposure — recording it would train the optimizer on the override, the\n // same \"no events, weights unchanged\" contract <Adaptive> honors for\n // component overrides.\n // `seeded` is the core holding a snapshot arm or a failure baseline: it\n // renders, but no slot_decisions row exists for it this session, so an\n // impression would train an arm the server never served — and a failed\n // decide batch used to yield one phantom baseline exposure per slot.\n if (!client || source === 'baseline' || source === 'seeded' || source === 'override' || exposedArmRef.current === arm) return;\n exposedArmRef.current = arm;\n trackExposure(client, apiKey, id, arm);\n }, [client, apiKey, id, arm, source]);\n\n // Funnel membership declaration — same override gate as the exposure. A\n // weighted composite with no `funnel` declares its own (compositeFunnelId).\n const funnel = opts?.funnel;\n useEffect(() => {\n if (!client || source === 'override') return;\n maybeDeclareFunnel(client, apiKey, id, funnel, normalizeGoal(opts?.goal ?? 'click'));\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [client, apiKey, id, funnel, goalKey, source]);\n\n // Optional goal: the returned props carry data-sentient-slot, so the slot's\n // element is findable without a ref (the pinned return type has no ref).\n // Credit flows through componentGoal(slot id) — the core resolves the\n // attributed arm from its slot state (Task 3.3 fallback).\n useEffect(() => {\n // Forced arms record nothing (preview only), and an unresolved `baseline`\n // source never recorded an impression (see the exposure effect above) — a\n // conversion attached in that state would attribute to an arm with zero\n // exposures. Same source gates as the exposure.\n if (!client || !opts?.goal || source === 'override' || source === 'baseline' || source === 'seeded') return;\n const node = document.querySelector(`[data-sentient-slot=\"${cssEscape(id)}\"]`);\n if (!node) {\n if (isDevBuild()) {\n console.warn(\n `[sentient] useAdaptiveTokens(\"${id}\"): a goal is declared but no element carries the returned props — spread {...props} on the slot's element.`,\n );\n }\n return;\n }\n const label = goalLabelOf(opts.goal);\n const declaredValue = goalValueOf(opts.goal);\n let fired = false;\n return attachGoalListeners(node, normalizeGoal(opts.goal), {\n fireGoal: () => {\n if (fired) return;\n fired = true;\n // componentGoal credits the bandit (goal_achieved event, arm resolved\n // from slot state); goal() writes the session-level conversion funnel\n // record — exactly what <Adaptive> does for component goals. Slots\n // fired only the former, so slot conversions were invisible in the\n // goal funnel; fire both so membership matches components. (One funnel\n // record per conversion — see useAdaptiveGoal; keep labels unique.)\n // A static goal-config value rides on both writes (spec §5).\n if (declaredValue !== undefined) client.componentGoal(id, label, { value: declaredValue });\n else client.componentGoal(id, label);\n client.goal(label, {\n metadata: { componentId: id, arm },\n weight: 1.0,\n stepIndex: 0,\n ...(declaredValue !== undefined ? { value: declaredValue } : {}),\n });\n },\n fireStep: (name, weight, stepIndex) => {\n client.componentGoal(id, name, { reward: weight });\n client.goal(name, { metadata: { componentId: id, arm }, weight, stepIndex });\n },\n }, label);\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [client, id, goalKey, arm, source]);\n\n const props = useMemo(() => {\n const p: Record<string, string> = { 'data-sentient-slot': id };\n for (const [dim, value] of Object.entries(tokens)) p[`data-${dim}`] = value;\n return p;\n }, [id, tokens]);\n\n return { tokens, props };\n}\n","import { useEffect, useReducer, useState, useSyncExternalStore } from 'react';\nimport { armOfResult, baselineResultFor, type SlotDeclInput, type SlotResult } from '@sentientui/core';\nimport { confidenceBand } from '@sentientui/policy';\nimport { useInitialPersona, useInitialSlots, useSentient } from './provider.js';\nimport { subscribeOverridesChanged, getOverridesVersion } from './override-events.js';\n\ndeclare global {\n interface Window {\n /** Test/devtools forcing: slot id → forced result (applyScenario sets this). */\n __sentient_slot_overrides?: Record<string, SlotResult>;\n /** Test/devtools forcing: forced persona (applyScenario sets this). */\n __sentient_persona_override?: { persona: string; confidence?: number };\n }\n}\n\nexport type SlotResolution = {\n result: SlotResult;\n /** Canonical arm string (`dim=value|…` for dims slots, arm id for arms slots). */\n arm: string;\n /**\n * `client` = decided for this session (a slot_decisions row exists);\n * `seeded` = the core client holds a result that was NOT decided this\n * session — a snapshot from an earlier visit or the baseline it wrote when a\n * decide failed. Seeded results render (pre-paint parity) but must never be\n * exposed or credited: there is no trial for them to belong to.\n */\n source: 'override' | 'preloaded' | 'client' | 'seeded' | 'baseline';\n};\n\n/**\n * Internal. Resolves what a slot serves this render, synchronously:\n * test/devtools override → SSR-preloaded result → core client state\n * (decide cache, snapshot seed, failure baseline) → declared baseline.\n * Purely read-side: exposure/goal wiring belongs to the calling hook.\n */\nexport function useSlotResult(slotId: string, decl: SlotDeclInput): SlotResolution {\n const client = useSentient();\n const initialSlots = useInitialSlots();\n const [, bump] = useReducer((n: number) => n + 1, 0);\n\n // Devtools/test forcing (window.__sentient_slot_overrides — applyScenario,\n // the Playwright/Cypress mocks) read through the useSyncExternalStore\n // SNAPSHOT with a null server snapshot, exactly like useAssignment's dev\n // override and useLayoutOrder. The old direct window read in the render body\n // made the pre-hydration client render disagree with the server HTML\n // whenever an override was written before hydration — which is precisely\n // when the package's own Playwright/Cypress mocks write it — i.e. a\n // hydration mismatch. The snapshot returns the stored object by reference\n // (stable until the override bus notifies a rewrite), so it passes React's\n // Object.is snapshot-caching check.\n const override = useSyncExternalStore(\n subscribeOverridesChanged,\n () => (typeof window !== 'undefined' ? window.__sentient_slot_overrides?.[slotId] : undefined),\n () => undefined,\n );\n const preloaded = override === undefined ? initialSlots[slotId] : undefined;\n const fromClient =\n override === undefined && preloaded === undefined && client\n ? client.getSlotResult(slotId)\n : null;\n\n // Keyless local mode on a CSR-only page: nothing has decided this slot yet\n // (no SSR preload, no snapshot), so ask the local engine — zero network,\n // deterministic — and re-render when the decision lands. Keyed clients\n // never take this path: their slots decide server-side (SSR preload).\n const needsLocalDecide =\n client?.isLocal === true &&\n override === undefined &&\n preloaded === undefined &&\n fromClient === null;\n useEffect(() => {\n if (!needsLocalDecide || !client) return;\n let cancelled = false;\n void client.decide({ slots: [decl] }).then((outcome) => {\n if (!cancelled && outcome) bump();\n });\n return () => {\n cancelled = true;\n };\n // decl identity is fixed per slot id (callers memoize it on id).\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [client, slotId, needsLocalDecide]);\n\n const resolution: SlotResolution = (() => {\n if (override !== undefined) {\n return { result: override, arm: armOfResult(override), source: 'override' };\n }\n if (preloaded !== undefined) {\n return { result: preloaded, arm: armOfResult(preloaded), source: 'preloaded' };\n }\n if (fromClient !== null) {\n // A result the core holds but did not decide this session (snapshot seed,\n // failure baseline) renders as-is but is `seeded`, so the exposure and\n // goal gates in the calling hooks skip it. Clients without the probe\n // (hand-rolled/test) read as decided, as before.\n const decided = client?.isSlotDecided ? client.isSlotDecided(slotId) : true;\n return { result: fromClient, arm: armOfResult(fromClient), source: decided ? 'client' : 'seeded' };\n }\n const baseline = baselineResultFor(decl);\n return { result: baseline, arm: armOfResult(baseline), source: 'baseline' };\n })();\n\n // Keyed clients decide THIS mounted slot when nothing preloaded it: one\n // batched decide per commit (core decideSlots), then re-render when it lands.\n // Before this a keyed client never decided request-declared slots in the\n // browser — useAdaptiveTokens and AdaptiveGroup served their baseline for the\n // whole session and learned nothing unless the same declaration was\n // duplicated into AdaptiveRoot's `slots` for SSR. Snapshot-seeded ('client')\n // slots still ask: the snapshot is the last visit's answer, not a decision\n // for this session. Only mounted slots are decided, so a declaration on\n // another page never becomes a trial for this visit.\n const settled = resolution.source === 'preloaded' || resolution.source === 'override';\n useEffect(() => {\n if (!client || client.isLocal === true || settled || !client.decideSlots) return;\n const off = client.onSlotsChanged?.(bump);\n client.decideSlots([decl]);\n return () => {\n // Unmounted before the batch was sent (redirecting route, StrictMode\n // probe): withdraw it — a slot that is not on the page is not a trial.\n client.cancelSlots?.([slotId]);\n off?.();\n };\n // decl identity is fixed per slot id (callers memoize it on id).\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [client, slotId, settled]);\n\n return resolution;\n}\n\n/**\n * Reads a forced persona: `window.__sentient_persona_override` (the devtools\n * panel, `applyScenario`, the Playwright/Cypress helpers) or the\n * `?sentient_persona=<persona key>` URL param (any project vocabulary key;\n * mirrors `?sentient_variant=`).\n * Read POST-MOUNT only — it touches `window.location`.\n */\nfunction getPersonaOverride(): { persona: string; confidence: number } | null {\n if (typeof window === 'undefined') return null;\n const forced = window.__sentient_persona_override;\n if (forced?.persona) return { persona: forced.persona, confidence: forced.confidence ?? 1 };\n try {\n const value = new URLSearchParams(window.location.search).get('sentient_persona');\n if (value) return { persona: value, confidence: 1 };\n } catch {\n /* non-browser env */\n }\n return null;\n}\n\nexport type AdaptivePersona = {\n persona: string;\n confidence: number;\n band: 'low' | 'medium' | 'high';\n};\n\n/**\n * The current persona estimate for React consumers, resolved in priority\n * order: a forced override (devtools / `applyScenario` / `?sentient_persona=`)\n * → the SSR-provided `initialPersona` → the live client estimate (adopted\n * attributes / snapshot / decide). Returns `null` when nothing is known yet.\n *\n * Hydration-safe: the first render (server + pre-hydration client) uses ONLY\n * the SSR-provided persona so server and client agree; the override channel and\n * the live client estimate — neither visible to the server — are read after\n * mount. Re-renders when a persona/variant override is written, so devtools or\n * a test forcing a persona mid-session takes effect immediately.\n */\nexport function useAdaptivePersona(): AdaptivePersona | null {\n const client = useSentient();\n const initialPersona = useInitialPersona();\n // Re-render when the override channel is written. NOTE: unlike useAssignment /\n // AdaptiveText — which fold the override into the useSyncExternalStore snapshot\n // (getDevOverride returns a STABLE string) — persona can't: getPersonaOverride\n // allocates a fresh object each call, which would fail the snapshot's Object.is\n // check and trip React's \"getSnapshot should be cached\" loop guard. So we\n // subscribe to the stable version counter for reactivity and read the override\n // in the render body (behind a mounted gate). That one-frame post-mount flip is\n // harmless here because this hook is side-effect-free (no assign/exposure to\n // leak), which is exactly why useAssignment/AdaptiveText could NOT tolerate it.\n useSyncExternalStore(subscribeOverridesChanged, getOverridesVersion, () => 0);\n const [mounted, setMounted] = useState(false);\n useEffect(() => setMounted(true), []);\n\n const withBand = (p: { persona: string; confidence: number }): AdaptivePersona => ({\n persona: p.persona,\n confidence: p.confidence,\n band: confidenceBand(p.confidence),\n });\n\n // First render must match the server, which can see neither window nor the\n // client estimate — use only initialPersona to avoid a hydration mismatch on\n // a ?sentient_persona= page.\n if (!mounted) {\n return initialPersona ? withBand(initialPersona) : null;\n }\n const override = getPersonaOverride();\n if (override) return withBand(override);\n if (initialPersona) return withBand(initialPersona);\n const live = client ? client.getPersona() : null;\n return live ? withBand(live) : null;\n}\n","import type { GoalName } from './goal-names.js';\nimport { useCallback, useEffect, useMemo } from 'react';\nimport type { ComponentGoalOptions } from '@sentientui/core';\nimport { isDevBuild, type GoalConfig } from './adaptive-shared.js';\nimport { useVariantComponent, type MicroSignalGoals } from './use-variant-component.js';\nimport { useInitialUnified } from './provider.js';\n\nexport type UseAdaptiveBind = {\n ref: (el: HTMLElement | null) => void;\n 'data-sentient-id': string;\n 'data-sentient-variant': string;\n};\n\nexport type UseAdaptiveResult<T> = {\n variant: string;\n value: T;\n /** Spread on the rendered element — wires exposure, goal listeners, and micro-signals. */\n bind: UseAdaptiveBind;\n fireGoal: (goalType?: string, opts?: ComponentGoalOptions) => void;\n};\n\nconst warnedUnbound = new Set<string>();\nconst warnedUnified = new Set<string>();\n\n/**\n * Rung 2 — headless, measurement-complete variant swap. Supersedes\n * `useAssignment` (which selects a variant but wires no measurement).\n *\n * `goal` is REQUIRED: without one the optimizer accumulates exposures with\n * zero rewards and cannot learn. `bind` MUST be attached to the rendered\n * element — dev mode warns loudly when a slot renders unbound.\n *\n * ```tsx\n * const { value, bind } = useAdaptive('buy-box', {\n * variants: { calm: <CalmBuyBox/>, urgent: <UrgentBuyBox/> }, // first key = baseline\n * goal: 'buy_click',\n * });\n * return <div {...bind}>{value}</div>;\n * ```\n */\nexport function useAdaptive<T>(\n id: string,\n config: {\n variants: Record<string, T>;\n goal: GoalName | GoalConfig;\n /** Funnel this component serves (stable funnel id, e.g. \"checkout\") —\n * same declaration semantics as <Adaptive funnel=\"...\">. */\n funnel?: string;\n /** When a passive micro-signal fires on the bound element, also record a\n * named goal — same mapping as <Adaptive microSignalGoals>. */\n microSignalGoals?: MicroSignalGoals;\n },\n): UseAdaptiveResult<T> {\n if (isDevBuild() && !config.goal) {\n throw new Error(\n `[sentient] useAdaptive(\"${id}\"): a goal is required — without one the optimizer accumulates exposures with no rewards and cannot learn. Pass e.g. goal: 'buy_click'.`,\n );\n }\n\n // Selection + exposure/funnel/goal/micro-signal wiring is the engine shared\n // with <Adaptive variants>. No cursor_signal here: the hook never sent one and\n // adding an event stream is not a refactor.\n const { client, variantIds, variantId, isOverride, goalLabel, ref, nodeRef } = useVariantComponent(\n id,\n config.variants,\n { goal: config.goal, funnel: config.funnel, microSignalGoals: config.microSignalGoals },\n );\n // Unlike <Adaptive> (which renders nothing without a variant), the headless\n // hook always hands back a value: the first key until a variant resolves.\n const variant = variantId ?? variantIds[0] ?? '';\n const value = config.variants[variant] as T;\n\n // A moved component (CONTRACTS §2 \"A unified component is a slot\") has no\n // headless slot path yet: the hook keeps being served the frozen variants\n // result read-only, and nothing it shows is learned from. Said once, in dev,\n // rather than failing silently.\n const knownUnified = useInitialUnified().includes(id) || client?.isUnified?.(id) === true;\n useEffect(() => {\n if (!knownUnified || !isDevBuild() || warnedUnified.has(id)) return;\n warnedUnified.add(id);\n console.warn(\n `[sentient] useAdaptive(\"${id}\"): this component was moved to the shared track, which useAdaptive cannot render yet. ` +\n `It keeps showing the frozen result and learns nothing — render it with <Adaptive id=\"${id}\" variants={...}> instead.`,\n );\n }, [knownUnified, id]);\n\n // Dev warning: bind never attached shortly after mount → exposures would\n // never fire and the slot cannot learn. Once per slot id.\n useEffect(() => {\n if (!isDevBuild()) return;\n if (!client) return;\n const timer = setTimeout(() => {\n if (!nodeRef.current && !warnedUnbound.has(id)) {\n warnedUnbound.add(id);\n console.warn(\n `[sentient] useAdaptive(\"${id}\"): bind was never attached — spread {...bind} on the rendered element, otherwise exposure and goal tracking cannot work and the optimizer learns nothing.`,\n );\n }\n }, 0);\n return () => clearTimeout(timer);\n }, [client, id]);\n\n const fireGoal = useCallback(\n (goalType?: string, opts?: ComponentGoalOptions) => {\n if (isOverride) return; // forced variants record nothing, even manual goals\n // componentGoal credits the bandit; goal() writes the session goal-funnel\n // record. The declared-goal listener above fires both, so a manual goal\n // for the same slot must too (otherwise it's absent from the funnel).\n // Like useAdaptiveGoal, this writes one funnel record per call with no\n // cross-call latch — keep goal labels unique per conversion (a component\n // that ALSO fires a declared goal on the same action records both).\n const name = goalType ?? goalLabel;\n // Empty only on the missing-goal misuse path (fail-soft above) with no\n // explicit goalType — nothing meaningful to record.\n if (!name) return;\n client?.componentGoal(id, name, opts);\n client?.goal(name, {\n metadata: opts?.metadata ?? {},\n weight: opts?.reward ?? 1.0,\n stepIndex: 0,\n ...(opts?.value !== undefined ? { value: opts.value } : {}),\n ...(opts?.currency !== undefined ? { currency: opts.currency } : {}),\n ...(opts?.externalId !== undefined ? { externalId: opts.externalId } : {}),\n });\n },\n [client, id, goalLabel, isOverride],\n );\n\n const bind = useMemo<UseAdaptiveBind>(\n () => ({ ref, 'data-sentient-id': id, 'data-sentient-variant': variant }),\n [ref, id, variant],\n );\n\n return { variant, value, bind, fireGoal };\n}\n","// `type JSX` from react, not the global namespace removed in @types/react@19\n// (peers allow react >=18) — see adaptive-text.tsx.\nimport { Children, isValidElement, useEffect, useMemo, useRef, type JSX, type ReactNode } from 'react';\nimport type { GoalName } from './goal-names.js';\nimport type { SlotDeclInput } from '@sentientui/core';\nimport { useAdaptiveApiKey, useSentient } from './provider.js';\nimport { useSlotResult } from './use-slot-result.js';\nimport { registerSlot } from './devtools-registry.js';\nimport {\n attachGoalListeners,\n goalLabelOf,\n goalValueOf,\n isDevBuild,\n maybeDeclareFunnel,\n normalizeGoal,\n trackExposure,\n type GoalConfig,\n} from './adaptive-shared.js';\n\nexport type AdaptiveGroupProps = {\n id: string;\n /** Arrangement id → ordered child keys. FIRST key = baseline default. */\n arrangements: Record<string, string[]>;\n /** Explicit baseline arrangement id (defaults to the first declared). */\n baseline?: string;\n /** Optional slot-scoped goal — credited via componentGoal(group id). */\n goal?: GoalName | GoalConfig;\n /** Funnel this group serves (stable funnel id, e.g. \"checkout\") — same\n * declaration semantics as <Adaptive funnel=\"...\">. */\n funnel?: string;\n /** Keyed children — every key referenced by an arrangement must exist. */\n children: ReactNode;\n};\n\n// Warn once per group id per page lifetime.\nconst warnedGroups = new Set<string>();\n\n/**\n * Rung 3 — bounded mini-layout. Reorders KEYED children into the decided\n * arrangement (enumerated-arms slot: arms = Object.keys(arrangements)).\n * Declared orders only — never free permutation, never show/hide.\n * Fail-safe: unknown arrangement or key mismatch renders declaration order.\n */\nexport function AdaptiveGroup(props: AdaptiveGroupProps): JSX.Element {\n const client = useSentient();\n const apiKey = useAdaptiveApiKey();\n const containerRef = useRef<HTMLDivElement>(null);\n\n // Freeze the arrangement-id array on the KEY SET (same convention as\n // <Adaptive> / useAdaptive / useAdaptiveTokens): stable across renders for the\n // same keys yet updates if the declared set changes. Declared space is\n // normally fixed per group id for a session.\n const arrangementKey = Object.keys(props.arrangements).join(' ');\n // eslint-disable-next-line react-hooks/exhaustive-deps\n const arrangementIds = useMemo(() => Object.keys(props.arrangements), [arrangementKey]);\n const decl = useMemo<SlotDeclInput>(\n () => ({\n id: props.id,\n arms: arrangementIds,\n ...(props.baseline !== undefined ? { baseline: props.baseline } : {}),\n }),\n [props.id, arrangementIds, props.baseline],\n );\n const { arm, source } = useSlotResult(props.id, decl);\n\n if (\n isDevBuild() &&\n props.baseline !== undefined &&\n props.baseline !== arrangementIds[0] &&\n !warnedGroups.has(props.id + ':baseline')\n ) {\n warnedGroups.add(props.id + ':baseline');\n console.warn(\n `[sentient] <AdaptiveGroup id=\"${props.id}\">: baseline \"${props.baseline}\" is not the first-declared arrangement (\"${arrangementIds[0]}\"). The first arrangement should usually be the page's real incumbent (the holdout sees it).`,\n );\n }\n\n const childArray = Children.toArray(props.children).filter(isValidElement);\n const byKey = new Map<string, (typeof childArray)[number]>();\n for (const child of childArray) {\n // Children.toArray prefixes explicit keys with '.$'.\n byKey.set(String(child.key ?? '').replace(/^\\.\\$/, ''), child);\n }\n\n const order = props.arrangements[arm];\n const canReorder =\n order !== undefined &&\n order.length === childArray.length &&\n order.every((key) => byKey.has(key));\n\n if (\n isDevBuild() &&\n order !== undefined &&\n !canReorder &&\n !warnedGroups.has(props.id + ':keys')\n ) {\n warnedGroups.add(props.id + ':keys');\n console.warn(\n `[sentient] <AdaptiveGroup id=\"${props.id}\">: arrangement \"${arm}\" [${order.join(', ')}] does not match the children's keys — rendering declaration order (fail-safe).`,\n );\n }\n\n const ordered = canReorder ? order.map((key) => byKey.get(key)!) : childArray;\n\n // Devtools slot registry — the declared arms space drives persona simulation\n // and the panel's per-arm override buttons. A group is a slot, not a component:\n // registering it as one produced buttons that wrote the wrong override channel.\n useEffect(\n () => registerSlot({ id: props.id, arms: Object.keys(props.arrangements) }),\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [props.id],\n );\n\n // Exposure — once per (group, arrangement). An unresolved `baseline` source\n // means the group was never decided (interim local decide, or a keyed client\n // with no SSR preload); exposing it would record a phantom baseline\n // impression that can never convert, so skip until a real arm resolves.\n const exposedArmRef = useRef<string | null>(null);\n useEffect(() => {\n // A forced arm (`override`, from devtools/tests) is a preview, not a real\n // exposure — skip it so the optimizer isn't trained on the override (same\n // contract <Adaptive> honors for component overrides). `seeded` — a\n // snapshot arm or failure baseline the core holds without a decision for\n // this session — renders but is not a trial either.\n if (!client || source === 'baseline' || source === 'seeded' || source === 'override' || exposedArmRef.current === arm) return;\n exposedArmRef.current = arm;\n trackExposure(client, apiKey, props.id, arm);\n }, [client, apiKey, props.id, arm, source]);\n\n // Funnel membership declaration — same override gate as the exposure. A\n // weighted composite with no `funnel` declares its own (compositeFunnelId).\n const funnel = props.funnel;\n const declaredGoalKey = props.goal === undefined || typeof props.goal === 'string' ? '' : JSON.stringify(props.goal);\n useEffect(() => {\n if (!client || source === 'override') return;\n maybeDeclareFunnel(client, apiKey, props.id, funnel, normalizeGoal(props.goal ?? 'click'));\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [client, apiKey, props.id, funnel, declaredGoalKey, source]);\n\n // Optional goal — slot-scoped credit through componentGoal (the core\n // resolves the attributed arm from its slot state; see Task 3.3).\n const goalKey =\n props.goal === undefined ? null : typeof props.goal === 'string' ? props.goal : JSON.stringify(props.goal);\n useEffect(() => {\n // Forced arms record nothing (preview only), and an unresolved `baseline`\n // source never recorded an impression (see the exposure effect above) — a\n // conversion attached in that state would attribute to an arm with zero\n // exposures. Same source gates as the exposure.\n if (!client || props.goal === undefined || source === 'override' || source === 'baseline' || source === 'seeded') return;\n const node = containerRef.current;\n if (!node) return;\n const label = goalLabelOf(props.goal);\n const declaredValue = goalValueOf(props.goal);\n let fired = false;\n return attachGoalListeners(node, normalizeGoal(props.goal), {\n fireGoal: () => {\n if (fired) return;\n fired = true;\n // componentGoal credits the bandit; goal() writes the session-level\n // conversion funnel record — matching <Adaptive>. Firing only the\n // former left group conversions out of the goal funnel. A static\n // goal-config value rides on both writes (spec §5).\n if (declaredValue !== undefined) client.componentGoal(props.id, label, { value: declaredValue });\n else client.componentGoal(props.id, label);\n client.goal(label, {\n metadata: { componentId: props.id, arm },\n weight: 1.0,\n stepIndex: 0,\n ...(declaredValue !== undefined ? { value: declaredValue } : {}),\n });\n },\n fireStep: (name, weight, stepIndex) => {\n client.componentGoal(props.id, name, { reward: weight });\n client.goal(name, { metadata: { componentId: props.id, arm }, weight, stepIndex });\n },\n }, label);\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [client, props.id, goalKey, arm, source]);\n\n return (\n <div ref={containerRef} data-sentient-id={props.id} data-sentient-variant={arm}>\n {ordered}\n </div>\n );\n}\n","/** @deprecated Use `useSessionSegment()` (exported from `@sentientui/react`) for the segment the\n * provider uses, or `deriveSessionSegment` from `@sentientui/core` outside React. Removed in 1.0. */\nexport { deriveSessionSegment as detectSegment } from '@sentientui/core';\n","/**\n * Agent-readable content feed. Merges SDK-known data (winning variants, layout\n * order) with developer-supplied page content, and renders it either as a\n * server-rendered inline JSON-LD block (read by passive AI crawlers, which do\n * not run JS) or as Markdown (for agents that content-negotiate `text/markdown`).\n *\n * No React or DOM APIs — safe to import in server components, route handlers,\n * and middleware.\n */\n\nexport type AgentBlock = {\n /** Component ID. */\n id: string;\n /** Winning variant ID currently served. */\n variant: string;\n /** Agent-readable data attached to the served variant, if any. */\n content?: unknown;\n};\n\nexport type AgentFeed = {\n page: string;\n title?: string;\n summary?: string;\n layoutOrder?: string[];\n blocks: AgentBlock[];\n /** Developer-supplied extra fields (products, specs, arbitrary JSON). */\n [key: string]: unknown;\n};\n\n/** Fields the SDK owns — developer content can never overwrite these. */\nconst RESERVED_FIELDS = ['page', 'blocks', 'layoutOrder'] as const;\n\nconst registry = new Map<string, Record<string, unknown>>();\n\n/**\n * Register page-level structured content the SDK can't infer (title, summary,\n * product fields, arbitrary JSON), keyed by page path. Call at module load.\n */\nexport function defineAgentContent(page: string, content: Record<string, unknown>): void {\n registry.set(page, content);\n}\n\n/** Look up registered content for a page. */\nexport function getAgentContent(page: string): Record<string, unknown> | undefined {\n return registry.get(page);\n}\n\n/** Clear the registry — intended for tests. */\nexport function clearAgentContent(): void {\n registry.clear();\n}\n\n/**\n * Merge SDK-known data with developer-supplied content into a single feed.\n * Developer content fills in title/summary/etc. but can never overwrite the\n * SDK-authoritative fields (`page`, `blocks`, `layoutOrder`).\n */\nexport function buildAgentFeed(input: {\n page: string;\n blocks: AgentBlock[];\n layoutOrder?: string[];\n content?: Record<string, unknown>;\n}): AgentFeed {\n const supplied = input.content ?? getAgentContent(input.page) ?? {};\n const safe: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(supplied)) {\n if (!(RESERVED_FIELDS as readonly string[]).includes(k)) safe[k] = v;\n }\n const feed: AgentFeed = {\n ...safe,\n page: input.page,\n blocks: input.blocks,\n };\n if (input.layoutOrder) feed.layoutOrder = input.layoutOrder;\n return feed;\n}\n\n/**\n * Render the feed as a server-rendered inline JSON-LD `<script>` string. `<` is\n * escaped to `<` so embedded content cannot break out of the script\n * element. MUST be emitted on the server — passive crawlers never run client JS.\n */\nexport function renderAgentJsonLd(feed: AgentFeed): string {\n return `<script type=\"application/ld+json\">${renderAgentJsonLdBody(feed)}</script>`;\n}\n\n/**\n * The escaped JSON-LD body only (no `<script>` wrapper). For React server\n * components, inject via `<script type=\"application/ld+json\"\n * dangerouslySetInnerHTML={{ __html: renderAgentJsonLdBody(feed) }} />`.\n */\nexport function renderAgentJsonLdBody(feed: AgentFeed): string {\n return JSON.stringify({ '@context': 'https://schema.org', '@type': 'WebPage', ...feed })\n .replace(/</g, '\\\\u003c');\n}\n\n/** Render the feed as Markdown for agents that negotiate `text/markdown`. */\nexport function renderAgentMarkdown(feed: AgentFeed): string {\n const lines: string[] = [];\n if (feed.title) lines.push(`# ${feed.title}`, '');\n if (feed.summary) lines.push(String(feed.summary), '');\n\n for (const [k, v] of Object.entries(feed)) {\n if (['page', 'title', 'summary', 'blocks', 'layoutOrder'].includes(k)) continue;\n lines.push(`## ${k}`, '', '```json', JSON.stringify(v, null, 2), '```', '');\n }\n\n if (feed.blocks.length > 0) {\n lines.push('## blocks', '');\n for (const b of feed.blocks) {\n lines.push(`- **${b.id}** → variant \\`${b.variant}\\``);\n if (b.content !== undefined) {\n lines.push('', ' ```json', JSON.stringify(b.content, null, 2), ' ```');\n }\n }\n lines.push('');\n }\n\n return lines.join('\\n').trimEnd() + '\\n';\n}\n","export { AdaptiveProvider, useSentient, useInitialAssignments, useLayoutOrder, useAdaptiveApiBaseUrl, useSessionSegment } from './provider.js';\nexport type { AdaptiveProviderProps, SsrFallback } from './provider.js';\n// The vocabulary `sectionTypes` accepts, so a typed app can build the map\n// without a direct @sentientui/core dependency.\nexport type { SemanticType } from '@sentientui/core/engagement';\n\nexport { Adaptive } from './adaptive.js';\nexport type {\n AdaptiveProps,\n AdaptiveVariantsProps,\n AdaptiveGeneratedProps,\n AdaptiveElement,\n GoalConfig,\n ClickGoal,\n ScrollDepthGoal,\n FormSubmitGoal,\n CompositeGoal,\n WeightedStep,\n WeightedCompositeGoal,\n MicroSignalGoals,\n MicroSignalGoalConfig,\n} from './adaptive.js';\n\nexport { AdaptiveText } from './adaptive-text.js';\nexport type { AdaptiveTextProps } from './adaptive-text.js';\n\n/**\n * @deprecated Use {@link useAdaptive} instead — it selects a variant AND wires\n * exposure, goal, and micro-signal tracking. `useAssignment` only selects, so a\n * component built on it directly records no learning signal. Kept exported for\n * back-compat (it is `useAdaptive`'s internal selection engine); moving to\n * internal-only in 1.0.0.\n */\nexport { useAssignment } from './use-assignment.js';\nexport type { AssignmentState } from './use-assignment.js';\n\nexport { useAdaptiveGoal } from './use-adaptive-goal.js';\nexport type { FireGoal } from './use-adaptive-goal.js';\n\nexport { usePageGoal } from './use-page-goal.js';\nexport type { PageGoalOptions } from './use-page-goal.js';\n\nexport type { Register, GoalName } from './goal-names.js';\nexport { useGoal } from './use-goal.js';\nexport type { UseGoalOptions, FireNamedGoal } from './use-goal.js';\n\nexport { SentientPersonaScript } from './persona-script.js';\nexport type { SentientPersonaScriptProps } from './persona-script.js';\n\nexport { useAdaptiveTokens } from './use-adaptive-tokens.js';\n\nexport { AdaptiveSlot } from './adaptive-slot.js';\nexport type { AdaptiveSlotProps } from './adaptive-slot.js';\nexport type { UseAdaptiveTokensOptions, UseAdaptiveTokensResult } from './use-adaptive-tokens.js';\n\nexport { useAdaptive } from './use-adaptive.js';\nexport type { UseAdaptiveResult, UseAdaptiveBind } from './use-adaptive.js';\n\nexport { useAdaptivePersona } from './use-slot-result.js';\nexport type { AdaptivePersona } from './use-slot-result.js';\n\nexport { AdaptiveGroup } from './adaptive-group.js';\nexport type { AdaptiveGroupProps } from './adaptive-group.js';\n\nexport type { ComponentWeights, VariantWeight } from './weights-store.js';\n\nexport { detectSegment } from './segment.js';\n\nexport {\n defineAgentContent,\n getAgentContent,\n buildAgentFeed,\n renderAgentJsonLd,\n renderAgentJsonLdBody,\n renderAgentMarkdown,\n} from './agent-feed.js';\nexport type { AgentFeed, AgentBlock } from './agent-feed.js';\n\n// Re-exported from core so a React app can wire its consent banner to the SDK\n// without adding @sentientui/core as a direct dependency — the docs already\n// point React users at grantConsent(), so it belongs on this entry.\n//\n// Safe here, unlike the server-only helpers re-exported from /next — though\n// not for the reason once claimed: tsup DOES stamp a 'use client' banner on\n// this bundle (see tsup.config.ts), so this re-export IS a client reference.\n// It stays safe because grantConsent is browser-only (it returns immediately\n// during SSR), so it is only ever invoked from client components and the\n// client reference is never called on the server.\nexport { grantConsent } from '@sentientui/core';\n\n// Composition Block renderer, exported for operator surfaces (the dashboard's\n// review preview renders a pending arm exactly as AdaptiveSlot would, with the\n// same palette). Not needed for normal SDK integration — AdaptiveSlot renders\n// served arms itself.\nexport { renderBlocks, renderCompose } from './blocks-render.js';\nexport type { RenderBlocksOptions } from './blocks-render.js';\nexport type { SitePalette } from '@sentientui/core';\n// Consent platforms (Cookiebot, OneTrust, CookieYes, IAB TCF, Google Consent\n// Mode): the same watcher `consentFrom` uses, for gating a site's OTHER\n// consent-bound scripts (an ad pixel) on the same platform, from one package.\nexport { consentWatcher } from '@sentientui/core/consent';\nexport type { ConsentSource, Con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AC,IAAK,OAAO,QAAQE,CAAI,EAClC,CAAC,OAAQ,QAAS,UAAW,SAAU,aAAa,EAAE,SAASH,CAAC,GACpES,EAAM,KAAK,MAAMT,CAAC,GAAI,GAAI,UAAW,KAAK,UAAUC,EAAG,KAAM,CAAC,EAAG,MAAO,EAAE,EAG5E,GAAIE,EAAK,OAAO,OAAS,EAAG,CAC1BM,EAAM,KAAK,YAAa,EAAE,EAC1B,QAAWC,KAAKP,EAAK,OACnBM,EAAM,KAAK,OAAOC,EAAE,EAAE,uBAAkBA,EAAE,OAAO,IAAI,EACjDA,EAAE,UAAY,QAChBD,EAAM,KAAK,GAAI,YAAa,KAAK,UAAUC,EAAE,QAAS,KAAM,CAAC,EAAG,OAAO,EAG3ED,EAAM,KAAK,EAAE,CACf,CAEA,OAAOA,EAAM,KAAK;AAAA,CAAI,EAAE,QAAQ,EAAI;AAAA,CACtC,CC/BA,OAAS,gBAAAE,OAAoB,mBAY7B,OAAS,kBAAAC,OAAsB","names":["createContext","useContext","useEffect","useMemo","useRef","useState","useSyncExternalStore","deriveSessionSegment","init","store","listeners","subscribe","componentId","cb","set","update","weights","e","getWeights","_a","ssrFallback","state","w","getPreviewMode","state","subscribePreview","fn","listeners","createPreviewClient","inner","componentId","segment","_a","_b","variantIds","agentData","agentDataByVariant","opts","slotId","ids","EVENT","getOverridesVersion","_a","notifyOverridesChanged","w","subscribeOverridesChanged","fn","publishDevtoolsConfig","config","isDevBuild","_a","normalizeGoal","goal","goalLabelOf","goalValueOf","scrollFiredThisTask","scrollGateClearArmed","scrollFireCollapsedThisTask","key","clear","ch","isClickableTarget","el","tag","findClickable","start","container","selector","cursor","e","attachGoalListeners","node","handlers","scrollDedupeKey","firedSteps","wcCleanups","sub","stepName","stepWeight","idx","fireStep","viaScroll","onClick","target","onSubmit","threshold","io","entries","entry","subgoals","remaining","_","i","fireViaScroll","checkComposite","cleanups","c","declaredFunnels","declaredMemberships","compositeFunnelId","componentId","slug","h","i","MAX_FUNNEL_STEPS","compositeFunnelSteps","goal","seen","steps","s","n","ordered","a","b","isDevBuild","maybeDeclareFunnel","client","apiKey","explicitFunnelId","composite","funnelId","memberKey","declaredMemberships","declaredFunnels","withSteps","trackExposure","variantId","ssrFallback","state","w","emit","fn","NOOP_UNREGISTER","registerComponent","c","isDevBuild","registerSlot","s","registerSections","sections","version","SDK_IDENT","store","w","setSlotConfigOverride","slotId","entry","setVocabularyOverride","v","getVocabularyOverride","_a","store","w","setSlotOverride","slotId","result","takeHashParam","name","v","h","m","after","rest","e","TOKEN_KEY","pending","active","editorSessionActive","cached","editorSession","apiBase","code","takeHashParam","t","res","token","e","endEditorSession","PARAM_CELL","PARAM_REFRESH","BAR_ID","PREVIEW_ARM","pendingRefresh","takeRegionRefresh","slotId","r","submitRegionRefresh","body","s","__spreadValues","res","mountBar","maybeStartCellPreview","apiBaseUrl","cell","refresh","params","e","base","session","editorSession","editorSessionActive","setSlotConfigOverride","setSlotOverride","notifyOverridesChanged","sep","persona","data","setVocabularyOverride","_a","text","bar","label","exit","endEditorSession","url","started","maybeCaptureStyles","apiBaseUrl","base","editorSession","session","capture","token","run","sampleStyleVocabulary","jsx","deriveDefaultSegment","_a","_b","deriveSessionSegment","e","DEFAULT_API_BASE_URL","AdaptiveContext","createContext","warnedNoConsentGate","answeredThisPage","useConsentSource","source","apiKey","onRefused","onRefusedRef","useRef","granted","setGranted","useState","refused","setRefused","sourceRef","key","__spreadProps","__spreadValues","useEffect","s","stop","cancelled","consentWatcher","forgetVisitor","watcher","wasRefused","update","r","g","AdaptiveProvider","props","_c","_d","_e","client","setClient","sessionSegment","previewOn","setPreviewOn","getPreviewMode","subscribePreview","maybeStartCellPreview","maybeCaptureStyles","dropHeldRef","consent","forgetOnFalse","forgetRef","clientRef","trackingRef","heldRef","refusedRef","c","tracking","adopt","config","SDK_IDENT","created","stopEngagement","handOff","call","startEngagement","startEngagementCapture","initGraph","init","poll","entries","entry","weights","v","timerId","ssrFallback","apiBaseUrl","frozenConfigRef","current","prev","publishDevtoolsConfig","identityUser","identityHash","decided","registerSections","isDevBuild","declared","present","el","missing","id","exposedClient","useMemo","createPreviewClient","value","_f","_g","_h","_i","NO_UNIFIED","useSentient","useContext","useAdaptiveApiKey","useInitialAssignments","useInitialUnified","useSessionSegment","useSsrFallback","useOnAssignment","useDebug","useLayoutOrder","contextOrder","override","useSyncExternalStore","subscribeOverridesChanged","useInitialSlots","useInitialPersona","useInitialSlotConfig","useInitialPalette","useInitialVocabulary","useAdaptiveApiBaseUrl","memo","useCallback","useEffect","useState","useCallback","useEffect","useMemo","useRef","useState","attachMicroSignalDetectors","useEffect","useRef","useState","useSyncExternalStore","pickFromWeights","getDevOverride","componentId","_a","global","params","raw","sep","e","useAssignment","componentId","variantIds","agentData","agentDataByVariant","opts","initialAssignments","useInitialAssignments","ssrFallback","useSsrFallback","client","useSentient","segment","useSessionSegment","onAssignment","useOnAssignment","debug","useDebug","assignmentReportedRef","useRef","devOverride","useSyncExternalStore","subscribeOverridesChanged","getDevOverride","overrideVariant","overrideLoggedRef","useEffect","state","setState","useState","_a","_b","preloaded","cached","weights","getWeights","chosen","pickFromWeights","reportAssignment","variantId","prev","cancelled","onUnified","result","subscribe","useVariantComponent","id","variants","opts","client","useSentient","apiKey","useAdaptiveApiKey","variantKey","variantIds","useMemo","variantId","content","isOverride","settled","useAssignment","node","setNode","useState","nodeRef","useRef","ref","useCallback","el","rawGoal","goalKey","goal","normalizeGoal","goalLabel","goalLabelOf","useEffect","registerComponent","exposedRef","trackExposure","goalFiredRef","microGoalFiredRef","funnel","maybeDeclareFunnel","cursorSignal","timerId","hoverStart","onEnter","onLeave","microSignalGoalsRef","microKey","assignedAt","attachMicroSignalDetectors","signalType","extra","_a","_b","_c","__spreadValues","mapping","name","weight","stepIndex","declaredValue","goalValueOf","attachGoalListeners","useEffect","useMemo","useRef","useState","useSyncExternalStore","attachMicroSignalDetectors","containsFormBlock","reveal","captureRegionSkeleton","useCallback","useEffect","useRef","useSyncExternalStore","armOfResult","warnedUnservedSlots","FORCED_ARM_CONFIG","useSlotConfig","slotId","opts","_a","_b","_c","client","useSentient","baselineTextRef","useRef","renderRef","skeletonRef","initialSlots","useInitialSlots","initialSlotConfig","useInitialSlotConfig","initialPalette","useInitialPalette","initialVocabulary","useInitialVocabulary","overrideConfig","useSyncExternalStore","subscribeOverridesChanged","overrideResult","armOf","r","armOfResult","subscribeSlots","useCallback","cb","preloaded","fromClient","palette","vocabulary","resolution","getVocabularyOverride","decided","deferred","settled","useEffect","_d","_e","unserved","text","texts","caps","skeleton","extras","__spreadValues","hasExtras","isDevBuild","cloneElement","Fragment","jsx","jsxs","safeBlockUrl","v","GAP","FLEX_POS","FONT_SIZE","HEADING_SIZE","BTN_PAD","SPACER","RATIO","WEIGHT","toneStyles","tone","palette","__spreadValues","buttonStyle","emphasis","size","_a","_b","_c","_d","accent","__spreadProps","FormNode","node","opts","_e","fieldStyle","e","data","values","f","o","classOf","like","inheritedColor","x","renderBlocks","el","renderOwn","color","cloneElement","_f","_g","_h","_i","_j","_k","_l","_m","_n","_o","_p","_q","_r","_s","_t","_u","_v","_w","cls","gap","raised","pad","child","i","rendered","Fragment","Tag","renderCompose","compose","body","surface","cloneElement","isValidElement","normalizeLeafText","skeletonFingerprint","isTextLeaf","node","childrenOf","el","props","countTextLeaves","n","c","isValidElement","withChildren","children","cloneElement","replaceOnlyLeaf","text","inner","substituteSlotText","keyOf","p","indexTree","path","out","normalizeLeafText","buildIndex","idx","reactLeafTexts","reactFingerprint","skeletonFingerprint","enclosingElements","leaf","s","i","nodeOwners","leafToNode","count","m","owners","k","lists","common","l","keys","classNameOf","_a","annotateSkeletonForReact","skeleton","t","nodes","owner","restylable","__spreadProps","__spreadValues","applyEdits","edits","nodeCount","firstLeaf","leafAt","hidden","restyle","failed","ks","e","src","target","cls","pendingOrders","rebuild","g","perm","positions","o","slots","a","b","before","slot","key","rebuilt","jsx","warnedFormSlots","warnedOpaqueSlots","warnedBlockedSlots","AUTHORED_PREFIX","AdaptiveSlot","id","children","variants","onFormSubmit","goal","className","Tag","reportBaselineText","funnel","microSignalGoals","clientOnly","agentDataByVariant","agentData","variantsOnly","_a","_b","client","useSentient","apiKey","useAdaptiveApiKey","nodeRef","useRef","mounted","setMounted","useState","useEffect","hidden","childFp","useMemo","reactFingerprint","authoredKey","caps","__spreadValues","countTextLeaves","captureSkeleton","el","cap","captureRegionSkeleton","annotateSkeletonForReact","__spreadProps","n","forcedKey","useSyncExternalStore","subscribeOverridesChanged","getDevOverride","forcedArm","config","arm","palette","vocabulary","source","useSlotConfig","tree","composed","formBlocked","containsFormBlock","isDevBuild","fireFormGoal","goalName","body","armBlocked","authoredArm","rendered","renderCompose","renderBlocks","e","placed","applyEdits","substituteSlotText","textBlocked","authoredOnScreen","sk","text","editsDrift","showsChildren","r","takeRegionRefresh","submitRegionRefresh","armsKey","devVariantIds","registerComponent","registerSlot","exposedArmRef","trackExposure","armCreditable","goalArm","goalKey","node","label","goalLabelOf","declaredValue","goalValueOf","fired","attachGoalListeners","normalizeGoal","name","weight","stepIndex","goalConfig","maybeDeclareFunnel","microRef","microFiredRef","microKey","attachMicroSignalDetectors","signalType","extra","_c","mapping","agentRef","agentSentRef","fallback","byArm","lookup","data","revealedArm","reveal","dataProps","jsx","AdaptiveImpl","props","_a","_b","client","variantId","content","ref","useVariantComponent","mounted","setMounted","useState","useEffect","Tag","jsxContent","managedContent","isDevBuild","AdaptiveVariants","memo","prev","next","prevKeys","nextKeys","k","Adaptive","AdaptiveSlot","__spreadValues","v","variants","slotProps","__objRest","__spreadProps","AdaptiveVariantsOrUnified","unifiedId","setUnifiedId","id","onUnified","useCallback","useSentient","known","useInitialUnified","_children","rest","first","useEffect","useMemo","useRef","useState","useSyncExternalStore","jsx","AdaptiveText","id","defaultText","Tag","className","goalProp","_a","client","useSentient","apiKey","useAdaptiveApiKey","onAssignment","useOnAssignment","segment","useSessionSegment","trackedRef","useRef","nodeRef","override","useSyncExternalStore","subscribeOverridesChanged","getDevOverride","text","setText","useState","_b","variantId","setVariantId","useEffect","cached","cancelled","result","isDevBuild","goalKey","goal","useMemo","normalizeGoal","goalLabel","goalFiredRef","maybeDeclareFunnel","node","declaredValue","goalValueOf","attachGoalListeners","__spreadValues","name","weight","stepIndex","displayText","el","useCallback","useRef","goalOptionsOf","opts","_a","_b","__spreadValues","useAdaptiveGoal","componentId","client","useSentient","firedOnce","useRef","useCallback","goalType","getDevOverride","useEffect","useRef","usePageGoal","goalName","opts","_a","componentId","goalOpts","__objRest","client","useSentient","fireComponentGoal","useAdaptiveGoal","fired","useRef","optsRef","useEffect","goalOptionsOf","useCallback","useEffect","useRef","declared","primaryByKey","declareGoal","client","apiKey","name","primary","asPrimary","existing","primaryByKey","isDevBuild","key","declared","useGoal","options","componentId","useSentient","useAdaptiveApiKey","fireComponentGoal","useAdaptiveGoal","firedOnce","useRef","useEffect","useCallback","opts","goalOptionsOf","renderPrePaintScript","confidenceBand","jsx","inlineJsString","value","personaScriptBody","props","SentientPersonaScript","useEffect","useMemo","useRef","validateSlotDecl","useEffect","useReducer","useState","useSyncExternalStore","armOfResult","baselineResultFor","confidenceBand","useSlotResult","slotId","decl","client","useSentient","initialSlots","useInitialSlots","bump","useReducer","n","override","useSyncExternalStore","subscribeOverridesChanged","_a","preloaded","fromClient","needsLocalDecide","useEffect","cancelled","outcome","resolution","armOfResult","decided","baseline","baselineResultFor","settled","off","getPersonaOverride","forced","value","e","useAdaptivePersona","initialPersona","useInitialPersona","getOverridesVersion","mounted","setMounted","useState","withBand","p","confidenceBand","live","warnedTokenSlots","cssEscape","value","useAdaptiveTokens","id","dims","opts","client","useSentient","apiKey","useAdaptiveApiKey","dimsKey","decl","useMemo","result","arm","source","useSlotResult","tokens","isDevBuild","validity","validateSlotDecl","k","v","space","n","values","goalKey","useEffect","registerSlot","exposedArmRef","useRef","trackExposure","funnel","_a","maybeDeclareFunnel","normalizeGoal","node","label","goalLabelOf","declaredValue","goalValueOf","fired","attachGoalListeners","__spreadValues","name","weight","stepIndex","props","p","dim","useCallback","useEffect","useMemo","warnedUnbound","warnedUnified","useAdaptive","id","config","_a","_b","isDevBuild","client","variantIds","variantId","isOverride","goalLabel","ref","nodeRef","useVariantComponent","variant","value","knownUnified","useInitialUnified","useEffect","timer","fireGoal","useCallback","goalType","opts","name","__spreadValues","bind","useMemo","Children","isValidElement","useEffect","useMemo","useRef","jsx","warnedGroups","AdaptiveGroup","props","_a","client","useSentient","apiKey","useAdaptiveApiKey","containerRef","useRef","arrangementKey","arrangementIds","useMemo","decl","__spreadValues","arm","source","useSlotResult","isDevBuild","childArray","Children","isValidElement","byKey","child","order","canReorder","key","ordered","useEffect","registerSlot","exposedArmRef","trackExposure","funnel","declaredGoalKey","maybeDeclareFunnel","normalizeGoal","goalKey","node","label","goalLabelOf","declaredValue","goalValueOf","fired","attachGoalListeners","name","weight","stepIndex","deriveSessionSegment","RESERVED_FIELDS","registry","defineAgentContent","page","content","getAgentContent","buildAgentFeed","input","_a","_b","supplied","getAgentContent","safe","k","v","RESERVED_FIELDS","feed","__spreadProps","__spreadValues","renderAgentJsonLd","renderAgentJsonLdBody","renderAgentMarkdown","lines","b","grantConsent","consentWatcher"]}
|
|
1
|
+
{"version":3,"sources":["../src/provider.tsx","../src/weights-store.ts","../src/preview-mode.ts","../src/override-events.ts","../src/devtools-config.ts","../src/adaptive-shared.ts","../src/devtools-registry.ts","../src/sdk-version.ts","../src/devtools-slot-config-overrides.ts","../src/devtools-slot-overrides.ts","../src/hash-param.ts","../src/editor-session.ts","../src/cell-preview.ts","../src/style-capture.ts","../src/adaptive.tsx","../src/use-variant-component.ts","../src/use-assignment.ts","../src/dev-override.ts","../src/adaptive-slot.tsx","../src/use-slot-config.ts","../src/blocks-render.tsx","../src/slot-text.ts","../src/adaptive-text.tsx","../src/use-adaptive-goal.ts","../src/use-page-goal.ts","../src/use-goal.ts","../src/persona-script.tsx","../src/use-adaptive-tokens.ts","../src/use-slot-result.ts","../src/use-adaptive.ts","../src/adaptive-group.tsx","../src/segment.ts","../src/agent-feed.ts","../src/index.ts"],"sourcesContent":["'use client';\n\ndeclare const process: { env?: { NODE_ENV?: string } } | undefined;\n\n// `type JSX` from react, not the global namespace removed in @types/react@19\n// (peers allow react >=18) — see adaptive-text.tsx.\nimport {\n createContext,\n useContext,\n useEffect,\n useMemo,\n useRef,\n useState,\n useSyncExternalStore,\n type JSX,\n type ReactNode,\n} from 'react';\nimport {\n deriveSessionSegment,\n init,\n type ConsentSource,\n type SentientClient,\n type SentientConfig,\n type SitePalette,\n type SlotConfigEntry,\n type StyleVocabulary,\n type StageAttributes,\n type SlotResult,\n} from '@sentientui/core';\nimport type { SemanticType } from '@sentientui/core/engagement';\nimport { update as updateWeightsStore, type ComponentWeights } from './weights-store.js';\nimport { getPreviewMode, subscribePreview, createPreviewClient } from './preview-mode.js';\nimport { subscribeOverridesChanged } from './override-events.js';\nimport { publishDevtoolsConfig } from './devtools-config.js';\nimport { registerSections } from './devtools-registry.js';\nimport { isDevBuild } from './adaptive-shared.js';\nimport { SDK_IDENT } from './sdk-version.js';\nimport { maybeStartCellPreview } from './cell-preview.js';\nimport { maybeCaptureStyles } from './style-capture.js';\n\n/**\n * Feeds browser globals into core's `deriveSessionSegment` so the cache key\n * used by `useAssignment` always matches the key `assign()` writes under.\n * Before this, the context defaulted to 'desktop:direct' while core used the\n * detected segment — a systematic cache miss for every integration that\n * didn't pass `sessionSegment` explicitly. The derivation itself lives in\n * core (audit REACT-14): a hand-mirrored `${device}:${source}` copy here\n * drifted independently of the key core writes, which is the cache-miss bug\n * all over again, one refactor later.\n */\nfunction deriveDefaultSegment(): string {\n if (typeof window === 'undefined') return 'desktop:direct';\n try {\n return deriveSessionSegment({\n userAgent: navigator.userAgent ?? '',\n referer: document.referrer ?? '',\n appOrigin: window.location.origin,\n });\n } catch {\n return 'desktop:direct';\n }\n}\n\nconst DEFAULT_API_BASE_URL = 'https://api.sentient-ui.com/v1';\n\n/** How to render adaptive slots during SSR when assignments are not preloaded. */\nexport type SsrFallback = 'first' | 'none';\n\ntype AdaptiveContextValue = {\n client: SentientClient | null;\n // The publishable API key (pk_…). Historically named `projectId` because the\n // API uses it as the project identifier on the wire, but it is the API key,\n // not the project UUID. Field renamed for clarity.\n apiKey: string;\n initialAssignments: Record<string, string>;\n /** Components an SSR preload found moved onto the shared track. */\n initialUnified: readonly string[];\n sessionSegment: string;\n ssrFallback: SsrFallback;\n onAssignment: ((componentId: string, variantId: string) => void) | undefined;\n initialLayoutOrder: string[] | null;\n initialSlots: Record<string, SlotResult>;\n initialSlotConfig: Record<string, SlotConfigEntry>;\n initialPalette: SitePalette | null;\n initialVocabulary: StyleVocabulary | null;\n initialPersona: { persona: string; confidence: number } | null;\n apiBaseUrl: string;\n debug: boolean;\n};\n\nconst AdaptiveContext = createContext<AdaptiveContextValue>({\n client: null,\n apiKey: '',\n initialAssignments: {},\n initialUnified: [],\n sessionSegment: 'desktop:direct',\n ssrFallback: 'first',\n onAssignment: undefined,\n initialLayoutOrder: null,\n initialSlots: {},\n initialSlotConfig: {},\n initialPalette: null,\n initialVocabulary: null,\n initialPersona: null,\n apiBaseUrl: DEFAULT_API_BASE_URL,\n debug: false,\n});\n\nexport type AdaptiveProviderProps = {\n apiKey: string;\n /**\n * @deprecated Unused — the project's type is set in the dashboard. Safe to omit.\n * Still accepted (and forwarded to core, which ignores it) so existing code compiles.\n */\n context?: SentientConfig['context'];\n debug?: boolean;\n /**\n * SSR-preloaded assignments from `preloadAssignments()` / `loadAdaptiveAssignments()`.\n * Passed through to `useAssignment` as synchronous initial state so crawlers and\n * the first paint see real content (recommended for SEO).\n */\n initialAssignments?: Record<string, string>;\n /**\n * Component ids the SSR preload found moved onto the shared track (the\n * `unified` of `loadAdaptiveAssignments()` / `loadAdaptiveDecision()`;\n * `<AdaptiveRoot>` passes it for you). A variants-only `<Adaptive>` with one\n * of these ids renders on the shared track from the server HTML on, and an\n * assignment cached before the move is ignored.\n */\n initialUnified?: string[];\n /**\n * Bandit segment from SSR (`device:source`). Keeps cache, assign, and worker\n * weights on one row — must match `loadAdaptiveAssignments` / session upsert.\n */\n sessionSegment?: string;\n /**\n * @deprecated Use `clientOnly` on the component; the default behaviour renders\n * the first variant.\n *\n * When no `initialAssignments` exist for a component, `'first'` renders\n * `variantIds[0]` in server HTML (safe default for SEO); `'none'` renders\n * nothing until the client resolves. Still accepted with that exact behaviour\n * so existing trees don't change. Deprecated because it was a provider-wide\n * switch for a per-component decision (`clientOnly` already expresses it), and\n * it only ever reached `<Adaptive variants>` / `useAssignment` — `useAdaptive`\n * falls back to the first key regardless, and AdaptiveText, generated-version\n * `<Adaptive>` and slots never read it, so it read broader than it was.\n * @default 'first'\n */\n ssrFallback?: SsrFallback;\n /**\n * Consent gate. When `false` the SDK is not initialised and no events are\n * sent. Flip to `true` (e.g. after the user accepts the cookie banner) to\n * initialise and begin tracking.\n */\n consent?: boolean;\n /**\n * Where to read the visitor's consent decision from, so the SDK can gate and\n * un-gate itself instead of the host app wiring `grantConsent()` by hand.\n *\n * Keep your own banner or CMP — this only tells us how to observe it. The\n * provider reads the source on mount, re-reads it whenever `event` fires, and\n * initialises the moment it grants. Nothing is requested and no cookie is set\n * until then, and there is no page reload.\n *\n * Because the provider owns the whole lifecycle there is no ordering rule to\n * get right: pass this instead of managing `consent` yourself.\n *\n * @example // cookie written by your own banner\n * consentFrom={{ cookie: 'cookie_consent', value: 'accepted', event: 'consent-decided' }}\n * @example // a supported consent platform (reads its API, events and cookie)\n * consentFrom=\"cookiebot\" // or 'onetrust' | 'cookieyes' | 'tcf' | 'google-consent-mode'\n * consentFrom={{ cmp: 'onetrust', group: 'C0004' }}\n * @example // any other CMP with a JS API\n * consentFrom={{ check: () => window.myCmp?.analytics === true, event: 'mycmp:changed' }}\n */\n consentFrom?: ConsentSource;\n /**\n * Behavior before consent is granted. Pass `'statistical_winner'` to serve the\n * best-performing variant via `GET /v1/winner` with zero tracking while the\n * consent banner is showing. Requires `consent: false`.\n * @see SentientConfig.preConsentBehavior\n */\n preConsentBehavior?: 'statistical_winner' | 'control';\n /**\n * Honor the browser's Do Not Track signal. Defaults to `true`: when DNT is\n * enabled the SDK sets no cookies and sends no tracking data (overriding\n * `consent: true`). Set `false` to make your own consent gate authoritative.\n * @see SentientConfig.respectDoNotTrack\n */\n respectDoNotTrack?: boolean;\n /**\n * Called once per component the first time a variant is resolved for that\n * component in this session. Use to forward assignments to your own analytics\n * (Mixpanel, PostHog, Segment, etc.) without having to wrap `useAssignment`.\n */\n onAssignment?: (componentId: string, variantId: string) => void;\n /**\n * SSR-preloaded section order from `loadAdaptiveDecision()`.\n * Pass the `layoutOrder` field from `DecideResult`. When set,\n * `useLayoutOrder()` returns this on first render so there is no layout shift.\n */\n initialLayoutOrder?: string[] | null;\n /**\n * The section ids the app declares as reorderable, independent of any\n * decision. `AdaptiveRoot` forwards its `sections` prop here.\n *\n * Devtools reads this to offer layout previewing: a page whose decision was\n * gated by consent, or timed out, has no `initialLayoutOrder`, and registering\n * only that left the layout panel empty in exactly the situation you reach for\n * it — running the site locally before accepting a cookie banner.\n */\n declaredSections?: string[];\n /**\n * What each section IS, keyed by its `data-sentient-id`:\n * `{ about: 'trust', contact: 'cta' }`. Optional — sections are classified\n * from their content — but the classifier reads a section with little\n * signal-bearing copy (an \"About us\" band, a contact form) as `generic`, and\n * a `generic` section is ordered the same for every persona. Declare the\n * ones it gets wrong; any section with a `data-sentient-id` can appear here,\n * reorderable or not. Wins over legacy `data-sentient-type` markup.\n */\n sectionTypes?: Readonly<Partial<Record<string, SemanticType>>>;\n /**\n * SSR-preloaded slot results from `loadAdaptiveDecision()` (the `slots`\n * field of its result). Guarantees `useAdaptiveTokens`/`AdaptiveGroup`\n * render the decided arm in server HTML — zero flicker, hydration-safe.\n */\n initialSlots?: Record<string, SlotResult>;\n /**\n * SSR-preloaded registry slot config from `loadAdaptiveDecision()` (the\n * `slotConfig` field of its result, registry mode). Lets `AdaptiveSlot`\n * render server-authored content/blocks in server HTML — zero flicker.\n */\n initialSlotConfig?: Record<string, SlotConfigEntry>;\n /** SSR-preloaded site palette (`palette` field of `loadAdaptiveDecision()`'s\n * registry-mode result) for block rendering. */\n initialPalette?: SitePalette;\n /** SSR-preloaded site styles (`vocabulary` field of `loadAdaptiveDecision()`'s\n * registry-mode result) that served Redesign arms borrow. */\n initialVocabulary?: StyleVocabulary;\n /**\n * Persona decided during SSR (`persona` + `confidence` fields of\n * `loadAdaptiveDecision()`'s result). Adopted by the core client;\n * rendered into html attributes only by `SentientPersonaScript`.\n */\n initialPersona?: { persona: string; confidence: number };\n /**\n * Base URL of the Sentient API (no trailing slash). Read by the devtools\n * panel for /v1/explain and by future client helpers. Defaults to the\n * hosted API.\n */\n apiBaseUrl?: string;\n /**\n * Session ID generated during SSR (the `sessionId` field returned by\n * `loadAdaptiveAssignments` / `loadAdaptiveDecision`). When provided and no\n * existing session cookie or localStorage entry is found, the client adopts\n * this ID so events and goals are attributed to the same session the server\n * used for variant assignment.\n */\n ssrSessionId?: string;\n /**\n * Where the visitor cookie lives. By default it is shared on the site's\n * registrable domain (auto-detected), so `example.com` and\n * `app.example.com` running the same project key count one visitor and one\n * journey. `false` keeps it on this host only; a string names the domain.\n */\n cookieDomain?: string | false;\n /**\n * The signed-in user: identifies the visitor once per client. Pass the\n * server-signed `userHash` (`signUserId` from `@sentientui/core/server`,\n * or let `<AdaptiveRoot userId>` do it) to make it a VERIFIED identify —\n * required for server goals by `userId` once a project signs its identifies.\n */\n identity?: { userId: string; userHash?: string; email?: string };\n /**\n * Your own team or a test site: the visit is served versions as usual (QA\n * keeps working) but left out of every report and out of learning. Compute\n * it in your code — `internal={user.email.endsWith('@example.com')}` — and\n * only `internal: true` is sent, never the email. Read once when the client\n * starts (like `persona`): a value that arrives later (auth still loading)\n * is ignored, so decide it before the provider mounts or remount it.\n * Sticky server-side. Needs a SentientUI API that knows internal traffic;\n * older ones ignore it.\n */\n internal?: boolean;\n /**\n * ISO 3166-1 alpha-2 country code. Pass the value of the `CF-IPCountry`\n * header from your Next.js server component to populate country on landing\n * sessions without client-side geo lookup.\n */\n country?: 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 → Matrix → Audiences); unrecognized values are\n * ignored server-side and surfaced in the dashboard. Served at full\n * confidence, overriding the inferred persona. Stable for the session —\n * like `country`, changing it after init is ignored (decisions are locked\n * per visit); remount the provider to apply a new value.\n */\n persona?: string;\n /**\n * Opt-in theme hook: put the visitor's funnel stage on\n * `<html data-sentient-stage>` so CSS can make deterministic per-stage\n * changes (hide the first-order discount from people who have bought).\n * Projects with stages turned on only; never for the control group.\n * `true` exposes `new`, `browsing`, `carted` and `returning` (has bought\n * here); `'detailed'` splits `returning` into `customer` and `lapsed`. Any\n * script on the page can read it, which is why detail is a second opt-in.\n * How the visitor arrived (ads, emails) is never written to the page.\n * `AdaptiveRoot` also writes it in the server HTML.\n */\n stageAttributes?: StageAttributes;\n /**\n * Keyless local mode. 'auto' (default) simulates decisions on-device in\n * development builds when no valid API key is configured; `true` forces the\n * local engine; `false` restores the silent keyless no-op.\n * @see SentientConfig.localMode\n */\n localMode?: 'auto' | boolean;\n /**\n * DOM graph scanning + page-structure sync. ON by default: the provider\n * dynamically loads `@sentientui/core/graph` and uses its graph-capable\n * `init()` for the single client, so the SDK scans your page structure,\n * auto-detects semantic sections, and syncs them to power personas and the\n * dashboard graph page. Pass `false` to keep the lean bundle only.\n */\n enableGraph?: boolean;\n /**\n * Include captured heading / DOM text in graph sync payloads. OFF by default.\n * Only applies when graph scanning is enabled (`enableGraph` not `false`).\n */\n captureDomText?: boolean;\n /**\n * Behavioral engagement capture (per-section dwell/scroll + semantic section\n * registration) powering personas. ON by default — pass `false` to disable.\n * Never runs for a DNT/GPC or consent-gated visitor (no client → no capture).\n */\n engagement?: boolean;\n /**\n * CSP nonce for the <style> the SDK injects (the adaptation reveal), so a\n * nonce-based CSP needs no `style-src 'unsafe-inline'`. `AdaptiveRoot`\n * forwards its own `nonce`. Defaults to the nonce of a script on the page.\n */\n nonce?: string;\n children: ReactNode;\n};\n\n/** Once per page load — StrictMode and route-level providers remount. */\nlet warnedNoConsentGate = false;\n\n/** Projects whose consent source has answered (non-null) in this page load.\n * Module-level, not per mount: a remounted provider (route-level placement,\n * a cached RSC payload on Back) or a changed consentFrom started over and fell\n * back to AdaptiveRoot's stale request-time consent={true} (review R11 #1). */\nconst answeredThisPage = new Set<string>();\n\n/**\n * Watches a {@link AdaptiveProviderProps.consentFrom} source and reports whether\n * it currently grants consent. Returns false (and subscribes to nothing) when no\n * source is configured.\n */\nfunction useConsentSource(\n source: AdaptiveProviderProps['consentFrom'],\n apiKey: string,\n onRefused: () => void,\n): { granted: boolean | null; refused: boolean } {\n const onRefusedRef = useRef(onRefused);\n onRefusedRef.current = onRefused;\n const [granted, setGranted] = useState<boolean | null>(null);\n const [refused, setRefused] = useState(false);\n\n // The source is usually an inline object literal, so its identity changes\n // every render. Read it through a ref and key the effect on a stable string,\n // otherwise the listener would be torn down and re-added on every render.\n const sourceRef = useRef(source);\n sourceRef.current = source;\n const key =\n source === undefined\n ? ''\n : typeof source === 'string'\n ? source\n : JSON.stringify({\n ...source,\n check: typeof (source as { check?: unknown }).check,\n refused: typeof (source as { refused?: unknown }).refused,\n });\n\n useEffect(() => {\n const s = sourceRef.current;\n if (s === undefined || typeof window === 'undefined') return;\n // Symmetric: every signal re-reads the source both ways, so a CMP\n // \"withdrawn\" decision later in the visit re-gates the SDK (the old shape\n // latched true and stopped listening). Payloads are never trusted.\n // The watcher is its own core entry, loaded only by pages that configure\n // a consent source; until it arrives the state stays \"unknown\" (gated,\n // or the server's read).\n let stop: (() => void) | undefined;\n let cancelled = false;\n void import('@sentientui/core/consent').then(({ consentWatcher, forgetVisitor }) => {\n if (cancelled) return;\n const watcher = consentWatcher(\n // Both predicates through the ref: an inline `refused` closing over\n // state was frozen at the first render, so a later \"no\" never\n // forgot the visitor (review R7 #4).\n typeof s === 'object' && s.cmp === undefined && s.check\n ? {\n ...s,\n check: () => (sourceRef.current as { check: () => boolean }).check(),\n ...(s.refused ? { refused: () => (sourceRef.current as { refused?: () => boolean }).refused?.() === true } : {}),\n }\n : s,\n );\n // A recorded refusal forgets the visitor even when no tracking client\n // exists to destroy — a \"no\" given where the SDK wasn't watching (a CMP\n // settings page, checkout) otherwise left the 365-day id and the\n // decision snapshot in place for good (audit N2). refused() is false for\n // \"not loaded yet\" and \"banner up\", so a consented visitor is never\n // wiped by a slow CMP.\n let wasRefused = false;\n // Once the platform has answered in this page view, \"no answer\" again\n // (a custom banner's reset deleting its cookie) reads false — a pause.\n // As null it fell back to the server's request-time read, so a visitor\n // who withdrew under AdaptiveRoot's consent={true} was tracked again\n // under a fresh identity (grader N10-1). See answeredThisPage.\n const update = (): void => {\n // Never while the source reads granted (a custom `refused` that\n // disagrees with its own `check`): that would wipe a tracked visitor.\n const r = watcher.refused() && watcher.read() !== true;\n // On a change only: Consent Mode calls back on every dataLayer push.\n if (r && !wasRefused) {\n forgetVisitor(apiKey);\n onRefusedRef.current();\n }\n wasRefused = r;\n setRefused(r);\n const g = watcher.read();\n if (g !== null) answeredThisPage.add(apiKey);\n setGranted(g ?? (answeredThisPage.has(apiKey) ? false : null));\n };\n update();\n stop = watcher.subscribe(update);\n });\n return () => {\n cancelled = true;\n stop?.();\n };\n }, [key, apiKey]);\n\n return { granted, refused };\n}\n\n/**\n * Initialises the Sentient core SDK in a useEffect (SSR-safe) and exposes the\n * client via React context. Re-initialises when consent changes.\n */\nexport function AdaptiveProvider(props: AdaptiveProviderProps): JSX.Element {\n const [client, setClient] = useState<SentientClient | null>(null);\n // Derived once per mount: identical to what core init() computes, so cache\n // reads (context segment) and cache writes (core segment) always agree.\n const [sessionSegment] = useState(() => props.sessionSegment ?? deriveDefaultSegment());\n // Devtools preview: when on, expose an event-suppressing client so previewing\n // variants/personas writes nothing. Off by default (inert in production).\n const [previewOn, setPreviewOn] = useState(getPreviewMode());\n useEffect(() => subscribePreview(() => setPreviewOn(getPreviewMode())), []);\n // On-site cell preview (dashboard \"Preview on your site\" link). No-ops\n // without both URL params; forces the previewed arm through the override\n // channel AdaptiveSlot already renders exposure-free.\n useEffect(() => {\n maybeStartCellPreview(props.apiBaseUrl);\n // Any editor-token session also samples the site's styles for Redesign\n // (React sites never load the snippet editor that does it elsewhere).\n maybeCaptureStyles(props.apiBaseUrl);\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n // When a consentFrom source is configured it owns the gate: start closed and\n // open only once the source grants. An explicit consent={true} (e.g. resolved\n // from the cookie on the server by AdaptiveRoot) short-circuits it, so a\n // returning visitor isn't gated waiting for a client-side re-read.\n // The browser source decides as soon as it knows (true OR false). Until then\n // (null: CMP not loaded yet) the server's read stands. The old\n // `props.consent === true || sourceGranted` let a server-side grant override\n // a mid-visit revocation for the rest of the page view.\n // Declared ahead of useConsentSource (which must call it): the refs it\n // clears are created further down.\n const dropHeldRef = useRef<() => void>(() => undefined);\n const source = useConsentSource(props.consentFrom, props.apiKey, () => dropHeldRef.current());\n // The server's read stands only until the browser source has answered in\n // this page load — also across remounts, before the watcher reloads.\n const consent = props.consentFrom\n ? (source.granted ?? (answeredThisPage.has(props.apiKey) ? false : props.consent === true))\n : props.consent;\n // Whether a `false` means \"forget the visitor\" or only \"stop for now\". An\n // explicit consent={false} is the site's own revocation; from a platform,\n // only a recorded refusal forgets — a consented visitor reopening the TCF\n // banner reads false too and was fully forgotten (review M2).\n const forgetOnFalse = props.consentFrom ? source.refused : true;\n const forgetRef = useRef(forgetOnFalse);\n forgetRef.current = forgetOnFalse;\n\n // The live client mirrored outside React state, so teardown can reach it\n // without a side effect inside a setState updater: React double-invokes\n // updaters in StrictMode dev (they must be pure), so `prev?.destroy()` inside\n // setClient ran twice — and could run during a render that never commits.\n const clientRef = useRef<SentientClient | null>(null);\n // Whether clientRef holds a TRACKING client (created with consent not false).\n // A revocation must forget that client's visitor; a pre-consent proxy has\n // nothing to forget.\n const trackingRef = useRef(false);\n // Conversions a gated client held (goal() before the consent source\n // answered), taken from it on teardown and handed to the next client: React\n // replaces the gated client on a grant instead of upgrading it in place, so\n // they were discarded with it (grader F2).\n const heldRef = useRef<Array<(c: SentientClient) => void>>([]);\n // A recorded refusal drops held conversions — ours and the gated client's —\n // so a later accept in the same page view can't send them (grader F-R1:\n // the effect is keyed on `consent`, which stays false from \"unknown\" to\n // \"refused\", so nothing else runs on the refusal).\n // The gated client is RELEASED, not just drained: draining left it holding,\n // so a goal fired after the refusal was held again and sent on a later\n // accept (grader R8 NEW-2). dispose() on a gated proxy drops its held calls,\n // answers its decides with null and holds nothing more; its read-only\n // winner (preConsentBehavior) keeps serving until the next consent change.\n // Latched too, until the next grant: a gated client created AFTER the\n // refusal — the re-init when a tracked visitor refuses, or the /graph\n // client landing after a boot-time refusal — was never released, so its\n // held goals reached the tracking client on a later accept (grader R9-1).\n const refusedRef = useRef(false);\n dropHeldRef.current = () => {\n heldRef.current = [];\n refusedRef.current = true;\n const c = clientRef.current;\n if (c?.gated) c.dispose();\n else c?.takeHeld?.();\n };\n\n useEffect(() => {\n // Revocation (a tracking client → consent false): forget the visitor —\n // identity cookie, assignment cache, decision snapshot, retry buckets —\n // via the ref, in the effect body (see clientRef above). This used to run\n // only without preConsentBehavior; with 'statistical_winner' the previous\n // run's cleanup merely dispose()d, so a withdrawn visitor kept the 365-day\n // cookie and their snapshot re-personalized the next page load.\n // (Only a forgetting revocation destroys; a pause was already disposed by\n // the previous run's cleanup, which keeps the identity.)\n if (forgetRef.current && consent === false) heldRef.current = [];\n if (consent === false && trackingRef.current) {\n if (forgetRef.current) clientRef.current?.destroy();\n clientRef.current = null;\n trackingRef.current = false;\n }\n if (consent === false && !props.preConsentBehavior) {\n if (forgetRef.current) clientRef.current?.destroy();\n clientRef.current = null;\n setClient(null);\n return;\n }\n const tracking = consent !== false;\n if (tracking) refusedRef.current = false;\n // A gated client born after a refusal is released at once (see refusedRef).\n const adopt = (c: SentientClient): void => {\n if (!tracking && refusedRef.current && c.gated) c.dispose();\n };\n\n const config = {\n apiKey: props.apiKey,\n context: props.context,\n debug: props.debug,\n initialAssignments: props.initialAssignments,\n initialUnified: props.initialUnified,\n sessionSegment,\n consent,\n preConsentBehavior: props.preConsentBehavior,\n respectDoNotTrack: props.respectDoNotTrack,\n ssrSessionId: props.ssrSessionId,\n cookieDomain: props.cookieDomain,\n country: props.country,\n persona: props.persona,\n internal: props.internal,\n stageAttributes: props.stageAttributes,\n localMode: props.localMode,\n initialSlots: props.initialSlots,\n initialSlotConfig: props.initialSlotConfig,\n initialPalette: props.initialPalette,\n initialVocabulary: props.initialVocabulary,\n initialPersona: props.initialPersona,\n ingestUrl: props.apiBaseUrl ? `${props.apiBaseUrl.replace(/\\/$/, '')}/events` : undefined,\n nonce: props.nonce,\n // Declare which SDK (and which release) is driving this client, so the\n // dashboard can tell the project when it is running an old one. A React\n // install cannot self-update the way the snippet's CDN tag does, so this\n // nudge is the only update path there is.\n ...(SDK_IDENT ? { sdk: SDK_IDENT } : {}),\n };\n\n // Track the client created by this effect run so cleanup destroys exactly\n // the right one, and so a late-resolving dynamic import can bail if the\n // effect was already torn down (unmount / consent change).\n let cancelled = false;\n let created: SentientClient | null = null;\n let stopEngagement: (() => void) | null = null;\n\n // Engagement capture (default ON): per-section dwell/scroll + semantic\n // section registration, lazy-loaded so the lean bundle stays lean. Only for\n // a TRACKING client: with preConsentBehavior a gated visitor still gets a\n // (pre-consent proxy) client, and capture used to start on it — POSTing\n // /v1/section-map and attaching collectors while consent was false. The\n // capture module re-checks DNT internally.\n // Replay held conversions: sent by a tracking client, re-held by a gated one.\n // Each in its own task, like core's replay: one task would put them in\n // one latch window and collapse repeat conversions into one.\n const handOff = (c: SentientClient): void => {\n for (const call of heldRef.current.splice(0)) {\n setTimeout(() => {\n // Replaced before this task ran (unmount, another consent flip):\n // back into the stash for the next client, never into a disposed\n // one's dead queue (review R7 #6).\n if (clientRef.current !== c) {\n // …unless a refusal landed in between: it dropped the stash,\n // and pushing back revived the goal for a later accept\n // (review R10 #2).\n if (!refusedRef.current) heldRef.current.push(call);\n return;\n }\n try {\n call(c);\n } catch {\n /* one bad call never blocks the rest */\n }\n }, 0);\n }\n };\n\n const startEngagement = (c: SentientClient): void => {\n if (props.engagement === false || !tracking) return;\n void import('@sentientui/core/engagement').then(({ startEngagementCapture }) => {\n if (cancelled) return;\n stopEngagement = startEngagementCapture(c, {\n apiKey: props.apiKey,\n sectionTypes: props.sectionTypes,\n apiBase: props.apiBaseUrl ? props.apiBaseUrl.replace(/\\/$/, '') : undefined,\n });\n });\n };\n\n if (props.enableGraph !== false) {\n // Graph scanning is the default — load the graph entry dynamically so the\n // scanner never lands in the lean bundle. The provider still creates ONE\n // client (graph-capable). Pass enableGraph={false} for the lean client.\n void import('@sentientui/core/graph').then(({ init: initGraph }) => {\n if (cancelled) return;\n created = initGraph({\n ...config,\n graph: true,\n captureDomText: props.captureDomText === true,\n sectionTypes: props.sectionTypes,\n });\n adopt(created);\n clientRef.current = created;\n trackingRef.current = tracking;\n handOff(created);\n setClient(created);\n startEngagement(created);\n });\n } else {\n created = init(config);\n adopt(created);\n clientRef.current = created;\n trackingRef.current = tracking;\n handOff(created);\n setClient(created);\n startEngagement(created);\n }\n\n return () => {\n cancelled = true;\n stopEngagement?.();\n heldRef.current = heldRef.current.concat(created?.takeHeld?.() ?? []);\n // dispose, not destroy: effect cleanup runs on unmount, StrictMode's\n // dev double-invoke, and consent re-init — the visitor identity must\n // survive all of those. Full destroy() happens only on the explicit\n // consent-revocation branch above.\n created?.dispose();\n };\n // Re-init when consent changes — whether that came from the prop or from a\n // consentFrom source granting. Other props (incl. enableGraph) are\n // intentionally stable for a session.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [consent]);\n\n // Poll /v1/weights every 60 s so long-lived sessions see updated bandit weights\n // without a page reload. useAssignment subscribers react via weights-store.\n useEffect(() => {\n if (!client) return;\n let cancelled = false;\n const poll = async (): Promise<void> => {\n if (cancelled) return;\n let entries;\n try {\n entries = await client.fetchWeights();\n } catch {\n // Network/transient error: skip this cycle and retry on the next\n // interval. Swallowed deliberately so a failed poll never surfaces as\n // an unhandled rejection.\n return;\n }\n if (cancelled) return;\n for (const entry of entries) {\n const weights: ComponentWeights = {\n componentId: entry.componentId,\n updatedAt: entry.updatedAt,\n variants: entry.variants.map((v) => ({\n variantId: v.variantId,\n pulls: v.pulls,\n avgReward: v.avgReward ?? 0,\n })),\n };\n updateWeightsStore(entry.componentId, weights);\n }\n };\n void poll();\n const timerId = setInterval(() => void poll(), 60_000);\n return () => {\n cancelled = true;\n clearInterval(timerId);\n };\n }, [client]);\n\n const ssrFallback = props.ssrFallback ?? 'first';\n // Strip a trailing slash so consumers (devtools /explain, useAdaptiveApiBaseUrl)\n // build URLs the same way the core client does (it strips before appending\n // /events and /section-map) — otherwise an apiBaseUrl ending in \"/\" yields a\n // double slash like \".../v1//explain\".\n const apiBaseUrl = (props.apiBaseUrl ?? DEFAULT_API_BASE_URL).replace(/\\/$/, '');\n\n // The init effect above re-runs only on `props.consent`: apiKey / context /\n // country / apiBaseUrl are captured once and are deliberately stable for the\n // session, so changing them at runtime silently no-ops. That silence is\n // surprising — warn (dev only) when one actually changes value after init, so\n // the no-op is visible. To apply a new value, remount the provider (e.g. a\n // changing React `key`).\n const frozenConfigRef = useRef<{\n apiKey: string;\n // Optional since `context` was deprecated: undefined → undefined compares\n // equal under Object.is, so omitting it never trips the warning below.\n context: SentientConfig['context'] | undefined;\n country: string | undefined;\n persona: string | undefined;\n internal: boolean | undefined;\n apiBaseUrl: string;\n } | null>(null);\n useEffect(() => {\n if (typeof process !== 'undefined' && process.env?.NODE_ENV === 'production') return;\n const current = { apiKey: props.apiKey, context: props.context, country: props.country, persona: props.persona, internal: props.internal, apiBaseUrl };\n const prev = frozenConfigRef.current;\n frozenConfigRef.current = current;\n if (prev === null) return; // first run: capture the frozen baseline, nothing to compare\n // `internal` too: `internal={user?.isStaff}` with auth still loading\n // starts the client unmarked, and the later `true` silently did nothing.\n for (const key of ['apiKey', 'context', 'country', 'persona', 'internal', 'apiBaseUrl'] as const) {\n if (!Object.is(prev[key], current[key])) {\n console.warn(\n `[sentient] AdaptiveProvider: \\`${key}\\` changed after initialisation, but the SDK client is stable for the session and only re-inits on \\`consent\\` — the new value is ignored. Remount the provider (e.g. via a changing \\`key\\` prop) to apply it.`,\n );\n }\n }\n }, [props.apiKey, props.context, props.country, props.persona, props.internal, apiBaseUrl]);\n\n // Publish devtools config through window: the /devtools entry is a separate\n // bundle and cannot read this provider's context instance. Dev-only.\n useEffect(() => {\n if (typeof process !== 'undefined' && process.env?.NODE_ENV === 'production') return;\n publishDevtoolsConfig({\n apiKey: props.apiKey,\n apiBaseUrl,\n isLocal: client?.isLocal === true,\n });\n }, [client, props.apiKey, apiBaseUrl]);\n\n // identify() is an upsert: once per client and user, never per render. A\n // consent grant makes a new client, which identifies again — the gated one\n // dropped it.\n const identityUser = props.identity?.userId;\n const identityHash = props.identity?.userHash;\n // Hashed by core before it leaves the page; only the hash + domain are sent.\n const identityEmail = props.identity?.email;\n useEffect(() => {\n if (client && identityUser) client.identify(identityUser, { userHash: identityHash, email: identityEmail });\n }, [client, identityUser, identityHash, identityEmail]);\n\n // Sections registry for devtools /v1/explain + local simulation. The decided\n // order wins when there is one (it is what the page is actually rendering);\n // the declared list is the fallback so the layout panel still knows what is\n // reorderable when no decision arrived.\n useEffect(() => {\n const decided = props.initialLayoutOrder;\n if (decided && decided.length > 0) {\n registerSections(decided);\n return;\n }\n if (props.declaredSections && props.declaredSections.length > 0) {\n registerSections(props.declaredSections);\n }\n }, [props.initialLayoutOrder, props.declaredSections]);\n\n // Dev-only: tracking is on by default, so an install that never wires a\n // consent gate tracks EU visitors from the first paint without anyone\n // having decided that (audit S6). Say so once, with the one-line fix.\n useEffect(() => {\n if (!isDevBuild() || props.consent !== undefined || props.consentFrom !== undefined) return;\n if (warnedNoConsentGate) return;\n warnedNoConsentGate = true;\n console.warn(\n '[SentientUI] No consent gate: every visitor is tracked from first paint. Pass consentFrom=\"<your CMP>\" ' +\n '(or consent={true} to silence). https://sentient-ui.com/docs#consent',\n );\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n // Dev-only: a declared section with no `data-sentient-id=\"<id>\"` element is\n // invisible to the DOM graph scanner, so the server never learns its semantic\n // type and every persona gets the identity order — the layout looks \"on\" but\n // can never personalize (found on a real site 2026-09-05: nine declared\n // sections, zero graph rows, one bandit arm). Warn once with the exact fix\n // rather than leaving the integration silently inert.\n useEffect(() => {\n if (!isDevBuild()) return;\n const declared = props.declaredSections;\n if (!declared || declared.length === 0 || typeof document === 'undefined') return;\n const present = new Set(\n Array.from(document.querySelectorAll('[data-sentient-id]'), (el) =>\n el.getAttribute('data-sentient-id'),\n ),\n );\n const missing = declared.filter((id) => !present.has(id));\n if (missing.length > 0) {\n console.warn(\n `[SentientUI] Declared section${missing.length > 1 ? 's' : ''} ${missing\n .map((id) => `\"${id}\"`)\n .join(', ')} ${missing.length > 1 ? 'have' : 'has'} no matching ` +\n 'data-sentient-id element, so the layout engine cannot learn what ' +\n 'they are and will serve the same order to every persona. Add ' +\n 'data-sentient-id=\"<sectionId>\" to each section\\'s element.',\n );\n }\n }, [props.declaredSections]);\n\n // The client exposed to consumers — wrapped to suppress events while previewing.\n const exposedClient = useMemo(\n () => (client && previewOn ? createPreviewClient(client) : client),\n [client, previewOn],\n );\n\n // Memoized so unrelated parent re-renders don't cascade through every\n // useSentient / useAssignment consumer via a fresh context object.\n const value = useMemo<AdaptiveContextValue>(\n () => ({\n client: exposedClient,\n apiKey: props.apiKey,\n initialAssignments: props.initialAssignments ?? {},\n initialUnified: props.initialUnified ?? NO_UNIFIED,\n sessionSegment,\n ssrFallback,\n onAssignment: props.onAssignment,\n initialLayoutOrder: props.initialLayoutOrder ?? null,\n initialSlots: props.initialSlots ?? {},\n initialSlotConfig: props.initialSlotConfig ?? {},\n initialPalette: props.initialPalette ?? null,\n initialVocabulary: props.initialVocabulary ?? null,\n initialPersona: props.initialPersona ?? null,\n apiBaseUrl,\n debug: props.debug ?? false,\n }),\n [\n exposedClient,\n props.apiKey,\n props.initialAssignments,\n props.initialUnified,\n sessionSegment,\n ssrFallback,\n props.onAssignment,\n props.initialLayoutOrder,\n props.initialSlots,\n props.initialSlotConfig,\n props.initialPalette,\n props.initialVocabulary,\n props.initialPersona,\n apiBaseUrl,\n props.debug,\n ],\n );\n\n return (\n <AdaptiveContext.Provider value={value}>\n {props.children}\n </AdaptiveContext.Provider>\n );\n}\n\n/**\n * Returns the SentientClient, or null until the provider has finished\n * initialising on the client.\n */\nexport function useSentient(): SentientClient | null {\n return useContext(AdaptiveContext).client;\n}\n\n/** Internal: publishable API key carried alongside the client. */\nexport function useAdaptiveApiKey(): string {\n return useContext(AdaptiveContext).apiKey;\n}\n\n/** Internal: SSR-preloaded assignments for hydration-safe first render. */\nexport function useInitialAssignments(): Record<string, string> {\n return useContext(AdaptiveContext).initialAssignments;\n}\n\nconst NO_UNIFIED: readonly string[] = [];\n\n/** Internal. Ids the SSR preload found moved onto the shared track. */\nexport function useInitialUnified(): readonly string[] {\n return useContext(AdaptiveContext).initialUnified;\n}\n\n/** The `device:source` segment this provider decides and caches under —\n * the SSR value when one was passed, else derived once per mount. */\nexport function useSessionSegment(): string {\n return useContext(AdaptiveContext).sessionSegment;\n}\n\n/** Internal: SSR fallback strategy when a slot has no preloaded assignment. */\nexport function useSsrFallback(): SsrFallback {\n return useContext(AdaptiveContext).ssrFallback;\n}\n\n/** Internal: forwarding hook for consumer analytics integration. */\nexport function useOnAssignment(): ((componentId: string, variantId: string) => void) | undefined {\n return useContext(AdaptiveContext).onAssignment;\n}\n\n/** Internal: debug flag from the provider config, for dev-only diagnostic logging. */\nexport function useDebug(): boolean {\n return useContext(AdaptiveContext).debug;\n}\n\n/**\n * Returns the persona-specific section order from SSR, or null when no\n * sections were declared on AdaptiveRoot or reliability is below threshold.\n * Devtools/testing can force it via `window.__sentient_layout_override`;\n * consumers re-render when the devtools notifies an override change.\n */\nexport function useLayoutOrder(): string[] | null {\n const contextOrder = useContext(AdaptiveContext).initialLayoutOrder;\n const override = useSyncExternalStore(\n subscribeOverridesChanged,\n () =>\n typeof window === 'undefined'\n ? null\n : ((window as unknown as { __sentient_layout_override?: string[] })\n .__sentient_layout_override ?? null),\n () => null,\n );\n return override ?? contextOrder;\n}\n\n/** Internal: SSR-preloaded slot results for hydration-safe first render. */\nexport function useInitialSlots(): Record<string, SlotResult> {\n return useContext(AdaptiveContext).initialSlots;\n}\n\n/** Internal: SSR-decided persona carried alongside the client. */\nexport function useInitialPersona(): { persona: string; confidence: number } | null {\n return useContext(AdaptiveContext).initialPersona;\n}\n\n/** Internal: SSR-preloaded registry slot config for hydration-safe AdaptiveSlot. */\nexport function useInitialSlotConfig(): Record<string, SlotConfigEntry> {\n return useContext(AdaptiveContext).initialSlotConfig;\n}\n\n/** Internal: SSR-preloaded site palette for block rendering. */\nexport function useInitialPalette(): SitePalette | null {\n return useContext(AdaptiveContext).initialPalette;\n}\n\n/** Internal: SSR-preloaded site styles for Redesign rendering. */\nexport function useInitialVocabulary(): StyleVocabulary | null {\n return useContext(AdaptiveContext).initialVocabulary;\n}\n\n/** Internal: configured API base URL (devtools fetches /v1/explain against this, never a relative URL). */\nexport function useAdaptiveApiBaseUrl(): string {\n return useContext(AdaptiveContext).apiBaseUrl;\n}\n","/** Per-component weights store with isolated subscriptions. */\n\nexport type VariantWeight = {\n variantId: string;\n pulls: number;\n avgReward: number;\n};\n\nexport type ComponentWeights = {\n componentId: string;\n variants: VariantWeight[];\n updatedAt: number;\n};\n\ntype Listener = (weights: ComponentWeights) => void;\n\nconst store = new Map<string, ComponentWeights>();\nconst listeners = new Map<string, Set<Listener>>();\n\n/**\n * Subscribes a listener to a single component. Returns an unsubscribe function.\n * Updates to other components never trigger this listener.\n */\nexport function subscribe(componentId: string, cb: Listener): () => void {\n let set = listeners.get(componentId);\n if (!set) {\n set = new Set();\n listeners.set(componentId, set);\n }\n set.add(cb);\n return () => {\n set!.delete(cb);\n if (set!.size === 0) listeners.delete(componentId);\n };\n}\n\n/**\n * Replaces the weights for a component and notifies only that component's\n * subscribers.\n */\nexport function update(componentId: string, weights: ComponentWeights): void {\n store.set(componentId, weights);\n const set = listeners.get(componentId);\n if (!set) return;\n for (const cb of set) {\n try {\n cb(weights);\n } catch {\n /* never throw to other listeners */\n }\n }\n}\n\n/**\n * Returns the latest known weights for a component, or null if none seen.\n */\nexport function getWeights(componentId: string): ComponentWeights | null {\n return store.get(componentId) ?? null;\n}\n\n/** Test-only: wipe the entire store. */\nexport function _resetWeightsStore(): void {\n store.clear();\n listeners.clear();\n}\n","import type { SentientClient } from '@sentientui/core';\n\ntype PreviewState = { on: boolean; listeners: Set<() => void> };\nconst ssrFallback: PreviewState = { on: false, listeners: new Set() };\n\n// Window-backed: the /devtools entry (a separate bundle) toggles preview mode\n// and the provider (main bundle) must observe it.\nfunction state(): PreviewState {\n if (typeof window === 'undefined') return ssrFallback;\n const w = window as unknown as { __sentient_preview?: PreviewState };\n if (!w.__sentient_preview) w.__sentient_preview = { on: false, listeners: new Set() };\n return w.__sentient_preview;\n}\n\nexport function setPreviewMode(on: boolean): void {\n const s = state();\n if (s.on === on) return;\n s.on = on;\n for (const fn of s.listeners) fn();\n}\n\nexport function getPreviewMode(): boolean {\n return state().on;\n}\n\nexport function subscribePreview(fn: () => void): () => void {\n const listeners = state().listeners;\n listeners.add(fn);\n return () => {\n listeners.delete(fn);\n };\n}\n\n/**\n * Wraps a client so it writes nothing: reads pass through, all emitters no-op.\n * Used while previewing variants/personas so no `variant_assigned`, goal, or\n * session events are sent.\n */\nexport function createPreviewClient(inner: SentientClient): SentientClient {\n return {\n isLocal: inner.isLocal,\n track: () => undefined,\n goal: () => undefined,\n componentGoal: () => undefined,\n identify: () => undefined,\n fetchWeights: () => Promise.resolve([]),\n getAssignment: (componentId, segment) => inner.getAssignment(componentId, segment),\n isUnified: (componentId) => inner.isUnified?.(componentId) ?? false,\n assign: (componentId, variantIds, agentData, agentDataByVariant, opts) =>\n inner.assign(componentId, variantIds, agentData, agentDataByVariant, opts),\n // Reads pass through; decide is a write (slot decisions persist server-side)\n // so preview mode never issues it.\n decide: () => Promise.resolve(null),\n getSlotResult: (slotId) => inner.getSlotResult(slotId),\n getSlotConfig: (slotId) => inner.getSlotConfig(slotId),\n getSitePalette: () => inner.getSitePalette(),\n reportSlots: (ids) => inner.reportSlots(ids),\n getPersona: () => inner.getPersona(),\n getGraph: () => inner.getGraph(),\n flush: () => inner.flush(),\n dispose: () => inner.dispose(),\n destroy: () => inner.destroy(),\n };\n}\n","/**\n * Cross-bundle re-render bus for devtools overrides. The main entry and the\n * /devtools entry are separate bundles, so state and notifications go through\n * window (a version counter + a DOM event) — never module-local state.\n */\nconst EVENT = 'sentient:overrides-changed';\n\ntype VersionWindow = Window & { __sentient_overrides_version?: number };\n\nexport function getOverridesVersion(): number {\n if (typeof window === 'undefined') return 0;\n return (window as VersionWindow).__sentient_overrides_version ?? 0;\n}\n\nexport function notifyOverridesChanged(): void {\n if (typeof window === 'undefined') return;\n const w = window as VersionWindow;\n w.__sentient_overrides_version = (w.__sentient_overrides_version ?? 0) + 1;\n window.dispatchEvent(new Event(EVENT));\n}\n\nexport function subscribeOverridesChanged(fn: () => void): () => void {\n if (typeof window === 'undefined') return () => undefined;\n window.addEventListener(EVENT, fn);\n return () => window.removeEventListener(EVENT, fn);\n}\n","/** Provider → devtools config handoff. Window-backed: the /devtools entry is a\n * separate bundle and cannot share the provider's React context instance. */\nexport type DevtoolsConfig = {\n apiKey: string;\n apiBaseUrl: string;\n isLocal: boolean;\n};\n\ntype ConfigWindow = Window & { __sentient_devtools_config?: DevtoolsConfig };\n\nexport function publishDevtoolsConfig(config: DevtoolsConfig): void {\n if (typeof window === 'undefined') return;\n (window as ConfigWindow).__sentient_devtools_config = config;\n}\n\nexport function readDevtoolsConfig(): DevtoolsConfig | null {\n if (typeof window === 'undefined') return null;\n return (window as ConfigWindow).__sentient_devtools_config ?? null;\n}\n","import type { GoalName } from './goal-names.js';\nimport type { SentientClient } from '@sentientui/core';\n\ndeclare const process: { env?: { NODE_ENV?: string } } | undefined;\n\n/**\n * True unless NODE_ENV is 'production'. Never `process?.env` — optional\n * chaining still throws ReferenceError on an undeclared global, and browsers\n * without a bundler shim (raw esbuild, vanilla script tags) have no `process`.\n */\nexport function isDevBuild(): boolean {\n return typeof process === 'undefined' || process.env?.NODE_ENV !== 'production';\n}\n\n/**\n * The element `<Adaptive>` renders around its content (audit S17: it was\n * always a `<div>`, which is invalid inside a `<ul>`, a `<p>` or a table row\n * and broke `display: grid` children). Intrinsic tags only: the wrapper is\n * what exposure, goals and micro-signals observe, so it must be a real box —\n * `display: contents` would give IntersectionObserver nothing to measure.\n */\nexport type AdaptiveElement =\n | 'div' | 'section' | 'article' | 'aside' | 'header' | 'footer' | 'main' | 'nav'\n | 'span' | 'li' | 'figure' | 'form' | 'label' | 'td' | 'th';\n\nexport type ScrollDepthGoal = { type: 'scroll_depth'; threshold: number; value?: number };\nexport type ClickGoal = { type: 'click'; selector?: string; value?: number };\nexport type FormSubmitGoal = { type: 'form_submit'; value?: number };\nexport type CompositeGoal = { type: 'composite'; all: GoalConfig[] };\nexport type WeightedStep = { goal: GoalConfig; name: GoalName; weight: number };\nexport type WeightedCompositeGoal = { type: 'weighted_composite'; steps: WeightedStep[] };\nexport type GoalConfig = ScrollDepthGoal | ClickGoal | FormSubmitGoal | CompositeGoal | WeightedCompositeGoal;\n\nexport function normalizeGoal(goal: string | GoalConfig): GoalConfig {\n if (typeof goal === 'string') return { type: 'click' };\n return goal;\n}\n\n/** The goalType label events are recorded under (named goal or config type). */\nexport function goalLabelOf(goal: string | GoalConfig): string {\n return typeof goal === 'string' ? goal : goal.type;\n}\n\n/** Static revenue value declared on a simple goal config, if any. Composites\n * carry no value (weights and values don't mix — spec §9.4); dynamic values\n * go through the imperative hooks. */\nexport function goalValueOf(goal: string | GoalConfig): number | undefined {\n if (typeof goal === 'string') return undefined;\n if (goal.type === 'click' || goal.type === 'form_submit' || goal.type === 'scroll_depth') {\n return goal.value;\n }\n return undefined;\n}\n\n/**\n * Collapses scroll-depth goal fires that belong to one observation moment.\n *\n * Two nested Adaptive components sharing one scroll_depth goal label attach two\n * SEPARATE IntersectionObservers (they observe different container nodes), and\n * one scroll can satisfy both. The platform delivers all IntersectionObserver\n * notifications for that moment within one task, but runs a microtask\n * checkpoint between the two callback invocations (\"clean up after running\n * script\" fires whenever the JS stack empties — including between separate UA\n * callback invocations in the same task). Core's action latch closes its\n * non-dispatch window on a microtask precisely so a genuine repeat conversion\n * can never be swallowed by a stale window — which means that checkpoint SPLITS\n * the two observer callbacks into two windows, and the goal double-records.\n *\n * So the collapse for this one double-fire lives here, at the layer that knows\n * both fires are scroll-driven, instead of widening core's window for every\n * caller. The scope is one task — the very clock core abandoned — and that is\n * safe HERE for the reason it was wrong there: core's window could be jumped\n * because ANY code (an already-armed timer on the page) can call goal(), so a\n * genuinely separate conversion could land inside a window that outlived its\n * action. Every caller of this gate is an IntersectionObserver callback; timers\n * never consult it, and a genuinely separate scroll fire arrives in a later\n * rendering-update task. Worst case, an implausibly delayed close collapses two\n * same-label, same-value scroll fires — exactly the collapse this gate exists\n * to perform — never a differently-valued or click-driven conversion.\n */\nconst scrollFiredThisTask = new Set<string>();\nlet scrollGateClearArmed = false;\n\nexport function scrollFireCollapsedThisTask(key: string): boolean {\n if (scrollFiredThisTask.has(key)) return true;\n scrollFiredThisTask.add(key);\n if (!scrollGateClearArmed) {\n scrollGateClearArmed = true;\n const clear = (): void => {\n scrollGateClearArmed = false;\n scrollFiredThisTask.clear();\n };\n // MessageChannel over setTimeout when available: fake-timer test setups\n // freeze setTimeout, which would latch the gate open and swallow every\n // later scroll goal (the same hazard core's old clearNextTask named).\n // Both are macrotasks, so either closes the window after this task.\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 } else {\n setTimeout(clear, 0);\n }\n }\n return false;\n}\n\nfunction isClickableTarget(el: EventTarget | null): boolean {\n if (!(el instanceof Element)) return false;\n const tag = el.tagName.toLowerCase();\n if (tag === 'a' || tag === 'button') return true;\n const role = el.getAttribute('role');\n return role === 'button';\n}\n\nfunction findClickable(start: Element, container: Element, selector?: string): boolean {\n if (selector) {\n try {\n let cursor: Element | null = start;\n while (cursor && cursor !== container) {\n if (cursor.matches(selector)) return true;\n cursor = cursor.parentElement;\n }\n } catch {\n // Invalid CSS selector — treat as no match rather than breaking all click handlers.\n }\n return false;\n }\n let cursor: Element | null = start;\n while (cursor && cursor !== container) {\n if (isClickableTarget(cursor)) return true;\n cursor = cursor.parentElement;\n }\n return false;\n}\n\nexport type GoalHandlers = {\n /** Primary goal completion. Latch-once semantics are the CALLER's job. */\n fireGoal: () => void;\n /** Weighted-composite step completion (already deduped per step here). */\n fireStep: (name: string, weight: number, stepIndex: number) => void;\n};\n\n/**\n * Attaches the goal-detection listeners `<Adaptive>`'s container uses —\n * click / form_submit / scroll_depth, composite (all-of), and\n * weighted_composite (independent steps). Returns the cleanup function.\n * Extracted from adaptive.tsx so useAdaptive / useAdaptiveTokens /\n * AdaptiveGroup wire the SAME machinery instead of duplicating it.\n *\n * `scrollDedupeKey` is the goal LABEL: nested instances sharing a label and\n * satisfied by one scroll moment are one user action, whatever value each\n * instance declares, so scroll-driven fires collapse per label — see\n * scrollFireCollapsedThisTask. (The inner instance's observer is created first\n * and its callback delivered first, so when an inner valued goal nests in a\n * valueless wrapper, the valued fire is the one that wins the gate.)\n * Click/submit fires never consult it: those share a real event dispatch,\n * which core's action latch already collapses on.\n */\nexport function attachGoalListeners(\n node: Element,\n goal: GoalConfig,\n handlers: GoalHandlers,\n scrollDedupeKey?: string,\n): () => void {\n // --- Weighted composite: each step fires independently as it completes ---\n if (goal.type === 'weighted_composite') {\n const firedSteps = new Set<number>();\n const wcCleanups: Array<() => void> = [];\n\n goal.steps.forEach(({ goal: sub, name: stepName, weight: stepWeight }, idx) => {\n // viaScroll: a step completed by an IntersectionObserver callback runs the\n // same nested-instance double-fire risk as a plain scroll_depth goal (the\n // microtask checkpoint between two observers' callbacks splits core's\n // window), so it goes through the task gate under its own step identity.\n const fireStep = (viaScroll = false): void => {\n if (firedSteps.has(idx)) return;\n if (\n viaScroll &&\n scrollDedupeKey !== undefined &&\n scrollFireCollapsedThisTask(`step\\0${stepName}\\0${stepWeight}\\0${idx}`)\n ) {\n return;\n }\n firedSteps.add(idx);\n handlers.fireStep(stepName, stepWeight, idx);\n };\n\n if (sub.type === 'click') {\n const onClick = (e: Event): void => {\n const target = e.target;\n if (!(target instanceof Element)) return;\n if (!findClickable(target, node, sub.selector)) return;\n fireStep();\n };\n node.addEventListener('click', onClick);\n wcCleanups.push(() => node.removeEventListener('click', onClick));\n return;\n }\n\n if (sub.type === 'form_submit') {\n const onSubmit = (e: Event): void => {\n if (!(e.target instanceof HTMLFormElement)) return;\n if (!node.contains(e.target)) return;\n fireStep();\n };\n node.addEventListener('submit', onSubmit);\n wcCleanups.push(() => node.removeEventListener('submit', onSubmit));\n return;\n }\n\n if (sub.type === 'scroll_depth') {\n const threshold = Math.max(0, Math.min(1, sub.threshold));\n const io = new IntersectionObserver(\n (entries) => {\n for (const entry of entries) {\n if (entry.intersectionRatio >= threshold) {\n fireStep(true);\n io.disconnect();\n break;\n }\n }\n },\n { threshold: [threshold] },\n );\n io.observe(node);\n wcCleanups.push(() => io.disconnect());\n }\n });\n\n return () => {\n for (const c of wcCleanups) c();\n };\n }\n // --- End weighted composite ---\n\n const subgoals: GoalConfig[] = goal.type === 'composite' ? goal.all : [goal];\n const remaining = new Set<number>(subgoals.map((_, i) => i));\n // The scroll gate is consulted only at the moment a goal actually FIRES from\n // a scroll callback — never when a scroll merely completes one subgoal of a\n // still-open composite. Consulting it early would claim the key for an\n // instance that fires nothing, suppressing the nested instance that would\n // have fired, and the conversion would be lost outright.\n const fireViaScroll = (): void => {\n if (scrollDedupeKey !== undefined && scrollFireCollapsedThisTask(scrollDedupeKey)) return;\n handlers.fireGoal();\n };\n const checkComposite = (idx: number, viaScroll = false): void => {\n remaining.delete(idx);\n if (remaining.size !== 0) return;\n if (viaScroll) fireViaScroll();\n else handlers.fireGoal();\n };\n\n const cleanups: Array<() => void> = [];\n\n subgoals.forEach((sub, idx) => {\n if (sub.type === 'click') {\n const onClick = (e: Event): void => {\n const target = e.target;\n if (!(target instanceof Element)) return;\n if (!findClickable(target, node, sub.selector)) return;\n if (goal.type === 'composite') checkComposite(idx);\n else handlers.fireGoal();\n };\n node.addEventListener('click', onClick);\n cleanups.push(() => node.removeEventListener('click', onClick));\n return;\n }\n\n if (sub.type === 'form_submit') {\n const onSubmit = (e: Event): void => {\n if (!(e.target instanceof HTMLFormElement)) return;\n if (!node.contains(e.target)) return;\n if (goal.type === 'composite') checkComposite(idx);\n else handlers.fireGoal();\n };\n node.addEventListener('submit', onSubmit);\n cleanups.push(() => node.removeEventListener('submit', onSubmit));\n return;\n }\n\n if (sub.type === 'scroll_depth') {\n const threshold = Math.max(0, Math.min(1, sub.threshold));\n const io = new IntersectionObserver(\n (entries) => {\n for (const entry of entries) {\n if (entry.intersectionRatio >= threshold) {\n if (goal.type === 'composite') checkComposite(idx, true);\n else fireViaScroll();\n io.disconnect();\n break;\n }\n }\n },\n { threshold: [threshold] },\n );\n io.observe(node);\n cleanups.push(() => io.disconnect());\n return;\n }\n });\n\n return () => {\n for (const c of cleanups) c();\n };\n}\n\n/**\n * Funnel declaration (spec §7.4): one steps-declaration per funnel per page\n * load; membership is per component and idempotent server-side, so re-sends\n * are harmless but avoided. Only a weighted_composite carries steps — a plain\n * goal declares membership only (the funnel must exist server-side already).\n */\nconst declaredFunnels = new Set<string>();\nconst declaredMemberships = new Set<string>();\n\n/** Test-only: clears the page-load dedup sets. */\nexport function __resetFunnelDeclarations(): void {\n declaredFunnels.clear();\n declaredMemberships.clear();\n}\n\n/**\n * The funnel a weighted composite declares when no `funnel` prop names one.\n * Composites and funnels are one model: without this, a composite on its own\n * was credited the SUM of its steps' weights while the same steps under a\n * `funnel` prop earned the furthest step reached — two rewards for one\n * journey, picked by whether a prop was present. Deterministic from the\n * component id so every page and visit lands on the same funnel; the\n * `-steps` suffix keeps it off ids a human is likely to author (a human funnel\n * with the id would otherwise absorb the component as a member).\n */\nexport function compositeFunnelId(componentId: string): string {\n const slug = componentId.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 100);\n // A lossy slug (\"Hero CTA\" and \"hero_cta\" both → \"hero-cta\") gets a short\n // hash of the raw id so two components never share one funnel.\n if (slug && slug === componentId) return `${slug}-steps`;\n let h = 5381;\n for (let i = 0; i < componentId.length; i++) h = ((h << 5) + h + componentId.charCodeAt(i)) >>> 0;\n return `${slug || 'component'}-${h.toString(36)}-steps`;\n}\n\nconst MAX_FUNNEL_STEPS = 12;\n\n/**\n * A composite's steps as a funnel declaration the server will ACCEPT\n * (funnel-declare parseSteps + validateFunnelSteps). A rejected declaration is\n * silent and leaves the component off the funnel, back on the summed-steps\n * reward — so instead of sending something invalid: weights clamp to [0, 1];\n * a repeated name, a name the server can't take as a goal id (empty, > 128,\n * the reserved `funnel:` prefix) and anything past 12 steps are skipped.\n *\n * Steps are then ORDERED BY WEIGHT, lowest first. A composite's steps were\n * never ordered — each was credited on its own and summed — so the weight is\n * the only statement of which step matters most. Keeping the listed order made\n * a low-value step listed last the funnel's completion (full credit) and the\n * real conversion an intermediate step: the objective, inverted. The sort is\n * stable, so equal weights keep their listed order. Dev builds say when any of\n * this changed what was written.\n */\nexport function compositeFunnelSteps(componentId: string, goal: WeightedCompositeGoal): Array<{ goalId: string; weight: number }> {\n const seen = new Set<string>();\n const steps: Array<{ goalId: string; weight: number }> = [];\n for (const s of goal.steps) {\n const n = s.name;\n if (!n || n.length > 128 || n.startsWith('funnel:') || seen.has(n) || steps.length === MAX_FUNNEL_STEPS) continue;\n seen.add(n);\n steps.push({ goalId: n, weight: Math.min(1, Math.max(0, s.weight || 0)) });\n }\n const ordered = [...steps].sort((a, b) => a.weight - b.weight);\n // Bundle budget: one message for every adjustment, not one per kind.\n if ((steps.length < goal.steps.length || ordered.some((s, i) => s !== steps[i])) && isDevBuild()) {\n console.warn(`[SentientUI] \"${componentId}\": weighted_composite steps adjusted for its funnel (skipped invalid/repeated/over-12 steps, or ordered by weight)`);\n }\n return ordered;\n}\n\n/**\n * Declares the component's funnel: the explicit `funnel` prop, else — for a\n * weighted composite — its own derived funnel (compositeFunnelId). Anything\n * else declares nothing.\n */\nexport function maybeDeclareFunnel(\n client: SentientClient,\n apiKey: string,\n componentId: string,\n explicitFunnelId: string | undefined,\n goal: GoalConfig | null,\n): void {\n const composite = goal?.type === 'weighted_composite' ? goal : null;\n const funnelId = explicitFunnelId ?? (composite ? compositeFunnelId(componentId) : undefined);\n if (!funnelId) return;\n const memberKey = `${funnelId}|${componentId}`;\n if (declaredMemberships.has(memberKey)) return;\n declaredMemberships.add(memberKey);\n // Counted AFTER cleaning: a composite whose steps dedupe to one is a single\n // goal, not a funnel (the server needs 2+, and rejecting it would leave the\n // component on the summed rule).\n const steps = composite && !declaredFunnels.has(funnelId) ? compositeFunnelSteps(componentId, composite) : null;\n const withSteps = steps !== null && steps.length >= 2;\n if (withSteps) declaredFunnels.add(funnelId);\n if (!withSteps && explicitFunnelId === undefined) return; // nothing a derived funnel could join\n client.track({\n projectId: apiKey,\n componentId,\n eventType: 'funnel_declared',\n payload: withSteps ? { funnelId, steps } : { funnelId },\n });\n}\n\n/**\n * Records the `variant_assigned` exposure event.\n */\nexport function trackExposure(\n client: SentientClient,\n apiKey: string,\n componentId: string,\n variantId: string,\n): void {\n client.track({\n projectId: apiKey,\n componentId,\n variantId,\n eventType: 'variant_assigned',\n payload: {},\n });\n}\n","import { isDevBuild } from './adaptive-shared.js';\n\nexport type RegisteredComponent = { id: string; variantIds: string[]; goal?: string };\nexport type RegisteredSlot = {\n id: string;\n arms?: string[];\n dims?: Record<string, readonly string[]>;\n};\n\ntype RegistryState = {\n components: Map<string, RegisteredComponent>;\n slots: Map<string, RegisteredSlot>;\n sections: string[];\n listeners: Set<() => void>;\n /** Bumped on every mutation so `useSyncExternalStore` can read a stable, comparable snapshot. */\n version: number;\n};\n\n// Shared through a window global: the main entry and the /devtools entry are\n// separate bundles, each with its own copy of this module — module-local\n// state would give the devtools an always-empty registry in published apps.\nconst ssrFallback: RegistryState = {\n components: new Map(),\n slots: new Map(),\n sections: [],\n listeners: new Set(),\n version: 0,\n};\n\nfunction state(): RegistryState {\n if (typeof window === 'undefined') return ssrFallback;\n const w = window as unknown as { __sentient_registry?: RegistryState };\n if (!w.__sentient_registry) {\n w.__sentient_registry = {\n components: new Map(),\n slots: new Map(),\n sections: [],\n listeners: new Set(),\n version: 0,\n };\n }\n return w.__sentient_registry;\n}\n\nfunction emit(): void {\n // Bump BEFORE notifying so a useSyncExternalStore consumer re-reading its\n // snapshot inside the notification sees the new value and re-renders.\n state().version += 1;\n for (const fn of state().listeners) fn();\n}\n\n// The registry exists solely to feed the opt-in devtools panel, which is a\n// dev-only surface. In a production build there is no panel reading it, so\n// every register call is dead work plus a `window.__sentient_registry`\n// footprint on the customer's page. Short-circuit to a noop in production —\n// every <Adaptive>/useAdaptive/slot mount calls one of these.\nconst NOOP_UNREGISTER = (): void => undefined;\n\n/** Register (or re-register) a component. Returns an unregister function. */\nexport function registerComponent(c: RegisteredComponent): () => void {\n if (!isDevBuild()) return NOOP_UNREGISTER;\n state().components.set(c.id, c);\n emit();\n return () => {\n state().components.delete(c.id);\n emit();\n };\n}\n\n/** Register (or re-register) a slot declaration. Returns an unregister function. */\nexport function registerSlot(s: RegisteredSlot): () => void {\n if (!isDevBuild()) return NOOP_UNREGISTER;\n state().slots.set(s.id, s);\n emit();\n return () => {\n state().slots.delete(s.id);\n emit();\n };\n}\n\n/** Register the page's declared section ids (from AdaptiveRoot/provider). */\nexport function registerSections(sections: string[]): void {\n if (!isDevBuild()) return;\n state().sections = [...sections];\n emit();\n}\n\nexport function getRegistered(): RegisteredComponent[] {\n return [...state().components.values()];\n}\n\nexport function getRegisteredSlots(): RegisteredSlot[] {\n return [...state().slots.values()];\n}\n\nexport function getRegisteredSections(): string[] {\n return [...state().sections];\n}\n\nexport function subscribeRegistry(fn: () => void): () => void {\n const listeners = state().listeners;\n listeners.add(fn);\n return () => {\n listeners.delete(fn);\n };\n}\n\n/** Monotonic snapshot for `useSyncExternalStore` — changes on every registry mutation. */\nexport function getRegistryVersion(): number {\n return state().version;\n}\n","/**\n * This package's released build version, injected by tsup's `define` from\n * package.json (see tsup.config.ts) so the version inside a published bundle\n * can never drift from the version on npm. Mirrors the snippet's\n * `__SNIPPET_VERSION__`.\n *\n * Why the React SDK reports a version at all: unlike the snippet, it is a\n * build-time npm dependency, so it CANNOT self-update — a customer on an old\n * release stays there until they run an install. Telling them they're behind is\n * the only remedy available, and the dashboard can only tell them if the\n * running bundle says what it is.\n */\ndeclare const __REACT_SDK_VERSION__: string;\n\nexport const version: string =\n typeof __REACT_SDK_VERSION__ !== 'undefined' ? __REACT_SDK_VERSION__ : '0.0.0-dev';\n\n/**\n * The identity handed to core's session upsert, or undefined for a dev build.\n * The '0.0.0-dev' sentinel (unit tests, or any build without tsup's define)\n * passes the server's semver validation and would be persisted as the\n * project's SDK version, leaving the dashboard permanently claiming the\n * project is behind — the same trap the snippet documents as audit M12.\n */\nexport const SDK_IDENT: { name: string; version: string } | undefined =\n version !== '0.0.0-dev' ? { name: 'react', version } : undefined;\n","import type { SlotConfigEntry, StyleVocabulary } from '@sentientui/core';\n\n/**\n * Slot-CONFIG override store — the channel `useSlotConfig` reads (AdaptiveSlot).\n * Separate from `__sentient_slot_overrides` (which forces the slot RESULT — the\n * arm): forcing an arm alone can't test AdaptiveSlot's rendering, because the\n * content/blocks live in the config entry. Window-backed so the /devtools and\n * /testing bundles and the main bundle share one store.\n */\nfunction store(): Record<string, SlotConfigEntry> {\n const w = window as unknown as { __sentient_slot_config_overrides?: Record<string, SlotConfigEntry> };\n if (!w.__sentient_slot_config_overrides) w.__sentient_slot_config_overrides = {};\n return w.__sentient_slot_config_overrides;\n}\n\n/** Force `slotId`'s config entry — read by `useSlotConfig`. */\nexport function setSlotConfigOverride(slotId: string, entry: SlotConfigEntry): void {\n store()[slotId] = entry;\n}\n\n/** Site styles for forced configs (the on-site preview of a redesigned\n * section): the decision that would normally carry them never ran. */\nexport function setVocabularyOverride(v: StyleVocabulary | null): void {\n (window as unknown as { __sentient_vocabulary_override?: StyleVocabulary | null }).__sentient_vocabulary_override = v;\n}\n\nexport function getVocabularyOverride(): StyleVocabulary | null {\n if (typeof window === 'undefined') return null;\n return (window as unknown as { __sentient_vocabulary_override?: StyleVocabulary | null }).__sentient_vocabulary_override ?? null;\n}\n\nexport function clearSlotConfigOverride(slotId: string): void {\n delete store()[slotId];\n}\n\nexport function getSlotConfigOverrides(): Record<string, SlotConfigEntry> {\n return { ...store() };\n}\n","import type { SlotResult } from '@sentientui/core';\n\n/**\n * Slot-override store — the channel `useSlotResult` reads (`useAdaptiveTokens` /\n * `AdaptiveGroup`). Separate from `__sentient_overrides` (variant components):\n * a slot result is a token object (`{ tone: 'urgent' }`) or an arm string\n * (`'social_first'`), never a bare variant id. Window-backed so the /devtools\n * bundle and the main bundle share one store.\n */\nfunction store(): Record<string, SlotResult> {\n const w = window as unknown as { __sentient_slot_overrides?: Record<string, SlotResult> };\n if (!w.__sentient_slot_overrides) w.__sentient_slot_overrides = {};\n return w.__sentient_slot_overrides;\n}\n\n/** Force `slotId` to resolve to `result` — read by `useSlotResult`. */\nexport function setSlotOverride(slotId: string, result: SlotResult): void {\n store()[slotId] = result;\n}\n\nexport function clearSlotOverride(slotId: string): void {\n delete store()[slotId];\n}\n\nexport function getSlotOverrides(): Record<string, SlotResult> {\n return { ...store() };\n}\n","// Credentials the dashboard hands the site (`sentient_preview_token`, the\n// editor's one-time `sentient_editor_code`) ride the URL FRAGMENT, which is\n// never sent over the network — no server/CDN log, no Referer (grades C13, E1).\n//\n// The fragment is also where hash-routed sites keep their route (grade E2).\n// The first version wrote `#sentient_preview_token=…` over the whole hash, so a\n// preview of `/#/pricing` opened the home route instead. The dashboard now\n// APPENDS the param (appendHashParam in apps/dashboard/app/lib/hash-param.ts):\n// '' → #name=v\n// '/pricing' → #/pricing?name=v (routers read it as a query param, so\n// '/p?x=1' → #/p?x=1&name=v the route still matches pre-strip)\n// and this takes it back out, restoring the site's own hash EXACTLY — or\n// removing the '#' altogether when the site had none. Twin of\n// packages/snippet/src/hash-param.ts (the snippet cannot import this package\n// and vice versa); keep the two in step — both suites run the same cases.\nexport function takeHashParam(name: string): string | null {\n let v: string | null = null;\n try {\n const h = location.hash.slice(1);\n const m = RegExp('(^|[?&])' + name + '=([^&]*)').exec(h);\n if (m) {\n // Taken BEFORE the rewrite: an opaque-origin frame may refuse\n // replaceState, and the value is still ours to use. Base64url, so no\n // decoding (the dashboard never percent-encodes it).\n v = m[2]!;\n let after = h.slice(m.index + m[0].length);\n // '?name=v&rest' / 'name=v&rest': the next param inherits the separator.\n if (m[1] != '&' && after[0] == '&') after = m[1] + after.slice(1);\n const rest = h.slice(0, m.index) + after;\n // replaceState, not location.hash=: no hashchange, so a hash router does\n // not re-route mid-boot; history.state kept so its entry key survives.\n history.replaceState(history.state, '', rest ? '#' + rest : location.pathname + location.search);\n }\n } catch {\n /* fail-safe */\n }\n return v;\n}\n","// The operator's editor session on a React site (dashboard \"Preview on your\n// site\", \"Refresh from page\", style capture). The dashboard sends a one-time\n// code in the URL FRAGMENT (#sentient_editor_code=, grade E1) — never the\n// token itself, which as `?sentient_editor=` reached server/CDN logs,\n// analytics page URLs and Referer headers, and can publish. This trades the\n// code for the token (POST /v1/editor/exchange; the API checks the Origin is\n// the project's own) and keeps the token in sessionStorage only.\n//\n// Memoised: cell preview, region refresh and style capture all ask, but the\n// code is single use — a second exchange would be refused and whichever\n// caller lost the race would report an \"expired\" link that was fine.\nimport { takeHashParam } from './hash-param.js';\n\n// Same key as the snippet's cache, so both SDKs agree on \"this tab is in an\n// editor session\" if a page ever carries both.\nconst TOKEN_KEY = '__snt_editor_token';\n\nexport type EditorSession = { token: string; fresh: boolean };\ntype Outcome = EditorSession | { error: number } | null;\n\nlet pending: Promise<Outcome> | null = null;\nlet active = false;\n\n/** Synchronous: did editorSession() find a code or a cached token? Lets a\n * caller refuse to act on a bare URL param (a visitor, not an operator)\n * without waiting for the exchange — the old token-in-query check was sync. */\nexport function editorSessionActive(): boolean {\n return active;\n}\n\nfunction cached(): string | null {\n try {\n return sessionStorage.getItem(TOKEN_KEY);\n } catch {\n return null;\n }\n}\n\n/**\n * The editor token for this page view: exchanged from a fresh fragment code\n * (`fresh: true`), else the one cached earlier in this tab. `{ error }` is a\n * refused exchange (401 = expired/used, anything else = couldn't load); null\n * means this is not an editor session at all.\n */\nexport function editorSession(apiBase: string): Promise<Outcome> {\n if (pending) return pending;\n const code = typeof window === 'undefined' ? null : takeHashParam('sentient_editor_code');\n if (!code) {\n const t = typeof window === 'undefined' ? null : cached();\n active = !!t;\n pending = Promise.resolve(t ? { token: t, fresh: false } : null);\n return pending;\n }\n active = true;\n pending = fetch(`${apiBase}/editor/exchange`, {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify({ code }),\n })\n .then(async (res): Promise<Outcome> => {\n const token = res.ok ? ((await res.json()) as { token?: string }).token : undefined;\n if (!token) return { error: res.ok ? 500 : res.status };\n try {\n sessionStorage.setItem(TOKEN_KEY, token);\n } catch {\n /* the session still works for this page view */\n }\n return { token, fresh: true };\n })\n .catch((): Outcome => ({ error: 0 }));\n return pending;\n}\n\n/** End the session (Exit preview): a reload is a normal visit again. */\nexport function endEditorSession(): void {\n try {\n sessionStorage.removeItem(TOKEN_KEY);\n } catch {\n /* fail-safe */\n }\n}\n\n/** Test hook. */\nexport function resetEditorSessionForTests(): void {\n pending = null;\n active = false;\n}\n","// On-site preview for generated versions (the dashboard's \"Preview on your\n// site\" link): ?sentient_preview_cell=<slotId>~<persona>#sentient_editor_code=…\n// (a one-time code exchanged for the editor token — editor-session.ts, E1)\n// fetches the square's PENDING (review) or live arm through the editor-token\n// API and forces it through the devtools override channel — which AdaptiveSlot\n// already renders IN PLACE, with the page's real CSS, and WITHOUT recording an\n// exposure ('override' source is excluded from tracking by design). A floating\n// bar names what is being previewed and offers Exit.\n//\n// Deliberately framework-light: the bar is plain DOM (no React tree to mount\n// into), and everything no-ops without both params, so normal visitors pay\n// one URLSearchParams read.\nimport { setSlotConfigOverride, setVocabularyOverride } from './devtools-slot-config-overrides.js';\nimport { setSlotOverride } from './devtools-slot-overrides.js';\nimport { notifyOverridesChanged } from './override-events.js';\nimport { editorSession, editorSessionActive, endEditorSession } from './editor-session.js';\nimport type { ComposeArm, StyleVocabulary } from '@sentientui/core';\n\nconst PARAM_CELL = 'sentient_preview_cell';\nconst PARAM_REFRESH = 'sentient_refresh_region';\nconst BAR_ID = 'sentient-cell-preview-bar';\nconst PREVIEW_ARM = '__preview__';\n\ntype CellPreviewResponse = {\n status: 'review' | 'live';\n slotName: string;\n personaDisplay: string;\n content: string | null;\n blocks: unknown | null;\n edits?: unknown;\n skeletonFp?: string;\n leafToNode?: number[];\n compose?: unknown;\n vocabulary?: StyleVocabulary;\n};\n\n// \"Refresh from page\" (spec 2026-09-23 §4.2): the operator says the region\n// changed. The capture runs INSIDE the AdaptiveSlot — only it holds the\n// children the element-tree parity check needs — so this module just forces\n// the original to show and leaves the request here for the slot to take.\n// `session` is a promise: the token arrives by exchange after this module ran,\n// but the slot's capture effect may run first and only once — holding the\n// promise lets it take the request now and post when the token lands.\ntype RegionRefresh = { slotId: string; session: ReturnType<typeof editorSession>; base: string };\nlet pendingRefresh: RegionRefresh | null = null;\n\n/** The refresh this page was opened for, if it targets `slotId`. Taken once. */\nexport function takeRegionRefresh(slotId: string): RegionRefresh | null {\n if (pendingRefresh?.slotId !== slotId) return null;\n const r = pendingRefresh;\n pendingRefresh = null;\n return r;\n}\n\n/** Post a trusted skeleton and tell the operator how it went. */\nexport function submitRegionRefresh(r: RegionRefresh, body: Record<string, unknown>): void {\n void r.session\n .then((s) => {\n if (!s || !('token' in s)) throw new Error('no editor session');\n return fetch(`${r.base}/editor/region-skeleton`, {\n method: 'POST',\n headers: { authorization: `Bearer ${s.token}`, 'content-type': 'application/json' },\n body: JSON.stringify({ slotId: r.slotId, ...body }),\n });\n })\n .then((res) =>\n mountBar(res.ok ? 'Region refreshed — you can regenerate its versions now.' : 'Couldn’t refresh this region — reopen the link from your dashboard.'),\n )\n .catch(() => mountBar('Couldn’t refresh this region — check your connection and reopen the link from your dashboard.'));\n}\n\n/** Start the on-site cell preview when the URL asks for one. Idempotent. */\nexport function maybeStartCellPreview(apiBaseUrl?: string): void {\n if (typeof window === 'undefined' || typeof document === 'undefined') return;\n if (document.getElementById(BAR_ID)) return;\n let cell: string | null;\n let refresh: string | null;\n try {\n const params = new URLSearchParams(window.location.search);\n cell = params.get(PARAM_CELL);\n refresh = params.get(PARAM_REFRESH);\n } catch {\n return;\n }\n if (!cell && !refresh) return;\n const base = (apiBaseUrl ?? 'https://api.sentient-ui.com/v1').replace(/\\/$/, '');\n const session = editorSession(base);\n // Only an operator's session acts on these params; a visitor who lands on a\n // shared ?sentient_refresh_region= URL gets the normal page.\n if (!editorSessionActive()) return;\n if (refresh) {\n pendingRefresh = { slotId: refresh, session, base };\n // Force the original: a served version on screen is not the region.\n // 'override' records no exposure, so the refresh visit is never a trial.\n setSlotConfigOverride(refresh, { kind: 'arms' });\n setSlotOverride(refresh, PREVIEW_ARM);\n notifyOverridesChanged();\n return;\n }\n if (!cell) return;\n const sep = cell.lastIndexOf('~');\n if (sep <= 0) return;\n const slotId = cell.slice(0, sep);\n const persona = cell.slice(sep + 1);\n\n void session\n .then((s) => {\n // No code and nothing cached: a bare param, not an editor session.\n if (!s) return null;\n if (!('token' in s)) {\n mountBar(s.error === 401\n ? 'This preview link has expired — reopen it from your dashboard.'\n : 'Couldn’t load this preview — reopen it from your dashboard.');\n return null;\n }\n return fetch(`${base}/editor/cell-preview?slotId=${encodeURIComponent(slotId)}&persona=${encodeURIComponent(persona)}`, {\n headers: { authorization: `Bearer ${s.token}` },\n });\n })\n .then(async (res) => {\n if (!res) return;\n if (!res.ok) {\n mountBar(res.status === 401\n ? 'This preview link has expired — reopen it from your dashboard.'\n : 'Couldn’t load this preview — reopen it from your dashboard.');\n return;\n }\n const data = (await res.json()) as CellPreviewResponse;\n if (data.vocabulary && Array.isArray(data.vocabulary.entries)) setVocabularyOverride(data.vocabulary);\n if (data.compose != null) {\n setSlotConfigOverride(slotId, { kind: 'arms', compose: { [PREVIEW_ARM]: data.compose as ComposeArm } });\n setSlotOverride(slotId, PREVIEW_ARM);\n } else if (data.edits != null && typeof data.skeletonFp === 'string' && Array.isArray(data.leafToNode)) {\n setSlotConfigOverride(slotId, { kind: 'arms', edits: { edits: data.edits as never, fp: data.skeletonFp, leafToNode: data.leafToNode } });\n setSlotOverride(slotId, PREVIEW_ARM);\n } else if (data.blocks != null) {\n setSlotConfigOverride(slotId, { kind: 'arms', blocks: { [PREVIEW_ARM]: data.blocks } } as never);\n setSlotOverride(slotId, PREVIEW_ARM);\n } else if (data.content != null) {\n setSlotConfigOverride(slotId, { kind: 'arms', content: data.content });\n setSlotOverride(slotId, PREVIEW_ARM);\n } else {\n mountBar('Nothing to preview in that square yet.');\n return;\n }\n notifyOverridesChanged();\n mountBar(\n `Previewing “${data.slotName}” for ${data.personaDisplay}${data.status === 'review' ? ' — waiting for your approval' : ''}. Nothing is being tracked.`,\n );\n // Bring the slot into view once it re-renders with the forced arm.\n setTimeout(() => {\n try {\n document.querySelector(`[data-sentient-slot=\"${slotId}\"]`)?.scrollIntoView({ block: 'center' });\n } catch {\n /* older browsers */\n }\n }, 300);\n })\n .catch(() => mountBar('Couldn’t load this preview — check your connection and reopen it from your dashboard.'));\n}\n\nfunction mountBar(text: string): void {\n if (document.getElementById(BAR_ID)) return;\n const bar = document.createElement('div');\n bar.id = BAR_ID;\n Object.assign(bar.style, {\n position: 'fixed', bottom: '16px', left: '50%', transform: 'translateX(-50%)', zIndex: '2147483647',\n display: 'flex', alignItems: 'center', gap: '10px', padding: '10px 14px', borderRadius: '12px',\n maxWidth: '90vw', background: '#111827', color: '#fff', font: '13px system-ui, sans-serif',\n border: '1px solid rgba(139,92,246,0.6)', boxShadow: '0 10px 34px rgba(0,0,0,0.45)',\n } satisfies Partial<CSSStyleDeclaration>);\n const label = document.createElement('span');\n label.textContent = text;\n const exit = document.createElement('button');\n exit.textContent = 'Exit preview';\n Object.assign(exit.style, {\n padding: '4px 10px', borderRadius: '999px', border: '1px solid rgba(255,255,255,0.35)',\n background: 'transparent', color: '#fff', font: '12px system-ui, sans-serif', cursor: 'pointer',\n } satisfies Partial<CSSStyleDeclaration>);\n exit.onclick = () => {\n endEditorSession();\n const url = new URL(window.location.href);\n url.searchParams.delete(PARAM_CELL);\n url.searchParams.delete(PARAM_REFRESH);\n window.location.assign(url.toString());\n };\n bar.append(label, exit);\n (document.body ?? document.documentElement).append(bar);\n}\n","// Style-vocabulary capture for React installs (native generation phase 2).\n// React sites never load the snippet editor, so without this a React project\n// (Bodyshop) would only ever get the crawler's colorless guess. Runs ONLY when\n// this page load exchanged a fresh editor code (#sentient_editor_code=, see\n// editor-session.ts), i.e. when an operator opened the page from the dashboard\n// — never for visitors, and not on every later page of a cached session. The\n// sampler is a separate core subpath, dynamically imported, so the normal\n// bundle pays nothing.\nimport { editorSession, resetEditorSessionForTests } from './editor-session.js';\n\nlet started = false;\n\nexport function maybeCaptureStyles(apiBaseUrl?: string): void {\n if (started || typeof window === 'undefined') return;\n started = true;\n const base = (apiBaseUrl ?? 'https://api.sentient-ui.com/v1').replace(/\\/$/, '');\n void editorSession(base).then((session) => {\n if (!session || !('token' in session) || !session.fresh) return;\n capture(base, session.token);\n });\n}\n\nfunction capture(base: string, token: string): void {\n // After load + 1s, so client-rendered heroes exist before we look.\n const run = (): void => {\n window.setTimeout(() => {\n void import('@sentientui/core/style-sample')\n .then(({ sampleStyleVocabulary }) =>\n fetch(`${base}/editor/style-vocabulary`, {\n method: 'POST',\n headers: { authorization: `Bearer ${token}`, 'content-type': 'application/json' },\n body: JSON.stringify(sampleStyleVocabulary(document)),\n }),\n )\n .catch(() => undefined);\n }, 1000);\n };\n if (document.readyState === 'complete') run();\n else window.addEventListener('load', run, { once: true });\n}\n\n/** Test hook. */\nexport function resetStyleCaptureForTests(): void {\n started = false;\n resetEditorSessionForTests();\n}\n","'use client';\n\n// `type JSX` from react, not the global namespace removed in @types/react@19\n// (peers allow react >=18) — see adaptive-text.tsx.\nimport { memo, useCallback, useEffect, useState, type JSX, type ReactNode, type Ref } from 'react';\nimport type { GoalName } from './goal-names.js';\nimport { useVariantComponent, type MicroSignalGoals } from './use-variant-component.js';\nimport { AdaptiveSlot, type AdaptiveSlotProps } from './adaptive-slot.js';\nimport { useInitialUnified, useSentient } from './provider.js';\n\nexport type {\n ScrollDepthGoal,\n ClickGoal,\n FormSubmitGoal,\n CompositeGoal,\n WeightedStep,\n WeightedCompositeGoal,\n GoalConfig,\n} from './adaptive-shared.js';\nimport { isDevBuild, type AdaptiveElement, type GoalConfig } from './adaptive-shared.js';\n\nexport type { MicroSignalGoalConfig, MicroSignalGoals } from './use-variant-component.js';\nexport type { AdaptiveElement } from './adaptive-shared.js';\n\n/** `<Adaptive>` with variants written in code — each key an arm, first key the control. */\nexport type AdaptiveVariantsProps = {\n id: string;\n variants: Record<string, ReactNode>;\n /** Your original. With `variants` AND children the component is a hybrid:\n * your hand-written versions, your original and dashboard-generated\n * versions compete in one experiment (spec 2026-09-23 §7). Without\n * children, `variants` keeps the variants-only experiment it always had. */\n children?: ReactNode;\n goal: GoalName | GoalConfig;\n /**\n * Funnel this component serves (stable funnel id, e.g. \"checkout\" —\n * shown on the dashboard's Funnels tab). Declares membership to the server;\n * a weighted_composite goal also declares the funnel's ordered steps, so a\n * code-first funnel appears in the dashboard without opening it. The\n * optimizer then trains this component on journey progress: small credit for\n * intermediate steps, full (or revenue-scaled) credit at completion.\n */\n funnel?: string;\n /**\n * When a passive micro-signal fires on this component, also record a named goal.\n * Use for inferred goals surfaced in the dashboard (e.g. rage_click → 'confused_by_hero').\n */\n microSignalGoals?: MicroSignalGoals;\n /** Wrapper element. @default 'div' */\n as?: AdaptiveElement;\n /** Class for the wrapper element. */\n className?: string;\n /**\n * When true, renders nothing during SSR and before client hydration.\n * Use when you cannot pass `initialAssignments` and prefer a blank slot over\n * a hydration mismatch. Tradeoff: minor CLS on first paint.\n */\n clientOnly?: boolean;\n /**\n * Variant-specific structured data for AI agent consumption via /sentient.json and\n * GET /v1/agent/layout. Keyed by variant ID — only the assigned variant's entry is stored,\n * so agents see only the content currently being served to visitors.\n *\n * Prefer this over `agentData` when variants have meaningfully different content.\n *\n * Captured at MOUNT: this value is read once, when the component's assignment\n * is requested, and is intentionally not part of the assign effect's deps.\n * Changing it after mount does not re-send it — pass the final value on first\n * render (e.g. from SSR/loader data, not a value that streams in later).\n */\n agentDataByVariant?: Record<string, unknown>;\n /**\n * @deprecated Use agentDataByVariant for variant-specific content. Stored as-is for the assigned variant.\n *\n * Captured at MOUNT (see `agentDataByVariant`): changing it after mount has no\n * effect on what is sent for the assignment.\n */\n agentData?: unknown;\n};\n\n/**\n * `<Adaptive>` without `variants`: the children are your original, and the\n * versions come from the dashboard (generated per visitor type, no redeploy).\n */\nexport type AdaptiveGeneratedProps = Omit<AdaptiveSlotProps, 'children'> & {\n children: ReactNode;\n variants?: undefined;\n};\n\nexport type AdaptiveProps = AdaptiveVariantsProps | AdaptiveGeneratedProps;\n\nfunction AdaptiveImpl(props: AdaptiveVariantsProps & { onUnified?: () => void }): JSX.Element | null {\n // Exposure, funnel, goal listeners, cursor + micro-signals all live in the\n // engine shared with useAdaptive, so a gate added for one applies to both.\n const { client, variantId, content, ref } = useVariantComponent(props.id, props.variants, {\n goal: props.goal,\n funnel: props.funnel,\n microSignalGoals: props.microSignalGoals,\n agentData: props.agentData,\n agentDataByVariant: props.agentDataByVariant,\n cursorSignal: true,\n onUnified: props.onUnified,\n });\n const [mounted, setMounted] = useState(false);\n useEffect(() => { setMounted(true); }, []);\n\n // Decorative slots: empty in SSR HTML and until the client has mounted.\n const Tag = props.as ?? 'div';\n if (props.clientOnly && (!mounted || !client)) return null;\n if (!variantId) return null;\n\n const jsxContent = props.variants[variantId] ?? null;\n const managedContent = jsxContent === null ? content : null;\n\n if (isDevBuild() && jsxContent === null && managedContent === null) {\n console.warn(\n `[sentient] <Adaptive id=\"${props.id}\"> was assigned variant \"${variantId}\" but no matching key exists in props.variants.` +\n ` If this is a dashboard-managed text variant, use <AdaptiveText id=\"${props.id}\"> instead.`,\n );\n }\n\n return (\n <Tag ref={ref as Ref<never>} className={props.className} data-sentient-id={props.id} data-sentient-variant={variantId}>\n {jsxContent ?? managedContent}\n </Tag>\n );\n}\n\n/**\n * Skips re-render only when nothing the output depends on has changed. The\n * variant node values must be compared, not just their keys: the assigned\n * `variantId` is stable, so if we compared keys alone, dynamic content inside a\n * variant (e.g. `<Price value={price}/>`) would render once and then freeze when\n * `price` changes. Elements are compared by reference — a caller that recreates\n * variant JSX on every render re-renders every time (correct), while stable/\n * memoized elements keep the optimization.\n */\nconst AdaptiveVariants = memo(AdaptiveImpl, (prev, next) => {\n if (prev.id !== next.id) return false;\n // Serialize only when the goal reference actually changed — a stable/memoized\n // goal (the common case) skips the stringify entirely.\n if (prev.goal !== next.goal && JSON.stringify(prev.goal) !== JSON.stringify(next.goal)) return false;\n if (prev.microSignalGoals !== next.microSignalGoals) return false;\n // `funnel` feeds the funnel-declaration effect: omitting it here swallowed a\n // funnel added or changed after first render (the memo skipped the re-render\n // that would have re-run the declaration).\n if (prev.funnel !== next.funnel) return false;\n if (prev.clientOnly !== next.clientOnly) return false;\n if (prev.as !== next.as || prev.className !== next.className) return false;\n if (prev.agentData !== next.agentData) return false;\n if (prev.agentDataByVariant !== next.agentDataByVariant) return false;\n if (prev.onUnified !== next.onUnified) return false;\n if (prev.variants === next.variants) return true;\n const prevKeys = Object.keys(prev.variants);\n const nextKeys = Object.keys(next.variants);\n if (prevKeys.length !== nextKeys.length) return false;\n return prevKeys.every((k) => k in next.variants && Object.is(prev.variants[k], next.variants[k]));\n});\n\n/**\n * One component, two ways to fill it. Without `variants`, the children are the\n * original and SentientUI serves dashboard-generated versions (the slot path —\n * what `<AdaptiveSlot>` was). With `variants`, the arms are the JSX you wrote.\n * The two stay separate optimizers underneath (slot_decisions vs the variant\n * bandit, CONTRACTS §1–§2); only the API is shared. Switching a mounted element\n * between modes remounts it, which is the honest behaviour: it becomes a\n * different experiment.\n */\nexport function Adaptive(props: AdaptiveProps): JSX.Element | null {\n if (props.variants === undefined) return <AdaptiveSlot {...props} />;\n const v = props as AdaptiveVariantsProps;\n if (v.children != null) {\n // Hybrid: authored arms + your original + generated versions on ONE slot\n // ledger — never the variant bandit too, which would book two trials per\n // impression (CONTRACTS §2). funnel, microSignalGoals, agentData,\n // agentDataByVariant and clientOnly carry over: the slot path implements\n // each, so a hand-written component keeps them when it gains children.\n const { variants, ...slotProps } = v;\n return <AdaptiveSlot {...(slotProps as Omit<AdaptiveSlotProps, 'variants'>)} children={v.children} variants={variants} />;\n }\n // Variants only: the variant ledger — unless the operator migrated this id.\n // Moving it is the operator's Migrate action, never an SDK upgrade (§7.5);\n // the SDK only follows it (ruling C1).\n return <AdaptiveVariantsOrUnified {...v} />;\n}\n\n/**\n * A variants-only `<Adaptive>`: the variant experiment it always ran, until\n * /v1/assign answers `unified: true` for its id (the operator migrated it —\n * CONTRACTS §2 \"A unified component is a slot\"). From then on it renders\n * through the slot path: its keys are the authored versions, it has no\n * children, so the FIRST key is the control (exactly as variantIds[0] is in\n * variants mode), and generated versions can join it. Without this an upgraded\n * page kept asking for a frozen variant experiment and learned nothing.\n *\n * It may already know before asking (ruling C20): an SSR preload lists the\n * moved ids (`initialUnified`, so the server HTML is already the slot path —\n * AdaptiveRoot `components`, the hero), or the client learned it earlier this\n * page. Then the variant path never mounts: an assignment cached before the\n * move would otherwise settle it, render a frozen variant and expose it.\n *\n * Only this component asks with the cap: useAdaptive has no slot path, so it\n * keeps being served the frozen run read-only (it warns in dev).\n */\nfunction AdaptiveVariantsOrUnified(props: AdaptiveVariantsProps): JSX.Element | null {\n // Keyed on the id: a mounted element whose id changes is a different\n // component, and must ask again rather than inherit the old answer.\n const [unifiedId, setUnifiedId] = useState<string | null>(null);\n const { id } = props;\n const onUnified = useCallback(() => setUnifiedId(id), [id]);\n const client = useSentient();\n // initialUnified is in the SSR render and the first client render alike;\n // the client only exists after hydration, so neither can mismatch.\n const known = useInitialUnified().includes(id) || client?.isUnified?.(id) === true;\n if (unifiedId !== id && !known) return <AdaptiveVariants {...props} onUnified={onUnified} />;\n const { variants, children: _children, ...rest } = props;\n const first = Object.keys(variants)[0];\n return (\n <AdaptiveSlot\n {...(rest as Omit<AdaptiveSlotProps, 'variants' | 'children'>)}\n variants={variants}\n variantsOnly\n >\n {first !== undefined ? variants[first] : null}\n </AdaptiveSlot>\n );\n}\n","import type { GoalName } from './goal-names.js';\nimport { useCallback, useEffect, useMemo, useRef, useState, type RefObject } from 'react';\nimport { attachMicroSignalDetectors, type MicroSignalType, type SentientClient } from '@sentientui/core';\nimport { useAdaptiveApiKey, useSentient } from './provider.js';\nimport { useAssignment } from './use-assignment.js';\nimport { registerComponent } from './devtools-registry.js';\nimport {\n attachGoalListeners,\n goalLabelOf,\n goalValueOf,\n maybeDeclareFunnel,\n normalizeGoal,\n trackExposure,\n type GoalConfig,\n} from './adaptive-shared.js';\n\n/** Maps a detected micro-signal to a named session goal (`client.goal`). */\nexport type MicroSignalGoalConfig = GoalName | { name: GoalName; weight?: number; stepIndex?: number };\nexport type MicroSignalGoals = Partial<Record<MicroSignalType, MicroSignalGoalConfig>>;\n\nexport type VariantComponentOptions = {\n goal: string | GoalConfig | undefined;\n funnel?: string;\n microSignalGoals?: MicroSignalGoals;\n agentData?: unknown;\n agentDataByVariant?: Record<string, unknown>;\n /** Emit `cursor_signal` after 800 ms of continuous hover (<Adaptive> only). */\n cursorSignal?: boolean;\n /** <Adaptive> only: called when the server says this id was migrated onto\n * the shared track (see useAssignment). Without it the hook never sends the\n * unified cap — useAdaptive has no slot path to move to. */\n onUnified?: () => void;\n};\n\nexport type VariantComponentState = {\n client: SentientClient | null;\n variantIds: string[];\n /** Null until useAssignment has any variant (e.g. SSR with ssrFallback 'none'). */\n variantId: string | null;\n content: string | null;\n settled: boolean;\n isOverride: boolean;\n goalLabel: string;\n /** Callback ref — attach to the element exposure/goals/micro-signals bind to. */\n ref: (el: HTMLElement | null) => void;\n nodeRef: RefObject<HTMLElement | null>;\n};\n\n/**\n * The measurement engine shared by `<Adaptive variants>` and `useAdaptive`:\n * assignment, devtools registration, exposure, funnel declaration, goal\n * listeners and micro-signal detectors.\n *\n * It exists because the two used to carry copies of these effects and drifted:\n * the hook's micro-signal effect lost the `settled` gate <Adaptive> had, so a\n * rage-click during the interim-baseline window recorded a micro_signal on an\n * arm that was never served, and the hook silently had no `microSignalGoals`.\n * Every gate below now applies to both callers at once.\n */\nexport function useVariantComponent(\n id: string,\n variants: Record<string, unknown>,\n opts: VariantComponentOptions,\n): VariantComponentState {\n const client = useSentient();\n const apiKey = useAdaptiveApiKey();\n // Freeze the variant-id array on the KEY SET, not the object identity: an\n // inline `variants={{...}}` literal is a fresh object every render, so keying\n // on the object churned a new array each commit — re-running the register\n // effect and unregistering+re-registering the component on every render.\n // Same convention as AdaptiveGroup / useAdaptiveTokens.\n const variantKey = Object.keys(variants).join('\\u0000');\n // eslint-disable-next-line react-hooks/exhaustive-deps\n const variantIds = useMemo(() => Object.keys(variants), [variantKey]);\n const { variantId, content, isOverride = false, settled } = useAssignment(\n id,\n variantIds,\n opts.agentData,\n opts.agentDataByVariant,\n opts.onUnified ? { onUnified: opts.onUnified } : undefined,\n );\n\n // Callback ref + state, not a plain useRef: useAdaptive's bind target is the\n // caller's element and may attach after (or be swapped out from under) the\n // first commit — a useRef read inside effects never re-runs them, so\n // listeners stayed on a detached node or never attached.\n const [node, setNode] = useState<HTMLElement | null>(null);\n const nodeRef = useRef<HTMLElement | null>(null);\n const ref = useCallback((el: HTMLElement | null) => {\n nodeRef.current = el;\n setNode(el);\n }, []);\n\n const rawGoal = opts.goal;\n const goalKey = typeof rawGoal === 'string' ? rawGoal : JSON.stringify(rawGoal);\n // Missing-goal misuse fails SOFT (callers may throw in dev first): an\n // unconditional goalLabelOf(undefined) crashed the whole prod render on\n // `undefined.type`. Serve and expose the variant, wire no goal.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n const goal = useMemo(() => (rawGoal ? normalizeGoal(rawGoal) : null), [goalKey]);\n const goalLabel = rawGoal ? goalLabelOf(rawGoal) : '';\n\n // Register with the devtools registry so the dev widget can list this\n // component + its variants. Inert in production; cleanup unregisters.\n useEffect(() => registerComponent({ id, variantIds, goal: goalLabel }), [id, variantIds, goalLabel]);\n\n // Exposure: variant_assigned exactly once per (component, variant) mount.\n const exposedRef = useRef<string | null>(null);\n useEffect(() => {\n // A forced variant is a dev/test view, not a real exposure — recording it\n // would train the bandit on the override. Same gate on every tracking\n // effect below (\"no events recorded, weights unchanged\").\n if (isOverride) return;\n // Only expose a SETTLED assignment. On the CSR path the served variant\n // resolves in two steps (interim baseline variantIds[0] → bandit choice);\n // tracking the interim would accrue a phantom baseline exposure that can\n // never convert.\n if (!settled) return;\n if (!client || !variantId || !apiKey || !node) return;\n if (exposedRef.current === variantId) return;\n exposedRef.current = variantId;\n trackExposure(client, apiKey, id, variantId);\n }, [client, variantId, apiKey, id, node, isOverride, settled]);\n\n // Goal latches reset when the variant or goal changes.\n const goalFiredRef = useRef(false);\n const microGoalFiredRef = useRef<Set<MicroSignalType>>(new Set());\n useEffect(() => {\n goalFiredRef.current = false;\n microGoalFiredRef.current = new Set();\n }, [variantId, goal]);\n\n // Declare funnel membership (and, for weighted composites, the funnel's\n // steps) once per page load. Same settle/override gates as the exposure —\n // a forced dev view must not declare anything. A weighted composite with no\n // `funnel` declares its own (compositeFunnelId).\n const funnel = opts.funnel;\n useEffect(() => {\n if (isOverride || !settled) return;\n if (!client || !goal) return;\n maybeDeclareFunnel(client, apiKey, id, funnel, goal);\n }, [client, apiKey, id, funnel, goal, isOverride, settled]);\n\n // cursor_signal after 800 ms of continuous hover.\n const cursorSignal = opts.cursorSignal === true;\n useEffect(() => {\n if (!cursorSignal || isOverride) return;\n // Same settle gate as the exposure: before assign() resolves, variantId is\n // the interim baseline placeholder — a hover then would attribute a\n // cursor_signal to an arm that was never really served.\n if (!settled) return;\n if (!client || !variantId || !node) return;\n\n let timerId: ReturnType<typeof setTimeout> | null = null;\n let hoverStart = 0;\n const onEnter = (): void => {\n hoverStart = Date.now();\n timerId = setTimeout(() => {\n client.track({\n projectId: apiKey,\n componentId: id,\n variantId,\n eventType: 'cursor_signal',\n payload: { hoverDuration: Date.now() - hoverStart },\n });\n timerId = null;\n }, 800);\n };\n const onLeave = (): void => {\n if (timerId !== null) {\n clearTimeout(timerId);\n timerId = null;\n }\n };\n node.addEventListener('mouseenter', onEnter);\n node.addEventListener('mouseleave', onLeave);\n return () => {\n node.removeEventListener('mouseenter', onEnter);\n node.removeEventListener('mouseleave', onLeave);\n if (timerId !== null) clearTimeout(timerId);\n };\n }, [cursorSignal, client, variantId, apiKey, id, node, isOverride, settled]);\n\n // Micro-signal detectors — rage click, text copy, scroll hesitation, tab loss.\n // The mapping is read through a ref and the effect is keyed on its CONTENT:\n // attachMicroSignalDetectors latches each signal once per attach, so keying\n // on identity re-attached on every render for an inline `microSignalGoals`\n // literal (the natural way to call useAdaptive), resetting those latches and\n // re-emitting the same micro_signal repeatedly.\n const microSignalGoalsRef = useRef(opts.microSignalGoals);\n microSignalGoalsRef.current = opts.microSignalGoals;\n const microKey = opts.microSignalGoals ? JSON.stringify(opts.microSignalGoals) : '';\n useEffect(() => {\n if (isOverride) return;\n // Gate on settle too (like the exposure): during the pre-assign() window\n // variantId is the interim baseline placeholder, so a rage-click / tab-loss\n // would record a micro_signal — and fire a mapped named goal — attributed\n // to an arm that was never really served. useAdaptive lacked this gate\n // before the two paths shared this hook.\n if (!settled) return;\n if (!client || !variantId || !node) return;\n const assignedAt = Date.now();\n return attachMicroSignalDetectors(\n (signalType, extra = {}) => {\n client.track({\n projectId: apiKey,\n componentId: id,\n variantId,\n eventType: 'micro_signal',\n payload: { signalType, ...extra },\n });\n\n const mapping = microSignalGoalsRef.current?.[signalType];\n if (!mapping || microGoalFiredRef.current.has(signalType)) return;\n microGoalFiredRef.current.add(signalType);\n const name = typeof mapping === 'string' ? mapping : mapping.name;\n const weight = typeof mapping === 'string' ? 1.0 : (mapping.weight ?? 1.0);\n const stepIndex = typeof mapping === 'string' ? 0 : (mapping.stepIndex ?? 0);\n // Explicit options form: `extra` is arbitrary micro-signal data, so it\n // must land in metadata and never be mistaken for GoalOptions keys.\n client.goal(name, { metadata: { signalType, ...extra }, weight, stepIndex });\n },\n node,\n assignedAt,\n );\n }, [client, variantId, apiKey, id, node, microKey, isOverride, settled]);\n\n // Goal listeners (shared machinery — see adaptive-shared.ts).\n useEffect(() => {\n if (isOverride) return;\n // Same settle gate as the exposure: before assign() resolves, variantId is\n // the interim baseline placeholder, which never recorded an impression — a\n // conversion in that window would attribute to an arm with zero exposures\n // and corrupt its stats.\n if (!settled) return;\n if (!client || !variantId || !node || !goal) return;\n\n // A static `value` on the goal config rides on BOTH writes (the component-\n // attributed event and the session funnel record) so read-time dedup never\n // picks a valueless row. Steps carry weights, never values (spec §9.4).\n const declaredValue = goalValueOf(goal);\n return attachGoalListeners(node, goal, {\n fireGoal: () => {\n if (goalFiredRef.current) return;\n goalFiredRef.current = true;\n client.track({\n projectId: apiKey,\n componentId: id,\n variantId,\n eventType: 'goal_achieved',\n goalType: goalLabel,\n payload: { reward: 1.0, ...(declaredValue !== undefined ? { goalValue: declaredValue } : {}) },\n });\n client.goal(goalLabel, {\n metadata: { componentId: id, variantId },\n weight: 1.0,\n stepIndex: 0,\n ...(declaredValue !== undefined ? { value: declaredValue } : {}),\n });\n },\n fireStep: (name, weight, stepIndex) => {\n client.track({\n projectId: apiKey,\n componentId: id,\n variantId,\n eventType: 'goal_achieved',\n goalType: name,\n payload: { reward: weight },\n });\n client.goal(name, { metadata: {}, weight, stepIndex });\n },\n }, goalLabel);\n }, [client, variantId, apiKey, id, node, goal, goalLabel, isOverride, settled]);\n\n return { client, variantIds, variantId, content, settled, isOverride, goalLabel, ref, nodeRef };\n}\n","import { useEffect, useRef, useState, useSyncExternalStore } from 'react';\nimport { type AssignResult } from '@sentientui/core';\n// The degraded-fallback pick lives in @sentientui/policy so its shrinkage\n// formula is single-sourced with the pinned statistics (audit REACT-14 — a\n// local copy here was a third shrinkage variant nobody replayed).\nimport { pickFromWeights } from '@sentientui/policy';\nimport { useSentient, useInitialAssignments, useSessionSegment, useSsrFallback, useOnAssignment, useDebug } from './provider.js';\nimport { subscribe, getWeights } from './weights-store.js';\nimport { subscribeOverridesChanged } from './override-events.js';\nimport { getDevOverride } from './dev-override.js';\n\nexport type AssignmentState = {\n variantId: string | null;\n /** Populated when the assigned variant is a dashboard-managed text variant. */\n content: string | null;\n isLoading: boolean;\n /**\n * True once `variantId` reflects a REAL decision — an SSR preload, the local\n * assignment cache, a server `assign()`, live bandit weights, or a dev\n * override — rather than the interim `variantIds[0]` placeholder shown while a\n * decision is still in flight. Exposure tracking MUST gate on this: emitting\n * `variant_assigned` for the placeholder accrues a phantom baseline\n * impression that can never convert and dilutes that arm's CVR.\n */\n settled: boolean;\n /**\n * True while a dev override (?sentient_variant= / window.__sentient_overrides)\n * is forcing this variant. Consumers must suppress ALL tracking while set —\n * the override contract is \"no events recorded, weights unchanged\".\n */\n isOverride?: boolean;\n};\n\n/**\n * Returns a sticky variant assignment for a component.\n *\n * @deprecated Since 0.13.0 — use {@link useAdaptive} instead. `useAssignment`\n * only SELECTS a variant; it wires no exposure tracking, no goal listeners,\n * and no micro-signals, so components using it directly accumulate no\n * learning signal. It keeps working (it is `useAdaptive`'s internal\n * selection engine) but will move to internal-only in 1.0.0.\n *\n * First render reads the local SDK cache; if empty, falls back to a\n * deterministic default and asynchronously calls `/v1/assign`. The server\n * picks the actual variant via Thompson Sampling and the result replaces the fallback\n * on the next render. Subsequent paints read synchronously from cache —\n * no flicker, no loading state after first paint.\n */\nexport function useAssignment(\n componentId: string,\n variantIds: string[],\n agentData?: unknown,\n agentDataByVariant?: Record<string, unknown>,\n /** `onUnified`: the caller can render this component on the shared track.\n * The assign then carries the unified cap, and a `unified` answer calls this\n * INSTEAD of settling — it is not an assignment, and settling on its\n * placeholder would expose that variant on a frozen ledger. */\n opts?: { onUnified?: () => void },\n): AssignmentState {\n const initialAssignments = useInitialAssignments();\n const ssrFallback = useSsrFallback();\n const client = useSentient();\n const segment = useSessionSegment();\n const onAssignment = useOnAssignment();\n const debug = useDebug();\n const assignmentReportedRef = useRef<string | null>(null);\n\n // Dev override (URL ?sentient_variant=componentId:variantId or\n // window.__sentient_overrides[componentId]) read through useSyncExternalStore:\n // - server snapshot is null (no window), so SSR renders the un-forced variant;\n // - the client snapshot reads the override, and React reconciles the two\n // across hydration WITHOUT a mismatch (this is exactly what the hook is for);\n // - unlike a post-mount flip it is already correct on a remount / CSR-nav, so\n // a forced variant never leaks an interim assign() or exposure before the\n // override applies.\n // It also re-renders when the devtools/scenario helpers bump the override bus.\n const devOverride = useSyncExternalStore(\n subscribeOverridesChanged,\n () => getDevOverride(componentId),\n () => null,\n );\n const overrideVariant = devOverride && variantIds.includes(devOverride) ? devOverride : null;\n const overrideLoggedRef = useRef<string | null>(null);\n // Diagnostic log for an active dev override — effect, never render body, and\n // gated behind the provider's debug flag so it stays silent in production.\n useEffect(() => {\n if (!debug) return;\n if (!overrideVariant) return;\n if (overrideLoggedRef.current === overrideVariant) return;\n overrideLoggedRef.current = overrideVariant;\n console.info(`[sentient] override active: ${componentId} -> ${overrideVariant}`);\n }, [debug, overrideVariant, componentId]);\n\n // Lazy initializer: this selection logic (URLSearchParams parse via the\n // override read above, cache + weights Map lookups) runs ONCE on mount, not\n // on every render. React only uses a useState initializer's value on first\n // render, so computing it eagerly each render was pure waste on every\n // <Adaptive>/useAdaptive re-render. Mirrors AdaptiveText's lazy seeds.\n const [state, setState] = useState<AssignmentState>((): AssignmentState => {\n if (overrideVariant) {\n return { variantId: overrideVariant, content: null, isLoading: false, settled: true };\n }\n // SSR / pre-hydration: no client yet. Use initialAssignments if provided so\n // the server and client first render agree on the same variant (no mismatch).\n if (!client) {\n const preloaded = initialAssignments[componentId];\n if (preloaded && variantIds.includes(preloaded)) {\n // Server-decided — a real assignment, safe to expose.\n return { variantId: preloaded, content: null, isLoading: false, settled: true };\n }\n if (ssrFallback === 'first' && variantIds.length > 0) {\n // SEO placeholder shown until the client resolves a real decision — NOT\n // settled, so no exposure fires for this interim baseline.\n return { variantId: variantIds[0], content: null, isLoading: false, settled: false };\n }\n return { variantId: null, content: null, isLoading: true, settled: false };\n }\n const cached = client.getAssignment(componentId, segment);\n // Allow cached managed variants (content present) even if not in variantIds.\n if (cached && (variantIds.includes(cached.variantId) || cached.content)) {\n return { variantId: cached.variantId, content: cached.content ?? null, isLoading: false, settled: true };\n }\n const weights = getWeights(componentId);\n if (weights) {\n const chosen = pickFromWeights(weights.variants, variantIds);\n if (chosen) return { variantId: chosen, content: null, isLoading: false, settled: true };\n }\n // Interim placeholder while the async assign() below is in flight — not a\n // real decision yet, so it stays unsettled and emits no exposure.\n return { variantId: variantIds[0] ?? null, content: null, isLoading: false, settled: false };\n });\n\n // Helper: call onAssignment at most once per resolved variant.\n const reportAssignment = (variantId: string): void => {\n if (!onAssignment) return;\n if (assignmentReportedRef.current === variantId) return;\n assignmentReportedRef.current = variantId;\n onAssignment(componentId, variantId);\n };\n\n // As soon as the client is ready, unblock the UI immediately with variantIds[0]\n // (or a cached value) so the component never stays invisible while assign is\n // in-flight. The async assign call below then swaps to the bandit-chosen variant.\n useEffect(() => {\n if (overrideVariant) return;\n if (!client) return;\n const cached = client.getAssignment(componentId, segment);\n if (cached && (variantIds.includes(cached.variantId) || cached.content)) {\n setState({ variantId: cached.variantId, content: cached.content ?? null, isLoading: false, settled: true });\n reportAssignment(cached.variantId);\n return;\n }\n // Weights-resolved initializer pick: the useState initializer above can\n // settle on a variant chosen from cached bandit weights but, being\n // render-phase, it cannot call onAssignment — so weights-resolved variants\n // never reported while the cache/assign paths always did. Report it here;\n // the pick is recomputed (deterministic for the same store contents) so a\n // settled state from any OTHER source is left alone.\n const weights = getWeights(componentId);\n if (weights && state.settled && state.variantId && state.variantId === pickFromWeights(weights.variants, variantIds)) {\n reportAssignment(state.variantId);\n return;\n }\n setState((prev) => prev.variantId ? prev : { variantId: variantIds[0] ?? null, content: null, isLoading: false, settled: false });\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [overrideVariant, client, componentId, segment]);\n\n // Ask the server for a real assignment when we have a client but no cached one.\n useEffect(() => {\n if (overrideVariant) return;\n if (!client) return;\n const cached = client.getAssignment(componentId, segment);\n if (cached && variantIds.includes(cached.variantId)) return;\n\n // A late answer is still swapped in. Declining it (audit S9's deadline)\n // would not avoid a trial: /v1/assign records the exposure server-side at\n // draw time, so a declined arm was booked as shown while the page showed\n // the placeholder. Bounding lateness happens before the request instead\n // (core's SESSION_WAIT_MS: an assign that would start late isn't sent).\n let cancelled = false;\n const onUnified = opts?.onUnified;\n const request = onUnified\n ? client.assign(componentId, variantIds, agentData, agentDataByVariant, { unified: true })\n : client.assign(componentId, variantIds, agentData, agentDataByVariant);\n void request.then((result: AssignResult | null) => {\n if (cancelled) return;\n if (!result) return;\n if (result.unified === true) {\n onUnified?.();\n return;\n }\n // Allow the result if it's a known code variant OR a managed text variant (has content).\n if (!variantIds.includes(result.variantId) && !result.content) return;\n setState({ variantId: result.variantId, content: result.content ?? null, isLoading: false, settled: true });\n reportAssignment(result.variantId);\n });\n return () => { cancelled = true; };\n // variantIds intentionally excluded — changing variants mid-mount is unsupported\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [overrideVariant, client, componentId, segment]);\n\n // Live weight updates from the dashboard SSE stream (when wired).\n useEffect(() => {\n if (overrideVariant) return;\n if (!client) return;\n return subscribe(componentId, (weights) => {\n const cached = client.getAssignment(componentId, segment);\n if (cached && (variantIds.includes(cached.variantId) || cached.content)) {\n setState({ variantId: cached.variantId, content: cached.content ?? null, isLoading: false, settled: true });\n reportAssignment(cached.variantId);\n return;\n }\n const chosen = pickFromWeights(weights.variants, variantIds);\n if (chosen) {\n setState({ variantId: chosen, content: null, isLoading: false, settled: true });\n // A live-subscription pick is as real an assignment as assign()'s\n // result — without this report, onAssignment fired late or never for\n // weights-resolved variants (reportAssignment dedupes per variant).\n reportAssignment(chosen);\n }\n });\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [overrideVariant, client, componentId, segment]);\n\n if (overrideVariant) {\n return { variantId: overrideVariant, content: null, isLoading: false, settled: true, isOverride: true };\n }\n\n return state;\n}\n","declare global {\n interface Window {\n __sentient_overrides?: Record<string, string>;\n }\n}\n\n/**\n * Reads a forced variant for a component from the dev-override channels:\n * `window.__sentient_overrides[id]` (devtools panel, `applyScenario`, the\n * Playwright/Cypress helpers) or the `?sentient_variant=id:variant` URL param\n * (repeatable for multiple components). Returns `null` in non-browser envs.\n *\n * Callers MUST read this POST-MOUNT (never in the render body): it touches\n * `window.location`, which is absent on the server, so reading it during render\n * diverges the SSR output from the client's first render and throws a hydration\n * mismatch on any SSR page carrying `?sentient_variant=`.\n */\nexport function getDevOverride(componentId: string): string | null {\n if (typeof window === 'undefined') return null;\n const global = window.__sentient_overrides?.[componentId];\n if (global) return global;\n // This runs as a useSyncExternalStore getSnapshot (once or twice per render\n // pass, per adaptive component), so skip the URLSearchParams parse entirely on\n // the overwhelmingly common no-query-string page.\n if (!window.location.search) return null;\n try {\n const params = new URLSearchParams(window.location.search);\n for (const raw of params.getAll('sentient_variant')) {\n // sentient_variant=componentId:variantId (repeatable for multiple components)\n const sep = raw.indexOf(':');\n if (sep === -1) continue;\n if (raw.slice(0, sep) === componentId) return raw.slice(sep + 1);\n }\n } catch {\n /* non-browser env */\n }\n return null;\n}\n","'use client';\nimport type { GoalName } from './goal-names.js';\nimport { useEffect, useMemo, useRef, useState, useSyncExternalStore, type JSX, type ReactNode, type Ref } from 'react';\nimport { attachMicroSignalDetectors, containsFormBlock, reveal, type RenderCaps, type SkeletonReport } from '@sentientui/core';\nimport type { MicroSignalGoals } from './use-variant-component.js';\nimport { captureRegionSkeleton } from '@sentientui/core/region';\nimport { useAdaptiveApiKey, useSentient } from './provider.js';\nimport { useSlotConfig } from './use-slot-config.js';\nimport { renderBlocks, renderCompose } from './blocks-render.js';\nimport { annotateSkeletonForReact, applyEdits, countTextLeaves, reactFingerprint, substituteSlotText } from './slot-text.js';\nimport {\n attachGoalListeners,\n goalLabelOf,\n goalValueOf,\n isDevBuild,\n maybeDeclareFunnel,\n normalizeGoal,\n trackExposure,\n type AdaptiveElement,\n type GoalConfig,\n} from './adaptive-shared.js';\nimport { registerComponent, registerSlot } from './devtools-registry.js';\nimport { submitRegionRefresh, takeRegionRefresh } from './cell-preview.js';\nimport { subscribeOverridesChanged } from './override-events.js';\nimport { getDevOverride } from './dev-override.js';\n\n// Warn once per slot id per page lifetime, not per render.\nconst warnedFormSlots = new Set<string>();\nconst warnedOpaqueSlots = new Set<string>();\nconst warnedBlockedSlots = new Set<string>();\n\nexport type AdaptiveSlotProps = {\n id: string;\n /** Baseline JSX — holdout, unknown personas, empty cells, every error path. */\n children: ReactNode;\n /** Hand-written versions (a hybrid <Adaptive>): each key is an arm the\n * server may draw alongside your original and the generated versions, in\n * one experiment (spec 2026-09-23 §7). */\n variants?: Record<string, ReactNode>;\n /** Receives form values when a generated form arm submits. Without it, form\n * arms fall back to children entirely. Values never reach Sentient. */\n onFormSubmit?: (values: Record<string, string>) => void;\n /** Optional goal attached to the container (click/scroll/composite), same\n * shape as AdaptiveGroup's. Form arms fire their own submitGoal regardless. */\n goal?: GoalName | GoalConfig;\n className?: string;\n /** Wrapper element. @default 'div' */\n as?: AdaptiveElement;\n /** On first registration the SDK sends the region's rendered text (capped at\n * 400 chars) so dashboard-generated versions are grounded in what they\n * replace. Set false for a slot wrapping personalized or account content —\n * the text of THIS region is all that is ever read, never the page. */\n reportBaselineText?: boolean;\n /** Funnel this component serves (stable funnel id). Same meaning as on a\n * variants-only `<Adaptive>`: declares membership (and, for a\n * weighted_composite goal, the funnel's steps) once per page load. */\n funnel?: string;\n /** Also record a named goal when a passive micro-signal fires here (e.g.\n * rage_click → 'confused_by_hero'). Recorded only for a served arm, and\n * credited to the component like `goal`. */\n microSignalGoals?: MicroSignalGoals;\n /** Render nothing during SSR and before client hydration. */\n clientOnly?: boolean;\n /** Per-arm structured data for AI agents, keyed by the authored key for a\n * hand-written arm and by arm id for a generated one. Only the served arm's\n * entry is sent. Captured at MOUNT, like on a variants-only `<Adaptive>`. */\n agentDataByVariant?: Record<string, unknown>;\n /** @deprecated Use agentDataByVariant. Sent for any served arm that has no\n * entry of its own. Captured at MOUNT. */\n agentData?: unknown;\n /** @internal Set by `<Adaptive variants>` (no children) once the server says\n * its id was migrated onto the shared track. `children` is then the FIRST\n * variant, not an original: the page tells decide it has no children, so\n * the first authored key is the control and the 'baseline' arm — which\n * would render that same first variant under another id — is never drawn. */\n variantsOnly?: boolean;\n};\n\n/**\n * @deprecated Use `<Adaptive id=\"…\">{children}</Adaptive>` — `<Adaptive>`\n * without `variants` is this component. Kept exported because the package is\n * published; it will not be removed in a minor release.\n *\n * A region whose content the server may replace with a named arm — a copy\n * string or a validated Composition Block tree (registry slot config). The\n * children are the founder's baseline: they render untouched for holdout\n * traffic, unserved slots, and every error path, so the worst case is always\n * \"nothing changed\" (spec 2026-09-08 empty-cell-generation §3).\n */\nconst AUTHORED_PREFIX = 'authored.';\n\nexport function AdaptiveSlot({\n id,\n children,\n variants,\n onFormSubmit,\n goal,\n className,\n as: Tag = 'div',\n reportBaselineText = true,\n funnel,\n microSignalGoals,\n clientOnly,\n agentDataByVariant,\n agentData,\n variantsOnly = false,\n}: AdaptiveSlotProps): JSX.Element | null {\n const client = useSentient();\n const apiKey = useAdaptiveApiKey();\n const nodeRef = useRef<HTMLElement | null>(null);\n // clientOnly renders nothing in SSR HTML and until a client exists. Every\n // effect that binds to the wrapper element lists `hidden` in its deps: they\n // ran once against a null node on the first commit and, without it, never\n // re-ran when the wrapper appeared — a clientOnly slot with no goal wiring.\n const [mounted, setMounted] = useState(false);\n useEffect(() => { setMounted(true); }, []);\n const hidden = clientOnly === true && (!mounted || !client);\n // What this region can render (CONTRACTS §2), from the element tree so it\n // is known before any DOM exists. No reachable text → a fingerprint no real\n // skeleton has: no Rewrite arm can land here, so none may be drawn.\n const childFp = useMemo(() => reactFingerprint(children), [children]);\n // A hybrid declares its authored keys on every decide: the server draws\n // `authored.<key>` only for keys this page has, so a key removed in a deploy\n // simply leaves the arm space (and a sticky visitor re-decides).\n const authoredKey = variants ? Object.keys(variants).join('|') : '';\n const caps = useMemo<RenderCaps>(\n () => ({\n fp: childFp ?? '0000000000000000',\n forms: !!onFormSubmit,\n // This SDK renders Redesign trees (`like` + compose), so the server may\n // draw them for this page (CONTRACTS §2).\n compose: true,\n content: countTextLeaves(children) === 1,\n // React never applies `ops`. Without this, an <Adaptive id> matching a\n // script-tag component was drawn its ops version, rendered the original,\n // and booked a trial for a version nobody saw.\n ops: false,\n ...(authoredKey !== '' ? { authored: authoredKey.split('|'), children: !variantsOnly } : {}),\n }),\n [childFp, children, onFormSubmit, authoredKey, variantsOnly],\n );\n // The region's skeleton, read from the DOM while it shows the developer's\n // children. Tied to the ELEMENT TREE by a parity check: edits are addressed\n // by leaf order, so if the tree and the DOM disagree the region is\n // unaddressable rather than edited in the wrong place.\n const captureSkeleton = (): SkeletonReport | null => {\n const el = nodeRef.current;\n if (!el || !reportBaselineText) return null;\n const cap = captureRegionSkeleton(el);\n if (!cap.skeleton) return { status: cap.reason };\n // A region wrapping a component (`<Adaptive><CtaButtons /></Adaptive>`, the\n // usual React shape) fails the parity check: the element tree can't see\n // text a component renders. It used to be reported unaddressable with no\n // skeleton at all, which blocked Redesign too — the Bodyshop CTA. The DOM\n // capture still describes the region, so send it marked non-editable:\n // Redesign replaces the whole region and needs no addressing, and this\n // page's fingerprint (childFp) never matches it, so no Rewrite arm can be\n // drawn here either way.\n return (\n annotateSkeletonForReact(cap.skeleton, children) ?? {\n ...cap.skeleton,\n editable: false,\n nodes: cap.skeleton.nodes.map((n) => ({ ...n, restylable: false })),\n }\n );\n };\n // Any <Adaptive> with `variants` answers the variant dev-override channels:\n // ?sentient_variant=id:key, __sentient_overrides (devtools, the\n // Playwright/Cypress helpers).\n // - Moved variants-only components (ruling C24): without this, moving a\n // component broke every test that forced one of its variants.\n // - Hybrids with children (ruling C27): the sentient-ui.com hero ignored\n // ?sentient_variant= and kept deciding and crediting. Meanwhile\n // useAdaptiveGoal, which does read the override, dropped its goals. The\n // preview and the recording disagreed.\n // How a forced key maps to an arm:\n // - a `variants` key → `authored.<key>`;\n // - `baseline` → the original (hybrids only; variants-only has none);\n // - any other key → the control. An override is still active, so this\n // stays a silent preview, as useAdaptiveGoal treats it.\n // The server snapshot is null, so SSR never reads window (see dev-override.ts).\n const forcedKey = useSyncExternalStore(\n subscribeOverridesChanged,\n () => (variants ? getDevOverride(id) : null),\n () => null,\n );\n const forcedArm = forcedKey === null || !variants\n ? null\n : Object.prototype.hasOwnProperty.call(variants, forcedKey)\n ? `${AUTHORED_PREFIX}${forcedKey}`\n : variantsOnly\n ? `${AUTHORED_PREFIX}${Object.keys(variants)[0]}`\n : 'baseline';\n const { config, arm, palette, vocabulary, source } = useSlotConfig(id, {\n forcedArm,\n // Only ever read when the slot is unserved — at that moment the wrapper\n // contains exactly the baseline children this slot exists to replace.\n baselineText: reportBaselineText ? () => nodeRef.current?.textContent ?? null : undefined,\n render: () => caps,\n skeleton: captureSkeleton,\n defer: hidden,\n });\n\n const tree = arm !== '' ? config?.blocks?.[arm] : undefined;\n // A Redesign arm: a composed section borrowing the site's own class lists.\n const composed = arm !== '' ? config?.compose?.[arm] : undefined;\n // A form tree without a handler is refused WHOLE (children render instead):\n // dropping just the form node would show a section minus its call-to-action —\n // looks live, converts nothing. Same rule the snippet applies.\n const formBlocked =\n ((tree !== undefined && containsFormBlock(tree)) || (composed !== undefined && containsFormBlock(composed.tree))) && !onFormSubmit;\n\n useEffect(() => {\n if (!formBlocked || !isDevBuild() || warnedFormSlots.has(id)) return;\n warnedFormSlots.add(id);\n console.warn(\n `[sentient] AdaptiveSlot \"${id}\" was served a form arm but has no onFormSubmit handler — ` +\n `rendering its baseline children instead. Pass onFormSubmit to render generated forms.`,\n );\n }, [formBlocked, id]);\n\n const fireFormGoal = (goalName: string): void => {\n if (!client || source === 'override') return;\n // componentGoal credits the optimizer (arm resolved from slot state);\n // goal() writes the session funnel record — the slot-goal shape\n // (use-adaptive-tokens). Field values are NOT on either write. A seeded\n // (not-yet-decided) arm keeps the session goal — the visitor did convert —\n // but not the arm credit: close-out would hand it to whichever arm this\n // session's decide draws afterwards.\n if (source !== 'seeded') client.componentGoal(id, goalName);\n client.goal(goalName, { metadata: { componentId: id, arm }, weight: 1.0, stepIndex: 0 });\n };\n\n // Precedence: served arm's block tree, else served content string, else the\n // developer's children. content/blocks are mutually exclusive on purpose —\n // the snippet's \"content overwrites blocks' textContent\" ordering hazard\n // (apply.ts) must not be reproduced here.\n let body: ReactNode = children;\n // True when the served arm never reaches the page: the form gate refused\n // its tree, renderBlocks returned root-level null (unknown ROOT node from a\n // newer server), or its copy had no text in children to land on. The\n // children shown then are a fallback,\n // not an assignment — the exposure gate below reads this so the arm is not\n // charged an impression it could never convert on.\n let armBlocked = false;\n const authoredArm = arm.startsWith(AUTHORED_PREFIX) ? arm.slice(AUTHORED_PREFIX.length) : null;\n if (config?.blocked === 'variant_history') {\n // Held back server-side: this id's trials live on the variant ledger until\n // the operator migrates it. Nothing was decided; nothing is exposed.\n armBlocked = true;\n } else if (authoredArm !== null) {\n // A served authored arm renders the developer's own JSX. The server only\n // draws keys this page declared, so a miss is an SSR/preload race — render\n // the original and don't expose.\n if (variants && Object.prototype.hasOwnProperty.call(variants, authoredArm)) body = variants[authoredArm];\n else armBlocked = true;\n } else if (composed !== undefined) {\n const rendered = formBlocked ? null : renderCompose(composed, { palette, vocabulary, onFormSubmit, onFormGoal: fireFormGoal });\n if (rendered === null) armBlocked = true;\n else body = rendered;\n } else if (tree !== undefined) {\n const rendered = formBlocked ? null : renderBlocks(tree, { palette, vocabulary, onFormSubmit, onFormGoal: fireFormGoal });\n if (rendered === null) armBlocked = true;\n else body = rendered;\n } else if (config?.edits !== undefined && source !== 'none') {\n // A Rewrite arm: new words (and swaps, hides, reorders) applied to the\n // developer's own elements. Written against a skeleton fingerprint; if the\n // children no longer match it, the edits would land on the wrong element.\n const e = config.edits;\n const placed = e.fp === childFp ? applyEdits(children, e.edits, e.leafToNode) : null;\n if (placed === null) armBlocked = true;\n else body = placed;\n } else if (config?.content !== undefined && source !== 'none') {\n // The copy goes INSIDE the developer's markup (slot-text.ts) — assigning\n // the string to body replaced a styled <button> with bare text.\n const placed = substituteSlotText(children, config.content);\n if (placed === null) armBlocked = true;\n else body = placed;\n }\n const textBlocked =\n armBlocked && tree === undefined && composed === undefined && config?.edits === undefined && authoredArm === null && config?.blocked === undefined;\n\n // Dev: say why a hybrid shows its original instead of experimenting.\n useEffect(() => {\n if (config?.blocked !== 'variant_history' || !isDevBuild() || warnedBlockedSlots.has(id)) return;\n warnedBlockedSlots.add(id);\n console.warn(\n `[sentient] <Adaptive id=\"${id}\"> has results from its earlier variants experiment, so it is showing your ` +\n `original until you migrate it: Matrix → Components → \"${id}\" → Migrate. Deploying code never switches an experiment.`,\n );\n }, [config?.blocked, id]);\n\n // What an authored arm rendered, for the dashboard's arm list and to ground\n // generation in the versions the team wrote (spec §7.4). Core dedupes per\n // (slot, key); the skeleton is parity-checked against that arm's JSX.\n const authoredOnScreen = authoredArm !== null && !armBlocked ? authoredArm : null;\n useEffect(() => {\n if (!authoredOnScreen || !reportBaselineText || !client) return;\n const el = nodeRef.current;\n if (!el) return;\n const cap = captureRegionSkeleton(el);\n const sk = cap.skeleton ? annotateSkeletonForReact(cap.skeleton, variants?.[authoredOnScreen]) : null;\n const text = el.textContent?.trim();\n client.reportSlots([], undefined, undefined, {\n [id]: [{ key: authoredOnScreen, ...(text ? { text } : {}), ...(sk ? { skeleton: sk } : {}) }],\n });\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [authoredOnScreen, client, id, hidden]);\n\n // A served Rewrite arm this page couldn't apply. The decide normally\n // excludes it up front (the page sends its fingerprint), so this fires for\n // SSR preloads, which have no DOM to fingerprint. Enough distinct visitors\n // reporting it suspend the stale skeleton's arms server-side. Previews\n // ('override') and snapshot seeds ('seeded') are not this session's draw.\n const editsDrift = armBlocked && config?.edits !== undefined && (source === 'preloaded' || source === 'client');\n useEffect(() => {\n if (!editsDrift || !config?.edits) return;\n // `client` in deps: it lands after the provider's init effect, and the\n // core dedupes per (slot, fingerprint), so a re-run never double-reports.\n client?.reportDrift?.(id, config.edits.fp, childFp, config.edits.fp === childFp ? 'unaddressable' : 'fp_mismatch');\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [editsDrift, id, childFp, client]);\n\n // A published slot the server has no skeleton for (registered before\n // skeletons existed): fill it from this page, once, while the DOM shows the\n // developer's children and not an arm's rendering of them.\n const showsChildren = body === children;\n useEffect(() => {\n if (!config?.needsSkeleton || !showsChildren) return;\n const sk = captureSkeleton();\n if (sk) client?.reportSkeleton?.(id, sk);\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [config?.needsSkeleton, showsChildren, id, client, hidden]);\n\n // \"Refresh from page\" (operator, editor-token link): the trusted overwrite.\n // The preview module forced the original on screen; capture it here, where\n // the element-tree parity check can run, and post it.\n useEffect(() => {\n if (!showsChildren) return;\n const r = takeRegionRefresh(id);\n if (!r) return;\n const sk = captureSkeleton();\n submitRegionRefresh(r, sk && 'status' in sk ? { status: sk.status } : { skeleton: sk });\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [id, showsChildren, hidden]);\n\n useEffect(() => {\n if (!textBlocked || !isDevBuild() || warnedOpaqueSlots.has(id)) return;\n warnedOpaqueSlots.add(id);\n console.warn(\n `[sentient] <Adaptive id=\"${id}\"> was served a text version, but its children have several separate ` +\n `texts or none Sentient can reach — rendering the original instead. Regenerate the version (new ` +\n `versions edit each text in place), or put a single text inline.`,\n );\n }, [textBlocked, id]);\n\n // Devtools slot registry — arms come from the config's block map (the only\n // arm list the client can see for a registry slot). A slot is NOT a\n // component: registering it as one writes the wrong override channel.\n const armsKey = config?.blocks ? Object.keys(config.blocks).sort().join('|') : '';\n // An <Adaptive> with `variants` answers the VARIANT override channel (see\n // forcedKey above), so it is listed as a component whose buttons write that\n // channel: `baseline` (hybrids only) plus each written key. Registering it as\n // a slot instead showed sentient-ui.com's hero_cta_v4 with no buttons at all\n // (2026-11-02) — a hybrid's written versions are never in a config's blocks.\n const devVariantIds = variants ? [...(variantsOnly ? [] : ['baseline']), ...authoredKey.split('|')].join('|') : '';\n useEffect(() => {\n if (devVariantIds !== '') return registerComponent({ id, variantIds: devVariantIds.split('|') });\n return registerSlot({ id, arms: armsKey === '' ? undefined : armsKey.split('|') });\n }, [id, armsKey, devVariantIds]);\n\n // Exposure — once per (slot, arm). 'none' means the slot was never served\n // (children baseline): recording it would accrue a phantom impression that\n // can never convert. A forced arm ('override') is a preview, not an\n // exposure — same contract as useAdaptiveTokens. armBlocked is the same\n // phantom from the other direction: the arm was served but never rendered\n // (form gate, unknown root block, copy with nowhere to land), so an exposure here would let\n // the bandit permanently bury the arm on this install for a rendering\n // failure. No baseline exposure is reported either — decide didn't assign\n // baseline, the children are just the fail-safe. 'seeded' (last visit's\n // snapshot, not yet decided this session) renders for pre-paint parity but\n // has no slot_decisions row: exposing it trained an arm the server never\n // served this session, then exposed a second arm when the decide landed.\n const exposedArmRef = useRef<string | null>(null);\n useEffect(() => {\n if (!client || source === 'none' || source === 'seeded' || source === 'override' || arm === '' || armBlocked) return;\n if (exposedArmRef.current === arm) return;\n exposedArmRef.current = arm;\n trackExposure(client, apiKey, id, arm);\n }, [client, apiKey, id, arm, source, armBlocked]);\n\n // Optional container goal (click/scroll/composite) — slot-goal shape.\n //\n // Two writes, two different gates, because they answer different questions.\n //\n // `componentGoal` credits an ARM. It is suppressed whenever no arm earned\n // the conversion — nothing decided ('none'), decided-but-not-yet-confirmed\n // ('seeded'), or a served tree that never reached the page (armBlocked) —\n // because a goal stamped with the served arm would let close-out's\n // first-pass reconciliation (goal_achieved counts as an implied exposure,\n // CONTRACTS §2) re-mint the very phantom impression the exposure gate\n // suppressed, plus credit the arm for baseline's conversion.\n //\n // `goal` writes the SESSION funnel record, which is about the visitor, not\n // the arm. It fires whenever a real visitor converts. This effect used to\n // share the exposure gate and record NEITHER, which silently deleted the\n // conversion: measured on prod 2026-09-22 (Bodyshop Manchester), an\n // <Adaptive> switched from `variants` to generated mode registers a DRAFT\n // slot, sits at source 'none' until someone publishes a version, and its CTA\n // recorded nothing for five days while the funnel read 0%. `fireFormGoal`\n // above already makes exactly this split for a seeded arm; the container\n // goal disagreeing with it thirty lines away was the bug.\n //\n // 'override' is the one source that still records NOTHING: a forced arm is a\n // devtools/test preview, and a conversion nobody made must not reach either\n // write.\n //\n // When the arm is not creditable the session record carries NO arm either:\n // '' is the same shape an undecided slot already writes, and stamping the\n // arm the visitor never saw would re-introduce the attribution through the\n // metadata after the componentGoal write had been suppressed.\n const armCreditable = source !== 'none' && source !== 'seeded' && !armBlocked;\n const goalArm = armCreditable ? arm : '';\n const goalKey = goal === undefined ? null : typeof goal === 'string' ? goal : JSON.stringify(goal);\n useEffect(() => {\n if (!client || !goal || source === 'override') return;\n const node = nodeRef.current;\n if (!node) return;\n const label = goalLabelOf(goal);\n const declaredValue = goalValueOf(goal);\n let fired = false;\n return attachGoalListeners(\n node,\n normalizeGoal(goal),\n {\n fireGoal: () => {\n if (fired) return;\n fired = true;\n if (armCreditable) {\n if (declaredValue !== undefined) client.componentGoal(id, label, { value: declaredValue });\n else client.componentGoal(id, label);\n }\n client.goal(label, {\n metadata: { componentId: id, arm: goalArm },\n weight: 1.0,\n stepIndex: 0,\n ...(declaredValue !== undefined ? { value: declaredValue } : {}),\n });\n },\n fireStep: (name, weight, stepIndex) => {\n if (armCreditable) client.componentGoal(id, name, { reward: weight });\n client.goal(name, { metadata: { componentId: id, arm: goalArm }, weight, stepIndex });\n },\n },\n label,\n );\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [client, id, goalKey, arm, source, armBlocked, armCreditable, goalArm, hidden]);\n\n // Funnel membership — the declaration is about the COMPONENT, not an arm, so\n // it needs no served arm (an unpublished component still belongs to its\n // funnel); a forced preview must not declare anything, as on the variants\n // path. Needs a goal: the declaration carries the goal's steps. A weighted\n // composite with no `funnel` declares its own (compositeFunnelId).\n const goalConfig = useMemo(\n () => (goal ? normalizeGoal(goal) : null),\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [goalKey],\n );\n useEffect(() => {\n if (source === 'override' || !client || !goalConfig) return;\n maybeDeclareFunnel(client, apiKey, id, funnel, goalConfig);\n }, [client, apiKey, id, funnel, goalConfig, source]);\n\n // Passive micro-signals → optional named goal. Gated on armCreditable like\n // the container goal: before an arm is served (or when it never rendered) a\n // rage-click would record a micro_signal against an arm nobody saw. The\n // mapping is read through a ref and keyed on its CONTENT — an inline literal\n // is a new object every render, and re-attaching resets the detectors'\n // once-per-attach latches (the same bug use-variant-component fixed).\n const microRef = useRef(microSignalGoals);\n microRef.current = microSignalGoals;\n // Latched for the COMPONENT's lifetime, not per attach: an arm change\n // re-attaches the detectors, and a per-attach latch let one visitor fire the\n // same mapped goal once per arm (use-variant-component latches per variant\n // for the same reason it must not double-fire).\n const microFiredRef = useRef<Set<string>>(new Set());\n const microKey = microSignalGoals ? JSON.stringify(microSignalGoals) : '';\n useEffect(() => {\n if (!client || source === 'override' || !armCreditable || arm === '') return;\n const node = nodeRef.current;\n if (!node) return;\n return attachMicroSignalDetectors(\n (signalType, extra = {}) => {\n client.track({\n projectId: apiKey,\n componentId: id,\n variantId: arm,\n eventType: 'micro_signal',\n payload: { signalType, ...extra },\n });\n const mapping = microRef.current?.[signalType];\n if (!mapping || microFiredRef.current.has(signalType)) return;\n microFiredRef.current.add(signalType);\n const name = typeof mapping === 'string' ? mapping : mapping.name;\n const weight = typeof mapping === 'string' ? 1.0 : (mapping.weight ?? 1.0);\n const stepIndex = typeof mapping === 'string' ? 0 : (mapping.stepIndex ?? 0);\n // Session goal ONLY, as on the variants path. componentGoal on a slot\n // feeds computeSlotCredit (closeout), so a rage click would reward the\n // version that was on screen — a scoring bug, not parity.\n client.goal(name, { metadata: { componentId: id, arm, signalType, ...extra }, weight, stepIndex });\n },\n node,\n Date.now(),\n );\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [client, apiKey, id, arm, source, armCreditable, microKey, hidden]);\n\n // Agent data for the SERVED arm only (agents see what visitors see). A\n // hand-written arm is looked up by its authored key — the key the developer\n // wrote — and any other arm by its id. With agentDataByVariant given it alone decides (an\n // arm missing from it sends nothing, as /v1/assign); agentData alone is the\n // shorthand for every served arm.\n // Read through refs: captured at mount, like the variants path.\n const agentRef = useRef({ agentData, agentDataByVariant });\n agentRef.current = { agentData, agentDataByVariant };\n const agentSentRef = useRef<string | null>(null);\n useEffect(() => {\n if (!client || source === 'override' || !armCreditable || arm === '') return;\n if (agentSentRef.current === arm) return;\n const { agentData: fallback, agentDataByVariant: byArm } = agentRef.current;\n const lookup = authoredArm ?? arm;\n // As /v1/assign: when agentDataByVariant is given it ALONE decides; an arm\n // missing from it sends nothing (agentData is only the no-map shorthand).\n const data = byArm !== undefined ? (Object.prototype.hasOwnProperty.call(byArm, lookup) ? byArm[lookup] : undefined) : fallback;\n if (data === undefined) return;\n agentSentRef.current = arm;\n client.reportAgentData?.(id, arm, data);\n }, [client, id, arm, armCreditable, authoredArm, source]);\n\n // The adaptation reveal. Fires only when the ARM CHANGES after mount — an\n // SSR-rendered slot arrives with its arm already in the HTML, so the page was\n // always that way and animating it would be theatre on every page load. The\n // cases this does catch are the ones a visitor should notice: a client-side\n // decide resolving, and a persona upgrade re-deciding on a return visit.\n const revealedArm = useRef<string | null>(null);\n useEffect(() => {\n const node = nodeRef.current;\n if (!node) return;\n // First observation is the mounted state, whatever it is — record and stop.\n if (revealedArm.current === null) {\n revealedArm.current = arm;\n return;\n }\n if (revealedArm.current === arm) return;\n revealedArm.current = arm;\n // `previous` is deliberately omitted: React has already swapped the\n // children by the time this effect runs, so the pre-change text is gone and\n // the arm change is itself the evidence that something changed. The arm is\n // not passed either — `dataProps` already stamps `data-sentient-arm`, and\n // writing it twice would let the two drift.\n reveal(node);\n }, [arm, hidden]);\n\n const dataProps = useMemo(\n () => ({ 'data-sentient-slot': id, ...(arm !== '' ? { 'data-sentient-arm': arm } : {}) }),\n [id, arm],\n );\n\n if (hidden) return null;\n\n return (\n <Tag ref={nodeRef as Ref<never>} className={className} {...dataProps}>\n {body}\n </Tag>\n );\n}\n","import { useCallback, useEffect, useRef, useSyncExternalStore } from 'react';\nimport { armOfResult, type RenderCaps, type SitePalette, type SkeletonReport, type SlotConfigEntry, type SlotResult, type StyleVocabulary } from '@sentientui/core';\nimport { useInitialPalette, useInitialSlotConfig, useInitialSlots, useInitialVocabulary, useSentient } from './provider.js';\nimport { subscribeOverridesChanged } from './override-events.js';\nimport { getVocabularyOverride } from './devtools-slot-config-overrides.js';\nimport { isDevBuild } from './adaptive-shared.js';\n\n// Warn once per slot id per page lifetime, not per render.\nconst warnedUnservedSlots = new Set<string>();\n// One shared object: a fresh one per render would read as a config change.\nconst FORCED_ARM_CONFIG: SlotConfigEntry = { kind: 'arms' };\n\ndeclare global {\n interface Window {\n /** Test/devtools forcing: slot id → forced config entry (applyScenario sets this). */\n __sentient_slot_config_overrides?: Record<string, SlotConfigEntry>;\n }\n}\n\nexport type SlotConfigResolution = {\n config: SlotConfigEntry | null;\n /** Served arm for the slot ('' when unknown). */\n arm: string;\n palette: SitePalette | null;\n /** Site styles served Redesign arms borrow (SSR seed, else the client's). */\n vocabulary: StyleVocabulary | null;\n /**\n * `client` = decided for this session; `seeded` = the core holds config\n * from an earlier visit's snapshot that this session has not decided yet.\n * Seeded config renders (pre-paint parity) but is not exposed or credited —\n * there is no slot_decisions row for it until requestSlots answers.\n */\n source: 'override' | 'preloaded' | 'client' | 'seeded' | 'none';\n};\n\n/**\n * Internal. Resolves the registry slot config AdaptiveSlot renders, synchronously:\n * test/devtools override → SSR-preloaded `initialSlotConfig` → core client state\n * (registry decide, snapshot seed) → none (render baseline children).\n * Purely read-side: exposure/goal wiring belongs to AdaptiveSlot.\n */\nexport function useSlotConfig(\n slotId: string,\n opts?: {\n /** Read the region's rendered baseline text at registration time (only\n * called when the slot is unserved and about to self-register). Kept in\n * a ref so an inline arrow never re-fires the effect. */\n baselineText?: () => string | null;\n /** What this mounted slot can render (CONTRACTS §2) — sent with the\n * scoped decide so the server never draws an arm the page would refuse. */\n render?: () => RenderCaps;\n /** Capture the region's skeleton. Only called while the wrapper shows the\n * developer's children — never an arm's rendering of them. */\n skeleton?: () => SkeletonReport | null;\n /** Hold the request until false. A clientOnly slot has no wrapper element on\n * its first commit, so asking then sent no baseline text or skeleton — and\n * the ask is deduped forever per id, so they were never sent. */\n defer?: boolean;\n /** A forced arm from the VARIANT dev-override channel, already mapped to\n * its arm id (`authored.<key>`) — a migrated variants-only <Adaptive>\n * (ruling C24). Resolves as source 'override': rendered, never exposed,\n * never decided, exactly like a forced slot config. */\n forcedArm?: string | null;\n },\n): SlotConfigResolution {\n const client = useSentient();\n const baselineTextRef = useRef(opts?.baselineText);\n baselineTextRef.current = opts?.baselineText;\n const renderRef = useRef(opts?.render);\n renderRef.current = opts?.render;\n const skeletonRef = useRef(opts?.skeleton);\n skeletonRef.current = opts?.skeleton;\n const initialSlots = useInitialSlots();\n const initialSlotConfig = useInitialSlotConfig();\n const initialPalette = useInitialPalette();\n const initialVocabulary = useInitialVocabulary();\n\n // Same useSyncExternalStore discipline as useSlotResult: the server snapshot\n // returns undefined so SSR HTML and the pre-hydration client render agree\n // even when a Playwright/Cypress mock wrote the override before hydration.\n // The snapshot returns the stored object by reference (stable until the\n // override bus notifies), so it passes React's Object.is caching check.\n const overrideConfig = useSyncExternalStore(\n subscribeOverridesChanged,\n () => (typeof window !== 'undefined' ? window.__sentient_slot_config_overrides?.[slotId] : undefined),\n () => undefined,\n );\n const overrideResult = useSyncExternalStore(\n subscribeOverridesChanged,\n () => (typeof window !== 'undefined' ? window.__sentient_slot_overrides?.[slotId] : undefined),\n () => undefined,\n );\n\n const armOf = (r: SlotResult | null | undefined): string => (r == null ? '' : armOfResult(r));\n\n // Re-render when the client's slot state changes — a mounted-slot decide\n // (requestSlots) answers after first paint. Values are still read below;\n // these two hooks only make React notice the change. Both snapshots are\n // stable between notifications (stored object by reference / arm string).\n const subscribeSlots = useCallback(\n (cb: () => void) => client?.onSlotsChanged?.(cb) ?? (() => undefined),\n [client],\n );\n useSyncExternalStore(subscribeSlots, () => client?.getSlotConfig(slotId) ?? null, () => null);\n useSyncExternalStore(subscribeSlots, () => armOf(client?.getSlotResult(slotId)), () => '');\n\n const preloaded = overrideConfig === undefined ? initialSlotConfig[slotId] : undefined;\n const fromClient =\n overrideConfig === undefined && preloaded === undefined && client ? client.getSlotConfig(slotId) : null;\n\n const palette = initialPalette ?? client?.getSitePalette() ?? null;\n const vocabulary = initialVocabulary ?? client?.getStyleVocabulary?.() ?? null;\n\n // No local-mode decide here, deliberately: the local engine has no registry\n // concept — decide({ slotsFrom: 'registry' }) ran the whole engine once per\n // mounted slot and could never produce a slotConfig (local getSlotConfig\n // reads only the initialSlotConfig SSR seed). Local slots resolve\n // synchronously from that seed or fall through to children; the dev warning\n // below says so instead of burning an engine run per mount.\n\n const resolution: SlotConfigResolution = (() => {\n if (overrideConfig !== undefined) {\n return { config: overrideConfig, arm: armOf(overrideResult), palette, vocabulary: getVocabularyOverride() ?? vocabulary, source: 'override' };\n }\n if (opts?.forcedArm) {\n return { config: FORCED_ARM_CONFIG, arm: opts.forcedArm, palette, vocabulary, source: 'override' };\n }\n if (preloaded !== undefined) {\n return { config: preloaded, arm: armOf(initialSlots[slotId] ?? client?.getSlotResult(slotId)), palette, vocabulary, source: 'preloaded' };\n }\n if (fromClient !== null) {\n const decided = client?.isSlotDecided ? client.isSlotDecided(slotId) : true;\n return {\n config: fromClient,\n arm: armOf(client?.getSlotResult(slotId) ?? initialSlots[slotId]),\n palette,\n vocabulary,\n source: decided ? 'client' : 'seeded',\n };\n }\n return { config: null, arm: '', palette, vocabulary, source: 'none' };\n })();\n\n // Keyed clients ask the server for THIS mounted slot: one decide scoped to\n // the ids actually on the page (batched per commit), which also registers it\n // as a draft when nothing is published. This used to be registration only —\n // no client-side registry decide existed, so outside an SSR registry preload\n // (which AdaptiveRoot never did) a slot rendered its children forever and\n // never served a generated version. Snapshot-seeded ('client') slots still\n // ask: the snapshot is the last visit's answer, and this session needs its\n // own decision (or to learn the slot was unpublished). Preloaded and forced\n // slots already have this session's answer.\n const deferred = opts?.defer === true;\n const settled = resolution.source === 'preloaded' || resolution.source === 'override';\n useEffect(() => {\n if (!client || client.isLocal === true || settled || deferred) return;\n // Children are on screen only while unserved — that is the only moment the\n // wrapper's text is the baseline generation should be grounded in.\n const unserved = resolution.source === 'none';\n const text = unserved ? baselineTextRef.current?.() ?? null : null;\n const texts = text != null && text !== '' ? { [slotId]: text } : undefined;\n const caps = renderRef.current?.();\n const skeleton = unserved ? skeletonRef.current?.() ?? null : null;\n // Trailing arguments only when there is something to send: hand-rolled\n // clients and older cores see exactly the call they always did.\n const extras = {\n ...(caps ? { render: { [slotId]: caps } } : {}),\n ...(skeleton ? { skeletons: { [slotId]: skeleton } } : {}),\n };\n const hasExtras = Object.keys(extras).length > 0;\n if (client.requestSlots) {\n if (hasExtras) client.requestSlots([slotId], texts, extras);\n else if (texts) client.requestSlots([slotId], texts);\n else client.requestSlots([slotId]);\n } else if (unserved) {\n if (skeleton) client.reportSlots([slotId], texts ?? {}, { [slotId]: skeleton });\n else if (texts) client.reportSlots([slotId], texts);\n else client.reportSlots([slotId]);\n }\n // Unmounted before the batch was sent (redirecting route, StrictMode\n // probe): withdraw it — a slot that is not on the page is not a trial.\n return () => client.cancelSlots?.([slotId]);\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [client, settled, resolution.source, slotId, deferred]);\n\n // Dev-only: local/keyless mode has no registry, so an unserved slot renders\n // its children all session and looks identical to a healthy holdout.\n useEffect(() => {\n if (!isDevBuild() || client?.isLocal !== true || resolution.source !== 'none') return;\n if (warnedUnservedSlots.has(slotId)) return;\n warnedUnservedSlots.add(slotId);\n console.warn(\n `[sentient] <Adaptive id=\"${slotId}\"> is rendering its baseline children: in local/keyless mode ` +\n `<Adaptive> serves ONLY what you pass as \\`initialSlotConfig\\` (there is no registry to decide from). ` +\n `Pass initialSlotConfig/initialSlots to <AdaptiveProvider> to preview arms locally.`,\n );\n }, [client, resolution.source, slotId]);\n\n return resolution;\n}\n","import { cloneElement, Fragment, type CSSProperties, type JSX } from 'react';\nimport type { BlockNode, ComposeArm, FormBlock, SitePalette, StyleVocabulary } from '@sentientui/core';\n\n/** A block's href/src, or undefined unless absolute https or a site-relative\n * path — the rule the server validates (twin of the snippet's `safeBlockUrl`\n * in ops.ts). The renderer is the last line: a stale config or a bypassed\n * validator must not render `javascript:` into an <a> (audit S14). React\n * itself only warns on `javascript:` URLs; it does not block them. */\nfunction safeBlockUrl(v: unknown): string | undefined {\n // Whitespace/control chars rejected: browsers strip tab/newline, so\n // `/\\t/evil.example` would become `//evil.example`.\n return typeof v === 'string' && !/[\\s\\x00-\\x1f\\\\]/.test(v) && (/^https:\\/\\//i.test(v) || (v[0] === '/' && v[1] !== '/')) ? v : undefined;\n}\n\n// React Composition Block renderer (spec 2026-09-08 empty-cell-generation §3).\n// JSX from typed props ONLY — no dangerouslySetInnerHTML exists on this path,\n// preserving the \"no HTML ever accepted\" security property. The server has\n// total-validated every tree before publish; render still fail-safes per node\n// (an unknown type from a NEWER server renders nothing rather than throwing,\n// so a version-skewed bundle degrades to a partial arm, never a broken page —\n// the same contract packages/snippet/src/blocks.ts pins in its tests).\n\n// Token → CSS maps, ported verbatim from packages/snippet/src/blocks.ts:31-38.\n// The drift-pin test in @sentientui/core blocks.test.ts is what keeps the three\n// parties (server validator, snippet renderer, this file) agreeing.\nconst GAP: Record<string, string> = { none: '0', sm: '8px', md: '16px', lg: '24px' };\nconst FLEX_POS: Record<string, string> = { start: 'flex-start', center: 'center', end: 'flex-end', stretch: 'stretch', between: 'space-between' };\nconst FONT_SIZE: Record<string, string> = { sm: '0.875em', md: '1em', lg: '1.25em' };\nconst HEADING_SIZE: Record<string, string> = { sm: '1.25em', md: '1.5em', lg: '2em' };\nconst BTN_PAD: Record<string, string> = { sm: '6px 14px', md: '10px 20px', lg: '14px 28px' };\nconst SPACER: Record<string, string> = { sm: '8px', md: '16px', lg: '32px' };\nconst RATIO: Record<string, string> = { square: '1 / 1', landscape: '4 / 3', wide: '16 / 9' };\nconst WEIGHT: Record<string, string> = { normal: '400', medium: '500', bold: '700' };\n\nexport type RenderBlocksOptions = {\n palette: SitePalette | null;\n /** The site styles a Redesign tree borrows (native generation phase 2). */\n vocabulary?: StyleVocabulary | null;\n /** Absent handler = form trees must not reach this function (AdaptiveSlot gates). */\n onFormSubmit?: (values: Record<string, string>) => void;\n /** Fired with the form's submitGoal when a rendered form submits. */\n onFormGoal?: (goal: string) => void;\n};\n\nfunction toneStyles(tone: string | undefined, palette: SitePalette | null): CSSProperties {\n // Brand tokens when the palette carries them; the original neutral\n // fallbacks otherwise, so pre-token palettes render exactly as before.\n return {\n ...(tone === 'muted' ? (palette?.muted ? { color: palette.muted } : { opacity: 0.7 }) : {}),\n ...(tone === 'accent' ? { fontWeight: 600, ...(palette?.accent ? { color: palette.accent } : {}) } : {}),\n };\n}\n\nfunction buttonStyle(emphasis: string, palette: SitePalette | null, size?: string): CSSProperties {\n // Mirrors the snippet's button case (blocks.ts): palette tokens when\n // available, neutral inherit-first defaults otherwise. Secondary/ghost\n // resolve to the ACCENT — before brand tokens they rendered in\n // currentColor/inherit, which made every non-primary button look like\n // body text on brand-heavy sites.\n const accent = palette?.accent;\n return {\n display: 'inline-block',\n padding: BTN_PAD[size ?? 'md'] ?? BTN_PAD['md'],\n borderRadius: palette?.radius ?? '8px',\n font: 'inherit',\n ...(size ? { fontSize: FONT_SIZE[size] } : {}),\n textDecoration: emphasis === 'ghost' ? 'underline' : 'none',\n cursor: 'pointer',\n background: emphasis === 'primary' ? (palette?.primaryBg ?? '#111827') : 'transparent',\n color:\n emphasis === 'primary'\n ? (palette?.primaryText ?? '#ffffff')\n : (accent ?? 'inherit'),\n border: emphasis === 'secondary' ? `1px solid ${accent ?? 'currentColor'}` : 'none',\n };\n}\n\nfunction FormNode({ node, opts }: { node: FormBlock; opts: RenderBlocksOptions }): JSX.Element {\n const emphasis = node.emphasis ?? 'primary';\n const fieldStyle: CSSProperties = {\n padding: '8px 10px',\n font: 'inherit',\n border: `1px solid ${opts.palette?.border ?? 'currentColor'}`,\n borderRadius: opts.palette?.radius ?? '8px',\n };\n return (\n <form\n onSubmit={(e) => {\n e.preventDefault();\n const data = new FormData(e.currentTarget);\n const values: Record<string, string> = {};\n for (const f of node.fields) values[f.name] = String(data.get(f.name) ?? '');\n // Goal first: the conversion must be credited even if the site's own\n // handler throws — their bug must not cost them the learning signal.\n // Values go ONLY to the site's handler, never into any tracked payload.\n opts.onFormGoal?.(node.submitGoal);\n try {\n opts.onFormSubmit?.(values);\n } catch {\n /* site handler error is theirs to see in their own console */\n }\n }}\n style={{ display: 'flex', flexDirection: 'column', gap: '12px' }}\n >\n {node.fields.map((f) => (\n <label key={f.name} style={{ display: 'flex', flexDirection: 'column', gap: '4px', font: 'inherit' }}>\n {f.label}\n {f.kind === 'textarea' ? (\n <textarea name={f.name} required={f.required} placeholder={f.placeholder} rows={3} style={fieldStyle} />\n ) : f.kind === 'select' ? (\n <select name={f.name} required={f.required} style={fieldStyle}>\n {(f.options ?? []).map((o) => (\n <option key={o} value={o}>\n {o}\n </option>\n ))}\n </select>\n ) : (\n <input\n name={f.name}\n type={f.inputType ?? 'text'}\n required={f.required}\n placeholder={f.placeholder}\n style={fieldStyle}\n />\n )}\n </label>\n ))}\n <button type=\"submit\" style={buttonStyle(emphasis, opts.palette)}>\n {node.submitLabel}\n </button>\n </form>\n );\n}\n\n/** Render one validated block tree as JSX. Null for anything unrenderable — fail-safe. */\n/** The site's own class list for a node that borrows one, or undefined —\n * then the node renders with palette styling exactly as before (a dropped\n * vocabulary entry degrades, never blanks). */\nfunction classOf(node: BlockNode, opts: RenderBlocksOptions): string | undefined {\n const like = (node as { like?: string }).like;\n return like ? opts.vocabulary?.entries.find((e) => e.id === like)?.classes : undefined;\n}\n\n/** The measured text colour of a borrowed style whose class list doesn't set\n * one (StyleEntry.computed.inheritsColor) — applied to the element, or it\n * inherits whatever colour its new surroundings have. */\nfunction inheritedColor(like: string | undefined, opts: RenderBlocksOptions): string | undefined {\n const e = like ? opts.vocabulary?.entries.find((x) => x.id === like) : undefined;\n return e?.computed.inheritsColor ? e.computed.color : undefined;\n}\n\nexport function renderBlocks(node: BlockNode, opts: RenderBlocksOptions): JSX.Element | null {\n const el = renderOwn(node, opts);\n const color = inheritedColor((node as { like?: string }).like, opts);\n return el && color ? cloneElement(el, { style: { ...((el.props as { style?: CSSProperties }).style ?? {}), color } }) : el;\n}\n\nfunction renderOwn(node: BlockNode, opts: RenderBlocksOptions): JSX.Element | null {\n try {\n // A borrowed class list is the site's own styling: when it resolves, the\n // node keeps only LAYOUT styles (flex/grid/gap/pad/align, image fit,\n // measure) and none of the palette paint — colors, borders, radius and\n // type come from the site's CSS.\n const cls = classOf(node, opts);\n switch (node.type) {\n case 'stack': {\n // Same unknown-token fallback as the grid below (audit SNIP-11).\n const gap = GAP[node.gap ?? 'md'] ?? GAP['md'];\n // Rung 1: pad reuses the GAP scale; a raised stack with no pad\n // defaults to md (a zero-padding card is a design bug, not a choice).\n // Mirrors packages/snippet/src/blocks.ts — the drift-pin test is what\n // keeps the two renderers agreeing on these literals.\n const raised = node.surface === 'raised' && !cls;\n const pad = node.pad ?? (raised ? 'md' : undefined);\n return (\n <div\n {...(cls ? { className: cls } : {})}\n style={{\n display: 'flex',\n flexDirection: node.direction,\n gap,\n ...(node.align ? { alignItems: FLEX_POS[node.align] } : {}),\n ...(node.justify ? { justifyContent: FLEX_POS[node.justify] } : {}),\n ...(node.wrap ? { flexWrap: 'wrap' } : {}),\n ...(pad ? { padding: GAP[pad] ?? GAP['md'] } : {}),\n ...(raised\n ? {\n ...(opts.palette?.surface ? { background: opts.palette.surface } : {}),\n ...(opts.palette?.surface && opts.palette?.surfaceText ? { color: opts.palette.surfaceText } : {}),\n border: `1px solid ${opts.palette?.border ?? 'currentColor'}`,\n borderRadius: opts.palette?.radius ?? '8px',\n }\n : {}),\n }}\n >\n {(node.children ?? []).map((child, i) => {\n const rendered = renderBlocks(child, opts);\n return rendered === null ? null : <Fragment key={i}>{rendered}</Fragment>;\n })}\n </div>\n );\n }\n case 'grid': {\n // Responsive by construction — identical template to the snippet\n // (blocks.ts:84): auto-fit collapses on narrow screens, the calc()\n // floor keeps each item at an exact 1/columns share on wide ones.\n const gap = GAP[node.gap ?? 'md'] ?? GAP['md']!;\n return (\n <div\n {...(cls ? { className: cls } : {})}\n style={{\n display: 'grid',\n gridTemplateColumns: `repeat(auto-fit, minmax(max(200px, calc((100% - ${node.columns - 1} * ${gap}) / ${node.columns})), 1fr))`,\n gap,\n ...(node.align ? { alignItems: FLEX_POS[node.align] } : {}),\n ...(node.pad ? { padding: GAP[node.pad] ?? GAP['md'] } : {}),\n }}\n >\n {(node.children ?? []).map((child, i) => {\n const rendered = renderBlocks(child, opts);\n return rendered === null ? null : <Fragment key={i}>{rendered}</Fragment>;\n })}\n </div>\n );\n }\n case 'text':\n if (cls) {\n return (\n <p className={cls} style={node.maxWidth === 'measure' ? { maxWidth: '65ch' } : undefined}>\n {node.value}\n </p>\n );\n }\n return (\n <p\n style={{\n margin: 0,\n ...(node.size ? { fontSize: FONT_SIZE[node.size] } : {}),\n ...(node.weight ? { fontWeight: WEIGHT[node.weight] } : {}),\n ...(node.align ? { textAlign: node.align } : {}),\n ...(node.maxWidth === 'measure' ? { maxWidth: '65ch' } : {}),\n ...toneStyles(node.tone, opts.palette),\n }}\n >\n {node.value}\n </p>\n );\n case 'heading': {\n const Tag = `h${node.level}` as 'h1' | 'h2' | 'h3' | 'h4';\n if (cls) {\n return (\n <Tag className={cls} style={node.maxWidth === 'measure' ? { maxWidth: '65ch' } : undefined}>\n {node.value}\n </Tag>\n );\n }\n return (\n <Tag\n style={{\n margin: 0,\n fontSize: HEADING_SIZE[node.size ?? 'md'],\n ...(node.align ? { textAlign: node.align } : {}),\n ...(node.maxWidth === 'measure' ? { maxWidth: '65ch' } : {}),\n }}\n >\n {node.value}\n </Tag>\n );\n }\n case 'button': {\n const emphasis = node.emphasis ?? 'primary';\n return (\n <a\n href={safeBlockUrl(node.href)}\n {...(node.tag ? { 'data-sentient-tag': node.tag } : {})}\n {...(cls ? { className: cls } : { style: buttonStyle(emphasis, opts.palette, node.size) })}\n >\n {node.label}\n </a>\n );\n }\n case 'link':\n return (\n <a\n href={safeBlockUrl(node.href)}\n {...(node.tag ? { 'data-sentient-tag': node.tag } : {})}\n {...(cls ? { className: cls } : { style: { color: 'inherit', textDecoration: 'underline' } })}\n >\n {node.label}\n </a>\n );\n case 'image':\n return (\n <img\n src={safeBlockUrl(node.src)}\n alt={node.alt}\n {...(cls ? { className: cls } : {})}\n style={{\n display: 'block',\n maxWidth: '100%',\n ...(node.ratio && node.ratio !== 'auto' ? { aspectRatio: RATIO[node.ratio], width: '100%' } : {}),\n ...(node.fit ? { objectFit: node.fit } : {}),\n }}\n />\n );\n case 'badge':\n if (cls) return <span className={cls}>{node.value}</span>;\n return (\n <span\n style={{\n display: 'inline-block',\n padding: '2px 10px',\n borderRadius: '999px',\n fontSize: '0.75em',\n border: `1px solid ${opts.palette?.border ?? 'currentColor'}`,\n ...toneStyles(node.tone, opts.palette),\n }}\n >\n {node.value}\n </span>\n );\n case 'spacer':\n return <div style={{ height: SPACER[node.size] ?? SPACER['md'] }} />;\n case 'divider':\n // <hr> for semantics; border-top (not the default inset border) so the\n // hairline matches form fields and badges in the palette border color.\n return (\n <hr\n style={{\n border: 'none',\n borderTop: `1px solid ${opts.palette?.border ?? 'currentColor'}`,\n margin: 0,\n width: '100%',\n }}\n />\n );\n case 'form':\n return <FormNode node={node} opts={opts} />;\n default:\n return null; // newer-server node type — skip, never throw\n }\n } catch {\n return null; // fail-safe\n }\n}\n\n/**\n * A Redesign (compose) arm: the tree, painted on a site section/card surface\n * when its style resolves. Null when the tree's root can't render (a newer\n * server's node type) — the caller treats that like a blocked blocks arm.\n */\nexport function renderCompose(compose: ComposeArm, opts: RenderBlocksOptions): JSX.Element | null {\n const body = renderBlocks(compose.tree, opts);\n if (body === null) return null;\n const surface = compose.surface?.like ? opts.vocabulary?.entries.find((e) => e.id === compose.surface!.like)?.classes : undefined;\n const color = inheritedColor(compose.surface?.like, opts);\n return surface ? <div className={surface} {...(color ? { style: { color } } : {})}>{body}</div> : body;\n}\n","import { cloneElement, isValidElement, type ReactElement, type ReactNode } from 'react';\nimport type { ArmEdits, RegionSkeleton } from '@sentientui/core';\nimport { normalizeLeafText, skeletonFingerprint } from '@sentientui/core/region';\n\n// A served content arm is COPY, not a component. AdaptiveSlot used to render\n// it as `body = config.content` — the developer's children thrown away whole —\n// so an <Adaptive> wrapping a styled <button> served a bare string in a div:\n// the site's button, its classes and its icon all gone (observed on Bodyshop,\n// 2026-09-23; the generated arm was never approved because it looked broken).\n// The copy has to land INSIDE the element the developer wrote.\n//\n// Stricter than the snippet's `applyContentText` fallback (textContent on the\n// target): React has no target element to keep, only the developer's tree.\n// - exactly one visible text leaf → only that leaf changes; every element,\n// class, icon and sibling around it survives.\n// - anything else (zero leaves, or several) → null. Several leaves means the\n// region has structure one string cannot fill (Bodyshop's two buttons\n// flattened into a sentence, 2026-09-23); zero means the text lives where\n// the tree can't see it (`label={…}`, i18n components). The caller renders\n// children and — since phase 1 — declares the region unable to render\n// content arms (RenderCaps.content = false), so none is ever drawn.\n\nfunction isTextLeaf(node: ReactNode): node is string | number {\n return (typeof node === 'string' && node.trim() !== '') || typeof node === 'number';\n}\n\nfunction childrenOf(el: ReactElement): ReactNode {\n const props = el.props as { children?: ReactNode; dangerouslySetInnerHTML?: unknown };\n // Raw HTML is opaque to the tree walk — its text is not a leaf we can swap,\n // and descending into `children` beside it would find nothing anyway.\n if (props.dangerouslySetInnerHTML != null) return undefined;\n return props.children;\n}\n\nexport function countTextLeaves(node: ReactNode): number {\n if (isTextLeaf(node)) return 1;\n if (Array.isArray(node)) return node.reduce<number>((n, c) => n + countTextLeaves(c as ReactNode), 0);\n if (isValidElement(node)) return countTextLeaves(childrenOf(node));\n return 0;\n}\n\n/** Re-parent children onto a clone. Arrays are spread as separate arguments —\n * the same shape JSX's static children have — so unkeyed siblings the\n * developer wrote don't start raising key warnings just because we cloned. */\nfunction withChildren(el: ReactElement, children: ReactNode): ReactElement {\n return Array.isArray(children) ? cloneElement(el, undefined, ...(children as ReactNode[])) : cloneElement(el, undefined, children);\n}\n\nfunction replaceOnlyLeaf(node: ReactNode, text: string): ReactNode {\n if (isTextLeaf(node)) return text;\n if (Array.isArray(node)) return node.map((c) => replaceOnlyLeaf(c as ReactNode, text));\n if (isValidElement(node)) {\n const inner = childrenOf(node);\n // Untouched subtrees keep their identity — no clone, no remount.\n if (countTextLeaves(inner) === 0) return node;\n return withChildren(node, replaceOnlyLeaf(inner, text));\n }\n return node;\n}\n\n/**\n * The developer's children with a content arm's copy placed inside them, or\n * null when the region doesn't have exactly one text to replace (see above).\n */\nexport function substituteSlotText(children: ReactNode, text: string): ReactNode | null {\n return countTextLeaves(children) === 1 ? replaceOnlyLeaf(children, text) : null;\n}\n\n// ── Per-node edits (spec 2026-09-23 §4.5, Rewrite) ──────────────────────────\n// A generated `edits` arm names nodes of the region skeleton the DOM capture\n// produced. React applies it over the ELEMENT TREE, not the DOM, so SSR and\n// hydration render the same thing. The bridge is the leaf order: the capture\n// only reports a skeleton when the tree's text leaves equal the DOM's\n// (annotateSkeletonForReact), so leaf i here is leaf i there, and\n// `leafToNode[i]` says which node owns it.\n\n// A position in the tree: array indices, and 'c' for \"into this element's\n// children\". An element's path is always followed by 'c' in its leaves' paths.\ntype Step = number | 'c';\ntype Path = Step[];\n\ntype TreeIndex = {\n leafPaths: Path[];\n texts: string[];\n elements: Map<string, ReactElement>;\n};\n\nconst keyOf = (p: Path): string => p.join('/');\n\nfunction indexTree(node: ReactNode, path: Path, out: TreeIndex): void {\n if (isTextLeaf(node)) {\n out.leafPaths.push(path);\n out.texts.push(normalizeLeafText(String(node)));\n return;\n }\n if (Array.isArray(node)) {\n node.forEach((c, i) => indexTree(c as ReactNode, [...path, i], out));\n return;\n }\n if (isValidElement(node)) {\n out.elements.set(keyOf(path), node);\n indexTree(childrenOf(node), [...path, 'c'], out);\n }\n}\n\nfunction buildIndex(children: ReactNode): TreeIndex {\n const idx: TreeIndex = { leafPaths: [], texts: [], elements: new Map() };\n indexTree(children, [], idx);\n return idx;\n}\n\nexport function reactLeafTexts(children: ReactNode): string[] {\n return buildIndex(children).texts;\n}\n\n/** Same value as the DOM capture's `fp` when parity holds — computable at\n * decide time from the tree alone, before any DOM exists. */\nexport function reactFingerprint(children: ReactNode): string | null {\n const t = reactLeafTexts(children);\n return t.length === 0 ? null : skeletonFingerprint(t);\n}\n\n/** Paths of every element that encloses the leaf, outermost first. */\nfunction enclosingElements(leaf: Path): Path[] {\n const out: Path[] = [];\n leaf.forEach((s, i) => {\n if (s === 'c') out.push(leaf.slice(0, i));\n });\n return out;\n}\n\n/** Owner of each node: the deepest element enclosing all of its leaves, or\n * null when a leaf sits directly at the root (no element to hide/restyle). */\nfunction nodeOwners(idx: TreeIndex, leafToNode: number[]): Array<Path | null> {\n const count = leafToNode.reduce((m, n) => Math.max(m, n + 1), 0);\n const owners: Array<Path | null> = [];\n for (let k = 0; k < count; k++) {\n const lists = leafToNode.flatMap((n, i) => (n === k ? [enclosingElements(idx.leafPaths[i]!)] : []));\n if (lists.length === 0) {\n owners.push(null);\n continue;\n }\n let common = lists[0]!;\n for (const l of lists.slice(1)) {\n const keys = new Set(l.map(keyOf));\n common = common.filter((p) => keys.has(keyOf(p)));\n }\n owners.push(common.length > 0 ? common[common.length - 1]! : null);\n }\n return owners;\n}\n\nfunction classNameOf(el: ReactElement | undefined): string | undefined {\n const c = (el?.props as { className?: unknown } | undefined)?.className;\n return typeof c === 'string' ? c : undefined;\n}\n\n/**\n * The skeleton with React's view of it applied, or null when the tree and the\n * DOM disagree (a composite that adds, drops or reorders text; `label={…}`\n * props; i18n components) — edits addressed by leaf order would then land on\n * the wrong element, so the region is reported unaddressable instead.\n */\nexport function annotateSkeletonForReact(skeleton: RegionSkeleton, children: ReactNode): RegionSkeleton | null {\n const idx = buildIndex(children);\n if (idx.texts.length !== skeleton.leaves.length || idx.texts.some((t, i) => t !== skeleton.leaves[i])) return null;\n const owners = nodeOwners(idx, skeleton.leafToNode);\n const nodes = skeleton.nodes.map((n, k) => {\n const owner = owners[k];\n const el = owner ? idx.elements.get(keyOf(owner)) : undefined;\n // A host element always takes className; a composite only visibly when it\n // was handed one (it may not forward an unknown prop).\n const restylable = !!el && (typeof el.type === 'string' || classNameOf(el) !== undefined);\n return { ...n, restylable };\n });\n return { ...skeleton, nodes };\n}\n\n/**\n * The developer's children with a Rewrite arm applied, or null when this tree\n * can't take it (leaf count moved since the skeleton, an owner that can't be\n * hidden/restyled/reordered). Null means the caller renders children — and\n * the page declared its fingerprint at decide time, so a mismatch is normally\n * excluded before the draw rather than discovered here.\n */\nexport function applyEdits(children: ReactNode, edits: ArmEdits, leafToNode: number[]): ReactNode | null {\n const idx = buildIndex(children);\n if (idx.leafPaths.length !== leafToNode.length) return null;\n const nodeCount = leafToNode.reduce((m, n) => Math.max(m, n + 1), 0);\n for (const k of Object.keys(edits.nodes)) {\n if (!/^\\d+$/.test(k) || Number(k) >= nodeCount) return null;\n }\n const owners = nodeOwners(idx, leafToNode);\n const firstLeaf = new Map<number, number>();\n leafToNode.forEach((n, i) => {\n if (!firstLeaf.has(n)) firstLeaf.set(n, i);\n });\n const leafAt = new Map(idx.leafPaths.map((p, i) => [keyOf(p), i]));\n\n const hidden = new Set<string>();\n const restyle = new Map<string, string>();\n let failed = false;\n for (const [ks, e] of Object.entries(edits.nodes)) {\n const k = Number(ks);\n const owner = owners[k];\n if (e.hidden) {\n if (!owner) failed = true;\n else hidden.add(keyOf(owner));\n }\n if (e.like !== undefined) {\n const src = owners[e.like];\n const target = owner ? idx.elements.get(keyOf(owner)) : undefined;\n const cls = src ? classNameOf(idx.elements.get(keyOf(src))) : undefined;\n if (!owner || cls === undefined || classNameOf(target) === undefined) failed = true;\n else restyle.set(keyOf(owner), cls);\n }\n }\n // order[g]: node indices in their new order. Applied at the array that holds\n // all of the group's owners as direct entries.\n const pendingOrders = new Map<string, number[]>(Object.entries(edits.order ?? {}));\n\n const rebuild = (node: ReactNode, path: Path): ReactNode => {\n if (isTextLeaf(node)) {\n const i = leafAt.get(keyOf(path));\n if (i === undefined) return node;\n const k = leafToNode[i]!;\n const text = edits.nodes[String(k)]?.text;\n if (text === undefined) return node;\n return firstLeaf.get(k) === i ? text : '';\n }\n if (Array.isArray(node)) {\n const out = node.map((c, i) => rebuild(c as ReactNode, [...path, i]));\n for (const [g, perm] of pendingOrders) {\n const positions = perm.map((k) => {\n const o = owners[k];\n if (!o || o.length !== path.length + 1 || keyOf(o.slice(0, -1)) !== keyOf(path)) return -1;\n return o[o.length - 1] as number;\n });\n if (positions.some((p) => p < 0)) continue;\n const slots = [...positions].sort((a, b) => a - b);\n const before = [...out];\n slots.forEach((slot, m) => {\n out[slot] = before[positions[m]!];\n });\n pendingOrders.delete(g);\n }\n return out;\n }\n if (isValidElement(node)) {\n const key = keyOf(path);\n if (hidden.has(key)) return null;\n const inner = childrenOf(node);\n // Untouched subtrees keep their identity — no clone, no remount.\n if (countTextLeaves(inner) === 0) return node;\n const rebuilt = rebuild(inner, [...path, 'c']);\n const cls = restyle.get(key);\n const props = cls !== undefined ? { className: cls } : undefined;\n return Array.isArray(rebuilt)\n ? cloneElement(node, props, ...(rebuilt as ReactNode[]))\n : cloneElement(node, props, rebuilt);\n }\n return node;\n };\n\n const out = rebuild(children, []);\n if (failed || pendingOrders.size > 0) return null;\n return out;\n}\n","'use client';\n\n// `type JSX` comes from react, not the global namespace: @types/react@19\n// removed the global JSX while the peer range allows react >=18, so a bare\n// `JSX.*` in the public d.ts fails to resolve for React 19 consumers.\nimport { useEffect, useMemo, useRef, useState, useSyncExternalStore, type ElementType, type JSX } from 'react';\nimport type { GoalName } from './goal-names.js';\nimport type { AssignResult } from '@sentientui/core';\nimport { useSentient, useAdaptiveApiKey, useOnAssignment, useSessionSegment } from './provider.js';\nimport { attachGoalListeners, goalValueOf, isDevBuild, maybeDeclareFunnel, normalizeGoal, type GoalConfig } from './adaptive-shared.js';\nimport { getDevOverride } from './dev-override.js';\nimport { subscribeOverridesChanged } from './override-events.js';\n\n\nexport type AdaptiveTextProps = {\n id: string;\n default: string;\n component?: keyof JSX.IntrinsicElements;\n className?: string;\n /**\n * Optional conversion goal to optimize this copy toward. Without it, the\n * variant is served and logged but never scored — the copy rotates and never\n * learns. Provide a goal (a name string or a GoalConfig) to make the optimizer\n * attribute conversions to the winning wording, exactly like `<Adaptive>`.\n */\n goal?: GoalName | GoalConfig;\n};\n\n/**\n * Dashboard-managed copy for a single element. The variants are **text only** —\n * they change the wording, never the CSS, markup, or layout of the element\n * (managed variants created from the dashboard/MCP carry text, nothing else).\n * For anything structural — style, markup shape, position — write the change in\n * code with `<Adaptive>` (any JSX per variant) or use adaptive slots on no-code\n * sites. Pass `goal` to make the managed copy optimizable (see below).\n */\nexport function AdaptiveText({\n id,\n default: defaultText,\n component: Tag = 'span',\n className,\n goal: goalProp,\n}: AdaptiveTextProps) {\n const client = useSentient();\n const apiKey = useAdaptiveApiKey();\n const onAssignment = useOnAssignment();\n const segment = useSessionSegment();\n const trackedRef = useRef<string | null>(null);\n const nodeRef = useRef<HTMLElement | null>(null);\n\n // Dev override parity with <Adaptive>/useAdaptive: honor\n // ?sentient_variant=id:variant and window.__sentient_overrides (devtools,\n // applyScenario, Playwright/Cypress). A forced variant is a preview — it\n // suppresses the network assign, exposure, and goals (\"no events recorded,\n // weights unchanged\"). Read through useSyncExternalStore (server snapshot\n // null → no hydration mismatch on a ?sentient_variant= page; client snapshot\n // synchronous → no interim assign() before the override applies on remount).\n const override = useSyncExternalStore(\n subscribeOverridesChanged,\n () => getDevOverride(id),\n () => null,\n );\n\n // Seed from cache synchronously so remounts don't flash back to defaultText.\n const [text, setText] = useState<string | null>(() =>\n client?.getAssignment(id, segment)?.content ?? null\n );\n const [variantId, setVariantId] = useState<string | null>(() =>\n client?.getAssignment(id, segment)?.variantId ?? null\n );\n\n useEffect(() => {\n if (override) return; // forced variant — no network assign\n if (!client) return;\n const cached = client.getAssignment(id, segment);\n if (cached?.content !== undefined) {\n // Content already cached — skip the network assign, but DO sync it into\n // state. The client normally arrives AFTER mount (the provider inits it\n // in an effect), so the useState seeds above ran against a null client;\n // early-returning here left text/variantId null, and a returning visitor\n // rendered defaultText all session with no exposure ever recorded. The\n // sync makes the exposure effect below fire variant_assigned (and\n // onAssignment) exactly like the fresh-assign path; when the seeds\n // already caught the cache, these setters are no-op re-renders.\n setVariantId(cached.variantId);\n setText(cached.content);\n return;\n }\n\n let cancelled = false;\n void client.assign(id).then((result: AssignResult | null) => {\n if (cancelled) return;\n if (!result) {\n if (isDevBuild()) {\n console.warn(`[sentient] <AdaptiveText id=\"${id}\"> assignment failed — showing default text.`);\n }\n return;\n }\n setVariantId(result.variantId);\n if (result.content) setText(result.content);\n });\n return () => {\n cancelled = true;\n };\n }, [client, id, segment, override]);\n\n useEffect(() => {\n if (override) return; // forced variant records no exposure\n if (!client || !variantId || !apiKey) return;\n if (trackedRef.current === variantId) return;\n trackedRef.current = variantId;\n client.track({\n projectId: apiKey,\n componentId: id,\n variantId,\n eventType: 'variant_assigned',\n payload: {},\n });\n onAssignment?.(id, variantId);\n }, [client, variantId, apiKey, id, onAssignment, override]);\n\n // Optional goal attribution (opt-in) — mirrors <Adaptive>. Without a goal the\n // copy is served but never scored.\n const goalKey = goalProp === undefined ? '' : typeof goalProp === 'string' ? goalProp : JSON.stringify(goalProp);\n const goal = useMemo(() => (goalProp === undefined ? null : normalizeGoal(goalProp)), [goalKey]);\n const goalLabel = goalProp === undefined ? null : typeof goalProp === 'string' ? goalProp : goal!.type;\n const goalFiredRef = useRef(false);\n\n useEffect(() => {\n goalFiredRef.current = false;\n }, [variantId, goalKey]);\n\n // A weighted composite here is a funnel like everywhere else; without this\n // declaration the copy was credited the SUM of its steps (no `funnel` prop\n // exists on AdaptiveText, so it never joined one).\n useEffect(() => {\n if (override || !client || !apiKey) return;\n maybeDeclareFunnel(client, apiKey, id, undefined, goal);\n }, [client, apiKey, id, goal, override]);\n\n useEffect(() => {\n if (override) return; // forced variant records no goals\n if (!client || !variantId || !apiKey || !goal || !goalLabel) return;\n const node = nodeRef.current;\n if (!node) return;\n // A static goal-config value rides on both writes (spec §5).\n const declaredValue = goalValueOf(goal);\n return attachGoalListeners(node, goal, {\n fireGoal: () => {\n if (goalFiredRef.current) return;\n goalFiredRef.current = true;\n client.track({\n projectId: apiKey,\n componentId: id,\n variantId,\n eventType: 'goal_achieved',\n goalType: goalLabel,\n payload: { reward: 1.0, ...(declaredValue !== undefined ? { goalValue: declaredValue } : {}) },\n });\n client.goal(goalLabel, {\n metadata: { componentId: id, variantId },\n weight: 1.0,\n stepIndex: 0,\n ...(declaredValue !== undefined ? { value: declaredValue } : {}),\n });\n },\n fireStep: (name, weight, stepIndex) => {\n client.track({\n projectId: apiKey,\n componentId: id,\n variantId,\n eventType: 'goal_achieved',\n goalType: name,\n payload: { reward: weight },\n });\n client.goal(name, { metadata: {}, weight, stepIndex });\n },\n });\n }, [client, variantId, apiKey, id, goal, goalLabel, override]);\n\n // Under a forced override, show the override variant's managed copy only if\n // it happens to be cached (managed text lives server-side, so an arbitrary\n // forced variant has no client-available copy) — otherwise fall back to the\n // default. Without an override this is just the assigned/default text.\n let displayText = text ?? defaultText;\n if (override) {\n const cached = client?.getAssignment(id, segment);\n displayText = cached && cached.variantId === override ? (cached.content ?? defaultText) : defaultText;\n }\n\n // Cast to ElementType so a single ref callback works across every intrinsic\n // tag without exploding into the full HTML/SVG ref union.\n const Component = Tag as ElementType;\n return (\n <Component ref={(el: HTMLElement | null) => { nodeRef.current = el; }} className={className}>\n {displayText}\n </Component>\n );\n}\n","import type { GoalName } from './goal-names.js';\nimport { useCallback, useRef } from 'react';\nimport type { ComponentGoalOptions, GoalOptions } from '@sentientui/core';\nimport { useSentient } from './provider.js';\nimport { getDevOverride } from './dev-override.js';\n\nexport interface FireGoalOptions extends ComponentGoalOptions {\n /**\n * Record this goal at most once per mounted component, however many times the\n * callback is invoked. Use it for conversions that are a state, not an action\n * — \"reached step 3\", \"form validated\", an effect that may re-run — where a\n * second record is double counting rather than a second conversion.\n *\n * Leave it off for genuine repeat actions (each click of \"add to cart\" is its\n * own conversion). The latch is per goal type and lives for the lifetime of\n * the component holding the callback, so a remount can record again.\n */\n once?: boolean;\n}\n\nexport type FireGoal = (goalType: GoalName, opts?: FireGoalOptions) => void;\n\n/**\n * The session goal record's options, from a conversion's options. One builder\n * for every hook that records a goal (this one, usePageGoal, useGoal): each\n * built the same object inline, and the React bundle has a byte budget.\n * Revenue fields are passed only when set, so a valueless call stays valueless.\n */\nexport function goalOptionsOf(opts?: ComponentGoalOptions): GoalOptions {\n return {\n metadata: opts?.metadata ?? {},\n weight: opts?.reward ?? 1.0,\n stepIndex: 0,\n ...(opts?.value !== undefined ? { value: opts.value } : {}),\n ...(opts?.currency !== undefined ? { currency: opts.currency } : {}),\n ...(opts?.externalId !== undefined ? { externalId: opts.externalId } : {}),\n };\n}\n\n/**\n * Returns a `fireGoal(goalType, opts?)` callback that records a conversion\n * attributed to the variant currently served for `componentId` — so it shows\n * up in the per-variant CVR funnel with no manual variantId/projectId plumbing.\n *\n * The served variant is resolved from the SDK's assignment cache (the same one\n * `<Adaptive id={componentId}>` populates), so render that component before\n * firing. Use this for imperative handlers (click, form submit, custom events);\n * for purely declarative goals prefer `<Adaptive goal={...}>`.\n *\n * Each call records one bandit reward event AND one session goal-funnel record.\n * It has no cross-call latch, so a component that *also* declares a matching\n * `<Adaptive goal>` (or fires this on every click) records one conversion per\n * call — keep goal labels unique per conversion so counts aren't inflated.\n *\n * @example\n * const fireContact = useAdaptiveGoal('hero_headline');\n * <button onClick={() => fireContact('hero_contact', { metadata: { method } })}>Call</button>\n */\nexport function useAdaptiveGoal(componentId: string): FireGoal {\n const client = useSentient();\n // Goal types already recorded through this callback, for `once`. A ref, not\n // state: latching must not re-render, and the set has to survive the callback\n // being recreated when the client arrives (consent granted mid-session).\n const firedOnce = useRef<Set<string>>(new Set());\n return useCallback<FireGoal>(\n (goalType, opts) => {\n // A forced variant (?sentient_variant= / window.__sentient_overrides) is a\n // dev/QA preview, not real traffic. Recording a goal would credit the\n // bandit and pollute the session funnel for the overridden arm — breaking\n // the \"no events recorded, weights unchanged\" override contract that\n // <Adaptive>, useAdaptive.fireGoal, and the declarative path all honor.\n // Read post-mount (inside the callback), never in a render body.\n // Checked BEFORE the `once` latch: a preview must not consume the one\n // record a real conversion is entitled to after the override clears.\n if (getDevOverride(componentId)) return;\n if (opts?.once) {\n if (firedOnce.current.has(goalType)) return;\n firedOnce.current.add(goalType);\n }\n // componentGoal credits the bandit (arm resolved from the assignment\n // cache); goal() writes the session-level conversion funnel record. A\n // declared <Adaptive goal> fires both — a manual conversion for the same\n // component must too, or it shows up in per-variant CVR but never in the\n // session goal funnel. Revenue fields ride on both writes so read-time\n // dedup never picks a valueless row (spec §5).\n client?.componentGoal(componentId, goalType, opts);\n client?.goal(goalType, goalOptionsOf(opts));\n },\n [client, componentId],\n );\n}\n","import type { GoalName } from './goal-names.js';\nimport { useEffect, useRef } from 'react';\nimport type { ComponentGoalOptions } from '@sentientui/core';\nimport { useSentient } from './provider.js';\nimport { goalOptionsOf, useAdaptiveGoal } from './use-adaptive-goal.js';\n\nexport interface PageGoalOptions extends ComponentGoalOptions {\n /**\n * Credit the arrival to the variant currently served for this component —\n * typically the CTA on the page the visitor came FROM. The served variant is\n * read from the assignment cache, which is localStorage-backed, so the credit\n * survives the navigation. Omit for a session-level goal with no per-variant\n * attribution.\n */\n componentId?: string;\n}\n\n/**\n * Records `goalName` once, when a page or route is reached.\n *\n * Use this for funnel steps that are a *destination* rather than a click:\n * reaching /pricing, landing on a signup form, opening a checkout. Arrival is\n * the better signal — it survives the navigation that a click goal can lose,\n * and it also counts visitors who arrived from the nav, a search result or a\n * shared link, none of whom clicked the CTA being measured.\n *\n * Two things this handles that hand-rolling `useAdaptiveGoal` in an effect does\n * not, both of which fail silently:\n *\n * - **Fires once per mount.** A hand-rolled effect re-runs — React's\n * double-invoked effects in development, or the client arriving — and\n * records the arrival again unless you pass `useAdaptiveGoal`'s `once`.\n * (Both latches are per mounted component: a remount records again.)\n * - **Waits for consent.** Under a consent gate the client does not exist when\n * the page mounts, and a visitor who accepts a moment later would lose the\n * goal entirely — `once` would even spend its latch on that dropped call.\n * The arrival is held until the SDK is running, then sent.\n *\n * Safe during SSR (effects do not run on the server) and a no-op without a\n * provider above it.\n *\n * @example\n * // Credit reaching the pricing page to whichever hero CTA sent them.\n * usePageGoal('pricing_view', { componentId: 'hero_cta' });\n *\n * @example\n * // Session-level only — no component to attribute it to.\n * usePageGoal('docs_view');\n */\nexport function usePageGoal(goalName: GoalName, opts: PageGoalOptions = {}): void {\n const { componentId, ...goalOpts } = opts;\n const client = useSentient();\n // Called unconditionally (rules of hooks); only used when componentId is set.\n // It carries the dev-override contract — a forced variant records nothing —\n // so component-attributed arrivals inherit it for free.\n const fireComponentGoal = useAdaptiveGoal(componentId ?? '');\n const fired = useRef(false);\n // Callers pass an object literal, so `goalOpts` has a new identity every\n // render. Keeping it in a ref keeps it out of the dep array without making\n // the effect re-run (the latch would ignore it anyway).\n const optsRef = useRef(goalOpts);\n optsRef.current = goalOpts;\n\n useEffect(() => {\n // Not into a consent-gated client (preConsentBehavior): React replaces it\n // with a new tracking client on grant, so a goal fired now would go\n // nowhere while spending the latch — the arrival was lost for every\n // visitor who accepted after landing (grader NEW-1). The effect re-runs\n // when the tracking client arrives.\n if (!client || fired.current || client.gated) return;\n fired.current = true;\n if (componentId) {\n fireComponentGoal(goalName, optsRef.current);\n return;\n }\n client.goal(goalName, goalOptionsOf(optsRef.current));\n }, [client, componentId, goalName, fireComponentGoal]);\n}\n","import type { GoalName } from './goal-names.js';\nimport { useCallback, useEffect, useRef } from 'react';\nimport type { SentientClient } from '@sentientui/core';\nimport { useAdaptiveApiKey, useSentient } from './provider.js';\nimport { goalOptionsOf, useAdaptiveGoal, type FireGoalOptions } from './use-adaptive-goal.js';\nimport { isDevBuild } from './adaptive-shared.js';\n\nexport interface UseGoalOptions {\n /**\n * Make this the project's main goal — the one experiments optimize and\n * results are measured on. Change which hook carries it and deploy to change\n * the main goal; no dashboard visit needed.\n *\n * It moves the main goal only when the declared goal CHANGES, so a main goal\n * picked in the dashboard sticks until your code declares a different one.\n * From localhost it only sets a main goal when the project has none. Every\n * change is in the project's activity log. Declare it in ONE place: two\n * different `primary` goals on a page are a mistake, and only the first counts.\n */\n primary?: boolean;\n /**\n * Also credit the conversion to the version currently served for this\n * component (same as `useAdaptiveGoal(componentId)`). Omit for a goal that\n * belongs to the visit, not to one component.\n */\n componentId?: string;\n}\n\n/** Records the goal. Options are per conversion: a value, an order id, `once`. */\nexport type FireNamedGoal = (opts?: FireGoalOptions) => void;\n\n// What this page load has already declared, per API key. A declaration is a\n// definition, not telemetry: once per page is all the server needs (it keeps\n// the steady state at zero writes itself), and every mount of a component\n// holding the hook re-running it would be one event per render tree.\nconst declared = new Set<string>();\nconst primaryByKey = new Map<string, string>();\n\n/** Test-only: clears the page-load declaration state. */\nexport function __resetGoalDeclarations(): void {\n declared.clear();\n primaryByKey.clear();\n}\n\nfunction declareGoal(client: SentientClient, apiKey: string, name: string, primary: boolean): void {\n let asPrimary = primary;\n if (primary) {\n const existing = primaryByKey.get(apiKey);\n if (existing && existing !== name) {\n // Two main goals on one page: whichever mounts first would win per page,\n // and the server would see them alternate. Keep the first and say so,\n // rather than let the main goal depend on render order.\n if (isDevBuild()) {\n console.warn(`[SentientUI] useGoal('${name}'): '${existing}' is already primary on this page`);\n }\n asPrimary = false;\n } else {\n primaryByKey.set(apiKey, name);\n }\n }\n const key = `${apiKey}|${name}|${asPrimary ? 'primary' : ''}`;\n if (declared.has(key)) return;\n declared.add(key);\n client.track({\n projectId: apiKey,\n componentId: '__session__',\n eventType: 'goal_declared',\n payload: asPrimary ? { goalId: name, primary: true } : { goalId: name },\n });\n}\n\n/**\n * A goal your site records — declared where it happens, and fired from there.\n *\n * Declaring it is what makes it show in the dashboard straight away, at an\n * honest 0, before anyone has completed it. `primary: true` makes it the\n * project's main goal. The returned function records one conversion.\n *\n * @example\n * const signup = useGoal('signup', { primary: true });\n * <form onSubmit={() => signup()}>…</form>\n *\n * @example\n * // A revenue goal, credited to the hero version that was showing.\n * const purchase = useGoal('purchase', { componentId: 'hero_cta' });\n * purchase({ value: order.total, externalId: order.id });\n */\nexport function useGoal(name: GoalName, options: UseGoalOptions = {}): FireNamedGoal {\n const { primary = false, componentId } = options;\n const client = useSentient();\n const apiKey = useAdaptiveApiKey();\n // Called unconditionally (rules of hooks); used only with componentId. It\n // carries the dev-override contract — a forced version records nothing.\n const fireComponentGoal = useAdaptiveGoal(componentId ?? '');\n const firedOnce = useRef(false);\n\n useEffect(() => {\n // Not into a consent-gated client: React swaps in a tracking client on\n // grant, the effect re-runs with it, and the declaration goes out then.\n if (!client || client.gated || !apiKey) return;\n declareGoal(client, apiKey, name, primary);\n }, [client, apiKey, name, primary]);\n\n return useCallback<FireNamedGoal>(\n (opts) => {\n if (opts?.once) {\n if (firedOnce.current) return;\n firedOnce.current = true;\n }\n if (componentId) {\n fireComponentGoal(name, opts);\n return;\n }\n client?.goal(name, goalOptionsOf(opts));\n },\n [client, componentId, fireComponentGoal, name],\n );\n}\n","// `type JSX` from react, not the global namespace removed in @types/react@19\n// (peers allow react >=18) — see adaptive-text.tsx.\nimport type { JSX } from 'react';\nimport { renderPrePaintScript, type StageAttributes } from '@sentientui/core';\nimport { confidenceBand } from '@sentientui/policy';\n\nexport type SentientPersonaScriptProps = {\n /** Publishable API key — selects the localStorage snapshot in the fallback path. */\n apiKey: string;\n /**\n * CSP nonce for the inline pre-paint script. Pass the same nonce your\n * `Content-Security-Policy` `script-src` allows (e.g. from Next.js middleware).\n * Required for strict CSP deployments that block `'unsafe-inline'`.\n */\n nonce?: string;\n /**\n * SSR-decided persona (from `loadAdaptiveDecision`). When present the\n * script embeds the literal values; when absent it reads the local\n * decision snapshot (SPA / return-visit path).\n */\n persona?: { persona: string; confidence: number } | null;\n /**\n * The same consent gate you give the provider. With `consent={false}`, or a\n * `consentFrom` source and no `consent={true}`, nothing is rendered: the\n * fallback reads the stored decision from the visitor's device, and that\n * must wait for consent (grader F3). `AdaptiveRoot` handles this for you.\n */\n consent?: boolean;\n consentFrom?: unknown;\n /**\n * Opt-in `data-sentient-stage` (see `AdaptiveProviderProps.stageAttributes`).\n * With a server decision, pass the value to write as `stage` (already\n * coarsened — `exposedStage` from `@sentientui/core`); without one the\n * script copies the stage the visitor's last decide stored.\n */\n stageAttributes?: StageAttributes;\n /** The stage value to write, from this request's decide; null writes none. */\n stage?: string | null;\n};\n\n/** JSON string literal that is also safe inside an inline <script> element. */\nfunction inlineJsString(value: string): string {\n return JSON.stringify(value).replace(/</g, '\\\\u003c');\n}\n\n/** Exported for tests. Builds the inline JS (concatenation only — no backticks). */\nexport function personaScriptBody(props: SentientPersonaScriptProps): string {\n if (props.persona) {\n return (\n '(function(){try{var d=document.documentElement;' +\n // The stage first, with its own single-writer check: an already-set\n // persona must not stop it. Only a value this request's decide gave.\n (props.stage\n ? 'if(!d.hasAttribute(\"data-sentient-stage\"))d.setAttribute(\"data-sentient-stage\",' + inlineJsString(props.stage) + ');'\n : '') +\n 'if(d.hasAttribute(\"data-sentient-persona\"))return;' +\n 'd.setAttribute(\"data-sentient-persona\",' + inlineJsString(props.persona.persona) + ');' +\n 'd.setAttribute(\"data-sentient-confidence\",' + inlineJsString(confidenceBand(props.persona.confidence)) + ');' +\n '}catch(e){}})();'\n );\n }\n return renderPrePaintScript(props.apiKey, props.stageAttributes ? { stage: true } : undefined);\n}\n\n/**\n * Single writer of the Rung-1a `<html>` attributes\n * (`data-sentient-persona`, `data-sentient-confidence`), executed pre-paint.\n *\n * `AdaptiveRoot` renders this automatically as its first child. For Pages\n * Router / Remix, render it yourself in `_document` / the root layout.\n *\n * IMPORTANT (install docs): add `suppressHydrationWarning` to your `<html>`\n * element — this script mutates documentElement before React hydrates it\n * (the same pattern next-themes uses). The client SDK adopts the attributes\n * as truth and never rewrites them mid-session.\n */\nexport function SentientPersonaScript(props: SentientPersonaScriptProps): JSX.Element | null {\n // A server-decided persona is not a storage read, so it always renders.\n if (!props.persona && (props.consent === false || (props.consentFrom !== undefined && props.consent !== true))) return null;\n return (\n <script\n data-sentient-persona-script=\"\"\n nonce={props.nonce}\n dangerouslySetInnerHTML={{ __html: personaScriptBody(props) }}\n />\n );\n}\n","import type { GoalName } from './goal-names.js';\nimport { useEffect, useMemo, useRef } from 'react';\nimport type { SlotDeclInput } from '@sentientui/core';\nimport { validateSlotDecl } from '@sentientui/policy';\nimport { useAdaptiveApiKey, useSentient } from './provider.js';\nimport { useSlotResult } from './use-slot-result.js';\nimport { registerSlot } from './devtools-registry.js';\nimport {\n attachGoalListeners,\n goalLabelOf,\n goalValueOf,\n isDevBuild,\n maybeDeclareFunnel,\n normalizeGoal,\n trackExposure,\n type GoalConfig,\n} from './adaptive-shared.js';\n\nexport type UseAdaptiveTokensOptions = {\n goal?: GoalName | GoalConfig;\n /** Funnel this slot serves (stable funnel id, e.g. \"checkout\") — same\n * declaration semantics as <Adaptive funnel=\"...\">. */\n funnel?: string;\n};\nexport type UseAdaptiveTokensResult = {\n tokens: Record<string, string>;\n /** Spread on the slot's element: `data-<dim>` per dim + `data-sentient-slot`. */\n props: Record<string, string>;\n};\n\n// Warn once per slot id per page lifetime — not per render.\nconst warnedTokenSlots = new Set<string>();\n\nfunction cssEscape(value: string): string {\n if (typeof CSS !== 'undefined' && typeof CSS.escape === 'function') return CSS.escape(value);\n // Fallback for environments without CSS.escape: the value is interpolated\n // inside a double-quoted attribute selector (`[data-sentient-slot=\"…\"]`), so\n // both the backslash and the closing quote must be escaped — the old\n // quote-only escape let a slot id containing `\\` break out of the selector\n // (and an unescaped `\"` in a since-fixed path could match the wrong node).\n return value.replace(/[\\\\\"]/g, '\\\\$&');\n}\n\n/**\n * Rung 1b — adaptive design tokens. Declares a bounded token space; the\n * optimizer picks per persona; values apply as element-scoped data\n * attributes so they serialize through SSR markup (zero flicker,\n * hydration-safe). First value of each dim = baseline.\n *\n * ```tsx\n * const t = useAdaptiveTokens('hero', { tone: ['calm', 'urgent'] });\n * return <section {...t.props} className=\"hero\">…</section>;\n * // CSS: .hero[data-tone=\"urgent\"] .cta { … }\n * ```\n */\nexport function useAdaptiveTokens(\n id: string,\n dims: Record<string, readonly string[]>,\n opts?: UseAdaptiveTokensOptions,\n): UseAdaptiveTokensResult {\n const client = useSentient();\n const apiKey = useAdaptiveApiKey();\n\n // Freeze the declaration on the DIMS SIGNATURE, not the object identity: an\n // inline `dims={{...}}` literal is a fresh object each render, so keying on it\n // would churn a new decl every commit. A stringified signature is stable\n // across renders for the same dims yet updates if the declared space changes\n // (same convention as <Adaptive> / useAdaptive / AdaptiveGroup). A slot's\n // declared space is normally fixed for the session.\n const dimsKey = JSON.stringify(dims);\n // eslint-disable-next-line react-hooks/exhaustive-deps\n const decl = useMemo<SlotDeclInput>(() => ({ id, dims }), [id, dimsKey]);\n const { result, arm, source } = useSlotResult(id, decl);\n const tokens = useMemo<Record<string, string>>(\n () => (typeof result === 'string' ? {} : result),\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [arm],\n );\n\n if (isDevBuild() && !warnedTokenSlots.has(id)) {\n // Added UNCONDITIONALLY: the id used to be added only on the warn branches,\n // so a VALID declaration re-ran validateSlotDecl plus the combination-space\n // product on every dev render for the page's whole lifetime.\n warnedTokenSlots.add(id);\n const validity = validateSlotDecl({\n id,\n dims: Object.fromEntries(Object.entries(dims).map(([k, v]) => [k, [...v]])),\n });\n const space = Object.values(dims).reduce((n, values) => n * values.length, 1);\n if (!validity.ok) {\n console.warn(\n `[sentient] useAdaptiveTokens(\"${id}\"): invalid declaration — ${validity.reason}. Serving baseline.`,\n );\n } else if (space > 4) {\n console.warn(\n `[sentient] useAdaptiveTokens(\"${id}\") declares ${space} combinations — more than the recommended 4. Each extra combination needs more traffic to learn; consider fewer dims/values.`,\n );\n }\n }\n\n const goalKey =\n opts?.goal === undefined ? null : typeof opts.goal === 'string' ? opts.goal : JSON.stringify(opts.goal);\n\n // Devtools slot registry — the declared dims space drives both persona\n // simulation and the panel's per-dim override buttons. A slot is NOT a\n // component: registering it as one produced buttons that wrote the wrong\n // override channel (`__sentient_overrides` instead of `__sentient_slot_overrides`).\n // eslint-disable-next-line react-hooks/exhaustive-deps\n useEffect(() => registerSlot({ id, dims }), [id]);\n\n // Exposure — the slot equivalent of <Adaptive>'s variant_assigned event,\n // once per (slot, arm). variantId = canonical arm string.\n const exposedArmRef = useRef<string | null>(null);\n useEffect(() => {\n // Don't expose an unresolved baseline: a `baseline` source means the slot\n // was never decided (interim local decide, or a keyed client with no SSR\n // preload). Recording it accrues a phantom baseline impression that can\n // never convert. Once a real arm resolves (source flips to preloaded/\n // client) the exposure fires for that arm.\n // A forced arm (`override`, from devtools/tests) is a preview, not a real\n // exposure — recording it would train the optimizer on the override, the\n // same \"no events, weights unchanged\" contract <Adaptive> honors for\n // component overrides.\n // `seeded` is the core holding a snapshot arm or a failure baseline: it\n // renders, but no slot_decisions row exists for it this session, so an\n // impression would train an arm the server never served — and a failed\n // decide batch used to yield one phantom baseline exposure per slot.\n if (!client || source === 'baseline' || source === 'seeded' || source === 'override' || exposedArmRef.current === arm) return;\n exposedArmRef.current = arm;\n trackExposure(client, apiKey, id, arm);\n }, [client, apiKey, id, arm, source]);\n\n // Funnel membership declaration — same override gate as the exposure. A\n // weighted composite with no `funnel` declares its own (compositeFunnelId).\n const funnel = opts?.funnel;\n useEffect(() => {\n if (!client || source === 'override') return;\n maybeDeclareFunnel(client, apiKey, id, funnel, normalizeGoal(opts?.goal ?? 'click'));\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [client, apiKey, id, funnel, goalKey, source]);\n\n // Optional goal: the returned props carry data-sentient-slot, so the slot's\n // element is findable without a ref (the pinned return type has no ref).\n // Credit flows through componentGoal(slot id) — the core resolves the\n // attributed arm from its slot state (Task 3.3 fallback).\n useEffect(() => {\n // Forced arms record nothing (preview only), and an unresolved `baseline`\n // source never recorded an impression (see the exposure effect above) — a\n // conversion attached in that state would attribute to an arm with zero\n // exposures. Same source gates as the exposure.\n if (!client || !opts?.goal || source === 'override' || source === 'baseline' || source === 'seeded') return;\n const node = document.querySelector(`[data-sentient-slot=\"${cssEscape(id)}\"]`);\n if (!node) {\n if (isDevBuild()) {\n console.warn(\n `[sentient] useAdaptiveTokens(\"${id}\"): a goal is declared but no element carries the returned props — spread {...props} on the slot's element.`,\n );\n }\n return;\n }\n const label = goalLabelOf(opts.goal);\n const declaredValue = goalValueOf(opts.goal);\n let fired = false;\n return attachGoalListeners(node, normalizeGoal(opts.goal), {\n fireGoal: () => {\n if (fired) return;\n fired = true;\n // componentGoal credits the bandit (goal_achieved event, arm resolved\n // from slot state); goal() writes the session-level conversion funnel\n // record — exactly what <Adaptive> does for component goals. Slots\n // fired only the former, so slot conversions were invisible in the\n // goal funnel; fire both so membership matches components. (One funnel\n // record per conversion — see useAdaptiveGoal; keep labels unique.)\n // A static goal-config value rides on both writes (spec §5).\n if (declaredValue !== undefined) client.componentGoal(id, label, { value: declaredValue });\n else client.componentGoal(id, label);\n client.goal(label, {\n metadata: { componentId: id, arm },\n weight: 1.0,\n stepIndex: 0,\n ...(declaredValue !== undefined ? { value: declaredValue } : {}),\n });\n },\n fireStep: (name, weight, stepIndex) => {\n client.componentGoal(id, name, { reward: weight });\n client.goal(name, { metadata: { componentId: id, arm }, weight, stepIndex });\n },\n }, label);\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [client, id, goalKey, arm, source]);\n\n const props = useMemo(() => {\n const p: Record<string, string> = { 'data-sentient-slot': id };\n for (const [dim, value] of Object.entries(tokens)) p[`data-${dim}`] = value;\n return p;\n }, [id, tokens]);\n\n return { tokens, props };\n}\n","import { useEffect, useReducer, useState, useSyncExternalStore } from 'react';\nimport { armOfResult, baselineResultFor, type SlotDeclInput, type SlotResult } from '@sentientui/core';\nimport { confidenceBand } from '@sentientui/policy';\nimport { useInitialPersona, useInitialSlots, useSentient } from './provider.js';\nimport { subscribeOverridesChanged, getOverridesVersion } from './override-events.js';\n\ndeclare global {\n interface Window {\n /** Test/devtools forcing: slot id → forced result (applyScenario sets this). */\n __sentient_slot_overrides?: Record<string, SlotResult>;\n /** Test/devtools forcing: forced persona (applyScenario sets this). */\n __sentient_persona_override?: { persona: string; confidence?: number };\n }\n}\n\nexport type SlotResolution = {\n result: SlotResult;\n /** Canonical arm string (`dim=value|…` for dims slots, arm id for arms slots). */\n arm: string;\n /**\n * `client` = decided for this session (a slot_decisions row exists);\n * `seeded` = the core client holds a result that was NOT decided this\n * session — a snapshot from an earlier visit or the baseline it wrote when a\n * decide failed. Seeded results render (pre-paint parity) but must never be\n * exposed or credited: there is no trial for them to belong to.\n */\n source: 'override' | 'preloaded' | 'client' | 'seeded' | 'baseline';\n};\n\n/**\n * Internal. Resolves what a slot serves this render, synchronously:\n * test/devtools override → SSR-preloaded result → core client state\n * (decide cache, snapshot seed, failure baseline) → declared baseline.\n * Purely read-side: exposure/goal wiring belongs to the calling hook.\n */\nexport function useSlotResult(slotId: string, decl: SlotDeclInput): SlotResolution {\n const client = useSentient();\n const initialSlots = useInitialSlots();\n const [, bump] = useReducer((n: number) => n + 1, 0);\n\n // Devtools/test forcing (window.__sentient_slot_overrides — applyScenario,\n // the Playwright/Cypress mocks) read through the useSyncExternalStore\n // SNAPSHOT with a null server snapshot, exactly like useAssignment's dev\n // override and useLayoutOrder. The old direct window read in the render body\n // made the pre-hydration client render disagree with the server HTML\n // whenever an override was written before hydration — which is precisely\n // when the package's own Playwright/Cypress mocks write it — i.e. a\n // hydration mismatch. The snapshot returns the stored object by reference\n // (stable until the override bus notifies a rewrite), so it passes React's\n // Object.is snapshot-caching check.\n const override = useSyncExternalStore(\n subscribeOverridesChanged,\n () => (typeof window !== 'undefined' ? window.__sentient_slot_overrides?.[slotId] : undefined),\n () => undefined,\n );\n const preloaded = override === undefined ? initialSlots[slotId] : undefined;\n const fromClient =\n override === undefined && preloaded === undefined && client\n ? client.getSlotResult(slotId)\n : null;\n\n // Keyless local mode on a CSR-only page: nothing has decided this slot yet\n // (no SSR preload, no snapshot), so ask the local engine — zero network,\n // deterministic — and re-render when the decision lands. Keyed clients\n // never take this path: their slots decide server-side (SSR preload).\n const needsLocalDecide =\n client?.isLocal === true &&\n override === undefined &&\n preloaded === undefined &&\n fromClient === null;\n useEffect(() => {\n if (!needsLocalDecide || !client) return;\n let cancelled = false;\n void client.decide({ slots: [decl] }).then((outcome) => {\n if (!cancelled && outcome) bump();\n });\n return () => {\n cancelled = true;\n };\n // decl identity is fixed per slot id (callers memoize it on id).\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [client, slotId, needsLocalDecide]);\n\n const resolution: SlotResolution = (() => {\n if (override !== undefined) {\n return { result: override, arm: armOfResult(override), source: 'override' };\n }\n if (preloaded !== undefined) {\n return { result: preloaded, arm: armOfResult(preloaded), source: 'preloaded' };\n }\n if (fromClient !== null) {\n // A result the core holds but did not decide this session (snapshot seed,\n // failure baseline) renders as-is but is `seeded`, so the exposure and\n // goal gates in the calling hooks skip it. Clients without the probe\n // (hand-rolled/test) read as decided, as before.\n const decided = client?.isSlotDecided ? client.isSlotDecided(slotId) : true;\n return { result: fromClient, arm: armOfResult(fromClient), source: decided ? 'client' : 'seeded' };\n }\n const baseline = baselineResultFor(decl);\n return { result: baseline, arm: armOfResult(baseline), source: 'baseline' };\n })();\n\n // Keyed clients decide THIS mounted slot when nothing preloaded it: one\n // batched decide per commit (core decideSlots), then re-render when it lands.\n // Before this a keyed client never decided request-declared slots in the\n // browser — useAdaptiveTokens and AdaptiveGroup served their baseline for the\n // whole session and learned nothing unless the same declaration was\n // duplicated into AdaptiveRoot's `slots` for SSR. Snapshot-seeded ('client')\n // slots still ask: the snapshot is the last visit's answer, not a decision\n // for this session. Only mounted slots are decided, so a declaration on\n // another page never becomes a trial for this visit.\n const settled = resolution.source === 'preloaded' || resolution.source === 'override';\n useEffect(() => {\n if (!client || client.isLocal === true || settled || !client.decideSlots) return;\n const off = client.onSlotsChanged?.(bump);\n client.decideSlots([decl]);\n return () => {\n // Unmounted before the batch was sent (redirecting route, StrictMode\n // probe): withdraw it — a slot that is not on the page is not a trial.\n client.cancelSlots?.([slotId]);\n off?.();\n };\n // decl identity is fixed per slot id (callers memoize it on id).\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [client, slotId, settled]);\n\n return resolution;\n}\n\n/**\n * Reads a forced persona: `window.__sentient_persona_override` (the devtools\n * panel, `applyScenario`, the Playwright/Cypress helpers) or the\n * `?sentient_persona=<persona key>` URL param (any project vocabulary key;\n * mirrors `?sentient_variant=`).\n * Read POST-MOUNT only — it touches `window.location`.\n */\nfunction getPersonaOverride(): { persona: string; confidence: number } | null {\n if (typeof window === 'undefined') return null;\n const forced = window.__sentient_persona_override;\n if (forced?.persona) return { persona: forced.persona, confidence: forced.confidence ?? 1 };\n try {\n const value = new URLSearchParams(window.location.search).get('sentient_persona');\n if (value) return { persona: value, confidence: 1 };\n } catch {\n /* non-browser env */\n }\n return null;\n}\n\nexport type AdaptivePersona = {\n persona: string;\n confidence: number;\n band: 'low' | 'medium' | 'high';\n};\n\n/**\n * The current persona estimate for React consumers, resolved in priority\n * order: a forced override (devtools / `applyScenario` / `?sentient_persona=`)\n * → the SSR-provided `initialPersona` → the live client estimate (adopted\n * attributes / snapshot / decide). Returns `null` when nothing is known yet.\n *\n * Hydration-safe: the first render (server + pre-hydration client) uses ONLY\n * the SSR-provided persona so server and client agree; the override channel and\n * the live client estimate — neither visible to the server — are read after\n * mount. Re-renders when a persona/variant override is written, so devtools or\n * a test forcing a persona mid-session takes effect immediately.\n */\nexport function useAdaptivePersona(): AdaptivePersona | null {\n const client = useSentient();\n const initialPersona = useInitialPersona();\n // Re-render when the override channel is written. NOTE: unlike useAssignment /\n // AdaptiveText — which fold the override into the useSyncExternalStore snapshot\n // (getDevOverride returns a STABLE string) — persona can't: getPersonaOverride\n // allocates a fresh object each call, which would fail the snapshot's Object.is\n // check and trip React's \"getSnapshot should be cached\" loop guard. So we\n // subscribe to the stable version counter for reactivity and read the override\n // in the render body (behind a mounted gate). That one-frame post-mount flip is\n // harmless here because this hook is side-effect-free (no assign/exposure to\n // leak), which is exactly why useAssignment/AdaptiveText could NOT tolerate it.\n useSyncExternalStore(subscribeOverridesChanged, getOverridesVersion, () => 0);\n const [mounted, setMounted] = useState(false);\n useEffect(() => setMounted(true), []);\n\n const withBand = (p: { persona: string; confidence: number }): AdaptivePersona => ({\n persona: p.persona,\n confidence: p.confidence,\n band: confidenceBand(p.confidence),\n });\n\n // First render must match the server, which can see neither window nor the\n // client estimate — use only initialPersona to avoid a hydration mismatch on\n // a ?sentient_persona= page.\n if (!mounted) {\n return initialPersona ? withBand(initialPersona) : null;\n }\n const override = getPersonaOverride();\n if (override) return withBand(override);\n if (initialPersona) return withBand(initialPersona);\n const live = client ? client.getPersona() : null;\n return live ? withBand(live) : null;\n}\n","import type { GoalName } from './goal-names.js';\nimport { useCallback, useEffect, useMemo } from 'react';\nimport type { ComponentGoalOptions } from '@sentientui/core';\nimport { isDevBuild, type GoalConfig } from './adaptive-shared.js';\nimport { useVariantComponent, type MicroSignalGoals } from './use-variant-component.js';\nimport { useInitialUnified } from './provider.js';\n\nexport type UseAdaptiveBind = {\n ref: (el: HTMLElement | null) => void;\n 'data-sentient-id': string;\n 'data-sentient-variant': string;\n};\n\nexport type UseAdaptiveResult<T> = {\n variant: string;\n value: T;\n /** Spread on the rendered element — wires exposure, goal listeners, and micro-signals. */\n bind: UseAdaptiveBind;\n fireGoal: (goalType?: string, opts?: ComponentGoalOptions) => void;\n};\n\nconst warnedUnbound = new Set<string>();\nconst warnedUnified = new Set<string>();\n\n/**\n * Rung 2 — headless, measurement-complete variant swap. Supersedes\n * `useAssignment` (which selects a variant but wires no measurement).\n *\n * `goal` is REQUIRED: without one the optimizer accumulates exposures with\n * zero rewards and cannot learn. `bind` MUST be attached to the rendered\n * element — dev mode warns loudly when a slot renders unbound.\n *\n * ```tsx\n * const { value, bind } = useAdaptive('buy-box', {\n * variants: { calm: <CalmBuyBox/>, urgent: <UrgentBuyBox/> }, // first key = baseline\n * goal: 'buy_click',\n * });\n * return <div {...bind}>{value}</div>;\n * ```\n */\nexport function useAdaptive<T>(\n id: string,\n config: {\n variants: Record<string, T>;\n goal: GoalName | GoalConfig;\n /** Funnel this component serves (stable funnel id, e.g. \"checkout\") —\n * same declaration semantics as <Adaptive funnel=\"...\">. */\n funnel?: string;\n /** When a passive micro-signal fires on the bound element, also record a\n * named goal — same mapping as <Adaptive microSignalGoals>. */\n microSignalGoals?: MicroSignalGoals;\n },\n): UseAdaptiveResult<T> {\n if (isDevBuild() && !config.goal) {\n throw new Error(\n `[sentient] useAdaptive(\"${id}\"): a goal is required — without one the optimizer accumulates exposures with no rewards and cannot learn. Pass e.g. goal: 'buy_click'.`,\n );\n }\n\n // Selection + exposure/funnel/goal/micro-signal wiring is the engine shared\n // with <Adaptive variants>. No cursor_signal here: the hook never sent one and\n // adding an event stream is not a refactor.\n const { client, variantIds, variantId, isOverride, goalLabel, ref, nodeRef } = useVariantComponent(\n id,\n config.variants,\n { goal: config.goal, funnel: config.funnel, microSignalGoals: config.microSignalGoals },\n );\n // Unlike <Adaptive> (which renders nothing without a variant), the headless\n // hook always hands back a value: the first key until a variant resolves.\n const variant = variantId ?? variantIds[0] ?? '';\n const value = config.variants[variant] as T;\n\n // A moved component (CONTRACTS §2 \"A unified component is a slot\") has no\n // headless slot path yet: the hook keeps being served the frozen variants\n // result read-only, and nothing it shows is learned from. Said once, in dev,\n // rather than failing silently.\n const knownUnified = useInitialUnified().includes(id) || client?.isUnified?.(id) === true;\n useEffect(() => {\n if (!knownUnified || !isDevBuild() || warnedUnified.has(id)) return;\n warnedUnified.add(id);\n console.warn(\n `[sentient] useAdaptive(\"${id}\"): this component was moved to the shared track, which useAdaptive cannot render yet. ` +\n `It keeps showing the frozen result and learns nothing — render it with <Adaptive id=\"${id}\" variants={...}> instead.`,\n );\n }, [knownUnified, id]);\n\n // Dev warning: bind never attached shortly after mount → exposures would\n // never fire and the slot cannot learn. Once per slot id.\n useEffect(() => {\n if (!isDevBuild()) return;\n if (!client) return;\n const timer = setTimeout(() => {\n if (!nodeRef.current && !warnedUnbound.has(id)) {\n warnedUnbound.add(id);\n console.warn(\n `[sentient] useAdaptive(\"${id}\"): bind was never attached — spread {...bind} on the rendered element, otherwise exposure and goal tracking cannot work and the optimizer learns nothing.`,\n );\n }\n }, 0);\n return () => clearTimeout(timer);\n }, [client, id]);\n\n const fireGoal = useCallback(\n (goalType?: string, opts?: ComponentGoalOptions) => {\n if (isOverride) return; // forced variants record nothing, even manual goals\n // componentGoal credits the bandit; goal() writes the session goal-funnel\n // record. The declared-goal listener above fires both, so a manual goal\n // for the same slot must too (otherwise it's absent from the funnel).\n // Like useAdaptiveGoal, this writes one funnel record per call with no\n // cross-call latch — keep goal labels unique per conversion (a component\n // that ALSO fires a declared goal on the same action records both).\n const name = goalType ?? goalLabel;\n // Empty only on the missing-goal misuse path (fail-soft above) with no\n // explicit goalType — nothing meaningful to record.\n if (!name) return;\n client?.componentGoal(id, name, opts);\n client?.goal(name, {\n metadata: opts?.metadata ?? {},\n weight: opts?.reward ?? 1.0,\n stepIndex: 0,\n ...(opts?.value !== undefined ? { value: opts.value } : {}),\n ...(opts?.currency !== undefined ? { currency: opts.currency } : {}),\n ...(opts?.externalId !== undefined ? { externalId: opts.externalId } : {}),\n });\n },\n [client, id, goalLabel, isOverride],\n );\n\n const bind = useMemo<UseAdaptiveBind>(\n () => ({ ref, 'data-sentient-id': id, 'data-sentient-variant': variant }),\n [ref, id, variant],\n );\n\n return { variant, value, bind, fireGoal };\n}\n","// `type JSX` from react, not the global namespace removed in @types/react@19\n// (peers allow react >=18) — see adaptive-text.tsx.\nimport { Children, isValidElement, useEffect, useMemo, useRef, type JSX, type ReactNode } from 'react';\nimport type { GoalName } from './goal-names.js';\nimport type { SlotDeclInput } from '@sentientui/core';\nimport { useAdaptiveApiKey, useSentient } from './provider.js';\nimport { useSlotResult } from './use-slot-result.js';\nimport { registerSlot } from './devtools-registry.js';\nimport {\n attachGoalListeners,\n goalLabelOf,\n goalValueOf,\n isDevBuild,\n maybeDeclareFunnel,\n normalizeGoal,\n trackExposure,\n type GoalConfig,\n} from './adaptive-shared.js';\n\nexport type AdaptiveGroupProps = {\n id: string;\n /** Arrangement id → ordered child keys. FIRST key = baseline default. */\n arrangements: Record<string, string[]>;\n /** Explicit baseline arrangement id (defaults to the first declared). */\n baseline?: string;\n /** Optional slot-scoped goal — credited via componentGoal(group id). */\n goal?: GoalName | GoalConfig;\n /** Funnel this group serves (stable funnel id, e.g. \"checkout\") — same\n * declaration semantics as <Adaptive funnel=\"...\">. */\n funnel?: string;\n /** Keyed children — every key referenced by an arrangement must exist. */\n children: ReactNode;\n};\n\n// Warn once per group id per page lifetime.\nconst warnedGroups = new Set<string>();\n\n/**\n * Rung 3 — bounded mini-layout. Reorders KEYED children into the decided\n * arrangement (enumerated-arms slot: arms = Object.keys(arrangements)).\n * Declared orders only — never free permutation, never show/hide.\n * Fail-safe: unknown arrangement or key mismatch renders declaration order.\n */\nexport function AdaptiveGroup(props: AdaptiveGroupProps): JSX.Element {\n const client = useSentient();\n const apiKey = useAdaptiveApiKey();\n const containerRef = useRef<HTMLDivElement>(null);\n\n // Freeze the arrangement-id array on the KEY SET (same convention as\n // <Adaptive> / useAdaptive / useAdaptiveTokens): stable across renders for the\n // same keys yet updates if the declared set changes. Declared space is\n // normally fixed per group id for a session.\n const arrangementKey = Object.keys(props.arrangements).join(' ');\n // eslint-disable-next-line react-hooks/exhaustive-deps\n const arrangementIds = useMemo(() => Object.keys(props.arrangements), [arrangementKey]);\n const decl = useMemo<SlotDeclInput>(\n () => ({\n id: props.id,\n arms: arrangementIds,\n ...(props.baseline !== undefined ? { baseline: props.baseline } : {}),\n }),\n [props.id, arrangementIds, props.baseline],\n );\n const { arm, source } = useSlotResult(props.id, decl);\n\n if (\n isDevBuild() &&\n props.baseline !== undefined &&\n props.baseline !== arrangementIds[0] &&\n !warnedGroups.has(props.id + ':baseline')\n ) {\n warnedGroups.add(props.id + ':baseline');\n console.warn(\n `[sentient] <AdaptiveGroup id=\"${props.id}\">: baseline \"${props.baseline}\" is not the first-declared arrangement (\"${arrangementIds[0]}\"). The first arrangement should usually be the page's real incumbent (the holdout sees it).`,\n );\n }\n\n const childArray = Children.toArray(props.children).filter(isValidElement);\n const byKey = new Map<string, (typeof childArray)[number]>();\n for (const child of childArray) {\n // Children.toArray prefixes explicit keys with '.$'.\n byKey.set(String(child.key ?? '').replace(/^\\.\\$/, ''), child);\n }\n\n const order = props.arrangements[arm];\n const canReorder =\n order !== undefined &&\n order.length === childArray.length &&\n order.every((key) => byKey.has(key));\n\n if (\n isDevBuild() &&\n order !== undefined &&\n !canReorder &&\n !warnedGroups.has(props.id + ':keys')\n ) {\n warnedGroups.add(props.id + ':keys');\n console.warn(\n `[sentient] <AdaptiveGroup id=\"${props.id}\">: arrangement \"${arm}\" [${order.join(', ')}] does not match the children's keys — rendering declaration order (fail-safe).`,\n );\n }\n\n const ordered = canReorder ? order.map((key) => byKey.get(key)!) : childArray;\n\n // Devtools slot registry — the declared arms space drives persona simulation\n // and the panel's per-arm override buttons. A group is a slot, not a component:\n // registering it as one produced buttons that wrote the wrong override channel.\n useEffect(\n () => registerSlot({ id: props.id, arms: Object.keys(props.arrangements) }),\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [props.id],\n );\n\n // Exposure — once per (group, arrangement). An unresolved `baseline` source\n // means the group was never decided (interim local decide, or a keyed client\n // with no SSR preload); exposing it would record a phantom baseline\n // impression that can never convert, so skip until a real arm resolves.\n const exposedArmRef = useRef<string | null>(null);\n useEffect(() => {\n // A forced arm (`override`, from devtools/tests) is a preview, not a real\n // exposure — skip it so the optimizer isn't trained on the override (same\n // contract <Adaptive> honors for component overrides). `seeded` — a\n // snapshot arm or failure baseline the core holds without a decision for\n // this session — renders but is not a trial either.\n if (!client || source === 'baseline' || source === 'seeded' || source === 'override' || exposedArmRef.current === arm) return;\n exposedArmRef.current = arm;\n trackExposure(client, apiKey, props.id, arm);\n }, [client, apiKey, props.id, arm, source]);\n\n // Funnel membership declaration — same override gate as the exposure. A\n // weighted composite with no `funnel` declares its own (compositeFunnelId).\n const funnel = props.funnel;\n const declaredGoalKey = props.goal === undefined || typeof props.goal === 'string' ? '' : JSON.stringify(props.goal);\n useEffect(() => {\n if (!client || source === 'override') return;\n maybeDeclareFunnel(client, apiKey, props.id, funnel, normalizeGoal(props.goal ?? 'click'));\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [client, apiKey, props.id, funnel, declaredGoalKey, source]);\n\n // Optional goal — slot-scoped credit through componentGoal (the core\n // resolves the attributed arm from its slot state; see Task 3.3).\n const goalKey =\n props.goal === undefined ? null : typeof props.goal === 'string' ? props.goal : JSON.stringify(props.goal);\n useEffect(() => {\n // Forced arms record nothing (preview only), and an unresolved `baseline`\n // source never recorded an impression (see the exposure effect above) — a\n // conversion attached in that state would attribute to an arm with zero\n // exposures. Same source gates as the exposure.\n if (!client || props.goal === undefined || source === 'override' || source === 'baseline' || source === 'seeded') return;\n const node = containerRef.current;\n if (!node) return;\n const label = goalLabelOf(props.goal);\n const declaredValue = goalValueOf(props.goal);\n let fired = false;\n return attachGoalListeners(node, normalizeGoal(props.goal), {\n fireGoal: () => {\n if (fired) return;\n fired = true;\n // componentGoal credits the bandit; goal() writes the session-level\n // conversion funnel record — matching <Adaptive>. Firing only the\n // former left group conversions out of the goal funnel. A static\n // goal-config value rides on both writes (spec §5).\n if (declaredValue !== undefined) client.componentGoal(props.id, label, { value: declaredValue });\n else client.componentGoal(props.id, label);\n client.goal(label, {\n metadata: { componentId: props.id, arm },\n weight: 1.0,\n stepIndex: 0,\n ...(declaredValue !== undefined ? { value: declaredValue } : {}),\n });\n },\n fireStep: (name, weight, stepIndex) => {\n client.componentGoal(props.id, name, { reward: weight });\n client.goal(name, { metadata: { componentId: props.id, arm }, weight, stepIndex });\n },\n }, label);\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [client, props.id, goalKey, arm, source]);\n\n return (\n <div ref={containerRef} data-sentient-id={props.id} data-sentient-variant={arm}>\n {ordered}\n </div>\n );\n}\n","/** @deprecated Use `useSessionSegment()` (exported from `@sentientui/react`) for the segment the\n * provider uses, or `deriveSessionSegment` from `@sentientui/core` outside React. Removed in 1.0. */\nexport { deriveSessionSegment as detectSegment } from '@sentientui/core';\n","/**\n * Agent-readable content feed. Merges SDK-known data (winning variants, layout\n * order) with developer-supplied page content, and renders it either as a\n * server-rendered inline JSON-LD block (read by passive AI crawlers, which do\n * not run JS) or as Markdown (for agents that content-negotiate `text/markdown`).\n *\n * No React or DOM APIs — safe to import in server components, route handlers,\n * and middleware.\n */\n\nexport type AgentBlock = {\n /** Component ID. */\n id: string;\n /** Winning variant ID currently served. */\n variant: string;\n /** Agent-readable data attached to the served variant, if any. */\n content?: unknown;\n};\n\nexport type AgentFeed = {\n page: string;\n title?: string;\n summary?: string;\n layoutOrder?: string[];\n blocks: AgentBlock[];\n /** Developer-supplied extra fields (products, specs, arbitrary JSON). */\n [key: string]: unknown;\n};\n\n/** Fields the SDK owns — developer content can never overwrite these. */\nconst RESERVED_FIELDS = ['page', 'blocks', 'layoutOrder'] as const;\n\nconst registry = new Map<string, Record<string, unknown>>();\n\n/**\n * Register page-level structured content the SDK can't infer (title, summary,\n * product fields, arbitrary JSON), keyed by page path. Call at module load.\n */\nexport function defineAgentContent(page: string, content: Record<string, unknown>): void {\n registry.set(page, content);\n}\n\n/** Look up registered content for a page. */\nexport function getAgentContent(page: string): Record<string, unknown> | undefined {\n return registry.get(page);\n}\n\n/** Clear the registry — intended for tests. */\nexport function clearAgentContent(): void {\n registry.clear();\n}\n\n/**\n * Merge SDK-known data with developer-supplied content into a single feed.\n * Developer content fills in title/summary/etc. but can never overwrite the\n * SDK-authoritative fields (`page`, `blocks`, `layoutOrder`).\n */\nexport function buildAgentFeed(input: {\n page: string;\n blocks: AgentBlock[];\n layoutOrder?: string[];\n content?: Record<string, unknown>;\n}): AgentFeed {\n const supplied = input.content ?? getAgentContent(input.page) ?? {};\n const safe: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(supplied)) {\n if (!(RESERVED_FIELDS as readonly string[]).includes(k)) safe[k] = v;\n }\n const feed: AgentFeed = {\n ...safe,\n page: input.page,\n blocks: input.blocks,\n };\n if (input.layoutOrder) feed.layoutOrder = input.layoutOrder;\n return feed;\n}\n\n/**\n * Render the feed as a server-rendered inline JSON-LD `<script>` string. `<` is\n * escaped to `<` so embedded content cannot break out of the script\n * element. MUST be emitted on the server — passive crawlers never run client JS.\n */\nexport function renderAgentJsonLd(feed: AgentFeed): string {\n return `<script type=\"application/ld+json\">${renderAgentJsonLdBody(feed)}</script>`;\n}\n\n/**\n * The escaped JSON-LD body only (no `<script>` wrapper). For React server\n * components, inject via `<script type=\"application/ld+json\"\n * dangerouslySetInnerHTML={{ __html: renderAgentJsonLdBody(feed) }} />`.\n */\nexport function renderAgentJsonLdBody(feed: AgentFeed): string {\n return JSON.stringify({ '@context': 'https://schema.org', '@type': 'WebPage', ...feed })\n .replace(/</g, '\\\\u003c');\n}\n\n/** Render the feed as Markdown for agents that negotiate `text/markdown`. */\nexport function renderAgentMarkdown(feed: AgentFeed): string {\n const lines: string[] = [];\n if (feed.title) lines.push(`# ${feed.title}`, '');\n if (feed.summary) lines.push(String(feed.summary), '');\n\n for (const [k, v] of Object.entries(feed)) {\n if (['page', 'title', 'summary', 'blocks', 'layoutOrder'].includes(k)) continue;\n lines.push(`## ${k}`, '', '```json', JSON.stringify(v, null, 2), '```', '');\n }\n\n if (feed.blocks.length > 0) {\n lines.push('## blocks', '');\n for (const b of feed.blocks) {\n lines.push(`- **${b.id}** → variant \\`${b.variant}\\``);\n if (b.content !== undefined) {\n lines.push('', ' ```json', JSON.stringify(b.content, null, 2), ' ```');\n }\n }\n lines.push('');\n }\n\n return lines.join('\\n').trimEnd() + '\\n';\n}\n","export { AdaptiveProvider, useSentient, useInitialAssignments, useLayoutOrder, useAdaptiveApiBaseUrl, useSessionSegment } from './provider.js';\nexport type { AdaptiveProviderProps, SsrFallback } from './provider.js';\n// The vocabulary `sectionTypes` accepts, so a typed app can build the map\n// without a direct @sentientui/core dependency.\nexport type { SemanticType } from '@sentientui/core/engagement';\n\nexport { Adaptive } from './adaptive.js';\nexport type {\n AdaptiveProps,\n AdaptiveVariantsProps,\n AdaptiveGeneratedProps,\n AdaptiveElement,\n GoalConfig,\n ClickGoal,\n ScrollDepthGoal,\n FormSubmitGoal,\n CompositeGoal,\n WeightedStep,\n WeightedCompositeGoal,\n MicroSignalGoals,\n MicroSignalGoalConfig,\n} from './adaptive.js';\n\nexport { AdaptiveText } from './adaptive-text.js';\nexport type { AdaptiveTextProps } from './adaptive-text.js';\n\n/**\n * @deprecated Use {@link useAdaptive} instead — it selects a variant AND wires\n * exposure, goal, and micro-signal tracking. `useAssignment` only selects, so a\n * component built on it directly records no learning signal. Kept exported for\n * back-compat (it is `useAdaptive`'s internal selection engine); moving to\n * internal-only in 1.0.0.\n */\nexport { useAssignment } from './use-assignment.js';\nexport type { AssignmentState } from './use-assignment.js';\n\nexport { useAdaptiveGoal } from './use-adaptive-goal.js';\nexport type { FireGoal } from './use-adaptive-goal.js';\n\nexport { usePageGoal } from './use-page-goal.js';\nexport type { PageGoalOptions } from './use-page-goal.js';\n\nexport type { Register, GoalName } from './goal-names.js';\nexport { useGoal } from './use-goal.js';\nexport type { UseGoalOptions, FireNamedGoal } from './use-goal.js';\n\nexport { SentientPersonaScript } from './persona-script.js';\nexport type { SentientPersonaScriptProps } from './persona-script.js';\n\nexport { useAdaptiveTokens } from './use-adaptive-tokens.js';\n\nexport { AdaptiveSlot } from './adaptive-slot.js';\nexport type { AdaptiveSlotProps } from './adaptive-slot.js';\nexport type { UseAdaptiveTokensOptions, UseAdaptiveTokensResult } from './use-adaptive-tokens.js';\n\nexport { useAdaptive } from './use-adaptive.js';\nexport type { UseAdaptiveResult, UseAdaptiveBind } from './use-adaptive.js';\n\nexport { useAdaptivePersona } from './use-slot-result.js';\nexport type { AdaptivePersona } from './use-slot-result.js';\n\nexport { AdaptiveGroup } from './adaptive-group.js';\nexport type { AdaptiveGroupProps } from './adaptive-group.js';\n\nexport type { ComponentWeights, VariantWeight } from './weights-store.js';\n\nexport { detectSegment } from './segment.js';\n\nexport {\n defineAgentContent,\n getAgentContent,\n buildAgentFeed,\n renderAgentJsonLd,\n renderAgentJsonLdBody,\n renderAgentMarkdown,\n} from './agent-feed.js';\nexport type { AgentFeed, AgentBlock } from './agent-feed.js';\n\n// Re-exported from core so a React app can wire its consent banner to the SDK\n// without adding @sentientui/core as a direct dependency — the docs already\n// point React users at grantConsent(), so it belongs on this entry.\n//\n// Safe here, unlike the server-only helpers re-exported from /next — though\n// not for the reason once claimed: tsup DOES stamp a 'use client' banner on\n// this bundle (see tsup.config.ts), so this re-export IS a client reference.\n// It stays safe because grantConsent is browser-only (it returns immediately\n// during SSR), so it is only ever invoked from client components and the\n// client reference is never called on the server.\nexport { grantConsent } from '@sentientui/core';\n\n// Composition Block renderer, exported for operator surfaces (the dashboard's\n// review preview renders a pending arm exactly as AdaptiveSlot would, with the\n// same palette). Not needed for normal SDK integration — AdaptiveSlot renders\n// served arms itself.\nexport { renderBlocks, renderCompose } from './blocks-render.js';\nexport type { RenderBlocksOptions } from './blocks-render.js';\nexport type { SitePalette } from '@sentientui/core';\n// Consent platforms (Cookiebot, OneTrust, CookieYes, IAB TCF, Google Consent\n// Mode): the same watcher `consentFrom` uses, for gating a site's OTHER\n// consent-bound scripts (an ad pixel) on the same platform, from one package.\nexport { consentWatcher } from '@sentientui/core/consent';\nexport type { ConsentSource, ConsentPreset, ConsentWatcher } from '@sentientui/core';\n"],"mappings":";omBAMA,OACE,iBAAAA,GACA,cAAAC,EACA,aAAAC,GACA,WAAAC,GACA,UAAAC,GACA,YAAAC,GACA,wBAAAC,OAGK,QACP,OACE,wBAAAC,GACA,QAAAC,OASK,mBCZP,IAAMC,GAAQ,IAAI,IACZC,GAAY,IAAI,IAMf,SAASC,GAAUC,EAAqBC,EAA0B,CACvE,IAAIC,EAAMJ,GAAU,IAAIE,CAAW,EACnC,OAAKE,IACHA,EAAM,IAAI,IACVJ,GAAU,IAAIE,EAAaE,CAAG,GAEhCA,EAAI,IAAID,CAAE,EACH,IAAM,CACXC,EAAK,OAAOD,CAAE,EACVC,EAAK,OAAS,GAAGJ,GAAU,OAAOE,CAAW,CACnD,CACF,CAMO,SAASG,GAAOH,EAAqBI,EAAiC,CAC3EP,GAAM,IAAIG,EAAaI,CAAO,EAC9B,IAAMF,EAAMJ,GAAU,IAAIE,CAAW,EACrC,GAAKE,EACL,QAAWD,KAAMC,EACf,GAAI,CACFD,EAAGG,CAAO,CACZ,OAAQC,EAAA,CAER,CAEJ,CA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A,OAAS,gBAAAE,OAAoB,mBAY7B,OAAS,kBAAAC,OAAsB","names":["createContext","useContext","useEffect","useMemo","useRef","useState","useSyncExternalStore","deriveSessionSegment","init","store","listeners","subscribe","componentId","cb","set","update","weights","e","getWeights","_a","ssrFallback","state","w","getPreviewMode","state","subscribePreview","fn","listeners","createPreviewClient","inner","componentId","segment","_a","_b","variantIds","agentData","agentDataByVariant","opts","slotId","ids","EVENT","getOverridesVersion","_a","notifyOverridesChanged","w","subscribeOverridesChanged","fn","publishDevtoolsConfig","config","isDevBuild","_a","normalizeGoal","goal","goalLabelOf","goalValueOf","scrollFiredThisTask","scrollGateClearArmed","scrollFireCollapsedThisTask","key","clear","ch","isClickableTarget","el","tag","findClickable","start","container","selector","cursor","e","attachGoalListeners","node","handlers","scrollDedupeKey","firedSteps","wcCleanups","sub","stepName","stepWeight","idx","fireStep","viaScroll","onClick","target","onSubmit","threshold","io","entries","entry","subgoals","remaining","_","i","fireViaScroll","checkComposite","cleanups","c","declaredFunnels","declaredMemberships","compositeFunnelId","componentId","slug","h","i","MAX_FUNNEL_STEPS","compositeFunnelSteps","goal","seen","steps","s","n","ordered","a","b","isDevBuild","maybeDeclareFunnel","client","apiKey","explicitFunnelId","composite","funnelId","memberKey","declaredMemberships","declaredFunnels","withSteps","trackExposure","variantId","ssrFallback","state","w","emit","fn","NOOP_UNREGISTER","registerComponent","c","isDevBuild","registerSlot","s","registerSections","sections","version","SDK_IDENT","store","w","setSlotConfigOverride","slotId","entry","setVocabularyOverride","v","getVocabularyOverride","_a","store","w","setSlotOverride","slotId","result","takeHashParam","name","v","h","m","after","rest","e","TOKEN_KEY","pending","active","editorSessionActive","cached","editorSession","apiBase","code","takeHashParam","t","res","token","e","endEditorSession","PARAM_CELL","PARAM_REFRESH","BAR_ID","PREVIEW_ARM","pendingRefresh","takeRegionRefresh","slotId","r","submitRegionRefresh","body","s","__spreadValues","res","mountBar","maybeStartCellPreview","apiBaseUrl","cell","refresh","params","e","base","session","editorSession","editorSessionActive","setSlotConfigOverride","setSlotOverride","notifyOverridesChanged","sep","persona","data","setVocabularyOverride","_a","text","bar","label","exit","endEditorSession","url","started","maybeCaptureStyles","apiBaseUrl","base","editorSession","session","capture","token","run","sampleStyleVocabulary","jsx","deriveDefaultSegment","_a","_b","deriveSessionSegment","e","DEFAULT_API_BASE_URL","AdaptiveContext","createContext","warnedNoConsentGate","answeredThisPage","useConsentSource","source","apiKey","onRefused","onRefusedRef","useRef","granted","setGranted","useState","refused","setRefused","sourceRef","key","__spreadProps","__spreadValues","useEffect","s","stop","cancelled","consentWatcher","forgetVisitor","watcher","wasRefused","update","r","g","AdaptiveProvider","props","_c","_d","_e","_f","client","setClient","sessionSegment","previewOn","setPreviewOn","getPreviewMode","subscribePreview","maybeStartCellPreview","maybeCaptureStyles","dropHeldRef","consent","forgetOnFalse","forgetRef","clientRef","trackingRef","heldRef","refusedRef","c","tracking","adopt","config","SDK_IDENT","created","stopEngagement","handOff","call","startEngagement","startEngagementCapture","initGraph","init","poll","entries","entry","weights","v","timerId","ssrFallback","apiBaseUrl","frozenConfigRef","current","prev","publishDevtoolsConfig","identityUser","identityHash","identityEmail","decided","registerSections","isDevBuild","declared","present","el","missing","id","exposedClient","useMemo","createPreviewClient","value","_g","_h","_i","NO_UNIFIED","useSentient","useContext","useAdaptiveApiKey","useInitialAssignments","useInitialUnified","useSessionSegment","useSsrFallback","useOnAssignment","useDebug","useLayoutOrder","contextOrder","override","useSyncExternalStore","subscribeOverridesChanged","useInitialSlots","useInitialPersona","useInitialSlotConfig","useInitialPalette","useInitialVocabulary","useAdaptiveApiBaseUrl","memo","useCallback","useEffect","useState","useCallback","useEffect","useMemo","useRef","useState","attachMicroSignalDetectors","useEffect","useRef","useState","useSyncExternalStore","pickFromWeights","getDevOverride","componentId","_a","global","params","raw","sep","e","useAssignment","componentId","variantIds","agentData","agentDataByVariant","opts","initialAssignments","useInitialAssignments","ssrFallback","useSsrFallback","client","useSentient","segment","useSessionSegment","onAssignment","useOnAssignment","debug","useDebug","assignmentReportedRef","useRef","devOverride","useSyncExternalStore","subscribeOverridesChanged","getDevOverride","overrideVariant","overrideLoggedRef","useEffect","state","setState","useState","_a","_b","preloaded","cached","weights","getWeights","chosen","pickFromWeights","reportAssignment","variantId","prev","cancelled","onUnified","result","subscribe","useVariantComponent","id","variants","opts","client","useSentient","apiKey","useAdaptiveApiKey","variantKey","variantIds","useMemo","variantId","content","isOverride","settled","useAssignment","node","setNode","useState","nodeRef","useRef","ref","useCallback","el","rawGoal","goalKey","goal","normalizeGoal","goalLabel","goalLabelOf","useEffect","registerComponent","exposedRef","trackExposure","goalFiredRef","microGoalFiredRef","funnel","maybeDeclareFunnel","cursorSignal","timerId","hoverStart","onEnter","onLeave","microSignalGoalsRef","microKey","assignedAt","attachMicroSignalDetectors","signalType","extra","_a","_b","_c","__spreadValues","mapping","name","weight","stepIndex","declaredValue","goalValueOf","attachGoalListeners","useEffect","useMemo","useRef","useState","useSyncExternalStore","attachMicroSignalDetectors","containsFormBlock","reveal","captureRegionSkeleton","useCallback","useEffect","useRef","useSyncExternalStore","armOfResult","warnedUnservedSlots","FORCED_ARM_CONFIG","useSlotConfig","slotId","opts","_a","_b","_c","client","useSentient","baselineTextRef","useRef","renderRef","skeletonRef","initialSlots","useInitialSlots","initialSlotConfig","useInitialSlotConfig","initialPalette","useInitialPalette","initialVocabulary","useInitialVocabulary","overrideConfig","useSyncExternalStore","subscribeOverridesChanged","overrideResult","armOf","r","armOfResult","subscribeSlots","useCallback","cb","preloaded","fromClient","palette","vocabulary","resolution","getVocabularyOverride","decided","deferred","settled","useEffect","_d","_e","unserved","text","texts","caps","skeleton","extras","__spreadValues","hasExtras","isDevBuild","cloneElement","Fragment","jsx","jsxs","safeBlockUrl","v","GAP","FLEX_POS","FONT_SIZE","HEADING_SIZE","BTN_PAD","SPACER","RATIO","WEIGHT","toneStyles","tone","palette","__spreadValues","buttonStyle","emphasis","size","_a","_b","_c","_d","accent","__spreadProps","FormNode","node","opts","_e","fieldStyle","e","data","values","f","o","classOf","like","inheritedColor","x","renderBlocks","el","renderOwn","color","cloneElement","_f","_g","_h","_i","_j","_k","_l","_m","_n","_o","_p","_q","_r","_s","_t","_u","_v","_w","cls","gap","raised","pad","child","i","rendered","Fragment","Tag","renderCompose","compose","body","surface","cloneElement","isValidElement","normalizeLeafText","skeletonFingerprint","isTextLeaf","node","childrenOf","el","props","countTextLeaves","n","c","isValidElement","withChildren","children","cloneElement","replaceOnlyLeaf","text","inner","substituteSlotText","keyOf","p","indexTree","path","out","normalizeLeafText","buildIndex","idx","reactLeafTexts","reactFingerprint","skeletonFingerprint","enclosingElements","leaf","s","i","nodeOwners","leafToNode","count","m","owners","k","lists","common","l","keys","classNameOf","_a","annotateSkeletonForReact","skeleton","t","nodes","owner","restylable","__spreadProps","__spreadValues","applyEdits","edits","nodeCount","firstLeaf","leafAt","hidden","restyle","failed","ks","e","src","target","cls","pendingOrders","rebuild","g","perm","positions","o","slots","a","b","before","slot","key","rebuilt","jsx","warnedFormSlots","warnedOpaqueSlots","warnedBlockedSlots","AUTHORED_PREFIX","AdaptiveSlot","id","children","variants","onFormSubmit","goal","className","Tag","reportBaselineText","funnel","microSignalGoals","clientOnly","agentDataByVariant","agentData","variantsOnly","_a","_b","client","useSentient","apiKey","useAdaptiveApiKey","nodeRef","useRef","mounted","setMounted","useState","useEffect","hidden","childFp","useMemo","reactFingerprint","authoredKey","caps","__spreadValues","countTextLeaves","captureSkeleton","el","cap","captureRegionSkeleton","annotateSkeletonForReact","__spreadProps","n","forcedKey","useSyncExternalStore","subscribeOverridesChanged","getDevOverride","forcedArm","config","arm","palette","vocabulary","source","useSlotConfig","tree","composed","formBlocked","containsFormBlock","isDevBuild","fireFormGoal","goalName","body","armBlocked","authoredArm","rendered","renderCompose","renderBlocks","e","placed","applyEdits","substituteSlotText","textBlocked","authoredOnScreen","sk","text","editsDrift","showsChildren","r","takeRegionRefresh","submitRegionRefresh","armsKey","devVariantIds","registerComponent","registerSlot","exposedArmRef","trackExposure","armCreditable","goalArm","goalKey","node","label","goalLabelOf","declaredValue","goalValueOf","fired","attachGoalListeners","normalizeGoal","name","weight","stepIndex","goalConfig","maybeDeclareFunnel","microRef","microFiredRef","microKey","attachMicroSignalDetectors","signalType","extra","_c","mapping","agentRef","agentSentRef","fallback","byArm","lookup","data","revealedArm","reveal","dataProps","jsx","AdaptiveImpl","props","_a","_b","client","variantId","content","ref","useVariantComponent","mounted","setMounted","useState","useEffect","Tag","jsxContent","managedContent","isDevBuild","AdaptiveVariants","memo","prev","next","prevKeys","nextKeys","k","Adaptive","AdaptiveSlot","__spreadValues","v","variants","slotProps","__objRest","__spreadProps","AdaptiveVariantsOrUnified","unifiedId","setUnifiedId","id","onUnified","useCallback","useSentient","known","useInitialUnified","_children","rest","first","useEffect","useMemo","useRef","useState","useSyncExternalStore","jsx","AdaptiveText","id","defaultText","Tag","className","goalProp","_a","client","useSentient","apiKey","useAdaptiveApiKey","onAssignment","useOnAssignment","segment","useSessionSegment","trackedRef","useRef","nodeRef","override","useSyncExternalStore","subscribeOverridesChanged","getDevOverride","text","setText","useState","_b","variantId","setVariantId","useEffect","cached","cancelled","result","isDevBuild","goalKey","goal","useMemo","normalizeGoal","goalLabel","goalFiredRef","maybeDeclareFunnel","node","declaredValue","goalValueOf","attachGoalListeners","__spreadValues","name","weight","stepIndex","displayText","el","useCallback","useRef","goalOptionsOf","opts","_a","_b","__spreadValues","useAdaptiveGoal","componentId","client","useSentient","firedOnce","useRef","useCallback","goalType","getDevOverride","useEffect","useRef","usePageGoal","goalName","opts","_a","componentId","goalOpts","__objRest","client","useSentient","fireComponentGoal","useAdaptiveGoal","fired","useRef","optsRef","useEffect","goalOptionsOf","useCallback","useEffect","useRef","declared","primaryByKey","declareGoal","client","apiKey","name","primary","asPrimary","existing","primaryByKey","isDevBuild","key","declared","useGoal","options","componentId","useSentient","useAdaptiveApiKey","fireComponentGoal","useAdaptiveGoal","firedOnce","useRef","useEffect","useCallback","opts","goalOptionsOf","renderPrePaintScript","confidenceBand","jsx","inlineJsString","value","personaScriptBody","props","SentientPersonaScript","useEffect","useMemo","useRef","validateSlotDecl","useEffect","useReducer","useState","useSyncExternalStore","armOfResult","baselineResultFor","confidenceBand","useSlotResult","slotId","decl","client","useSentient","initialSlots","useInitialSlots","bump","useReducer","n","override","useSyncExternalStore","subscribeOverridesChanged","_a","preloaded","fromClient","needsLocalDecide","useEffect","cancelled","outcome","resolution","armOfResult","decided","baseline","baselineResultFor","settled","off","getPersonaOverride","forced","value","e","useAdaptivePersona","initialPersona","useInitialPersona","getOverridesVersion","mounted","setMounted","useState","withBand","p","confidenceBand","live","warnedTokenSlots","cssEscape","value","useAdaptiveTokens","id","dims","opts","client","useSentient","apiKey","useAdaptiveApiKey","dimsKey","decl","useMemo","result","arm","source","useSlotResult","tokens","isDevBuild","validity","validateSlotDecl","k","v","space","n","values","goalKey","useEffect","registerSlot","exposedArmRef","useRef","trackExposure","funnel","_a","maybeDeclareFunnel","normalizeGoal","node","label","goalLabelOf","declaredValue","goalValueOf","fired","attachGoalListeners","__spreadValues","name","weight","stepIndex","props","dim","useCallback","useEffect","useMemo","warnedUnbound","warnedUnified","useAdaptive","id","config","_a","_b","isDevBuild","client","variantIds","variantId","isOverride","goalLabel","ref","nodeRef","useVariantComponent","variant","value","knownUnified","useInitialUnified","useEffect","timer","fireGoal","useCallback","goalType","opts","name","__spreadValues","bind","useMemo","Children","isValidElement","useEffect","useMemo","useRef","jsx","warnedGroups","AdaptiveGroup","props","_a","client","useSentient","apiKey","useAdaptiveApiKey","containerRef","useRef","arrangementKey","arrangementIds","useMemo","decl","__spreadValues","arm","source","useSlotResult","isDevBuild","childArray","Children","isValidElement","byKey","child","order","canReorder","key","ordered","useEffect","registerSlot","exposedArmRef","trackExposure","funnel","declaredGoalKey","maybeDeclareFunnel","normalizeGoal","goalKey","node","label","goalLabelOf","declaredValue","goalValueOf","fired","attachGoalListeners","name","weight","stepIndex","deriveSessionSegment","RESERVED_FIELDS","registry","defineAgentContent","page","content","getAgentContent","buildAgentFeed","input","_a","_b","supplied","getAgentContent","safe","k","v","RESERVED_FIELDS","feed","__spreadProps","__spreadValues","renderAgentJsonLd","renderAgentJsonLdBody","renderAgentMarkdown","lines","b","grantConsent","consentWatcher"]}
|