@sentientui/react 0.18.2 → 0.18.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.
@@ -108,6 +108,11 @@ type AdaptiveProviderProps = {
108
108
  * dashboard graph page. Pass `false` to keep the lean bundle only.
109
109
  */
110
110
  enableGraph?: boolean;
111
+ /**
112
+ * Include captured heading / DOM text in graph sync payloads. OFF by default.
113
+ * Only applies when graph scanning is enabled (`enableGraph` not `false`).
114
+ */
115
+ captureDomText?: boolean;
111
116
  /**
112
117
  * Behavioral engagement capture (per-section dwell/scroll + semantic section
113
118
  * registration) powering personas. ON by default — pass `false` to disable.
@@ -173,17 +178,6 @@ type AgentFeedRouteConfig = {
173
178
  };
174
179
  declare function createAgentFeed(config: AgentFeedRouteConfig): (request: Request) => Promise<Response>;
175
180
 
176
- type CrawlerRequestEntry = {
177
- path: string;
178
- userAgent: string | null;
179
- botName: string;
180
- };
181
- type SentientAgentMiddlewareConfig = {
182
- /** Best-effort sink — persist to `crawler_requests` here. Failures are swallowed. */
183
- onCrawler: (entry: CrawlerRequestEntry) => void | Promise<void>;
184
- };
185
- declare function sentientAgentMiddleware(config: SentientAgentMiddlewareConfig): (request: Request) => Promise<boolean>;
186
-
187
181
  type PreloadComponent = {
188
182
  id: string;
189
183
  variantIds: string[];
@@ -233,6 +227,18 @@ type AdaptiveRootProps = Omit<AdaptiveProviderProps, 'initialAssignments' | 'onA
233
227
  /** Structured page content. Falls back to the `defineAgentContent` registry for this path. */
234
228
  content?: Record<string, unknown>;
235
229
  };
230
+ /**
231
+ * When true (default), a known AI-agent fetch (matched by user-agent —
232
+ * GPTBot, ChatGPT-User, Claude-User, PerplexityBot, …) is logged server-side
233
+ * to your agent analytics. Machine telemetry only (no cookie, no session);
234
+ * fire-and-forget, never affects render. Set false to opt out.
235
+ */
236
+ captureAgents?: boolean;
237
+ /**
238
+ * CSP nonce for the inline persona (and optional agent JSON-LD) scripts.
239
+ * Pass through from Next.js middleware / `headers()` when using a strict CSP.
240
+ */
241
+ nonce?: string;
236
242
  children: ReactNode;
237
243
  };
238
244
  /**
@@ -267,4 +273,4 @@ type AdaptiveRootProps = Omit<AdaptiveProviderProps, 'initialAssignments' | 'onA
267
273
  */
268
274
  declare function AdaptiveRoot(props: AdaptiveRootProps): Promise<JSX.Element>;
269
275
 
270
- export { AdaptiveRoot, type AdaptiveRootProps, type AgentFeed, type AgentFeedReadEntry, type AgentFeedRouteConfig, type CrawlerRequestEntry, type PreloadComponent, type SentientAgentMiddlewareConfig, buildAgentFeed as buildAgentFeedFor, createAgentFeed, defineAgentContent, sentientAgentMiddleware };
276
+ export { AdaptiveRoot, type AdaptiveRootProps, type AgentFeed, type AgentFeedReadEntry, type AgentFeedRouteConfig, type PreloadComponent, buildAgentFeed as buildAgentFeedFor, createAgentFeed, defineAgentContent };
@@ -1,4 +1,4 @@
1
- var te=Object.defineProperty,ne=Object.defineProperties;var re=Object.getOwnPropertyDescriptors;var I=Object.getOwnPropertySymbols;var T=Object.prototype.hasOwnProperty,j=Object.prototype.propertyIsEnumerable;var K=(e,t,n)=>t in e?te(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,m=(e,t)=>{for(var n in t||(t={}))T.call(t,n)&&K(e,n,t[n]);if(I)for(var n of I(t))j.call(t,n)&&K(e,n,t[n]);return e},S=(e,t)=>ne(e,re(t));var J=(e,t)=>{var n={};for(var r in e)T.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&I)for(var r of I(e))t.indexOf(r)<0&&j.call(e,r)&&(n[r]=e[r]);return n};import{deriveSessionSegment as Se}from"@sentientui/core";import{cookies as ve,headers as ke}from"next/headers";import{renderPrePaintScript as se}from"@sentientui/core";import{confidenceBand as oe}from"@sentientui/policy";import{jsx as ae}from"react/jsx-runtime";function $(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",'+$(e.persona.persona)+');d.setAttribute("data-sentient-confidence",'+$(oe(e.persona.confidence))+");}catch(e){}})();":se(e.apiKey)}function q(e){return ae("script",{"data-sentient-persona-script":"",dangerouslySetInnerHTML:{__html:ie(e)}})}import{preloadAssignments as de,readSessionCookie as ce}from"@sentientui/core/server";import{preloadDecisions as Ne}from"@sentientui/core/server";function V(){return typeof crypto!="undefined"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`snt-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}async function H(e,t){var s,i,o;let n=(o=(i=ce(t.cookies))!=null?i:(s=t.createSessionId)==null?void 0:s.call(t))!=null?o:V();return{assignments:await de(e,n,{apiKey:t.apiKey,baseUrl:t.baseUrl,origin:t.origin,userAgent:t.userAgent,referer:t.referer,doNotTrack:t.doNotTrack,timeoutMs:t.timeoutMs}),sessionId:n}}async function W(e){var o,a,p,b,c,g,u,f,A,y;let{preloadDecisions:t,readSessionCookie:n}=await import("@sentientui/core/server"),r=(p=(a=n(e.cookies))!=null?a:(o=e.createSessionId)==null?void 0:o.call(e))!=null?p:V();if(!(typeof e.apiKey=="string"&&e.apiKey.startsWith("pk_"))){let v={layoutOrder:(b=e.sections)!=null?b:[],assignments:{},slots:{},persona:"unknown",confidence:0,sessionId:r};try{let k=await import("@sentientui/core/local");if(!k.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."),v;let l=k.createLocalEngine({sessionId:r}).decide({sections:e.sections,components:(c=e.components)!=null?c:[],slots:(g=e.slots)!=null?g:[]});return{layoutOrder:(f=(u=l.layoutOrder)!=null?u:e.sections)!=null?f:[],assignments:l.assignments,slots:l.slots,persona:l.persona,confidence:l.confidence,sessionId:r}}catch(k){return v}}let i=await t({sections:e.sections,components:(A=e.components)!=null?A:[],slots:(y=e.slots)!=null?y:[]},r,{apiKey:e.apiKey,baseUrl:e.baseUrl,origin:e.origin,userAgent:e.userAgent,referer:e.referer,doNotTrack:e.doNotTrack,timeoutMs:e.timeoutMs});return S(m({},i),{sessionId:r})}import{AdaptiveRootClient as he}from"./adaptive-root-client.js";var ge=["page","blocks","layoutOrder"],X=new Map;function le(e,t){X.set(e,t)}function pe(e){return X.get(e)}function P(e){var s,i;let t=(i=(s=e.content)!=null?s:pe(e.page))!=null?i:{},n={};for(let[o,a]of Object.entries(t))ge.includes(o)||(n[o]=a);let r=S(m({},n),{page:e.page,blocks:e.blocks});return e.layoutOrder&&(r.layoutOrder=e.layoutOrder),r}function G(e){return JSON.stringify(m({"@context":"https://schema.org","@type":"WebPage"},e)).replace(/</g,"\\u003c")}function Y(e){let t=[];e.title&&t.push(`# ${e.title}`,""),e.summary&&t.push(String(e.summary),"");for(let[n,r]of Object.entries(e))["page","title","summary","blocks","layoutOrder"].includes(n)||t.push(`## ${n}`,"","```json",JSON.stringify(r,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 oe=Object.defineProperty,ie=Object.defineProperties;var ae=Object.getOwnPropertyDescriptors;var x=Object.getOwnPropertySymbols;var $=Object.prototype.hasOwnProperty,V=Object.prototype.propertyIsEnumerable;var J=(e,t,n)=>t in e?oe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,A=(e,t)=>{for(var n in t||(t={}))$.call(t,n)&&J(e,n,t[n]);if(x)for(var n of x(t))V.call(t,n)&&J(e,n,t[n]);return e},h=(e,t)=>ie(e,ae(t));var H=(e,t)=>{var n={};for(var s in e)$.call(e,s)&&t.indexOf(s)<0&&(n[s]=e[s]);if(e!=null&&x)for(var s of x(e))t.indexOf(s)<0&&V.call(e,s)&&(n[s]=e[s]);return n};import{deriveSessionSegment as ve,matchedAgentToken as ke}from"@sentientui/core";import{cookies as be,headers as Re}from"next/headers";import{renderPrePaintScript as ce}from"@sentientui/core";import{confidenceBand as de}from"@sentientui/policy";import{jsx as pe}from"react/jsx-runtime";function W(e){return JSON.stringify(e).replace(/</g,"\\u003c")}function ge(e){return e.persona?'(function(){try{var d=document.documentElement;if(d.hasAttribute("data-sentient-persona"))return;d.setAttribute("data-sentient-persona",'+W(e.persona.persona)+');d.setAttribute("data-sentient-confidence",'+W(de(e.persona.confidence))+");}catch(e){}})();":ce(e.apiKey)}function X(e){return pe("script",{"data-sentient-persona-script":"",nonce:e.nonce,dangerouslySetInnerHTML:{__html:ge(e)}})}import{preloadAssignments as le,readSessionCookie as ue}from"@sentientui/core/server";import{preloadDecisions as Ue}from"@sentientui/core/server";function q(){return typeof crypto!="undefined"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`snt-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}async function G(e,t){var r,o,i;let n=(i=(o=ue(t.cookies))!=null?o:(r=t.createSessionId)==null?void 0:r.call(t))!=null?i:q();return{assignments:await le(e,n,{apiKey:t.apiKey,baseUrl:t.baseUrl,origin:t.origin,userAgent:t.userAgent,referer:t.referer,doNotTrack:t.doNotTrack,timeoutMs:t.timeoutMs}),sessionId:n}}async function z(e){var i,a,p,R,S,I,c,l,m,y;let{preloadDecisions:t,readSessionCookie:n}=await import("@sentientui/core/server"),s=(p=(a=n(e.cookies))!=null?a:(i=e.createSessionId)==null?void 0:i.call(e))!=null?p:q();if(!(typeof e.apiKey=="string"&&e.apiKey.startsWith("pk_"))){let d={layoutOrder:(R=e.sections)!=null?R:[],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."),d;let u=f.createLocalEngine({sessionId:s}).decide({sections:e.sections,components:(S=e.components)!=null?S:[],slots:(I=e.slots)!=null?I:[]});return{layoutOrder:(l=(c=u.layoutOrder)!=null?c:e.sections)!=null?l:[],assignments:u.assignments,slots:u.slots,persona:u.persona,confidence:u.confidence,sessionId:s}}catch(f){return d}}let o=await t({sections:e.sections,components:(m=e.components)!=null?m:[],slots:(y=e.slots)!=null?y:[]},s,{apiKey:e.apiKey,baseUrl:e.baseUrl,origin:e.origin,userAgent:e.userAgent,referer:e.referer,doNotTrack:e.doNotTrack,timeoutMs:e.timeoutMs});return h(A({},o),{sessionId:s})}import{AdaptiveRootClient as Ie}from"./adaptive-root-client.js";var me=["page","blocks","layoutOrder"],Y=new Map;function fe(e,t){Y.set(e,t)}function Ae(e){return Y.get(e)}function w(e){var r,o;let t=(o=(r=e.content)!=null?r:Ae(e.page))!=null?o:{},n={};for(let[i,a]of Object.entries(t))me.includes(i)||(n[i]=a);let s=h(A({},n),{page:e.page,blocks:e.blocks});return e.layoutOrder&&(s.layoutOrder=e.layoutOrder),s}function Q(e){return JSON.stringify(A({"@context":"https://schema.org","@type":"WebPage"},e)).replace(/</g,"\\u003c")}function Z(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
- `}import{matchedAgentToken as ue}from"@sentientui/core";function me(e,t){return e.pathname.endsWith(".md")||t.toLowerCase().includes("text/markdown")}function fe(e){return async t=>{var a;let n=new URL(t.url),r=(a=t.headers.get("accept"))!=null?a:"",s=t.headers.get("user-agent"),i=n.pathname.replace(/\.(md|json)$/,"");if(e.onRead)try{Promise.resolve(e.onRead({path:i,userAgent:s,botName:ue(s!=null?s:"")})).catch(()=>{})}catch(p){}let o=await e.getFeed(t);return me(n,r)?new Response(Y(o),{headers:{"content-type":"text/markdown; charset=utf-8"}}):new Response(JSON.stringify(o),{headers:{"content-type":"application/json; charset=utf-8"}})}}import{matchedAgentToken as Ae}from"@sentientui/core";function ye(e){return async t=>{let n=t.headers.get("user-agent"),r=Ae(n!=null?n:"");if(!r)return!1;try{let s=new URL(t.url).pathname;await Promise.resolve(e.onCrawler({path:s,userAgent:n,botName:r})).catch(()=>{})}catch(s){}return!0}}import{Fragment as z,jsx as O,jsxs as Q}from"react/jsx-runtime";var Re="https://api.sentient-ui.com/v1";function we(e){return Object.entries(e).map(([t,n])=>{var r;return{id:t,variant:typeof n=="string"?n:(r=n==null?void 0:n.variantId)!=null?r:""}})}async function We(e){var D,M,_,U,B;let C=e,{components:t=[],sections:n,slots:r,appOrigin:s,initialAssignments:i,ssrSessionId:o,timeoutMs:a,agentFeed:p,children:b}=C,c=J(C,["components","sections","slots","appOrigin","initialAssignments","ssrSessionId","timeoutMs","agentFeed","children"]),g=await ke(),u=g.get("host");!s&&process.env.NODE_ENV==="production"&&!u&&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=s!=null?s:process.env.NODE_ENV==="production"?`https://${u!=null?u:"localhost"}`:"http://localhost:3001",A=(D=g.get("user-agent"))!=null?D:void 0,y=(M=g.get("referer"))!=null?M:void 0,v=g.get("dnt")==="1"||g.get("sec-gpc")==="1",k=Se({userAgent:A,referer:y,appOrigin:f}),l=await ve(),L=c.apiBaseUrl?c.apiBaseUrl.replace(/\/$/,""):Re,h,R=null,E,w=null,x;if(i)h=i,x=o;else if(n&&n.length>0||r&&r.length>0){let d=await W({sections:n!=null?n:[],components:t,slots:r,cookies:l,apiKey:c.apiKey,baseUrl:L,origin:f,userAgent:A,referer:y,doNotTrack:v,timeoutMs:a});h=d.assignments,R=d.layoutOrder,E=d.slots,w=d.persona!==void 0?{persona:d.persona,confidence:(_=d.confidence)!=null?_:0}:null,x=d.sessionId}else{let d=await H(t,{cookies:l,apiKey:c.apiKey,baseUrl:L,origin:f,userAgent:A,referer:y,doNotTrack:v,timeoutMs:a});h=d.assignments,x=d.sessionId}let F=O(q,{apiKey:c.apiKey,persona:w}),N=O(he,S(m({},c),{initialAssignments:h,initialLayoutOrder:R,initialSlots:E,initialPersona:w!=null?w:void 0,sessionSegment:k,ssrSessionId:x,children:b}));if(!p)return Q(z,{children:[F,N]});let Z=(B=(U=p.path)!=null?U:g.get("x-pathname"))!=null?B:"/",ee=P({page:Z,blocks:we(h),layoutOrder:R!=null?R:void 0,content:p.content});return Q(z,{children:[F,O("script",{type:"application/ld+json",dangerouslySetInnerHTML:{__html:G(ee)}}),N]})}export{We as AdaptiveRoot,P as buildAgentFeedFor,fe as createAgentFeed,le as defineAgentContent,ye as sentientAgentMiddleware};
3
+ `}function ee(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 ye}from"@sentientui/core";function he(e,t){return e.pathname.endsWith(".md")||t.toLowerCase().includes("text/markdown")}function Se(e){return async t=>{var a;let n=new URL(t.url),s=(a=t.headers.get("accept"))!=null?a:"",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:ye(r!=null?r:"")})).catch(()=>{})}catch(p){}let i=await e.getFeed(t);return he(n,s)?new Response(Z(i),{headers:{"content-type":"text/markdown; charset=utf-8"}}):new Response(JSON.stringify(i),{headers:{"content-type":"application/json; charset=utf-8"}})}}import{Fragment as te,jsx as L,jsxs as ne}from"react/jsx-runtime";var Oe="https://api.sentient-ui.com/v1";function xe(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 ze(e){var C,B,T,M,j;let _=e,{components:t=[],sections:n,slots:s,appOrigin:r,initialAssignments:o,ssrSessionId:i,timeoutMs:a,agentFeed:p,captureAgents:R,nonce:S,children:I}=_,c=H(_,["components","sections","slots","appOrigin","initialAssignments","ssrSessionId","timeoutMs","agentFeed","captureAgents","nonce","children"]),l=await Re(),m=l.get("host");!r&&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 y=r!=null?r:process.env.NODE_ENV==="production"?`https://${m!=null?m:"localhost"}`:"http://localhost:3001",d=(C=l.get("user-agent"))!=null?C:void 0,f=(B=l.get("referer"))!=null?B:void 0,u=l.get("dnt")==="1"||l.get("sec-gpc")==="1",se=ve({userAgent:d,referer:f,appOrigin:y}),F=await be(),P=c.apiBaseUrl?c.apiBaseUrl.replace(/\/$/,""):Oe,N=(M=(T=p==null?void 0:p.path)!=null?T:l.get("x-pathname"))!=null?M:"/",E=ke(d!=null?d:"");R!==!1&&E&&ee({baseUrl:P,apiKey:c.apiKey,path:N,botName:E,userAgent:d});let v,k=null,D,b=null,O;if(o)v=o,O=i;else if(n&&n.length>0||s&&s.length>0){let g=await z({sections:n!=null?n:[],components:t,slots:s,cookies:F,apiKey:c.apiKey,baseUrl:P,origin:y,userAgent:d,referer:f,doNotTrack:u,timeoutMs:a});v=g.assignments,k=g.layoutOrder,D=g.slots,b=g.persona!==void 0?{persona:g.persona,confidence:(j=g.confidence)!=null?j:0}:null,O=g.sessionId}else{let g=await G(t,{cookies:F,apiKey:c.apiKey,baseUrl:P,origin:y,userAgent:d,referer:f,doNotTrack:u,timeoutMs:a});v=g.assignments,O=g.sessionId}let K=L(X,{apiKey:c.apiKey,persona:b,nonce:S}),U=L(Ie,h(A({},c),{initialAssignments:v,initialLayoutOrder:k,initialSlots:D,initialPersona:b!=null?b:void 0,sessionSegment:se,ssrSessionId:O,children:I}));if(!p)return ne(te,{children:[K,U]});let re=w({page:N,blocks:xe(v),layoutOrder:k!=null?k:void 0,content:p.content});return ne(te,{children:[K,L("script",{type:"application/ld+json",nonce:S,dangerouslySetInnerHTML:{__html:Q(re)}}),U]})}export{ze as AdaptiveRoot,w as buildAgentFeedFor,Se as createAgentFeed,fe as defineAgentContent};
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/agent-feed-route.ts","../../src/next/agent-middleware.ts"],"sourcesContent":["import { deriveSessionSegment } from '@sentientui/core';\nimport type { SlotDeclInput, SlotResult } from '@sentientui/core';\nimport { cookies, headers } from 'next/headers';\nimport type { ReactNode } from 'react';\nimport type { AdaptiveProviderProps } from '../provider.js';\nimport { SentientPersonaScript } from '../persona-script.js';\nimport {\n loadAdaptiveAssignments,\n loadAdaptiveDecision,\n type ServerAssignments,\n} from '../server.js';\nimport { AdaptiveRootClient } from './adaptive-root-client.js';\nimport { buildAgentFeed, renderAgentJsonLdBody, type AgentBlock } from '../agent-feed.js';\n\nexport { createAgentFeed } from './agent-feed-route.js';\nexport type { AgentFeedRouteConfig, AgentFeedReadEntry } from './agent-feed-route.js';\nexport { sentientAgentMiddleware } from './agent-middleware.js';\nexport type { SentientAgentMiddlewareConfig, CrawlerRequestEntry } from './agent-middleware.js';\nexport { defineAgentContent, buildAgentFeed as buildAgentFeedFor } from '../agent-feed.js';\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 'initialAssignments' | 'onAssignment' | 'initialSlots' | 'initialPersona'\n> & {\n /**\n * Components to assign server-side (SEO-safe). Optional — omit when the\n * tree uses only slots/sections, or assigns client-side via hooks.\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 * @example sections={['hero', 'pricing', 'features', 'social_proof']}\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 /** App origin — must be in the project's `allowed_origins`. */\n appOrigin?: 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 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\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 * context=\"landing\"\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 appOrigin,\n initialAssignments: initialAssignmentsOverride,\n ssrSessionId: ssrSessionIdProp,\n timeoutMs,\n agentFeed,\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 // 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 const sessionSegment = deriveSessionSegment({ userAgent, referer, appOrigin: resolvedOrigin });\n const cookieStore = await cookies();\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 let initialAssignments: ServerAssignments;\n let initialLayoutOrder: string[] | null = null;\n let initialSlots: Record<string, SlotResult> | undefined;\n let initialPersona: { persona: string; confidence: number } | null = null;\n let ssrSessionId: string | undefined;\n\n if (initialAssignmentsOverride) {\n initialAssignments = initialAssignmentsOverride;\n ssrSessionId = ssrSessionIdProp;\n } else if ((sections && sections.length > 0) || (slots && slots.length > 0)) {\n const decision = await loadAdaptiveDecision({\n sections: sections ?? [],\n components,\n slots,\n cookies: cookieStore,\n apiKey: providerProps.apiKey,\n baseUrl,\n origin: resolvedOrigin,\n userAgent,\n referer,\n doNotTrack,\n timeoutMs,\n });\n initialAssignments = decision.assignments;\n initialLayoutOrder = decision.layoutOrder;\n initialSlots = decision.slots;\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 doNotTrack,\n timeoutMs,\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} />\n );\n\n const client = (\n <AdaptiveRootClient\n {...providerProps}\n initialAssignments={initialAssignments}\n initialLayoutOrder={initialLayoutOrder}\n initialSlots={initialSlots}\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 path = agentFeed.path ?? headerStore.get('x-pathname') ?? '/';\n const feed = buildAgentFeed({\n page: path,\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 dangerouslySetInnerHTML={{ __html: renderAgentJsonLdBody(feed) }}\n />\n {client}\n </>\n );\n}\n","import { 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 * 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 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 /** 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\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 const sessionId =\n readSessionCookie(options.cookies) ??\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 doNotTrack: options.doNotTrack,\n timeoutMs: options.timeoutMs,\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};\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 const sessionId =\n readSessionCookie(options.cookies) ??\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 },\n sessionId,\n {\n apiKey: options.apiKey,\n baseUrl: options.baseUrl,\n origin: options.origin,\n userAgent: options.userAgent,\n referer: options.referer,\n doNotTrack: options.doNotTrack,\n timeoutMs: options.timeoutMs,\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","/**\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","/**\n * `sentientAgentMiddleware` — additive-discovery middleware. Detects known AI\n * crawler / agent user-agents on page requests and reports them so they can be\n * logged to `crawler_requests` (the only way to observe passive crawlers, which\n * run no JS and never create a session). It NEVER changes the response — the\n * caller composes it into their Next.js middleware and returns `NextResponse.next()`.\n *\n * export async function middleware(request: NextRequest) {\n * await logCrawler(request); // sentientAgentMiddleware instance\n * return NextResponse.next();\n * }\n */\nimport { matchedAgentToken } from '@sentientui/core';\n\nexport type CrawlerRequestEntry = {\n path: string;\n userAgent: string | null;\n botName: string;\n};\n\nexport type SentientAgentMiddlewareConfig = {\n /** Best-effort sink — persist to `crawler_requests` here. Failures are swallowed. */\n onCrawler: (entry: CrawlerRequestEntry) => void | Promise<void>;\n};\n\nexport function sentientAgentMiddleware(\n config: SentientAgentMiddlewareConfig,\n): (request: Request) => Promise<boolean> {\n return async (request: Request): Promise<boolean> => {\n const userAgent = request.headers.get('user-agent');\n const botName = matchedAgentToken(userAgent ?? '');\n if (!botName) return false;\n\n try {\n const path = new URL(request.url).pathname;\n await Promise.resolve(config.onCrawler({ path, userAgent, botName })).catch(() => {});\n } catch {\n /* detection/logging must never break the request */\n }\n return true;\n };\n}\n"],"mappings":"qlBAAA,OAAS,wBAAAA,OAA4B,mBAErC,OAAS,WAAAC,GAAS,WAAAC,OAAe,eCFjC,OAAS,wBAAAC,OAA4B,mBACrC,OAAS,kBAAAC,OAAsB,qBA8C3B,cAAAC,OAAA,oBAhCJ,SAASC,EAAeC,EAAuB,CAC7C,OAAO,KAAK,UAAUA,CAAK,EAAE,QAAQ,KAAM,SAAS,CACtD,CAGO,SAASC,GAAkBC,EAA2C,CAC3E,OAAIA,EAAM,QAEN,2IAE4CH,EAAeG,EAAM,QAAQ,OAAO,EAAI,+CACrCH,EAAeF,GAAeK,EAAM,QAAQ,UAAU,CAAC,EAAI,qBAIvGN,GAAqBM,EAAM,MAAM,CAC1C,CAcO,SAASC,EAAsBD,EAAgD,CACpF,OACEJ,GAAC,UACC,+BAA6B,GAC7B,wBAAyB,CAAE,OAAQG,GAAkBC,CAAK,CAAE,EAC9D,CAEJ,CCjDA,OACE,sBAAAE,GACA,qBAAAC,OAGK,0BAiEP,OAAS,oBAAAC,OAAwB,0BAlCjC,SAASC,GAA2B,CAClC,OAAI,OAAO,QAAW,aAAe,OAAO,OAAO,YAAe,WACzD,OAAO,WAAW,EAEpB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AU,OAAV,KAAAT,EAAkBa,EAAY,IAAI,YAAY,IAA9C,KAAAZ,EAAmD,IAC1DwC,GAAOC,EAAe,CAC1B,KAAMF,EACN,OAAQlD,GAAoBmC,CAAkB,EAC9C,YAAaC,GAAA,KAAAA,EAAsB,OACnC,QAASjB,EAAU,OACrB,CAAC,EAED,OACErB,EAAAF,EAAA,CACG,UAAAgD,EACD/C,EAAC,UACC,KAAK,sBACL,wBAAyB,CAAE,OAAQwD,EAAsBF,EAAI,CAAE,EACjE,EACCL,GACH,CAEJ","names":["deriveSessionSegment","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","matchedAgentToken","wantsMarkdown","url","accept","createAgentFeed","config","request","_a","userAgent","path","matchedAgentToken","e","feed","renderAgentMarkdown","matchedAgentToken","sentientAgentMiddleware","config","request","userAgent","botName","path","e","Fragment","jsx","jsxs","DEFAULT_API_BASE_URL","assignmentsToBlocks","assignments","id","v","_a","AdaptiveRoot","props","_b","_c","_d","_e","_f","components","sections","slots","appOrigin","initialAssignmentsOverride","ssrSessionIdProp","timeoutMs","agentFeed","children","providerProps","__objRest","headerStore","headers","host","resolvedOrigin","userAgent","referer","doNotTrack","sessionSegment","deriveSessionSegment","cookieStore","cookies","baseUrl","initialAssignments","initialLayoutOrder","initialSlots","initialPersona","ssrSessionId","decision","loadAdaptiveDecision","result","loadAdaptiveAssignments","personaScript","SentientPersonaScript","client","AdaptiveRootClient","__spreadProps","__spreadValues","path","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, matchedAgentToken } from '@sentientui/core';\nimport type { SlotDeclInput, SlotResult } from '@sentientui/core';\nimport { cookies, headers } from 'next/headers';\nimport type { ReactNode } from 'react';\nimport type { AdaptiveProviderProps } from '../provider.js';\nimport { SentientPersonaScript } from '../persona-script.js';\nimport {\n loadAdaptiveAssignments,\n loadAdaptiveDecision,\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';\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 'initialAssignments' | 'onAssignment' | 'initialSlots' | 'initialPersona'\n> & {\n /**\n * Components to assign server-side (SEO-safe). Optional — omit when the\n * tree uses only slots/sections, or assigns client-side via hooks.\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 * @example sections={['hero', 'pricing', 'features', 'social_proof']}\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 /** App origin — must be in the project's `allowed_origins`. */\n appOrigin?: 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\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 * context=\"landing\"\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 appOrigin,\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 // 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 const sessionSegment = deriveSessionSegment({ userAgent, referer, appOrigin: resolvedOrigin });\n const cookieStore = await cookies();\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 initialPersona: { persona: string; confidence: number } | null = null;\n let ssrSessionId: string | undefined;\n\n if (initialAssignmentsOverride) {\n initialAssignments = initialAssignmentsOverride;\n ssrSessionId = ssrSessionIdProp;\n } else if ((sections && sections.length > 0) || (slots && slots.length > 0)) {\n const decision = await loadAdaptiveDecision({\n sections: sections ?? [],\n components,\n slots,\n cookies: cookieStore,\n apiKey: providerProps.apiKey,\n baseUrl,\n origin: resolvedOrigin,\n userAgent,\n referer,\n doNotTrack,\n timeoutMs,\n });\n initialAssignments = decision.assignments;\n initialLayoutOrder = decision.layoutOrder;\n initialSlots = decision.slots;\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 doNotTrack,\n timeoutMs,\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 initialAssignments={initialAssignments}\n initialLayoutOrder={initialLayoutOrder}\n initialSlots={initialSlots}\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","import { 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 /** 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\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 const sessionId =\n readSessionCookie(options.cookies) ??\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 doNotTrack: options.doNotTrack,\n timeoutMs: options.timeoutMs,\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};\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 const sessionId =\n readSessionCookie(options.cookies) ??\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 },\n sessionId,\n {\n apiKey: options.apiKey,\n baseUrl: options.baseUrl,\n origin: options.origin,\n userAgent: options.userAgent,\n referer: options.referer,\n doNotTrack: options.doNotTrack,\n timeoutMs: options.timeoutMs,\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":"qlBAAA,OAAS,wBAAAA,GAAsB,qBAAAC,OAAyB,mBAExD,OAAS,WAAAC,GAAS,WAAAC,OAAe,eCFjC,OAAS,wBAAAC,OAA4B,mBACrC,OAAS,kBAAAC,OAAsB,qBAoD3B,cAAAC,OAAA,oBAhCJ,SAASC,EAAeC,EAAuB,CAC7C,OAAO,KAAK,UAAUA,CAAK,EAAE,QAAQ,KAAM,SAAS,CACtD,CAGO,SAASC,GAAkBC,EAA2C,CAC3E,OAAIA,EAAM,QAEN,2IAE4CH,EAAeG,EAAM,QAAQ,OAAO,EAAI,+CACrCH,EAAeF,GAAeK,EAAM,QAAQ,UAAU,CAAC,EAAI,qBAIvGN,GAAqBM,EAAM,MAAM,CAC1C,CAcO,SAASC,EAAsBD,EAAgD,CACpF,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uB,CAAE,EAClE,KACNkC,EAAeC,EAAS,SAC1B,KAAO,CACL,IAAME,EAAS,MAAMC,EAAwBrC,EAAY,CACvD,QAASsB,EACT,OAAQX,EAAc,OACtB,QAAAa,EACA,OAAQR,EACR,UAAAC,EACA,QAAAC,EACA,WAAAC,EACA,UAAAb,CACF,CAAC,EACDuB,EAAqBO,EAAO,YAC5BH,EAAeG,EAAO,SACxB,CAIA,IAAME,EACJrD,EAACsD,EAAA,CAAsB,OAAQ5B,EAAc,OAAQ,QAASqB,EAAgB,MAAOvB,EAAO,EAGxF+B,EACJvD,EAACwD,GAAAC,EAAAC,EAAA,GACKhC,GADL,CAEC,mBAAoBkB,EACpB,mBAAoBC,EACpB,aAAcC,EACd,eAAgBC,GAAA,KAAAA,EAAkB,OAClC,eAAgBZ,GAChB,aAAca,EAEb,SAAAvB,GACH,EAGF,GAAI,CAACH,EACH,OACErB,GAAAF,GAAA,CACG,UAAAsD,EACAE,GACH,EAOJ,IAAMI,GAAOC,EAAe,CAC1B,KAAMpB,EACN,OAAQrC,GAAoByC,CAAkB,EAC9C,YAAaC,GAAA,KAAAA,EAAsB,OACnC,QAASvB,EAAU,OACrB,CAAC,EAED,OACErB,GAAAF,GAAA,CACG,UAAAsD,EACDrD,EAAC,UACC,KAAK,sBACL,MAAOwB,EACP,wBAAyB,CAAE,OAAQqC,EAAsBF,EAAI,CAAE,EACjE,EACCJ,GACH,CAEJ","names":["deriveSessionSegment","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","Fragment","jsx","jsxs","DEFAULT_API_BASE_URL","assignmentsToBlocks","assignments","id","v","_a","AdaptiveRoot","props","_b","_c","_d","_e","_f","components","sections","slots","appOrigin","initialAssignmentsOverride","ssrSessionIdProp","timeoutMs","agentFeed","captureAgents","nonce","children","providerProps","__objRest","headerStore","headers","host","resolvedOrigin","userAgent","referer","doNotTrack","sessionSegment","deriveSessionSegment","cookieStore","cookies","baseUrl","agentPath","agentBot","matchedAgentToken","logAgentFetch","initialAssignments","initialLayoutOrder","initialSlots","initialPersona","ssrSessionId","decision","loadAdaptiveDecision","result","loadAdaptiveAssignments","personaScript","SentientPersonaScript","client","AdaptiveRootClient","__spreadProps","__spreadValues","feed","buildAgentFeed","renderAgentJsonLdBody"]}
package/dist/testing.js CHANGED
@@ -1,3 +1,3 @@
1
1
  'use client';
2
- "use strict";var be=Object.create;var P=Object.defineProperty,he=Object.defineProperties,xe=Object.getOwnPropertyDescriptor,Ce=Object.getOwnPropertyDescriptors,Re=Object.getOwnPropertyNames,Q=Object.getOwnPropertySymbols,Ee=Object.getPrototypeOf,Z=Object.prototype.hasOwnProperty,ke=Object.prototype.propertyIsEnumerable;var Y=(e,t,n)=>t in e?P(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,O=(e,t)=>{for(var n in t||(t={}))Z.call(t,n)&&Y(e,n,t[n]);if(Q)for(var n of Q(t))ke.call(t,n)&&Y(e,n,t[n]);return e},ee=(e,t)=>he(e,Ce(t));var Ae=(e,t)=>{for(var n in t)P(e,n,{get:t[n],enumerable:!0})},te=(e,t,n,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Re(t))!Z.call(e,o)&&o!==n&&P(e,o,{get:()=>t[o],enumerable:!(i=xe(t,o))||i.enumerable});return e};var ne=(e,t,n)=>(n=e!=null?be(Ee(e)):{},te(t||!e||!e.__esModule?P(n,"default",{value:e,enumerable:!0}):n,e)),Pe=e=>te(P({},"__esModule",{value:!0}),e);var je={};Ae(je,{applyScenario:()=>K,clearSentientEvents:()=>fe,getSentientEvents:()=>D,hasFiredGoal:()=>ge,mockSentient:()=>ye,mockSentientCypress:()=>_e,renderWithSentient:()=>Ne,resetScenario:()=>N,resolveScenario:()=>h,scenarioToHandlers:()=>ve,setupSentientTests:()=>Fe});module.exports=Pe(je);var we=require("@testing-library/react");var d=require("react"),E=require("@sentientui/core");var Oe=new Map,Ie=new Map;function ie(e,t){Oe.set(e,t);let n=Ie.get(e);if(n)for(let i of n)try{i(t)}catch(o){}}var Le={on:!1,listeners:new Set};function oe(){if(typeof window=="undefined")return Le;let e=window;return e.__sentient_preview||(e.__sentient_preview={on:!1,listeners:new Set}),e.__sentient_preview}function T(){return oe().on}function re(e){let t=oe().listeners;return t.add(e),()=>{t.delete(e)}}function se(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),getPersona:()=>e.getPersona(),getGraph:()=>e.getGraph(),dispose:()=>e.dispose(),destroy:()=>e.destroy()}}var Ge="sentient:overrides-changed";function B(){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 ae(e){typeof window!="undefined"&&(window.__sentient_devtools_config=e)}function le(){var e;return typeof process=="undefined"||((e=process.env)==null?void 0:e.NODE_ENV)!=="production"}var De={components:new Map,slots:new Map,sections:[],listeners:new Set,version:0};function M(){if(typeof window=="undefined")return De;let e=window;return e.__sentient_registry||(e.__sentient_registry={components:new Map,slots:new Map,sections:[],listeners:new Set,version:0}),e.__sentient_registry}function We(){M().version+=1;for(let e of M().listeners)e()}function ce(e){le()&&(M().sections=[...e],We())}var pe=require("react/jsx-runtime");function Te(){var e,t;if(typeof window=="undefined")return"desktop:direct";try{let n=(0,E.detectDeviceClass)((e=navigator.userAgent)!=null?e:""),i=(0,E.detectTrafficSource)((t=document.referrer)!=null?t:"",window.location.origin);return`${n}:${i}`}catch(n){return"desktop:direct"}}var ue="https://api.sentient-ui.com/v1",Be=(0,d.createContext)({client:null,apiKey:"",initialAssignments:{},sessionSegment:"desktop:direct",ssrFallback:"first",onAssignment:void 0,initialLayoutOrder:null,initialSlots:{},initialPersona:null,apiBaseUrl:ue,debug:!1});function de(e){var S,f;let[t,n]=(0,d.useState)(null),[i]=(0,d.useState)(()=>{var r;return(r=e.sessionSegment)!=null?r:Te()}),[o,a]=(0,d.useState)(T());(0,d.useEffect)(()=>re(()=>a(T())),[]),(0,d.useEffect)(()=>{if(e.consent===!1&&!e.preConsentBehavior){n(w=>(w==null||w.destroy(),null));return}let r={apiKey:e.apiKey,context:e.context,debug:e.debug,initialAssignments:e.initialAssignments,sessionSegment:i,consent:e.consent,preConsentBehavior:e.preConsentBehavior,respectDoNotTrack:e.respectDoNotTrack,ssrSessionId:e.ssrSessionId,country:e.country,localMode:e.localMode,initialSlots:e.initialSlots,initialPersona:e.initialPersona,ingestUrl:e.apiBaseUrl?`${e.apiBaseUrl.replace(/\/$/,"")}/events`:void 0},u=!1,s=null,g=null,_=w=>{e.engagement!==!1&&import("@sentientui/core/engagement").then(({startEngagementCapture:b})=>{u||(g=b(w,{apiKey:e.apiKey,apiBase:e.apiBaseUrl?e.apiBaseUrl.replace(/\/$/,""):void 0}))})};return e.enableGraph!==!1?import("@sentientui/core/graph").then(({init:w})=>{u||(s=w(ee(O({},r),{graph:!0})),n(s),_(s))}):(s=(0,E.init)(r),n(s),_(s)),()=>{u=!0,g==null||g(),s==null||s.dispose()}},[e.consent]),(0,d.useEffect)(()=>{if(!t)return;let r=!1,u=async()=>{if(r)return;let g;try{g=await t.fetchWeights()}catch(_){return}if(!r)for(let _ of g){let w={componentId:_.componentId,updatedAt:_.updatedAt,variants:_.variants.map(b=>{var k;return{variantId:b.variantId,pulls:b.pulls,avgReward:(k=b.avgReward)!=null?k:0}})};ie(_.componentId,w)}};u();let s=setInterval(()=>{u()},6e4);return()=>{r=!0,clearInterval(s)}},[t]);let v=(S=e.ssrFallback)!=null?S:"first",c=((f=e.apiBaseUrl)!=null?f:ue).replace(/\/$/,""),l=(0,d.useRef)(null);(0,d.useEffect)(()=>{var s;if(typeof process!="undefined"&&((s=process.env)==null?void 0:s.NODE_ENV)==="production")return;let r={apiKey:e.apiKey,context:e.context,country:e.country,apiBaseUrl:c},u=l.current;if(l.current=r,u!==null)for(let g of["apiKey","context","country","apiBaseUrl"])Object.is(u[g],r[g])||console.warn(`[sentient] AdaptiveProvider: \`${g}\` 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,c]),(0,d.useEffect)(()=>{var r;typeof process!="undefined"&&((r=process.env)==null?void 0:r.NODE_ENV)==="production"||ae({apiKey:e.apiKey,apiBaseUrl:c,isLocal:(t==null?void 0:t.isLocal)===!0})},[t,e.apiKey,c]),(0,d.useEffect)(()=>{e.initialLayoutOrder&&e.initialLayoutOrder.length>0&&ce(e.initialLayoutOrder)},[e.initialLayoutOrder]);let p=(0,d.useMemo)(()=>t&&o?se(t):t,[t,o]),y=(0,d.useMemo)(()=>{var r,u,s,g,_;return{client:p,apiKey:e.apiKey,initialAssignments:(r=e.initialAssignments)!=null?r:{},sessionSegment:i,ssrFallback:v,onAssignment:e.onAssignment,initialLayoutOrder:(u=e.initialLayoutOrder)!=null?u:null,initialSlots:(s=e.initialSlots)!=null?s:{},initialPersona:(g=e.initialPersona)!=null?g:null,apiBaseUrl:c,debug:(_=e.debug)!=null?_:!1}},[p,e.apiKey,e.initialAssignments,i,v,e.onAssignment,e.initialLayoutOrder,e.initialSlots,e.initialPersona,c,e.debug]);return(0,pe.jsx)(Be.Provider,{value:y,children:e.children})}function I(e){return e<.3?"low":e<.7?"medium":"high"}function K(e={}){var n,i,o;let t=window;if(t.__sentient_overrides=O({},(n=e.variants)!=null?n:{}),e.layout?t.__sentient_layout_override=e.layout:delete t.__sentient_layout_override,e.slots?t.__sentient_slot_overrides=O({},e.slots):delete t.__sentient_slot_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",I((o=e.confidence)!=null?o:1))}catch(a){}}else delete t.__sentient_persona_override;B()}function N(){let e=window;delete e.__sentient_overrides,delete e.__sentient_layout_override,delete e.__sentient_slot_overrides,delete e.__sentient_persona_override;try{document.documentElement.removeAttribute("data-sentient-persona"),document.documentElement.removeAttribute("data-sentient-confidence")}catch(t){}B()}var L=require("msw");var F=[];function j(e){F.push(e)}function D(){return[...F]}function fe(){F.length=0}function ge(e,t){return e.some(n=>(n.eventType==="goal_achieved"||n.eventType==="goal")&&n.goalType===t)}function Me(e){var t;try{return new URL(e).pathname}catch(n){return(t=e.split("?")[0])!=null?t:e}}async function Ke(e,t){var i,o,a;let n=(i=e.api)==null?void 0:i[t];return n===void 0?null:n==="error"?{status:500}:typeof n=="number"?{status:n}:(n.delayMs&&await new Promise(v=>setTimeout(v,n.delayMs)),{status:(o=n.status)!=null?o:200,json:(a=n.body)!=null?a:{}})}async function h(e,t,n,i){var l,p,y,S,f,r,u,s,g,_,w,b,k,U,V,H,$,z,J,X,q;let o=Me(n);if(!o.includes("/v1/"))return null;let a="/v1/"+((l=o.split("/v1/")[1])!=null?l:""),v=await Ke(e,a);if(v)return v;let c=i?JSON.parse(i):{};if(a==="/v1/sessions")return{status:204};if(a==="/v1/events"){for(let m of c)j(m);return{status:204}}if(a==="/v1/goals")return j({eventType:"goal",goalType:c.name}),{status:204};if(a==="/v1/assign"){let m=c;return{status:200,json:{variantId:(f=(S=(p=e.variants)==null?void 0:p[m.componentId])!=null?S:(y=m.variantIds)==null?void 0:y[0])!=null?f:"control",assignmentTtlMs:6e4}}}if(a==="/v1/decide"){let m=c,x={layoutOrder:(u=e.layout)!=null?u:((r=m.sections)!=null?r:[]).map(C=>C.id),assignments:(s=e.variants)!=null?s:{},persona:(g=e.persona)!=null?g:"unknown",confidence:(_=e.confidence)!=null?_:1};if(m.slots&&m.slots.length>0){let C={};for(let R of m.slots)C[R.id]=(b=(w=e.slots)==null?void 0:w[R.id])!=null?b:me(R);x.slots=C}return{status:200,json:x}}if(a==="/v1/explain"){let m=c,A=(U=e.layout)!=null?U:((k=m.sections)!=null?k:[]).map(G=>G.id),x=(H=(V=m.persona)!=null?V:e.persona)!=null?H:"unknown",C=($=e.confidence)!=null?$:1,R={layoutOrder:A,assignments:(z=e.variants)!=null?z:{},persona:x,reasons:[],personaAttributes:{persona:x,confidence:I(C)}};if(m.slots&&m.slots.length>0){let G={};for(let W of m.slots)G[W.id]=(X=(J=e.slots)==null?void 0:J[W.id])!=null?X:me(W);R.slots=G}return{status:200,json:R}}return a==="/v1/weights"?{status:200,json:{components:Object.entries((q=e.weights)!=null?q:{}).map(([A,x])=>({componentId:A,updatedAt:0,variants:x}))}}:null}function me(e){var n,i,o;if(e.arms)return typeof e.baseline=="string"?e.baseline:(n=e.arms[0])!=null?n:"baseline";let t={};for(let[a,v]of Object.entries((i=e.dims)!=null?i:{})){let c=typeof e.baseline=="object"&&e.baseline!==null?e.baseline[a]:void 0;t[a]=(o=c!=null?c:v[0])!=null?o:""}return t}function ve(e={}){return[L.http.all("*/v1/*",async({request:t})=>{let n=t.method==="GET"||t.method==="HEAD"?null:await t.text(),i=await h(e,t.method,t.url,n);if(i)return i.json===void 0?new L.HttpResponse(null,{status:i.status}):L.HttpResponse.json(i.json,{status:i.status})})]}async function ye(e,t={}){var i,o,a,v,c;let n={overrides:(i=t.variants)!=null?i:{},layout:(o=t.layout)!=null?o:null,slots:(a=t.slots)!=null?a:null,persona:(v=t.persona)!=null?v:null,confidence:(c=t.confidence)!=null?c:1};return await e.addInitScript(l=>{let p=window;if(p.__sentient_overrides=l.overrides,l.layout&&(p.__sentient_layout_override=l.layout),l.slots&&(p.__sentient_slot_overrides=l.slots),l.persona){p.__sentient_persona_override={persona:l.persona,confidence:l.confidence};try{let y=l.confidence<.3?"low":l.confidence<.7?"medium":"high";document.documentElement.setAttribute("data-sentient-persona",l.persona),document.documentElement.setAttribute("data-sentient-confidence",y)}catch(y){}}},n),await e.route("**/v1/**",async l=>{var S;let p=l.request(),y=await h(t,p.method(),p.url(),p.postData());if(!y)return l.continue();await l.fulfill({status:y.status,contentType:"application/json",body:JSON.stringify((S=y.json)!=null?S:{})})}),{events:()=>D()}}function _e(e,t={}){var c,l,p,y,S;let n=(c=t.variants)!=null?c:{},i=(l=t.layout)!=null?l:null,o=(p=t.slots)!=null?p:null,a=(y=t.persona)!=null?y:null,v=(S=t.confidence)!=null?S:1;e.on("window:before:load",f=>{var r,u;if(f.__sentient_overrides=n,i&&(f.__sentient_layout_override=i),o&&(f.__sentient_slot_overrides=o),a){f.__sentient_persona_override={persona:a,confidence:v};try{let s=f.document;(r=s==null?void 0:s.documentElement)==null||r.setAttribute("data-sentient-persona",a),(u=s==null?void 0:s.documentElement)==null||u.setAttribute("data-sentient-confidence",I(v))}catch(s){}}}),e.intercept("**/v1/**",async f=>{var u;let r=await h(t,f.method,f.url,f.body!=null?JSON.stringify(f.body):null);r&&f.reply({statusCode:r.status,body:(u=r.json)!=null?u:""})})}var Se=require("react/jsx-runtime");function Ne(e,t={},n){return K(t),(0,we.render)((0,Se.jsx)(de,{apiKey:"pk_test",context:"saas",consent:!1,children:e}),n)}function Fe(){var t;let e=globalThis;(t=e.afterEach)==null||t.call(e,()=>N())}0&&(module.exports={applyScenario,clearSentientEvents,getSentientEvents,hasFiredGoal,mockSentient,mockSentientCypress,renderWithSentient,resetScenario,resolveScenario,scenarioToHandlers,setupSentientTests});
2
+ "use strict";var be=Object.create;var P=Object.defineProperty,he=Object.defineProperties,xe=Object.getOwnPropertyDescriptor,Ce=Object.getOwnPropertyDescriptors,Re=Object.getOwnPropertyNames,Q=Object.getOwnPropertySymbols,Ee=Object.getPrototypeOf,Z=Object.prototype.hasOwnProperty,ke=Object.prototype.propertyIsEnumerable;var Y=(e,t,n)=>t in e?P(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,O=(e,t)=>{for(var n in t||(t={}))Z.call(t,n)&&Y(e,n,t[n]);if(Q)for(var n of Q(t))ke.call(t,n)&&Y(e,n,t[n]);return e},ee=(e,t)=>he(e,Ce(t));var Ae=(e,t)=>{for(var n in t)P(e,n,{get:t[n],enumerable:!0})},te=(e,t,n,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Re(t))!Z.call(e,o)&&o!==n&&P(e,o,{get:()=>t[o],enumerable:!(i=xe(t,o))||i.enumerable});return e};var ne=(e,t,n)=>(n=e!=null?be(Ee(e)):{},te(t||!e||!e.__esModule?P(n,"default",{value:e,enumerable:!0}):n,e)),Pe=e=>te(P({},"__esModule",{value:!0}),e);var je={};Ae(je,{applyScenario:()=>K,clearSentientEvents:()=>fe,getSentientEvents:()=>G,hasFiredGoal:()=>ge,mockSentient:()=>ye,mockSentientCypress:()=>_e,renderWithSentient:()=>Ne,resetScenario:()=>N,resolveScenario:()=>h,scenarioToHandlers:()=>ve,setupSentientTests:()=>Fe});module.exports=Pe(je);var we=require("@testing-library/react");var d=require("react"),E=require("@sentientui/core");var Oe=new Map,Ie=new Map;function ie(e,t){Oe.set(e,t);let n=Ie.get(e);if(n)for(let i of n)try{i(t)}catch(o){}}var Le={on:!1,listeners:new Set};function oe(){if(typeof window=="undefined")return Le;let e=window;return e.__sentient_preview||(e.__sentient_preview={on:!1,listeners:new Set}),e.__sentient_preview}function T(){return oe().on}function re(e){let t=oe().listeners;return t.add(e),()=>{t.delete(e)}}function se(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),getPersona:()=>e.getPersona(),getGraph:()=>e.getGraph(),dispose:()=>e.dispose(),destroy:()=>e.destroy()}}var De="sentient:overrides-changed";function B(){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(De))}function ae(e){typeof window!="undefined"&&(window.__sentient_devtools_config=e)}function le(){var e;return typeof process=="undefined"||((e=process.env)==null?void 0:e.NODE_ENV)!=="production"}var Ge={components:new Map,slots:new Map,sections:[],listeners:new Set,version:0};function M(){if(typeof window=="undefined")return Ge;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 We(){M().version+=1;for(let e of M().listeners)e()}function ce(e){le()&&(M().sections=[...e],We())}var pe=require("react/jsx-runtime");function Te(){var e,t;if(typeof window=="undefined")return"desktop:direct";try{let n=(0,E.detectDeviceClass)((e=navigator.userAgent)!=null?e:""),i=(0,E.detectTrafficSource)((t=document.referrer)!=null?t:"",window.location.origin);return`${n}:${i}`}catch(n){return"desktop:direct"}}var ue="https://api.sentient-ui.com/v1",Be=(0,d.createContext)({client:null,apiKey:"",initialAssignments:{},sessionSegment:"desktop:direct",ssrFallback:"first",onAssignment:void 0,initialLayoutOrder:null,initialSlots:{},initialPersona:null,apiBaseUrl:ue,debug:!1});function de(e){var S,f;let[t,n]=(0,d.useState)(null),[i]=(0,d.useState)(()=>{var r;return(r=e.sessionSegment)!=null?r:Te()}),[o,a]=(0,d.useState)(T());(0,d.useEffect)(()=>re(()=>a(T())),[]),(0,d.useEffect)(()=>{if(e.consent===!1&&!e.preConsentBehavior){n(w=>(w==null||w.destroy(),null));return}let r={apiKey:e.apiKey,context:e.context,debug:e.debug,initialAssignments:e.initialAssignments,sessionSegment:i,consent:e.consent,preConsentBehavior:e.preConsentBehavior,respectDoNotTrack:e.respectDoNotTrack,ssrSessionId:e.ssrSessionId,country:e.country,localMode:e.localMode,initialSlots:e.initialSlots,initialPersona:e.initialPersona,ingestUrl:e.apiBaseUrl?`${e.apiBaseUrl.replace(/\/$/,"")}/events`:void 0},u=!1,s=null,g=null,_=w=>{e.engagement!==!1&&import("@sentientui/core/engagement").then(({startEngagementCapture:b})=>{u||(g=b(w,{apiKey:e.apiKey,apiBase:e.apiBaseUrl?e.apiBaseUrl.replace(/\/$/,""):void 0}))})};return e.enableGraph!==!1?import("@sentientui/core/graph").then(({init:w})=>{u||(s=w(ee(O({},r),{graph:!0,captureDomText:e.captureDomText===!0})),n(s),_(s))}):(s=(0,E.init)(r),n(s),_(s)),()=>{u=!0,g==null||g(),s==null||s.dispose()}},[e.consent]),(0,d.useEffect)(()=>{if(!t)return;let r=!1,u=async()=>{if(r)return;let g;try{g=await t.fetchWeights()}catch(_){return}if(!r)for(let _ of g){let w={componentId:_.componentId,updatedAt:_.updatedAt,variants:_.variants.map(b=>{var k;return{variantId:b.variantId,pulls:b.pulls,avgReward:(k=b.avgReward)!=null?k:0}})};ie(_.componentId,w)}};u();let s=setInterval(()=>{u()},6e4);return()=>{r=!0,clearInterval(s)}},[t]);let v=(S=e.ssrFallback)!=null?S:"first",c=((f=e.apiBaseUrl)!=null?f:ue).replace(/\/$/,""),l=(0,d.useRef)(null);(0,d.useEffect)(()=>{var s;if(typeof process!="undefined"&&((s=process.env)==null?void 0:s.NODE_ENV)==="production")return;let r={apiKey:e.apiKey,context:e.context,country:e.country,apiBaseUrl:c},u=l.current;if(l.current=r,u!==null)for(let g of["apiKey","context","country","apiBaseUrl"])Object.is(u[g],r[g])||console.warn(`[sentient] AdaptiveProvider: \`${g}\` 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,c]),(0,d.useEffect)(()=>{var r;typeof process!="undefined"&&((r=process.env)==null?void 0:r.NODE_ENV)==="production"||ae({apiKey:e.apiKey,apiBaseUrl:c,isLocal:(t==null?void 0:t.isLocal)===!0})},[t,e.apiKey,c]),(0,d.useEffect)(()=>{e.initialLayoutOrder&&e.initialLayoutOrder.length>0&&ce(e.initialLayoutOrder)},[e.initialLayoutOrder]);let p=(0,d.useMemo)(()=>t&&o?se(t):t,[t,o]),y=(0,d.useMemo)(()=>{var r,u,s,g,_;return{client:p,apiKey:e.apiKey,initialAssignments:(r=e.initialAssignments)!=null?r:{},sessionSegment:i,ssrFallback:v,onAssignment:e.onAssignment,initialLayoutOrder:(u=e.initialLayoutOrder)!=null?u:null,initialSlots:(s=e.initialSlots)!=null?s:{},initialPersona:(g=e.initialPersona)!=null?g:null,apiBaseUrl:c,debug:(_=e.debug)!=null?_:!1}},[p,e.apiKey,e.initialAssignments,i,v,e.onAssignment,e.initialLayoutOrder,e.initialSlots,e.initialPersona,c,e.debug]);return(0,pe.jsx)(Be.Provider,{value:y,children:e.children})}function I(e){return e<.3?"low":e<.7?"medium":"high"}function K(e={}){var n,i,o;let t=window;if(t.__sentient_overrides=O({},(n=e.variants)!=null?n:{}),e.layout?t.__sentient_layout_override=e.layout:delete t.__sentient_layout_override,e.slots?t.__sentient_slot_overrides=O({},e.slots):delete t.__sentient_slot_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",I((o=e.confidence)!=null?o:1))}catch(a){}}else delete t.__sentient_persona_override;B()}function N(){let e=window;delete e.__sentient_overrides,delete e.__sentient_layout_override,delete e.__sentient_slot_overrides,delete e.__sentient_persona_override;try{document.documentElement.removeAttribute("data-sentient-persona"),document.documentElement.removeAttribute("data-sentient-confidence")}catch(t){}B()}var L=require("msw");var F=[];function j(e){F.push(e)}function G(){return[...F]}function fe(){F.length=0}function ge(e,t){return e.some(n=>(n.eventType==="goal_achieved"||n.eventType==="goal")&&n.goalType===t)}function Me(e){var t;try{return new URL(e).pathname}catch(n){return(t=e.split("?")[0])!=null?t:e}}async function Ke(e,t){var i,o,a;let n=(i=e.api)==null?void 0:i[t];return n===void 0?null:n==="error"?{status:500}:typeof n=="number"?{status:n}:(n.delayMs&&await new Promise(v=>setTimeout(v,n.delayMs)),{status:(o=n.status)!=null?o:200,json:(a=n.body)!=null?a:{}})}async function h(e,t,n,i){var l,p,y,S,f,r,u,s,g,_,w,b,k,U,V,H,$,z,J,X,q;let o=Me(n);if(!o.includes("/v1/"))return null;let a="/v1/"+((l=o.split("/v1/")[1])!=null?l:""),v=await Ke(e,a);if(v)return v;let c=i?JSON.parse(i):{};if(a==="/v1/sessions")return{status:204};if(a==="/v1/events"){for(let m of c)j(m);return{status:204}}if(a==="/v1/goals")return j({eventType:"goal",goalType:c.name}),{status:204};if(a==="/v1/assign"){let m=c;return{status:200,json:{variantId:(f=(S=(p=e.variants)==null?void 0:p[m.componentId])!=null?S:(y=m.variantIds)==null?void 0:y[0])!=null?f:"control",assignmentTtlMs:6e4}}}if(a==="/v1/decide"){let m=c,x={layoutOrder:(u=e.layout)!=null?u:((r=m.sections)!=null?r:[]).map(C=>C.id),assignments:(s=e.variants)!=null?s:{},persona:(g=e.persona)!=null?g:"unknown",confidence:(_=e.confidence)!=null?_:1};if(m.slots&&m.slots.length>0){let C={};for(let R of m.slots)C[R.id]=(b=(w=e.slots)==null?void 0:w[R.id])!=null?b:me(R);x.slots=C}return{status:200,json:x}}if(a==="/v1/explain"){let m=c,A=(U=e.layout)!=null?U:((k=m.sections)!=null?k:[]).map(D=>D.id),x=(H=(V=m.persona)!=null?V:e.persona)!=null?H:"unknown",C=($=e.confidence)!=null?$:1,R={layoutOrder:A,assignments:(z=e.variants)!=null?z:{},persona:x,reasons:[],personaAttributes:{persona:x,confidence:I(C)}};if(m.slots&&m.slots.length>0){let D={};for(let W of m.slots)D[W.id]=(X=(J=e.slots)==null?void 0:J[W.id])!=null?X:me(W);R.slots=D}return{status:200,json:R}}return a==="/v1/weights"?{status:200,json:{components:Object.entries((q=e.weights)!=null?q:{}).map(([A,x])=>({componentId:A,updatedAt:0,variants:x}))}}:null}function me(e){var n,i,o;if(e.arms)return typeof e.baseline=="string"?e.baseline:(n=e.arms[0])!=null?n:"baseline";let t={};for(let[a,v]of Object.entries((i=e.dims)!=null?i:{})){let c=typeof e.baseline=="object"&&e.baseline!==null?e.baseline[a]:void 0;t[a]=(o=c!=null?c:v[0])!=null?o:""}return t}function ve(e={}){return[L.http.all("*/v1/*",async({request:t})=>{let n=t.method==="GET"||t.method==="HEAD"?null:await t.text(),i=await h(e,t.method,t.url,n);if(i)return i.json===void 0?new L.HttpResponse(null,{status:i.status}):L.HttpResponse.json(i.json,{status:i.status})})]}async function ye(e,t={}){var i,o,a,v,c;let n={overrides:(i=t.variants)!=null?i:{},layout:(o=t.layout)!=null?o:null,slots:(a=t.slots)!=null?a:null,persona:(v=t.persona)!=null?v:null,confidence:(c=t.confidence)!=null?c:1};return await e.addInitScript(l=>{let p=window;if(p.__sentient_overrides=l.overrides,l.layout&&(p.__sentient_layout_override=l.layout),l.slots&&(p.__sentient_slot_overrides=l.slots),l.persona){p.__sentient_persona_override={persona:l.persona,confidence:l.confidence};try{let y=l.confidence<.3?"low":l.confidence<.7?"medium":"high";document.documentElement.setAttribute("data-sentient-persona",l.persona),document.documentElement.setAttribute("data-sentient-confidence",y)}catch(y){}}},n),await e.route("**/v1/**",async l=>{var S;let p=l.request(),y=await h(t,p.method(),p.url(),p.postData());if(!y)return l.continue();await l.fulfill({status:y.status,contentType:"application/json",body:JSON.stringify((S=y.json)!=null?S:{})})}),{events:()=>G()}}function _e(e,t={}){var c,l,p,y,S;let n=(c=t.variants)!=null?c:{},i=(l=t.layout)!=null?l:null,o=(p=t.slots)!=null?p:null,a=(y=t.persona)!=null?y:null,v=(S=t.confidence)!=null?S:1;e.on("window:before:load",f=>{var r,u;if(f.__sentient_overrides=n,i&&(f.__sentient_layout_override=i),o&&(f.__sentient_slot_overrides=o),a){f.__sentient_persona_override={persona:a,confidence:v};try{let s=f.document;(r=s==null?void 0:s.documentElement)==null||r.setAttribute("data-sentient-persona",a),(u=s==null?void 0:s.documentElement)==null||u.setAttribute("data-sentient-confidence",I(v))}catch(s){}}}),e.intercept("**/v1/**",async f=>{var u;let r=await h(t,f.method,f.url,f.body!=null?JSON.stringify(f.body):null);r&&f.reply({statusCode:r.status,body:(u=r.json)!=null?u:""})})}var Se=require("react/jsx-runtime");function Ne(e,t={},n){return K(t),(0,we.render)((0,Se.jsx)(de,{apiKey:"pk_test",context:"saas",consent:!1,children:e}),n)}function Fe(){var t;let e=globalThis;(t=e.afterEach)==null||t.call(e,()=>N())}0&&(module.exports={applyScenario,clearSentientEvents,getSentientEvents,hasFiredGoal,mockSentient,mockSentientCypress,renderWithSentient,resetScenario,resolveScenario,scenarioToHandlers,setupSentientTests});
3
3
  //# sourceMappingURL=testing.js.map