@sentientui/react 0.44.2 → 0.44.3

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 CHANGED
@@ -10,6 +10,31 @@ learns which one converts best for each visitor type, and measures the lift agai
10
10
  npm install @sentientui/react # or: npx @sentientui/cli init (installs + writes .env.local + an example component)
11
11
  ```
12
12
 
13
+ ## Install with shadcn
14
+
15
+ The public repo [SentientUI/sdk](https://github.com/SentientUI/sdk) is a
16
+ [shadcn registry](https://ui.shadcn.com/docs/registry/github). In a project with a
17
+ `components.json`:
18
+
19
+ ```bash
20
+ # components/sentient-provider.tsx: AdaptiveProvider for the root layout; installs @sentientui/react
21
+ npx shadcn@latest add SentientUI/sdk/sentient-provider # Next.js
22
+ npx shadcn@latest add SentientUI/sdk/sentient-provider-vite # Vite: same file, key from import.meta.env
23
+ # components/adaptive-section.tsx: an example hero in <Adaptive id="hero">, using shadcn's Button
24
+ npx shadcn@latest add SentientUI/sdk/adaptive-section
25
+ # .claude/skills and .agents/skills: setup rules for AI coding agents
26
+ npx shadcn@latest add SentientUI/sdk/sentientui-setup
27
+ ```
28
+
29
+ Then render `<SentientProvider>{children}</SentientProvider>` inside `<body>` in `app/layout.tsx`
30
+ and set `NEXT_PUBLIC_SENTIENT_API_KEY`. The provider is `<AdaptiveProvider>`, so every route stays
31
+ static (see [Setup](#setup)). Set `NEXT_PUBLIC_SENTIENT_INTERNAL=true` on staging and preview
32
+ deploys only: it marks those visits internal
33
+ ([Excluding your team and test sites](#excluding-your-team-and-test-sites)). In a Vite app, render
34
+ `<SentientProvider>` around `<App />` in `src/main.tsx` and set `VITE_SENTIENT_API_KEY` /
35
+ `VITE_SENTIENT_INTERNAL` instead (see [Vite](#vite-and-other-react-spas)). The installed files
36
+ are yours to edit. Append `#<tag or commit>` to an address to pin it.
37
+
13
38
  ## 2-minute start (no account)
14
39
 
15
40
  ```bash
@@ -62,6 +87,59 @@ return visit starts from the last version served, with no network wait. It can b
62
87
  straight from a Server Component, as above. To pass it a function (`onAssignment`, a
63
88
  `consentFrom` with `check()`), put it in a small `'use client'` file of your own instead.
64
89
 
90
+ ### Vite (and other React SPAs)
91
+
92
+ Render the provider once, where the root is created, around everything, router included, so
93
+ a navigation never remounts it (a remount starts a new client):
94
+
95
+ ```tsx
96
+ // src/main.tsx
97
+ import { StrictMode } from 'react';
98
+ import { createRoot } from 'react-dom/client';
99
+ import { BrowserRouter } from 'react-router-dom';
100
+ import { AdaptiveProvider } from '@sentientui/react';
101
+ import App from './App';
102
+
103
+ createRoot(document.getElementById('root')!).render(
104
+ <StrictMode>
105
+ <AdaptiveProvider
106
+ apiKey={import.meta.env.VITE_SENTIENT_API_KEY ?? ''}
107
+ internal={import.meta.env.VITE_SENTIENT_INTERNAL === 'true'}
108
+ // Cookie banner? Name it, e.g. consentFrom="cookiebot" (see Consent management)
109
+ >
110
+ <BrowserRouter>
111
+ <App />
112
+ </BrowserRouter>
113
+ </AdaptiveProvider>
114
+ </StrictMode>,
115
+ );
116
+ ```
117
+
118
+ ```bash
119
+ # .env.local (and the same variable in your host's build settings)
120
+ VITE_SENTIENT_API_KEY=pk_your_key
121
+ ```
122
+
123
+ - **Read the key from `import.meta.env`, never `process.env`.** Vite defines no `process` in the
124
+ browser: `process.env.X` throws `process is not defined` under `vite` dev, and `vite build`
125
+ rewrites it to `{}`, so production silently runs keyless. Only `VITE_`-prefixed variables
126
+ reach browser code, and they are inlined at build time: rebuild after changing one. A
127
+ production build with no key logs `[sentient] No API key configured`.
128
+ - **Route changes need no wiring.** The SDK records a page view on every
129
+ `history.pushState` / `replaceState` and on back/forward, which is how React Router, TanStack
130
+ Router and wouter navigate. For a goal that means "reached this route", call
131
+ `usePageGoal('pricing_view')` in that route's component ([`usePageGoal`](#usepagegoalgoalname-opts)).
132
+ - **Consent** works as documented in [Consent management](#consent-management-gdpr): a
133
+ `consentFrom` preset, the cookie form, a `check()` function (no Server Component boundary
134
+ here, so no extra file needed), or your own `consent={hasConsent}` flag.
135
+ - No `'use client'` is needed in your files. `<AdaptiveRoot>`, `@sentientui/react/next` and the
136
+ static-route advice above are Next.js-only.
137
+ - Every decision happens in the browser, so the first visit shows the originals and then the
138
+ chosen versions after one round trip, as under `<AdaptiveProvider>` in Next.js.
139
+ `<SentientPersonaScript>` needs server-rendered HTML (React does not run an inline script it
140
+ creates in the browser), so a client-only app gets everything except the Rung-1a persona
141
+ attributes in hosted mode.
142
+
65
143
  **Want the chosen version in the first HTML, with no swap?** Use `<AdaptiveRoot>` from
66
144
  `@sentientui/react/next` — but only around the pages that adapt, never as the default in the
67
145
  root layout:
package/dist/devtools.js CHANGED
@@ -1,3 +1,3 @@
1
1
  'use client';
2
- "use strict";"use client";var Ee=Object.create;var R=Object.defineProperty,Ne=Object.defineProperties,De=Object.getOwnPropertyDescriptor,Ae=Object.getOwnPropertyDescriptors,Le=Object.getOwnPropertyNames,ee=Object.getOwnPropertySymbols,We=Object.getPrototypeOf,ne=Object.prototype.hasOwnProperty,Ve=Object.prototype.propertyIsEnumerable;var te=(e,t,o)=>t in e?R(e,t,{enumerable:!0,configurable:!0,writable:!0,value:o}):e[t]=o,l=(e,t)=>{for(var o in t||(t={}))ne.call(t,o)&&te(e,o,t[o]);if(ee)for(var o of ee(t))Ve.call(t,o)&&te(e,o,t[o]);return e},h=(e,t)=>Ne(e,Ae(t));var Me=(e,t)=>{for(var o in t)R(e,o,{get:t[o],enumerable:!0})},oe=(e,t,o,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let a of Le(t))!ne.call(e,a)&&a!==o&&R(e,a,{get:()=>t[a],enumerable:!(s=De(t,a))||s.enumerable});return e};var Be=(e,t,o)=>(o=e!=null?Ee(We(e)):{},oe(t||!e||!e.__esModule?R(o,"default",{value:e,enumerable:!0}):o,e)),Ie=e=>oe(R({},"__esModule",{value:!0}),e);var Qe={};Me(Qe,{AdaptiveDevtools:()=>qe,LOCAL_MODE_DEVTOOLS_BANNER:()=>pe,previewContextParam:()=>H});module.exports=Ie(Qe);var c=require("react"),w=require("@sentientui/policy"),k=require("@sentientui/core");var Te={components:new Map,slots:new Map,sections:[],listeners:new Set,version:0};function C(){if(typeof window=="undefined")return Te;let e=window;return e.__sentient_registry||(e.__sentient_registry={components:new Map,slots:new Map,sections:[],listeners:new Set,version:0}),e.__sentient_registry}function E(){return[...C().components.values()]}function T(){return[...C().slots.values()]}function N(){return[...C().sections]}function ie(e){let t=C().listeners;return t.add(e),()=>{t.delete(e)}}function re(){return C().version}function j(){let e=window;return e.__sentient_overrides||(e.__sentient_overrides={}),e.__sentient_overrides}function z(e,t){j()[e]=t}function U(e){delete j()[e]}function D(){return l({},j())}function F(){let e=window;return e.__sentient_slot_overrides||(e.__sentient_slot_overrides={}),e.__sentient_slot_overrides}function $(e,t){F()[e]=t}function se(e){delete F()[e]}function A(){return l({},F())}var je={on:!1,listeners:new Set};function ae(){if(typeof window=="undefined")return je;let e=window;return e.__sentient_preview||(e.__sentient_preview={on:!1,listeners:new Set}),e.__sentient_preview}function _(e){let t=ae();if(t.on!==e){t.on=e;for(let o of t.listeners)o()}}function de(){return ae().on}var ze="sentient:overrides-changed";function p(){var t;if(typeof window=="undefined")return;let e=window;e.__sentient_overrides_version=((t=e.__sentient_overrides_version)!=null?t:0)+1,window.dispatchEvent(new Event(ze))}function G(){var e;return typeof window=="undefined"?null:(e=window.__sentient_devtools_config)!=null?e:null}var i=require("react/jsx-runtime"),ue,le=typeof process!="undefined"&&((ue=process.env)==null?void 0:ue.NODE_ENV)==="production",ce="https://api.sentient-ui.com/v1",pe="Local mode \u2014 decisions are simulated; add a key to learn from real traffic";function ge(){let e=window.__sentient_layout_override,t=N();return!e||e.length===0?t:[...e,...t.filter(o=>!e.includes(o))]}function Ue(e,t){let o=ge();if(e===t||e<0||t<0||e>=o.length||t>=o.length)return;let s=[...o],[a]=s.splice(e,1);s.splice(t,0,a),window.__sentient_layout_override=s,_(!0),p()}function Fe(){delete window.__sentient_layout_override,p()}function fe(e){var o,s;for(let[a,u]of Object.entries((o=e.assignments)!=null?o:{}))z(a,u);let t=window;e.layoutOrder&&e.layoutOrder.length>0&&(t.__sentient_layout_override=e.layoutOrder),e.slots&&(t.__sentient_slot_overrides=l(l({},(s=t.__sentient_slot_overrides)!=null?s:{}),e.slots)),e.personaAttributes&&(document.documentElement.dataset.sentientPersona=e.personaAttributes.persona,document.documentElement.dataset.sentientConfidence=e.personaAttributes.confidence),_(!0),p()}function $e(e){var o,s;let t=a=>{try{let u=document.cookie.match(new RegExp(`(?:^|; )${a}=([^;]*)`));return u?decodeURIComponent(u[1]):null}catch(u){return null}};return(s=(o=e?t((0,k.sessionCookieName)(e)):null)!=null?o:t(k.LEGACY_SESSION_COOKIE_NAME))!=null?s:"devtools-preview"}function ve(){return T().map(e=>l(l({id:e.id},e.arms?{arms:e.arms}:{}),e.dims?{dims:e.dims}:{}))}var Ge={key:w.UNKNOWN_PERSONA,displayName:w.UNKNOWN_PERSONA_DISPLAY};async function He(e,t){try{let o=await fetch(`${t}/personas`,{headers:{authorization:`Bearer ${e}`}});if(!o.ok)return null;let s=await o.json(),a=b=>Array.isArray(b)?b.filter(f=>f&&typeof f.key=="string"&&typeof f.displayName=="string"):[],u=a(s.personas);return u.length>0?{personas:u,discovered:a(s.discovered)}:null}catch(o){return null}}function H(){try{let e=new URLSearchParams(window.location.search).get("sentient_context");return e&&/^[a-z_]{1,40}$/.test(e)?e:null}catch(e){return null}}async function Ke(e,t,o){var u,b,f;let s=await fetch(`${t}/explain`,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e}`},body:JSON.stringify(l({persona:o,sections:N().map(S=>({id:S})),components:E().map(S=>({id:S.id,variantIds:S.variantIds})),slots:ve()},H()?{context:H()}:{}))});if(!s.ok)return null;let a=await s.json();return fe(h(l({},a),{personaAttributes:(u=a.personaAttributes)!=null?u:{persona:o,confidence:"high"}})),{recognized:a.recognized!==!1,resolvedDisplay:(f=(b=a.personaDisplay)!=null?b:a.persona)!=null?f:o}}async function Ye(e,t){let o=await import("@sentientui/core/local");if(!o.LOCAL_ENGINE_AVAILABLE)return;let s=o.createLocalEngine({sessionId:$e(t),forcedPersona:e}).decide({sections:N(),components:E().map(a=>({id:a.id,variantIds:a.variantIds})),slots:ve()});fe({assignments:s.assignments,layoutOrder:s.layoutOrder,slots:s.slots,personaAttributes:{persona:s.persona,confidence:(0,w.confidenceBand)(s.confidence)}})}function Je(){for(let t of Object.keys(D()))U(t);let e=window;delete e.__sentient_layout_override,delete e.__sentient_slot_overrides,delete document.documentElement.dataset.sentientPersona,delete document.documentElement.dataset.sentientConfidence;try{let t=[];for(let o=0;o<localStorage.length;o++){let s=localStorage.key(o);s&&s.startsWith(k.SNAPSHOT_STORAGE_KEY_PREFIX)&&t.push(s)}for(let o of t)localStorage.removeItem(o)}catch(t){}_(!1),p();try{window.location.reload()}catch(t){}}var g=e=>({padding:"2px 8px",borderRadius:4,border:"1px solid #444",background:e?"#3b82f6":"#222",color:"#eee",cursor:"pointer"});function Xe({size:e=26}={}){return(0,i.jsxs)("svg",{width:e,height:e,viewBox:"0 0 32 32",fill:"none","aria-hidden":"true",children:[(0,i.jsx)("path",{d:"M21 9H14C11.2 9 9.8 10.8 9.8 13C9.8 15.4 11.6 16.6 14.5 16.6H18.5C20.5 16.6 20.7 18.2 20.4 19.6",stroke:"#fff",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round"}),(0,i.jsx)("path",{d:"M10 22H17",stroke:"#fff",strokeWidth:"2.2",strokeLinecap:"round"}),(0,i.jsx)("circle",{cx:"20.6",cy:"22",r:"2.1",fill:"#fff"})]})}function qe({apiKey:e}={}){var Q;let[t,o]=(0,c.useState)(!1),[s,a]=(0,c.useState)(null),[u,b]=(0,c.useState)(null),[f,S]=(0,c.useState)(""),[K,ye]=(0,c.useState)([]),[Y,J]=(0,c.useState)(null),[O,L]=(0,c.useState)(null),[me,_e]=(0,c.useState)(!1),[,v]=(0,c.useReducer)(n=>n+1,0);if((0,c.useSyncExternalStore)(ie,re,()=>0),(0,c.useEffect)(()=>_e(!0),[]),(0,c.useEffect)(()=>{var d;if(le)return;let n=(d=G())!=null?d:{apiKey:e!=null?e:"",apiBaseUrl:ce,isLocal:!1};if(n.isLocal||!n.apiKey)return;let r=!1;return He(n.apiKey,n.apiBaseUrl).then(y=>{r||!y||(b(y.personas),ye(y.discovered))}),()=>{r=!0}},[e]),le||!me)return null;let x=(Q=G())!=null?Q:{apiKey:e!=null?e:"",apiBaseUrl:ce,isLocal:!1},W=x.isLocal||!x.apiKey,P=E(),V=T(),M=D(),X=A(),B=ge(),we=window.__sentient_layout_override!==void 0;function be(n,r){Ue(n,r),v()}function he(){Fe(),I(),v()}function I(){Object.keys(D()).length===0&&Object.keys(A()).length===0&&window.__sentient_layout_override===void 0&&_(!1)}function Se(n,r){z(n,r),_(!0),p(),v()}function xe(n){U(n),I(),p(),v()}function ke(n,r){$(n,r),_(!0),p(),v()}function Oe(n,r,d,y){let m=A()[n],Z=m&&typeof m=="object"?l({},m):Object.fromEntries(Object.entries(y!=null?y:{}).map(([Ce,Pe])=>[Ce,Pe[0]]));Z[r]=d,$(n,Z),_(!0),p(),v()}function Re(n){se(n),I(),p(),v()}function q(n){if(a(n.key),J(null),W){Ye(n.key,x.apiKey).then(v).catch(()=>{});return}Ke(x.apiKey,x.apiBaseUrl,n.key).then(r=>{r&&!r.recognized&&J(`\u201C${n.displayName}\u201D isn\u2019t in this project\u2019s personas \u2014 the page is showing the default experience.`),v()}).catch(()=>{})}return(0,i.jsxs)("div",{style:{position:"fixed",bottom:16,right:16,zIndex:2147483647,fontFamily:"system-ui"},children:[(0,i.jsx)("div",{"aria-hidden":!t,style:{position:"absolute",bottom:52,right:0,transformOrigin:"bottom right",transition:"opacity .18s ease, transform .2s cubic-bezier(.16,1,.3,1)",opacity:t?1:0,transform:t?"translateY(0) scale(1)":"translateY(6px) scale(.96)",pointerEvents:t?"auto":"none"},children:(0,i.jsxs)("div",{style:{width:300,maxHeight:460,overflowY:"auto",background:"#111",color:"#eee",borderRadius:8,padding:12,boxShadow:"0 8px 30px rgba(0,0,0,.4)",fontSize:12},children:[x.isLocal&&(0,i.jsx)("div",{style:{background:"#1e293b",border:"1px solid #334155",borderRadius:4,padding:"6px 8px",marginBottom:8},children:pe}),(0,i.jsxs)("div",{style:{opacity:.7,marginBottom:8},children:[P.length," component",P.length===1?"":"s"," \xB7 ",de()?"preview \u2014 writing nothing":"live"]}),(0,i.jsxs)("div",{style:{borderBottom:"1px solid #333",paddingBottom:8,marginBottom:8},children:[(0,i.jsx)("div",{style:{opacity:.7,marginBottom:4},children:"Preview persona"}),(0,i.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",gap:4},children:[[...W?[]:u!=null?u:[],Ge].map(n=>(0,i.jsx)("button",{onClick:()=>q(n),style:g(s===n.key),children:n.displayName},n.key)),(s!==null||Object.keys(M).length>0||Object.keys(X).length>0)&&(0,i.jsx)("button",{onClick:Je,style:h(l({},g(!1)),{color:"#aaa"}),children:"Reset"})]}),(0,i.jsxs)("form",{onSubmit:n=>{n.preventDefault();let r=(0,w.normalizeDeclaredPersona)(f);r&&q({key:r,displayName:r})},style:{display:"flex",gap:4,marginTop:6},children:[(0,i.jsx)("input",{"aria-label":"Persona key",placeholder:"any persona key, e.g. admin",value:f,onChange:n=>S(n.target.value),style:{flex:1,minWidth:0,background:"#111",color:"#fff",border:"1px solid #333",borderRadius:4,padding:"4px 6px",fontSize:12}}),(0,i.jsx)("button",{type:"submit",style:g(!1),children:"Preview"})]}),Y&&(0,i.jsx)("div",{style:{marginTop:6,fontSize:11,color:"#fbbf24"},children:Y}),!W&&K.length>0&&(0,i.jsxs)("div",{style:{marginTop:8},children:[(0,i.jsx)("div",{style:{opacity:.5,fontSize:11,marginBottom:4},children:"Discovered \u2014 not serving yet (promote from the dashboard)"}),(0,i.jsx)("div",{style:{display:"flex",flexWrap:"wrap",gap:4},children:K.map(n=>(0,i.jsx)("span",{title:"Found by clustering your traffic; it starts serving only after promotion.",style:h(l({},g(!1)),{opacity:.45,cursor:"default",display:"inline-block"}),children:n.displayName},n.key))})]})]}),B.length>0&&(0,i.jsxs)("div",{style:{borderBottom:"1px solid #333",paddingBottom:8,marginBottom:8},children:[(0,i.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:4},children:[(0,i.jsx)("span",{style:{opacity:.7},children:"Layout \u2014 drag to reorder"}),we&&(0,i.jsx)("button",{"aria-label":"Reset section order",onClick:he,style:h(l({},g(!1)),{color:"#aaa"}),children:"reset"})]}),(0,i.jsx)("ul",{"aria-label":"Section order",style:{listStyle:"none",margin:0,padding:0},children:B.map((n,r)=>(0,i.jsxs)("li",{draggable:!0,onDragStart:()=>L(r),onDragOver:d=>d.preventDefault(),onDrop:d=>{d.preventDefault(),O!==null&&be(O,r),L(null)},onDragEnd:()=>L(null),style:{display:"flex",alignItems:"center",gap:6,padding:"4px 6px",marginBottom:2,borderRadius:4,border:"1px solid #262626",cursor:"grab",background:O===r?"#1e293b":"#181818",opacity:O!==null&&O!==r?.6:1},children:[(0,i.jsx)("span",{style:{opacity:.4,minWidth:10,fontVariantNumeric:"tabular-nums"},children:r+1}),(0,i.jsx)("span",{"aria-hidden":"true",style:{opacity:.35},children:"\u283F"}),(0,i.jsx)("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:n})]},n))})]}),P.length===0&&V.length===0&&B.length===0&&(0,i.jsx)("div",{style:{opacity:.6},children:"No components, sections or slots on this page yet."}),P.map(n=>(0,i.jsxs)("div",{style:{borderTop:"1px solid #333",padding:"8px 0"},children:[(0,i.jsxs)("div",{style:{fontWeight:600},children:[n.id,n.goal?` \xB7 goal: ${n.goal}`:""]}),(0,i.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",gap:4,marginTop:4},children:[n.variantIds.map(r=>(0,i.jsx)("button",{onClick:()=>Se(n.id,r),style:g(M[n.id]===r),children:r},r)),M[n.id]&&(0,i.jsx)("button",{onClick:()=>xe(n.id),style:h(l({},g(!1)),{color:"#aaa"}),children:"reset"})]})]},n.id)),V.length>0&&(0,i.jsxs)("div",{style:{borderTop:"1px solid #333",paddingTop:8,marginTop:4},children:[(0,i.jsx)("div",{style:{opacity:.7,marginBottom:4},children:"Slots"}),V.map(n=>{let r=X[n.id];return(0,i.jsxs)("div",{style:{padding:"6px 0"},children:[(0,i.jsx)("div",{style:{fontWeight:600},children:n.id}),n.arms&&(0,i.jsx)("div",{style:{display:"flex",flexWrap:"wrap",gap:4,marginTop:4},children:n.arms.map(d=>(0,i.jsx)("button",{onClick:()=>ke(n.id,d),style:g(r===d),children:d},d))}),n.dims&&Object.entries(n.dims).map(([d,y])=>(0,i.jsxs)("div",{style:{marginTop:4},children:[(0,i.jsx)("div",{style:{opacity:.6,fontSize:11},children:d}),(0,i.jsx)("div",{style:{display:"flex",flexWrap:"wrap",gap:4},children:y.map(m=>(0,i.jsx)("button",{onClick:()=>Oe(n.id,d,m,n.dims),style:g(!!r&&typeof r=="object"&&r[d]===m),children:m},m))})]},d)),r!==void 0&&(0,i.jsx)("button",{onClick:()=>Re(n.id),style:h(l({},g(!1)),{color:"#aaa",marginTop:4}),children:"reset"})]},n.id)})]})]})}),(0,i.jsx)("button",{"aria-label":"Sentient DevTools","aria-expanded":t,onClick:()=>o(n=>!n),style:{width:44,height:44,borderRadius:12,border:"1px solid #2a2a2a",background:"#000",display:"flex",alignItems:"center",justifyContent:"center",padding:0,cursor:"pointer",boxShadow:"0 6px 18px rgba(0,0,0,.4)"},children:(0,i.jsx)(Xe,{})})]})}0&&(module.exports={AdaptiveDevtools,LOCAL_MODE_DEVTOOLS_BANNER,previewContextParam});
2
+ "use strict";"use client";var Ee=Object.create;var R=Object.defineProperty,De=Object.defineProperties,Ne=Object.getOwnPropertyDescriptor,Ae=Object.getOwnPropertyDescriptors,Le=Object.getOwnPropertyNames,ee=Object.getOwnPropertySymbols,We=Object.getPrototypeOf,ne=Object.prototype.hasOwnProperty,Ve=Object.prototype.propertyIsEnumerable;var te=(e,t,o)=>t in e?R(e,t,{enumerable:!0,configurable:!0,writable:!0,value:o}):e[t]=o,l=(e,t)=>{for(var o in t||(t={}))ne.call(t,o)&&te(e,o,t[o]);if(ee)for(var o of ee(t))Ve.call(t,o)&&te(e,o,t[o]);return e},h=(e,t)=>De(e,Ae(t));var Be=(e,t)=>{for(var o in t)R(e,o,{get:t[o],enumerable:!0})},oe=(e,t,o,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let a of Le(t))!ne.call(e,a)&&a!==o&&R(e,a,{get:()=>t[a],enumerable:!(s=Ne(t,a))||s.enumerable});return e};var Me=(e,t,o)=>(o=e!=null?Ee(We(e)):{},oe(t||!e||!e.__esModule?R(o,"default",{value:e,enumerable:!0}):o,e)),Ie=e=>oe(R({},"__esModule",{value:!0}),e);var Qe={};Be(Qe,{AdaptiveDevtools:()=>qe,LOCAL_MODE_DEVTOOLS_BANNER:()=>pe,previewContextParam:()=>H});module.exports=Ie(Qe);var c=require("react"),w=require("@sentientui/policy"),k=require("@sentientui/core");function ie(){try{return process.env.NODE_ENV!=="production"}catch(e){return!0}}var Te={components:new Map,slots:new Map,sections:[],listeners:new Set,version:0};function C(){if(typeof window=="undefined")return Te;let e=window;return e.__sentient_registry||(e.__sentient_registry={components:new Map,slots:new Map,sections:[],listeners:new Set,version:0}),e.__sentient_registry}function E(){return[...C().components.values()]}function T(){return[...C().slots.values()]}function D(){return[...C().sections]}function re(e){let t=C().listeners;return t.add(e),()=>{t.delete(e)}}function se(){return C().version}function j(){let e=window;return e.__sentient_overrides||(e.__sentient_overrides={}),e.__sentient_overrides}function z(e,t){j()[e]=t}function U(e){delete j()[e]}function N(){return l({},j())}function F(){let e=window;return e.__sentient_slot_overrides||(e.__sentient_slot_overrides={}),e.__sentient_slot_overrides}function $(e,t){F()[e]=t}function ae(e){delete F()[e]}function A(){return l({},F())}var je={on:!1,listeners:new Set};function de(){if(typeof window=="undefined")return je;let e=window;return e.__sentient_preview||(e.__sentient_preview={on:!1,listeners:new Set}),e.__sentient_preview}function _(e){let t=de();if(t.on!==e){t.on=e;for(let o of t.listeners)o()}}function le(){return de().on}var ze="sentient:overrides-changed";function p(){var t;if(typeof window=="undefined")return;let e=window;e.__sentient_overrides_version=((t=e.__sentient_overrides_version)!=null?t:0)+1,window.dispatchEvent(new Event(ze))}function G(){var e;return typeof window=="undefined"?null:(e=window.__sentient_devtools_config)!=null?e:null}var i=require("react/jsx-runtime"),ce=!ie(),ue="https://api.sentient-ui.com/v1",pe="Local mode \u2014 decisions are simulated; add a key to learn from real traffic";function ge(){let e=window.__sentient_layout_override,t=D();return!e||e.length===0?t:[...e,...t.filter(o=>!e.includes(o))]}function Ue(e,t){let o=ge();if(e===t||e<0||t<0||e>=o.length||t>=o.length)return;let s=[...o],[a]=s.splice(e,1);s.splice(t,0,a),window.__sentient_layout_override=s,_(!0),p()}function Fe(){delete window.__sentient_layout_override,p()}function fe(e){var o,s;for(let[a,u]of Object.entries((o=e.assignments)!=null?o:{}))z(a,u);let t=window;e.layoutOrder&&e.layoutOrder.length>0&&(t.__sentient_layout_override=e.layoutOrder),e.slots&&(t.__sentient_slot_overrides=l(l({},(s=t.__sentient_slot_overrides)!=null?s:{}),e.slots)),e.personaAttributes&&(document.documentElement.dataset.sentientPersona=e.personaAttributes.persona,document.documentElement.dataset.sentientConfidence=e.personaAttributes.confidence),_(!0),p()}function $e(e){var o,s;let t=a=>{try{let u=document.cookie.match(new RegExp(`(?:^|; )${a}=([^;]*)`));return u?decodeURIComponent(u[1]):null}catch(u){return null}};return(s=(o=e?t((0,k.sessionCookieName)(e)):null)!=null?o:t(k.LEGACY_SESSION_COOKIE_NAME))!=null?s:"devtools-preview"}function ve(){return T().map(e=>l(l({id:e.id},e.arms?{arms:e.arms}:{}),e.dims?{dims:e.dims}:{}))}var Ge={key:w.UNKNOWN_PERSONA,displayName:w.UNKNOWN_PERSONA_DISPLAY};async function He(e,t){try{let o=await fetch(`${t}/personas`,{headers:{authorization:`Bearer ${e}`}});if(!o.ok)return null;let s=await o.json(),a=b=>Array.isArray(b)?b.filter(f=>f&&typeof f.key=="string"&&typeof f.displayName=="string"):[],u=a(s.personas);return u.length>0?{personas:u,discovered:a(s.discovered)}:null}catch(o){return null}}function H(){try{let e=new URLSearchParams(window.location.search).get("sentient_context");return e&&/^[a-z_]{1,40}$/.test(e)?e:null}catch(e){return null}}async function Ke(e,t,o){var u,b,f;let s=await fetch(`${t}/explain`,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e}`},body:JSON.stringify(l({persona:o,sections:D().map(S=>({id:S})),components:E().map(S=>({id:S.id,variantIds:S.variantIds})),slots:ve()},H()?{context:H()}:{}))});if(!s.ok)return null;let a=await s.json();return fe(h(l({},a),{personaAttributes:(u=a.personaAttributes)!=null?u:{persona:o,confidence:"high"}})),{recognized:a.recognized!==!1,resolvedDisplay:(f=(b=a.personaDisplay)!=null?b:a.persona)!=null?f:o}}async function Ye(e,t){let o=await import("@sentientui/core/local");if(!o.LOCAL_ENGINE_AVAILABLE)return;let s=o.createLocalEngine({sessionId:$e(t),forcedPersona:e}).decide({sections:D(),components:E().map(a=>({id:a.id,variantIds:a.variantIds})),slots:ve()});fe({assignments:s.assignments,layoutOrder:s.layoutOrder,slots:s.slots,personaAttributes:{persona:s.persona,confidence:(0,w.confidenceBand)(s.confidence)}})}function Je(){for(let t of Object.keys(N()))U(t);let e=window;delete e.__sentient_layout_override,delete e.__sentient_slot_overrides,delete document.documentElement.dataset.sentientPersona,delete document.documentElement.dataset.sentientConfidence;try{let t=[];for(let o=0;o<localStorage.length;o++){let s=localStorage.key(o);s&&s.startsWith(k.SNAPSHOT_STORAGE_KEY_PREFIX)&&t.push(s)}for(let o of t)localStorage.removeItem(o)}catch(t){}_(!1),p();try{window.location.reload()}catch(t){}}var g=e=>({padding:"2px 8px",borderRadius:4,border:"1px solid #444",background:e?"#3b82f6":"#222",color:"#eee",cursor:"pointer"});function Xe({size:e=26}={}){return(0,i.jsxs)("svg",{width:e,height:e,viewBox:"0 0 32 32",fill:"none","aria-hidden":"true",children:[(0,i.jsx)("path",{d:"M21 9H14C11.2 9 9.8 10.8 9.8 13C9.8 15.4 11.6 16.6 14.5 16.6H18.5C20.5 16.6 20.7 18.2 20.4 19.6",stroke:"#fff",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round"}),(0,i.jsx)("path",{d:"M10 22H17",stroke:"#fff",strokeWidth:"2.2",strokeLinecap:"round"}),(0,i.jsx)("circle",{cx:"20.6",cy:"22",r:"2.1",fill:"#fff"})]})}function qe({apiKey:e}={}){var Q;let[t,o]=(0,c.useState)(!1),[s,a]=(0,c.useState)(null),[u,b]=(0,c.useState)(null),[f,S]=(0,c.useState)(""),[K,ye]=(0,c.useState)([]),[Y,J]=(0,c.useState)(null),[O,L]=(0,c.useState)(null),[me,_e]=(0,c.useState)(!1),[,v]=(0,c.useReducer)(n=>n+1,0);if((0,c.useSyncExternalStore)(re,se,()=>0),(0,c.useEffect)(()=>_e(!0),[]),(0,c.useEffect)(()=>{var d;if(ce)return;let n=(d=G())!=null?d:{apiKey:e!=null?e:"",apiBaseUrl:ue,isLocal:!1};if(n.isLocal||!n.apiKey)return;let r=!1;return He(n.apiKey,n.apiBaseUrl).then(y=>{r||!y||(b(y.personas),ye(y.discovered))}),()=>{r=!0}},[e]),ce||!me)return null;let x=(Q=G())!=null?Q:{apiKey:e!=null?e:"",apiBaseUrl:ue,isLocal:!1},W=x.isLocal||!x.apiKey,P=E(),V=T(),B=N(),X=A(),M=ge(),we=window.__sentient_layout_override!==void 0;function be(n,r){Ue(n,r),v()}function he(){Fe(),I(),v()}function I(){Object.keys(N()).length===0&&Object.keys(A()).length===0&&window.__sentient_layout_override===void 0&&_(!1)}function Se(n,r){z(n,r),_(!0),p(),v()}function xe(n){U(n),I(),p(),v()}function ke(n,r){$(n,r),_(!0),p(),v()}function Oe(n,r,d,y){let m=A()[n],Z=m&&typeof m=="object"?l({},m):Object.fromEntries(Object.entries(y!=null?y:{}).map(([Ce,Pe])=>[Ce,Pe[0]]));Z[r]=d,$(n,Z),_(!0),p(),v()}function Re(n){ae(n),I(),p(),v()}function q(n){if(a(n.key),J(null),W){Ye(n.key,x.apiKey).then(v).catch(()=>{});return}Ke(x.apiKey,x.apiBaseUrl,n.key).then(r=>{r&&!r.recognized&&J(`\u201C${n.displayName}\u201D isn\u2019t in this project\u2019s personas \u2014 the page is showing the default experience.`),v()}).catch(()=>{})}return(0,i.jsxs)("div",{style:{position:"fixed",bottom:16,right:16,zIndex:2147483647,fontFamily:"system-ui"},children:[(0,i.jsx)("div",{"aria-hidden":!t,style:{position:"absolute",bottom:52,right:0,transformOrigin:"bottom right",transition:"opacity .18s ease, transform .2s cubic-bezier(.16,1,.3,1)",opacity:t?1:0,transform:t?"translateY(0) scale(1)":"translateY(6px) scale(.96)",pointerEvents:t?"auto":"none"},children:(0,i.jsxs)("div",{style:{width:300,maxHeight:460,overflowY:"auto",background:"#111",color:"#eee",borderRadius:8,padding:12,boxShadow:"0 8px 30px rgba(0,0,0,.4)",fontSize:12},children:[x.isLocal&&(0,i.jsx)("div",{style:{background:"#1e293b",border:"1px solid #334155",borderRadius:4,padding:"6px 8px",marginBottom:8},children:pe}),(0,i.jsxs)("div",{style:{opacity:.7,marginBottom:8},children:[P.length," component",P.length===1?"":"s"," \xB7 ",le()?"preview \u2014 writing nothing":"live"]}),(0,i.jsxs)("div",{style:{borderBottom:"1px solid #333",paddingBottom:8,marginBottom:8},children:[(0,i.jsx)("div",{style:{opacity:.7,marginBottom:4},children:"Preview persona"}),(0,i.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",gap:4},children:[[...W?[]:u!=null?u:[],Ge].map(n=>(0,i.jsx)("button",{onClick:()=>q(n),style:g(s===n.key),children:n.displayName},n.key)),(s!==null||Object.keys(B).length>0||Object.keys(X).length>0)&&(0,i.jsx)("button",{onClick:Je,style:h(l({},g(!1)),{color:"#aaa"}),children:"Reset"})]}),(0,i.jsxs)("form",{onSubmit:n=>{n.preventDefault();let r=(0,w.normalizeDeclaredPersona)(f);r&&q({key:r,displayName:r})},style:{display:"flex",gap:4,marginTop:6},children:[(0,i.jsx)("input",{"aria-label":"Persona key",placeholder:"any persona key, e.g. admin",value:f,onChange:n=>S(n.target.value),style:{flex:1,minWidth:0,background:"#111",color:"#fff",border:"1px solid #333",borderRadius:4,padding:"4px 6px",fontSize:12}}),(0,i.jsx)("button",{type:"submit",style:g(!1),children:"Preview"})]}),Y&&(0,i.jsx)("div",{style:{marginTop:6,fontSize:11,color:"#fbbf24"},children:Y}),!W&&K.length>0&&(0,i.jsxs)("div",{style:{marginTop:8},children:[(0,i.jsx)("div",{style:{opacity:.5,fontSize:11,marginBottom:4},children:"Discovered \u2014 not serving yet (promote from the dashboard)"}),(0,i.jsx)("div",{style:{display:"flex",flexWrap:"wrap",gap:4},children:K.map(n=>(0,i.jsx)("span",{title:"Found by clustering your traffic; it starts serving only after promotion.",style:h(l({},g(!1)),{opacity:.45,cursor:"default",display:"inline-block"}),children:n.displayName},n.key))})]})]}),M.length>0&&(0,i.jsxs)("div",{style:{borderBottom:"1px solid #333",paddingBottom:8,marginBottom:8},children:[(0,i.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:4},children:[(0,i.jsx)("span",{style:{opacity:.7},children:"Layout \u2014 drag to reorder"}),we&&(0,i.jsx)("button",{"aria-label":"Reset section order",onClick:he,style:h(l({},g(!1)),{color:"#aaa"}),children:"reset"})]}),(0,i.jsx)("ul",{"aria-label":"Section order",style:{listStyle:"none",margin:0,padding:0},children:M.map((n,r)=>(0,i.jsxs)("li",{draggable:!0,onDragStart:()=>L(r),onDragOver:d=>d.preventDefault(),onDrop:d=>{d.preventDefault(),O!==null&&be(O,r),L(null)},onDragEnd:()=>L(null),style:{display:"flex",alignItems:"center",gap:6,padding:"4px 6px",marginBottom:2,borderRadius:4,border:"1px solid #262626",cursor:"grab",background:O===r?"#1e293b":"#181818",opacity:O!==null&&O!==r?.6:1},children:[(0,i.jsx)("span",{style:{opacity:.4,minWidth:10,fontVariantNumeric:"tabular-nums"},children:r+1}),(0,i.jsx)("span",{"aria-hidden":"true",style:{opacity:.35},children:"\u283F"}),(0,i.jsx)("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:n})]},n))})]}),P.length===0&&V.length===0&&M.length===0&&(0,i.jsx)("div",{style:{opacity:.6},children:"No components, sections or slots on this page yet."}),P.map(n=>(0,i.jsxs)("div",{style:{borderTop:"1px solid #333",padding:"8px 0"},children:[(0,i.jsxs)("div",{style:{fontWeight:600},children:[n.id,n.goal?` \xB7 goal: ${n.goal}`:""]}),(0,i.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",gap:4,marginTop:4},children:[n.variantIds.map(r=>(0,i.jsx)("button",{onClick:()=>Se(n.id,r),style:g(B[n.id]===r),children:r},r)),B[n.id]&&(0,i.jsx)("button",{onClick:()=>xe(n.id),style:h(l({},g(!1)),{color:"#aaa"}),children:"reset"})]})]},n.id)),V.length>0&&(0,i.jsxs)("div",{style:{borderTop:"1px solid #333",paddingTop:8,marginTop:4},children:[(0,i.jsx)("div",{style:{opacity:.7,marginBottom:4},children:"Slots"}),V.map(n=>{let r=X[n.id];return(0,i.jsxs)("div",{style:{padding:"6px 0"},children:[(0,i.jsx)("div",{style:{fontWeight:600},children:n.id}),n.arms&&(0,i.jsx)("div",{style:{display:"flex",flexWrap:"wrap",gap:4,marginTop:4},children:n.arms.map(d=>(0,i.jsx)("button",{onClick:()=>ke(n.id,d),style:g(r===d),children:d},d))}),n.dims&&Object.entries(n.dims).map(([d,y])=>(0,i.jsxs)("div",{style:{marginTop:4},children:[(0,i.jsx)("div",{style:{opacity:.6,fontSize:11},children:d}),(0,i.jsx)("div",{style:{display:"flex",flexWrap:"wrap",gap:4},children:y.map(m=>(0,i.jsx)("button",{onClick:()=>Oe(n.id,d,m,n.dims),style:g(!!r&&typeof r=="object"&&r[d]===m),children:m},m))})]},d)),r!==void 0&&(0,i.jsx)("button",{onClick:()=>Re(n.id),style:h(l({},g(!1)),{color:"#aaa",marginTop:4}),children:"reset"})]},n.id)})]})]})}),(0,i.jsx)("button",{"aria-label":"Sentient DevTools","aria-expanded":t,onClick:()=>o(n=>!n),style:{width:44,height:44,borderRadius:12,border:"1px solid #2a2a2a",background:"#000",display:"flex",alignItems:"center",justifyContent:"center",padding:0,cursor:"pointer",boxShadow:"0 6px 18px rgba(0,0,0,.4)"},children:(0,i.jsx)(Xe,{})})]})}0&&(module.exports={AdaptiveDevtools,LOCAL_MODE_DEVTOOLS_BANNER,previewContextParam});
3
3
  //# sourceMappingURL=devtools.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/devtools/index.tsx","../src/devtools-registry.ts","../src/devtools-overrides.ts","../src/devtools-slot-overrides.ts","../src/preview-mode.ts","../src/override-events.ts","../src/devtools-config.ts"],"sourcesContent":["'use client';\n// `type JSX` from react, not the global namespace removed in @types/react@19\n// (peers allow react >=18) — see adaptive-text.tsx.\nimport { useEffect, useReducer, useState, useSyncExternalStore, type CSSProperties, type JSX } from 'react';\nimport { UNKNOWN_PERSONA, UNKNOWN_PERSONA_DISPLAY, confidenceBand, normalizeDeclaredPersona } from '@sentientui/policy';\nimport { LEGACY_SESSION_COOKIE_NAME, SNAPSHOT_STORAGE_KEY_PREFIX, sessionCookieName } from '@sentientui/core';\nimport {\n getRegistered,\n getRegisteredSlots,\n getRegisteredSections,\n subscribeRegistry,\n getRegistryVersion,\n type RegisteredSlot,\n} from '../devtools-registry.js';\nimport { setVariantOverride, clearVariantOverride, getOverrides } from '../devtools-overrides.js';\nimport { setSlotOverride, clearSlotOverride, getSlotOverrides } from '../devtools-slot-overrides.js';\nimport { setPreviewMode, getPreviewMode } from '../preview-mode.js';\nimport { notifyOverridesChanged } from '../override-events.js';\nimport { readDevtoolsConfig, type DevtoolsConfig } from '../devtools-config.js';\n\ndeclare const process: { env?: { NODE_ENV?: string } } | undefined;\nconst IS_PROD = typeof process !== 'undefined' && process.env?.NODE_ENV === 'production';\nconst DEFAULT_API_BASE_URL = 'https://api.sentient-ui.com/v1';\n\nexport const LOCAL_MODE_DEVTOOLS_BANNER =\n 'Local mode — decisions are simulated; add a key to learn from real traffic';\n\ntype OutcomeToApply = {\n assignments?: Record<string, string>;\n layoutOrder?: string[] | null;\n slots?: Record<string, string | Record<string, string>>;\n personaAttributes?: { persona: string; confidence: 'low' | 'medium' | 'high' };\n};\n\ntype OverrideWindow = Window & {\n __sentient_layout_override?: string[];\n __sentient_slot_overrides?: Record<string, string | Record<string, string>>;\n};\n\n/** The order the page is rendering: a previewed override, else what was registered. */\nfunction currentLayout(): string[] {\n const forced = (window as unknown as OverrideWindow).__sentient_layout_override;\n const registered = getRegisteredSections();\n if (!forced || forced.length === 0) return registered;\n // Registered ids the override omits still render (useLayoutOrder returns the\n // override verbatim, and the app maps whatever ids it is given), so show them\n // trailing rather than dropping them from the list you are dragging.\n return [...forced, ...registered.filter((id) => !forced.includes(id))];\n}\n\n/**\n * Move `from` to `to` within the current order and preview it.\n *\n * Writes the whole order rather than swapping neighbours: the point is to try an\n * arrangement, not to walk one block up a list one press at a time.\n */\nfunction reorderLayout(from: number, to: number): void {\n const order = currentLayout();\n if (from === to || from < 0 || to < 0 || from >= order.length || to >= order.length) return;\n const next = [...order];\n const [moved] = next.splice(from, 1);\n next.splice(to, 0, moved!);\n (window as unknown as OverrideWindow).__sentient_layout_override = next;\n setPreviewMode(true); // an arrangement you are trying must not train the bandit\n notifyOverridesChanged();\n}\n\nfunction resetLayout(): void {\n delete (window as unknown as OverrideWindow).__sentient_layout_override;\n notifyOverridesChanged();\n}\n\n/** Apply a simulated outcome across every surface: variants, layout, slots/tokens, persona attrs. */\nfunction applyOutcome(result: OutcomeToApply): void {\n for (const [id, variantId] of Object.entries(result.assignments ?? {})) {\n setVariantOverride(id, variantId);\n }\n const w = window as unknown as OverrideWindow;\n if (result.layoutOrder && result.layoutOrder.length > 0) {\n w.__sentient_layout_override = result.layoutOrder;\n }\n if (result.slots) {\n w.__sentient_slot_overrides = { ...(w.__sentient_slot_overrides ?? {}), ...result.slots };\n }\n if (result.personaAttributes) {\n document.documentElement.dataset.sentientPersona = result.personaAttributes.persona;\n document.documentElement.dataset.sentientConfidence = result.personaAttributes.confidence;\n }\n setPreviewMode(true); // suppress events while previewing\n notifyOverridesChanged(); // re-render layout/slot consumers\n}\n\n// Reads the SDK's own session cookie — the per-project SUFFIXED name first\n// (that is what the client writes since namespacing; the bare `_snt_uid` this\n// used to read is only written in keyless/local mode), then the bare name as\n// the legacy/local fallback.\nfunction readSessionId(apiKey?: string): string {\n const read = (name: string): string | null => {\n try {\n const match = document.cookie.match(new RegExp(`(?:^|; )${name}=([^;]*)`));\n return match ? decodeURIComponent(match[1]!) : null;\n } catch {\n return null;\n }\n };\n return (apiKey ? read(sessionCookieName(apiKey)) : null) ?? read(LEGACY_SESSION_COOKIE_NAME) ?? 'devtools-preview';\n}\n\nfunction slotDecls(): Array<{ id: string; arms?: string[]; dims?: RegisteredSlot['dims'] }> {\n return getRegisteredSlots().map((s) => ({\n id: s.id,\n ...(s.arms ? { arms: s.arms } : {}),\n ...(s.dims ? { dims: s.dims } : {}),\n }));\n}\n\n/** One member of the project's persona vocabulary, as /v1/personas serves it. */\ntype VocabMember = { key: string; displayName: string };\n\n/** Always offered: previewing the unidentified visitor is meaningful on every\n * project, and it is the only persona the product itself defines. */\nconst UNKNOWN_CHOICE: VocabMember = { key: UNKNOWN_PERSONA, displayName: UNKNOWN_PERSONA_DISPLAY };\n\n/**\n * Keyed mode: the project's ACTIVE vocabulary from /v1/personas. Personas are\n * per-project (persona_sets, migration 113) — declared by the app or promoted\n * by discovery. This used to fall back to a hardcoded list of four seeded\n * personas, which offered buttons that silently simulated the default\n * experience on any project whose vocabulary differs, and named audiences\n * nobody had declared. null on any failure → the panel offers only `unknown`\n * and a free-text key.\n */\nasync function fetchPersonaVocabulary(\n apiKey: string,\n apiBaseUrl: string,\n): Promise<{ personas: VocabMember[]; discovered: VocabMember[] } | null> {\n try {\n const res = await fetch(`${apiBaseUrl}/personas`, {\n headers: { authorization: `Bearer ${apiKey}` },\n });\n if (!res.ok) return null;\n const data = (await res.json()) as { personas?: VocabMember[]; discovered?: VocabMember[] };\n const valid = (list: VocabMember[] | undefined): VocabMember[] =>\n Array.isArray(list)\n ? list.filter((p) => p && typeof p.key === 'string' && typeof p.displayName === 'string')\n : [];\n const personas = valid(data.personas);\n return personas.length > 0 ? { personas, discovered: valid(data.discovered) } : null;\n } catch {\n return null;\n }\n}\n\n/**\n * `?sentient_context=<context>` on the page URL: the on-site context preview\n * (a stage such as `carted`, or an arrival class such as `cart_recovery`).\n * Forwarded to /v1/explain so a persona simulated from this panel is also\n * simulated in that context — the API validates the value (400 on anything\n * else) and applies it to the project's published (registry) versions:\n * those restricted to the context become eligible and its pins win. Lives\n * here, not in the provider: devtools is the React SDK's only explain-backed\n * preview, and the main bundle pays for nothing it does not use.\n * @internal Exported for tests.\n */\nexport function previewContextParam(): string | null {\n try {\n const v = new URLSearchParams(window.location.search).get('sentient_context');\n return v && /^[a-z_]{1,40}$/.test(v) ? v : null;\n } catch {\n return null;\n }\n}\n\n/** Keyed mode: simulate via /v1/explain (read-only, event-free). Returns how\n * the persona RESOLVED so the panel can say when the project didn't\n * recognize it — the page then shows the default experience, and a silently\n * highlighted button claiming otherwise was the old lie. */\nasync function forcePersonaKeyed(\n apiKey: string,\n apiBaseUrl: string,\n persona: string,\n): Promise<{ recognized: boolean; resolvedDisplay: string } | null> {\n const res = await fetch(`${apiBaseUrl}/explain`, {\n method: 'POST',\n headers: { 'content-type': 'application/json', authorization: `Bearer ${apiKey}` },\n body: JSON.stringify({\n persona,\n sections: getRegisteredSections().map((id) => ({ id })),\n components: getRegistered().map((c) => ({ id: c.id, variantIds: c.variantIds })),\n slots: slotDecls(),\n ...(previewContextParam() ? { context: previewContextParam() } : {}),\n }),\n });\n if (!res.ok) return null;\n const data = (await res.json()) as OutcomeToApply & {\n recognized?: boolean;\n persona?: string;\n personaDisplay?: string;\n };\n applyOutcome({\n ...data,\n personaAttributes: data.personaAttributes ?? { persona, confidence: 'high' },\n });\n return {\n // An older API omits the field — treat as recognized (no basis to warn).\n recognized: data.recognized !== false,\n resolvedDisplay: data.personaDisplay ?? data.persona ?? persona,\n };\n}\n\n/** Local mode: simulate via the deterministic local engine — zero network. */\nasync function forcePersonaLocal(persona: string, apiKey?: string): Promise<void> {\n const mod = await import('@sentientui/core/local');\n if (!mod.LOCAL_ENGINE_AVAILABLE) return;\n const outcome = mod\n .createLocalEngine({ sessionId: readSessionId(apiKey), forcedPersona: persona })\n .decide({\n sections: getRegisteredSections(),\n components: getRegistered().map((c) => ({ id: c.id, variantIds: c.variantIds })),\n slots: slotDecls(),\n });\n applyOutcome({\n assignments: outcome.assignments,\n layoutOrder: outcome.layoutOrder,\n slots: outcome.slots,\n personaAttributes: {\n persona: outcome.persona,\n confidence: confidenceBand(outcome.confidence),\n },\n });\n}\n\n/** Reset: clear the decision snapshot + every override, then reload to re-decide. */\nfunction resetAll(): void {\n for (const id of Object.keys(getOverrides())) clearVariantOverride(id);\n const w = window as unknown as OverrideWindow;\n delete w.__sentient_layout_override;\n delete w.__sentient_slot_overrides;\n delete document.documentElement.dataset.sentientPersona;\n delete document.documentElement.dataset.sentientConfidence;\n try {\n const stale: string[] = [];\n for (let i = 0; i < localStorage.length; i++) {\n const key = localStorage.key(i);\n if (key && key.startsWith(SNAPSHOT_STORAGE_KEY_PREFIX)) stale.push(key);\n }\n for (const key of stale) localStorage.removeItem(key);\n } catch {\n /* ignore */\n }\n setPreviewMode(false);\n notifyOverridesChanged();\n try {\n window.location.reload();\n } catch {\n /* jsdom */\n }\n}\n\nconst btn = (active: boolean): CSSProperties => ({\n padding: '2px 8px',\n borderRadius: 4,\n border: '1px solid #444',\n background: active ? '#3b82f6' : '#222',\n color: '#eee',\n cursor: 'pointer',\n});\n\n/** Sentient \"S.\" wordmark, monoline — white strokes for the black launcher button. */\nfunction SentientMark({ size = 26 }: { size?: number } = {}): JSX.Element {\n return (\n <svg width={size} height={size} viewBox=\"0 0 32 32\" fill=\"none\" aria-hidden=\"true\">\n <path\n d=\"M21 9H14C11.2 9 9.8 10.8 9.8 13C9.8 15.4 11.6 16.6 14.5 16.6H18.5C20.5 16.6 20.7 18.2 20.4 19.6\"\n stroke=\"#fff\"\n strokeWidth=\"2.2\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n />\n <path d=\"M10 22H17\" stroke=\"#fff\" strokeWidth=\"2.2\" strokeLinecap=\"round\" />\n <circle cx=\"20.6\" cy=\"22\" r=\"2.1\" fill=\"#fff\" />\n </svg>\n );\n}\n\nexport function AdaptiveDevtools({ apiKey }: { apiKey?: string } = {}): JSX.Element | null {\n const [open, setOpen] = useState(false);\n const [activePersona, setActivePersona] = useState<string | null>(null);\n // The project's vocabulary (keyed mode); null = not loaded → no persona\n // buttons beyond `unknown`. Local mode never fetches: there is no project,\n // and the local engine previews ANY key typed into the free-text field.\n const [vocab, setVocab] = useState<VocabMember[] | null>(null);\n const [customKey, setCustomKey] = useState('');\n // Discovered SHADOW personas — display-only. They never serve until\n // promotion, so there is no button: forcing one would simulate a persona\n // that cannot occur on this project.\n const [discovered, setDiscovered] = useState<VocabMember[]>([]);\n // Set when a forced persona did NOT resolve against the project's\n // vocabulary — the page is showing the default experience and the panel\n // must say so instead of highlighting the button as if the preview worked.\n const [personaNote, setPersonaNote] = useState<string | null>(null);\n const [dragFrom, setDragFrom] = useState<number | null>(null);\n const [mounted, setMounted] = useState(false);\n const [, force] = useReducer((n: number) => n + 1, 0);\n // Re-render when the component/slot registry changes. useSyncExternalStore\n // (not a manual useEffect subscription) so the subscription can't go stale\n // across Next Fast Refresh — a stale listener was why the panel needed a hard\n // refresh to pick up a renamed id.\n useSyncExternalStore(subscribeRegistry, getRegistryVersion, () => 0);\n // Client-mount gate: render nothing during SSR / the first paint so the widget\n // never reads `window` on the server. Lets consumers drop `<AdaptiveDevtools/>`\n // straight into a tree without a `dynamic(..., { ssr: false })` wrapper.\n useEffect(() => setMounted(true), []);\n // Load the project's persona vocabulary once (keyed mode only).\n useEffect(() => {\n if (IS_PROD) return;\n const cfg = readDevtoolsConfig() ?? { apiKey: apiKey ?? '', apiBaseUrl: DEFAULT_API_BASE_URL, isLocal: false };\n if (cfg.isLocal || !cfg.apiKey) return;\n let cancelled = false;\n void fetchPersonaVocabulary(cfg.apiKey, cfg.apiBaseUrl).then((v) => {\n if (cancelled || !v) return;\n setVocab(v.personas);\n setDiscovered(v.discovered);\n });\n return () => { cancelled = true; };\n }, [apiKey]);\n\n // Never render in production, even if imported by mistake. (Hooks run first\n // so the rules of hooks hold regardless of these early returns.)\n if (IS_PROD) return null;\n if (!mounted) return null;\n\n const config: DevtoolsConfig = readDevtoolsConfig() ?? {\n apiKey: apiKey ?? '',\n apiBaseUrl: DEFAULT_API_BASE_URL,\n isLocal: false,\n };\n const useLocalEngine = config.isLocal || !config.apiKey;\n const components = getRegistered();\n const slots = getRegisteredSlots();\n const overrides = getOverrides();\n const slotOverrides = getSlotOverrides();\n const sections = currentLayout();\n const layoutForced = (window as unknown as OverrideWindow).__sentient_layout_override !== undefined;\n\n function onReorder(from: number, to: number): void {\n reorderLayout(from, to);\n force();\n }\n function onResetLayout(): void {\n resetLayout();\n maybeExitPreview();\n force();\n }\n\n // Preview mode stays on while ANY override (variant, slot or layout) is\n // active. Omitting layout here let clearing the last variant re-enable event\n // recording while a previewed section order was still on screen.\n function maybeExitPreview(): void {\n if (\n Object.keys(getOverrides()).length === 0 &&\n Object.keys(getSlotOverrides()).length === 0 &&\n (window as unknown as OverrideWindow).__sentient_layout_override === undefined\n ) {\n setPreviewMode(false);\n }\n }\n\n function choose(id: string, variantId: string): void {\n setVariantOverride(id, variantId);\n setPreviewMode(true);\n notifyOverridesChanged();\n force();\n }\n function resetVariant(id: string): void {\n clearVariantOverride(id);\n maybeExitPreview();\n notifyOverridesChanged();\n force();\n }\n function chooseSlotArm(id: string, arm: string): void {\n setSlotOverride(id, arm);\n setPreviewMode(true);\n notifyOverridesChanged();\n force();\n }\n function chooseSlotDim(id: string, dim: string, value: string, dims: RegisteredSlot['dims']): void {\n const current = getSlotOverrides()[id];\n // Merge onto the existing forced object, or seed from each dim's baseline\n // (first value) so unset dims stay at baseline instead of vanishing.\n const next: Record<string, string> =\n current && typeof current === 'object'\n ? { ...current }\n : Object.fromEntries(Object.entries(dims ?? {}).map(([d, values]) => [d, values[0]!]));\n next[dim] = value;\n setSlotOverride(id, next);\n setPreviewMode(true);\n notifyOverridesChanged();\n force();\n }\n function resetSlot(id: string): void {\n clearSlotOverride(id);\n maybeExitPreview();\n notifyOverridesChanged();\n force();\n }\n function choosePersona(member: VocabMember): void {\n setActivePersona(member.key);\n setPersonaNote(null);\n // .catch: a failed simulate (offline /v1/explain, bad key, failed local\n // dynamic import) is a preview no-op — without the handler it surfaced as\n // an unhandled promise rejection in the console.\n if (useLocalEngine) {\n forcePersonaLocal(member.key, config.apiKey).then(force).catch(() => {});\n return;\n }\n forcePersonaKeyed(config.apiKey, config.apiBaseUrl, member.key)\n .then((r) => {\n if (r && !r.recognized) {\n setPersonaNote(\n `“${member.displayName}” isn’t in this project’s personas — the page is showing the default experience.`,\n );\n }\n force();\n })\n .catch(() => {});\n }\n\n return (\n <div style={{ position: 'fixed', bottom: 16, right: 16, zIndex: 2147483647, fontFamily: 'system-ui' }}>\n {/* Panel stays mounted and animates in/out from the button's corner, so the\n launcher below never shifts. transform-origin is the button (bottom-right). */}\n <div\n aria-hidden={!open}\n style={{\n position: 'absolute',\n bottom: 52,\n right: 0,\n transformOrigin: 'bottom right',\n transition: 'opacity .18s ease, transform .2s cubic-bezier(.16,1,.3,1)',\n opacity: open ? 1 : 0,\n transform: open ? 'translateY(0) scale(1)' : 'translateY(6px) scale(.96)',\n pointerEvents: open ? 'auto' : 'none',\n }}\n >\n <div style={{ width: 300, maxHeight: 460, overflowY: 'auto', background: '#111', color: '#eee',\n borderRadius: 8, padding: 12, boxShadow: '0 8px 30px rgba(0,0,0,.4)', fontSize: 12 }}>\n {config.isLocal && (\n <div style={{ background: '#1e293b', border: '1px solid #334155', borderRadius: 4,\n padding: '6px 8px', marginBottom: 8 }}>\n {LOCAL_MODE_DEVTOOLS_BANNER}\n </div>\n )}\n <div style={{ opacity: .7, marginBottom: 8 }}>\n {components.length} component{components.length === 1 ? '' : 's'} · {getPreviewMode() ? 'preview — writing nothing' : 'live'}\n </div>\n <div style={{ borderBottom: '1px solid #333', paddingBottom: 8, marginBottom: 8 }}>\n <div style={{ opacity: .7, marginBottom: 4 }}>Preview persona</div>\n <div style={{ display: 'flex', flexWrap: 'wrap', gap: 4 }}>\n {/* Keyed mode renders the project's OWN vocabulary once\n /v1/personas answers; nothing is invented while it hasn't. */}\n {[...(useLocalEngine ? [] : vocab ?? []), UNKNOWN_CHOICE].map((p) => (\n <button key={p.key} onClick={() => choosePersona(p)} style={btn(activePersona === p.key)}>\n {p.displayName}\n </button>\n ))}\n {(activePersona !== null || Object.keys(overrides).length > 0 || Object.keys(slotOverrides).length > 0) && (\n <button onClick={resetAll} style={{ ...btn(false), color: '#aaa' }}>\n Reset\n </button>\n )}\n </div>\n <form\n onSubmit={(e) => {\n e.preventDefault();\n const key = normalizeDeclaredPersona(customKey);\n if (key) choosePersona({ key, displayName: key });\n }}\n style={{ display: 'flex', gap: 4, marginTop: 6 }}\n >\n <input\n aria-label=\"Persona key\"\n placeholder=\"any persona key, e.g. admin\"\n value={customKey}\n onChange={(e) => setCustomKey(e.target.value)}\n style={{ flex: 1, minWidth: 0, background: '#111', color: '#fff', border: '1px solid #333',\n borderRadius: 4, padding: '4px 6px', fontSize: 12 }}\n />\n <button type=\"submit\" style={btn(false)}>Preview</button>\n </form>\n {personaNote && (\n <div style={{ marginTop: 6, fontSize: 11, color: '#fbbf24' }}>{personaNote}</div>\n )}\n {!useLocalEngine && discovered.length > 0 && (\n <div style={{ marginTop: 8 }}>\n <div style={{ opacity: .5, fontSize: 11, marginBottom: 4 }}>\n Discovered — not serving yet (promote from the dashboard)\n </div>\n <div style={{ display: 'flex', flexWrap: 'wrap', gap: 4 }}>\n {discovered.map((p) => (\n <span\n key={p.key}\n title=\"Found by clustering your traffic; it starts serving only after promotion.\"\n style={{ ...btn(false), opacity: .45, cursor: 'default', display: 'inline-block' }}\n >\n {p.displayName}\n </span>\n ))}\n </div>\n </div>\n )}\n </div>\n {sections.length > 0 && (\n <div style={{ borderBottom: '1px solid #333', paddingBottom: 8, marginBottom: 8 }}>\n <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 4 }}>\n <span style={{ opacity: .7 }}>Layout — drag to reorder</span>\n {layoutForced && (\n // Distinct accessible name: the per-variant and per-slot resets\n // below are also labelled \"reset\", and three identical buttons\n // in one panel is ambiguous to a screen reader and to tests.\n <button\n aria-label=\"Reset section order\"\n onClick={onResetLayout}\n style={{ ...btn(false), color: '#aaa' }}\n >\n reset\n </button>\n )}\n </div>\n {/* Drop-on-row inserts at that row's position, so any block can go\n anywhere in one gesture. The whole order is written on each\n drop — see reorderLayout. */}\n <ul aria-label=\"Section order\" style={{ listStyle: 'none', margin: 0, padding: 0 }}>\n {sections.map((id, i) => (\n <li\n key={id}\n draggable\n onDragStart={() => setDragFrom(i)}\n onDragOver={(e) => e.preventDefault()}\n onDrop={(e) => {\n e.preventDefault();\n if (dragFrom !== null) onReorder(dragFrom, i);\n setDragFrom(null);\n }}\n onDragEnd={() => setDragFrom(null)}\n style={{\n display: 'flex', alignItems: 'center', gap: 6, padding: '4px 6px', marginBottom: 2,\n borderRadius: 4, border: '1px solid #262626', cursor: 'grab',\n background: dragFrom === i ? '#1e293b' : '#181818',\n opacity: dragFrom !== null && dragFrom !== i ? .6 : 1,\n }}\n >\n <span style={{ opacity: .4, minWidth: 10, fontVariantNumeric: 'tabular-nums' }}>{i + 1}</span>\n <span aria-hidden=\"true\" style={{ opacity: .35 }}>⠿</span>\n <span style={{ flex: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>\n {id}\n </span>\n </li>\n ))}\n </ul>\n </div>\n )}\n {components.length === 0 && slots.length === 0 && sections.length === 0 && (\n <div style={{ opacity: .6 }}>No components, sections or slots on this page yet.</div>\n )}\n {components.map((c) => (\n <div key={c.id} style={{ borderTop: '1px solid #333', padding: '8px 0' }}>\n <div style={{ fontWeight: 600 }}>{c.id}{c.goal ? ` · goal: ${c.goal}` : ''}</div>\n <div style={{ display: 'flex', flexWrap: 'wrap', gap: 4, marginTop: 4 }}>\n {c.variantIds.map((v) => (\n <button key={v} onClick={() => choose(c.id, v)} style={btn(overrides[c.id] === v)}>\n {v}\n </button>\n ))}\n {overrides[c.id] && (\n <button onClick={() => resetVariant(c.id)} style={{ ...btn(false), color: '#aaa' }}>\n reset\n </button>\n )}\n </div>\n </div>\n ))}\n {slots.length > 0 && (\n <div style={{ borderTop: '1px solid #333', paddingTop: 8, marginTop: 4 }}>\n <div style={{ opacity: .7, marginBottom: 4 }}>Slots</div>\n {slots.map((s) => {\n const ov = slotOverrides[s.id];\n return (\n <div key={s.id} style={{ padding: '6px 0' }}>\n <div style={{ fontWeight: 600 }}>{s.id}</div>\n {s.arms && (\n <div style={{ display: 'flex', flexWrap: 'wrap', gap: 4, marginTop: 4 }}>\n {s.arms.map((arm) => (\n <button key={arm} onClick={() => chooseSlotArm(s.id, arm)} style={btn(ov === arm)}>\n {arm}\n </button>\n ))}\n </div>\n )}\n {s.dims && Object.entries(s.dims).map(([dim, values]) => (\n <div key={dim} style={{ marginTop: 4 }}>\n <div style={{ opacity: .6, fontSize: 11 }}>{dim}</div>\n <div style={{ display: 'flex', flexWrap: 'wrap', gap: 4 }}>\n {values.map((v) => (\n <button\n key={v}\n onClick={() => chooseSlotDim(s.id, dim, v, s.dims)}\n style={btn(!!ov && typeof ov === 'object' && ov[dim] === v)}\n >\n {v}\n </button>\n ))}\n </div>\n </div>\n ))}\n {ov !== undefined && (\n <button onClick={() => resetSlot(s.id)} style={{ ...btn(false), color: '#aaa', marginTop: 4 }}>\n reset\n </button>\n )}\n </div>\n );\n })}\n </div>\n )}\n </div>\n </div>\n <button\n aria-label=\"Sentient DevTools\"\n aria-expanded={open}\n onClick={() => setOpen((o) => !o)}\n style={{ width: 44, height: 44, borderRadius: 12, border: '1px solid #2a2a2a', background: '#000',\n display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 0,\n cursor: 'pointer', boxShadow: '0 6px 18px rgba(0,0,0,.4)' }}\n >\n <SentientMark />\n </button>\n </div>\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","function store(): Record<string, string> {\n const w = window as unknown as { __sentient_overrides?: Record<string, string> };\n if (!w.__sentient_overrides) w.__sentient_overrides = {};\n return w.__sentient_overrides;\n}\n\n/** Force `componentId` to render `variantId` — read by `useAssignment`. */\nexport function setVariantOverride(componentId: string, variantId: string): void {\n store()[componentId] = variantId;\n}\n\nexport function clearVariantOverride(componentId: string): void {\n delete store()[componentId];\n}\n\nexport function getOverrides(): Record<string, string> {\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","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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,GAAKoC,EAAI,EAAK,GAAd,CAAiB,MAAO,OAAQ,UAAW,CAAE,GAAG,iBAE/F,IA9BM3B,EAAE,EAgCZ,CAEJ,CAAC,GACH,GAEJ,EACF,KACA,OAAC,UACC,aAAW,oBACX,gBAAegC,EACf,QAAS,IAAMC,EAASmD,GAAM,CAACA,CAAC,EAChC,MAAO,CAAE,MAAO,GAAI,OAAQ,GAAI,aAAc,GAAI,OAAQ,oBAAqB,WAAY,OAClF,QAAS,OAAQ,WAAY,SAAU,eAAgB,SAAU,QAAS,EAC1E,OAAQ,UAAW,UAAW,2BAA4B,EAEnE,mBAACvD,GAAA,EAAa,EAChB,GACF,CAEJ","names":["devtools_exports","__export","AdaptiveDevtools","LOCAL_MODE_DEVTOOLS_BANNER","previewContextParam","__toCommonJS","import_react","import_policy","import_core","ssrFallback","state","w","getRegistered","state","getRegisteredSlots","getRegisteredSections","subscribeRegistry","fn","listeners","getRegistryVersion","store","w","setVariantOverride","componentId","variantId","clearVariantOverride","getOverrides","__spreadValues","store","w","setSlotOverride","slotId","result","clearSlotOverride","getSlotOverrides","__spreadValues","ssrFallback","state","w","setPreviewMode","on","s","fn","getPreviewMode","EVENT","notifyOverridesChanged","_a","w","EVENT","readDevtoolsConfig","_a","import_jsx_runtime","_a","IS_PROD","DEFAULT_API_BASE_URL","LOCAL_MODE_DEVTOOLS_BANNER","currentLayout","forced","registered","getRegisteredSections","id","reorderLayout","from","to","order","next","moved","setPreviewMode","notifyOverridesChanged","resetLayout","applyOutcome","result","_b","variantId","setVariantOverride","w","__spreadValues","readSessionId","apiKey","read","name","match","e","slotDecls","getRegisteredSlots","s","UNKNOWN_CHOICE","fetchPersonaVocabulary","apiBaseUrl","res","data","valid","list","p","personas","previewContextParam","v","forcePersonaKeyed","persona","_c","getRegistered","c","__spreadProps","forcePersonaLocal","mod","outcome","resetAll","getOverrides","clearVariantOverride","stale","i","key","btn","active","SentientMark","size","AdaptiveDevtools","open","setOpen","activePersona","setActivePersona","vocab","setVocab","customKey","setCustomKey","discovered","setDiscovered","personaNote","setPersonaNote","dragFrom","setDragFrom","mounted","setMounted","force","subscribeRegistry","getRegistryVersion","cfg","readDevtoolsConfig","cancelled","config","useLocalEngine","components","slots","overrides","slotOverrides","getSlotOverrides","sections","layoutForced","onReorder","onResetLayout","maybeExitPreview","choose","resetVariant","chooseSlotArm","arm","setSlotOverride","chooseSlotDim","dim","value","dims","current","d","values","resetSlot","clearSlotOverride","choosePersona","member","getPreviewMode","ov","o"]}
1
+ {"version":3,"sources":["../src/devtools/index.tsx","../src/dev-build.ts","../src/devtools-registry.ts","../src/devtools-overrides.ts","../src/devtools-slot-overrides.ts","../src/preview-mode.ts","../src/override-events.ts","../src/devtools-config.ts"],"sourcesContent":["'use client';\n// `type JSX` from react, not the global namespace removed in @types/react@19\n// (peers allow react >=18) — see adaptive-text.tsx.\nimport { useEffect, useReducer, useState, useSyncExternalStore, type CSSProperties, type JSX } from 'react';\nimport { UNKNOWN_PERSONA, UNKNOWN_PERSONA_DISPLAY, confidenceBand, normalizeDeclaredPersona } from '@sentientui/policy';\nimport { LEGACY_SESSION_COOKIE_NAME, SNAPSHOT_STORAGE_KEY_PREFIX, sessionCookieName } from '@sentientui/core';\nimport {\n getRegistered,\n getRegisteredSlots,\n getRegisteredSections,\n subscribeRegistry,\n getRegistryVersion,\n type RegisteredSlot,\n} from '../devtools-registry.js';\nimport { setVariantOverride, clearVariantOverride, getOverrides } from '../devtools-overrides.js';\nimport { setSlotOverride, clearSlotOverride, getSlotOverrides } from '../devtools-slot-overrides.js';\nimport { setPreviewMode, getPreviewMode } from '../preview-mode.js';\nimport { notifyOverridesChanged } from '../override-events.js';\nimport { readDevtoolsConfig, type DevtoolsConfig } from '../devtools-config.js';\n\nimport { isDevBuild } from '../dev-build.js';\n\n// A Vite production build read the old inline check as \"not production\" and\n// rendered the panel for visitors; see dev-build.ts.\nconst IS_PROD = !isDevBuild();\nconst DEFAULT_API_BASE_URL = 'https://api.sentient-ui.com/v1';\n\nexport const LOCAL_MODE_DEVTOOLS_BANNER =\n 'Local mode — decisions are simulated; add a key to learn from real traffic';\n\ntype OutcomeToApply = {\n assignments?: Record<string, string>;\n layoutOrder?: string[] | null;\n slots?: Record<string, string | Record<string, string>>;\n personaAttributes?: { persona: string; confidence: 'low' | 'medium' | 'high' };\n};\n\ntype OverrideWindow = Window & {\n __sentient_layout_override?: string[];\n __sentient_slot_overrides?: Record<string, string | Record<string, string>>;\n};\n\n/** The order the page is rendering: a previewed override, else what was registered. */\nfunction currentLayout(): string[] {\n const forced = (window as unknown as OverrideWindow).__sentient_layout_override;\n const registered = getRegisteredSections();\n if (!forced || forced.length === 0) return registered;\n // Registered ids the override omits still render (useLayoutOrder returns the\n // override verbatim, and the app maps whatever ids it is given), so show them\n // trailing rather than dropping them from the list you are dragging.\n return [...forced, ...registered.filter((id) => !forced.includes(id))];\n}\n\n/**\n * Move `from` to `to` within the current order and preview it.\n *\n * Writes the whole order rather than swapping neighbours: the point is to try an\n * arrangement, not to walk one block up a list one press at a time.\n */\nfunction reorderLayout(from: number, to: number): void {\n const order = currentLayout();\n if (from === to || from < 0 || to < 0 || from >= order.length || to >= order.length) return;\n const next = [...order];\n const [moved] = next.splice(from, 1);\n next.splice(to, 0, moved!);\n (window as unknown as OverrideWindow).__sentient_layout_override = next;\n setPreviewMode(true); // an arrangement you are trying must not train the bandit\n notifyOverridesChanged();\n}\n\nfunction resetLayout(): void {\n delete (window as unknown as OverrideWindow).__sentient_layout_override;\n notifyOverridesChanged();\n}\n\n/** Apply a simulated outcome across every surface: variants, layout, slots/tokens, persona attrs. */\nfunction applyOutcome(result: OutcomeToApply): void {\n for (const [id, variantId] of Object.entries(result.assignments ?? {})) {\n setVariantOverride(id, variantId);\n }\n const w = window as unknown as OverrideWindow;\n if (result.layoutOrder && result.layoutOrder.length > 0) {\n w.__sentient_layout_override = result.layoutOrder;\n }\n if (result.slots) {\n w.__sentient_slot_overrides = { ...(w.__sentient_slot_overrides ?? {}), ...result.slots };\n }\n if (result.personaAttributes) {\n document.documentElement.dataset.sentientPersona = result.personaAttributes.persona;\n document.documentElement.dataset.sentientConfidence = result.personaAttributes.confidence;\n }\n setPreviewMode(true); // suppress events while previewing\n notifyOverridesChanged(); // re-render layout/slot consumers\n}\n\n// Reads the SDK's own session cookie — the per-project SUFFIXED name first\n// (that is what the client writes since namespacing; the bare `_snt_uid` this\n// used to read is only written in keyless/local mode), then the bare name as\n// the legacy/local fallback.\nfunction readSessionId(apiKey?: string): string {\n const read = (name: string): string | null => {\n try {\n const match = document.cookie.match(new RegExp(`(?:^|; )${name}=([^;]*)`));\n return match ? decodeURIComponent(match[1]!) : null;\n } catch {\n return null;\n }\n };\n return (apiKey ? read(sessionCookieName(apiKey)) : null) ?? read(LEGACY_SESSION_COOKIE_NAME) ?? 'devtools-preview';\n}\n\nfunction slotDecls(): Array<{ id: string; arms?: string[]; dims?: RegisteredSlot['dims'] }> {\n return getRegisteredSlots().map((s) => ({\n id: s.id,\n ...(s.arms ? { arms: s.arms } : {}),\n ...(s.dims ? { dims: s.dims } : {}),\n }));\n}\n\n/** One member of the project's persona vocabulary, as /v1/personas serves it. */\ntype VocabMember = { key: string; displayName: string };\n\n/** Always offered: previewing the unidentified visitor is meaningful on every\n * project, and it is the only persona the product itself defines. */\nconst UNKNOWN_CHOICE: VocabMember = { key: UNKNOWN_PERSONA, displayName: UNKNOWN_PERSONA_DISPLAY };\n\n/**\n * Keyed mode: the project's ACTIVE vocabulary from /v1/personas. Personas are\n * per-project (persona_sets, migration 113) — declared by the app or promoted\n * by discovery. This used to fall back to a hardcoded list of four seeded\n * personas, which offered buttons that silently simulated the default\n * experience on any project whose vocabulary differs, and named audiences\n * nobody had declared. null on any failure → the panel offers only `unknown`\n * and a free-text key.\n */\nasync function fetchPersonaVocabulary(\n apiKey: string,\n apiBaseUrl: string,\n): Promise<{ personas: VocabMember[]; discovered: VocabMember[] } | null> {\n try {\n const res = await fetch(`${apiBaseUrl}/personas`, {\n headers: { authorization: `Bearer ${apiKey}` },\n });\n if (!res.ok) return null;\n const data = (await res.json()) as { personas?: VocabMember[]; discovered?: VocabMember[] };\n const valid = (list: VocabMember[] | undefined): VocabMember[] =>\n Array.isArray(list)\n ? list.filter((p) => p && typeof p.key === 'string' && typeof p.displayName === 'string')\n : [];\n const personas = valid(data.personas);\n return personas.length > 0 ? { personas, discovered: valid(data.discovered) } : null;\n } catch {\n return null;\n }\n}\n\n/**\n * `?sentient_context=<context>` on the page URL: the on-site context preview\n * (a stage such as `carted`, or an arrival class such as `cart_recovery`).\n * Forwarded to /v1/explain so a persona simulated from this panel is also\n * simulated in that context — the API validates the value (400 on anything\n * else) and applies it to the project's published (registry) versions:\n * those restricted to the context become eligible and its pins win. Lives\n * here, not in the provider: devtools is the React SDK's only explain-backed\n * preview, and the main bundle pays for nothing it does not use.\n * @internal Exported for tests.\n */\nexport function previewContextParam(): string | null {\n try {\n const v = new URLSearchParams(window.location.search).get('sentient_context');\n return v && /^[a-z_]{1,40}$/.test(v) ? v : null;\n } catch {\n return null;\n }\n}\n\n/** Keyed mode: simulate via /v1/explain (read-only, event-free). Returns how\n * the persona RESOLVED so the panel can say when the project didn't\n * recognize it — the page then shows the default experience, and a silently\n * highlighted button claiming otherwise was the old lie. */\nasync function forcePersonaKeyed(\n apiKey: string,\n apiBaseUrl: string,\n persona: string,\n): Promise<{ recognized: boolean; resolvedDisplay: string } | null> {\n const res = await fetch(`${apiBaseUrl}/explain`, {\n method: 'POST',\n headers: { 'content-type': 'application/json', authorization: `Bearer ${apiKey}` },\n body: JSON.stringify({\n persona,\n sections: getRegisteredSections().map((id) => ({ id })),\n components: getRegistered().map((c) => ({ id: c.id, variantIds: c.variantIds })),\n slots: slotDecls(),\n ...(previewContextParam() ? { context: previewContextParam() } : {}),\n }),\n });\n if (!res.ok) return null;\n const data = (await res.json()) as OutcomeToApply & {\n recognized?: boolean;\n persona?: string;\n personaDisplay?: string;\n };\n applyOutcome({\n ...data,\n personaAttributes: data.personaAttributes ?? { persona, confidence: 'high' },\n });\n return {\n // An older API omits the field — treat as recognized (no basis to warn).\n recognized: data.recognized !== false,\n resolvedDisplay: data.personaDisplay ?? data.persona ?? persona,\n };\n}\n\n/** Local mode: simulate via the deterministic local engine — zero network. */\nasync function forcePersonaLocal(persona: string, apiKey?: string): Promise<void> {\n const mod = await import('@sentientui/core/local');\n if (!mod.LOCAL_ENGINE_AVAILABLE) return;\n const outcome = mod\n .createLocalEngine({ sessionId: readSessionId(apiKey), forcedPersona: persona })\n .decide({\n sections: getRegisteredSections(),\n components: getRegistered().map((c) => ({ id: c.id, variantIds: c.variantIds })),\n slots: slotDecls(),\n });\n applyOutcome({\n assignments: outcome.assignments,\n layoutOrder: outcome.layoutOrder,\n slots: outcome.slots,\n personaAttributes: {\n persona: outcome.persona,\n confidence: confidenceBand(outcome.confidence),\n },\n });\n}\n\n/** Reset: clear the decision snapshot + every override, then reload to re-decide. */\nfunction resetAll(): void {\n for (const id of Object.keys(getOverrides())) clearVariantOverride(id);\n const w = window as unknown as OverrideWindow;\n delete w.__sentient_layout_override;\n delete w.__sentient_slot_overrides;\n delete document.documentElement.dataset.sentientPersona;\n delete document.documentElement.dataset.sentientConfidence;\n try {\n const stale: string[] = [];\n for (let i = 0; i < localStorage.length; i++) {\n const key = localStorage.key(i);\n if (key && key.startsWith(SNAPSHOT_STORAGE_KEY_PREFIX)) stale.push(key);\n }\n for (const key of stale) localStorage.removeItem(key);\n } catch {\n /* ignore */\n }\n setPreviewMode(false);\n notifyOverridesChanged();\n try {\n window.location.reload();\n } catch {\n /* jsdom */\n }\n}\n\nconst btn = (active: boolean): CSSProperties => ({\n padding: '2px 8px',\n borderRadius: 4,\n border: '1px solid #444',\n background: active ? '#3b82f6' : '#222',\n color: '#eee',\n cursor: 'pointer',\n});\n\n/** Sentient \"S.\" wordmark, monoline — white strokes for the black launcher button. */\nfunction SentientMark({ size = 26 }: { size?: number } = {}): JSX.Element {\n return (\n <svg width={size} height={size} viewBox=\"0 0 32 32\" fill=\"none\" aria-hidden=\"true\">\n <path\n d=\"M21 9H14C11.2 9 9.8 10.8 9.8 13C9.8 15.4 11.6 16.6 14.5 16.6H18.5C20.5 16.6 20.7 18.2 20.4 19.6\"\n stroke=\"#fff\"\n strokeWidth=\"2.2\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n />\n <path d=\"M10 22H17\" stroke=\"#fff\" strokeWidth=\"2.2\" strokeLinecap=\"round\" />\n <circle cx=\"20.6\" cy=\"22\" r=\"2.1\" fill=\"#fff\" />\n </svg>\n );\n}\n\nexport function AdaptiveDevtools({ apiKey }: { apiKey?: string } = {}): JSX.Element | null {\n const [open, setOpen] = useState(false);\n const [activePersona, setActivePersona] = useState<string | null>(null);\n // The project's vocabulary (keyed mode); null = not loaded → no persona\n // buttons beyond `unknown`. Local mode never fetches: there is no project,\n // and the local engine previews ANY key typed into the free-text field.\n const [vocab, setVocab] = useState<VocabMember[] | null>(null);\n const [customKey, setCustomKey] = useState('');\n // Discovered SHADOW personas — display-only. They never serve until\n // promotion, so there is no button: forcing one would simulate a persona\n // that cannot occur on this project.\n const [discovered, setDiscovered] = useState<VocabMember[]>([]);\n // Set when a forced persona did NOT resolve against the project's\n // vocabulary — the page is showing the default experience and the panel\n // must say so instead of highlighting the button as if the preview worked.\n const [personaNote, setPersonaNote] = useState<string | null>(null);\n const [dragFrom, setDragFrom] = useState<number | null>(null);\n const [mounted, setMounted] = useState(false);\n const [, force] = useReducer((n: number) => n + 1, 0);\n // Re-render when the component/slot registry changes. useSyncExternalStore\n // (not a manual useEffect subscription) so the subscription can't go stale\n // across Next Fast Refresh — a stale listener was why the panel needed a hard\n // refresh to pick up a renamed id.\n useSyncExternalStore(subscribeRegistry, getRegistryVersion, () => 0);\n // Client-mount gate: render nothing during SSR / the first paint so the widget\n // never reads `window` on the server. Lets consumers drop `<AdaptiveDevtools/>`\n // straight into a tree without a `dynamic(..., { ssr: false })` wrapper.\n useEffect(() => setMounted(true), []);\n // Load the project's persona vocabulary once (keyed mode only).\n useEffect(() => {\n if (IS_PROD) return;\n const cfg = readDevtoolsConfig() ?? { apiKey: apiKey ?? '', apiBaseUrl: DEFAULT_API_BASE_URL, isLocal: false };\n if (cfg.isLocal || !cfg.apiKey) return;\n let cancelled = false;\n void fetchPersonaVocabulary(cfg.apiKey, cfg.apiBaseUrl).then((v) => {\n if (cancelled || !v) return;\n setVocab(v.personas);\n setDiscovered(v.discovered);\n });\n return () => { cancelled = true; };\n }, [apiKey]);\n\n // Never render in production, even if imported by mistake. (Hooks run first\n // so the rules of hooks hold regardless of these early returns.)\n if (IS_PROD) return null;\n if (!mounted) return null;\n\n const config: DevtoolsConfig = readDevtoolsConfig() ?? {\n apiKey: apiKey ?? '',\n apiBaseUrl: DEFAULT_API_BASE_URL,\n isLocal: false,\n };\n const useLocalEngine = config.isLocal || !config.apiKey;\n const components = getRegistered();\n const slots = getRegisteredSlots();\n const overrides = getOverrides();\n const slotOverrides = getSlotOverrides();\n const sections = currentLayout();\n const layoutForced = (window as unknown as OverrideWindow).__sentient_layout_override !== undefined;\n\n function onReorder(from: number, to: number): void {\n reorderLayout(from, to);\n force();\n }\n function onResetLayout(): void {\n resetLayout();\n maybeExitPreview();\n force();\n }\n\n // Preview mode stays on while ANY override (variant, slot or layout) is\n // active. Omitting layout here let clearing the last variant re-enable event\n // recording while a previewed section order was still on screen.\n function maybeExitPreview(): void {\n if (\n Object.keys(getOverrides()).length === 0 &&\n Object.keys(getSlotOverrides()).length === 0 &&\n (window as unknown as OverrideWindow).__sentient_layout_override === undefined\n ) {\n setPreviewMode(false);\n }\n }\n\n function choose(id: string, variantId: string): void {\n setVariantOverride(id, variantId);\n setPreviewMode(true);\n notifyOverridesChanged();\n force();\n }\n function resetVariant(id: string): void {\n clearVariantOverride(id);\n maybeExitPreview();\n notifyOverridesChanged();\n force();\n }\n function chooseSlotArm(id: string, arm: string): void {\n setSlotOverride(id, arm);\n setPreviewMode(true);\n notifyOverridesChanged();\n force();\n }\n function chooseSlotDim(id: string, dim: string, value: string, dims: RegisteredSlot['dims']): void {\n const current = getSlotOverrides()[id];\n // Merge onto the existing forced object, or seed from each dim's baseline\n // (first value) so unset dims stay at baseline instead of vanishing.\n const next: Record<string, string> =\n current && typeof current === 'object'\n ? { ...current }\n : Object.fromEntries(Object.entries(dims ?? {}).map(([d, values]) => [d, values[0]!]));\n next[dim] = value;\n setSlotOverride(id, next);\n setPreviewMode(true);\n notifyOverridesChanged();\n force();\n }\n function resetSlot(id: string): void {\n clearSlotOverride(id);\n maybeExitPreview();\n notifyOverridesChanged();\n force();\n }\n function choosePersona(member: VocabMember): void {\n setActivePersona(member.key);\n setPersonaNote(null);\n // .catch: a failed simulate (offline /v1/explain, bad key, failed local\n // dynamic import) is a preview no-op — without the handler it surfaced as\n // an unhandled promise rejection in the console.\n if (useLocalEngine) {\n forcePersonaLocal(member.key, config.apiKey).then(force).catch(() => {});\n return;\n }\n forcePersonaKeyed(config.apiKey, config.apiBaseUrl, member.key)\n .then((r) => {\n if (r && !r.recognized) {\n setPersonaNote(\n `“${member.displayName}” isn’t in this project’s personas — the page is showing the default experience.`,\n );\n }\n force();\n })\n .catch(() => {});\n }\n\n return (\n <div style={{ position: 'fixed', bottom: 16, right: 16, zIndex: 2147483647, fontFamily: 'system-ui' }}>\n {/* Panel stays mounted and animates in/out from the button's corner, so the\n launcher below never shifts. transform-origin is the button (bottom-right). */}\n <div\n aria-hidden={!open}\n style={{\n position: 'absolute',\n bottom: 52,\n right: 0,\n transformOrigin: 'bottom right',\n transition: 'opacity .18s ease, transform .2s cubic-bezier(.16,1,.3,1)',\n opacity: open ? 1 : 0,\n transform: open ? 'translateY(0) scale(1)' : 'translateY(6px) scale(.96)',\n pointerEvents: open ? 'auto' : 'none',\n }}\n >\n <div style={{ width: 300, maxHeight: 460, overflowY: 'auto', background: '#111', color: '#eee',\n borderRadius: 8, padding: 12, boxShadow: '0 8px 30px rgba(0,0,0,.4)', fontSize: 12 }}>\n {config.isLocal && (\n <div style={{ background: '#1e293b', border: '1px solid #334155', borderRadius: 4,\n padding: '6px 8px', marginBottom: 8 }}>\n {LOCAL_MODE_DEVTOOLS_BANNER}\n </div>\n )}\n <div style={{ opacity: .7, marginBottom: 8 }}>\n {components.length} component{components.length === 1 ? '' : 's'} · {getPreviewMode() ? 'preview — writing nothing' : 'live'}\n </div>\n <div style={{ borderBottom: '1px solid #333', paddingBottom: 8, marginBottom: 8 }}>\n <div style={{ opacity: .7, marginBottom: 4 }}>Preview persona</div>\n <div style={{ display: 'flex', flexWrap: 'wrap', gap: 4 }}>\n {/* Keyed mode renders the project's OWN vocabulary once\n /v1/personas answers; nothing is invented while it hasn't. */}\n {[...(useLocalEngine ? [] : vocab ?? []), UNKNOWN_CHOICE].map((p) => (\n <button key={p.key} onClick={() => choosePersona(p)} style={btn(activePersona === p.key)}>\n {p.displayName}\n </button>\n ))}\n {(activePersona !== null || Object.keys(overrides).length > 0 || Object.keys(slotOverrides).length > 0) && (\n <button onClick={resetAll} style={{ ...btn(false), color: '#aaa' }}>\n Reset\n </button>\n )}\n </div>\n <form\n onSubmit={(e) => {\n e.preventDefault();\n const key = normalizeDeclaredPersona(customKey);\n if (key) choosePersona({ key, displayName: key });\n }}\n style={{ display: 'flex', gap: 4, marginTop: 6 }}\n >\n <input\n aria-label=\"Persona key\"\n placeholder=\"any persona key, e.g. admin\"\n value={customKey}\n onChange={(e) => setCustomKey(e.target.value)}\n style={{ flex: 1, minWidth: 0, background: '#111', color: '#fff', border: '1px solid #333',\n borderRadius: 4, padding: '4px 6px', fontSize: 12 }}\n />\n <button type=\"submit\" style={btn(false)}>Preview</button>\n </form>\n {personaNote && (\n <div style={{ marginTop: 6, fontSize: 11, color: '#fbbf24' }}>{personaNote}</div>\n )}\n {!useLocalEngine && discovered.length > 0 && (\n <div style={{ marginTop: 8 }}>\n <div style={{ opacity: .5, fontSize: 11, marginBottom: 4 }}>\n Discovered — not serving yet (promote from the dashboard)\n </div>\n <div style={{ display: 'flex', flexWrap: 'wrap', gap: 4 }}>\n {discovered.map((p) => (\n <span\n key={p.key}\n title=\"Found by clustering your traffic; it starts serving only after promotion.\"\n style={{ ...btn(false), opacity: .45, cursor: 'default', display: 'inline-block' }}\n >\n {p.displayName}\n </span>\n ))}\n </div>\n </div>\n )}\n </div>\n {sections.length > 0 && (\n <div style={{ borderBottom: '1px solid #333', paddingBottom: 8, marginBottom: 8 }}>\n <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 4 }}>\n <span style={{ opacity: .7 }}>Layout — drag to reorder</span>\n {layoutForced && (\n // Distinct accessible name: the per-variant and per-slot resets\n // below are also labelled \"reset\", and three identical buttons\n // in one panel is ambiguous to a screen reader and to tests.\n <button\n aria-label=\"Reset section order\"\n onClick={onResetLayout}\n style={{ ...btn(false), color: '#aaa' }}\n >\n reset\n </button>\n )}\n </div>\n {/* Drop-on-row inserts at that row's position, so any block can go\n anywhere in one gesture. The whole order is written on each\n drop — see reorderLayout. */}\n <ul aria-label=\"Section order\" style={{ listStyle: 'none', margin: 0, padding: 0 }}>\n {sections.map((id, i) => (\n <li\n key={id}\n draggable\n onDragStart={() => setDragFrom(i)}\n onDragOver={(e) => e.preventDefault()}\n onDrop={(e) => {\n e.preventDefault();\n if (dragFrom !== null) onReorder(dragFrom, i);\n setDragFrom(null);\n }}\n onDragEnd={() => setDragFrom(null)}\n style={{\n display: 'flex', alignItems: 'center', gap: 6, padding: '4px 6px', marginBottom: 2,\n borderRadius: 4, border: '1px solid #262626', cursor: 'grab',\n background: dragFrom === i ? '#1e293b' : '#181818',\n opacity: dragFrom !== null && dragFrom !== i ? .6 : 1,\n }}\n >\n <span style={{ opacity: .4, minWidth: 10, fontVariantNumeric: 'tabular-nums' }}>{i + 1}</span>\n <span aria-hidden=\"true\" style={{ opacity: .35 }}>⠿</span>\n <span style={{ flex: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>\n {id}\n </span>\n </li>\n ))}\n </ul>\n </div>\n )}\n {components.length === 0 && slots.length === 0 && sections.length === 0 && (\n <div style={{ opacity: .6 }}>No components, sections or slots on this page yet.</div>\n )}\n {components.map((c) => (\n <div key={c.id} style={{ borderTop: '1px solid #333', padding: '8px 0' }}>\n <div style={{ fontWeight: 600 }}>{c.id}{c.goal ? ` · goal: ${c.goal}` : ''}</div>\n <div style={{ display: 'flex', flexWrap: 'wrap', gap: 4, marginTop: 4 }}>\n {c.variantIds.map((v) => (\n <button key={v} onClick={() => choose(c.id, v)} style={btn(overrides[c.id] === v)}>\n {v}\n </button>\n ))}\n {overrides[c.id] && (\n <button onClick={() => resetVariant(c.id)} style={{ ...btn(false), color: '#aaa' }}>\n reset\n </button>\n )}\n </div>\n </div>\n ))}\n {slots.length > 0 && (\n <div style={{ borderTop: '1px solid #333', paddingTop: 8, marginTop: 4 }}>\n <div style={{ opacity: .7, marginBottom: 4 }}>Slots</div>\n {slots.map((s) => {\n const ov = slotOverrides[s.id];\n return (\n <div key={s.id} style={{ padding: '6px 0' }}>\n <div style={{ fontWeight: 600 }}>{s.id}</div>\n {s.arms && (\n <div style={{ display: 'flex', flexWrap: 'wrap', gap: 4, marginTop: 4 }}>\n {s.arms.map((arm) => (\n <button key={arm} onClick={() => chooseSlotArm(s.id, arm)} style={btn(ov === arm)}>\n {arm}\n </button>\n ))}\n </div>\n )}\n {s.dims && Object.entries(s.dims).map(([dim, values]) => (\n <div key={dim} style={{ marginTop: 4 }}>\n <div style={{ opacity: .6, fontSize: 11 }}>{dim}</div>\n <div style={{ display: 'flex', flexWrap: 'wrap', gap: 4 }}>\n {values.map((v) => (\n <button\n key={v}\n onClick={() => chooseSlotDim(s.id, dim, v, s.dims)}\n style={btn(!!ov && typeof ov === 'object' && ov[dim] === v)}\n >\n {v}\n </button>\n ))}\n </div>\n </div>\n ))}\n {ov !== undefined && (\n <button onClick={() => resetSlot(s.id)} style={{ ...btn(false), color: '#aaa', marginTop: 4 }}>\n reset\n </button>\n )}\n </div>\n );\n })}\n </div>\n )}\n </div>\n </div>\n <button\n aria-label=\"Sentient DevTools\"\n aria-expanded={open}\n onClick={() => setOpen((o) => !o)}\n style={{ width: 44, height: 44, borderRadius: 12, border: '1px solid #2a2a2a', background: '#000',\n display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 0,\n cursor: 'pointer', boxShadow: '0 6px 18px rgba(0,0,0,.4)' }}\n >\n <SentientMark />\n </button>\n </div>\n );\n}\n","// `env` is non-optional on purpose: the check below must be written as the\n// exact expression `process.env.NODE_ENV` (see isDevBuild).\ndeclare const process: { env: { NODE_ENV?: string } };\n\n/**\n * True unless the app was built for production.\n *\n * Written as the literal `process.env.NODE_ENV`, inside try/catch, because\n * that exact expression is the only one every bundler rewrites. Vite (like\n * webpack and esbuild) replaces `process.env.NODE_ENV` with a string literal\n * but leaves `typeof process` alone and defines nothing in the browser, so the\n * previous `typeof process === 'undefined' || process.env?.NODE_ENV !==\n * 'production'` read \"no process\" in every Vite production build and returned\n * true: production visitors got the dev-only warnings (\"No consent gate\",\n * \"rendering its baseline children\") and the devtools registry. `?.` defeats\n * the replacement too — Vite turned `process.env?.NODE_ENV` into\n * `{}.NODE_ENV`, i.e. undefined.\n *\n * The catch is for a page with no bundler at all (a raw ESM import, a CDN):\n * there `process` is undeclared and the read throws ReferenceError. That has\n * no build mode, so it counts as development, as it always did.\n */\nexport function isDevBuild(): boolean {\n try {\n return process.env.NODE_ENV !== 'production';\n } catch {\n return true;\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","function store(): Record<string, string> {\n const w = window as unknown as { __sentient_overrides?: Record<string, string> };\n if (!w.__sentient_overrides) w.__sentient_overrides = {};\n return w.__sentient_overrides;\n}\n\n/** Force `componentId` to render `variantId` — read by `useAssignment`. */\nexport function setVariantOverride(componentId: string, variantId: string): void {\n store()[componentId] = variantId;\n}\n\nexport function clearVariantOverride(componentId: string): void {\n delete store()[componentId];\n}\n\nexport function getOverrides(): Record<string, string> {\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","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"],"mappings":";27BAAA,IAAAA,GAAA,GAAAC,GAAAD,GAAA,sBAAAE,GAAA,+BAAAC,GAAA,wBAAAC,IAAA,eAAAC,GAAAL,IAGA,IAAAM,EAAoG,iBACpGC,EAAmG,8BACnGC,EAA2F,4BCiBpF,SAASC,IAAsB,CACpC,GAAI,CACF,OAAO,QAAQ,IAAI,WAAa,YAClC,OAAQ,GACN,MAAO,EACT,CACF,CCPA,IAAMC,GAA6B,CACjC,WAAY,IAAI,IAChB,MAAO,IAAI,IACX,SAAU,CAAC,EACX,UAAW,IAAI,IACf,QAAS,CACX,EAEA,SAASC,GAAuB,CAC9B,GAAI,OAAO,QAAW,YAAa,OAAOD,GAC1C,IAAME,EAAI,OACV,OAAKA,EAAE,sBACLA,EAAE,oBAAsB,CACtB,WAAY,IAAI,IAChB,MAAO,IAAI,IACX,SAAU,CAAC,EACX,UAAW,IAAI,IACf,QAAS,CACX,GAEKA,EAAE,mBACX,CA6CO,SAASC,GAAuC,CACrD,MAAO,CAAC,GAAGC,EAAM,EAAE,WAAW,OAAO,CAAC,CACxC,CAEO,SAAS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E,IAAI,EAAE,IAAI,CAAC,CAACwE,EAAKK,CAAM,OACjD,QAAC,OAAc,MAAO,CAAE,UAAW,CAAE,EACnC,oBAAC,OAAI,MAAO,CAAE,QAAS,GAAI,SAAU,EAAG,EAAI,SAAAL,EAAI,KAChD,OAAC,OAAI,MAAO,CAAE,QAAS,OAAQ,SAAU,OAAQ,IAAK,CAAE,EACrD,SAAAK,EAAO,IAAKlE,MACX,OAAC,UAEC,QAAS,IAAM4D,GAAcvE,EAAE,GAAIwE,EAAK7D,EAAGX,EAAE,IAAI,EACjD,MAAO2B,EAAI,CAAC,CAACwD,GAAM,OAAOA,GAAO,UAAYA,EAAGX,CAAG,IAAM7D,CAAC,EAEzD,SAAAA,GAJIA,CAKP,CACD,EACH,IAZQ6D,CAaV,CACD,EACAW,IAAO,WACN,OAAC,UAAO,QAAS,IAAML,GAAU9E,EAAE,EAAE,EAAG,MAAOiB,EAAA1B,EAAA,GAAKoC,EAAI,EAAK,GAAd,CAAiB,MAAO,OAAQ,UAAW,CAAE,GAAG,iBAE/F,IA9BM3B,EAAE,EAgCZ,CAEJ,CAAC,GACH,GAEJ,EACF,KACA,OAAC,UACC,aAAW,oBACX,gBAAegC,EACf,QAAS,IAAMC,EAASmD,GAAM,CAACA,CAAC,EAChC,MAAO,CAAE,MAAO,GAAI,OAAQ,GAAI,aAAc,GAAI,OAAQ,oBAAqB,WAAY,OAClF,QAAS,OAAQ,WAAY,SAAU,eAAgB,SAAU,QAAS,EAC1E,OAAQ,UAAW,UAAW,2BAA4B,EAEnE,mBAACvD,GAAA,EAAa,EAChB,GACF,CAEJ","names":["devtools_exports","__export","AdaptiveDevtools","LOCAL_MODE_DEVTOOLS_BANNER","previewContextParam","__toCommonJS","import_react","import_policy","import_core","isDevBuild","ssrFallback","state","w","getRegistered","state","getRegisteredSlots","getRegisteredSections","subscribeRegistry","fn","listeners","getRegistryVersion","store","w","setVariantOverride","componentId","variantId","clearVariantOverride","getOverrides","__spreadValues","store","w","setSlotOverride","slotId","result","clearSlotOverride","getSlotOverrides","__spreadValues","ssrFallback","state","w","setPreviewMode","on","s","fn","getPreviewMode","EVENT","notifyOverridesChanged","_a","w","EVENT","readDevtoolsConfig","_a","import_jsx_runtime","IS_PROD","isDevBuild","DEFAULT_API_BASE_URL","LOCAL_MODE_DEVTOOLS_BANNER","currentLayout","forced","registered","getRegisteredSections","id","reorderLayout","from","to","order","next","moved","setPreviewMode","notifyOverridesChanged","resetLayout","applyOutcome","result","_a","_b","variantId","setVariantOverride","w","__spreadValues","readSessionId","apiKey","read","name","match","e","slotDecls","getRegisteredSlots","s","UNKNOWN_CHOICE","fetchPersonaVocabulary","apiBaseUrl","res","data","valid","list","p","personas","previewContextParam","v","forcePersonaKeyed","persona","_c","getRegistered","c","__spreadProps","forcePersonaLocal","mod","outcome","resetAll","getOverrides","clearVariantOverride","stale","i","key","btn","active","SentientMark","size","AdaptiveDevtools","open","setOpen","activePersona","setActivePersona","vocab","setVocab","customKey","setCustomKey","discovered","setDiscovered","personaNote","setPersonaNote","dragFrom","setDragFrom","mounted","setMounted","force","subscribeRegistry","getRegistryVersion","cfg","readDevtoolsConfig","cancelled","config","useLocalEngine","components","slots","overrides","slotOverrides","getSlotOverrides","sections","layoutForced","onReorder","onResetLayout","maybeExitPreview","choose","resetVariant","chooseSlotArm","arm","setSlotOverride","chooseSlotDim","dim","value","dims","current","d","values","resetSlot","clearSlotOverride","choosePersona","member","getPreviewMode","ov","o"]}
package/dist/devtools.mjs CHANGED
@@ -1,3 +1,3 @@
1
1
  'use client';
2
- "use client";var Oe=Object.defineProperty,Re=Object.defineProperties;var Ce=Object.getOwnPropertyDescriptors;var q=Object.getOwnPropertySymbols;var Pe=Object.prototype.hasOwnProperty,Ee=Object.prototype.propertyIsEnumerable;var Q=(e,n,o)=>n in e?Oe(e,n,{enumerable:!0,configurable:!0,writable:!0,value:o}):e[n]=o,l=(e,n)=>{for(var o in n||(n={}))Pe.call(n,o)&&Q(e,o,n[o]);if(q)for(var o of q(n))Ee.call(n,o)&&Q(e,o,n[o]);return e},h=(e,n)=>Re(e,Ce(n));import{useEffect as ie,useReducer as Le,useState as w,useSyncExternalStore as We}from"react";import{UNKNOWN_PERSONA as Ve,UNKNOWN_PERSONA_DISPLAY as Me,confidenceBand as Be,normalizeDeclaredPersona as Ie}from"@sentientui/policy";import{LEGACY_SESSION_COOKIE_NAME as Te,SNAPSHOT_STORAGE_KEY_PREFIX as je,sessionCookieName as ze}from"@sentientui/core";var Ne={components:new Map,slots:new Map,sections:[],listeners:new Set,version:0};function O(){if(typeof window=="undefined")return Ne;let e=window;return e.__sentient_registry||(e.__sentient_registry={components:new Map,slots:new Map,sections:[],listeners:new Set,version:0}),e.__sentient_registry}function C(){return[...O().components.values()]}function B(){return[...O().slots.values()]}function P(){return[...O().sections]}function Z(e){let n=O().listeners;return n.add(e),()=>{n.delete(e)}}function ee(){return O().version}function I(){let e=window;return e.__sentient_overrides||(e.__sentient_overrides={}),e.__sentient_overrides}function T(e,n){I()[e]=n}function j(e){delete I()[e]}function E(){return l({},I())}function z(){let e=window;return e.__sentient_slot_overrides||(e.__sentient_slot_overrides={}),e.__sentient_slot_overrides}function U(e,n){z()[e]=n}function te(e){delete z()[e]}function N(){return l({},z())}var De={on:!1,listeners:new Set};function ne(){if(typeof window=="undefined")return De;let e=window;return e.__sentient_preview||(e.__sentient_preview={on:!1,listeners:new Set}),e.__sentient_preview}function _(e){let n=ne();if(n.on!==e){n.on=e;for(let o of n.listeners)o()}}function oe(){return ne().on}var Ae="sentient:overrides-changed";function p(){var n;if(typeof window=="undefined")return;let e=window;e.__sentient_overrides_version=((n=e.__sentient_overrides_version)!=null?n:0)+1,window.dispatchEvent(new Event(Ae))}function F(){var e;return typeof window=="undefined"?null:(e=window.__sentient_devtools_config)!=null?e:null}import{jsx as r,jsxs as c}from"react/jsx-runtime";var de,re=typeof process!="undefined"&&((de=process.env)==null?void 0:de.NODE_ENV)==="production",se="https://api.sentient-ui.com/v1",Ue="Local mode \u2014 decisions are simulated; add a key to learn from real traffic";function le(){let e=window.__sentient_layout_override,n=P();return!e||e.length===0?n:[...e,...n.filter(o=>!e.includes(o))]}function Fe(e,n){let o=le();if(e===n||e<0||n<0||e>=o.length||n>=o.length)return;let s=[...o],[a]=s.splice(e,1);s.splice(n,0,a),window.__sentient_layout_override=s,_(!0),p()}function $e(){delete window.__sentient_layout_override,p()}function ce(e){var o,s;for(let[a,u]of Object.entries((o=e.assignments)!=null?o:{}))T(a,u);let n=window;e.layoutOrder&&e.layoutOrder.length>0&&(n.__sentient_layout_override=e.layoutOrder),e.slots&&(n.__sentient_slot_overrides=l(l({},(s=n.__sentient_slot_overrides)!=null?s:{}),e.slots)),e.personaAttributes&&(document.documentElement.dataset.sentientPersona=e.personaAttributes.persona,document.documentElement.dataset.sentientConfidence=e.personaAttributes.confidence),_(!0),p()}function Ge(e){var o,s;let n=a=>{try{let u=document.cookie.match(new RegExp(`(?:^|; )${a}=([^;]*)`));return u?decodeURIComponent(u[1]):null}catch(u){return null}};return(s=(o=e?n(ze(e)):null)!=null?o:n(Te))!=null?s:"devtools-preview"}function ue(){return B().map(e=>l(l({id:e.id},e.arms?{arms:e.arms}:{}),e.dims?{dims:e.dims}:{}))}var He={key:Ve,displayName:Me};async function Ke(e,n){try{let o=await fetch(`${n}/personas`,{headers:{authorization:`Bearer ${e}`}});if(!o.ok)return null;let s=await o.json(),a=b=>Array.isArray(b)?b.filter(f=>f&&typeof f.key=="string"&&typeof f.displayName=="string"):[],u=a(s.personas);return u.length>0?{personas:u,discovered:a(s.discovered)}:null}catch(o){return null}}function ae(){try{let e=new URLSearchParams(window.location.search).get("sentient_context");return e&&/^[a-z_]{1,40}$/.test(e)?e:null}catch(e){return null}}async function Ye(e,n,o){var u,b,f;let s=await fetch(`${n}/explain`,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e}`},body:JSON.stringify(l({persona:o,sections:P().map(S=>({id:S})),components:C().map(S=>({id:S.id,variantIds:S.variantIds})),slots:ue()},ae()?{context:ae()}:{}))});if(!s.ok)return null;let a=await s.json();return ce(h(l({},a),{personaAttributes:(u=a.personaAttributes)!=null?u:{persona:o,confidence:"high"}})),{recognized:a.recognized!==!1,resolvedDisplay:(f=(b=a.personaDisplay)!=null?b:a.persona)!=null?f:o}}async function Je(e,n){let o=await import("@sentientui/core/local");if(!o.LOCAL_ENGINE_AVAILABLE)return;let s=o.createLocalEngine({sessionId:Ge(n),forcedPersona:e}).decide({sections:P(),components:C().map(a=>({id:a.id,variantIds:a.variantIds})),slots:ue()});ce({assignments:s.assignments,layoutOrder:s.layoutOrder,slots:s.slots,personaAttributes:{persona:s.persona,confidence:Be(s.confidence)}})}function Xe(){for(let n of Object.keys(E()))j(n);let e=window;delete e.__sentient_layout_override,delete e.__sentient_slot_overrides,delete document.documentElement.dataset.sentientPersona,delete document.documentElement.dataset.sentientConfidence;try{let n=[];for(let o=0;o<localStorage.length;o++){let s=localStorage.key(o);s&&s.startsWith(je)&&n.push(s)}for(let o of n)localStorage.removeItem(o)}catch(n){}_(!1),p();try{window.location.reload()}catch(n){}}var g=e=>({padding:"2px 8px",borderRadius:4,border:"1px solid #444",background:e?"#3b82f6":"#222",color:"#eee",cursor:"pointer"});function qe({size:e=26}={}){return c("svg",{width:e,height:e,viewBox:"0 0 32 32",fill:"none","aria-hidden":"true",children:[r("path",{d:"M21 9H14C11.2 9 9.8 10.8 9.8 13C9.8 15.4 11.6 16.6 14.5 16.6H18.5C20.5 16.6 20.7 18.2 20.4 19.6",stroke:"#fff",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round"}),r("path",{d:"M10 22H17",stroke:"#fff",strokeWidth:"2.2",strokeLinecap:"round"}),r("circle",{cx:"20.6",cy:"22",r:"2.1",fill:"#fff"})]})}function yt({apiKey:e}={}){var J;let[n,o]=w(!1),[s,a]=w(null),[u,b]=w(null),[f,S]=w(""),[$,pe]=w([]),[G,H]=w(null),[k,D]=w(null),[ge,fe]=w(!1),[,v]=Le(t=>t+1,0);if(We(Z,ee,()=>0),ie(()=>fe(!0),[]),ie(()=>{var d;if(re)return;let t=(d=F())!=null?d:{apiKey:e!=null?e:"",apiBaseUrl:se,isLocal:!1};if(t.isLocal||!t.apiKey)return;let i=!1;return Ke(t.apiKey,t.apiBaseUrl).then(y=>{i||!y||(b(y.personas),pe(y.discovered))}),()=>{i=!0}},[e]),re||!ge)return null;let x=(J=F())!=null?J:{apiKey:e!=null?e:"",apiBaseUrl:se,isLocal:!1},A=x.isLocal||!x.apiKey,R=C(),L=B(),W=E(),K=N(),V=le(),ve=window.__sentient_layout_override!==void 0;function ye(t,i){Fe(t,i),v()}function me(){$e(),M(),v()}function M(){Object.keys(E()).length===0&&Object.keys(N()).length===0&&window.__sentient_layout_override===void 0&&_(!1)}function _e(t,i){T(t,i),_(!0),p(),v()}function we(t){j(t),M(),p(),v()}function be(t,i){U(t,i),_(!0),p(),v()}function he(t,i,d,y){let m=N()[t],X=m&&typeof m=="object"?l({},m):Object.fromEntries(Object.entries(y!=null?y:{}).map(([xe,ke])=>[xe,ke[0]]));X[i]=d,U(t,X),_(!0),p(),v()}function Se(t){te(t),M(),p(),v()}function Y(t){if(a(t.key),H(null),A){Je(t.key,x.apiKey).then(v).catch(()=>{});return}Ye(x.apiKey,x.apiBaseUrl,t.key).then(i=>{i&&!i.recognized&&H(`\u201C${t.displayName}\u201D isn\u2019t in this project\u2019s personas \u2014 the page is showing the default experience.`),v()}).catch(()=>{})}return c("div",{style:{position:"fixed",bottom:16,right:16,zIndex:2147483647,fontFamily:"system-ui"},children:[r("div",{"aria-hidden":!n,style:{position:"absolute",bottom:52,right:0,transformOrigin:"bottom right",transition:"opacity .18s ease, transform .2s cubic-bezier(.16,1,.3,1)",opacity:n?1:0,transform:n?"translateY(0) scale(1)":"translateY(6px) scale(.96)",pointerEvents:n?"auto":"none"},children:c("div",{style:{width:300,maxHeight:460,overflowY:"auto",background:"#111",color:"#eee",borderRadius:8,padding:12,boxShadow:"0 8px 30px rgba(0,0,0,.4)",fontSize:12},children:[x.isLocal&&r("div",{style:{background:"#1e293b",border:"1px solid #334155",borderRadius:4,padding:"6px 8px",marginBottom:8},children:Ue}),c("div",{style:{opacity:.7,marginBottom:8},children:[R.length," component",R.length===1?"":"s"," \xB7 ",oe()?"preview \u2014 writing nothing":"live"]}),c("div",{style:{borderBottom:"1px solid #333",paddingBottom:8,marginBottom:8},children:[r("div",{style:{opacity:.7,marginBottom:4},children:"Preview persona"}),c("div",{style:{display:"flex",flexWrap:"wrap",gap:4},children:[[...A?[]:u!=null?u:[],He].map(t=>r("button",{onClick:()=>Y(t),style:g(s===t.key),children:t.displayName},t.key)),(s!==null||Object.keys(W).length>0||Object.keys(K).length>0)&&r("button",{onClick:Xe,style:h(l({},g(!1)),{color:"#aaa"}),children:"Reset"})]}),c("form",{onSubmit:t=>{t.preventDefault();let i=Ie(f);i&&Y({key:i,displayName:i})},style:{display:"flex",gap:4,marginTop:6},children:[r("input",{"aria-label":"Persona key",placeholder:"any persona key, e.g. admin",value:f,onChange:t=>S(t.target.value),style:{flex:1,minWidth:0,background:"#111",color:"#fff",border:"1px solid #333",borderRadius:4,padding:"4px 6px",fontSize:12}}),r("button",{type:"submit",style:g(!1),children:"Preview"})]}),G&&r("div",{style:{marginTop:6,fontSize:11,color:"#fbbf24"},children:G}),!A&&$.length>0&&c("div",{style:{marginTop:8},children:[r("div",{style:{opacity:.5,fontSize:11,marginBottom:4},children:"Discovered \u2014 not serving yet (promote from the dashboard)"}),r("div",{style:{display:"flex",flexWrap:"wrap",gap:4},children:$.map(t=>r("span",{title:"Found by clustering your traffic; it starts serving only after promotion.",style:h(l({},g(!1)),{opacity:.45,cursor:"default",display:"inline-block"}),children:t.displayName},t.key))})]})]}),V.length>0&&c("div",{style:{borderBottom:"1px solid #333",paddingBottom:8,marginBottom:8},children:[c("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:4},children:[r("span",{style:{opacity:.7},children:"Layout \u2014 drag to reorder"}),ve&&r("button",{"aria-label":"Reset section order",onClick:me,style:h(l({},g(!1)),{color:"#aaa"}),children:"reset"})]}),r("ul",{"aria-label":"Section order",style:{listStyle:"none",margin:0,padding:0},children:V.map((t,i)=>c("li",{draggable:!0,onDragStart:()=>D(i),onDragOver:d=>d.preventDefault(),onDrop:d=>{d.preventDefault(),k!==null&&ye(k,i),D(null)},onDragEnd:()=>D(null),style:{display:"flex",alignItems:"center",gap:6,padding:"4px 6px",marginBottom:2,borderRadius:4,border:"1px solid #262626",cursor:"grab",background:k===i?"#1e293b":"#181818",opacity:k!==null&&k!==i?.6:1},children:[r("span",{style:{opacity:.4,minWidth:10,fontVariantNumeric:"tabular-nums"},children:i+1}),r("span",{"aria-hidden":"true",style:{opacity:.35},children:"\u283F"}),r("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:t})]},t))})]}),R.length===0&&L.length===0&&V.length===0&&r("div",{style:{opacity:.6},children:"No components, sections or slots on this page yet."}),R.map(t=>c("div",{style:{borderTop:"1px solid #333",padding:"8px 0"},children:[c("div",{style:{fontWeight:600},children:[t.id,t.goal?` \xB7 goal: ${t.goal}`:""]}),c("div",{style:{display:"flex",flexWrap:"wrap",gap:4,marginTop:4},children:[t.variantIds.map(i=>r("button",{onClick:()=>_e(t.id,i),style:g(W[t.id]===i),children:i},i)),W[t.id]&&r("button",{onClick:()=>we(t.id),style:h(l({},g(!1)),{color:"#aaa"}),children:"reset"})]})]},t.id)),L.length>0&&c("div",{style:{borderTop:"1px solid #333",paddingTop:8,marginTop:4},children:[r("div",{style:{opacity:.7,marginBottom:4},children:"Slots"}),L.map(t=>{let i=K[t.id];return c("div",{style:{padding:"6px 0"},children:[r("div",{style:{fontWeight:600},children:t.id}),t.arms&&r("div",{style:{display:"flex",flexWrap:"wrap",gap:4,marginTop:4},children:t.arms.map(d=>r("button",{onClick:()=>be(t.id,d),style:g(i===d),children:d},d))}),t.dims&&Object.entries(t.dims).map(([d,y])=>c("div",{style:{marginTop:4},children:[r("div",{style:{opacity:.6,fontSize:11},children:d}),r("div",{style:{display:"flex",flexWrap:"wrap",gap:4},children:y.map(m=>r("button",{onClick:()=>he(t.id,d,m,t.dims),style:g(!!i&&typeof i=="object"&&i[d]===m),children:m},m))})]},d)),i!==void 0&&r("button",{onClick:()=>Se(t.id),style:h(l({},g(!1)),{color:"#aaa",marginTop:4}),children:"reset"})]},t.id)})]})]})}),r("button",{"aria-label":"Sentient DevTools","aria-expanded":n,onClick:()=>o(t=>!t),style:{width:44,height:44,borderRadius:12,border:"1px solid #2a2a2a",background:"#000",display:"flex",alignItems:"center",justifyContent:"center",padding:0,cursor:"pointer",boxShadow:"0 6px 18px rgba(0,0,0,.4)"},children:r(qe,{})})]})}export{yt as AdaptiveDevtools,Ue as LOCAL_MODE_DEVTOOLS_BANNER,ae as previewContextParam};
2
+ "use client";var Oe=Object.defineProperty,Re=Object.defineProperties;var Ce=Object.getOwnPropertyDescriptors;var q=Object.getOwnPropertySymbols;var Pe=Object.prototype.hasOwnProperty,Ee=Object.prototype.propertyIsEnumerable;var Q=(e,n,o)=>n in e?Oe(e,n,{enumerable:!0,configurable:!0,writable:!0,value:o}):e[n]=o,l=(e,n)=>{for(var o in n||(n={}))Pe.call(n,o)&&Q(e,o,n[o]);if(q)for(var o of q(n))Ee.call(n,o)&&Q(e,o,n[o]);return e},h=(e,n)=>Re(e,Ce(n));import{useEffect as re,useReducer as Le,useState as w,useSyncExternalStore as We}from"react";import{UNKNOWN_PERSONA as Ve,UNKNOWN_PERSONA_DISPLAY as Be,confidenceBand as Me,normalizeDeclaredPersona as Ie}from"@sentientui/policy";import{LEGACY_SESSION_COOKIE_NAME as Te,SNAPSHOT_STORAGE_KEY_PREFIX as je,sessionCookieName as ze}from"@sentientui/core";function Z(){try{return process.env.NODE_ENV!=="production"}catch(e){return!0}}var De={components:new Map,slots:new Map,sections:[],listeners:new Set,version:0};function O(){if(typeof window=="undefined")return De;let e=window;return e.__sentient_registry||(e.__sentient_registry={components:new Map,slots:new Map,sections:[],listeners:new Set,version:0}),e.__sentient_registry}function C(){return[...O().components.values()]}function M(){return[...O().slots.values()]}function P(){return[...O().sections]}function ee(e){let n=O().listeners;return n.add(e),()=>{n.delete(e)}}function te(){return O().version}function I(){let e=window;return e.__sentient_overrides||(e.__sentient_overrides={}),e.__sentient_overrides}function T(e,n){I()[e]=n}function j(e){delete I()[e]}function E(){return l({},I())}function z(){let e=window;return e.__sentient_slot_overrides||(e.__sentient_slot_overrides={}),e.__sentient_slot_overrides}function U(e,n){z()[e]=n}function ne(e){delete z()[e]}function D(){return l({},z())}var Ne={on:!1,listeners:new Set};function oe(){if(typeof window=="undefined")return Ne;let e=window;return e.__sentient_preview||(e.__sentient_preview={on:!1,listeners:new Set}),e.__sentient_preview}function _(e){let n=oe();if(n.on!==e){n.on=e;for(let o of n.listeners)o()}}function ie(){return oe().on}var Ae="sentient:overrides-changed";function p(){var n;if(typeof window=="undefined")return;let e=window;e.__sentient_overrides_version=((n=e.__sentient_overrides_version)!=null?n:0)+1,window.dispatchEvent(new Event(Ae))}function F(){var e;return typeof window=="undefined"?null:(e=window.__sentient_devtools_config)!=null?e:null}import{jsx as r,jsxs as c}from"react/jsx-runtime";var se=!Z(),ae="https://api.sentient-ui.com/v1",Ue="Local mode \u2014 decisions are simulated; add a key to learn from real traffic";function le(){let e=window.__sentient_layout_override,n=P();return!e||e.length===0?n:[...e,...n.filter(o=>!e.includes(o))]}function Fe(e,n){let o=le();if(e===n||e<0||n<0||e>=o.length||n>=o.length)return;let s=[...o],[a]=s.splice(e,1);s.splice(n,0,a),window.__sentient_layout_override=s,_(!0),p()}function $e(){delete window.__sentient_layout_override,p()}function ce(e){var o,s;for(let[a,u]of Object.entries((o=e.assignments)!=null?o:{}))T(a,u);let n=window;e.layoutOrder&&e.layoutOrder.length>0&&(n.__sentient_layout_override=e.layoutOrder),e.slots&&(n.__sentient_slot_overrides=l(l({},(s=n.__sentient_slot_overrides)!=null?s:{}),e.slots)),e.personaAttributes&&(document.documentElement.dataset.sentientPersona=e.personaAttributes.persona,document.documentElement.dataset.sentientConfidence=e.personaAttributes.confidence),_(!0),p()}function Ge(e){var o,s;let n=a=>{try{let u=document.cookie.match(new RegExp(`(?:^|; )${a}=([^;]*)`));return u?decodeURIComponent(u[1]):null}catch(u){return null}};return(s=(o=e?n(ze(e)):null)!=null?o:n(Te))!=null?s:"devtools-preview"}function ue(){return M().map(e=>l(l({id:e.id},e.arms?{arms:e.arms}:{}),e.dims?{dims:e.dims}:{}))}var He={key:Ve,displayName:Be};async function Ke(e,n){try{let o=await fetch(`${n}/personas`,{headers:{authorization:`Bearer ${e}`}});if(!o.ok)return null;let s=await o.json(),a=b=>Array.isArray(b)?b.filter(f=>f&&typeof f.key=="string"&&typeof f.displayName=="string"):[],u=a(s.personas);return u.length>0?{personas:u,discovered:a(s.discovered)}:null}catch(o){return null}}function de(){try{let e=new URLSearchParams(window.location.search).get("sentient_context");return e&&/^[a-z_]{1,40}$/.test(e)?e:null}catch(e){return null}}async function Ye(e,n,o){var u,b,f;let s=await fetch(`${n}/explain`,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e}`},body:JSON.stringify(l({persona:o,sections:P().map(S=>({id:S})),components:C().map(S=>({id:S.id,variantIds:S.variantIds})),slots:ue()},de()?{context:de()}:{}))});if(!s.ok)return null;let a=await s.json();return ce(h(l({},a),{personaAttributes:(u=a.personaAttributes)!=null?u:{persona:o,confidence:"high"}})),{recognized:a.recognized!==!1,resolvedDisplay:(f=(b=a.personaDisplay)!=null?b:a.persona)!=null?f:o}}async function Je(e,n){let o=await import("@sentientui/core/local");if(!o.LOCAL_ENGINE_AVAILABLE)return;let s=o.createLocalEngine({sessionId:Ge(n),forcedPersona:e}).decide({sections:P(),components:C().map(a=>({id:a.id,variantIds:a.variantIds})),slots:ue()});ce({assignments:s.assignments,layoutOrder:s.layoutOrder,slots:s.slots,personaAttributes:{persona:s.persona,confidence:Me(s.confidence)}})}function Xe(){for(let n of Object.keys(E()))j(n);let e=window;delete e.__sentient_layout_override,delete e.__sentient_slot_overrides,delete document.documentElement.dataset.sentientPersona,delete document.documentElement.dataset.sentientConfidence;try{let n=[];for(let o=0;o<localStorage.length;o++){let s=localStorage.key(o);s&&s.startsWith(je)&&n.push(s)}for(let o of n)localStorage.removeItem(o)}catch(n){}_(!1),p();try{window.location.reload()}catch(n){}}var g=e=>({padding:"2px 8px",borderRadius:4,border:"1px solid #444",background:e?"#3b82f6":"#222",color:"#eee",cursor:"pointer"});function qe({size:e=26}={}){return c("svg",{width:e,height:e,viewBox:"0 0 32 32",fill:"none","aria-hidden":"true",children:[r("path",{d:"M21 9H14C11.2 9 9.8 10.8 9.8 13C9.8 15.4 11.6 16.6 14.5 16.6H18.5C20.5 16.6 20.7 18.2 20.4 19.6",stroke:"#fff",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round"}),r("path",{d:"M10 22H17",stroke:"#fff",strokeWidth:"2.2",strokeLinecap:"round"}),r("circle",{cx:"20.6",cy:"22",r:"2.1",fill:"#fff"})]})}function _t({apiKey:e}={}){var J;let[n,o]=w(!1),[s,a]=w(null),[u,b]=w(null),[f,S]=w(""),[$,pe]=w([]),[G,H]=w(null),[k,N]=w(null),[ge,fe]=w(!1),[,v]=Le(t=>t+1,0);if(We(ee,te,()=>0),re(()=>fe(!0),[]),re(()=>{var d;if(se)return;let t=(d=F())!=null?d:{apiKey:e!=null?e:"",apiBaseUrl:ae,isLocal:!1};if(t.isLocal||!t.apiKey)return;let i=!1;return Ke(t.apiKey,t.apiBaseUrl).then(y=>{i||!y||(b(y.personas),pe(y.discovered))}),()=>{i=!0}},[e]),se||!ge)return null;let x=(J=F())!=null?J:{apiKey:e!=null?e:"",apiBaseUrl:ae,isLocal:!1},A=x.isLocal||!x.apiKey,R=C(),L=M(),W=E(),K=D(),V=le(),ve=window.__sentient_layout_override!==void 0;function ye(t,i){Fe(t,i),v()}function me(){$e(),B(),v()}function B(){Object.keys(E()).length===0&&Object.keys(D()).length===0&&window.__sentient_layout_override===void 0&&_(!1)}function _e(t,i){T(t,i),_(!0),p(),v()}function we(t){j(t),B(),p(),v()}function be(t,i){U(t,i),_(!0),p(),v()}function he(t,i,d,y){let m=D()[t],X=m&&typeof m=="object"?l({},m):Object.fromEntries(Object.entries(y!=null?y:{}).map(([xe,ke])=>[xe,ke[0]]));X[i]=d,U(t,X),_(!0),p(),v()}function Se(t){ne(t),B(),p(),v()}function Y(t){if(a(t.key),H(null),A){Je(t.key,x.apiKey).then(v).catch(()=>{});return}Ye(x.apiKey,x.apiBaseUrl,t.key).then(i=>{i&&!i.recognized&&H(`\u201C${t.displayName}\u201D isn\u2019t in this project\u2019s personas \u2014 the page is showing the default experience.`),v()}).catch(()=>{})}return c("div",{style:{position:"fixed",bottom:16,right:16,zIndex:2147483647,fontFamily:"system-ui"},children:[r("div",{"aria-hidden":!n,style:{position:"absolute",bottom:52,right:0,transformOrigin:"bottom right",transition:"opacity .18s ease, transform .2s cubic-bezier(.16,1,.3,1)",opacity:n?1:0,transform:n?"translateY(0) scale(1)":"translateY(6px) scale(.96)",pointerEvents:n?"auto":"none"},children:c("div",{style:{width:300,maxHeight:460,overflowY:"auto",background:"#111",color:"#eee",borderRadius:8,padding:12,boxShadow:"0 8px 30px rgba(0,0,0,.4)",fontSize:12},children:[x.isLocal&&r("div",{style:{background:"#1e293b",border:"1px solid #334155",borderRadius:4,padding:"6px 8px",marginBottom:8},children:Ue}),c("div",{style:{opacity:.7,marginBottom:8},children:[R.length," component",R.length===1?"":"s"," \xB7 ",ie()?"preview \u2014 writing nothing":"live"]}),c("div",{style:{borderBottom:"1px solid #333",paddingBottom:8,marginBottom:8},children:[r("div",{style:{opacity:.7,marginBottom:4},children:"Preview persona"}),c("div",{style:{display:"flex",flexWrap:"wrap",gap:4},children:[[...A?[]:u!=null?u:[],He].map(t=>r("button",{onClick:()=>Y(t),style:g(s===t.key),children:t.displayName},t.key)),(s!==null||Object.keys(W).length>0||Object.keys(K).length>0)&&r("button",{onClick:Xe,style:h(l({},g(!1)),{color:"#aaa"}),children:"Reset"})]}),c("form",{onSubmit:t=>{t.preventDefault();let i=Ie(f);i&&Y({key:i,displayName:i})},style:{display:"flex",gap:4,marginTop:6},children:[r("input",{"aria-label":"Persona key",placeholder:"any persona key, e.g. admin",value:f,onChange:t=>S(t.target.value),style:{flex:1,minWidth:0,background:"#111",color:"#fff",border:"1px solid #333",borderRadius:4,padding:"4px 6px",fontSize:12}}),r("button",{type:"submit",style:g(!1),children:"Preview"})]}),G&&r("div",{style:{marginTop:6,fontSize:11,color:"#fbbf24"},children:G}),!A&&$.length>0&&c("div",{style:{marginTop:8},children:[r("div",{style:{opacity:.5,fontSize:11,marginBottom:4},children:"Discovered \u2014 not serving yet (promote from the dashboard)"}),r("div",{style:{display:"flex",flexWrap:"wrap",gap:4},children:$.map(t=>r("span",{title:"Found by clustering your traffic; it starts serving only after promotion.",style:h(l({},g(!1)),{opacity:.45,cursor:"default",display:"inline-block"}),children:t.displayName},t.key))})]})]}),V.length>0&&c("div",{style:{borderBottom:"1px solid #333",paddingBottom:8,marginBottom:8},children:[c("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:4},children:[r("span",{style:{opacity:.7},children:"Layout \u2014 drag to reorder"}),ve&&r("button",{"aria-label":"Reset section order",onClick:me,style:h(l({},g(!1)),{color:"#aaa"}),children:"reset"})]}),r("ul",{"aria-label":"Section order",style:{listStyle:"none",margin:0,padding:0},children:V.map((t,i)=>c("li",{draggable:!0,onDragStart:()=>N(i),onDragOver:d=>d.preventDefault(),onDrop:d=>{d.preventDefault(),k!==null&&ye(k,i),N(null)},onDragEnd:()=>N(null),style:{display:"flex",alignItems:"center",gap:6,padding:"4px 6px",marginBottom:2,borderRadius:4,border:"1px solid #262626",cursor:"grab",background:k===i?"#1e293b":"#181818",opacity:k!==null&&k!==i?.6:1},children:[r("span",{style:{opacity:.4,minWidth:10,fontVariantNumeric:"tabular-nums"},children:i+1}),r("span",{"aria-hidden":"true",style:{opacity:.35},children:"\u283F"}),r("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:t})]},t))})]}),R.length===0&&L.length===0&&V.length===0&&r("div",{style:{opacity:.6},children:"No components, sections or slots on this page yet."}),R.map(t=>c("div",{style:{borderTop:"1px solid #333",padding:"8px 0"},children:[c("div",{style:{fontWeight:600},children:[t.id,t.goal?` \xB7 goal: ${t.goal}`:""]}),c("div",{style:{display:"flex",flexWrap:"wrap",gap:4,marginTop:4},children:[t.variantIds.map(i=>r("button",{onClick:()=>_e(t.id,i),style:g(W[t.id]===i),children:i},i)),W[t.id]&&r("button",{onClick:()=>we(t.id),style:h(l({},g(!1)),{color:"#aaa"}),children:"reset"})]})]},t.id)),L.length>0&&c("div",{style:{borderTop:"1px solid #333",paddingTop:8,marginTop:4},children:[r("div",{style:{opacity:.7,marginBottom:4},children:"Slots"}),L.map(t=>{let i=K[t.id];return c("div",{style:{padding:"6px 0"},children:[r("div",{style:{fontWeight:600},children:t.id}),t.arms&&r("div",{style:{display:"flex",flexWrap:"wrap",gap:4,marginTop:4},children:t.arms.map(d=>r("button",{onClick:()=>be(t.id,d),style:g(i===d),children:d},d))}),t.dims&&Object.entries(t.dims).map(([d,y])=>c("div",{style:{marginTop:4},children:[r("div",{style:{opacity:.6,fontSize:11},children:d}),r("div",{style:{display:"flex",flexWrap:"wrap",gap:4},children:y.map(m=>r("button",{onClick:()=>he(t.id,d,m,t.dims),style:g(!!i&&typeof i=="object"&&i[d]===m),children:m},m))})]},d)),i!==void 0&&r("button",{onClick:()=>Se(t.id),style:h(l({},g(!1)),{color:"#aaa",marginTop:4}),children:"reset"})]},t.id)})]})]})}),r("button",{"aria-label":"Sentient DevTools","aria-expanded":n,onClick:()=>o(t=>!t),style:{width:44,height:44,borderRadius:12,border:"1px solid #2a2a2a",background:"#000",display:"flex",alignItems:"center",justifyContent:"center",padding:0,cursor:"pointer",boxShadow:"0 6px 18px rgba(0,0,0,.4)"},children:r(qe,{})})]})}export{_t as AdaptiveDevtools,Ue as LOCAL_MODE_DEVTOOLS_BANNER,de as previewContextParam};
3
3
  //# sourceMappingURL=devtools.mjs.map