@sentientui/react 0.35.1 → 0.35.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.
@@ -269,7 +269,7 @@ type PreloadComponent = {
269
269
  id: string;
270
270
  variantIds: string[];
271
271
  };
272
- type AdaptiveRootProps = Omit<AdaptiveProviderProps, 'initialAssignments' | 'onAssignment' | 'initialSlots' | 'initialSlotConfig' | 'initialPalette' | 'initialPersona' | 'initialLayoutOrder' | 'declaredSections' | 'sessionSegment' | 'consentFrom'> & {
272
+ type AdaptiveRootProps = Omit<AdaptiveProviderProps, 'initialAssignments' | 'onAssignment' | 'initialSlots' | 'initialSlotConfig' | 'initialPalette' | 'initialVocabulary' | 'initialPersona' | 'initialLayoutOrder' | 'declaredSections' | 'sessionSegment' | 'consentFrom'> & {
273
273
  /**
274
274
  * Cookie-based consent source — see `AdaptiveProviderProps.consentFrom`.
275
275
  *
@@ -1,4 +1,4 @@
1
- var he=Object.defineProperty,Se=Object.defineProperties;var ve=Object.getOwnPropertyDescriptors;var F=Object.getOwnPropertySymbols;var ee=Object.prototype.hasOwnProperty,te=Object.prototype.propertyIsEnumerable;var Z=(e,t,n)=>t in e?he(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,u=(e,t)=>{for(var n in t||(t={}))ee.call(t,n)&&Z(e,n,t[n]);if(F)for(var n of F(t))te.call(t,n)&&Z(e,n,t[n]);return e},A=(e,t)=>Se(e,ve(t));var ne=(e,t)=>{var n={};for(var s in e)ee.call(e,s)&&t.indexOf(s)<0&&(n[s]=e[s]);if(e!=null&&F)for(var s of F(e))t.indexOf(s)<0&&te.call(e,s)&&(n[s]=e[s]);return n};import{deriveSessionSegment as De,extractTrackedParams as Ce,matchedAgentToken as Ke}from"@sentientui/core";import{cookies as Ue,headers as _e}from"next/headers";import{renderPrePaintScript as ke}from"@sentientui/core";import{confidenceBand as Re}from"@sentientui/policy";import{jsx as be}from"react/jsx-runtime";function se(e){return JSON.stringify(e).replace(/</g,"\\u003c")}function Ie(e){return e.persona?'(function(){try{var d=document.documentElement;if(d.hasAttribute("data-sentient-persona"))return;d.setAttribute("data-sentient-persona",'+se(e.persona.persona)+');d.setAttribute("data-sentient-confidence",'+se(Re(e.persona.confidence))+");}catch(e){}})();":ke(e.apiKey)}function re(e){return be("script",{"data-sentient-persona-script":"",nonce:e.nonce,dangerouslySetInnerHTML:{__html:Ie(e)}})}import{preloadAssignments as Pe,readSessionCookie as we}from"@sentientui/core/server";import{preloadDecisions as Ge}from"@sentientui/core/server";function oe(){return typeof crypto!="undefined"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`snt-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}async function ie(e,t){var r,o,i;let n=(i=(o=we(t.cookies,t.apiKey))!=null?o:(r=t.createSessionId)==null?void 0:r.call(t))!=null?i:oe();return{assignments:await Pe(e,n,{apiKey:t.apiKey,baseUrl:t.baseUrl,origin:t.origin,userAgent:t.userAgent,referer:t.referer,utmParams:t.utmParams,clickIds:t.clickIds,doNotTrack:t.doNotTrack,timeoutMs:t.timeoutMs,persona:t.persona}),sessionId:n}}async function ae(e){var i,l,S,v,p,b,k,P,a,g;let{preloadDecisions:t,readSessionCookie:n}=await import("@sentientui/core/server"),s=(S=(l=n(e.cookies,e.apiKey))!=null?l:(i=e.createSessionId)==null?void 0:i.call(e))!=null?S:oe();if(!(typeof e.apiKey=="string"&&e.apiKey.startsWith("pk_"))){let m={layoutOrder:(v=e.sections)!=null?v:[],assignments:{},slots:{},persona:"unknown",confidence:0,sessionId:s};try{let f=await import("@sentientui/core/local");if(!f.LOCAL_ENGINE_AVAILABLE)return console.error("[sentient] No API key configured \u2014 nothing is being learned. Set NEXT_PUBLIC_SENTIENT_API_KEY or pass localMode: true for local development."),m;let c=f.createLocalEngine({sessionId:s}).decide({sections:e.sections,components:(p=e.components)!=null?p:[],slots:(b=e.slots)!=null?b:[]});return{layoutOrder:(P=(k=c.layoutOrder)!=null?k:e.sections)!=null?P:[],assignments:c.assignments,slots:c.slots,persona:c.persona,confidence:c.confidence,sessionId:s}}catch(f){return m}}let o=await t({sections:e.sections,components:(a=e.components)!=null?a:[],slots:(g=e.slots)!=null?g:[],slotsFrom:e.slotsFrom,registrySlotIds:e.registrySlotIds},s,{apiKey:e.apiKey,baseUrl:e.baseUrl,origin:e.origin,userAgent:e.userAgent,referer:e.referer,utmParams:e.utmParams,clickIds:e.clickIds,doNotTrack:e.doNotTrack,timeoutMs:e.timeoutMs,persona:e.persona});return A(u({},o),{sessionId:s})}import{AdaptiveRootClient as Te}from"./adaptive-root-client.js";var Fe=["page","blocks","layoutOrder"],ce=new Map;function Oe(e,t){ce.set(e,t)}function xe(e){return ce.get(e)}function E(e){var r,o;let t=(o=(r=e.content)!=null?r:xe(e.page))!=null?o:{},n={};for(let[i,l]of Object.entries(t))Fe.includes(i)||(n[i]=l);let s=A(u({},n),{page:e.page,blocks:e.blocks});return e.layoutOrder&&(s.layoutOrder=e.layoutOrder),s}function de(e){return JSON.stringify(u({"@context":"https://schema.org","@type":"WebPage"},e)).replace(/</g,"\\u003c")}function le(e){let t=[];e.title&&t.push(`# ${e.title}`,""),e.summary&&t.push(String(e.summary),"");for(let[n,s]of Object.entries(e))["page","title","summary","blocks","layoutOrder"].includes(n)||t.push(`## ${n}`,"","```json",JSON.stringify(s,null,2),"```","");if(e.blocks.length>0){t.push("## blocks","");for(let n of e.blocks)t.push(`- **${n.id}** \u2192 variant \`${n.variant}\``),n.content!==void 0&&t.push(""," ```json",JSON.stringify(n.content,null,2)," ```");t.push("")}return t.join(`
1
+ var ve=Object.defineProperty,Se=Object.defineProperties;var ke=Object.getOwnPropertyDescriptors;var F=Object.getOwnPropertySymbols;var te=Object.prototype.hasOwnProperty,ne=Object.prototype.propertyIsEnumerable;var ee=(e,t,n)=>t in e?ve(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,u=(e,t)=>{for(var n in t||(t={}))te.call(t,n)&&ee(e,n,t[n]);if(F)for(var n of F(t))ne.call(t,n)&&ee(e,n,t[n]);return e},A=(e,t)=>Se(e,ke(t));var se=(e,t)=>{var n={};for(var s in e)te.call(e,s)&&t.indexOf(s)<0&&(n[s]=e[s]);if(e!=null&&F)for(var s of F(e))t.indexOf(s)<0&&ne.call(e,s)&&(n[s]=e[s]);return n};import{deriveSessionSegment as Ce,extractTrackedParams as Ke,matchedAgentToken as Ue}from"@sentientui/core";import{cookies as _e,headers as Te}from"next/headers";import{renderPrePaintScript as Re}from"@sentientui/core";import{confidenceBand as be}from"@sentientui/policy";import{jsx as Pe}from"react/jsx-runtime";function re(e){return JSON.stringify(e).replace(/</g,"\\u003c")}function Ie(e){return e.persona?'(function(){try{var d=document.documentElement;if(d.hasAttribute("data-sentient-persona"))return;d.setAttribute("data-sentient-persona",'+re(e.persona.persona)+');d.setAttribute("data-sentient-confidence",'+re(be(e.persona.confidence))+");}catch(e){}})();":Re(e.apiKey)}function oe(e){return Pe("script",{"data-sentient-persona-script":"",nonce:e.nonce,dangerouslySetInnerHTML:{__html:Ie(e)}})}import{preloadAssignments as we,readSessionCookie as Fe}from"@sentientui/core/server";import{preloadDecisions as ze}from"@sentientui/core/server";function ie(){return typeof crypto!="undefined"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`snt-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}async function ae(e,t){var r,o,i;let n=(i=(o=Fe(t.cookies,t.apiKey))!=null?o:(r=t.createSessionId)==null?void 0:r.call(t))!=null?i:ie();return{assignments:await we(e,n,{apiKey:t.apiKey,baseUrl:t.baseUrl,origin:t.origin,userAgent:t.userAgent,referer:t.referer,utmParams:t.utmParams,clickIds:t.clickIds,doNotTrack:t.doNotTrack,timeoutMs:t.timeoutMs,persona:t.persona}),sessionId:n}}async function ce(e){var i,l,v,S,p,I,k,P,a,g;let{preloadDecisions:t,readSessionCookie:n}=await import("@sentientui/core/server"),s=(v=(l=n(e.cookies,e.apiKey))!=null?l:(i=e.createSessionId)==null?void 0:i.call(e))!=null?v:ie();if(!(typeof e.apiKey=="string"&&e.apiKey.startsWith("pk_"))){let m={layoutOrder:(S=e.sections)!=null?S:[],assignments:{},slots:{},persona:"unknown",confidence:0,sessionId:s};try{let f=await import("@sentientui/core/local");if(!f.LOCAL_ENGINE_AVAILABLE)return console.error("[sentient] No API key configured \u2014 nothing is being learned. Set NEXT_PUBLIC_SENTIENT_API_KEY or pass localMode: true for local development."),m;let c=f.createLocalEngine({sessionId:s}).decide({sections:e.sections,components:(p=e.components)!=null?p:[],slots:(I=e.slots)!=null?I:[]});return{layoutOrder:(P=(k=c.layoutOrder)!=null?k:e.sections)!=null?P:[],assignments:c.assignments,slots:c.slots,persona:c.persona,confidence:c.confidence,sessionId:s}}catch(f){return m}}let o=await t({sections:e.sections,components:(a=e.components)!=null?a:[],slots:(g=e.slots)!=null?g:[],slotsFrom:e.slotsFrom,registrySlotIds:e.registrySlotIds},s,{apiKey:e.apiKey,baseUrl:e.baseUrl,origin:e.origin,userAgent:e.userAgent,referer:e.referer,utmParams:e.utmParams,clickIds:e.clickIds,doNotTrack:e.doNotTrack,timeoutMs:e.timeoutMs,persona:e.persona});return A(u({},o),{sessionId:s})}import{AdaptiveRootClient as Be}from"./adaptive-root-client.js";var Le=["page","blocks","layoutOrder"],de=new Map;function Oe(e,t){de.set(e,t)}function xe(e){return de.get(e)}function D(e){var r,o;let t=(o=(r=e.content)!=null?r:xe(e.page))!=null?o:{},n={};for(let[i,l]of Object.entries(t))Le.includes(i)||(n[i]=l);let s=A(u({},n),{page:e.page,blocks:e.blocks});return e.layoutOrder&&(s.layoutOrder=e.layoutOrder),s}function le(e){return JSON.stringify(u({"@context":"https://schema.org","@type":"WebPage"},e)).replace(/</g,"\\u003c")}function ge(e){let t=[];e.title&&t.push(`# ${e.title}`,""),e.summary&&t.push(String(e.summary),"");for(let[n,s]of Object.entries(e))["page","title","summary","blocks","layoutOrder"].includes(n)||t.push(`## ${n}`,"","```json",JSON.stringify(s,null,2),"```","");if(e.blocks.length>0){t.push("## blocks","");for(let n of e.blocks)t.push(`- **${n.id}** \u2192 variant \`${n.variant}\``),n.content!==void 0&&t.push(""," ```json",JSON.stringify(n.content,null,2)," ```");t.push("")}return t.join(`
2
2
  `).trimEnd()+`
3
- `}function ge(e,t={}){var s,r;let n=(s=t.fetchImpl)!=null?s:fetch;try{n(`${e.baseUrl}/crawler-events`,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e.apiKey}`},body:JSON.stringify({path:e.path,botName:e.botName,userAgent:(r=e.userAgent)!=null?r:null,source:"ssr"})}).catch(()=>{})}catch(o){}}import{matchedAgentToken as Le}from"@sentientui/core";function Ne(e,t){return e.pathname.endsWith(".md")||t.toLowerCase().includes("text/markdown")}function Ee(e){return async t=>{var l;let n=new URL(t.url),s=(l=t.headers.get("accept"))!=null?l:"",r=t.headers.get("user-agent"),o=n.pathname.replace(/\.(md|json)$/,"");if(e.onRead)try{Promise.resolve(e.onRead({path:o,userAgent:r,botName:Le(r!=null?r:"")})).catch(()=>{})}catch(S){}let i=await e.getFeed(t);return Ne(n,s)?new Response(le(i),{headers:{"content-type":"text/markdown; charset=utf-8"}}):new Response(JSON.stringify(i),{headers:{"content-type":"application/json; charset=utf-8"}})}}import{matchedAgentToken as ft,uaTokenMatch as At,agentIntent as yt,classifiedAgents as ht}from"@sentientui/core";import{Fragment as pe,jsx as D,jsxs as ue}from"react/jsx-runtime";var Be="https://api.sentient-ui.com/v1";function Me(e){return Object.entries(e).map(([t,n])=>{var s;return{id:t,variant:typeof n=="string"?n:(s=n==null?void 0:n.variantId)!=null?s:""}})}async function lt(e){var X,q,H,W,G,z,Y,Q;let V=e,{components:t=[],sections:n,slots:s,registrySlotIds:r,appOrigin:o,searchParams:i,initialAssignments:l,ssrSessionId:S,timeoutMs:v,agentFeed:p,captureAgents:b,nonce:k,children:P}=V,a=ne(V,["components","sections","slots","registrySlotIds","appOrigin","searchParams","initialAssignments","ssrSessionId","timeoutMs","agentFeed","captureAgents","nonce","children"]),g=await _e(),m=g.get("host");!o&&process.env.NODE_ENV==="production"&&!m&&console.error("[SentientUI] AdaptiveRoot: Host header is absent and no appOrigin was provided. Pass appOrigin explicitly \u2014 the https://localhost fallback will likely fail allowed_origins validation.");let f=o!=null?o:process.env.NODE_ENV==="production"?`https://${m!=null?m:"localhost"}`:"http://localhost:3001",c=(X=g.get("user-agent"))!=null?X:void 0,O=(q=g.get("referer"))!=null?q:void 0,{utmParams:C,clickIds:K}=Ce(i!=null?i:{}),me=g.get("dnt")==="1"||g.get("sec-gpc")==="1",fe=De({userAgent:c,referer:O,appOrigin:f}),x=await Ue(),y=a.consentFrom,L=(G=a.consent)!=null?G:y!=null&&y.cookie?((H=x.get(y.cookie))==null?void 0:H.value)===((W=y.value)!=null?W:"accepted"):void 0,Ae=me||L===!1||y!=null&&L!==!0,N=a.apiBaseUrl?a.apiBaseUrl.replace(/\/$/,""):Be,U=(Y=(z=p==null?void 0:p.path)!=null?z:g.get("x-pathname"))!=null?Y:"/",_=Ke(c!=null?c:"");b!==!1&&_&&ge({baseUrl:N,apiKey:a.apiKey,path:U,botName:_,userAgent:c});let h,R=null,T,B,M,I=null,w,J=!!(r!=null&&r.length);if(l)h=l,w=S;else if(Ae)h={};else if(n&&n.length>0||s&&s.length>0||J){let d=await ae(A(u({sections:n!=null?n:[],components:t,slots:s},J?{slotsFrom:"registry",registrySlotIds:r}:{}),{cookies:x,apiKey:a.apiKey,baseUrl:N,origin:f,userAgent:c,referer:O,utmParams:C,clickIds:K,timeoutMs:v,persona:a.persona}));h=d.assignments,R=d.layoutOrder,T=d.slots,B=d.slotConfig,M=d.palette,I=d.persona!==void 0?{persona:d.persona,confidence:(Q=d.confidence)!=null?Q:0}:null,w=d.sessionId}else{let d=await ie(t,{cookies:x,apiKey:a.apiKey,baseUrl:N,origin:f,userAgent:c,referer:O,utmParams:C,clickIds:K,timeoutMs:v,persona:a.persona});h=d.assignments,w=d.sessionId}let j=D(re,{apiKey:a.apiKey,persona:I,nonce:k}),$=D(Te,A(u({},a),{consent:L,initialAssignments:h,initialLayoutOrder:R,declaredSections:n,initialSlots:T,initialSlotConfig:B,initialPalette:M,initialPersona:I!=null?I:void 0,sessionSegment:fe,ssrSessionId:w,children:P}));if(!p)return ue(pe,{children:[j,$]});let ye=E({page:U,blocks:Me(h),layoutOrder:R!=null?R:void 0,content:p.content});return ue(pe,{children:[j,D("script",{type:"application/ld+json",nonce:k,dangerouslySetInnerHTML:{__html:de(ye)}}),$]})}export{lt as AdaptiveRoot,yt as agentIntent,E as buildAgentFeedFor,ht as classifiedAgents,Ee as createAgentFeed,Oe as defineAgentContent,ft as matchedAgentToken,At as uaTokenMatch};
3
+ `}function pe(e,t={}){var s,r;let n=(s=t.fetchImpl)!=null?s:fetch;try{n(`${e.baseUrl}/crawler-events`,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e.apiKey}`},body:JSON.stringify({path:e.path,botName:e.botName,userAgent:(r=e.userAgent)!=null?r:null,source:"ssr"})}).catch(()=>{})}catch(o){}}import{matchedAgentToken as Ne}from"@sentientui/core";function De(e,t){return e.pathname.endsWith(".md")||t.toLowerCase().includes("text/markdown")}function Ee(e){return async t=>{var l;let n=new URL(t.url),s=(l=t.headers.get("accept"))!=null?l:"",r=t.headers.get("user-agent"),o=n.pathname.replace(/\.(md|json)$/,"");if(e.onRead)try{Promise.resolve(e.onRead({path:o,userAgent:r,botName:Ne(r!=null?r:"")})).catch(()=>{})}catch(v){}let i=await e.getFeed(t);return De(n,s)?new Response(ge(i),{headers:{"content-type":"text/markdown; charset=utf-8"}}):new Response(JSON.stringify(i),{headers:{"content-type":"application/json; charset=utf-8"}})}}import{matchedAgentToken as At,uaTokenMatch as yt,agentIntent as ht,classifiedAgents as vt}from"@sentientui/core";import{Fragment as ue,jsx as E,jsxs as me}from"react/jsx-runtime";var Me="https://api.sentient-ui.com/v1";function Je(e){return Object.entries(e).map(([t,n])=>{var s;return{id:t,variant:typeof n=="string"?n:(s=n==null?void 0:n.variantId)!=null?s:""}})}async function gt(e){var q,H,W,G,z,Y,Q,Z;let X=e,{components:t=[],sections:n,slots:s,registrySlotIds:r,appOrigin:o,searchParams:i,initialAssignments:l,ssrSessionId:v,timeoutMs:S,agentFeed:p,captureAgents:I,nonce:k,children:P}=X,a=se(X,["components","sections","slots","registrySlotIds","appOrigin","searchParams","initialAssignments","ssrSessionId","timeoutMs","agentFeed","captureAgents","nonce","children"]),g=await Te(),m=g.get("host");!o&&process.env.NODE_ENV==="production"&&!m&&console.error("[SentientUI] AdaptiveRoot: Host header is absent and no appOrigin was provided. Pass appOrigin explicitly \u2014 the https://localhost fallback will likely fail allowed_origins validation.");let f=o!=null?o:process.env.NODE_ENV==="production"?`https://${m!=null?m:"localhost"}`:"http://localhost:3001",c=(q=g.get("user-agent"))!=null?q:void 0,L=(H=g.get("referer"))!=null?H:void 0,{utmParams:C,clickIds:K}=Ke(i!=null?i:{}),fe=g.get("dnt")==="1"||g.get("sec-gpc")==="1",Ae=Ce({userAgent:c,referer:L,appOrigin:f}),O=await _e(),y=a.consentFrom,x=(z=a.consent)!=null?z:y!=null&&y.cookie?((W=O.get(y.cookie))==null?void 0:W.value)===((G=y.value)!=null?G:"accepted"):void 0,ye=fe||x===!1||y!=null&&x!==!0,N=a.apiBaseUrl?a.apiBaseUrl.replace(/\/$/,""):Me,U=(Q=(Y=p==null?void 0:p.path)!=null?Y:g.get("x-pathname"))!=null?Q:"/",_=Ue(c!=null?c:"");I!==!1&&_&&pe({baseUrl:N,apiKey:a.apiKey,path:U,botName:_,userAgent:c});let h,R=null,T,B,M,J,b=null,w,j=!!(r!=null&&r.length);if(l)h=l,w=v;else if(ye)h={};else if(n&&n.length>0||s&&s.length>0||j){let d=await ce(A(u({sections:n!=null?n:[],components:t,slots:s},j?{slotsFrom:"registry",registrySlotIds:r}:{}),{cookies:O,apiKey:a.apiKey,baseUrl:N,origin:f,userAgent:c,referer:L,utmParams:C,clickIds:K,timeoutMs:S,persona:a.persona}));h=d.assignments,R=d.layoutOrder,T=d.slots,B=d.slotConfig,M=d.palette,J=d.vocabulary,b=d.persona!==void 0?{persona:d.persona,confidence:(Z=d.confidence)!=null?Z:0}:null,w=d.sessionId}else{let d=await ae(t,{cookies:O,apiKey:a.apiKey,baseUrl:N,origin:f,userAgent:c,referer:L,utmParams:C,clickIds:K,timeoutMs:S,persona:a.persona});h=d.assignments,w=d.sessionId}let $=E(oe,{apiKey:a.apiKey,persona:b,nonce:k}),V=E(Be,A(u({},a),{consent:x,initialAssignments:h,initialLayoutOrder:R,declaredSections:n,initialSlots:T,initialSlotConfig:B,initialPalette:M,initialVocabulary:J,initialPersona:b!=null?b:void 0,sessionSegment:Ae,ssrSessionId:w,children:P}));if(!p)return me(ue,{children:[$,V]});let he=D({page:U,blocks:Je(h),layoutOrder:R!=null?R:void 0,content:p.content});return me(ue,{children:[$,E("script",{type:"application/ld+json",nonce:k,dangerouslySetInnerHTML:{__html:le(he)}}),V]})}export{gt as AdaptiveRoot,ht as agentIntent,D as buildAgentFeedFor,vt as classifiedAgents,Ee as createAgentFeed,Oe as defineAgentContent,At as matchedAgentToken,yt as uaTokenMatch};
4
4
  //# sourceMappingURL=adaptive-root.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/next/adaptive-root.tsx","../../src/persona-script.tsx","../../src/server.ts","../../src/agent-feed.ts","../../src/next/log-agent-fetch.ts","../../src/next/agent-feed-route.ts"],"sourcesContent":["import { deriveSessionSegment, extractTrackedParams, matchedAgentToken } from '@sentientui/core';\nimport type { SlotDeclInput, SlotResult } from '@sentientui/core';\nimport { cookies, headers } from 'next/headers';\n// `type JSX` from react, not the global namespace removed in @types/react@19\n// (peers allow react >=18) — see adaptive-text.tsx.\nimport type { JSX, ReactNode } from 'react';\nimport type { AdaptiveProviderProps } from '../provider.js';\nimport { SentientPersonaScript } from '../persona-script.js';\nimport {\n loadAdaptiveAssignments,\n loadAdaptiveDecision,\n type LoadAdaptiveDecisionResult,\n type ServerAssignments,\n} from '../server.js';\nimport { AdaptiveRootClient } from './adaptive-root-client.js';\nimport { buildAgentFeed, renderAgentJsonLdBody, type AgentBlock } from '../agent-feed.js';\nimport { logAgentFetch } from './log-agent-fetch.js';\n\nexport { createAgentFeed } from './agent-feed-route.js';\nexport type { AgentFeedRouteConfig, AgentFeedReadEntry } from './agent-feed-route.js';\nexport { defineAgentContent, buildAgentFeed as buildAgentFeedFor } from '../agent-feed.js';\n// Re-exported from core on the SERVER entry (this module is server-only — it\n// imports next/headers). Lets server components do agent detection with just the\n// `@sentientui/react` package, no direct core dependency. Do NOT add this to the\n// package's client index: re-exporting a plain function through a 'use client'\n// module turns it into a client reference that throws when called during SSR.\nexport { matchedAgentToken, uaTokenMatch, agentIntent, classifiedAgents } from '@sentientui/core';\nexport type { AgentIntent } from '@sentientui/core';\nexport type { AgentFeed } from '../agent-feed.js';\n\nconst DEFAULT_API_BASE_URL = 'https://api.sentient-ui.com/v1';\n\nexport type PreloadComponent = { id: string; variantIds: string[] };\n\nexport type AdaptiveRootProps = Omit<\n AdaptiveProviderProps,\n // Every provider prop AdaptiveRoot itself resolves and passes AFTER the\n // {...providerProps} spread must be omitted here: a caller-supplied value\n // would typecheck but be silently clobbered by the spread order\n // (initialLayoutOrder, declaredSections and sessionSegment were missing\n // from this list and suffered exactly that).\n | 'initialAssignments'\n | 'onAssignment'\n | 'initialSlots'\n | 'initialSlotConfig'\n | 'initialPalette'\n | 'initialPersona'\n | 'initialLayoutOrder'\n | 'declaredSections'\n | 'sessionSegment'\n | 'consentFrom'\n> & {\n /**\n * Cookie-based consent source — see `AdaptiveProviderProps.consentFrom`.\n *\n * Narrowed to the cookie form: AdaptiveRoot is a Server Component and spreads\n * this straight into its client boundary, and a function prop crossing the\n * server→client boundary throws at render (\"Functions cannot be passed\n * directly to Client Components\"). The provider's type accepted `check`, so\n * a Cookiebot-style predicate typechecked here and then crashed the layout.\n * Need a JS-API CMP predicate? Use `<AdaptiveProvider>` in a client component.\n */\n consentFrom?: Omit<NonNullable<AdaptiveProviderProps['consentFrom']>, 'check'>;\n /**\n * Code-variant components to assign server-side (SEO-safe). Optional — an\n * `<Adaptive>` works without an entry here and assigns after mount.\n *\n * List only ids this tree actually renders. Each one is assigned on every\n * request, rendered or not, and every assignment logs an impression (or a\n * holdout exposure). An id the page never renders therefore accrues trials\n * that cannot convert, and in a root layout that happens on every route.\n */\n components?: PreloadComponent[];\n /**\n * Declare page section IDs in their default order. When provided,\n * AdaptiveRoot calls `/v1/decide` (single round trip) instead of\n * individual `/v1/assign` calls, and `useLayoutOrder()` returns the\n * persona-specific order on first render.\n *\n * Give each section's rendered element `data-sentient-id=\"<sectionId>\"` —\n * the only markup a section needs — so the DOM graph scanner can register\n * it under the same id. Without it the server never learns what the section\n * IS, types it `generic`, and serves the identity order to every persona —\n * the integration looks live but cannot personalize. The provider warns\n * about unresolvable ids in development. Correct a section the content\n * classifier mistypes with `sectionTypes`, not extra markup.\n *\n * @example sections={['hero', 'pricing', 'features', 'social_proof']}\n * // …and in the tree: <section data-sentient-id=\"pricing\">\n */\n sections?: string[];\n /**\n * Adaptive-slot declarations used by `useAdaptiveTokens` / `AdaptiveGroup`\n * in this tree. Declaring them here decides them in the same SSR\n * round trip, so their values serialize into the server HTML.\n */\n slots?: SlotDeclInput[];\n /**\n * The generated-mode `<Adaptive id>`s THIS page renders. Declaring them\n * decides their published versions in the same SSR round trip\n * (`/v1/decide` registry mode) and serializes the served content into the\n * server HTML, so the first paint shows the version rather than the\n * original children until the client-side decide answers. Without it a\n * registry slot renders its children first and swaps after mount.\n *\n * Scoped to exactly these ids on purpose: an unscoped registry decide\n * records a close-out trial for every published slot on every page.\n *\n * @example registrySlotIds={['hero-headline', 'pricing-cta']}\n */\n registrySlotIds?: string[];\n /** App origin — must be in the project's `allowed_origins`. */\n appOrigin?: string;\n /**\n * The page's `searchParams` prop (or an equivalent query string /\n * URLSearchParams). Server Components cannot read the request URL from\n * `headers()`, so without this the SSR-minted session carries no `utm_*`\n * params and no ad click IDs (gclid, fbclid, ttclid, …) — campaign\n * attribution only lands after client hydration, and never for visits the\n * client SDK doesn't get to finish (bounce before hydrate). Pass it on\n * landing pages that receive ad traffic:\n *\n * ```tsx\n * export default async function Page({ searchParams }: { searchParams: Promise<Record<string, string | string[] | undefined>> }) {\n * return <AdaptiveRoot ... searchParams={await searchParams}>...</AdaptiveRoot>;\n * }\n * ```\n */\n searchParams?: Record<string, string | string[] | undefined> | URLSearchParams | string;\n /** Override: when set no network fetch is made. Useful for tests. */\n initialAssignments?: ServerAssignments;\n /**\n * Milliseconds to wait for the API before rendering default variants.\n * Defaults to 1000. The hot path typically returns in well under 150 ms;\n * the full 1 s budget is only reached on a cold start or an API\n * geographically distant from your SSR host. Lower it if your API is\n * co-located and warm.\n */\n timeoutMs?: number;\n /**\n * When set, AdaptiveRoot emits a server-rendered inline JSON-LD block\n * describing the page's winning variants, layout order, and developer-supplied\n * content — readable by passive AI crawlers (which do not run JS). Invisible to\n * humans (a JSON-LD script renders no visible DOM). Omit to emit nothing.\n */\n agentFeed?: {\n /** Page path for the feed. Falls back to the `x-pathname` request header, then '/'. */\n path?: string;\n /** Structured page content. Falls back to the `defineAgentContent` registry for this path. */\n content?: Record<string, unknown>;\n };\n /**\n * When true (default), a known AI-agent fetch (matched by user-agent —\n * GPTBot, ChatGPT-User, Claude-User, PerplexityBot, …) is logged server-side\n * to your agent analytics. Machine telemetry only (no cookie, no session);\n * fire-and-forget, never affects render. Set false to opt out.\n */\n captureAgents?: boolean;\n /**\n * CSP nonce for the inline persona (and optional agent JSON-LD) scripts.\n * Pass through from Next.js middleware / `headers()` when using a strict CSP.\n */\n nonce?: string;\n children: ReactNode;\n};\n\n/** Build agent blocks from SSR assignments (Record<id, variantId | { variantId }>). */\nfunction assignmentsToBlocks(assignments: ServerAssignments): AgentBlock[] {\n return Object.entries(assignments as Record<string, unknown>).map(([id, v]) => ({\n id,\n variant: typeof v === 'string' ? v : ((v as { variantId?: string })?.variantId ?? ''),\n }));\n}\n\n/**\n * Next.js Server Component that resolves variant assignments (and optionally\n * section layout order) server-side for zero layout shift on first paint.\n *\n * When `sections` is provided, a single `POST /v1/decide` call returns both\n * the persona-specific section order and all component assignments.\n * Without `sections`, individual `/v1/assign` calls are made per component.\n *\n * @example\n * // app/page.tsx — with section layout. Declared on the page (not the root\n * // layout) because hero_cta renders only here; see the `components` prop.\n * import { AdaptiveRoot } from '@sentientui/react/next';\n *\n * export default async function Page() {\n * return (\n * <AdaptiveRoot\n * apiKey={process.env.NEXT_PUBLIC_SENTIENT_API_KEY!}\n * sections={['hero', 'pricing', 'features', 'social_proof']}\n * components={[\n * { id: 'hero_cta', variantIds: ['default', 'accent'] },\n * ]}\n * >\n * <HeroSection />\n * <PricingSection />\n * <FeaturesSection />\n * <SocialProofSection />\n * </AdaptiveRoot>\n * );\n * }\n */\nexport async function AdaptiveRoot(props: AdaptiveRootProps): Promise<JSX.Element> {\n const {\n components = [],\n sections,\n slots,\n registrySlotIds,\n appOrigin,\n searchParams,\n initialAssignments: initialAssignmentsOverride,\n ssrSessionId: ssrSessionIdProp,\n timeoutMs,\n agentFeed,\n captureAgents,\n nonce,\n children,\n ...providerProps\n } = props;\n\n const headerStore = await headers();\n const host = headerStore.get('host');\n if (!appOrigin && process.env.NODE_ENV === 'production' && !host) {\n console.error(\n '[SentientUI] AdaptiveRoot: Host header is absent and no appOrigin was provided. ' +\n 'Pass appOrigin explicitly — the https://localhost fallback will likely fail allowed_origins validation.',\n );\n }\n const resolvedOrigin = appOrigin ??\n (process.env.NODE_ENV === 'production'\n ? `https://${host ?? 'localhost'}`\n : 'http://localhost:3001');\n const userAgent = headerStore.get('user-agent') ?? undefined;\n const referer = headerStore.get('referer') ?? undefined;\n // Landing-URL attribution (utm_* + ad click IDs). Only available when the\n // page passes its searchParams down — headers() never carries the request's\n // own query string, and the Referer is the PREVIOUS page, not this one.\n const { utmParams, clickIds } = extractTrackedParams(searchParams ?? {});\n // Honor a tracking opt-out at SSR: `DNT: 1` or the legally-enforceable\n // `Sec-GPC: 1`. When set we skip the session upsert + assign/decide so no\n // session row is minted for the visitor (audit P4) — matching the client SDK,\n // which already no-ops for these signals.\n const doNotTrack = headerStore.get('dnt') === '1' || headerStore.get('sec-gpc') === '1';\n // `consent: false` must gate the SERVER too, not just the client. Without\n // this the SSR decide/assign still ran and still minted a session row for a\n // visitor who had not consented — contradicting the documented contract\n // (\"no SDK is initialised, no cookies are written, no events are sent\") and\n // forcing sites to hide AdaptiveRoot behind a conditional render, which is\n // what made consent-after-load cost a full server round trip.\n const sessionSegment = deriveSessionSegment({ userAgent, referer, appOrigin: resolvedOrigin });\n const cookieStore = await cookies();\n\n // This is a Server Component and already has the request cookies, so resolve\n // a cookie-based `consentFrom` here rather than making the app read the same\n // cookie again just to pass `consent` — naming it twice only invites drift.\n // An already-consented visitor therefore gets SSR variant assignment (zero\n // layout shift) with no extra code.\n //\n // An explicit `consent` prop always wins — it is the escape hatch for apps\n // that track consent elsewhere. (No `check()` form here: see the prop type.)\n //\n // Consent gates the SERVER too, not just the client: without it the SSR\n // decide/assign still ran and still minted a session row for a visitor who\n // had not consented, contradicting the documented contract (\"no SDK is\n // initialised, no cookies are written, no events are sent\").\n const cf = providerProps.consentFrom;\n const consent =\n providerProps.consent ??\n (cf?.cookie\n ? cookieStore.get(cf.cookie)?.value === (cf.value ?? 'accepted')\n : undefined);\n const skipSsr = doNotTrack || consent === false || (cf != null && consent !== true);\n\n // SSR preload MUST hit the same API host the client will use, otherwise the\n // SSR-minted session lives on the wrong host and the client's first /assign\n // misses it and re-mints — silently breaking SSR→client continuity for any\n // non-default / self-hosted deployment. The client derives its base from\n // apiBaseUrl too (see provider.tsx), so thread the same value here.\n const baseUrl = providerProps.apiBaseUrl\n ? providerProps.apiBaseUrl.replace(/\\/$/, '')\n : DEFAULT_API_BASE_URL;\n\n // Server-side agent-fetch capture (spec: nextjs-agent-fetch-capture). JS-less\n // assistants (GPTBot / ChatGPT-User / Claude-User / PerplexityBot / …) never\n // run client JS, but they trigger SSR — so AdaptiveRoot sees their UA here.\n // Fire-and-forget; never blocks or breaks render. `agentPath` is reused by the\n // agentFeed JSON-LD below.\n const agentPath = agentFeed?.path ?? headerStore.get('x-pathname') ?? '/';\n const agentBot = matchedAgentToken(userAgent ?? '');\n if (captureAgents !== false && agentBot) {\n logAgentFetch({ baseUrl, apiKey: providerProps.apiKey, path: agentPath, botName: agentBot, userAgent });\n }\n\n let initialAssignments: ServerAssignments;\n let initialLayoutOrder: string[] | null = null;\n let initialSlots: Record<string, SlotResult> | undefined;\n let initialSlotConfig: LoadAdaptiveDecisionResult['slotConfig'];\n let initialPalette: LoadAdaptiveDecisionResult['palette'];\n let initialPersona: { persona: string; confidence: number } | null = null;\n let ssrSessionId: string | undefined;\n\n // Registry mode only when ids were declared: an unscoped registry decide\n // records a close-out trial for every published slot on every page.\n const registry = !!registrySlotIds?.length;\n\n if (initialAssignmentsOverride) {\n initialAssignments = initialAssignmentsOverride;\n ssrSessionId = ssrSessionIdProp;\n } else if (skipSsr) {\n // Nothing server-side: no decide, no assign, no session. Components fall\n // back to `ssrFallback`, and the client starts only if the visitor later\n // consents — via the `consent` prop or grantConsent(), neither of which\n // needs a page reload.\n initialAssignments = {};\n } else if ((sections && sections.length > 0) || (slots && slots.length > 0) || registry) {\n // `loadAdaptiveDecision` accepted `registrySlotIds` long before AdaptiveRoot\n // passed them, so an `<Adaptive id>` under AdaptiveRoot showed its original\n // children on first paint until the client-side decide returned.\n const decision = await loadAdaptiveDecision({\n sections: sections ?? [],\n components,\n slots,\n ...(registry ? { slotsFrom: 'registry' as const, registrySlotIds } : {}),\n cookies: cookieStore,\n apiKey: providerProps.apiKey,\n baseUrl,\n origin: resolvedOrigin,\n userAgent,\n referer,\n utmParams,\n clickIds,\n // doNotTrack is deliberately not passed: it is necessarily false on this\n // branch — a DNT/GPC or consent-gated request already took the skipSsr\n // arm above and never reaches this loader.\n timeoutMs,\n persona: providerProps.persona,\n });\n initialAssignments = decision.assignments;\n initialLayoutOrder = decision.layoutOrder;\n initialSlots = decision.slots;\n initialSlotConfig = decision.slotConfig;\n initialPalette = decision.palette;\n initialPersona =\n decision.persona !== undefined\n ? { persona: decision.persona, confidence: decision.confidence ?? 0 }\n : null;\n ssrSessionId = decision.sessionId;\n } else {\n const result = await loadAdaptiveAssignments(components, {\n cookies: cookieStore,\n apiKey: providerProps.apiKey,\n baseUrl,\n origin: resolvedOrigin,\n userAgent,\n referer,\n utmParams,\n clickIds,\n // doNotTrack is deliberately not passed: it is necessarily false on this\n // branch — a DNT/GPC or consent-gated request already took the skipSsr\n // arm above and never reaches this loader.\n timeoutMs,\n persona: providerProps.persona,\n });\n initialAssignments = result.assignments;\n ssrSessionId = result.sessionId;\n }\n\n // Single-writer inline script — ALWAYS the first child, before any markup\n // that CSS keyed on the persona attributes could style.\n const personaScript = (\n <SentientPersonaScript apiKey={providerProps.apiKey} persona={initialPersona} nonce={nonce} />\n );\n\n const client = (\n <AdaptiveRootClient\n {...providerProps}\n // Forward the server-resolved value so a consented visitor's client does\n // not start gated and re-resolve the same cookie on mount.\n consent={consent}\n initialAssignments={initialAssignments}\n initialLayoutOrder={initialLayoutOrder}\n // Declared regardless of what came back, so devtools can preview layout on\n // a page whose decision was gated or timed out.\n declaredSections={sections}\n initialSlots={initialSlots}\n // Registry-mode preload: the hook treats a preloaded slot config as\n // settled, so the client does not decide the same slot a second time.\n initialSlotConfig={initialSlotConfig}\n initialPalette={initialPalette}\n initialPersona={initialPersona ?? undefined}\n sessionSegment={sessionSegment}\n ssrSessionId={ssrSessionId}\n >\n {children}\n </AdaptiveRootClient>\n );\n\n if (!agentFeed) {\n return (\n <>\n {personaScript}\n {client}\n </>\n );\n }\n\n // Server-rendered inline JSON-LD for AI crawlers. Emitted only on the server\n // path so passive crawlers (no JS) see it in the raw HTML. The body escapes\n // '<' so page content cannot break out of the <script> element.\n const feed = buildAgentFeed({\n page: agentPath,\n blocks: assignmentsToBlocks(initialAssignments),\n layoutOrder: initialLayoutOrder ?? undefined,\n content: agentFeed.content,\n });\n\n return (\n <>\n {personaScript}\n <script\n type=\"application/ld+json\"\n nonce={nonce}\n dangerouslySetInnerHTML={{ __html: renderAgentJsonLdBody(feed) }}\n />\n {client}\n </>\n );\n}\n","// `type JSX` from react, not the global namespace removed in @types/react@19\n// (peers allow react >=18) — see adaptive-text.tsx.\nimport type { JSX } from 'react';\nimport { renderPrePaintScript } from '@sentientui/core';\nimport { confidenceBand } from '@sentientui/policy';\n\nexport type SentientPersonaScriptProps = {\n /** Publishable API key — selects the localStorage snapshot in the fallback path. */\n apiKey: string;\n /**\n * CSP nonce for the inline pre-paint script. Pass the same nonce your\n * `Content-Security-Policy` `script-src` allows (e.g. from Next.js middleware).\n * Required for strict CSP deployments that block `'unsafe-inline'`.\n */\n nonce?: string;\n /**\n * SSR-decided persona (from `loadAdaptiveDecision`). When present the\n * script embeds the literal values; when absent it reads the local\n * decision snapshot (SPA / return-visit path).\n */\n persona?: { persona: string; confidence: number } | null;\n};\n\n/** JSON string literal that is also safe inside an inline <script> element. */\nfunction inlineJsString(value: string): string {\n return JSON.stringify(value).replace(/</g, '\\\\u003c');\n}\n\n/** Exported for tests. Builds the inline JS (concatenation only — no backticks). */\nexport function personaScriptBody(props: SentientPersonaScriptProps): string {\n if (props.persona) {\n return (\n '(function(){try{var d=document.documentElement;' +\n 'if(d.hasAttribute(\"data-sentient-persona\"))return;' +\n 'd.setAttribute(\"data-sentient-persona\",' + inlineJsString(props.persona.persona) + ');' +\n 'd.setAttribute(\"data-sentient-confidence\",' + inlineJsString(confidenceBand(props.persona.confidence)) + ');' +\n '}catch(e){}})();'\n );\n }\n return renderPrePaintScript(props.apiKey);\n}\n\n/**\n * Single writer of the Rung-1a `<html>` attributes\n * (`data-sentient-persona`, `data-sentient-confidence`), executed pre-paint.\n *\n * `AdaptiveRoot` renders this automatically as its first child. For Pages\n * Router / Remix, render it yourself in `_document` / the root layout.\n *\n * IMPORTANT (install docs): add `suppressHydrationWarning` to your `<html>`\n * element — this script mutates documentElement before React hydrates it\n * (the same pattern next-themes uses). The client SDK adopts the attributes\n * as truth and never rewrites them mid-session.\n */\nexport function SentientPersonaScript(props: SentientPersonaScriptProps): JSX.Element {\n return (\n <script\n data-sentient-persona-script=\"\"\n nonce={props.nonce}\n dangerouslySetInnerHTML={{ __html: personaScriptBody(props) }}\n />\n );\n}\n","/**\n * Server-only helpers for Next.js / SSR. No React or DOM APIs.\n */\nimport {\n preloadAssignments,\n readSessionCookie,\n type ServerAssignConfig,\n type ServerAssignments,\n} from '@sentientui/core/server';\n\nexport { preloadAssignments, readSessionCookie };\nexport type { ServerAssignConfig, ServerAssignments };\n\n/** Return value of `loadAdaptiveAssignments` — includes the session ID used for SSR. */\nexport type LoadAdaptiveAssignmentsResult = {\n assignments: ServerAssignments;\n /** The session ID used for SSR assignment. Pass as `ssrSessionId` to `<AdaptiveProvider>`. */\n sessionId: string;\n};\n\nexport type LoadAdaptiveAssignmentsOptions = {\n /** Next.js `cookies()` return value, or any object with `get(name)`. */\n cookies: { get(name: string): { value: string } | undefined };\n apiKey: string;\n baseUrl: string;\n /** Used when `_snt_uid` is absent (e.g. first visit, many crawlers). */\n createSessionId?: () => string;\n /** Must match a value in the project's `allowed_origins` (e.g. `http://localhost:3001`). */\n origin?: string;\n /** From Next.js `headers().get('user-agent')` — aligns SSR segment with the client. */\n userAgent?: string;\n /** From Next.js `headers().get('referer')`. */\n referer?: string;\n /**\n * `utm_*` params from the landing URL. The Referer header never carries the\n * page's OWN query string, so without this the SSR-minted session has no\n * campaign attribution until the client SDK hydrates and re-upserts.\n * Derive with `extractTrackedParams(searchParams)` from `@sentientui/core/server`.\n */\n utmParams?: Record<string, string>;\n /** Ad-platform click IDs (gclid, fbclid, ttclid, …) from the landing URL — same derivation as `utmParams`. */\n clickIds?: Record<string, string>;\n /** Set true when the request carries `DNT: 1` or `Sec-GPC: 1` — skips the SSR session upsert + assignment so no session is minted for an opted-out visitor (audit P4). `AdaptiveRoot` sets this automatically from the request headers. */\n doNotTrack?: boolean;\n /** Milliseconds to wait for the API before returning default variants. Defaults to 1000 (typical decide is well under 150 ms; the full budget is only reached on a cold start or a distant API). */\n timeoutMs?: number;\n /**\n * Declared persona — the role your app already knows for this visitor (e.g.\n * from your auth context: 'admin', 'evaluator'). Must be a key in the\n * project's persona vocabulary; unrecognized values are ignored server-side.\n * Never a user id or email.\n */\n persona?: string;\n};\n\nfunction defaultSessionId(): string {\n if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {\n return crypto.randomUUID();\n }\n return `snt-${Date.now()}-${Math.random().toString(36).slice(2, 11)}`;\n}\n\n/**\n * Fetches bandit assignments on the server for SEO-safe HTML.\n * Pass `assignments` as `initialAssignments` and `sessionId` as `ssrSessionId`\n * on `<AdaptiveProvider>` so the client adopts the same session on first visit.\n */\nexport async function loadAdaptiveAssignments(\n components: Array<{ id: string; variantIds: string[] }>,\n options: LoadAdaptiveAssignmentsOptions,\n): Promise<LoadAdaptiveAssignmentsResult> {\n // apiKey is not optional here: the client writes the per-project suffixed\n // cookie, so an un-keyed read missed every returning visitor and minted a\n // fresh orphan session per SSR request (see readSessionCookie in core).\n const sessionId =\n readSessionCookie(options.cookies, options.apiKey) ??\n options.createSessionId?.() ??\n defaultSessionId();\n\n const assignments = await preloadAssignments(components, sessionId, {\n apiKey: options.apiKey,\n baseUrl: options.baseUrl,\n origin: options.origin,\n userAgent: options.userAgent,\n referer: options.referer,\n utmParams: options.utmParams,\n clickIds: options.clickIds,\n doNotTrack: options.doNotTrack,\n timeoutMs: options.timeoutMs,\n persona: options.persona,\n });\n\n return { assignments, sessionId };\n}\n\nexport { preloadDecisions } from '@sentientui/core/server';\nexport type { DecideResult, SlotDeclInput, SlotResult } from '@sentientui/core/server';\n\n/** Return value of `loadAdaptiveDecision` — includes the session ID used for SSR. */\nexport type LoadAdaptiveDecisionResult = import('@sentientui/core/server').DecideResult & {\n sessionId: string;\n};\n\nexport type LoadAdaptiveDecisionOptions = LoadAdaptiveAssignmentsOptions & {\n /**\n * Section IDs in default order. Passed to /v1/decide as the candidate\n * layout. Optional since 0.13.0 — slot-only pages may omit it (at least\n * one of `sections`/`components`/`slots` must be non-empty).\n */\n sections?: string[];\n /** Components to assign in the same decide call. */\n components?: Array<{ id: string; variantIds?: string[] }>;\n /** Adaptive-slot declarations (useAdaptiveTokens / AdaptiveGroup) to decide server-side. */\n slots?: import('@sentientui/core/server').SlotDeclInput[];\n /** 'registry' serves the project's published slot definitions (`<Adaptive id>`)\n * and is the only way `slotConfig`/`palette` come back. Default 'request'.\n * Requires `registrySlotIds`. */\n slotsFrom?: 'request' | 'registry';\n /**\n * Registry mode: the `<Adaptive id>`s THIS page renders — the decide is\n * scoped to exactly these. Required with `slotsFrom: 'registry'`; without it\n * the call downgrades to request mode (with a console.error) instead of\n * recording a close-out trial for every published slot on every page.\n */\n registrySlotIds?: string[];\n};\n\n/**\n * SSR helper for pages with a declared section layout and/or adaptive slots.\n * Calls `/v1/decide` instead of multiple `/v1/assign` round trips.\n * Pass `sessionId` as `ssrSessionId` on `<AdaptiveProvider>` so the client\n * adopts the same session on first visit.\n *\n * Keyless: with no valid `pk_` key this never fetches (no timeout burn).\n * Under the `development` export condition the decision is computed by the\n * deterministic local engine with the same sessionId the client will adopt —\n * server and client agree by construction. In production the engine resolves\n * to a stub and defaults are returned with one console.error.\n */\nexport async function loadAdaptiveDecision(\n options: LoadAdaptiveDecisionOptions,\n): Promise<LoadAdaptiveDecisionResult> {\n const { preloadDecisions, readSessionCookie } = await import('@sentientui/core/server');\n\n // Keyed read — the client's cookie name is suffixed per project (see\n // loadAdaptiveAssignments above). Works for keyless too: with no pk_ key the\n // client writes the bare legacy name, which the un-suffixed read falls back to.\n const sessionId =\n readSessionCookie(options.cookies, options.apiKey) ??\n options.createSessionId?.() ??\n defaultSessionId();\n\n const keyValid = typeof options.apiKey === 'string' && options.apiKey.startsWith('pk_');\n if (!keyValid) {\n const fallback: LoadAdaptiveDecisionResult = {\n layoutOrder: options.sections ?? [],\n assignments: {},\n slots: {},\n persona: 'unknown',\n confidence: 0,\n sessionId,\n };\n try {\n const mod = (await import('@sentientui/core/local')) as unknown as {\n LOCAL_ENGINE_AVAILABLE: boolean;\n createLocalEngine(opts: { sessionId: string }): {\n decide(input: {\n sections?: string[];\n components?: Array<{ id: string; variantIds?: string[] }>;\n slots?: LoadAdaptiveDecisionOptions['slots'];\n }): {\n layoutOrder: string[] | null;\n assignments: Record<string, string>;\n slots: Record<string, string | Record<string, string>>;\n persona: string;\n confidence: number;\n };\n };\n };\n if (!mod.LOCAL_ENGINE_AVAILABLE) {\n // Pinned message — must byte-match PROD_KEYLESS_ERROR in @sentientui/core.\n console.error(\n '[sentient] No API key configured — nothing is being learned. Set NEXT_PUBLIC_SENTIENT_API_KEY or pass localMode: true for local development.',\n );\n return fallback;\n }\n const outcome = mod.createLocalEngine({ sessionId }).decide({\n sections: options.sections,\n components: options.components ?? [],\n slots: options.slots ?? [],\n });\n return {\n layoutOrder: outcome.layoutOrder ?? options.sections ?? [],\n assignments: outcome.assignments,\n slots: outcome.slots,\n persona: outcome.persona,\n confidence: outcome.confidence,\n sessionId,\n };\n } catch {\n return fallback;\n }\n }\n\n const result = await preloadDecisions(\n {\n sections: options.sections,\n components: options.components ?? [],\n slots: options.slots ?? [],\n slotsFrom: options.slotsFrom,\n registrySlotIds: options.registrySlotIds,\n },\n sessionId,\n {\n apiKey: options.apiKey,\n baseUrl: options.baseUrl,\n origin: options.origin,\n userAgent: options.userAgent,\n referer: options.referer,\n utmParams: options.utmParams,\n clickIds: options.clickIds,\n doNotTrack: options.doNotTrack,\n timeoutMs: options.timeoutMs,\n persona: options.persona,\n },\n );\n\n return { ...result, sessionId };\n}\n","/**\n * Agent-readable content feed. Merges SDK-known data (winning variants, layout\n * order) with developer-supplied page content, and renders it either as a\n * server-rendered inline JSON-LD block (read by passive AI crawlers, which do\n * not run JS) or as Markdown (for agents that content-negotiate `text/markdown`).\n *\n * No React or DOM APIs — safe to import in server components, route handlers,\n * and middleware.\n */\n\nexport type AgentBlock = {\n /** Component ID. */\n id: string;\n /** Winning variant ID currently served. */\n variant: string;\n /** Agent-readable data attached to the served variant, if any. */\n content?: unknown;\n};\n\nexport type AgentFeed = {\n page: string;\n title?: string;\n summary?: string;\n layoutOrder?: string[];\n blocks: AgentBlock[];\n /** Developer-supplied extra fields (products, specs, arbitrary JSON). */\n [key: string]: unknown;\n};\n\n/** Fields the SDK owns — developer content can never overwrite these. */\nconst RESERVED_FIELDS = ['page', 'blocks', 'layoutOrder'] as const;\n\nconst registry = new Map<string, Record<string, unknown>>();\n\n/**\n * Register page-level structured content the SDK can't infer (title, summary,\n * product fields, arbitrary JSON), keyed by page path. Call at module load.\n */\nexport function defineAgentContent(page: string, content: Record<string, unknown>): void {\n registry.set(page, content);\n}\n\n/** Look up registered content for a page. */\nexport function getAgentContent(page: string): Record<string, unknown> | undefined {\n return registry.get(page);\n}\n\n/** Clear the registry — intended for tests. */\nexport function clearAgentContent(): void {\n registry.clear();\n}\n\n/**\n * Merge SDK-known data with developer-supplied content into a single feed.\n * Developer content fills in title/summary/etc. but can never overwrite the\n * SDK-authoritative fields (`page`, `blocks`, `layoutOrder`).\n */\nexport function buildAgentFeed(input: {\n page: string;\n blocks: AgentBlock[];\n layoutOrder?: string[];\n content?: Record<string, unknown>;\n}): AgentFeed {\n const supplied = input.content ?? getAgentContent(input.page) ?? {};\n const safe: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(supplied)) {\n if (!(RESERVED_FIELDS as readonly string[]).includes(k)) safe[k] = v;\n }\n const feed: AgentFeed = {\n ...safe,\n page: input.page,\n blocks: input.blocks,\n };\n if (input.layoutOrder) feed.layoutOrder = input.layoutOrder;\n return feed;\n}\n\n/**\n * Render the feed as a server-rendered inline JSON-LD `<script>` string. `<` is\n * escaped to `<` so embedded content cannot break out of the script\n * element. MUST be emitted on the server — passive crawlers never run client JS.\n */\nexport function renderAgentJsonLd(feed: AgentFeed): string {\n return `<script type=\"application/ld+json\">${renderAgentJsonLdBody(feed)}</script>`;\n}\n\n/**\n * The escaped JSON-LD body only (no `<script>` wrapper). For React server\n * components, inject via `<script type=\"application/ld+json\"\n * dangerouslySetInnerHTML={{ __html: renderAgentJsonLdBody(feed) }} />`.\n */\nexport function renderAgentJsonLdBody(feed: AgentFeed): string {\n return JSON.stringify({ '@context': 'https://schema.org', '@type': 'WebPage', ...feed })\n .replace(/</g, '\\\\u003c');\n}\n\n/** Render the feed as Markdown for agents that negotiate `text/markdown`. */\nexport function renderAgentMarkdown(feed: AgentFeed): string {\n const lines: string[] = [];\n if (feed.title) lines.push(`# ${feed.title}`, '');\n if (feed.summary) lines.push(String(feed.summary), '');\n\n for (const [k, v] of Object.entries(feed)) {\n if (['page', 'title', 'summary', 'blocks', 'layoutOrder'].includes(k)) continue;\n lines.push(`## ${k}`, '', '```json', JSON.stringify(v, null, 2), '```', '');\n }\n\n if (feed.blocks.length > 0) {\n lines.push('## blocks', '');\n for (const b of feed.blocks) {\n lines.push(`- **${b.id}** → variant \\`${b.variant}\\``);\n if (b.content !== undefined) {\n lines.push('', ' ```json', JSON.stringify(b.content, null, 2), ' ```');\n }\n }\n lines.push('');\n }\n\n return lines.join('\\n').trimEnd() + '\\n';\n}\n","// Fire-and-forget server-side log of a known AI-agent fetch to crawler_requests\n// (via POST /v1/crawler-events). Machine telemetry — no cookie, no session.\n// MUST NOT throw or be awaited into the render path.\nexport type AgentFetchLog = {\n baseUrl: string; // API base ending in /v1\n apiKey: string; // public pk_ key\n path: string;\n botName: string;\n userAgent?: string;\n};\n\nexport function logAgentFetch(entry: AgentFetchLog, deps: { fetchImpl?: typeof fetch } = {}): void {\n const doFetch = deps.fetchImpl ?? fetch;\n try {\n void doFetch(`${entry.baseUrl}/crawler-events`, {\n method: 'POST',\n headers: { 'content-type': 'application/json', authorization: `Bearer ${entry.apiKey}` },\n body: JSON.stringify({\n path: entry.path,\n botName: entry.botName,\n userAgent: entry.userAgent ?? null,\n source: 'ssr',\n }),\n }).catch(() => {});\n } catch {\n /* never break render */\n }\n}\n","/**\n * `createAgentFeed` — a framework-standard Route Handler (Web `Request` →\n * `Response`) that serves the agent-readable feed via HTTP content negotiation:\n * `text/markdown` (Accept header or `.md` URL) → Markdown, otherwise JSON.\n *\n * This is the secondary channel of the agent-readable design — for agents that\n * *ask* (coding agents, agents the customer controls, future crawlers). The\n * primary channel is the server-rendered inline JSON-LD from `<AdaptiveRoot>`.\n *\n * Every fetch is reported to `onRead` (best-effort) so it can be logged to\n * `crawler_requests` and counted in the dashboard traffic breakdown.\n */\nimport { matchedAgentToken } from '@sentientui/core';\nimport { renderAgentMarkdown, type AgentFeed } from '../agent-feed.js';\n\nexport type AgentFeedReadEntry = {\n path: string;\n userAgent: string | null;\n botName: string | null;\n};\n\nexport type AgentFeedRouteConfig = {\n /** Resolve the feed for a request (winning variants + layout + dev content). */\n getFeed: (request: Request) => Promise<AgentFeed> | AgentFeed;\n /** Best-effort per-fetch hook — log to `crawler_requests` here. Never awaited into the response. */\n onRead?: (entry: AgentFeedReadEntry) => void | Promise<void>;\n};\n\nfunction wantsMarkdown(url: URL, accept: string): boolean {\n return url.pathname.endsWith('.md') || accept.toLowerCase().includes('text/markdown');\n}\n\nexport function createAgentFeed(\n config: AgentFeedRouteConfig,\n): (request: Request) => Promise<Response> {\n return async (request: Request): Promise<Response> => {\n const url = new URL(request.url);\n const accept = request.headers.get('accept') ?? '';\n const userAgent = request.headers.get('user-agent');\n // Strip the .md/.json suffix so the feed path matches the page path.\n const path = url.pathname.replace(/\\.(md|json)$/, '');\n\n if (config.onRead) {\n try {\n void Promise.resolve(\n config.onRead({ path, userAgent, botName: matchedAgentToken(userAgent ?? '') }),\n ).catch(() => {});\n } catch {\n /* logging must never break the response */\n }\n }\n\n const feed = await config.getFeed(request);\n\n if (wantsMarkdown(url, accept)) {\n return new Response(renderAgentMarkdown(feed), {\n headers: { 'content-type': 'text/markdown; charset=utf-8' },\n });\n }\n return new Response(JSON.stringify(feed), {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,CAEJ","names":["deriveSessionSegment","extractTrackedParams","matchedAgentToken","cookies","headers","renderPrePaintScript","confidenceBand","jsx","inlineJsString","value","personaScriptBody","props","SentientPersonaScript","preloadAssignments","readSessionCookie","preloadDecisions","defaultSessionId","loadAdaptiveAssignments","components","options","_a","_b","_c","sessionId","readSessionCookie","preloadAssignments","loadAdaptiveDecision","_d","_e","_f","_g","_h","_i","_j","preloadDecisions","fallback","mod","outcome","e","result","__spreadProps","__spreadValues","AdaptiveRootClient","RESERVED_FIELDS","registry","defineAgentContent","page","content","getAgentContent","buildAgentFeed","input","_a","_b","supplied","getAgentContent","safe","k","v","RESERVED_FIELDS","feed","__spreadProps","__spreadValues","renderAgentJsonLdBody","feed","__spreadValues","renderAgentMarkdown","lines","k","v","b","logAgentFetch","entry","deps","_a","_b","doFetch","e","matchedAgentToken","wantsMarkdown","url","accept","createAgentFeed","config","request","_a","userAgent","path","matchedAgentToken","e","feed","renderAgentMarkdown","matchedAgentToken","uaTokenMatch","agentIntent","classifiedAgents","Fragment","jsx","jsxs","DEFAULT_API_BASE_URL","assignmentsToBlocks","assignments","id","v","_a","AdaptiveRoot","props","_b","_c","_d","_e","_f","_g","_h","_i","components","sections","slots","registrySlotIds","appOrigin","searchParams","initialAssignmentsOverride","ssrSessionIdProp","timeoutMs","agentFeed","captureAgents","nonce","children","providerProps","__objRest","headerStore","headers","host","resolvedOrigin","userAgent","referer","utmParams","clickIds","extractTrackedParams","doNotTrack","sessionSegment","deriveSessionSegment","cookieStore","cookies","cf","consent","skipSsr","baseUrl","agentPath","agentBot","matchedAgentToken","logAgentFetch","initialAssignments","initialLayoutOrder","initialSlots","initialSlotConfig","initialPalette","initialPersona","ssrSessionId","registry","decision","loadAdaptiveDecision","__spreadProps","__spreadValues","result","loadAdaptiveAssignments","personaScript","SentientPersonaScript","client","AdaptiveRootClient","feed","buildAgentFeed","renderAgentJsonLdBody"]}
1
+ {"version":3,"sources":["../../src/next/adaptive-root.tsx","../../src/persona-script.tsx","../../src/server.ts","../../src/agent-feed.ts","../../src/next/log-agent-fetch.ts","../../src/next/agent-feed-route.ts"],"sourcesContent":["import { deriveSessionSegment, extractTrackedParams, matchedAgentToken } from '@sentientui/core';\nimport type { SlotDeclInput, SlotResult } from '@sentientui/core';\nimport { cookies, headers } from 'next/headers';\n// `type JSX` from react, not the global namespace removed in @types/react@19\n// (peers allow react >=18) — see adaptive-text.tsx.\nimport type { JSX, ReactNode } from 'react';\nimport type { AdaptiveProviderProps } from '../provider.js';\nimport { SentientPersonaScript } from '../persona-script.js';\nimport {\n loadAdaptiveAssignments,\n loadAdaptiveDecision,\n type LoadAdaptiveDecisionResult,\n type ServerAssignments,\n} from '../server.js';\nimport { AdaptiveRootClient } from './adaptive-root-client.js';\nimport { buildAgentFeed, renderAgentJsonLdBody, type AgentBlock } from '../agent-feed.js';\nimport { logAgentFetch } from './log-agent-fetch.js';\n\nexport { createAgentFeed } from './agent-feed-route.js';\nexport type { AgentFeedRouteConfig, AgentFeedReadEntry } from './agent-feed-route.js';\nexport { defineAgentContent, buildAgentFeed as buildAgentFeedFor } from '../agent-feed.js';\n// Re-exported from core on the SERVER entry (this module is server-only — it\n// imports next/headers). Lets server components do agent detection with just the\n// `@sentientui/react` package, no direct core dependency. Do NOT add this to the\n// package's client index: re-exporting a plain function through a 'use client'\n// module turns it into a client reference that throws when called during SSR.\nexport { matchedAgentToken, uaTokenMatch, agentIntent, classifiedAgents } from '@sentientui/core';\nexport type { AgentIntent } from '@sentientui/core';\nexport type { AgentFeed } from '../agent-feed.js';\n\nconst DEFAULT_API_BASE_URL = 'https://api.sentient-ui.com/v1';\n\nexport type PreloadComponent = { id: string; variantIds: string[] };\n\nexport type AdaptiveRootProps = Omit<\n AdaptiveProviderProps,\n // Every provider prop AdaptiveRoot itself resolves and passes AFTER the\n // {...providerProps} spread must be omitted here: a caller-supplied value\n // would typecheck but be silently clobbered by the spread order\n // (initialLayoutOrder, declaredSections and sessionSegment were missing\n // from this list and suffered exactly that).\n | 'initialAssignments'\n | 'onAssignment'\n | 'initialSlots'\n | 'initialSlotConfig'\n | 'initialPalette'\n | 'initialVocabulary'\n | 'initialPersona'\n | 'initialLayoutOrder'\n | 'declaredSections'\n | 'sessionSegment'\n | 'consentFrom'\n> & {\n /**\n * Cookie-based consent source — see `AdaptiveProviderProps.consentFrom`.\n *\n * Narrowed to the cookie form: AdaptiveRoot is a Server Component and spreads\n * this straight into its client boundary, and a function prop crossing the\n * server→client boundary throws at render (\"Functions cannot be passed\n * directly to Client Components\"). The provider's type accepted `check`, so\n * a Cookiebot-style predicate typechecked here and then crashed the layout.\n * Need a JS-API CMP predicate? Use `<AdaptiveProvider>` in a client component.\n */\n consentFrom?: Omit<NonNullable<AdaptiveProviderProps['consentFrom']>, 'check'>;\n /**\n * Code-variant components to assign server-side (SEO-safe). Optional — an\n * `<Adaptive>` works without an entry here and assigns after mount.\n *\n * List only ids this tree actually renders. Each one is assigned on every\n * request, rendered or not, and every assignment logs an impression (or a\n * holdout exposure). An id the page never renders therefore accrues trials\n * that cannot convert, and in a root layout that happens on every route.\n */\n components?: PreloadComponent[];\n /**\n * Declare page section IDs in their default order. When provided,\n * AdaptiveRoot calls `/v1/decide` (single round trip) instead of\n * individual `/v1/assign` calls, and `useLayoutOrder()` returns the\n * persona-specific order on first render.\n *\n * Give each section's rendered element `data-sentient-id=\"<sectionId>\"` —\n * the only markup a section needs — so the DOM graph scanner can register\n * it under the same id. Without it the server never learns what the section\n * IS, types it `generic`, and serves the identity order to every persona —\n * the integration looks live but cannot personalize. The provider warns\n * about unresolvable ids in development. Correct a section the content\n * classifier mistypes with `sectionTypes`, not extra markup.\n *\n * @example sections={['hero', 'pricing', 'features', 'social_proof']}\n * // …and in the tree: <section data-sentient-id=\"pricing\">\n */\n sections?: string[];\n /**\n * Adaptive-slot declarations used by `useAdaptiveTokens` / `AdaptiveGroup`\n * in this tree. Declaring them here decides them in the same SSR\n * round trip, so their values serialize into the server HTML.\n */\n slots?: SlotDeclInput[];\n /**\n * The generated-mode `<Adaptive id>`s THIS page renders. Declaring them\n * decides their published versions in the same SSR round trip\n * (`/v1/decide` registry mode) and serializes the served content into the\n * server HTML, so the first paint shows the version rather than the\n * original children until the client-side decide answers. Without it a\n * registry slot renders its children first and swaps after mount.\n *\n * Scoped to exactly these ids on purpose: an unscoped registry decide\n * records a close-out trial for every published slot on every page.\n *\n * @example registrySlotIds={['hero-headline', 'pricing-cta']}\n */\n registrySlotIds?: string[];\n /** App origin — must be in the project's `allowed_origins`. */\n appOrigin?: string;\n /**\n * The page's `searchParams` prop (or an equivalent query string /\n * URLSearchParams). Server Components cannot read the request URL from\n * `headers()`, so without this the SSR-minted session carries no `utm_*`\n * params and no ad click IDs (gclid, fbclid, ttclid, …) — campaign\n * attribution only lands after client hydration, and never for visits the\n * client SDK doesn't get to finish (bounce before hydrate). Pass it on\n * landing pages that receive ad traffic:\n *\n * ```tsx\n * export default async function Page({ searchParams }: { searchParams: Promise<Record<string, string | string[] | undefined>> }) {\n * return <AdaptiveRoot ... searchParams={await searchParams}>...</AdaptiveRoot>;\n * }\n * ```\n */\n searchParams?: Record<string, string | string[] | undefined> | URLSearchParams | string;\n /** Override: when set no network fetch is made. Useful for tests. */\n initialAssignments?: ServerAssignments;\n /**\n * Milliseconds to wait for the API before rendering default variants.\n * Defaults to 1000. The hot path typically returns in well under 150 ms;\n * the full 1 s budget is only reached on a cold start or an API\n * geographically distant from your SSR host. Lower it if your API is\n * co-located and warm.\n */\n timeoutMs?: number;\n /**\n * When set, AdaptiveRoot emits a server-rendered inline JSON-LD block\n * describing the page's winning variants, layout order, and developer-supplied\n * content — readable by passive AI crawlers (which do not run JS). Invisible to\n * humans (a JSON-LD script renders no visible DOM). Omit to emit nothing.\n */\n agentFeed?: {\n /** Page path for the feed. Falls back to the `x-pathname` request header, then '/'. */\n path?: string;\n /** Structured page content. Falls back to the `defineAgentContent` registry for this path. */\n content?: Record<string, unknown>;\n };\n /**\n * When true (default), a known AI-agent fetch (matched by user-agent —\n * GPTBot, ChatGPT-User, Claude-User, PerplexityBot, …) is logged server-side\n * to your agent analytics. Machine telemetry only (no cookie, no session);\n * fire-and-forget, never affects render. Set false to opt out.\n */\n captureAgents?: boolean;\n /**\n * CSP nonce for the inline persona (and optional agent JSON-LD) scripts.\n * Pass through from Next.js middleware / `headers()` when using a strict CSP.\n */\n nonce?: string;\n children: ReactNode;\n};\n\n/** Build agent blocks from SSR assignments (Record<id, variantId | { variantId }>). */\nfunction assignmentsToBlocks(assignments: ServerAssignments): AgentBlock[] {\n return Object.entries(assignments as Record<string, unknown>).map(([id, v]) => ({\n id,\n variant: typeof v === 'string' ? v : ((v as { variantId?: string })?.variantId ?? ''),\n }));\n}\n\n/**\n * Next.js Server Component that resolves variant assignments (and optionally\n * section layout order) server-side for zero layout shift on first paint.\n *\n * When `sections` is provided, a single `POST /v1/decide` call returns both\n * the persona-specific section order and all component assignments.\n * Without `sections`, individual `/v1/assign` calls are made per component.\n *\n * @example\n * // app/page.tsx — with section layout. Declared on the page (not the root\n * // layout) because hero_cta renders only here; see the `components` prop.\n * import { AdaptiveRoot } from '@sentientui/react/next';\n *\n * export default async function Page() {\n * return (\n * <AdaptiveRoot\n * apiKey={process.env.NEXT_PUBLIC_SENTIENT_API_KEY!}\n * sections={['hero', 'pricing', 'features', 'social_proof']}\n * components={[\n * { id: 'hero_cta', variantIds: ['default', 'accent'] },\n * ]}\n * >\n * <HeroSection />\n * <PricingSection />\n * <FeaturesSection />\n * <SocialProofSection />\n * </AdaptiveRoot>\n * );\n * }\n */\nexport async function AdaptiveRoot(props: AdaptiveRootProps): Promise<JSX.Element> {\n const {\n components = [],\n sections,\n slots,\n registrySlotIds,\n appOrigin,\n searchParams,\n initialAssignments: initialAssignmentsOverride,\n ssrSessionId: ssrSessionIdProp,\n timeoutMs,\n agentFeed,\n captureAgents,\n nonce,\n children,\n ...providerProps\n } = props;\n\n const headerStore = await headers();\n const host = headerStore.get('host');\n if (!appOrigin && process.env.NODE_ENV === 'production' && !host) {\n console.error(\n '[SentientUI] AdaptiveRoot: Host header is absent and no appOrigin was provided. ' +\n 'Pass appOrigin explicitly — the https://localhost fallback will likely fail allowed_origins validation.',\n );\n }\n const resolvedOrigin = appOrigin ??\n (process.env.NODE_ENV === 'production'\n ? `https://${host ?? 'localhost'}`\n : 'http://localhost:3001');\n const userAgent = headerStore.get('user-agent') ?? undefined;\n const referer = headerStore.get('referer') ?? undefined;\n // Landing-URL attribution (utm_* + ad click IDs). Only available when the\n // page passes its searchParams down — headers() never carries the request's\n // own query string, and the Referer is the PREVIOUS page, not this one.\n const { utmParams, clickIds } = extractTrackedParams(searchParams ?? {});\n // Honor a tracking opt-out at SSR: `DNT: 1` or the legally-enforceable\n // `Sec-GPC: 1`. When set we skip the session upsert + assign/decide so no\n // session row is minted for the visitor (audit P4) — matching the client SDK,\n // which already no-ops for these signals.\n const doNotTrack = headerStore.get('dnt') === '1' || headerStore.get('sec-gpc') === '1';\n // `consent: false` must gate the SERVER too, not just the client. Without\n // this the SSR decide/assign still ran and still minted a session row for a\n // visitor who had not consented — contradicting the documented contract\n // (\"no SDK is initialised, no cookies are written, no events are sent\") and\n // forcing sites to hide AdaptiveRoot behind a conditional render, which is\n // what made consent-after-load cost a full server round trip.\n const sessionSegment = deriveSessionSegment({ userAgent, referer, appOrigin: resolvedOrigin });\n const cookieStore = await cookies();\n\n // This is a Server Component and already has the request cookies, so resolve\n // a cookie-based `consentFrom` here rather than making the app read the same\n // cookie again just to pass `consent` — naming it twice only invites drift.\n // An already-consented visitor therefore gets SSR variant assignment (zero\n // layout shift) with no extra code.\n //\n // An explicit `consent` prop always wins — it is the escape hatch for apps\n // that track consent elsewhere. (No `check()` form here: see the prop type.)\n //\n // Consent gates the SERVER too, not just the client: without it the SSR\n // decide/assign still ran and still minted a session row for a visitor who\n // had not consented, contradicting the documented contract (\"no SDK is\n // initialised, no cookies are written, no events are sent\").\n const cf = providerProps.consentFrom;\n const consent =\n providerProps.consent ??\n (cf?.cookie\n ? cookieStore.get(cf.cookie)?.value === (cf.value ?? 'accepted')\n : undefined);\n const skipSsr = doNotTrack || consent === false || (cf != null && consent !== true);\n\n // SSR preload MUST hit the same API host the client will use, otherwise the\n // SSR-minted session lives on the wrong host and the client's first /assign\n // misses it and re-mints — silently breaking SSR→client continuity for any\n // non-default / self-hosted deployment. The client derives its base from\n // apiBaseUrl too (see provider.tsx), so thread the same value here.\n const baseUrl = providerProps.apiBaseUrl\n ? providerProps.apiBaseUrl.replace(/\\/$/, '')\n : DEFAULT_API_BASE_URL;\n\n // Server-side agent-fetch capture (spec: nextjs-agent-fetch-capture). JS-less\n // assistants (GPTBot / ChatGPT-User / Claude-User / PerplexityBot / …) never\n // run client JS, but they trigger SSR — so AdaptiveRoot sees their UA here.\n // Fire-and-forget; never blocks or breaks render. `agentPath` is reused by the\n // agentFeed JSON-LD below.\n const agentPath = agentFeed?.path ?? headerStore.get('x-pathname') ?? '/';\n const agentBot = matchedAgentToken(userAgent ?? '');\n if (captureAgents !== false && agentBot) {\n logAgentFetch({ baseUrl, apiKey: providerProps.apiKey, path: agentPath, botName: agentBot, userAgent });\n }\n\n let initialAssignments: ServerAssignments;\n let initialLayoutOrder: string[] | null = null;\n let initialSlots: Record<string, SlotResult> | undefined;\n let initialSlotConfig: LoadAdaptiveDecisionResult['slotConfig'];\n let initialPalette: LoadAdaptiveDecisionResult['palette'];\n let initialVocabulary: LoadAdaptiveDecisionResult['vocabulary'];\n let initialPersona: { persona: string; confidence: number } | null = null;\n let ssrSessionId: string | undefined;\n\n // Registry mode only when ids were declared: an unscoped registry decide\n // records a close-out trial for every published slot on every page.\n const registry = !!registrySlotIds?.length;\n\n if (initialAssignmentsOverride) {\n initialAssignments = initialAssignmentsOverride;\n ssrSessionId = ssrSessionIdProp;\n } else if (skipSsr) {\n // Nothing server-side: no decide, no assign, no session. Components fall\n // back to `ssrFallback`, and the client starts only if the visitor later\n // consents — via the `consent` prop or grantConsent(), neither of which\n // needs a page reload.\n initialAssignments = {};\n } else if ((sections && sections.length > 0) || (slots && slots.length > 0) || registry) {\n // `loadAdaptiveDecision` accepted `registrySlotIds` long before AdaptiveRoot\n // passed them, so an `<Adaptive id>` under AdaptiveRoot showed its original\n // children on first paint until the client-side decide returned.\n const decision = await loadAdaptiveDecision({\n sections: sections ?? [],\n components,\n slots,\n ...(registry ? { slotsFrom: 'registry' as const, registrySlotIds } : {}),\n cookies: cookieStore,\n apiKey: providerProps.apiKey,\n baseUrl,\n origin: resolvedOrigin,\n userAgent,\n referer,\n utmParams,\n clickIds,\n // doNotTrack is deliberately not passed: it is necessarily false on this\n // branch — a DNT/GPC or consent-gated request already took the skipSsr\n // arm above and never reaches this loader.\n timeoutMs,\n persona: providerProps.persona,\n });\n initialAssignments = decision.assignments;\n initialLayoutOrder = decision.layoutOrder;\n initialSlots = decision.slots;\n initialSlotConfig = decision.slotConfig;\n initialPalette = decision.palette;\n // The site styles the served Redesign trees borrow. Without forwarding\n // them, SSR sites (Bodyshop, 2026-09-24) rendered an approved redesign\n // with no site classes at all — black palette buttons and near-invisible\n // text on a navy card — because the client never re-decides a preloaded\n // slot and so never receives them either.\n initialVocabulary = decision.vocabulary;\n initialPersona =\n decision.persona !== undefined\n ? { persona: decision.persona, confidence: decision.confidence ?? 0 }\n : null;\n ssrSessionId = decision.sessionId;\n } else {\n const result = await loadAdaptiveAssignments(components, {\n cookies: cookieStore,\n apiKey: providerProps.apiKey,\n baseUrl,\n origin: resolvedOrigin,\n userAgent,\n referer,\n utmParams,\n clickIds,\n // doNotTrack is deliberately not passed: it is necessarily false on this\n // branch — a DNT/GPC or consent-gated request already took the skipSsr\n // arm above and never reaches this loader.\n timeoutMs,\n persona: providerProps.persona,\n });\n initialAssignments = result.assignments;\n ssrSessionId = result.sessionId;\n }\n\n // Single-writer inline script — ALWAYS the first child, before any markup\n // that CSS keyed on the persona attributes could style.\n const personaScript = (\n <SentientPersonaScript apiKey={providerProps.apiKey} persona={initialPersona} nonce={nonce} />\n );\n\n const client = (\n <AdaptiveRootClient\n {...providerProps}\n // Forward the server-resolved value so a consented visitor's client does\n // not start gated and re-resolve the same cookie on mount.\n consent={consent}\n initialAssignments={initialAssignments}\n initialLayoutOrder={initialLayoutOrder}\n // Declared regardless of what came back, so devtools can preview layout on\n // a page whose decision was gated or timed out.\n declaredSections={sections}\n initialSlots={initialSlots}\n // Registry-mode preload: the hook treats a preloaded slot config as\n // settled, so the client does not decide the same slot a second time.\n initialSlotConfig={initialSlotConfig}\n initialPalette={initialPalette}\n initialVocabulary={initialVocabulary}\n initialPersona={initialPersona ?? undefined}\n sessionSegment={sessionSegment}\n ssrSessionId={ssrSessionId}\n >\n {children}\n </AdaptiveRootClient>\n );\n\n if (!agentFeed) {\n return (\n <>\n {personaScript}\n {client}\n </>\n );\n }\n\n // Server-rendered inline JSON-LD for AI crawlers. Emitted only on the server\n // path so passive crawlers (no JS) see it in the raw HTML. The body escapes\n // '<' so page content cannot break out of the <script> element.\n const feed = buildAgentFeed({\n page: agentPath,\n blocks: assignmentsToBlocks(initialAssignments),\n layoutOrder: initialLayoutOrder ?? undefined,\n content: agentFeed.content,\n });\n\n return (\n <>\n {personaScript}\n <script\n type=\"application/ld+json\"\n nonce={nonce}\n dangerouslySetInnerHTML={{ __html: renderAgentJsonLdBody(feed) }}\n />\n {client}\n </>\n );\n}\n","// `type JSX` from react, not the global namespace removed in @types/react@19\n// (peers allow react >=18) — see adaptive-text.tsx.\nimport type { JSX } from 'react';\nimport { renderPrePaintScript } from '@sentientui/core';\nimport { confidenceBand } from '@sentientui/policy';\n\nexport type SentientPersonaScriptProps = {\n /** Publishable API key — selects the localStorage snapshot in the fallback path. */\n apiKey: string;\n /**\n * CSP nonce for the inline pre-paint script. Pass the same nonce your\n * `Content-Security-Policy` `script-src` allows (e.g. from Next.js middleware).\n * Required for strict CSP deployments that block `'unsafe-inline'`.\n */\n nonce?: string;\n /**\n * SSR-decided persona (from `loadAdaptiveDecision`). When present the\n * script embeds the literal values; when absent it reads the local\n * decision snapshot (SPA / return-visit path).\n */\n persona?: { persona: string; confidence: number } | null;\n};\n\n/** JSON string literal that is also safe inside an inline <script> element. */\nfunction inlineJsString(value: string): string {\n return JSON.stringify(value).replace(/</g, '\\\\u003c');\n}\n\n/** Exported for tests. Builds the inline JS (concatenation only — no backticks). */\nexport function personaScriptBody(props: SentientPersonaScriptProps): string {\n if (props.persona) {\n return (\n '(function(){try{var d=document.documentElement;' +\n 'if(d.hasAttribute(\"data-sentient-persona\"))return;' +\n 'd.setAttribute(\"data-sentient-persona\",' + inlineJsString(props.persona.persona) + ');' +\n 'd.setAttribute(\"data-sentient-confidence\",' + inlineJsString(confidenceBand(props.persona.confidence)) + ');' +\n '}catch(e){}})();'\n );\n }\n return renderPrePaintScript(props.apiKey);\n}\n\n/**\n * Single writer of the Rung-1a `<html>` attributes\n * (`data-sentient-persona`, `data-sentient-confidence`), executed pre-paint.\n *\n * `AdaptiveRoot` renders this automatically as its first child. For Pages\n * Router / Remix, render it yourself in `_document` / the root layout.\n *\n * IMPORTANT (install docs): add `suppressHydrationWarning` to your `<html>`\n * element — this script mutates documentElement before React hydrates it\n * (the same pattern next-themes uses). The client SDK adopts the attributes\n * as truth and never rewrites them mid-session.\n */\nexport function SentientPersonaScript(props: SentientPersonaScriptProps): JSX.Element {\n return (\n <script\n data-sentient-persona-script=\"\"\n nonce={props.nonce}\n dangerouslySetInnerHTML={{ __html: personaScriptBody(props) }}\n />\n );\n}\n","/**\n * Server-only helpers for Next.js / SSR. No React or DOM APIs.\n */\nimport {\n preloadAssignments,\n readSessionCookie,\n type ServerAssignConfig,\n type ServerAssignments,\n} from '@sentientui/core/server';\n\nexport { preloadAssignments, readSessionCookie };\nexport type { ServerAssignConfig, ServerAssignments };\n\n/** Return value of `loadAdaptiveAssignments` — includes the session ID used for SSR. */\nexport type LoadAdaptiveAssignmentsResult = {\n assignments: ServerAssignments;\n /** The session ID used for SSR assignment. Pass as `ssrSessionId` to `<AdaptiveProvider>`. */\n sessionId: string;\n};\n\nexport type LoadAdaptiveAssignmentsOptions = {\n /** Next.js `cookies()` return value, or any object with `get(name)`. */\n cookies: { get(name: string): { value: string } | undefined };\n apiKey: string;\n baseUrl: string;\n /** Used when `_snt_uid` is absent (e.g. first visit, many crawlers). */\n createSessionId?: () => string;\n /** Must match a value in the project's `allowed_origins` (e.g. `http://localhost:3001`). */\n origin?: string;\n /** From Next.js `headers().get('user-agent')` — aligns SSR segment with the client. */\n userAgent?: string;\n /** From Next.js `headers().get('referer')`. */\n referer?: string;\n /**\n * `utm_*` params from the landing URL. The Referer header never carries the\n * page's OWN query string, so without this the SSR-minted session has no\n * campaign attribution until the client SDK hydrates and re-upserts.\n * Derive with `extractTrackedParams(searchParams)` from `@sentientui/core/server`.\n */\n utmParams?: Record<string, string>;\n /** Ad-platform click IDs (gclid, fbclid, ttclid, …) from the landing URL — same derivation as `utmParams`. */\n clickIds?: Record<string, string>;\n /** Set true when the request carries `DNT: 1` or `Sec-GPC: 1` — skips the SSR session upsert + assignment so no session is minted for an opted-out visitor (audit P4). `AdaptiveRoot` sets this automatically from the request headers. */\n doNotTrack?: boolean;\n /** Milliseconds to wait for the API before returning default variants. Defaults to 1000 (typical decide is well under 150 ms; the full budget is only reached on a cold start or a distant API). */\n timeoutMs?: number;\n /**\n * Declared persona — the role your app already knows for this visitor (e.g.\n * from your auth context: 'admin', 'evaluator'). Must be a key in the\n * project's persona vocabulary; unrecognized values are ignored server-side.\n * Never a user id or email.\n */\n persona?: string;\n};\n\nfunction defaultSessionId(): string {\n if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {\n return crypto.randomUUID();\n }\n return `snt-${Date.now()}-${Math.random().toString(36).slice(2, 11)}`;\n}\n\n/**\n * Fetches bandit assignments on the server for SEO-safe HTML.\n * Pass `assignments` as `initialAssignments` and `sessionId` as `ssrSessionId`\n * on `<AdaptiveProvider>` so the client adopts the same session on first visit.\n */\nexport async function loadAdaptiveAssignments(\n components: Array<{ id: string; variantIds: string[] }>,\n options: LoadAdaptiveAssignmentsOptions,\n): Promise<LoadAdaptiveAssignmentsResult> {\n // apiKey is not optional here: the client writes the per-project suffixed\n // cookie, so an un-keyed read missed every returning visitor and minted a\n // fresh orphan session per SSR request (see readSessionCookie in core).\n const sessionId =\n readSessionCookie(options.cookies, options.apiKey) ??\n options.createSessionId?.() ??\n defaultSessionId();\n\n const assignments = await preloadAssignments(components, sessionId, {\n apiKey: options.apiKey,\n baseUrl: options.baseUrl,\n origin: options.origin,\n userAgent: options.userAgent,\n referer: options.referer,\n utmParams: options.utmParams,\n clickIds: options.clickIds,\n doNotTrack: options.doNotTrack,\n timeoutMs: options.timeoutMs,\n persona: options.persona,\n });\n\n return { assignments, sessionId };\n}\n\nexport { preloadDecisions } from '@sentientui/core/server';\nexport type { DecideResult, SlotDeclInput, SlotResult } from '@sentientui/core/server';\n\n/** Return value of `loadAdaptiveDecision` — includes the session ID used for SSR. */\nexport type LoadAdaptiveDecisionResult = import('@sentientui/core/server').DecideResult & {\n sessionId: string;\n};\n\nexport type LoadAdaptiveDecisionOptions = LoadAdaptiveAssignmentsOptions & {\n /**\n * Section IDs in default order. Passed to /v1/decide as the candidate\n * layout. Optional since 0.13.0 — slot-only pages may omit it (at least\n * one of `sections`/`components`/`slots` must be non-empty).\n */\n sections?: string[];\n /** Components to assign in the same decide call. */\n components?: Array<{ id: string; variantIds?: string[] }>;\n /** Adaptive-slot declarations (useAdaptiveTokens / AdaptiveGroup) to decide server-side. */\n slots?: import('@sentientui/core/server').SlotDeclInput[];\n /** 'registry' serves the project's published slot definitions (`<Adaptive id>`)\n * and is the only way `slotConfig`/`palette` come back. Default 'request'.\n * Requires `registrySlotIds`. */\n slotsFrom?: 'request' | 'registry';\n /**\n * Registry mode: the `<Adaptive id>`s THIS page renders — the decide is\n * scoped to exactly these. Required with `slotsFrom: 'registry'`; without it\n * the call downgrades to request mode (with a console.error) instead of\n * recording a close-out trial for every published slot on every page.\n */\n registrySlotIds?: string[];\n};\n\n/**\n * SSR helper for pages with a declared section layout and/or adaptive slots.\n * Calls `/v1/decide` instead of multiple `/v1/assign` round trips.\n * Pass `sessionId` as `ssrSessionId` on `<AdaptiveProvider>` so the client\n * adopts the same session on first visit.\n *\n * Keyless: with no valid `pk_` key this never fetches (no timeout burn).\n * Under the `development` export condition the decision is computed by the\n * deterministic local engine with the same sessionId the client will adopt —\n * server and client agree by construction. In production the engine resolves\n * to a stub and defaults are returned with one console.error.\n */\nexport async function loadAdaptiveDecision(\n options: LoadAdaptiveDecisionOptions,\n): Promise<LoadAdaptiveDecisionResult> {\n const { preloadDecisions, readSessionCookie } = await import('@sentientui/core/server');\n\n // Keyed read — the client's cookie name is suffixed per project (see\n // loadAdaptiveAssignments above). Works for keyless too: with no pk_ key the\n // client writes the bare legacy name, which the un-suffixed read falls back to.\n const sessionId =\n readSessionCookie(options.cookies, options.apiKey) ??\n options.createSessionId?.() ??\n defaultSessionId();\n\n const keyValid = typeof options.apiKey === 'string' && options.apiKey.startsWith('pk_');\n if (!keyValid) {\n const fallback: LoadAdaptiveDecisionResult = {\n layoutOrder: options.sections ?? [],\n assignments: {},\n slots: {},\n persona: 'unknown',\n confidence: 0,\n sessionId,\n };\n try {\n const mod = (await import('@sentientui/core/local')) as unknown as {\n LOCAL_ENGINE_AVAILABLE: boolean;\n createLocalEngine(opts: { sessionId: string }): {\n decide(input: {\n sections?: string[];\n components?: Array<{ id: string; variantIds?: string[] }>;\n slots?: LoadAdaptiveDecisionOptions['slots'];\n }): {\n layoutOrder: string[] | null;\n assignments: Record<string, string>;\n slots: Record<string, string | Record<string, string>>;\n persona: string;\n confidence: number;\n };\n };\n };\n if (!mod.LOCAL_ENGINE_AVAILABLE) {\n // Pinned message — must byte-match PROD_KEYLESS_ERROR in @sentientui/core.\n console.error(\n '[sentient] No API key configured — nothing is being learned. Set NEXT_PUBLIC_SENTIENT_API_KEY or pass localMode: true for local development.',\n );\n return fallback;\n }\n const outcome = mod.createLocalEngine({ sessionId }).decide({\n sections: options.sections,\n components: options.components ?? [],\n slots: options.slots ?? [],\n });\n return {\n layoutOrder: outcome.layoutOrder ?? options.sections ?? [],\n assignments: outcome.assignments,\n slots: outcome.slots,\n persona: outcome.persona,\n confidence: outcome.confidence,\n sessionId,\n };\n } catch {\n return fallback;\n }\n }\n\n const result = await preloadDecisions(\n {\n sections: options.sections,\n components: options.components ?? [],\n slots: options.slots ?? [],\n slotsFrom: options.slotsFrom,\n registrySlotIds: options.registrySlotIds,\n },\n sessionId,\n {\n apiKey: options.apiKey,\n baseUrl: options.baseUrl,\n origin: options.origin,\n userAgent: options.userAgent,\n referer: options.referer,\n utmParams: options.utmParams,\n clickIds: options.clickIds,\n doNotTrack: options.doNotTrack,\n timeoutMs: options.timeoutMs,\n persona: options.persona,\n },\n );\n\n return { ...result, sessionId };\n}\n","/**\n * Agent-readable content feed. Merges SDK-known data (winning variants, layout\n * order) with developer-supplied page content, and renders it either as a\n * server-rendered inline JSON-LD block (read by passive AI crawlers, which do\n * not run JS) or as Markdown (for agents that content-negotiate `text/markdown`).\n *\n * No React or DOM APIs — safe to import in server components, route handlers,\n * and middleware.\n */\n\nexport type AgentBlock = {\n /** Component ID. */\n id: string;\n /** Winning variant ID currently served. */\n variant: string;\n /** Agent-readable data attached to the served variant, if any. */\n content?: unknown;\n};\n\nexport type AgentFeed = {\n page: string;\n title?: string;\n summary?: string;\n layoutOrder?: string[];\n blocks: AgentBlock[];\n /** Developer-supplied extra fields (products, specs, arbitrary JSON). */\n [key: string]: unknown;\n};\n\n/** Fields the SDK owns — developer content can never overwrite these. */\nconst RESERVED_FIELDS = ['page', 'blocks', 'layoutOrder'] as const;\n\nconst registry = new Map<string, Record<string, unknown>>();\n\n/**\n * Register page-level structured content the SDK can't infer (title, summary,\n * product fields, arbitrary JSON), keyed by page path. Call at module load.\n */\nexport function defineAgentContent(page: string, content: Record<string, unknown>): void {\n registry.set(page, content);\n}\n\n/** Look up registered content for a page. */\nexport function getAgentContent(page: string): Record<string, unknown> | undefined {\n return registry.get(page);\n}\n\n/** Clear the registry — intended for tests. */\nexport function clearAgentContent(): void {\n registry.clear();\n}\n\n/**\n * Merge SDK-known data with developer-supplied content into a single feed.\n * Developer content fills in title/summary/etc. but can never overwrite the\n * SDK-authoritative fields (`page`, `blocks`, `layoutOrder`).\n */\nexport function buildAgentFeed(input: {\n page: string;\n blocks: AgentBlock[];\n layoutOrder?: string[];\n content?: Record<string, unknown>;\n}): AgentFeed {\n const supplied = input.content ?? getAgentContent(input.page) ?? {};\n const safe: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(supplied)) {\n if (!(RESERVED_FIELDS as readonly string[]).includes(k)) safe[k] = v;\n }\n const feed: AgentFeed = {\n ...safe,\n page: input.page,\n blocks: input.blocks,\n };\n if (input.layoutOrder) feed.layoutOrder = input.layoutOrder;\n return feed;\n}\n\n/**\n * Render the feed as a server-rendered inline JSON-LD `<script>` string. `<` is\n * escaped to `<` so embedded content cannot break out of the script\n * element. MUST be emitted on the server — passive crawlers never run client JS.\n */\nexport function renderAgentJsonLd(feed: AgentFeed): string {\n return `<script type=\"application/ld+json\">${renderAgentJsonLdBody(feed)}</script>`;\n}\n\n/**\n * The escaped JSON-LD body only (no `<script>` wrapper). For React server\n * components, inject via `<script type=\"application/ld+json\"\n * dangerouslySetInnerHTML={{ __html: renderAgentJsonLdBody(feed) }} />`.\n */\nexport function renderAgentJsonLdBody(feed: AgentFeed): string {\n return JSON.stringify({ '@context': 'https://schema.org', '@type': 'WebPage', ...feed })\n .replace(/</g, '\\\\u003c');\n}\n\n/** Render the feed as Markdown for agents that negotiate `text/markdown`. */\nexport function renderAgentMarkdown(feed: AgentFeed): string {\n const lines: string[] = [];\n if (feed.title) lines.push(`# ${feed.title}`, '');\n if (feed.summary) lines.push(String(feed.summary), '');\n\n for (const [k, v] of Object.entries(feed)) {\n if (['page', 'title', 'summary', 'blocks', 'layoutOrder'].includes(k)) continue;\n lines.push(`## ${k}`, '', '```json', JSON.stringify(v, null, 2), '```', '');\n }\n\n if (feed.blocks.length > 0) {\n lines.push('## blocks', '');\n for (const b of feed.blocks) {\n lines.push(`- **${b.id}** → variant \\`${b.variant}\\``);\n if (b.content !== undefined) {\n lines.push('', ' ```json', JSON.stringify(b.content, null, 2), ' ```');\n }\n }\n lines.push('');\n }\n\n return lines.join('\\n').trimEnd() + '\\n';\n}\n","// Fire-and-forget server-side log of a known AI-agent fetch to crawler_requests\n// (via POST /v1/crawler-events). Machine telemetry — no cookie, no session.\n// MUST NOT throw or be awaited into the render path.\nexport type AgentFetchLog = {\n baseUrl: string; // API base ending in /v1\n apiKey: string; // public pk_ key\n path: string;\n botName: string;\n userAgent?: string;\n};\n\nexport function logAgentFetch(entry: AgentFetchLog, deps: { fetchImpl?: typeof fetch } = {}): void {\n const doFetch = deps.fetchImpl ?? fetch;\n try {\n void doFetch(`${entry.baseUrl}/crawler-events`, {\n method: 'POST',\n headers: { 'content-type': 'application/json', authorization: `Bearer ${entry.apiKey}` },\n body: JSON.stringify({\n path: entry.path,\n botName: entry.botName,\n userAgent: entry.userAgent ?? null,\n source: 'ssr',\n }),\n }).catch(() => {});\n } catch {\n /* never break render */\n }\n}\n","/**\n * `createAgentFeed` — a framework-standard Route Handler (Web `Request` →\n * `Response`) that serves the agent-readable feed via HTTP content negotiation:\n * `text/markdown` (Accept header or `.md` URL) → Markdown, otherwise JSON.\n *\n * This is the secondary channel of the agent-readable design — for agents that\n * *ask* (coding agents, agents the customer controls, future crawlers). The\n * primary channel is the server-rendered inline JSON-LD from `<AdaptiveRoot>`.\n *\n * Every fetch is reported to `onRead` (best-effort) so it can be logged to\n * `crawler_requests` and counted in the dashboard traffic breakdown.\n */\nimport { matchedAgentToken } from '@sentientui/core';\nimport { renderAgentMarkdown, type AgentFeed } from '../agent-feed.js';\n\nexport type AgentFeedReadEntry = {\n path: string;\n userAgent: string | null;\n botName: string | null;\n};\n\nexport type AgentFeedRouteConfig = {\n /** Resolve the feed for a request (winning variants + layout + dev content). */\n getFeed: (request: Request) => Promise<AgentFeed> | AgentFeed;\n /** Best-effort per-fetch hook — log to `crawler_requests` here. Never awaited into the response. */\n onRead?: (entry: AgentFeedReadEntry) => void | Promise<void>;\n};\n\nfunction wantsMarkdown(url: URL, accept: string): boolean {\n return url.pathname.endsWith('.md') || accept.toLowerCase().includes('text/markdown');\n}\n\nexport function createAgentFeed(\n config: AgentFeedRouteConfig,\n): (request: Request) => Promise<Response> {\n return async (request: Request): Promise<Response> => {\n const url = new URL(request.url);\n const accept = request.headers.get('accept') ?? '';\n const userAgent = request.headers.get('user-agent');\n // Strip the .md/.json suffix so the feed path matches the page path.\n const path = url.pathname.replace(/\\.(md|json)$/, '');\n\n if (config.onRead) {\n try {\n void Promise.resolve(\n config.onRead({ path, userAgent, botName: matchedAgentToken(userAgent ?? '') }),\n ).catch(() => {});\n } catch {\n /* logging must never break the response */\n }\n }\n\n const feed = await config.getFeed(request);\n\n if (wantsMarkdown(url, accept)) {\n return new Response(renderAgentMarkdown(feed), {\n headers: { 'content-type': 'text/markdown; charset=utf-8' },\n });\n }\n return new Response(JSON.stringify(feed), {\n headers: { 'content-type': 'application/json; charset=utf-8' },\n });\n };\n}\n"],"mappings":"+lBAAA,OAAS,wBAAAA,GAAsB,wBAAAC,GAAsB,qBAAAC,OAAyB,mBAE9E,OAAS,WAAAC,GAAS,WAAAC,OAAe,eCCjC,OAAS,wBAAAC,OAA4B,mBACrC,OAAS,kBAAAC,OAAsB,qBAoD3B,cAAAC,OAAA,oBAhCJ,SAASC,GAAeC,EAAuB,CAC7C,OAAO,KAAK,UAAUA,CAAK,EAAE,QAAQ,KAAM,SAAS,CACtD,CAGO,SAASC,GAAkBC,EAA2C,CAC3E,OAAIA,EAAM,QAEN,2IAE4CH,GAAeG,EAAM,QAAQ,OAAO,EAAI,+CACrCH,GAAeF,GAAeK,EAAM,QAAQ,UAAU,CAAC,EAAI,qBAIvGN,GAAqBM,EAAM,MAAM,CAC1C,CAcO,SAASC,GAAsBD,EAAgD,CACpF,OACEJ,GAAC,UACC,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ACxB,CAIA,IAAME,EACJtE,EAACuE,GAAA,CAAsB,OAAQxC,EAAc,OAAQ,QAAS8B,EAAgB,MAAOhC,EAAO,EAGxF2C,EACJxE,EAACyE,GAAAP,EAAAC,EAAA,GACKpC,GADL,CAIC,QAASiB,EACT,mBAAoBO,EACpB,mBAAoBC,EAGpB,iBAAkBrC,EAClB,aAAcsC,EAGd,kBAAmBC,EACnB,eAAgBC,EAChB,kBAAmBC,EACnB,eAAgBC,GAAA,KAAAA,EAAkB,OAClC,eAAgBlB,GAChB,aAAcmB,EAEb,SAAAhC,GACH,EAGF,GAAI,CAACH,EACH,OACE1B,GAAAF,GAAA,CACG,UAAAuE,EACAE,GACH,EAOJ,IAAME,GAAOC,EAAe,CAC1B,KAAMxB,EACN,OAAQhD,GAAoBoD,CAAkB,EAC9C,YAAaC,GAAA,KAAAA,EAAsB,OACnC,QAAS7B,EAAU,OACrB,CAAC,EAED,OACE1B,GAAAF,GAAA,CACG,UAAAuE,EACDtE,EAAC,UACC,KAAK,sBACL,MAAO6B,EACP,wBAAyB,CAAE,OAAQ+C,GAAsBF,EAAI,CAAE,EACjE,EACCF,GACH,CAEJ","names":["deriveSessionSegment","extractTrackedParams","matchedAgentToken","cookies","headers","renderPrePaintScript","confidenceBand","jsx","inlineJsString","value","personaScriptBody","props","SentientPersonaScript","preloadAssignments","readSessionCookie","preloadDecisions","defaultSessionId","loadAdaptiveAssignments","components","options","_a","_b","_c","sessionId","readSessionCookie","preloadAssignments","loadAdaptiveDecision","_d","_e","_f","_g","_h","_i","_j","preloadDecisions","fallback","mod","outcome","e","result","__spreadProps","__spreadValues","AdaptiveRootClient","RESERVED_FIELDS","registry","defineAgentContent","page","content","getAgentContent","buildAgentFeed","input","_a","_b","supplied","getAgentContent","safe","k","v","RESERVED_FIELDS","feed","__spreadProps","__spreadValues","renderAgentJsonLdBody","feed","__spreadValues","renderAgentMarkdown","lines","k","v","b","logAgentFetch","entry","deps","_a","_b","doFetch","e","matchedAgentToken","wantsMarkdown","url","accept","createAgentFeed","config","request","_a","userAgent","path","matchedAgentToken","e","feed","renderAgentMarkdown","matchedAgentToken","uaTokenMatch","agentIntent","classifiedAgents","Fragment","jsx","jsxs","DEFAULT_API_BASE_URL","assignmentsToBlocks","assignments","id","v","_a","AdaptiveRoot","props","_b","_c","_d","_e","_f","_g","_h","_i","components","sections","slots","registrySlotIds","appOrigin","searchParams","initialAssignmentsOverride","ssrSessionIdProp","timeoutMs","agentFeed","captureAgents","nonce","children","providerProps","__objRest","headerStore","headers","host","resolvedOrigin","userAgent","referer","utmParams","clickIds","extractTrackedParams","doNotTrack","sessionSegment","deriveSessionSegment","cookieStore","cookies","cf","consent","skipSsr","baseUrl","agentPath","agentBot","matchedAgentToken","logAgentFetch","initialAssignments","initialLayoutOrder","initialSlots","initialSlotConfig","initialPalette","initialVocabulary","initialPersona","ssrSessionId","registry","decision","loadAdaptiveDecision","__spreadProps","__spreadValues","result","loadAdaptiveAssignments","personaScript","SentientPersonaScript","client","AdaptiveRootClient","feed","buildAgentFeed","renderAgentJsonLdBody"]}
@@ -1,3 +1,3 @@
1
1
  'use client';
2
- "use strict";var de=Object.create;var k=Object.defineProperty,ue=Object.defineProperties,fe=Object.getOwnPropertyDescriptor,ge=Object.getOwnPropertyDescriptors,pe=Object.getOwnPropertyNames,M=Object.getOwnPropertySymbols,me=Object.getPrototypeOf,K=Object.prototype.hasOwnProperty,ve=Object.prototype.propertyIsEnumerable;var $=(e,t,n)=>t in e?k(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,v=(e,t)=>{for(var n in t||(t={}))K.call(t,n)&&$(e,n,t[n]);if(M)for(var n of M(t))ve.call(t,n)&&$(e,n,t[n]);return e},B=(e,t)=>ue(e,ge(t));var ye=(e,t)=>{for(var n in t)k(e,n,{get:t[n],enumerable:!0})},U=(e,t,n,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of pe(t))!K.call(e,o)&&o!==n&&k(e,o,{get:()=>t[o],enumerable:!(i=fe(t,o))||i.enumerable});return e};var V=(e,t,n)=>(n=e!=null?de(me(e)):{},U(t||!e||!e.__esModule?k(n,"default",{value:e,enumerable:!0}):n,e)),_e=e=>U(k({},"__esModule",{value:!0}),e);var Le={};ye(Le,{renderWithSentient:()=>Te});module.exports=_e(Le);var le=require("@testing-library/react");var s=require("react"),O=require("@sentientui/core");var Se=new Map,he=new Map;function z(e,t){Se.set(e,t);let n=he.get(e);if(n)for(let i of n)try{i(t)}catch(o){}}var we={on:!1,listeners:new Set};function j(){if(typeof window=="undefined")return we;let e=window;return e.__sentient_preview||(e.__sentient_preview={on:!1,listeners:new Set}),e.__sentient_preview}function T(){return j().on}function H(e){let t=j().listeners;return t.add(e),()=>{t.delete(e)}}function J(e){return{isLocal:e.isLocal,track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},fetchWeights:()=>Promise.resolve([]),getAssignment:(t,n)=>e.getAssignment(t,n),assign:(t,n,i,o)=>e.assign(t,n,i,o),decide:()=>Promise.resolve(null),getSlotResult:t=>e.getSlotResult(t),getSlotConfig:t=>e.getSlotConfig(t),getSitePalette:()=>e.getSitePalette(),reportSlots:t=>e.reportSlots(t),getPersona:()=>e.getPersona(),getGraph:()=>e.getGraph(),flush:()=>e.flush(),dispose:()=>e.dispose(),destroy:()=>e.destroy()}}var be="sentient:overrides-changed";function E(){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(be))}function q(e){typeof window!="undefined"&&(window.__sentient_devtools_config=e)}function A(){var e;return typeof process=="undefined"||((e=process.env)==null?void 0:e.NODE_ENV)!=="production"}var Ce={components:new Map,slots:new Map,sections:[],listeners:new Set,version:0};function L(){if(typeof window=="undefined")return Ce;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 xe(){L().version+=1;for(let e of L().listeners)e()}function D(e){A()&&(L().sections=[...e],xe())}var X="0.35.1",G=X!=="0.0.0-dev"?{name:"react",version:X}:void 0;function Re(){let e=window;return e.__sentient_slot_config_overrides||(e.__sentient_slot_config_overrides={}),e.__sentient_slot_config_overrides}function b(e,t){Re()[e]=t}function Q(e){window.__sentient_vocabulary_override=e}function ke(){let e=window;return e.__sentient_slot_overrides||(e.__sentient_slot_overrides={}),e.__sentient_slot_overrides}function C(e,t){ke()[e]=t}var Y="sentient_editor",Z="sentient_preview_cell",ee="sentient_refresh_region",N="sentient-cell-preview-bar",w="__preview__",Ee=null;function te(e){if(typeof window=="undefined"||typeof document=="undefined"||document.getElementById(N))return;let t,n,i;try{let u=new URLSearchParams(window.location.search);t=u.get(Y),n=u.get(Z),i=u.get(ee)}catch(u){return}if(t&&i){Ee={slotId:i,token:t,base:(e!=null?e:"https://api.sentient-ui.com/v1").replace(/\/$/,"")},b(i,{kind:"arms"}),C(i,w),E();return}if(!t||!n)return;let o=n.lastIndexOf("~");if(o<=0)return;let c=n.slice(0,o),y=n.slice(o+1),_=(e!=null?e:"https://api.sentient-ui.com/v1").replace(/\/$/,"");fetch(`${_}/editor/cell-preview?slotId=${encodeURIComponent(c)}&persona=${encodeURIComponent(y)}`,{headers:{authorization:`Bearer ${t}`}}).then(async u=>{if(!u.ok){P(u.status===401?"This preview link has expired \u2014 reopen it from your dashboard.":"Couldn\u2019t load this preview \u2014 reopen it from your dashboard.");return}let a=await u.json();if(a.vocabulary&&Array.isArray(a.vocabulary.entries)&&Q(a.vocabulary),a.compose!=null)b(c,{kind:"arms",compose:{[w]:a.compose}}),C(c,w);else if(a.edits!=null&&typeof a.skeletonFp=="string"&&Array.isArray(a.leafToNode))b(c,{kind:"arms",edits:{edits:a.edits,fp:a.skeletonFp,leafToNode:a.leafToNode}}),C(c,w);else if(a.blocks!=null)b(c,{kind:"arms",blocks:{[w]:a.blocks}}),C(c,w);else if(a.content!=null)b(c,{kind:"arms",content:a.content}),C(c,w);else{P("Nothing to preview in that square yet.");return}E(),P(`Previewing \u201C${a.slotName}\u201D for ${a.personaDisplay}${a.status==="review"?" \u2014 waiting for your approval":""}. Nothing is being tracked.`),setTimeout(()=>{var f;try{(f=document.querySelector(`[data-sentient-slot="${c}"]`))==null||f.scrollIntoView({block:"center"})}catch(x){}},300)}).catch(()=>P("Couldn\u2019t load this preview \u2014 check your connection and reopen it from your dashboard."))}function P(e){var o;if(document.getElementById(N))return;let t=document.createElement("div");t.id=N,Object.assign(t.style,{position:"fixed",bottom:"16px",left:"50%",transform:"translateX(-50%)",zIndex:"2147483647",display:"flex",alignItems:"center",gap:"10px",padding:"10px 14px",borderRadius:"12px",maxWidth:"90vw",background:"#111827",color:"#fff",font:"13px system-ui, sans-serif",border:"1px solid rgba(139,92,246,0.6)",boxShadow:"0 10px 34px rgba(0,0,0,0.45)"});let n=document.createElement("span");n.textContent=e;let i=document.createElement("button");i.textContent="Exit preview",Object.assign(i.style,{padding:"4px 10px",borderRadius:"999px",border:"1px solid rgba(255,255,255,0.35)",background:"transparent",color:"#fff",font:"12px system-ui, sans-serif",cursor:"pointer"}),i.onclick=()=>{let c=new URL(window.location.href);c.searchParams.delete(Y),c.searchParams.delete(Z),c.searchParams.delete(ee),window.location.assign(c.toString())},t.append(n,i),((o=document.body)!=null?o:document.documentElement).append(t)}var Ae="sentient_editor",ne=!1;function ie(e){if(ne||typeof window=="undefined")return;let t=null;try{t=new URLSearchParams(window.location.search).get(Ae)}catch(o){return}if(!t)return;ne=!0;let n=(e!=null?e:"https://api.sentient-ui.com/v1").replace(/\/$/,""),i=()=>{window.setTimeout(()=>{import("@sentientui/core/style-sample").then(({sampleStyleVocabulary:o})=>fetch(`${n}/editor/style-vocabulary`,{method:"POST",headers:{authorization:`Bearer ${t}`,"content-type":"application/json"},body:JSON.stringify(o(document))})).catch(()=>{})},1e3)};document.readyState==="complete"?i():window.addEventListener("load",i,{once:!0})}var se=require("react/jsx-runtime");function Pe(){var e,t;if(typeof window=="undefined")return"desktop:direct";try{return(0,O.deriveSessionSegment)({userAgent:(e=navigator.userAgent)!=null?e:"",referer:(t=document.referrer)!=null?t:"",appOrigin:window.location.origin})}catch(n){return"desktop:direct"}}var oe="https://api.sentient-ui.com/v1",Oe=(0,s.createContext)({client:null,apiKey:"",initialAssignments:{},sessionSegment:"desktop:direct",ssrFallback:"first",onAssignment:void 0,initialLayoutOrder:null,initialSlots:{},initialSlotConfig:{},initialPalette:null,initialVocabulary:null,initialPersona:null,apiBaseUrl:oe,debug:!1});function Ie(e){let[t,n]=(0,s.useState)(!1),i=(0,s.useRef)(e);i.current=e;let{cookie:o,value:c,event:y}=e!=null?e:{},_=typeof(e==null?void 0:e.check)=="function";return(0,s.useEffect)(()=>{let u=()=>{var R;let f=i.current;if(!f)return!1;if(f.check)return f.check()===!0;if(!f.cookie||typeof document=="undefined")return!1;let x=`${f.cookie}=${(R=f.value)!=null?R:"accepted"}`;return document.cookie.split("; ").some(I=>I.trim()===x)};if(n(u()),!y)return;let a=()=>{n(u())};return window.addEventListener(y,a),()=>window.removeEventListener(y,a)},[o,c,y,_]),t}function re(e){var W,F;let[t,n]=(0,s.useState)(null),[i]=(0,s.useState)(()=>{var r;return(r=e.sessionSegment)!=null?r:Pe()}),[o,c]=(0,s.useState)(T());(0,s.useEffect)(()=>H(()=>c(T())),[]),(0,s.useEffect)(()=>{te(e.apiBaseUrl),ie(e.apiBaseUrl)},[]);let y=Ie(e.consentFrom),_=e.consentFrom?e.consent===!0||y:e.consent,u=(0,s.useRef)(null);(0,s.useEffect)(()=>{var S;if(_===!1&&!e.preConsentBehavior){(S=u.current)==null||S.destroy(),u.current=null,n(null);return}let r=v({apiKey:e.apiKey,context:e.context,debug:e.debug,initialAssignments:e.initialAssignments,sessionSegment:i,consent:_,preConsentBehavior:e.preConsentBehavior,respectDoNotTrack:e.respectDoNotTrack,ssrSessionId:e.ssrSessionId,country:e.country,persona:e.persona,localMode:e.localMode,initialSlots:e.initialSlots,initialSlotConfig:e.initialSlotConfig,initialPalette:e.initialPalette,initialVocabulary:e.initialVocabulary,initialPersona:e.initialPersona,ingestUrl:e.apiBaseUrl?`${e.apiBaseUrl.replace(/\/$/,"")}/events`:void 0},G?{sdk:G}:{}),g=!1,l=null,d=null,p=m=>{e.engagement!==!1&&import("@sentientui/core/engagement").then(({startEngagementCapture:h})=>{g||(d=h(m,{apiKey:e.apiKey,sectionTypes:e.sectionTypes,apiBase:e.apiBaseUrl?e.apiBaseUrl.replace(/\/$/,""):void 0}))})};return e.enableGraph!==!1?import("@sentientui/core/graph").then(({init:m})=>{g||(l=m(B(v({},r),{graph:!0,captureDomText:e.captureDomText===!0,sectionTypes:e.sectionTypes})),u.current=l,n(l),p(l))}):(l=(0,O.init)(r),u.current=l,n(l),p(l)),()=>{g=!0,d==null||d(),l==null||l.dispose()}},[_]),(0,s.useEffect)(()=>{if(!t)return;let r=!1,g=async()=>{if(r)return;let d;try{d=await t.fetchWeights()}catch(p){return}if(!r)for(let p of d){let S={componentId:p.componentId,updatedAt:p.updatedAt,variants:p.variants.map(m=>{var h;return{variantId:m.variantId,pulls:m.pulls,avgReward:(h=m.avgReward)!=null?h:0}})};z(p.componentId,S)}};g();let l=setInterval(()=>{g()},6e4);return()=>{r=!0,clearInterval(l)}},[t]);let a=(W=e.ssrFallback)!=null?W:"first",f=((F=e.apiBaseUrl)!=null?F:oe).replace(/\/$/,""),x=(0,s.useRef)(null);(0,s.useEffect)(()=>{var l;if(typeof process!="undefined"&&((l=process.env)==null?void 0:l.NODE_ENV)==="production")return;let r={apiKey:e.apiKey,context:e.context,country:e.country,persona:e.persona,apiBaseUrl:f},g=x.current;if(x.current=r,g!==null)for(let d of["apiKey","context","country","persona","apiBaseUrl"])Object.is(g[d],r[d])||console.warn(`[sentient] AdaptiveProvider: \`${d}\` changed after initialisation, but the SDK client is stable for the session and only re-inits on \`consent\` \u2014 the new value is ignored. Remount the provider (e.g. via a changing \`key\` prop) to apply it.`)},[e.apiKey,e.context,e.country,e.persona,f]),(0,s.useEffect)(()=>{var r;typeof process!="undefined"&&((r=process.env)==null?void 0:r.NODE_ENV)==="production"||q({apiKey:e.apiKey,apiBaseUrl:f,isLocal:(t==null?void 0:t.isLocal)===!0})},[t,e.apiKey,f]),(0,s.useEffect)(()=>{let r=e.initialLayoutOrder;if(r&&r.length>0){D(r);return}e.declaredSections&&e.declaredSections.length>0&&D(e.declaredSections)},[e.initialLayoutOrder,e.declaredSections]),(0,s.useEffect)(()=>{if(!A())return;let r=e.declaredSections;if(!r||r.length===0||typeof document=="undefined")return;let g=new Set(Array.from(document.querySelectorAll("[data-sentient-id]"),d=>d.getAttribute("data-sentient-id"))),l=r.filter(d=>!g.has(d));l.length>0&&console.warn(`[SentientUI] Declared section${l.length>1?"s":""} ${l.map(d=>`"${d}"`).join(", ")} ${l.length>1?"have":"has"} no matching data-sentient-id element, so the layout engine cannot learn what they are and will serve the same order to every persona. Add data-sentient-id="<sectionId>" to each section's element.`)},[e.declaredSections]);let R=(0,s.useMemo)(()=>t&&o?J(t):t,[t,o]),I=(0,s.useMemo)(()=>{var r,g,l,d,p,S,m,h;return{client:R,apiKey:e.apiKey,initialAssignments:(r=e.initialAssignments)!=null?r:{},sessionSegment:i,ssrFallback:a,onAssignment:e.onAssignment,initialLayoutOrder:(g=e.initialLayoutOrder)!=null?g:null,initialSlots:(l=e.initialSlots)!=null?l:{},initialSlotConfig:(d=e.initialSlotConfig)!=null?d:{},initialPalette:(p=e.initialPalette)!=null?p:null,initialVocabulary:(S=e.initialVocabulary)!=null?S:null,initialPersona:(m=e.initialPersona)!=null?m:null,apiBaseUrl:f,debug:(h=e.debug)!=null?h:!1}},[R,e.apiKey,e.initialAssignments,i,a,e.onAssignment,e.initialLayoutOrder,e.initialSlots,e.initialSlotConfig,e.initialPalette,e.initialVocabulary,e.initialPersona,f,e.debug]);return(0,se.jsx)(Oe.Provider,{value:I,children:e.children})}function Ve(e){return e<.3?"low":e<.7?"medium":"high"}function ae(e={}){var n,i,o;let t=window;if(t.__sentient_overrides=v({},(n=e.variants)!=null?n:{}),e.layout?t.__sentient_layout_override=e.layout:delete t.__sentient_layout_override,e.slots?t.__sentient_slot_overrides=v({},e.slots):delete t.__sentient_slot_overrides,e.slotConfig?t.__sentient_slot_config_overrides=v({},e.slotConfig):delete t.__sentient_slot_config_overrides,e.persona){t.__sentient_persona_override={persona:e.persona,confidence:(i=e.confidence)!=null?i:1};try{let c=document.documentElement;c.setAttribute("data-sentient-persona",e.persona),c.setAttribute("data-sentient-confidence",Ve((o=e.confidence)!=null?o:1))}catch(c){}}else delete t.__sentient_persona_override;E()}var ce=require("react/jsx-runtime");function Te(e,t={},n){return ae(t),(0,le.render)((0,ce.jsx)(re,{apiKey:"pk_test",consent:!1,children:e}),n)}0&&(module.exports={renderWithSentient});
2
+ "use strict";var de=Object.create;var k=Object.defineProperty,ue=Object.defineProperties,fe=Object.getOwnPropertyDescriptor,ge=Object.getOwnPropertyDescriptors,pe=Object.getOwnPropertyNames,M=Object.getOwnPropertySymbols,me=Object.getPrototypeOf,K=Object.prototype.hasOwnProperty,ve=Object.prototype.propertyIsEnumerable;var $=(e,t,n)=>t in e?k(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,v=(e,t)=>{for(var n in t||(t={}))K.call(t,n)&&$(e,n,t[n]);if(M)for(var n of M(t))ve.call(t,n)&&$(e,n,t[n]);return e},B=(e,t)=>ue(e,ge(t));var ye=(e,t)=>{for(var n in t)k(e,n,{get:t[n],enumerable:!0})},U=(e,t,n,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of pe(t))!K.call(e,o)&&o!==n&&k(e,o,{get:()=>t[o],enumerable:!(i=fe(t,o))||i.enumerable});return e};var V=(e,t,n)=>(n=e!=null?de(me(e)):{},U(t||!e||!e.__esModule?k(n,"default",{value:e,enumerable:!0}):n,e)),_e=e=>U(k({},"__esModule",{value:!0}),e);var Le={};ye(Le,{renderWithSentient:()=>Te});module.exports=_e(Le);var le=require("@testing-library/react");var s=require("react"),O=require("@sentientui/core");var Se=new Map,he=new Map;function z(e,t){Se.set(e,t);let n=he.get(e);if(n)for(let i of n)try{i(t)}catch(o){}}var we={on:!1,listeners:new Set};function j(){if(typeof window=="undefined")return we;let e=window;return e.__sentient_preview||(e.__sentient_preview={on:!1,listeners:new Set}),e.__sentient_preview}function T(){return j().on}function H(e){let t=j().listeners;return t.add(e),()=>{t.delete(e)}}function J(e){return{isLocal:e.isLocal,track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},fetchWeights:()=>Promise.resolve([]),getAssignment:(t,n)=>e.getAssignment(t,n),assign:(t,n,i,o)=>e.assign(t,n,i,o),decide:()=>Promise.resolve(null),getSlotResult:t=>e.getSlotResult(t),getSlotConfig:t=>e.getSlotConfig(t),getSitePalette:()=>e.getSitePalette(),reportSlots:t=>e.reportSlots(t),getPersona:()=>e.getPersona(),getGraph:()=>e.getGraph(),flush:()=>e.flush(),dispose:()=>e.dispose(),destroy:()=>e.destroy()}}var be="sentient:overrides-changed";function E(){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(be))}function q(e){typeof window!="undefined"&&(window.__sentient_devtools_config=e)}function A(){var e;return typeof process=="undefined"||((e=process.env)==null?void 0:e.NODE_ENV)!=="production"}var Ce={components:new Map,slots:new Map,sections:[],listeners:new Set,version:0};function L(){if(typeof window=="undefined")return Ce;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 xe(){L().version+=1;for(let e of L().listeners)e()}function D(e){A()&&(L().sections=[...e],xe())}var X="0.35.3",G=X!=="0.0.0-dev"?{name:"react",version:X}:void 0;function Re(){let e=window;return e.__sentient_slot_config_overrides||(e.__sentient_slot_config_overrides={}),e.__sentient_slot_config_overrides}function b(e,t){Re()[e]=t}function Q(e){window.__sentient_vocabulary_override=e}function ke(){let e=window;return e.__sentient_slot_overrides||(e.__sentient_slot_overrides={}),e.__sentient_slot_overrides}function C(e,t){ke()[e]=t}var Y="sentient_editor",Z="sentient_preview_cell",ee="sentient_refresh_region",N="sentient-cell-preview-bar",w="__preview__",Ee=null;function te(e){if(typeof window=="undefined"||typeof document=="undefined"||document.getElementById(N))return;let t,n,i;try{let u=new URLSearchParams(window.location.search);t=u.get(Y),n=u.get(Z),i=u.get(ee)}catch(u){return}if(t&&i){Ee={slotId:i,token:t,base:(e!=null?e:"https://api.sentient-ui.com/v1").replace(/\/$/,"")},b(i,{kind:"arms"}),C(i,w),E();return}if(!t||!n)return;let o=n.lastIndexOf("~");if(o<=0)return;let c=n.slice(0,o),y=n.slice(o+1),_=(e!=null?e:"https://api.sentient-ui.com/v1").replace(/\/$/,"");fetch(`${_}/editor/cell-preview?slotId=${encodeURIComponent(c)}&persona=${encodeURIComponent(y)}`,{headers:{authorization:`Bearer ${t}`}}).then(async u=>{if(!u.ok){P(u.status===401?"This preview link has expired \u2014 reopen it from your dashboard.":"Couldn\u2019t load this preview \u2014 reopen it from your dashboard.");return}let a=await u.json();if(a.vocabulary&&Array.isArray(a.vocabulary.entries)&&Q(a.vocabulary),a.compose!=null)b(c,{kind:"arms",compose:{[w]:a.compose}}),C(c,w);else if(a.edits!=null&&typeof a.skeletonFp=="string"&&Array.isArray(a.leafToNode))b(c,{kind:"arms",edits:{edits:a.edits,fp:a.skeletonFp,leafToNode:a.leafToNode}}),C(c,w);else if(a.blocks!=null)b(c,{kind:"arms",blocks:{[w]:a.blocks}}),C(c,w);else if(a.content!=null)b(c,{kind:"arms",content:a.content}),C(c,w);else{P("Nothing to preview in that square yet.");return}E(),P(`Previewing \u201C${a.slotName}\u201D for ${a.personaDisplay}${a.status==="review"?" \u2014 waiting for your approval":""}. Nothing is being tracked.`),setTimeout(()=>{var f;try{(f=document.querySelector(`[data-sentient-slot="${c}"]`))==null||f.scrollIntoView({block:"center"})}catch(x){}},300)}).catch(()=>P("Couldn\u2019t load this preview \u2014 check your connection and reopen it from your dashboard."))}function P(e){var o;if(document.getElementById(N))return;let t=document.createElement("div");t.id=N,Object.assign(t.style,{position:"fixed",bottom:"16px",left:"50%",transform:"translateX(-50%)",zIndex:"2147483647",display:"flex",alignItems:"center",gap:"10px",padding:"10px 14px",borderRadius:"12px",maxWidth:"90vw",background:"#111827",color:"#fff",font:"13px system-ui, sans-serif",border:"1px solid rgba(139,92,246,0.6)",boxShadow:"0 10px 34px rgba(0,0,0,0.45)"});let n=document.createElement("span");n.textContent=e;let i=document.createElement("button");i.textContent="Exit preview",Object.assign(i.style,{padding:"4px 10px",borderRadius:"999px",border:"1px solid rgba(255,255,255,0.35)",background:"transparent",color:"#fff",font:"12px system-ui, sans-serif",cursor:"pointer"}),i.onclick=()=>{let c=new URL(window.location.href);c.searchParams.delete(Y),c.searchParams.delete(Z),c.searchParams.delete(ee),window.location.assign(c.toString())},t.append(n,i),((o=document.body)!=null?o:document.documentElement).append(t)}var Ae="sentient_editor",ne=!1;function ie(e){if(ne||typeof window=="undefined")return;let t=null;try{t=new URLSearchParams(window.location.search).get(Ae)}catch(o){return}if(!t)return;ne=!0;let n=(e!=null?e:"https://api.sentient-ui.com/v1").replace(/\/$/,""),i=()=>{window.setTimeout(()=>{import("@sentientui/core/style-sample").then(({sampleStyleVocabulary:o})=>fetch(`${n}/editor/style-vocabulary`,{method:"POST",headers:{authorization:`Bearer ${t}`,"content-type":"application/json"},body:JSON.stringify(o(document))})).catch(()=>{})},1e3)};document.readyState==="complete"?i():window.addEventListener("load",i,{once:!0})}var se=require("react/jsx-runtime");function Pe(){var e,t;if(typeof window=="undefined")return"desktop:direct";try{return(0,O.deriveSessionSegment)({userAgent:(e=navigator.userAgent)!=null?e:"",referer:(t=document.referrer)!=null?t:"",appOrigin:window.location.origin})}catch(n){return"desktop:direct"}}var oe="https://api.sentient-ui.com/v1",Oe=(0,s.createContext)({client:null,apiKey:"",initialAssignments:{},sessionSegment:"desktop:direct",ssrFallback:"first",onAssignment:void 0,initialLayoutOrder:null,initialSlots:{},initialSlotConfig:{},initialPalette:null,initialVocabulary:null,initialPersona:null,apiBaseUrl:oe,debug:!1});function Ie(e){let[t,n]=(0,s.useState)(!1),i=(0,s.useRef)(e);i.current=e;let{cookie:o,value:c,event:y}=e!=null?e:{},_=typeof(e==null?void 0:e.check)=="function";return(0,s.useEffect)(()=>{let u=()=>{var R;let f=i.current;if(!f)return!1;if(f.check)return f.check()===!0;if(!f.cookie||typeof document=="undefined")return!1;let x=`${f.cookie}=${(R=f.value)!=null?R:"accepted"}`;return document.cookie.split("; ").some(I=>I.trim()===x)};if(n(u()),!y)return;let a=()=>{n(u())};return window.addEventListener(y,a),()=>window.removeEventListener(y,a)},[o,c,y,_]),t}function re(e){var W,F;let[t,n]=(0,s.useState)(null),[i]=(0,s.useState)(()=>{var r;return(r=e.sessionSegment)!=null?r:Pe()}),[o,c]=(0,s.useState)(T());(0,s.useEffect)(()=>H(()=>c(T())),[]),(0,s.useEffect)(()=>{te(e.apiBaseUrl),ie(e.apiBaseUrl)},[]);let y=Ie(e.consentFrom),_=e.consentFrom?e.consent===!0||y:e.consent,u=(0,s.useRef)(null);(0,s.useEffect)(()=>{var S;if(_===!1&&!e.preConsentBehavior){(S=u.current)==null||S.destroy(),u.current=null,n(null);return}let r=v({apiKey:e.apiKey,context:e.context,debug:e.debug,initialAssignments:e.initialAssignments,sessionSegment:i,consent:_,preConsentBehavior:e.preConsentBehavior,respectDoNotTrack:e.respectDoNotTrack,ssrSessionId:e.ssrSessionId,country:e.country,persona:e.persona,localMode:e.localMode,initialSlots:e.initialSlots,initialSlotConfig:e.initialSlotConfig,initialPalette:e.initialPalette,initialVocabulary:e.initialVocabulary,initialPersona:e.initialPersona,ingestUrl:e.apiBaseUrl?`${e.apiBaseUrl.replace(/\/$/,"")}/events`:void 0},G?{sdk:G}:{}),g=!1,l=null,d=null,p=m=>{e.engagement!==!1&&import("@sentientui/core/engagement").then(({startEngagementCapture:h})=>{g||(d=h(m,{apiKey:e.apiKey,sectionTypes:e.sectionTypes,apiBase:e.apiBaseUrl?e.apiBaseUrl.replace(/\/$/,""):void 0}))})};return e.enableGraph!==!1?import("@sentientui/core/graph").then(({init:m})=>{g||(l=m(B(v({},r),{graph:!0,captureDomText:e.captureDomText===!0,sectionTypes:e.sectionTypes})),u.current=l,n(l),p(l))}):(l=(0,O.init)(r),u.current=l,n(l),p(l)),()=>{g=!0,d==null||d(),l==null||l.dispose()}},[_]),(0,s.useEffect)(()=>{if(!t)return;let r=!1,g=async()=>{if(r)return;let d;try{d=await t.fetchWeights()}catch(p){return}if(!r)for(let p of d){let S={componentId:p.componentId,updatedAt:p.updatedAt,variants:p.variants.map(m=>{var h;return{variantId:m.variantId,pulls:m.pulls,avgReward:(h=m.avgReward)!=null?h:0}})};z(p.componentId,S)}};g();let l=setInterval(()=>{g()},6e4);return()=>{r=!0,clearInterval(l)}},[t]);let a=(W=e.ssrFallback)!=null?W:"first",f=((F=e.apiBaseUrl)!=null?F:oe).replace(/\/$/,""),x=(0,s.useRef)(null);(0,s.useEffect)(()=>{var l;if(typeof process!="undefined"&&((l=process.env)==null?void 0:l.NODE_ENV)==="production")return;let r={apiKey:e.apiKey,context:e.context,country:e.country,persona:e.persona,apiBaseUrl:f},g=x.current;if(x.current=r,g!==null)for(let d of["apiKey","context","country","persona","apiBaseUrl"])Object.is(g[d],r[d])||console.warn(`[sentient] AdaptiveProvider: \`${d}\` changed after initialisation, but the SDK client is stable for the session and only re-inits on \`consent\` \u2014 the new value is ignored. Remount the provider (e.g. via a changing \`key\` prop) to apply it.`)},[e.apiKey,e.context,e.country,e.persona,f]),(0,s.useEffect)(()=>{var r;typeof process!="undefined"&&((r=process.env)==null?void 0:r.NODE_ENV)==="production"||q({apiKey:e.apiKey,apiBaseUrl:f,isLocal:(t==null?void 0:t.isLocal)===!0})},[t,e.apiKey,f]),(0,s.useEffect)(()=>{let r=e.initialLayoutOrder;if(r&&r.length>0){D(r);return}e.declaredSections&&e.declaredSections.length>0&&D(e.declaredSections)},[e.initialLayoutOrder,e.declaredSections]),(0,s.useEffect)(()=>{if(!A())return;let r=e.declaredSections;if(!r||r.length===0||typeof document=="undefined")return;let g=new Set(Array.from(document.querySelectorAll("[data-sentient-id]"),d=>d.getAttribute("data-sentient-id"))),l=r.filter(d=>!g.has(d));l.length>0&&console.warn(`[SentientUI] Declared section${l.length>1?"s":""} ${l.map(d=>`"${d}"`).join(", ")} ${l.length>1?"have":"has"} no matching data-sentient-id element, so the layout engine cannot learn what they are and will serve the same order to every persona. Add data-sentient-id="<sectionId>" to each section's element.`)},[e.declaredSections]);let R=(0,s.useMemo)(()=>t&&o?J(t):t,[t,o]),I=(0,s.useMemo)(()=>{var r,g,l,d,p,S,m,h;return{client:R,apiKey:e.apiKey,initialAssignments:(r=e.initialAssignments)!=null?r:{},sessionSegment:i,ssrFallback:a,onAssignment:e.onAssignment,initialLayoutOrder:(g=e.initialLayoutOrder)!=null?g:null,initialSlots:(l=e.initialSlots)!=null?l:{},initialSlotConfig:(d=e.initialSlotConfig)!=null?d:{},initialPalette:(p=e.initialPalette)!=null?p:null,initialVocabulary:(S=e.initialVocabulary)!=null?S:null,initialPersona:(m=e.initialPersona)!=null?m:null,apiBaseUrl:f,debug:(h=e.debug)!=null?h:!1}},[R,e.apiKey,e.initialAssignments,i,a,e.onAssignment,e.initialLayoutOrder,e.initialSlots,e.initialSlotConfig,e.initialPalette,e.initialVocabulary,e.initialPersona,f,e.debug]);return(0,se.jsx)(Oe.Provider,{value:I,children:e.children})}function Ve(e){return e<.3?"low":e<.7?"medium":"high"}function ae(e={}){var n,i,o;let t=window;if(t.__sentient_overrides=v({},(n=e.variants)!=null?n:{}),e.layout?t.__sentient_layout_override=e.layout:delete t.__sentient_layout_override,e.slots?t.__sentient_slot_overrides=v({},e.slots):delete t.__sentient_slot_overrides,e.slotConfig?t.__sentient_slot_config_overrides=v({},e.slotConfig):delete t.__sentient_slot_config_overrides,e.persona){t.__sentient_persona_override={persona:e.persona,confidence:(i=e.confidence)!=null?i:1};try{let c=document.documentElement;c.setAttribute("data-sentient-persona",e.persona),c.setAttribute("data-sentient-confidence",Ve((o=e.confidence)!=null?o:1))}catch(c){}}else delete t.__sentient_persona_override;E()}var ce=require("react/jsx-runtime");function Te(e,t={},n){return ae(t),(0,le.render)((0,ce.jsx)(re,{apiKey:"pk_test",consent:!1,children:e}),n)}0&&(module.exports={renderWithSentient});
3
3
  //# sourceMappingURL=react.js.map
@@ -1,3 +1,3 @@
1
1
  'use client';
2
- var re=Object.defineProperty,se=Object.defineProperties;var ae=Object.getOwnPropertyDescriptors;var F=Object.getOwnPropertySymbols;var le=Object.prototype.hasOwnProperty,ce=Object.prototype.propertyIsEnumerable;var M=(e,t,n)=>t in e?re(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,m=(e,t)=>{for(var n in t||(t={}))le.call(t,n)&&M(e,n,t[n]);if(F)for(var n of F(t))ce.call(t,n)&&M(e,n,t[n]);return e},$=(e,t)=>se(e,ae(t));import{render as Ae}from"@testing-library/react";import{createContext as he,useContext as Xe,useEffect as v,useMemo as te,useRef as G,useState as P,useSyncExternalStore as Qe}from"react";import{deriveSessionSegment as we,init as be}from"@sentientui/core";var de=new Map,ue=new Map;function K(e,t){de.set(e,t);let n=ue.get(e);if(n)for(let i of n)try{i(t)}catch(l){}}var fe={on:!1,listeners:new Set};function B(){if(typeof window=="undefined")return fe;let e=window;return e.__sentient_preview||(e.__sentient_preview={on:!1,listeners:new Set}),e.__sentient_preview}function I(){return B().on}function U(e){let t=B().listeners;return t.add(e),()=>{t.delete(e)}}function z(e){return{isLocal:e.isLocal,track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},fetchWeights:()=>Promise.resolve([]),getAssignment:(t,n)=>e.getAssignment(t,n),assign:(t,n,i,l)=>e.assign(t,n,i,l),decide:()=>Promise.resolve(null),getSlotResult:t=>e.getSlotResult(t),getSlotConfig:t=>e.getSlotConfig(t),getSitePalette:()=>e.getSitePalette(),reportSlots:t=>e.reportSlots(t),getPersona:()=>e.getPersona(),getGraph:()=>e.getGraph(),flush:()=>e.flush(),dispose:()=>e.dispose(),destroy:()=>e.destroy()}}var ge="sentient:overrides-changed";function k(){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(ge))}function j(e){typeof window!="undefined"&&(window.__sentient_devtools_config=e)}function E(){var e;return typeof process=="undefined"||((e=process.env)==null?void 0:e.NODE_ENV)!=="production"}var pe={components:new Map,slots:new Map,sections:[],listeners:new Set,version:0};function V(){if(typeof window=="undefined")return pe;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 me(){V().version+=1;for(let e of V().listeners)e()}function T(e){E()&&(V().sections=[...e],me())}var H="0.35.1",L=H!=="0.0.0-dev"?{name:"react",version:H}:void 0;function ve(){let e=window;return e.__sentient_slot_config_overrides||(e.__sentient_slot_config_overrides={}),e.__sentient_slot_config_overrides}function b(e,t){ve()[e]=t}function J(e){window.__sentient_vocabulary_override=e}function ye(){let e=window;return e.__sentient_slot_overrides||(e.__sentient_slot_overrides={}),e.__sentient_slot_overrides}function C(e,t){ye()[e]=t}var q="sentient_editor",X="sentient_preview_cell",Q="sentient_refresh_region",D="sentient-cell-preview-bar",w="__preview__",_e=null;function Y(e){if(typeof window=="undefined"||typeof document=="undefined"||document.getElementById(D))return;let t,n,i;try{let d=new URLSearchParams(window.location.search);t=d.get(q),n=d.get(X),i=d.get(Q)}catch(d){return}if(t&&i){_e={slotId:i,token:t,base:(e!=null?e:"https://api.sentient-ui.com/v1").replace(/\/$/,"")},b(i,{kind:"arms"}),C(i,w),k();return}if(!t||!n)return;let l=n.lastIndexOf("~");if(l<=0)return;let a=n.slice(0,l),y=n.slice(l+1),_=(e!=null?e:"https://api.sentient-ui.com/v1").replace(/\/$/,"");fetch(`${_}/editor/cell-preview?slotId=${encodeURIComponent(a)}&persona=${encodeURIComponent(y)}`,{headers:{authorization:`Bearer ${t}`}}).then(async d=>{if(!d.ok){A(d.status===401?"This preview link has expired \u2014 reopen it from your dashboard.":"Couldn\u2019t load this preview \u2014 reopen it from your dashboard.");return}let r=await d.json();if(r.vocabulary&&Array.isArray(r.vocabulary.entries)&&J(r.vocabulary),r.compose!=null)b(a,{kind:"arms",compose:{[w]:r.compose}}),C(a,w);else if(r.edits!=null&&typeof r.skeletonFp=="string"&&Array.isArray(r.leafToNode))b(a,{kind:"arms",edits:{edits:r.edits,fp:r.skeletonFp,leafToNode:r.leafToNode}}),C(a,w);else if(r.blocks!=null)b(a,{kind:"arms",blocks:{[w]:r.blocks}}),C(a,w);else if(r.content!=null)b(a,{kind:"arms",content:r.content}),C(a,w);else{A("Nothing to preview in that square yet.");return}k(),A(`Previewing \u201C${r.slotName}\u201D for ${r.personaDisplay}${r.status==="review"?" \u2014 waiting for your approval":""}. Nothing is being tracked.`),setTimeout(()=>{var u;try{(u=document.querySelector(`[data-sentient-slot="${a}"]`))==null||u.scrollIntoView({block:"center"})}catch(x){}},300)}).catch(()=>A("Couldn\u2019t load this preview \u2014 check your connection and reopen it from your dashboard."))}function A(e){var l;if(document.getElementById(D))return;let t=document.createElement("div");t.id=D,Object.assign(t.style,{position:"fixed",bottom:"16px",left:"50%",transform:"translateX(-50%)",zIndex:"2147483647",display:"flex",alignItems:"center",gap:"10px",padding:"10px 14px",borderRadius:"12px",maxWidth:"90vw",background:"#111827",color:"#fff",font:"13px system-ui, sans-serif",border:"1px solid rgba(139,92,246,0.6)",boxShadow:"0 10px 34px rgba(0,0,0,0.45)"});let n=document.createElement("span");n.textContent=e;let i=document.createElement("button");i.textContent="Exit preview",Object.assign(i.style,{padding:"4px 10px",borderRadius:"999px",border:"1px solid rgba(255,255,255,0.35)",background:"transparent",color:"#fff",font:"12px system-ui, sans-serif",cursor:"pointer"}),i.onclick=()=>{let a=new URL(window.location.href);a.searchParams.delete(q),a.searchParams.delete(X),a.searchParams.delete(Q),window.location.assign(a.toString())},t.append(n,i),((l=document.body)!=null?l:document.documentElement).append(t)}var Se="sentient_editor",Z=!1;function ee(e){if(Z||typeof window=="undefined")return;let t=null;try{t=new URLSearchParams(window.location.search).get(Se)}catch(l){return}if(!t)return;Z=!0;let n=(e!=null?e:"https://api.sentient-ui.com/v1").replace(/\/$/,""),i=()=>{window.setTimeout(()=>{import("@sentientui/core/style-sample").then(({sampleStyleVocabulary:l})=>fetch(`${n}/editor/style-vocabulary`,{method:"POST",headers:{authorization:`Bearer ${t}`,"content-type":"application/json"},body:JSON.stringify(l(document))})).catch(()=>{})},1e3)};document.readyState==="complete"?i():window.addEventListener("load",i,{once:!0})}import{jsx as ke}from"react/jsx-runtime";function Ce(){var e,t;if(typeof window=="undefined")return"desktop:direct";try{return we({userAgent:(e=navigator.userAgent)!=null?e:"",referer:(t=document.referrer)!=null?t:"",appOrigin:window.location.origin})}catch(n){return"desktop:direct"}}var ne="https://api.sentient-ui.com/v1",xe=he({client:null,apiKey:"",initialAssignments:{},sessionSegment:"desktop:direct",ssrFallback:"first",onAssignment:void 0,initialLayoutOrder:null,initialSlots:{},initialSlotConfig:{},initialPalette:null,initialVocabulary:null,initialPersona:null,apiBaseUrl:ne,debug:!1});function Re(e){let[t,n]=P(!1),i=G(e);i.current=e;let{cookie:l,value:a,event:y}=e!=null?e:{},_=typeof(e==null?void 0:e.check)=="function";return v(()=>{let d=()=>{var R;let u=i.current;if(!u)return!1;if(u.check)return u.check()===!0;if(!u.cookie||typeof document=="undefined")return!1;let x=`${u.cookie}=${(R=u.value)!=null?R:"accepted"}`;return document.cookie.split("; ").some(O=>O.trim()===x)};if(n(d()),!y)return;let r=()=>{n(d())};return window.addEventListener(y,r),()=>window.removeEventListener(y,r)},[l,a,y,_]),t}function ie(e){var N,W;let[t,n]=P(null),[i]=P(()=>{var o;return(o=e.sessionSegment)!=null?o:Ce()}),[l,a]=P(I());v(()=>U(()=>a(I())),[]),v(()=>{Y(e.apiBaseUrl),ee(e.apiBaseUrl)},[]);let y=Re(e.consentFrom),_=e.consentFrom?e.consent===!0||y:e.consent,d=G(null);v(()=>{var S;if(_===!1&&!e.preConsentBehavior){(S=d.current)==null||S.destroy(),d.current=null,n(null);return}let o=m({apiKey:e.apiKey,context:e.context,debug:e.debug,initialAssignments:e.initialAssignments,sessionSegment:i,consent:_,preConsentBehavior:e.preConsentBehavior,respectDoNotTrack:e.respectDoNotTrack,ssrSessionId:e.ssrSessionId,country:e.country,persona:e.persona,localMode:e.localMode,initialSlots:e.initialSlots,initialSlotConfig:e.initialSlotConfig,initialPalette:e.initialPalette,initialVocabulary:e.initialVocabulary,initialPersona:e.initialPersona,ingestUrl:e.apiBaseUrl?`${e.apiBaseUrl.replace(/\/$/,"")}/events`:void 0},L?{sdk:L}:{}),f=!1,s=null,c=null,g=p=>{e.engagement!==!1&&import("@sentientui/core/engagement").then(({startEngagementCapture:h})=>{f||(c=h(p,{apiKey:e.apiKey,sectionTypes:e.sectionTypes,apiBase:e.apiBaseUrl?e.apiBaseUrl.replace(/\/$/,""):void 0}))})};return e.enableGraph!==!1?import("@sentientui/core/graph").then(({init:p})=>{f||(s=p($(m({},o),{graph:!0,captureDomText:e.captureDomText===!0,sectionTypes:e.sectionTypes})),d.current=s,n(s),g(s))}):(s=be(o),d.current=s,n(s),g(s)),()=>{f=!0,c==null||c(),s==null||s.dispose()}},[_]),v(()=>{if(!t)return;let o=!1,f=async()=>{if(o)return;let c;try{c=await t.fetchWeights()}catch(g){return}if(!o)for(let g of c){let S={componentId:g.componentId,updatedAt:g.updatedAt,variants:g.variants.map(p=>{var h;return{variantId:p.variantId,pulls:p.pulls,avgReward:(h=p.avgReward)!=null?h:0}})};K(g.componentId,S)}};f();let s=setInterval(()=>{f()},6e4);return()=>{o=!0,clearInterval(s)}},[t]);let r=(N=e.ssrFallback)!=null?N:"first",u=((W=e.apiBaseUrl)!=null?W:ne).replace(/\/$/,""),x=G(null);v(()=>{var s;if(typeof process!="undefined"&&((s=process.env)==null?void 0:s.NODE_ENV)==="production")return;let o={apiKey:e.apiKey,context:e.context,country:e.country,persona:e.persona,apiBaseUrl:u},f=x.current;if(x.current=o,f!==null)for(let c of["apiKey","context","country","persona","apiBaseUrl"])Object.is(f[c],o[c])||console.warn(`[sentient] AdaptiveProvider: \`${c}\` changed after initialisation, but the SDK client is stable for the session and only re-inits on \`consent\` \u2014 the new value is ignored. Remount the provider (e.g. via a changing \`key\` prop) to apply it.`)},[e.apiKey,e.context,e.country,e.persona,u]),v(()=>{var o;typeof process!="undefined"&&((o=process.env)==null?void 0:o.NODE_ENV)==="production"||j({apiKey:e.apiKey,apiBaseUrl:u,isLocal:(t==null?void 0:t.isLocal)===!0})},[t,e.apiKey,u]),v(()=>{let o=e.initialLayoutOrder;if(o&&o.length>0){T(o);return}e.declaredSections&&e.declaredSections.length>0&&T(e.declaredSections)},[e.initialLayoutOrder,e.declaredSections]),v(()=>{if(!E())return;let o=e.declaredSections;if(!o||o.length===0||typeof document=="undefined")return;let f=new Set(Array.from(document.querySelectorAll("[data-sentient-id]"),c=>c.getAttribute("data-sentient-id"))),s=o.filter(c=>!f.has(c));s.length>0&&console.warn(`[SentientUI] Declared section${s.length>1?"s":""} ${s.map(c=>`"${c}"`).join(", ")} ${s.length>1?"have":"has"} no matching data-sentient-id element, so the layout engine cannot learn what they are and will serve the same order to every persona. Add data-sentient-id="<sectionId>" to each section's element.`)},[e.declaredSections]);let R=te(()=>t&&l?z(t):t,[t,l]),O=te(()=>{var o,f,s,c,g,S,p,h;return{client:R,apiKey:e.apiKey,initialAssignments:(o=e.initialAssignments)!=null?o:{},sessionSegment:i,ssrFallback:r,onAssignment:e.onAssignment,initialLayoutOrder:(f=e.initialLayoutOrder)!=null?f:null,initialSlots:(s=e.initialSlots)!=null?s:{},initialSlotConfig:(c=e.initialSlotConfig)!=null?c:{},initialPalette:(g=e.initialPalette)!=null?g:null,initialVocabulary:(S=e.initialVocabulary)!=null?S:null,initialPersona:(p=e.initialPersona)!=null?p:null,apiBaseUrl:u,debug:(h=e.debug)!=null?h:!1}},[R,e.apiKey,e.initialAssignments,i,r,e.onAssignment,e.initialLayoutOrder,e.initialSlots,e.initialSlotConfig,e.initialPalette,e.initialVocabulary,e.initialPersona,u,e.debug]);return ke(xe.Provider,{value:O,children:e.children})}function Ee(e){return e<.3?"low":e<.7?"medium":"high"}function oe(e={}){var n,i,l;let t=window;if(t.__sentient_overrides=m({},(n=e.variants)!=null?n:{}),e.layout?t.__sentient_layout_override=e.layout:delete t.__sentient_layout_override,e.slots?t.__sentient_slot_overrides=m({},e.slots):delete t.__sentient_slot_overrides,e.slotConfig?t.__sentient_slot_config_overrides=m({},e.slotConfig):delete t.__sentient_slot_config_overrides,e.persona){t.__sentient_persona_override={persona:e.persona,confidence:(i=e.confidence)!=null?i:1};try{let a=document.documentElement;a.setAttribute("data-sentient-persona",e.persona),a.setAttribute("data-sentient-confidence",Ee((l=e.confidence)!=null?l:1))}catch(a){}}else delete t.__sentient_persona_override;k()}import{jsx as Pe}from"react/jsx-runtime";function vt(e,t={},n){return oe(t),Ae(Pe(ie,{apiKey:"pk_test",consent:!1,children:e}),n)}export{vt as renderWithSentient};
2
+ var re=Object.defineProperty,se=Object.defineProperties;var ae=Object.getOwnPropertyDescriptors;var F=Object.getOwnPropertySymbols;var le=Object.prototype.hasOwnProperty,ce=Object.prototype.propertyIsEnumerable;var M=(e,t,n)=>t in e?re(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,m=(e,t)=>{for(var n in t||(t={}))le.call(t,n)&&M(e,n,t[n]);if(F)for(var n of F(t))ce.call(t,n)&&M(e,n,t[n]);return e},$=(e,t)=>se(e,ae(t));import{render as Ae}from"@testing-library/react";import{createContext as he,useContext as Xe,useEffect as v,useMemo as te,useRef as G,useState as P,useSyncExternalStore as Qe}from"react";import{deriveSessionSegment as we,init as be}from"@sentientui/core";var de=new Map,ue=new Map;function K(e,t){de.set(e,t);let n=ue.get(e);if(n)for(let i of n)try{i(t)}catch(l){}}var fe={on:!1,listeners:new Set};function B(){if(typeof window=="undefined")return fe;let e=window;return e.__sentient_preview||(e.__sentient_preview={on:!1,listeners:new Set}),e.__sentient_preview}function I(){return B().on}function U(e){let t=B().listeners;return t.add(e),()=>{t.delete(e)}}function z(e){return{isLocal:e.isLocal,track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},fetchWeights:()=>Promise.resolve([]),getAssignment:(t,n)=>e.getAssignment(t,n),assign:(t,n,i,l)=>e.assign(t,n,i,l),decide:()=>Promise.resolve(null),getSlotResult:t=>e.getSlotResult(t),getSlotConfig:t=>e.getSlotConfig(t),getSitePalette:()=>e.getSitePalette(),reportSlots:t=>e.reportSlots(t),getPersona:()=>e.getPersona(),getGraph:()=>e.getGraph(),flush:()=>e.flush(),dispose:()=>e.dispose(),destroy:()=>e.destroy()}}var ge="sentient:overrides-changed";function k(){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(ge))}function j(e){typeof window!="undefined"&&(window.__sentient_devtools_config=e)}function E(){var e;return typeof process=="undefined"||((e=process.env)==null?void 0:e.NODE_ENV)!=="production"}var pe={components:new Map,slots:new Map,sections:[],listeners:new Set,version:0};function V(){if(typeof window=="undefined")return pe;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 me(){V().version+=1;for(let e of V().listeners)e()}function T(e){E()&&(V().sections=[...e],me())}var H="0.35.3",L=H!=="0.0.0-dev"?{name:"react",version:H}:void 0;function ve(){let e=window;return e.__sentient_slot_config_overrides||(e.__sentient_slot_config_overrides={}),e.__sentient_slot_config_overrides}function b(e,t){ve()[e]=t}function J(e){window.__sentient_vocabulary_override=e}function ye(){let e=window;return e.__sentient_slot_overrides||(e.__sentient_slot_overrides={}),e.__sentient_slot_overrides}function C(e,t){ye()[e]=t}var q="sentient_editor",X="sentient_preview_cell",Q="sentient_refresh_region",D="sentient-cell-preview-bar",w="__preview__",_e=null;function Y(e){if(typeof window=="undefined"||typeof document=="undefined"||document.getElementById(D))return;let t,n,i;try{let d=new URLSearchParams(window.location.search);t=d.get(q),n=d.get(X),i=d.get(Q)}catch(d){return}if(t&&i){_e={slotId:i,token:t,base:(e!=null?e:"https://api.sentient-ui.com/v1").replace(/\/$/,"")},b(i,{kind:"arms"}),C(i,w),k();return}if(!t||!n)return;let l=n.lastIndexOf("~");if(l<=0)return;let a=n.slice(0,l),y=n.slice(l+1),_=(e!=null?e:"https://api.sentient-ui.com/v1").replace(/\/$/,"");fetch(`${_}/editor/cell-preview?slotId=${encodeURIComponent(a)}&persona=${encodeURIComponent(y)}`,{headers:{authorization:`Bearer ${t}`}}).then(async d=>{if(!d.ok){A(d.status===401?"This preview link has expired \u2014 reopen it from your dashboard.":"Couldn\u2019t load this preview \u2014 reopen it from your dashboard.");return}let r=await d.json();if(r.vocabulary&&Array.isArray(r.vocabulary.entries)&&J(r.vocabulary),r.compose!=null)b(a,{kind:"arms",compose:{[w]:r.compose}}),C(a,w);else if(r.edits!=null&&typeof r.skeletonFp=="string"&&Array.isArray(r.leafToNode))b(a,{kind:"arms",edits:{edits:r.edits,fp:r.skeletonFp,leafToNode:r.leafToNode}}),C(a,w);else if(r.blocks!=null)b(a,{kind:"arms",blocks:{[w]:r.blocks}}),C(a,w);else if(r.content!=null)b(a,{kind:"arms",content:r.content}),C(a,w);else{A("Nothing to preview in that square yet.");return}k(),A(`Previewing \u201C${r.slotName}\u201D for ${r.personaDisplay}${r.status==="review"?" \u2014 waiting for your approval":""}. Nothing is being tracked.`),setTimeout(()=>{var u;try{(u=document.querySelector(`[data-sentient-slot="${a}"]`))==null||u.scrollIntoView({block:"center"})}catch(x){}},300)}).catch(()=>A("Couldn\u2019t load this preview \u2014 check your connection and reopen it from your dashboard."))}function A(e){var l;if(document.getElementById(D))return;let t=document.createElement("div");t.id=D,Object.assign(t.style,{position:"fixed",bottom:"16px",left:"50%",transform:"translateX(-50%)",zIndex:"2147483647",display:"flex",alignItems:"center",gap:"10px",padding:"10px 14px",borderRadius:"12px",maxWidth:"90vw",background:"#111827",color:"#fff",font:"13px system-ui, sans-serif",border:"1px solid rgba(139,92,246,0.6)",boxShadow:"0 10px 34px rgba(0,0,0,0.45)"});let n=document.createElement("span");n.textContent=e;let i=document.createElement("button");i.textContent="Exit preview",Object.assign(i.style,{padding:"4px 10px",borderRadius:"999px",border:"1px solid rgba(255,255,255,0.35)",background:"transparent",color:"#fff",font:"12px system-ui, sans-serif",cursor:"pointer"}),i.onclick=()=>{let a=new URL(window.location.href);a.searchParams.delete(q),a.searchParams.delete(X),a.searchParams.delete(Q),window.location.assign(a.toString())},t.append(n,i),((l=document.body)!=null?l:document.documentElement).append(t)}var Se="sentient_editor",Z=!1;function ee(e){if(Z||typeof window=="undefined")return;let t=null;try{t=new URLSearchParams(window.location.search).get(Se)}catch(l){return}if(!t)return;Z=!0;let n=(e!=null?e:"https://api.sentient-ui.com/v1").replace(/\/$/,""),i=()=>{window.setTimeout(()=>{import("@sentientui/core/style-sample").then(({sampleStyleVocabulary:l})=>fetch(`${n}/editor/style-vocabulary`,{method:"POST",headers:{authorization:`Bearer ${t}`,"content-type":"application/json"},body:JSON.stringify(l(document))})).catch(()=>{})},1e3)};document.readyState==="complete"?i():window.addEventListener("load",i,{once:!0})}import{jsx as ke}from"react/jsx-runtime";function Ce(){var e,t;if(typeof window=="undefined")return"desktop:direct";try{return we({userAgent:(e=navigator.userAgent)!=null?e:"",referer:(t=document.referrer)!=null?t:"",appOrigin:window.location.origin})}catch(n){return"desktop:direct"}}var ne="https://api.sentient-ui.com/v1",xe=he({client:null,apiKey:"",initialAssignments:{},sessionSegment:"desktop:direct",ssrFallback:"first",onAssignment:void 0,initialLayoutOrder:null,initialSlots:{},initialSlotConfig:{},initialPalette:null,initialVocabulary:null,initialPersona:null,apiBaseUrl:ne,debug:!1});function Re(e){let[t,n]=P(!1),i=G(e);i.current=e;let{cookie:l,value:a,event:y}=e!=null?e:{},_=typeof(e==null?void 0:e.check)=="function";return v(()=>{let d=()=>{var R;let u=i.current;if(!u)return!1;if(u.check)return u.check()===!0;if(!u.cookie||typeof document=="undefined")return!1;let x=`${u.cookie}=${(R=u.value)!=null?R:"accepted"}`;return document.cookie.split("; ").some(O=>O.trim()===x)};if(n(d()),!y)return;let r=()=>{n(d())};return window.addEventListener(y,r),()=>window.removeEventListener(y,r)},[l,a,y,_]),t}function ie(e){var N,W;let[t,n]=P(null),[i]=P(()=>{var o;return(o=e.sessionSegment)!=null?o:Ce()}),[l,a]=P(I());v(()=>U(()=>a(I())),[]),v(()=>{Y(e.apiBaseUrl),ee(e.apiBaseUrl)},[]);let y=Re(e.consentFrom),_=e.consentFrom?e.consent===!0||y:e.consent,d=G(null);v(()=>{var S;if(_===!1&&!e.preConsentBehavior){(S=d.current)==null||S.destroy(),d.current=null,n(null);return}let o=m({apiKey:e.apiKey,context:e.context,debug:e.debug,initialAssignments:e.initialAssignments,sessionSegment:i,consent:_,preConsentBehavior:e.preConsentBehavior,respectDoNotTrack:e.respectDoNotTrack,ssrSessionId:e.ssrSessionId,country:e.country,persona:e.persona,localMode:e.localMode,initialSlots:e.initialSlots,initialSlotConfig:e.initialSlotConfig,initialPalette:e.initialPalette,initialVocabulary:e.initialVocabulary,initialPersona:e.initialPersona,ingestUrl:e.apiBaseUrl?`${e.apiBaseUrl.replace(/\/$/,"")}/events`:void 0},L?{sdk:L}:{}),f=!1,s=null,c=null,g=p=>{e.engagement!==!1&&import("@sentientui/core/engagement").then(({startEngagementCapture:h})=>{f||(c=h(p,{apiKey:e.apiKey,sectionTypes:e.sectionTypes,apiBase:e.apiBaseUrl?e.apiBaseUrl.replace(/\/$/,""):void 0}))})};return e.enableGraph!==!1?import("@sentientui/core/graph").then(({init:p})=>{f||(s=p($(m({},o),{graph:!0,captureDomText:e.captureDomText===!0,sectionTypes:e.sectionTypes})),d.current=s,n(s),g(s))}):(s=be(o),d.current=s,n(s),g(s)),()=>{f=!0,c==null||c(),s==null||s.dispose()}},[_]),v(()=>{if(!t)return;let o=!1,f=async()=>{if(o)return;let c;try{c=await t.fetchWeights()}catch(g){return}if(!o)for(let g of c){let S={componentId:g.componentId,updatedAt:g.updatedAt,variants:g.variants.map(p=>{var h;return{variantId:p.variantId,pulls:p.pulls,avgReward:(h=p.avgReward)!=null?h:0}})};K(g.componentId,S)}};f();let s=setInterval(()=>{f()},6e4);return()=>{o=!0,clearInterval(s)}},[t]);let r=(N=e.ssrFallback)!=null?N:"first",u=((W=e.apiBaseUrl)!=null?W:ne).replace(/\/$/,""),x=G(null);v(()=>{var s;if(typeof process!="undefined"&&((s=process.env)==null?void 0:s.NODE_ENV)==="production")return;let o={apiKey:e.apiKey,context:e.context,country:e.country,persona:e.persona,apiBaseUrl:u},f=x.current;if(x.current=o,f!==null)for(let c of["apiKey","context","country","persona","apiBaseUrl"])Object.is(f[c],o[c])||console.warn(`[sentient] AdaptiveProvider: \`${c}\` changed after initialisation, but the SDK client is stable for the session and only re-inits on \`consent\` \u2014 the new value is ignored. Remount the provider (e.g. via a changing \`key\` prop) to apply it.`)},[e.apiKey,e.context,e.country,e.persona,u]),v(()=>{var o;typeof process!="undefined"&&((o=process.env)==null?void 0:o.NODE_ENV)==="production"||j({apiKey:e.apiKey,apiBaseUrl:u,isLocal:(t==null?void 0:t.isLocal)===!0})},[t,e.apiKey,u]),v(()=>{let o=e.initialLayoutOrder;if(o&&o.length>0){T(o);return}e.declaredSections&&e.declaredSections.length>0&&T(e.declaredSections)},[e.initialLayoutOrder,e.declaredSections]),v(()=>{if(!E())return;let o=e.declaredSections;if(!o||o.length===0||typeof document=="undefined")return;let f=new Set(Array.from(document.querySelectorAll("[data-sentient-id]"),c=>c.getAttribute("data-sentient-id"))),s=o.filter(c=>!f.has(c));s.length>0&&console.warn(`[SentientUI] Declared section${s.length>1?"s":""} ${s.map(c=>`"${c}"`).join(", ")} ${s.length>1?"have":"has"} no matching data-sentient-id element, so the layout engine cannot learn what they are and will serve the same order to every persona. Add data-sentient-id="<sectionId>" to each section's element.`)},[e.declaredSections]);let R=te(()=>t&&l?z(t):t,[t,l]),O=te(()=>{var o,f,s,c,g,S,p,h;return{client:R,apiKey:e.apiKey,initialAssignments:(o=e.initialAssignments)!=null?o:{},sessionSegment:i,ssrFallback:r,onAssignment:e.onAssignment,initialLayoutOrder:(f=e.initialLayoutOrder)!=null?f:null,initialSlots:(s=e.initialSlots)!=null?s:{},initialSlotConfig:(c=e.initialSlotConfig)!=null?c:{},initialPalette:(g=e.initialPalette)!=null?g:null,initialVocabulary:(S=e.initialVocabulary)!=null?S:null,initialPersona:(p=e.initialPersona)!=null?p:null,apiBaseUrl:u,debug:(h=e.debug)!=null?h:!1}},[R,e.apiKey,e.initialAssignments,i,r,e.onAssignment,e.initialLayoutOrder,e.initialSlots,e.initialSlotConfig,e.initialPalette,e.initialVocabulary,e.initialPersona,u,e.debug]);return ke(xe.Provider,{value:O,children:e.children})}function Ee(e){return e<.3?"low":e<.7?"medium":"high"}function oe(e={}){var n,i,l;let t=window;if(t.__sentient_overrides=m({},(n=e.variants)!=null?n:{}),e.layout?t.__sentient_layout_override=e.layout:delete t.__sentient_layout_override,e.slots?t.__sentient_slot_overrides=m({},e.slots):delete t.__sentient_slot_overrides,e.slotConfig?t.__sentient_slot_config_overrides=m({},e.slotConfig):delete t.__sentient_slot_config_overrides,e.persona){t.__sentient_persona_override={persona:e.persona,confidence:(i=e.confidence)!=null?i:1};try{let a=document.documentElement;a.setAttribute("data-sentient-persona",e.persona),a.setAttribute("data-sentient-confidence",Ee((l=e.confidence)!=null?l:1))}catch(a){}}else delete t.__sentient_persona_override;k()}import{jsx as Pe}from"react/jsx-runtime";function vt(e,t={},n){return oe(t),Ae(Pe(ie,{apiKey:"pk_test",consent:!1,children:e}),n)}export{vt as renderWithSentient};
3
3
  //# sourceMappingURL=react.mjs.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sentientui/react",
3
- "version": "0.35.1",
3
+ "version": "0.35.3",
4
4
  "private": false,
5
5
  "license": "MIT",
6
6
  "sideEffects": false,
@@ -75,8 +75,8 @@
75
75
  "llms.txt"
76
76
  ],
77
77
  "dependencies": {
78
- "@sentientui/core": "0.34.1",
79
- "@sentientui/policy": "0.12.0"
78
+ "@sentientui/policy": "0.12.0",
79
+ "@sentientui/core": "0.34.3"
80
80
  },
81
81
  "peerDependencies": {
82
82
  "@testing-library/react": ">=14.0.0",