@sentientui/react 0.39.1 → 0.40.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +32 -0
- package/dist/devtools.js.map +1 -1
- package/dist/devtools.mjs.map +1 -1
- package/dist/index.d.cts +40 -2
- package/dist/index.d.ts +40 -2
- package/dist/index.js +2 -2
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +2 -2
- package/dist/index.mjs.map +1 -1
- package/dist/next/adaptive-root.d.ts +35 -1
- package/dist/next/adaptive-root.js +2 -2
- package/dist/next/adaptive-root.js.map +1 -1
- package/dist/server.d.cts +12 -1
- package/dist/server.d.ts +12 -1
- package/dist/server.js +1 -1
- package/dist/server.js.map +1 -1
- package/dist/server.mjs +1 -1
- package/dist/server.mjs.map +1 -1
- package/dist/testing/react.js +1 -1
- package/dist/testing/react.js.map +1 -1
- package/dist/testing/react.mjs +1 -1
- package/dist/testing/react.mjs.map +1 -1
- package/dist/testing.d.cts +1 -0
- package/dist/testing.d.ts +1 -0
- package/dist/testing.js +1 -1
- package/dist/testing.js.map +1 -1
- package/dist/testing.mjs +1 -1
- package/dist/testing.mjs.map +1 -1
- package/package.json +2 -2
|
@@ -20,6 +20,14 @@ type AdaptiveProviderProps = {
|
|
|
20
20
|
* the first paint see real content (recommended for SEO).
|
|
21
21
|
*/
|
|
22
22
|
initialAssignments?: Record<string, string>;
|
|
23
|
+
/**
|
|
24
|
+
* Component ids the SSR preload found moved onto the shared track (the
|
|
25
|
+
* `unified` of `loadAdaptiveAssignments()` / `loadAdaptiveDecision()`;
|
|
26
|
+
* `<AdaptiveRoot>` passes it for you). A variants-only `<Adaptive>` with one
|
|
27
|
+
* of these ids renders on the shared track from the server HTML on, and an
|
|
28
|
+
* assignment cached before the move is ignored.
|
|
29
|
+
*/
|
|
30
|
+
initialUnified?: string[];
|
|
23
31
|
/**
|
|
24
32
|
* Bandit segment from SSR (`device:source`). Keeps cache, assign, and worker
|
|
25
33
|
* weights on one row — must match `loadAdaptiveAssignments` / session upsert.
|
|
@@ -277,6 +285,14 @@ type PreloadComponent = {
|
|
|
277
285
|
id: string;
|
|
278
286
|
variantIds: string[];
|
|
279
287
|
};
|
|
288
|
+
/** A registry `<Adaptive id>` declared with what it can render — see `AdaptiveRootProps.registrySlots`. */
|
|
289
|
+
type RegistrySlotDecl = {
|
|
290
|
+
id: string;
|
|
291
|
+
/** The `variants` keys of a hybrid `<Adaptive variants>{children}</Adaptive>`. */
|
|
292
|
+
authored?: string[];
|
|
293
|
+
/** The `<Adaptive>` has an `onFormSubmit`. @default true */
|
|
294
|
+
forms?: boolean;
|
|
295
|
+
};
|
|
280
296
|
type AdaptiveRootProps = Omit<AdaptiveProviderProps, 'initialAssignments' | 'onAssignment' | 'initialSlots' | 'initialSlotConfig' | 'initialPalette' | 'initialVocabulary' | 'initialPersona' | 'initialLayoutOrder' | 'declaredSections' | 'sessionSegment' | 'consentFrom'> & {
|
|
281
297
|
/**
|
|
282
298
|
* Consent source — see `AdaptiveProviderProps.consentFrom`. A platform preset
|
|
@@ -348,6 +364,24 @@ type AdaptiveRootProps = Omit<AdaptiveProviderProps, 'initialAssignments' | 'onA
|
|
|
348
364
|
* @example registrySlotIds={['hero-headline', 'pricing-cta']}
|
|
349
365
|
*/
|
|
350
366
|
registrySlotIds?: string[];
|
|
367
|
+
/**
|
|
368
|
+
* Like `registrySlotIds`, for `<Adaptive id>`s that need to tell the server
|
|
369
|
+
* more than their id. Most often that is a hybrid —
|
|
370
|
+
* `<Adaptive id variants={{ a, b }}>{original}</Adaptive>`. List its
|
|
371
|
+
* `variants` keys as `authored`, or the SSR decide cannot draw them. In that
|
|
372
|
+
* case the first paint can only be the original or a generated version, and
|
|
373
|
+
* the hand-written ones appear only on pages the browser decides.
|
|
374
|
+
*
|
|
375
|
+
* `forms`: whether the `<Adaptive>` has an `onFormSubmit`. Declare
|
|
376
|
+
* `forms: false` when it has none, or SSR can draw a generated form version
|
|
377
|
+
* that the page then refuses. The default is `true`, the same as a bare
|
|
378
|
+
* `registrySlotIds` entry.
|
|
379
|
+
*
|
|
380
|
+
* You may list an id in both props: it is decided once, with these caps.
|
|
381
|
+
*
|
|
382
|
+
* @example registrySlots={[{ id: 'hero_cta', authored: ['action', 'social'], forms: false }]}
|
|
383
|
+
*/
|
|
384
|
+
registrySlots?: RegistrySlotDecl[];
|
|
351
385
|
/** App origin — must be in the project's `allowed_origins`. */
|
|
352
386
|
appOrigin?: string;
|
|
353
387
|
/**
|
|
@@ -441,4 +475,4 @@ type AdaptiveRootProps = Omit<AdaptiveProviderProps, 'initialAssignments' | 'onA
|
|
|
441
475
|
*/
|
|
442
476
|
declare function AdaptiveRoot(props: AdaptiveRootProps): Promise<JSX.Element>;
|
|
443
477
|
|
|
444
|
-
export { AdaptiveRoot, type AdaptiveRootProps, type AgentFeed, type AgentFeedReadEntry, type AgentFeedRouteConfig, type PreloadComponent, buildAgentFeed as buildAgentFeedFor, createAgentFeed, defineAgentContent };
|
|
478
|
+
export { AdaptiveRoot, type AdaptiveRootProps, type AgentFeed, type AgentFeedReadEntry, type AgentFeedRouteConfig, type PreloadComponent, type RegistrySlotDecl, buildAgentFeed as buildAgentFeedFor, createAgentFeed, defineAgentContent };
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var
|
|
1
|
+
var Oe=Object.defineProperty,Le=Object.defineProperties;var Ce=Object.getOwnPropertyDescriptors;var C=Object.getOwnPropertySymbols;var pe=Object.prototype.hasOwnProperty,ue=Object.prototype.propertyIsEnumerable;var ge=(e,t,n)=>t in e?Oe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,g=(e,t)=>{for(var n in t||(t={}))pe.call(t,n)&&ge(e,n,t[n]);if(C)for(var n of C(t))ue.call(t,n)&&ge(e,n,t[n]);return e},m=(e,t)=>Le(e,Ce(t));var me=(e,t)=>{var n={};for(var s in e)pe.call(e,s)&&t.indexOf(s)<0&&(n[s]=e[s]);if(e!=null&&C)for(var s of C(e))t.indexOf(s)<0&&ue.call(e,s)&&(n[s]=e[s]);return n};import{deriveSessionSegment as Ve,exposedStage as Xe,extractTrackedParams as qe,matchedAgentToken as We}from"@sentientui/core";import{consentFromCookies as Ge}from"@sentientui/core/consent";import{cookies as He,headers as ze}from"next/headers";import{renderPrePaintScript as Ne}from"@sentientui/core";import{confidenceBand as De}from"@sentientui/policy";import{jsx as Ke}from"react/jsx-runtime";function _(e){return JSON.stringify(e).replace(/</g,"\\u003c")}function Ee(e){return e.persona?"(function(){try{var d=document.documentElement;"+(e.stage?'if(!d.hasAttribute("data-sentient-stage"))d.setAttribute("data-sentient-stage",'+_(e.stage)+");":"")+'if(d.hasAttribute("data-sentient-persona"))return;d.setAttribute("data-sentient-persona",'+_(e.persona.persona)+');d.setAttribute("data-sentient-confidence",'+_(De(e.persona.confidence))+");}catch(e){}})();":Ne(e.apiKey,e.stageAttributes?{stage:!0}:void 0)}function fe(e){return!e.persona&&(e.consent===!1||e.consentFrom!==void 0&&e.consent!==!0)?null:Ke("script",{"data-sentient-persona-script":"",nonce:e.nonce,dangerouslySetInnerHTML:{__html:Ee(e)}})}import{preloadAssignments as at,preloadAssignmentsDetailed as Ue,readSessionCookie as _e,trackServerGoal as dt}from"@sentientui/core/server";import{preloadDecisions as gt}from"@sentientui/core/server";function Ae(){return typeof crypto!="undefined"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`snt-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}async function ye(e,t){var o,d,c;let n=(c=(d=_e(t.cookies,t.apiKey))!=null?d:(o=t.createSessionId)==null?void 0:o.call(t))!=null?c:Ae(),{assignments:s,unified:a}=await Ue(e,n,{apiKey:t.apiKey,baseUrl:t.baseUrl,origin:t.origin,userAgent:t.userAgent,referer:t.referer,utmParams:t.utmParams,clickIds:t.clickIds,landingPath:t.landingPath,doNotTrack:t.doNotTrack,timeoutMs:t.timeoutMs,persona:t.persona},{unified:!0});return{assignments:s,sessionId:n,unified:a}}async function he(e){var d,c,A,S,x,k,u,F,y,O;let{preloadDecisions:t,readSessionCookie:n}=await import("@sentientui/core/server"),s=(A=(c=n(e.cookies,e.apiKey))!=null?c:(d=e.createSessionId)==null?void 0:d.call(e))!=null?A:Ae();if(!(typeof e.apiKey=="string"&&e.apiKey.startsWith("pk_"))){let i={layoutOrder:(S=e.sections)!=null?S:[],assignments:{},slots:{},persona:"unknown",confidence:0,sessionId:s};try{let l=await import("@sentientui/core/local");if(!l.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."),i;let p=l.createLocalEngine({sessionId:s}).decide({sections:e.sections,components:(x=e.components)!=null?x:[],slots:(k=e.slots)!=null?k:[]});return{layoutOrder:(F=(u=p.layoutOrder)!=null?u:e.sections)!=null?F:[],assignments:p.assignments,slots:p.slots,persona:p.persona,confidence:p.confidence,sessionId:s}}catch(l){return i}}let o=await t(m(g({sections:e.sections,components:(y=e.components)!=null?y:[],slots:(O=e.slots)!=null?O:[],slotsFrom:e.slotsFrom,registrySlotIds:e.registrySlotIds},e.renderCaps?{renderCaps:e.renderCaps}:{}),{unifiedCaps:!0}),s,{apiKey:e.apiKey,baseUrl:e.baseUrl,origin:e.origin,userAgent:e.userAgent,referer:e.referer,utmParams:e.utmParams,clickIds:e.clickIds,landingPath:e.landingPath,doNotTrack:e.doNotTrack,timeoutMs:e.timeoutMs,persona:e.persona});return m(g({},o),{sessionId:s})}import{AdaptiveRootClient as Ye}from"./adaptive-root-client.js";var Te=["page","blocks","layoutOrder"],ve=new Map;function Be(e,t){ve.set(e,t)}function Me(e){return ve.get(e)}function T(e){var a,o;let t=(o=(a=e.content)!=null?a:Me(e.page))!=null?o:{},n={};for(let[d,c]of Object.entries(t))Te.includes(d)||(n[d]=c);let s=m(g({},n),{page:e.page,blocks:e.blocks});return e.layoutOrder&&(s.layoutOrder=e.layoutOrder),s}function Se(e){return JSON.stringify(g({"@context":"https://schema.org","@type":"WebPage"},e)).replace(/</g,"\\u003c")}function ke(e){let t=[];e.title&&t.push(`# ${e.title}`,""),e.summary&&t.push(String(e.summary),"");for(let[n,s]of Object.entries(e))["page","title","summary","blocks","layoutOrder"].includes(n)||t.push(`## ${n}`,"","```json",JSON.stringify(s,null,2),"```","");if(e.blocks.length>0){t.push("## blocks","");for(let n of e.blocks)t.push(`- **${n.id}** \u2192 variant \`${n.variant}\``),n.content!==void 0&&t.push(""," ```json",JSON.stringify(n.content,null,2)," ```");t.push("")}return t.join(`
|
|
2
2
|
`).trimEnd()+`
|
|
3
|
-
`}function
|
|
3
|
+
`}function be(e,t={}){var s,a;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:(a=e.userAgent)!=null?a:null,source:"ssr"})}).catch(()=>{})}catch(o){}}import{matchedAgentToken as je}from"@sentientui/core";function Je(e,t){return e.pathname.endsWith(".md")||t.toLowerCase().includes("text/markdown")}function $e(e){return async t=>{var c;let n=new URL(t.url),s=(c=t.headers.get("accept"))!=null?c:"",a=t.headers.get("user-agent"),o=n.pathname.replace(/\.(md|json)$/,"");if(e.onRead)try{Promise.resolve(e.onRead({path:o,userAgent:a,botName:je(a!=null?a:"")})).catch(()=>{})}catch(A){}let d=await e.getFeed(t);return Je(n,s)?new Response(ke(d),{headers:{"content-type":"text/markdown; charset=utf-8"}}):new Response(JSON.stringify(d),{headers:{"content-type":"application/json; charset=utf-8"}})}}import{matchedAgentToken as Nt,uaTokenMatch as Dt,agentIntent as Et,classifiedAgents as Kt}from"@sentientui/core";import{Fragment as Re,jsx as B,jsxs as Ie}from"react/jsx-runtime";var Qe="https://api.sentient-ui.com/v1";function Ze(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:""}})}function et(e,t){if(e)for(let n of e.split(";")){let s=n.indexOf("=");if(s>0&&n.slice(0,s).trim()===t)return n.slice(s+1).trim()}}async function xt(e){var se,re,ie,oe,ae,de,ce;let ne=e,{components:t=[],sections:n,slots:s,registrySlotIds:a,registrySlots:o,appOrigin:d,searchParams:c,pathname:A,initialAssignments:S,ssrSessionId:x,timeoutMs:k,agentFeed:u,captureAgents:F,nonce:y,children:O}=ne,i=me(ne,["components","sections","slots","registrySlotIds","registrySlots","appOrigin","searchParams","pathname","initialAssignments","ssrSessionId","timeoutMs","agentFeed","captureAgents","nonce","children"]),l=await ze(),p=l.get("host");!d&&process.env.NODE_ENV==="production"&&!p&&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 N=d!=null?d:process.env.NODE_ENV==="production"?`https://${p!=null?p:"localhost"}`:"http://localhost:3001",f=(se=l.get("user-agent"))!=null?se:void 0,D=(re=l.get("referer"))!=null?re:void 0,{utmParams:M,clickIds:j}=qe(c!=null?c:{}),Pe=l.get("dnt")==="1"||l.get("sec-gpc")==="1",we=Ve({userAgent:f,referer:D,appOrigin:N}),J=await He(),E=i.consentFrom,K=(oe=i.consent)!=null?oe:E&&(ie=Ge(E,r=>et(l.get("cookie"),r)))!=null?ie:void 0,$=Pe||K===!1||E!=null&&K!==!0,V=i.localMode===!0||i.localMode!==!1&&!(typeof i.apiKey=="string"&&i.apiKey.startsWith("pk_")),U=i.apiBaseUrl?i.apiBaseUrl.replace(/\/$/,""):Qe,X=(de=(ae=u==null?void 0:u.path)!=null?ae:l.get("x-pathname"))!=null?de:"/",q=We(f!=null?f:"");!V&&F!==!1&&q&&be({baseUrl:U,apiKey:i.apiKey,path:X,botName:q,userAgent:f});let h,v,b=null,R,W,G,H,I=null,z=null,L,Y=[...new Set([...a!=null?a:[],...(o!=null?o:[]).map(r=>r.id)])],Q=o!=null&&o.length?Object.fromEntries(o.map(r=>{var P,w;return[r.id,g({forms:(P=r.forms)!=null?P:!0,compose:!0,ops:!1},(w=r.authored)!=null&&w.length?{authored:r.authored,children:!0}:{})]})):void 0,Z=Y.length>0;if(S)h=S,L=x;else if($||V)h={};else if(n&&n.length>0||s&&s.length>0||Z){let r=await he(m(g({sections:n!=null?n:[],components:t,slots:s},Z?g({slotsFrom:"registry",registrySlotIds:Y},Q?{renderCaps:Q}:{}):{}),{cookies:J,apiKey:i.apiKey,baseUrl:U,origin:N,userAgent:f,referer:D,utmParams:M,clickIds:j,landingPath:A,timeoutMs:k,persona:i.persona}));h=r.assignments,v=r.unified,b=r.layoutOrder,R=r.slots,W=r.slotConfig,G=r.palette,H=r.vocabulary,I=r.persona!==void 0?{persona:r.persona,confidence:(ce=r.confidence)!=null?ce:0}:null,z=Xe(r.stage,i.stageAttributes),L=r.sessionId}else{let r=await ye(t,{cookies:J,apiKey:i.apiKey,baseUrl:U,origin:N,userAgent:f,referer:D,utmParams:M,clickIds:j,landingPath:A,timeoutMs:k,persona:i.persona});h=r.assignments,v=r.unified,L=r.sessionId}let ee=$?null:B(fe,{apiKey:i.apiKey,persona:I,nonce:y,stageAttributes:i.stageAttributes,stage:z}),te=B(Ye,m(g({},i),{nonce:y,consent:K,initialAssignments:h,initialUnified:v,initialLayoutOrder:b,declaredSections:n,initialSlots:R,initialSlotConfig:W,initialPalette:G,initialVocabulary:H,initialPersona:I!=null?I:void 0,sessionSegment:we,ssrSessionId:L,children:O}));if(!u)return Ie(Re,{children:[ee,te]});let xe=T({page:X,blocks:[...Ze(h),...(v!=null?v:[]).map(r=>{var le;let P=R==null?void 0:R[r],w=(le=t.find(Fe=>Fe.id===r))==null?void 0:le.variantIds[0];return{id:r,variant:typeof P=="string"?P:w!==void 0?`authored.${w}`:""}})],layoutOrder:b!=null?b:void 0,content:u.content});return Ie(Re,{children:[ee,B("script",{type:"application/ld+json",nonce:y,dangerouslySetInnerHTML:{__html:Se(xe)}}),te]})}export{xt as AdaptiveRoot,Et as agentIntent,T as buildAgentFeedFor,Kt as classifiedAgents,$e as createAgentFeed,Be as defineAgentContent,Nt as matchedAgentToken,Dt as uaTokenMatch};
|
|
4
4
|
//# sourceMappingURL=adaptive-root.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/next/adaptive-root.tsx","../../src/persona-script.tsx","../../src/server.ts","../../src/agent-feed.ts","../../src/next/log-agent-fetch.ts","../../src/next/agent-feed-route.ts"],"sourcesContent":["import { deriveSessionSegment, exposedStage, extractTrackedParams, matchedAgentToken } from '@sentientui/core';\nimport { consentFromCookies } from '@sentientui/core/consent';\nimport type { SlotDeclInput, SlotResult } from '@sentientui/core';\nimport { cookies, headers } from 'next/headers';\n// `type JSX` from react, not the global namespace removed in @types/react@19\n// (peers allow react >=18) — see adaptive-text.tsx.\nimport type { JSX, ReactNode } from 'react';\nimport type { AdaptiveProviderProps } from '../provider.js';\nimport { SentientPersonaScript } from '../persona-script.js';\nimport {\n loadAdaptiveAssignments,\n loadAdaptiveDecision,\n type LoadAdaptiveDecisionResult,\n type ServerAssignments,\n} from '../server.js';\nimport { AdaptiveRootClient } from './adaptive-root-client.js';\nimport { buildAgentFeed, renderAgentJsonLdBody, type AgentBlock } from '../agent-feed.js';\nimport { logAgentFetch } from './log-agent-fetch.js';\n\nexport { createAgentFeed } from './agent-feed-route.js';\nexport type { AgentFeedRouteConfig, AgentFeedReadEntry } from './agent-feed-route.js';\nexport { defineAgentContent, buildAgentFeed as buildAgentFeedFor } from '../agent-feed.js';\n// Re-exported from core on the SERVER entry (this module is server-only — it\n// imports next/headers). Lets server components do agent detection with just the\n// `@sentientui/react` package, no direct core dependency. Do NOT add this to the\n// package's client index: re-exporting a plain function through a 'use client'\n// module turns it into a client reference that throws when called during SSR.\nexport { matchedAgentToken, uaTokenMatch, agentIntent, classifiedAgents } from '@sentientui/core';\nexport type { AgentIntent } from '@sentientui/core';\nexport type { AgentFeed } from '../agent-feed.js';\n\nconst DEFAULT_API_BASE_URL = 'https://api.sentient-ui.com/v1';\n\nexport type PreloadComponent = { id: string; variantIds: string[] };\n\nexport type AdaptiveRootProps = Omit<\n AdaptiveProviderProps,\n // Every provider prop AdaptiveRoot itself resolves and passes AFTER the\n // {...providerProps} spread must be omitted here: a caller-supplied value\n // would typecheck but be silently clobbered by the spread order\n // (initialLayoutOrder, declaredSections and sessionSegment were missing\n // from this list and suffered exactly that).\n | 'initialAssignments'\n | 'onAssignment'\n | 'initialSlots'\n | 'initialSlotConfig'\n | 'initialPalette'\n | 'initialVocabulary'\n | 'initialPersona'\n | 'initialLayoutOrder'\n | 'declaredSections'\n | 'sessionSegment'\n | 'consentFrom'\n> & {\n /**\n * Consent source — see `AdaptiveProviderProps.consentFrom`. A platform preset\n * (`'cookiebot'`, `'onetrust'`, `'cookieyes'`, `'tcf'`, `'google-consent-mode'`)\n * or a cookie. Resolved on the server from the platform's own cookie, so a\n * visitor who already consented gets SSR with no layout shift.\n *\n * No `check` form: AdaptiveRoot is a Server Component and spreads\n * this straight into its client boundary, and a function prop crossing the\n * server→client boundary throws at render (\"Functions cannot be passed\n * directly to Client Components\"). The provider's type accepted `check`, so\n * a Cookiebot-style predicate typechecked here and then crashed the layout.\n * Need a JS-API CMP predicate? Use `<AdaptiveProvider>` in a client component.\n */\n consentFrom?: Exclude<NonNullable<AdaptiveProviderProps['consentFrom']>, { check?: () => boolean; cmp?: undefined }> | { cmp?: undefined; cookie?: string; value?: string; event?: string };\n /**\n * Code-variant components to assign server-side (SEO-safe). Optional — an\n * `<Adaptive>` works without an entry here and assigns after mount.\n *\n * List only ids this tree actually renders. Each one is assigned on every\n * request, rendered or not, and every assignment logs an impression (or a\n * holdout exposure). An id the page never renders therefore accrues trials\n * that cannot convert, and in a root layout that happens on every route.\n */\n components?: PreloadComponent[];\n /**\n * Declare page section IDs in their default order. When provided,\n * AdaptiveRoot calls `/v1/decide` (single round trip) instead of\n * individual `/v1/assign` calls, and `useLayoutOrder()` returns the\n * persona-specific order on first render.\n *\n * Give each section's rendered element `data-sentient-id=\"<sectionId>\"` —\n * the only markup a section needs — so the DOM graph scanner can register\n * it under the same id. Without it the server never learns what the section\n * IS, types it `generic`, and serves the identity order to every persona —\n * the integration looks live but cannot personalize. The provider warns\n * about unresolvable ids in development. Correct a section the content\n * classifier mistypes with `sectionTypes`, not extra markup.\n *\n * @example sections={['hero', 'pricing', 'features', 'social_proof']}\n * // …and in the tree: <section data-sentient-id=\"pricing\">\n */\n sections?: string[];\n /**\n * Adaptive-slot declarations used by `useAdaptiveTokens` / `AdaptiveGroup`\n * in this tree. Declaring them here decides them in the same SSR\n * round trip, so their values serialize into the server HTML.\n */\n slots?: SlotDeclInput[];\n /**\n * The generated-mode `<Adaptive id>`s THIS page renders. Declaring them\n * decides their published versions in the same SSR round trip\n * (`/v1/decide` registry mode) and serializes the served content into the\n * server HTML, so the first paint shows the version rather than the\n * original children until the client-side decide answers. Without it a\n * registry slot renders its children first and swaps after mount.\n *\n * Scoped to exactly these ids on purpose: an unscoped registry decide\n * records a close-out trial for every published slot on every page.\n *\n * @example registrySlotIds={['hero-headline', 'pricing-cta']}\n */\n registrySlotIds?: string[];\n /** App origin — must be in the project's `allowed_origins`. */\n appOrigin?: string;\n /**\n * The page's `searchParams` prop (or an equivalent query string /\n * URLSearchParams). Server Components cannot read the request URL from\n * `headers()`, so without this the SSR-minted session carries no `utm_*`\n * params and no ad click IDs (gclid, fbclid, ttclid, …) — campaign\n * attribution only lands after client hydration, and never for visits the\n * client SDK doesn't get to finish (bounce before hydrate). Pass it on\n * landing pages that receive ad traffic:\n *\n * ```tsx\n * export default async function Page({ searchParams }: { searchParams: Promise<Record<string, string | string[] | undefined>> }) {\n * return <AdaptiveRoot ... searchParams={await searchParams}>...</AdaptiveRoot>;\n * }\n * ```\n */\n searchParams?: Record<string, string | string[] | undefined> | URLSearchParams | string;\n /**\n * The page's path (e.g. `/products/trail-shoe`). Server components cannot\n * read their own URL, so pass it on landing pages that receive ad or email\n * traffic: with it, a paid click to a product page or a `/discount/` link\n * is recognised on the server render — adapted from the first byte.\n */\n pathname?: 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 * A cookie's value exactly as the browser sent it. The CMP parsers need the\n * raw form: Next's cookies() decodes every value, which turns an encoded\n * `&groups=C0002:1` inside OneTrust's `landingPath` (a crafted link, before\n * any answer) into a real field that read as consent on the server — SSR\n * then minted a session and handed the client consent={true} (grader R8 NEW-1).\n * First match wins, like the browser's document.cookie read. A consent cookie\n * set only by middleware in this request is not in the header: the server\n * then reads \"unknown\" and the browser decides (fail-closed).\n */\nfunction rawCookie(header: string | null | undefined, name: string): string | undefined {\n if (!header) return undefined;\n for (const part of header.split(';')) {\n const eq = part.indexOf('=');\n if (eq > 0 && part.slice(0, eq).trim() === name) return part.slice(eq + 1).trim();\n }\n return undefined;\n}\n\n/**\n * Next.js Server Component that resolves variant assignments (and optionally\n * section layout order) server-side for zero layout shift on first paint.\n *\n * When `sections` is provided, a single `POST /v1/decide` call returns both\n * the persona-specific section order and all component assignments.\n * Without `sections`, individual `/v1/assign` calls are made per component.\n *\n * @example\n * // app/page.tsx — with section layout. Declared on the page (not the root\n * // layout) because hero_cta renders only here; see the `components` prop.\n * import { AdaptiveRoot } from '@sentientui/react/next';\n *\n * export default async function Page() {\n * return (\n * <AdaptiveRoot\n * apiKey={process.env.NEXT_PUBLIC_SENTIENT_API_KEY!}\n * sections={['hero', 'pricing', 'features', 'social_proof']}\n * components={[\n * { id: 'hero_cta', variantIds: ['default', 'accent'] },\n * ]}\n * >\n * <HeroSection />\n * <PricingSection />\n * <FeaturesSection />\n * <SocialProofSection />\n * </AdaptiveRoot>\n * );\n * }\n */\nexport async function AdaptiveRoot(props: AdaptiveRootProps): Promise<JSX.Element> {\n const {\n components = [],\n sections,\n slots,\n registrySlotIds,\n appOrigin,\n searchParams,\n pathname,\n initialAssignments: initialAssignmentsOverride,\n ssrSessionId: ssrSessionIdProp,\n timeoutMs,\n agentFeed,\n captureAgents,\n nonce,\n children,\n ...providerProps\n } = props;\n\n const headerStore = await headers();\n const host = headerStore.get('host');\n if (!appOrigin && process.env.NODE_ENV === 'production' && !host) {\n console.error(\n '[SentientUI] AdaptiveRoot: Host header is absent and no appOrigin was provided. ' +\n 'Pass appOrigin explicitly — the https://localhost fallback will likely fail allowed_origins validation.',\n );\n }\n const resolvedOrigin = appOrigin ??\n (process.env.NODE_ENV === 'production'\n ? `https://${host ?? 'localhost'}`\n : 'http://localhost:3001');\n const userAgent = headerStore.get('user-agent') ?? undefined;\n const referer = headerStore.get('referer') ?? undefined;\n // Landing-URL attribution (utm_* + ad click IDs). Only available when the\n // page passes its searchParams down — headers() never carries the request's\n // own query string, and the Referer is the PREVIOUS page, not this one.\n const { utmParams, clickIds } = extractTrackedParams(searchParams ?? {});\n // Honor a tracking opt-out at SSR: `DNT: 1` or the legally-enforceable\n // `Sec-GPC: 1`. When set we skip the session upsert + assign/decide so no\n // session row is minted for the visitor (audit P4) — matching the client SDK,\n // which already no-ops for these signals.\n const doNotTrack = headerStore.get('dnt') === '1' || headerStore.get('sec-gpc') === '1';\n // `consent: false` must gate the SERVER too, not just the client. Without\n // this the SSR decide/assign still ran and still minted a session row for a\n // visitor who had not consented — contradicting the documented contract\n // (\"no SDK is initialised, no cookies are written, no events are sent\") and\n // forcing sites to hide AdaptiveRoot behind a conditional render, which is\n // what made consent-after-load cost a full server round trip.\n const sessionSegment = deriveSessionSegment({ userAgent, referer, appOrigin: resolvedOrigin });\n const cookieStore = await cookies();\n\n // This is a Server Component and already has the request cookies, so resolve\n // a cookie-based `consentFrom` here rather than making the app read the same\n // cookie again just to pass `consent` — naming it twice only invites drift.\n // An already-consented visitor therefore gets SSR variant assignment (zero\n // layout shift) with no extra code.\n //\n // An explicit `consent` prop always wins — it is the escape hatch for apps\n // that track consent elsewhere. (No `check()` form here: see the prop type.)\n //\n // Consent gates the SERVER too, not just the client: without it the SSR\n // decide/assign still ran and still minted a session row for a visitor who\n // had not consented, contradicting the documented contract (\"no SDK is\n // initialised, no cookies are written, no events are sent\").\n const cf = providerProps.consentFrom;\n // The platform's own cookie (Cookiebot CookieConsent, OneTrust\n // OptanonConsent, CookieYes, the TCF string). Unknown (no cookie yet, a\n // JS-only source like Consent Mode) stays undefined → gated below; the\n // browser decides after hydration. A fixed-value cookie comparison could not\n // express Cookiebot's or OneTrust's format, so consented visitors on those\n // platforms were never server-rendered.\n const consent =\n providerProps.consent ??\n (cf ? (consentFromCookies(cf, (name) => rawCookie(headerStore.get('cookie'), name)) ?? undefined) : undefined);\n const skipSsr = doNotTrack || consent === false || (cf != null && consent !== true);\n // Keyless local mode, by the client's own rule (core init: a `pk_` key or\n // `localMode: false` means hosted). The browser runs on simulated decisions\n // with no network, but the server still called the hosted API with the\n // empty key — every SSR request logged `session upsert failed (401)` and\n // spent a round trip on a decision the client would never use. Nothing\n // hosted runs server-side either.\n const keyless =\n providerProps.localMode === true ||\n (providerProps.localMode !== false && !(typeof providerProps.apiKey === 'string' && providerProps.apiKey.startsWith('pk_')));\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 (!keyless && captureAgents !== false && agentBot) {\n logAgentFetch({ baseUrl, apiKey: providerProps.apiKey, path: agentPath, botName: agentBot, userAgent });\n }\n\n let initialAssignments: ServerAssignments;\n let initialLayoutOrder: string[] | null = null;\n let initialSlots: Record<string, SlotResult> | undefined;\n let initialSlotConfig: LoadAdaptiveDecisionResult['slotConfig'];\n let initialPalette: LoadAdaptiveDecisionResult['palette'];\n let initialVocabulary: LoadAdaptiveDecisionResult['vocabulary'];\n let initialPersona: { persona: string; confidence: number } | null = null;\n // Opt-in theme attribute: this request's stage, coarsened unless 'detailed'.\n let initialStage: string | null = null;\n let ssrSessionId: string | undefined;\n\n // Registry mode only when ids were declared: an unscoped registry decide\n // records a close-out trial for every published slot on every page.\n const registry = !!registrySlotIds?.length;\n\n if (initialAssignmentsOverride) {\n initialAssignments = initialAssignmentsOverride;\n ssrSessionId = ssrSessionIdProp;\n } else if (skipSsr || keyless) {\n // Nothing server-side: no decide, no assign, no session. Components fall\n // back to `ssrFallback`, and the client starts only if the visitor later\n // consents — via the `consent` prop or grantConsent(), neither of which\n // needs a page reload. Keyless: the client's local engine decides.\n initialAssignments = {};\n } else if ((sections && sections.length > 0) || (slots && slots.length > 0) || registry) {\n // `loadAdaptiveDecision` accepted `registrySlotIds` long before AdaptiveRoot\n // passed them, so an `<Adaptive id>` under AdaptiveRoot showed its original\n // children on first paint until the client-side decide returned.\n const decision = await loadAdaptiveDecision({\n sections: sections ?? [],\n components,\n slots,\n ...(registry ? { slotsFrom: 'registry' as const, registrySlotIds } : {}),\n cookies: cookieStore,\n apiKey: providerProps.apiKey,\n baseUrl,\n origin: resolvedOrigin,\n userAgent,\n referer,\n utmParams,\n clickIds,\n landingPath: pathname,\n // doNotTrack is deliberately not passed: it is necessarily false on this\n // branch — a DNT/GPC or consent-gated request already took the skipSsr\n // arm above and never reaches this loader.\n timeoutMs,\n persona: providerProps.persona,\n });\n initialAssignments = decision.assignments;\n initialLayoutOrder = decision.layoutOrder;\n initialSlots = decision.slots;\n initialSlotConfig = decision.slotConfig;\n initialPalette = decision.palette;\n // The site styles the served Redesign trees borrow. Without forwarding\n // them, SSR sites (Bodyshop, 2026-09-24) rendered an approved redesign\n // with no site classes at all — black palette buttons and near-invisible\n // text on a navy card — because the client never re-decides a preloaded\n // slot and so never receives them either.\n initialVocabulary = decision.vocabulary;\n initialPersona =\n decision.persona !== undefined\n ? { persona: decision.persona, confidence: decision.confidence ?? 0 }\n : null;\n initialStage = exposedStage(decision.stage, providerProps.stageAttributes);\n ssrSessionId = decision.sessionId;\n } else {\n const result = await loadAdaptiveAssignments(components, {\n cookies: cookieStore,\n apiKey: providerProps.apiKey,\n baseUrl,\n origin: resolvedOrigin,\n userAgent,\n referer,\n utmParams,\n clickIds,\n landingPath: pathname,\n // doNotTrack is deliberately not passed: it is necessarily false on this\n // branch — a DNT/GPC or consent-gated request already took the skipSsr\n // arm above and never reaches this loader.\n timeoutMs,\n persona: providerProps.persona,\n });\n initialAssignments = result.assignments;\n ssrSessionId = result.sessionId;\n }\n\n // Single-writer inline script — ALWAYS the first child, before any markup\n // that CSS keyed on the persona attributes could style.\n // Not for a request that must not be tracked (DNT/GPC, consent refused or\n // not yet known): with no server decision the script's fallback reads the\n // stored snapshot from localStorage, and reading the device's storage before\n // consent is exactly what a consent gate exists to prevent. The browser SDK\n // takes over once the visitor's platform says yes.\n const personaScript = skipSsr ? null : (\n <SentientPersonaScript\n apiKey={providerProps.apiKey}\n persona={initialPersona}\n nonce={nonce}\n stageAttributes={providerProps.stageAttributes}\n stage={initialStage}\n />\n );\n\n const client = (\n <AdaptiveRootClient\n {...providerProps}\n // The same nonce also covers the <style> the client injects (reveal).\n nonce={nonce}\n // Forward the server-resolved value so a consented visitor's client does\n // not start gated and re-resolve the same cookie on mount.\n consent={consent}\n initialAssignments={initialAssignments}\n initialLayoutOrder={initialLayoutOrder}\n // Declared regardless of what came back, so devtools can preview layout on\n // a page whose decision was gated or timed out.\n declaredSections={sections}\n initialSlots={initialSlots}\n // Registry-mode preload: the hook treats a preloaded slot config as\n // settled, so the client does not decide the same slot a second time.\n initialSlotConfig={initialSlotConfig}\n initialPalette={initialPalette}\n initialVocabulary={initialVocabulary}\n initialPersona={initialPersona ?? undefined}\n sessionSegment={sessionSegment}\n ssrSessionId={ssrSessionId}\n >\n {children}\n </AdaptiveRootClient>\n );\n\n if (!agentFeed) {\n return (\n <>\n {personaScript}\n {client}\n </>\n );\n }\n\n // Server-rendered inline JSON-LD for AI crawlers. Emitted only on the server\n // path so passive crawlers (no JS) see it in the raw HTML. The body escapes\n // '<' so page content cannot break out of the <script> element.\n const feed = buildAgentFeed({\n page: agentPath,\n blocks: assignmentsToBlocks(initialAssignments),\n layoutOrder: initialLayoutOrder ?? undefined,\n content: agentFeed.content,\n });\n\n return (\n <>\n {personaScript}\n <script\n type=\"application/ld+json\"\n nonce={nonce}\n dangerouslySetInnerHTML={{ __html: renderAgentJsonLdBody(feed) }}\n />\n {client}\n </>\n );\n}\n","// `type JSX` from react, not the global namespace removed in @types/react@19\n// (peers allow react >=18) — see adaptive-text.tsx.\nimport type { JSX } from 'react';\nimport { renderPrePaintScript, type StageAttributes } from '@sentientui/core';\nimport { confidenceBand } from '@sentientui/policy';\n\nexport type SentientPersonaScriptProps = {\n /** Publishable API key — selects the localStorage snapshot in the fallback path. */\n apiKey: string;\n /**\n * CSP nonce for the inline pre-paint script. Pass the same nonce your\n * `Content-Security-Policy` `script-src` allows (e.g. from Next.js middleware).\n * Required for strict CSP deployments that block `'unsafe-inline'`.\n */\n nonce?: string;\n /**\n * SSR-decided persona (from `loadAdaptiveDecision`). When present the\n * script embeds the literal values; when absent it reads the local\n * decision snapshot (SPA / return-visit path).\n */\n persona?: { persona: string; confidence: number } | null;\n /**\n * The same consent gate you give the provider. With `consent={false}`, or a\n * `consentFrom` source and no `consent={true}`, nothing is rendered: the\n * fallback reads the stored decision from the visitor's device, and that\n * must wait for consent (grader F3). `AdaptiveRoot` handles this for you.\n */\n consent?: boolean;\n consentFrom?: unknown;\n /**\n * Opt-in `data-sentient-stage` (see `AdaptiveProviderProps.stageAttributes`).\n * With a server decision, pass the value to write as `stage` (already\n * coarsened — `exposedStage` from `@sentientui/core`); without one the\n * script copies the stage the visitor's last decide stored.\n */\n stageAttributes?: StageAttributes;\n /** The stage value to write, from this request's decide; null writes none. */\n stage?: string | null;\n};\n\n/** JSON string literal that is also safe inside an inline <script> element. */\nfunction inlineJsString(value: string): string {\n return JSON.stringify(value).replace(/</g, '\\\\u003c');\n}\n\n/** Exported for tests. Builds the inline JS (concatenation only — no backticks). */\nexport function personaScriptBody(props: SentientPersonaScriptProps): string {\n if (props.persona) {\n return (\n '(function(){try{var d=document.documentElement;' +\n // The stage first, with its own single-writer check: an already-set\n // persona must not stop it. Only a value this request's decide gave.\n (props.stage\n ? 'if(!d.hasAttribute(\"data-sentient-stage\"))d.setAttribute(\"data-sentient-stage\",' + inlineJsString(props.stage) + ');'\n : '') +\n 'if(d.hasAttribute(\"data-sentient-persona\"))return;' +\n 'd.setAttribute(\"data-sentient-persona\",' + inlineJsString(props.persona.persona) + ');' +\n 'd.setAttribute(\"data-sentient-confidence\",' + inlineJsString(confidenceBand(props.persona.confidence)) + ');' +\n '}catch(e){}})();'\n );\n }\n return renderPrePaintScript(props.apiKey, props.stageAttributes ? { stage: true } : undefined);\n}\n\n/**\n * Single writer of the Rung-1a `<html>` attributes\n * (`data-sentient-persona`, `data-sentient-confidence`), executed pre-paint.\n *\n * `AdaptiveRoot` renders this automatically as its first child. For Pages\n * Router / Remix, render it yourself in `_document` / the root layout.\n *\n * IMPORTANT (install docs): add `suppressHydrationWarning` to your `<html>`\n * element — this script mutates documentElement before React hydrates it\n * (the same pattern next-themes uses). The client SDK adopts the attributes\n * as truth and never rewrites them mid-session.\n */\nexport function SentientPersonaScript(props: SentientPersonaScriptProps): JSX.Element | null {\n // A server-decided persona is not a storage read, so it always renders.\n if (!props.persona && (props.consent === false || (props.consentFrom !== undefined && props.consent !== true))) return null;\n return (\n <script\n data-sentient-persona-script=\"\"\n nonce={props.nonce}\n dangerouslySetInnerHTML={{ __html: personaScriptBody(props) }}\n />\n );\n}\n","/**\n * Server-only helpers for Next.js / SSR. No React or DOM APIs.\n */\nimport {\n preloadAssignments,\n readSessionCookie,\n type ServerAssignConfig,\n type ServerAssignments,\n} from '@sentientui/core/server';\n\nexport { preloadAssignments, readSessionCookie };\nexport type { ServerAssignConfig, ServerAssignments };\n\n/** Return value of `loadAdaptiveAssignments` — includes the session ID used for SSR. */\nexport type LoadAdaptiveAssignmentsResult = {\n assignments: ServerAssignments;\n /** The session ID used for SSR assignment. Pass as `ssrSessionId` to `<AdaptiveProvider>`. */\n sessionId: string;\n};\n\nexport type LoadAdaptiveAssignmentsOptions = {\n /** Next.js `cookies()` return value, or any object with `get(name)`. */\n cookies: { get(name: string): { value: string } | undefined };\n apiKey: string;\n baseUrl: string;\n /** Used when `_snt_uid` is absent (e.g. first visit, many crawlers). */\n createSessionId?: () => string;\n /** Must match a value in the project's `allowed_origins` (e.g. `http://localhost:3001`). */\n origin?: string;\n /** From Next.js `headers().get('user-agent')` — aligns SSR segment with the client. */\n userAgent?: string;\n /** From Next.js `headers().get('referer')`. */\n referer?: string;\n /**\n * `utm_*` params from the landing URL. The Referer header never carries the\n * page's OWN query string, so without this the SSR-minted session has no\n * campaign attribution until the client SDK hydrates and re-upserts.\n * Derive with `extractTrackedParams(searchParams)` from `@sentientui/core/server`.\n */\n utmParams?: Record<string, string>;\n /** Ad-platform click IDs (gclid, fbclid, ttclid, …) from the landing URL — same derivation as `utmParams`. */\n clickIds?: Record<string, string>;\n /** The landing page's path (no query string) — recognises a paid click to a product page or a `/discount/` link on the first decision. */\n landingPath?: string;\n /** Set true when the request carries `DNT: 1` or `Sec-GPC: 1` — skips the SSR session upsert + assignment so no session is minted for an opted-out visitor (audit P4). `AdaptiveRoot` sets this automatically from the request headers. */\n doNotTrack?: boolean;\n /** Milliseconds to wait for the API before returning default variants. Defaults to 1000 (typical decide is well under 150 ms; the full budget is only reached on a cold start or a distant API). */\n timeoutMs?: number;\n /**\n * Declared persona — the role your app already knows for this visitor (e.g.\n * from your auth context: 'admin', 'evaluator'). Must be a key in the\n * project's persona vocabulary; unrecognized values are ignored server-side.\n * Never a user id or email.\n */\n persona?: string;\n};\n\nfunction defaultSessionId(): string {\n if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {\n return crypto.randomUUID();\n }\n return `snt-${Date.now()}-${Math.random().toString(36).slice(2, 11)}`;\n}\n\n/**\n * Fetches bandit assignments on the server for SEO-safe HTML.\n * Pass `assignments` as `initialAssignments` and `sessionId` as `ssrSessionId`\n * on `<AdaptiveProvider>` so the client adopts the same session on first visit.\n */\nexport async function loadAdaptiveAssignments(\n components: Array<{ id: string; variantIds: string[] }>,\n options: LoadAdaptiveAssignmentsOptions,\n): Promise<LoadAdaptiveAssignmentsResult> {\n // apiKey is not optional here: the client writes the per-project suffixed\n // cookie, so an un-keyed read missed every returning visitor and minted a\n // fresh orphan session per SSR request (see readSessionCookie in core).\n const sessionId =\n readSessionCookie(options.cookies, options.apiKey) ??\n options.createSessionId?.() ??\n defaultSessionId();\n\n const assignments = await preloadAssignments(components, sessionId, {\n apiKey: options.apiKey,\n baseUrl: options.baseUrl,\n origin: options.origin,\n userAgent: options.userAgent,\n referer: options.referer,\n utmParams: options.utmParams,\n clickIds: options.clickIds,\n landingPath: options.landingPath,\n doNotTrack: options.doNotTrack,\n timeoutMs: options.timeoutMs,\n persona: options.persona,\n });\n\n return { assignments, sessionId };\n}\n\nexport { preloadDecisions } from '@sentientui/core/server';\nexport type { DecideResult, SlotDeclInput, SlotResult } from '@sentientui/core/server';\n\n/** Return value of `loadAdaptiveDecision` — includes the session ID used for SSR. */\nexport type LoadAdaptiveDecisionResult = import('@sentientui/core/server').DecideResult & {\n sessionId: string;\n};\n\nexport type LoadAdaptiveDecisionOptions = LoadAdaptiveAssignmentsOptions & {\n /**\n * Section IDs in default order. Passed to /v1/decide as the candidate\n * layout. Optional since 0.13.0 — slot-only pages may omit it (at least\n * one of `sections`/`components`/`slots` must be non-empty).\n */\n sections?: string[];\n /** Components to assign in the same decide call. */\n components?: Array<{ id: string; variantIds?: string[] }>;\n /** Adaptive-slot declarations (useAdaptiveTokens / AdaptiveGroup) to decide server-side. */\n slots?: import('@sentientui/core/server').SlotDeclInput[];\n /** 'registry' serves the project's published slot definitions (`<Adaptive id>`)\n * and is the only way `slotConfig`/`palette` come back. Default 'request'.\n * Requires `registrySlotIds`. */\n slotsFrom?: 'request' | 'registry';\n /**\n * Registry mode: the `<Adaptive id>`s THIS page renders — the decide is\n * scoped to exactly these. Required with `slotsFrom: 'registry'`; without it\n * the call downgrades to request mode (with a console.error) instead of\n * recording a close-out trial for every published slot on every page.\n */\n registrySlotIds?: string[];\n};\n\n/**\n * SSR helper for pages with a declared section layout and/or adaptive slots.\n * Calls `/v1/decide` instead of multiple `/v1/assign` round trips.\n * Pass `sessionId` as `ssrSessionId` on `<AdaptiveProvider>` so the client\n * adopts the same session on first visit.\n *\n * Keyless: with no valid `pk_` key this never fetches (no timeout burn).\n * Under the `development` export condition the decision is computed by the\n * deterministic local engine with the same sessionId the client will adopt —\n * server and client agree by construction. In production the engine resolves\n * to a stub and defaults are returned with one console.error.\n */\nexport async function loadAdaptiveDecision(\n options: LoadAdaptiveDecisionOptions,\n): Promise<LoadAdaptiveDecisionResult> {\n const { preloadDecisions, readSessionCookie } = await import('@sentientui/core/server');\n\n // Keyed read — the client's cookie name is suffixed per project (see\n // loadAdaptiveAssignments above). Works for keyless too: with no pk_ key the\n // client writes the bare legacy name, which the un-suffixed read falls back to.\n const sessionId =\n readSessionCookie(options.cookies, options.apiKey) ??\n options.createSessionId?.() ??\n defaultSessionId();\n\n const keyValid = typeof options.apiKey === 'string' && options.apiKey.startsWith('pk_');\n if (!keyValid) {\n const fallback: LoadAdaptiveDecisionResult = {\n layoutOrder: options.sections ?? [],\n assignments: {},\n slots: {},\n persona: 'unknown',\n confidence: 0,\n sessionId,\n };\n try {\n const mod = (await import('@sentientui/core/local')) as unknown as {\n LOCAL_ENGINE_AVAILABLE: boolean;\n createLocalEngine(opts: { sessionId: string }): {\n decide(input: {\n sections?: string[];\n components?: Array<{ id: string; variantIds?: string[] }>;\n slots?: LoadAdaptiveDecisionOptions['slots'];\n }): {\n layoutOrder: string[] | null;\n assignments: Record<string, string>;\n slots: Record<string, string | Record<string, string>>;\n persona: string;\n confidence: number;\n };\n };\n };\n if (!mod.LOCAL_ENGINE_AVAILABLE) {\n // Pinned message — must byte-match PROD_KEYLESS_ERROR in @sentientui/core.\n console.error(\n '[sentient] No API key configured — nothing is being learned. Set NEXT_PUBLIC_SENTIENT_API_KEY or pass localMode: true for local development.',\n );\n return fallback;\n }\n const outcome = mod.createLocalEngine({ sessionId }).decide({\n sections: options.sections,\n components: options.components ?? [],\n slots: options.slots ?? [],\n });\n return {\n layoutOrder: outcome.layoutOrder ?? options.sections ?? [],\n assignments: outcome.assignments,\n slots: outcome.slots,\n persona: outcome.persona,\n confidence: outcome.confidence,\n sessionId,\n };\n } catch {\n return fallback;\n }\n }\n\n const result = await preloadDecisions(\n {\n sections: options.sections,\n components: options.components ?? [],\n slots: options.slots ?? [],\n slotsFrom: options.slotsFrom,\n registrySlotIds: options.registrySlotIds,\n },\n sessionId,\n {\n apiKey: options.apiKey,\n baseUrl: options.baseUrl,\n origin: options.origin,\n userAgent: options.userAgent,\n referer: options.referer,\n utmParams: options.utmParams,\n clickIds: options.clickIds,\n landingPath: options.landingPath,\n doNotTrack: options.doNotTrack,\n timeoutMs: options.timeoutMs,\n persona: options.persona,\n },\n );\n\n return { ...result, sessionId };\n}\n","/**\n * Agent-readable content feed. Merges SDK-known data (winning variants, layout\n * order) with developer-supplied page content, and renders it either as a\n * server-rendered inline JSON-LD block (read by passive AI crawlers, which do\n * not run JS) or as Markdown (for agents that content-negotiate `text/markdown`).\n *\n * No React or DOM APIs — safe to import in server components, route handlers,\n * and middleware.\n */\n\nexport type AgentBlock = {\n /** Component ID. */\n id: string;\n /** Winning variant ID currently served. */\n variant: string;\n /** Agent-readable data attached to the served variant, if any. */\n content?: unknown;\n};\n\nexport type AgentFeed = {\n page: string;\n title?: string;\n summary?: string;\n layoutOrder?: string[];\n blocks: AgentBlock[];\n /** Developer-supplied extra fields (products, specs, arbitrary JSON). */\n [key: string]: unknown;\n};\n\n/** Fields the SDK owns — developer content can never overwrite these. */\nconst RESERVED_FIELDS = ['page', 'blocks', 'layoutOrder'] as const;\n\nconst registry = new Map<string, Record<string, unknown>>();\n\n/**\n * Register page-level structured content the SDK can't infer (title, summary,\n * product fields, arbitrary JSON), keyed by page path. Call at module load.\n */\nexport function defineAgentContent(page: string, content: Record<string, unknown>): void {\n registry.set(page, content);\n}\n\n/** Look up registered content for a page. */\nexport function getAgentContent(page: string): Record<string, unknown> | undefined {\n return registry.get(page);\n}\n\n/** Clear the registry — intended for tests. */\nexport function clearAgentContent(): void {\n registry.clear();\n}\n\n/**\n * Merge SDK-known data with developer-supplied content into a single feed.\n * Developer content fills in title/summary/etc. but can never overwrite the\n * SDK-authoritative fields (`page`, `blocks`, `layoutOrder`).\n */\nexport function buildAgentFeed(input: {\n page: string;\n blocks: AgentBlock[];\n layoutOrder?: string[];\n content?: Record<string, unknown>;\n}): AgentFeed {\n const supplied = input.content ?? getAgentContent(input.page) ?? {};\n const safe: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(supplied)) {\n if (!(RESERVED_FIELDS as readonly string[]).includes(k)) safe[k] = v;\n }\n const feed: AgentFeed = {\n ...safe,\n page: input.page,\n blocks: input.blocks,\n };\n if (input.layoutOrder) feed.layoutOrder = input.layoutOrder;\n return feed;\n}\n\n/**\n * Render the feed as a server-rendered inline JSON-LD `<script>` string. `<` is\n * escaped to `<` so embedded content cannot break out of the script\n * element. MUST be emitted on the server — passive crawlers never run client JS.\n */\nexport function renderAgentJsonLd(feed: AgentFeed): string {\n return `<script type=\"application/ld+json\">${renderAgentJsonLdBody(feed)}</script>`;\n}\n\n/**\n * The escaped JSON-LD body only (no `<script>` wrapper). For React server\n * components, inject via `<script type=\"application/ld+json\"\n * dangerouslySetInnerHTML={{ __html: renderAgentJsonLdBody(feed) }} />`.\n */\nexport function renderAgentJsonLdBody(feed: AgentFeed): string {\n return JSON.stringify({ '@context': 'https://schema.org', '@type': 'WebPage', ...feed })\n .replace(/</g, '\\\\u003c');\n}\n\n/** Render the feed as Markdown for agents that negotiate `text/markdown`. */\nexport function renderAgentMarkdown(feed: AgentFeed): string {\n const lines: string[] = [];\n if (feed.title) lines.push(`# ${feed.title}`, '');\n if (feed.summary) lines.push(String(feed.summary), '');\n\n for (const [k, v] of Object.entries(feed)) {\n if (['page', 'title', 'summary', 'blocks', 'layoutOrder'].includes(k)) continue;\n lines.push(`## ${k}`, '', '```json', JSON.stringify(v, null, 2), '```', '');\n }\n\n if (feed.blocks.length > 0) {\n lines.push('## blocks', '');\n for (const b of feed.blocks) {\n lines.push(`- **${b.id}** → variant \\`${b.variant}\\``);\n if (b.content !== undefined) {\n lines.push('', ' ```json', JSON.stringify(b.content, null, 2), ' ```');\n }\n }\n lines.push('');\n }\n\n return lines.join('\\n').trimEnd() + '\\n';\n}\n","// Fire-and-forget server-side log of a known AI-agent fetch to crawler_requests\n// (via POST /v1/crawler-events). Machine telemetry — no cookie, no session.\n// MUST NOT throw or be awaited into the render path.\nexport type AgentFetchLog = {\n baseUrl: string; // API base ending in /v1\n apiKey: string; // public pk_ key\n path: string;\n botName: string;\n userAgent?: string;\n};\n\nexport function logAgentFetch(entry: AgentFetchLog, deps: { fetchImpl?: typeof fetch } = {}): void {\n const doFetch = deps.fetchImpl ?? fetch;\n try {\n void doFetch(`${entry.baseUrl}/crawler-events`, {\n method: 'POST',\n headers: { 'content-type': 'application/json', authorization: `Bearer ${entry.apiKey}` },\n body: JSON.stringify({\n path: entry.path,\n botName: entry.botName,\n userAgent: entry.userAgent ?? null,\n source: 'ssr',\n }),\n }).catch(() => {});\n } catch {\n /* never break render */\n }\n}\n","/**\n * `createAgentFeed` — a framework-standard Route Handler (Web `Request` →\n * `Response`) that serves the agent-readable feed via HTTP content negotiation:\n * `text/markdown` (Accept header or `.md` URL) → Markdown, otherwise JSON.\n *\n * This is the secondary channel of the agent-readable design — for agents that\n * *ask* (coding agents, agents the customer controls, future crawlers). The\n * primary channel is the server-rendered inline JSON-LD from `<AdaptiveRoot>`.\n *\n * Every fetch is reported to `onRead` (best-effort) so it can be logged to\n * `crawler_requests` and counted in the dashboard traffic breakdown.\n */\nimport { matchedAgentToken } from '@sentientui/core';\nimport { renderAgentMarkdown, type AgentFeed } from '../agent-feed.js';\n\nexport type AgentFeedReadEntry = {\n path: string;\n userAgent: string | null;\n botName: string | null;\n};\n\nexport type AgentFeedRouteConfig = {\n /** Resolve the feed for a request (winning variants + layout + dev content). */\n getFeed: (request: Request) => Promise<AgentFeed> | AgentFeed;\n /** Best-effort per-fetch hook — log to `crawler_requests` here. Never awaited into the response. */\n onRead?: (entry: AgentFeedReadEntry) => void | Promise<void>;\n};\n\nfunction wantsMarkdown(url: URL, accept: string): boolean {\n return url.pathname.endsWith('.md') || accept.toLowerCase().includes('text/markdown');\n}\n\nexport function createAgentFeed(\n config: AgentFeedRouteConfig,\n): (request: Request) => Promise<Response> {\n return async (request: Request): Promise<Response> => {\n const url = new URL(request.url);\n const accept = request.headers.get('accept') ?? '';\n const userAgent = request.headers.get('user-agent');\n // Strip the .md/.json suffix so the feed path matches the page path.\n const path = url.pathname.replace(/\\.(md|json)$/, '');\n\n if (config.onRead) {\n try {\n void Promise.resolve(\n config.onRead({ path, userAgent, botName: matchedAgentToken(userAgent ?? '') }),\n ).catch(() => {});\n } catch {\n /* logging must never break the response */\n }\n }\n\n const feed = await config.getFeed(request);\n\n if (wantsMarkdown(url, accept)) {\n return new Response(renderAgentMarkdown(feed), {\n headers: { 'content-type': 'text/markdown; charset=utf-8' },\n });\n }\n return new Response(JSON.stringify(feed), {\n headers: { 'content-type': 'application/json; charset=utf-8' },\n });\n };\n}\n"],"mappings":"+lBAAA,OAAS,wBAAAA,GAAsB,gBAAAC,GAAc,wBAAAC,GAAsB,qBAAAC,OAAyB,mBAC5F,OAAS,sBAAAC,OAA0B,2BAEnC,OAAS,WAAAC,GAAS,WAAAC,OAAe,eCAjC,OAAS,wBAAAC,OAAkD,mBAC3D,OAAS,kBAAAC,OAAsB,qBA4E3B,cAAAC,OAAA,oBAvCJ,SAASC,EAAeC,EAAuB,CAC7C,OAAO,KAAK,UAAUA,CAAK,EAAE,QAAQ,KAAM,SAAS,CACtD,CAGO,SAASC,GAAkBC,EAA2C,CAC3E,OAAIA,EAAM,QAEN,mDAGCA,EAAM,MACH,kFAAoFH,EAA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AA,EAAkB,OAClC,eAAgBpB,GAChB,aAAcsB,EAEb,SAAAnC,GACH,EAGF,GAAI,CAACH,EACH,OACE/B,GAAAF,GAAA,CACG,UAAAgF,EACAE,GACH,EAOJ,IAAME,GAAOC,EAAe,CAC1B,KAAM1B,EACN,OAAQvD,GAAoB2D,CAAkB,EAC9C,YAAaC,GAAA,KAAAA,EAAsB,OACnC,QAAS/B,EAAU,OACrB,CAAC,EAED,OACE/B,GAAAF,GAAA,CACG,UAAAgF,EACD/E,EAAC,UACC,KAAK,sBACL,MAAOkC,EACP,wBAAyB,CAAE,OAAQmD,GAAsBF,EAAI,CAAE,EACjE,EACCF,GACH,CAEJ","names":["deriveSessionSegment","exposedStage","extractTrackedParams","matchedAgentToken","consentFromCookies","cookies","headers","renderPrePaintScript","confidenceBand","jsx","inlineJsString","value","personaScriptBody","props","SentientPersonaScript","preloadAssignments","readSessionCookie","preloadDecisions","defaultSessionId","loadAdaptiveAssignments","components","options","_a","_b","_c","sessionId","readSessionCookie","preloadAssignments","loadAdaptiveDecision","_d","_e","_f","_g","_h","_i","_j","preloadDecisions","fallback","mod","outcome","e","result","__spreadProps","__spreadValues","AdaptiveRootClient","RESERVED_FIELDS","registry","defineAgentContent","page","content","getAgentContent","buildAgentFeed","input","_a","_b","supplied","getAgentContent","safe","k","v","RESERVED_FIELDS","feed","__spreadProps","__spreadValues","renderAgentJsonLdBody","feed","__spreadValues","renderAgentMarkdown","lines","k","v","b","logAgentFetch","entry","deps","_a","_b","doFetch","e","matchedAgentToken","wantsMarkdown","url","accept","createAgentFeed","config","request","_a","userAgent","path","matchedAgentToken","e","feed","renderAgentMarkdown","matchedAgentToken","uaTokenMatch","agentIntent","classifiedAgents","Fragment","jsx","jsxs","DEFAULT_API_BASE_URL","assignmentsToBlocks","assignments","id","v","_a","rawCookie","header","name","part","eq","AdaptiveRoot","props","_b","_c","_d","_e","_f","_g","_h","components","sections","slots","registrySlotIds","appOrigin","searchParams","pathname","initialAssignmentsOverride","ssrSessionIdProp","timeoutMs","agentFeed","captureAgents","nonce","children","providerProps","__objRest","headerStore","headers","host","resolvedOrigin","userAgent","referer","utmParams","clickIds","extractTrackedParams","doNotTrack","sessionSegment","deriveSessionSegment","cookieStore","cookies","cf","consent","consentFromCookies","skipSsr","keyless","baseUrl","agentPath","agentBot","matchedAgentToken","logAgentFetch","initialAssignments","initialLayoutOrder","initialSlots","initialSlotConfig","initialPalette","initialVocabulary","initialPersona","initialStage","ssrSessionId","registry","decision","loadAdaptiveDecision","__spreadProps","__spreadValues","exposedStage","result","loadAdaptiveAssignments","personaScript","SentientPersonaScript","client","AdaptiveRootClient","feed","buildAgentFeed","renderAgentJsonLdBody"]}
|
|
1
|
+
{"version":3,"sources":["../../src/next/adaptive-root.tsx","../../src/persona-script.tsx","../../src/server.ts","../../src/agent-feed.ts","../../src/next/log-agent-fetch.ts","../../src/next/agent-feed-route.ts"],"sourcesContent":["import { deriveSessionSegment, exposedStage, extractTrackedParams, matchedAgentToken } from '@sentientui/core';\nimport { consentFromCookies } from '@sentientui/core/consent';\nimport type { RenderCaps, SlotDeclInput, SlotResult } from '@sentientui/core';\nimport { cookies, headers } from 'next/headers';\n// `type JSX` from react, not the global namespace removed in @types/react@19\n// (peers allow react >=18) — see adaptive-text.tsx.\nimport type { JSX, ReactNode } from 'react';\nimport type { AdaptiveProviderProps } from '../provider.js';\nimport { SentientPersonaScript } from '../persona-script.js';\nimport {\n loadAdaptiveAssignments,\n loadAdaptiveDecision,\n type LoadAdaptiveDecisionResult,\n type ServerAssignments,\n} from '../server.js';\nimport { AdaptiveRootClient } from './adaptive-root-client.js';\nimport { buildAgentFeed, renderAgentJsonLdBody, type AgentBlock } from '../agent-feed.js';\nimport { logAgentFetch } from './log-agent-fetch.js';\n\nexport { createAgentFeed } from './agent-feed-route.js';\nexport type { AgentFeedRouteConfig, AgentFeedReadEntry } from './agent-feed-route.js';\nexport { defineAgentContent, buildAgentFeed as buildAgentFeedFor } from '../agent-feed.js';\n// Re-exported from core on the SERVER entry (this module is server-only — it\n// imports next/headers). Lets server components do agent detection with just the\n// `@sentientui/react` package, no direct core dependency. Do NOT add this to the\n// package's client index: re-exporting a plain function through a 'use client'\n// module turns it into a client reference that throws when called during SSR.\nexport { matchedAgentToken, uaTokenMatch, agentIntent, classifiedAgents } from '@sentientui/core';\nexport type { AgentIntent } from '@sentientui/core';\nexport type { AgentFeed } from '../agent-feed.js';\n\nconst DEFAULT_API_BASE_URL = 'https://api.sentient-ui.com/v1';\n\nexport type PreloadComponent = { id: string; variantIds: string[] };\n\n/** A registry `<Adaptive id>` declared with what it can render — see `AdaptiveRootProps.registrySlots`. */\nexport type RegistrySlotDecl = {\n id: string;\n /** The `variants` keys of a hybrid `<Adaptive variants>{children}</Adaptive>`. */\n authored?: string[];\n /** The `<Adaptive>` has an `onFormSubmit`. @default true */\n forms?: boolean;\n};\n\nexport type AdaptiveRootProps = Omit<\n AdaptiveProviderProps,\n // Every provider prop AdaptiveRoot itself resolves and passes AFTER the\n // {...providerProps} spread must be omitted here: a caller-supplied value\n // would typecheck but be silently clobbered by the spread order\n // (initialLayoutOrder, declaredSections and sessionSegment were missing\n // from this list and suffered exactly that).\n | 'initialAssignments'\n | 'onAssignment'\n | 'initialSlots'\n | 'initialSlotConfig'\n | 'initialPalette'\n | 'initialVocabulary'\n | 'initialPersona'\n | 'initialLayoutOrder'\n | 'declaredSections'\n | 'sessionSegment'\n | 'consentFrom'\n> & {\n /**\n * Consent source — see `AdaptiveProviderProps.consentFrom`. A platform preset\n * (`'cookiebot'`, `'onetrust'`, `'cookieyes'`, `'tcf'`, `'google-consent-mode'`)\n * or a cookie. Resolved on the server from the platform's own cookie, so a\n * visitor who already consented gets SSR with no layout shift.\n *\n * No `check` form: AdaptiveRoot is a Server Component and spreads\n * this straight into its client boundary, and a function prop crossing the\n * server→client boundary throws at render (\"Functions cannot be passed\n * directly to Client Components\"). The provider's type accepted `check`, so\n * a Cookiebot-style predicate typechecked here and then crashed the layout.\n * Need a JS-API CMP predicate? Use `<AdaptiveProvider>` in a client component.\n */\n consentFrom?: Exclude<NonNullable<AdaptiveProviderProps['consentFrom']>, { check?: () => boolean; cmp?: undefined }> | { cmp?: undefined; cookie?: string; value?: string; event?: string };\n /**\n * Code-variant components to assign server-side (SEO-safe). Optional — an\n * `<Adaptive>` works without an entry here and assigns after mount.\n *\n * List only ids this tree actually renders. Each one is assigned on every\n * request, rendered or not, and every assignment logs an impression (or a\n * holdout exposure). An id the page never renders therefore accrues trials\n * that cannot convert, and in a root layout that happens on every route.\n */\n components?: PreloadComponent[];\n /**\n * Declare page section IDs in their default order. When provided,\n * AdaptiveRoot calls `/v1/decide` (single round trip) instead of\n * individual `/v1/assign` calls, and `useLayoutOrder()` returns the\n * persona-specific order on first render.\n *\n * Give each section's rendered element `data-sentient-id=\"<sectionId>\"` —\n * the only markup a section needs — so the DOM graph scanner can register\n * it under the same id. Without it the server never learns what the section\n * IS, types it `generic`, and serves the identity order to every persona —\n * the integration looks live but cannot personalize. The provider warns\n * about unresolvable ids in development. Correct a section the content\n * classifier mistypes with `sectionTypes`, not extra markup.\n *\n * @example sections={['hero', 'pricing', 'features', 'social_proof']}\n * // …and in the tree: <section data-sentient-id=\"pricing\">\n */\n sections?: string[];\n /**\n * Adaptive-slot declarations used by `useAdaptiveTokens` / `AdaptiveGroup`\n * in this tree. Declaring them here decides them in the same SSR\n * round trip, so their values serialize into the server HTML.\n */\n slots?: SlotDeclInput[];\n /**\n * The generated-mode `<Adaptive id>`s THIS page renders. Declaring them\n * decides their published versions in the same SSR round trip\n * (`/v1/decide` registry mode) and serializes the served content into the\n * server HTML, so the first paint shows the version rather than the\n * original children until the client-side decide answers. Without it a\n * registry slot renders its children first and swaps after mount.\n *\n * Scoped to exactly these ids on purpose: an unscoped registry decide\n * records a close-out trial for every published slot on every page.\n *\n * @example registrySlotIds={['hero-headline', 'pricing-cta']}\n */\n registrySlotIds?: string[];\n /**\n * Like `registrySlotIds`, for `<Adaptive id>`s that need to tell the server\n * more than their id. Most often that is a hybrid —\n * `<Adaptive id variants={{ a, b }}>{original}</Adaptive>`. List its\n * `variants` keys as `authored`, or the SSR decide cannot draw them. In that\n * case the first paint can only be the original or a generated version, and\n * the hand-written ones appear only on pages the browser decides.\n *\n * `forms`: whether the `<Adaptive>` has an `onFormSubmit`. Declare\n * `forms: false` when it has none, or SSR can draw a generated form version\n * that the page then refuses. The default is `true`, the same as a bare\n * `registrySlotIds` entry.\n *\n * You may list an id in both props: it is decided once, with these caps.\n *\n * @example registrySlots={[{ id: 'hero_cta', authored: ['action', 'social'], forms: false }]}\n */\n registrySlots?: RegistrySlotDecl[];\n /** App origin — must be in the project's `allowed_origins`. */\n appOrigin?: string;\n /**\n * The page's `searchParams` prop (or an equivalent query string /\n * URLSearchParams). Server Components cannot read the request URL from\n * `headers()`, so without this the SSR-minted session carries no `utm_*`\n * params and no ad click IDs (gclid, fbclid, ttclid, …) — campaign\n * attribution only lands after client hydration, and never for visits the\n * client SDK doesn't get to finish (bounce before hydrate). Pass it on\n * landing pages that receive ad traffic:\n *\n * ```tsx\n * export default async function Page({ searchParams }: { searchParams: Promise<Record<string, string | string[] | undefined>> }) {\n * return <AdaptiveRoot ... searchParams={await searchParams}>...</AdaptiveRoot>;\n * }\n * ```\n */\n searchParams?: Record<string, string | string[] | undefined> | URLSearchParams | string;\n /**\n * The page's path (e.g. `/products/trail-shoe`). Server components cannot\n * read their own URL, so pass it on landing pages that receive ad or email\n * traffic: with it, a paid click to a product page or a `/discount/` link\n * is recognised on the server render — adapted from the first byte.\n */\n pathname?: 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 * A cookie's value exactly as the browser sent it. The CMP parsers need the\n * raw form: Next's cookies() decodes every value, which turns an encoded\n * `&groups=C0002:1` inside OneTrust's `landingPath` (a crafted link, before\n * any answer) into a real field that read as consent on the server — SSR\n * then minted a session and handed the client consent={true} (grader R8 NEW-1).\n * First match wins, like the browser's document.cookie read. A consent cookie\n * set only by middleware in this request is not in the header: the server\n * then reads \"unknown\" and the browser decides (fail-closed).\n */\nfunction rawCookie(header: string | null | undefined, name: string): string | undefined {\n if (!header) return undefined;\n for (const part of header.split(';')) {\n const eq = part.indexOf('=');\n if (eq > 0 && part.slice(0, eq).trim() === name) return part.slice(eq + 1).trim();\n }\n return undefined;\n}\n\n/**\n * Next.js Server Component that resolves variant assignments (and optionally\n * section layout order) server-side for zero layout shift on first paint.\n *\n * When `sections` is provided, a single `POST /v1/decide` call returns both\n * the persona-specific section order and all component assignments.\n * Without `sections`, individual `/v1/assign` calls are made per component.\n *\n * @example\n * // app/page.tsx — with section layout. Declared on the page (not the root\n * // layout) because hero_cta renders only here; see the `components` prop.\n * import { AdaptiveRoot } from '@sentientui/react/next';\n *\n * export default async function Page() {\n * return (\n * <AdaptiveRoot\n * apiKey={process.env.NEXT_PUBLIC_SENTIENT_API_KEY!}\n * sections={['hero', 'pricing', 'features', 'social_proof']}\n * components={[\n * { id: 'hero_cta', variantIds: ['default', 'accent'] },\n * ]}\n * >\n * <HeroSection />\n * <PricingSection />\n * <FeaturesSection />\n * <SocialProofSection />\n * </AdaptiveRoot>\n * );\n * }\n */\nexport async function AdaptiveRoot(props: AdaptiveRootProps): Promise<JSX.Element> {\n const {\n components = [],\n sections,\n slots,\n registrySlotIds: registrySlotIdsProp,\n registrySlots,\n appOrigin,\n searchParams,\n pathname,\n initialAssignments: initialAssignmentsOverride,\n ssrSessionId: ssrSessionIdProp,\n timeoutMs,\n agentFeed,\n captureAgents,\n nonce,\n children,\n ...providerProps\n } = props;\n\n const headerStore = await headers();\n const host = headerStore.get('host');\n if (!appOrigin && process.env.NODE_ENV === 'production' && !host) {\n console.error(\n '[SentientUI] AdaptiveRoot: Host header is absent and no appOrigin was provided. ' +\n 'Pass appOrigin explicitly — the https://localhost fallback will likely fail allowed_origins validation.',\n );\n }\n const resolvedOrigin = appOrigin ??\n (process.env.NODE_ENV === 'production'\n ? `https://${host ?? 'localhost'}`\n : 'http://localhost:3001');\n const userAgent = headerStore.get('user-agent') ?? undefined;\n const referer = headerStore.get('referer') ?? undefined;\n // Landing-URL attribution (utm_* + ad click IDs). Only available when the\n // page passes its searchParams down — headers() never carries the request's\n // own query string, and the Referer is the PREVIOUS page, not this one.\n const { utmParams, clickIds } = extractTrackedParams(searchParams ?? {});\n // Honor a tracking opt-out at SSR: `DNT: 1` or the legally-enforceable\n // `Sec-GPC: 1`. When set we skip the session upsert + assign/decide so no\n // session row is minted for the visitor (audit P4) — matching the client SDK,\n // which already no-ops for these signals.\n const doNotTrack = headerStore.get('dnt') === '1' || headerStore.get('sec-gpc') === '1';\n // `consent: false` must gate the SERVER too, not just the client. Without\n // this the SSR decide/assign still ran and still minted a session row for a\n // visitor who had not consented — contradicting the documented contract\n // (\"no SDK is initialised, no cookies are written, no events are sent\") and\n // forcing sites to hide AdaptiveRoot behind a conditional render, which is\n // what made consent-after-load cost a full server round trip.\n const sessionSegment = deriveSessionSegment({ userAgent, referer, appOrigin: resolvedOrigin });\n const cookieStore = await cookies();\n\n // This is a Server Component and already has the request cookies, so resolve\n // a cookie-based `consentFrom` here rather than making the app read the same\n // cookie again just to pass `consent` — naming it twice only invites drift.\n // An already-consented visitor therefore gets SSR variant assignment (zero\n // layout shift) with no extra code.\n //\n // An explicit `consent` prop always wins — it is the escape hatch for apps\n // that track consent elsewhere. (No `check()` form here: see the prop type.)\n //\n // Consent gates the SERVER too, not just the client: without it the SSR\n // decide/assign still ran and still minted a session row for a visitor who\n // had not consented, contradicting the documented contract (\"no SDK is\n // initialised, no cookies are written, no events are sent\").\n const cf = providerProps.consentFrom;\n // The platform's own cookie (Cookiebot CookieConsent, OneTrust\n // OptanonConsent, CookieYes, the TCF string). Unknown (no cookie yet, a\n // JS-only source like Consent Mode) stays undefined → gated below; the\n // browser decides after hydration. A fixed-value cookie comparison could not\n // express Cookiebot's or OneTrust's format, so consented visitors on those\n // platforms were never server-rendered.\n const consent =\n providerProps.consent ??\n (cf ? (consentFromCookies(cf, (name) => rawCookie(headerStore.get('cookie'), name)) ?? undefined) : undefined);\n const skipSsr = doNotTrack || consent === false || (cf != null && consent !== true);\n // Keyless local mode, by the client's own rule (core init: a `pk_` key or\n // `localMode: false` means hosted). The browser runs on simulated decisions\n // with no network, but the server still called the hosted API with the\n // empty key — every SSR request logged `session upsert failed (401)` and\n // spent a round trip on a decision the client would never use. Nothing\n // hosted runs server-side either.\n const keyless =\n providerProps.localMode === true ||\n (providerProps.localMode !== false && !(typeof providerProps.apiKey === 'string' && providerProps.apiKey.startsWith('pk_')));\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 (!keyless && captureAgents !== false && agentBot) {\n logAgentFetch({ baseUrl, apiKey: providerProps.apiKey, path: agentPath, botName: agentBot, userAgent });\n }\n\n let initialAssignments: ServerAssignments;\n // SSR-declared components the operator moved onto the shared track: the\n // client renders them as slots (children:false, first variant key = the\n // original) instead of seeding a frozen variant (ruling C20).\n let initialUnified: string[] | undefined;\n let initialLayoutOrder: string[] | null = null;\n let initialSlots: Record<string, SlotResult> | undefined;\n let initialSlotConfig: LoadAdaptiveDecisionResult['slotConfig'];\n let initialPalette: LoadAdaptiveDecisionResult['palette'];\n let initialVocabulary: LoadAdaptiveDecisionResult['vocabulary'];\n let initialPersona: { persona: string; confidence: number } | null = null;\n // Opt-in theme attribute: this request's stage, coarsened unless 'detailed'.\n let initialStage: string | null = null;\n let ssrSessionId: string | undefined;\n\n // One decided id list from both props, each id once. The caps come only from\n // `registrySlots` entries: a bare id keeps core's default.\n const registrySlotIds = [...new Set([...(registrySlotIdsProp ?? []), ...(registrySlots ?? []).map((d) => d.id)])];\n // The caps a mounted AdaptiveSlot sends, minus the fingerprint (it needs a\n // DOM).\n // - `ops: false`: React never applies ops (see core's preloadDecisions).\n // - `children: true`: a hybrid's original is a real arm, so the server keeps\n // drawing `baseline` next to `authored.*`. A migrated variants-only\n // component's `children: false` comes from the decide's handed-off path,\n // not from here.\n const renderCaps: Record<string, Omit<RenderCaps, 'fp'>> | undefined = registrySlots?.length\n ? Object.fromEntries(registrySlots.map((d) => [d.id, {\n forms: d.forms ?? true,\n compose: true,\n ops: false,\n ...(d.authored?.length ? { authored: d.authored, children: true } : {}),\n }]))\n : undefined;\n // Registry mode only when ids were declared: an unscoped registry decide\n // records a close-out trial for every published slot on every page.\n const registry = registrySlotIds.length > 0;\n\n if (initialAssignmentsOverride) {\n initialAssignments = initialAssignmentsOverride;\n ssrSessionId = ssrSessionIdProp;\n } else if (skipSsr || keyless) {\n // Nothing server-side: no decide, no assign, no session. Components fall\n // back to `ssrFallback`, and the client starts only if the visitor later\n // consents — via the `consent` prop or grantConsent(), neither of which\n // needs a page reload. Keyless: the client's local engine decides.\n initialAssignments = {};\n } else if ((sections && sections.length > 0) || (slots && slots.length > 0) || registry) {\n // `loadAdaptiveDecision` accepted `registrySlotIds` long before AdaptiveRoot\n // passed them, so an `<Adaptive id>` under AdaptiveRoot showed its original\n // children on first paint until the client-side decide returned.\n const decision = await loadAdaptiveDecision({\n sections: sections ?? [],\n components,\n slots,\n ...(registry ? { slotsFrom: 'registry' as const, registrySlotIds, ...(renderCaps ? { renderCaps } : {}) } : {}),\n cookies: cookieStore,\n apiKey: providerProps.apiKey,\n baseUrl,\n origin: resolvedOrigin,\n userAgent,\n referer,\n utmParams,\n clickIds,\n landingPath: pathname,\n // doNotTrack is deliberately not passed: it is necessarily false on this\n // branch — a DNT/GPC or consent-gated request already took the skipSsr\n // arm above and never reaches this loader.\n timeoutMs,\n persona: providerProps.persona,\n });\n initialAssignments = decision.assignments;\n initialUnified = decision.unified;\n initialLayoutOrder = decision.layoutOrder;\n initialSlots = decision.slots;\n initialSlotConfig = decision.slotConfig;\n initialPalette = decision.palette;\n // The site styles the served Redesign trees borrow. Without forwarding\n // them, SSR sites (Bodyshop, 2026-09-24) rendered an approved redesign\n // with no site classes at all — black palette buttons and near-invisible\n // text on a navy card — because the client never re-decides a preloaded\n // slot and so never receives them either.\n initialVocabulary = decision.vocabulary;\n initialPersona =\n decision.persona !== undefined\n ? { persona: decision.persona, confidence: decision.confidence ?? 0 }\n : null;\n initialStage = exposedStage(decision.stage, providerProps.stageAttributes);\n ssrSessionId = decision.sessionId;\n } else {\n const result = await loadAdaptiveAssignments(components, {\n cookies: cookieStore,\n apiKey: providerProps.apiKey,\n baseUrl,\n origin: resolvedOrigin,\n userAgent,\n referer,\n utmParams,\n clickIds,\n landingPath: pathname,\n // doNotTrack is deliberately not passed: it is necessarily false on this\n // branch — a DNT/GPC or consent-gated request already took the skipSsr\n // arm above and never reaches this loader.\n timeoutMs,\n persona: providerProps.persona,\n });\n initialAssignments = result.assignments;\n initialUnified = result.unified;\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 // Not for a request that must not be tracked (DNT/GPC, consent refused or\n // not yet known): with no server decision the script's fallback reads the\n // stored snapshot from localStorage, and reading the device's storage before\n // consent is exactly what a consent gate exists to prevent. The browser SDK\n // takes over once the visitor's platform says yes.\n const personaScript = skipSsr ? null : (\n <SentientPersonaScript\n apiKey={providerProps.apiKey}\n persona={initialPersona}\n nonce={nonce}\n stageAttributes={providerProps.stageAttributes}\n stage={initialStage}\n />\n );\n\n const client = (\n <AdaptiveRootClient\n {...providerProps}\n // The same nonce also covers the <style> the client injects (reveal).\n nonce={nonce}\n // Forward the server-resolved value so a consented visitor's client does\n // not start gated and re-resolve the same cookie on mount.\n consent={consent}\n initialAssignments={initialAssignments}\n initialUnified={initialUnified}\n initialLayoutOrder={initialLayoutOrder}\n // Declared regardless of what came back, so devtools can preview layout on\n // a page whose decision was gated or timed out.\n declaredSections={sections}\n initialSlots={initialSlots}\n // Registry-mode preload: the hook treats a preloaded slot config as\n // settled, so the client does not decide the same slot a second time.\n initialSlotConfig={initialSlotConfig}\n initialPalette={initialPalette}\n initialVocabulary={initialVocabulary}\n initialPersona={initialPersona ?? undefined}\n sessionSegment={sessionSegment}\n ssrSessionId={ssrSessionId}\n >\n {children}\n </AdaptiveRootClient>\n );\n\n if (!agentFeed) {\n return (\n <>\n {personaScript}\n {client}\n </>\n );\n }\n\n // Server-rendered inline JSON-LD for AI crawlers. Emitted only on the server\n // path so passive crawlers (no JS) see it in the raw HTML. The body escapes\n // '<' so page content cannot break out of the <script> element.\n const feed = buildAgentFeed({\n page: agentPath,\n blocks: [\n ...assignmentsToBlocks(initialAssignments),\n // A moved component is not in initialAssignments (it was handed back to\n // be decided as a slot), so without this the JSON-LD dropped it — the\n // hero, for a crawler. Its decided arm, else the control: the first\n // variant key, as the page renders it (children:false).\n ...(initialUnified ?? []).map((id): AgentBlock => {\n const decided = initialSlots?.[id];\n const first = components.find((c) => c.id === id)?.variantIds[0];\n return { id, variant: typeof decided === 'string' ? decided : first !== undefined ? `authored.${first}` : '' };\n }),\n ],\n layoutOrder: initialLayoutOrder ?? undefined,\n content: agentFeed.content,\n });\n\n return (\n <>\n {personaScript}\n <script\n type=\"application/ld+json\"\n nonce={nonce}\n dangerouslySetInnerHTML={{ __html: renderAgentJsonLdBody(feed) }}\n />\n {client}\n </>\n );\n}\n","// `type JSX` from react, not the global namespace removed in @types/react@19\n// (peers allow react >=18) — see adaptive-text.tsx.\nimport type { JSX } from 'react';\nimport { renderPrePaintScript, type StageAttributes } from '@sentientui/core';\nimport { confidenceBand } from '@sentientui/policy';\n\nexport type SentientPersonaScriptProps = {\n /** Publishable API key — selects the localStorage snapshot in the fallback path. */\n apiKey: string;\n /**\n * CSP nonce for the inline pre-paint script. Pass the same nonce your\n * `Content-Security-Policy` `script-src` allows (e.g. from Next.js middleware).\n * Required for strict CSP deployments that block `'unsafe-inline'`.\n */\n nonce?: string;\n /**\n * SSR-decided persona (from `loadAdaptiveDecision`). When present the\n * script embeds the literal values; when absent it reads the local\n * decision snapshot (SPA / return-visit path).\n */\n persona?: { persona: string; confidence: number } | null;\n /**\n * The same consent gate you give the provider. With `consent={false}`, or a\n * `consentFrom` source and no `consent={true}`, nothing is rendered: the\n * fallback reads the stored decision from the visitor's device, and that\n * must wait for consent (grader F3). `AdaptiveRoot` handles this for you.\n */\n consent?: boolean;\n consentFrom?: unknown;\n /**\n * Opt-in `data-sentient-stage` (see `AdaptiveProviderProps.stageAttributes`).\n * With a server decision, pass the value to write as `stage` (already\n * coarsened — `exposedStage` from `@sentientui/core`); without one the\n * script copies the stage the visitor's last decide stored.\n */\n stageAttributes?: StageAttributes;\n /** The stage value to write, from this request's decide; null writes none. */\n stage?: string | null;\n};\n\n/** JSON string literal that is also safe inside an inline <script> element. */\nfunction inlineJsString(value: string): string {\n return JSON.stringify(value).replace(/</g, '\\\\u003c');\n}\n\n/** Exported for tests. Builds the inline JS (concatenation only — no backticks). */\nexport function personaScriptBody(props: SentientPersonaScriptProps): string {\n if (props.persona) {\n return (\n '(function(){try{var d=document.documentElement;' +\n // The stage first, with its own single-writer check: an already-set\n // persona must not stop it. Only a value this request's decide gave.\n (props.stage\n ? 'if(!d.hasAttribute(\"data-sentient-stage\"))d.setAttribute(\"data-sentient-stage\",' + inlineJsString(props.stage) + ');'\n : '') +\n 'if(d.hasAttribute(\"data-sentient-persona\"))return;' +\n 'd.setAttribute(\"data-sentient-persona\",' + inlineJsString(props.persona.persona) + ');' +\n 'd.setAttribute(\"data-sentient-confidence\",' + inlineJsString(confidenceBand(props.persona.confidence)) + ');' +\n '}catch(e){}})();'\n );\n }\n return renderPrePaintScript(props.apiKey, props.stageAttributes ? { stage: true } : undefined);\n}\n\n/**\n * Single writer of the Rung-1a `<html>` attributes\n * (`data-sentient-persona`, `data-sentient-confidence`), executed pre-paint.\n *\n * `AdaptiveRoot` renders this automatically as its first child. For Pages\n * Router / Remix, render it yourself in `_document` / the root layout.\n *\n * IMPORTANT (install docs): add `suppressHydrationWarning` to your `<html>`\n * element — this script mutates documentElement before React hydrates it\n * (the same pattern next-themes uses). The client SDK adopts the attributes\n * as truth and never rewrites them mid-session.\n */\nexport function SentientPersonaScript(props: SentientPersonaScriptProps): JSX.Element | null {\n // A server-decided persona is not a storage read, so it always renders.\n if (!props.persona && (props.consent === false || (props.consentFrom !== undefined && props.consent !== true))) return null;\n return (\n <script\n data-sentient-persona-script=\"\"\n nonce={props.nonce}\n dangerouslySetInnerHTML={{ __html: personaScriptBody(props) }}\n />\n );\n}\n","/**\n * Server-only helpers for Next.js / SSR. No React or DOM APIs.\n */\nimport {\n preloadAssignments,\n preloadAssignmentsDetailed,\n readSessionCookie,\n trackServerGoal,\n type ServerAssignConfig,\n type ServerAssignments,\n} from '@sentientui/core/server';\n\nexport { preloadAssignments, readSessionCookie, trackServerGoal };\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 /** Components the operator moved onto the shared track: not in\n * `assignments`. Pass as `initialUnified` to `<AdaptiveProvider>`. */\n unified: string[];\n};\n\nexport type LoadAdaptiveAssignmentsOptions = {\n /** Next.js `cookies()` return value, or any object with `get(name)`. */\n cookies: { get(name: string): { value: string } | undefined };\n apiKey: string;\n baseUrl: string;\n /** Used when `_snt_uid` is absent (e.g. first visit, many crawlers). */\n createSessionId?: () => string;\n /** Must match a value in the project's `allowed_origins` (e.g. `http://localhost:3001`). */\n origin?: string;\n /** From Next.js `headers().get('user-agent')` — aligns SSR segment with the client. */\n userAgent?: string;\n /** From Next.js `headers().get('referer')`. */\n referer?: string;\n /**\n * `utm_*` params from the landing URL. The Referer header never carries the\n * page's OWN query string, so without this the SSR-minted session has no\n * campaign attribution until the client SDK hydrates and re-upserts.\n * Derive with `extractTrackedParams(searchParams)` from `@sentientui/core/server`.\n */\n utmParams?: Record<string, string>;\n /** Ad-platform click IDs (gclid, fbclid, ttclid, …) from the landing URL — same derivation as `utmParams`. */\n clickIds?: Record<string, string>;\n /** The landing page's path (no query string) — recognises a paid click to a product page or a `/discount/` link on the first decision. */\n landingPath?: string;\n /** Set true when the request carries `DNT: 1` or `Sec-GPC: 1` — skips the SSR session upsert + assignment so no session is minted for an opted-out visitor (audit P4). `AdaptiveRoot` sets this automatically from the request headers. */\n doNotTrack?: boolean;\n /** Milliseconds to wait for the API before returning default variants. Defaults to 1000 (typical decide is well under 150 ms; the full budget is only reached on a cold start or a distant API). */\n timeoutMs?: number;\n /**\n * Declared persona — the role your app already knows for this visitor (e.g.\n * from your auth context: 'admin', 'evaluator'). Must be a key in the\n * project's persona vocabulary; unrecognized values are ignored server-side.\n * Never a user id or email.\n */\n persona?: string;\n};\n\nfunction defaultSessionId(): string {\n if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {\n return crypto.randomUUID();\n }\n return `snt-${Date.now()}-${Math.random().toString(36).slice(2, 11)}`;\n}\n\n/**\n * Fetches bandit assignments on the server for SEO-safe HTML.\n * Pass `assignments` as `initialAssignments` and `sessionId` as `ssrSessionId`\n * on `<AdaptiveProvider>` so the client adopts the same session on first visit.\n */\nexport async function loadAdaptiveAssignments(\n components: Array<{ id: string; variantIds: string[] }>,\n options: LoadAdaptiveAssignmentsOptions,\n): Promise<LoadAdaptiveAssignmentsResult> {\n // apiKey is not optional here: the client writes the per-project suffixed\n // cookie, so an un-keyed read missed every returning visitor and minted a\n // fresh orphan session per SSR request (see readSessionCookie in core).\n const sessionId =\n readSessionCookie(options.cookies, options.apiKey) ??\n options.createSessionId?.() ??\n defaultSessionId();\n\n // With the unified cap: a moved component is not assigned (nothing is\n // recorded) and comes back in `unified`, so the page renders it on the\n // shared track instead of seeding the frozen variant it would otherwise get.\n const { assignments, unified } = await preloadAssignmentsDetailed(components, sessionId, {\n apiKey: options.apiKey,\n baseUrl: options.baseUrl,\n origin: options.origin,\n userAgent: options.userAgent,\n referer: options.referer,\n utmParams: options.utmParams,\n clickIds: options.clickIds,\n landingPath: options.landingPath,\n doNotTrack: options.doNotTrack,\n timeoutMs: options.timeoutMs,\n persona: options.persona,\n }, { unified: true });\n\n return { assignments, sessionId, unified };\n}\n\nexport { preloadDecisions } from '@sentientui/core/server';\nexport type { DecideResult, SlotDeclInput, SlotResult } from '@sentientui/core/server';\n\n/** Return value of `loadAdaptiveDecision` — includes the session ID used for SSR. */\nexport type LoadAdaptiveDecisionResult = import('@sentientui/core/server').DecideResult & {\n sessionId: string;\n};\n\nexport type LoadAdaptiveDecisionOptions = LoadAdaptiveAssignmentsOptions & {\n /**\n * Section IDs in default order. Passed to /v1/decide as the candidate\n * layout. Optional since 0.13.0 — slot-only pages may omit it (at least\n * one of `sections`/`components`/`slots` must be non-empty).\n */\n sections?: string[];\n /** Components to assign in the same decide call. */\n components?: Array<{ id: string; variantIds?: string[] }>;\n /** Adaptive-slot declarations (useAdaptiveTokens / AdaptiveGroup) to decide server-side. */\n slots?: import('@sentientui/core/server').SlotDeclInput[];\n /** 'registry' serves the project's published slot definitions (`<Adaptive id>`)\n * and is the only way `slotConfig`/`palette` come back. Default 'request'.\n * Requires `registrySlotIds`. */\n slotsFrom?: 'request' | 'registry';\n /**\n * Registry mode: the `<Adaptive id>`s THIS page renders — the decide is\n * scoped to exactly these. Required with `slotsFrom: 'registry'`; without it\n * the call downgrades to request mode (with a console.error) instead of\n * recording a close-out trial for every published slot on every page.\n */\n registrySlotIds?: string[];\n /**\n * Registry mode: what each slot on this page can render, keyed by slot id\n * (see `preloadDecisions`). Ids without an entry get core's default caps.\n * A hybrid `<Adaptive variants>{children}</Adaptive>` needs its entry: the\n * server draws `authored.<key>` only for keys the page declares here.\n */\n renderCaps?: Record<string, Omit<import('@sentientui/core').RenderCaps, 'fp'>>;\n};\n\n/**\n * SSR helper for pages with a declared section layout and/or adaptive slots.\n * Calls `/v1/decide` instead of multiple `/v1/assign` round trips.\n * Pass `sessionId` as `ssrSessionId` on `<AdaptiveProvider>` so the client\n * adopts the same session on first visit.\n *\n * Keyless: with no valid `pk_` key this never fetches (no timeout burn).\n * Under the `development` export condition the decision is computed by the\n * deterministic local engine with the same sessionId the client will adopt —\n * server and client agree by construction. In production the engine resolves\n * to a stub and defaults are returned with one console.error.\n */\nexport async function loadAdaptiveDecision(\n options: LoadAdaptiveDecisionOptions,\n): Promise<LoadAdaptiveDecisionResult> {\n const { preloadDecisions, readSessionCookie } = await import('@sentientui/core/server');\n\n // Keyed read — the client's cookie name is suffixed per project (see\n // loadAdaptiveAssignments above). Works for keyless too: with no pk_ key the\n // client writes the bare legacy name, which the un-suffixed read falls back to.\n const sessionId =\n readSessionCookie(options.cookies, options.apiKey) ??\n options.createSessionId?.() ??\n defaultSessionId();\n\n const keyValid = typeof options.apiKey === 'string' && options.apiKey.startsWith('pk_');\n if (!keyValid) {\n const fallback: LoadAdaptiveDecisionResult = {\n layoutOrder: options.sections ?? [],\n assignments: {},\n slots: {},\n persona: 'unknown',\n confidence: 0,\n sessionId,\n };\n try {\n const mod = (await import('@sentientui/core/local')) as unknown as {\n LOCAL_ENGINE_AVAILABLE: boolean;\n createLocalEngine(opts: { sessionId: string }): {\n decide(input: {\n sections?: string[];\n components?: Array<{ id: string; variantIds?: string[] }>;\n slots?: LoadAdaptiveDecisionOptions['slots'];\n }): {\n layoutOrder: string[] | null;\n assignments: Record<string, string>;\n slots: Record<string, string | Record<string, string>>;\n persona: string;\n confidence: number;\n };\n };\n };\n if (!mod.LOCAL_ENGINE_AVAILABLE) {\n // Pinned message — must byte-match PROD_KEYLESS_ERROR in @sentientui/core.\n console.error(\n '[sentient] No API key configured — nothing is being learned. Set NEXT_PUBLIC_SENTIENT_API_KEY or pass localMode: true for local development.',\n );\n return fallback;\n }\n const outcome = mod.createLocalEngine({ sessionId }).decide({\n sections: options.sections,\n components: options.components ?? [],\n slots: options.slots ?? [],\n });\n return {\n layoutOrder: outcome.layoutOrder ?? options.sections ?? [],\n assignments: outcome.assignments,\n slots: outcome.slots,\n persona: outcome.persona,\n confidence: outcome.confidence,\n sessionId,\n };\n } catch {\n return fallback;\n }\n }\n\n const result = await preloadDecisions(\n {\n sections: options.sections,\n components: options.components ?? [],\n slots: options.slots ?? [],\n slotsFrom: options.slotsFrom,\n registrySlotIds: options.registrySlotIds,\n ...(options.renderCaps ? { renderCaps: options.renderCaps } : {}),\n // Moved components come back in `unified`, not as assignments (see\n // loadAdaptiveAssignments). Pass them as `initialUnified`.\n unifiedCaps: true,\n },\n sessionId,\n {\n apiKey: options.apiKey,\n baseUrl: options.baseUrl,\n origin: options.origin,\n userAgent: options.userAgent,\n referer: options.referer,\n utmParams: options.utmParams,\n clickIds: options.clickIds,\n landingPath: options.landingPath,\n doNotTrack: options.doNotTrack,\n timeoutMs: options.timeoutMs,\n persona: options.persona,\n },\n );\n\n return { ...result, sessionId };\n}\n","/**\n * Agent-readable content feed. Merges SDK-known data (winning variants, layout\n * order) with developer-supplied page content, and renders it either as a\n * server-rendered inline JSON-LD block (read by passive AI crawlers, which do\n * not run JS) or as Markdown (for agents that content-negotiate `text/markdown`).\n *\n * No React or DOM APIs — safe to import in server components, route handlers,\n * and middleware.\n */\n\nexport type AgentBlock = {\n /** Component ID. */\n id: string;\n /** Winning variant ID currently served. */\n variant: string;\n /** Agent-readable data attached to the served variant, if any. */\n content?: unknown;\n};\n\nexport type AgentFeed = {\n page: string;\n title?: string;\n summary?: string;\n layoutOrder?: string[];\n blocks: AgentBlock[];\n /** Developer-supplied extra fields (products, specs, arbitrary JSON). */\n [key: string]: unknown;\n};\n\n/** Fields the SDK owns — developer content can never overwrite these. */\nconst RESERVED_FIELDS = ['page', 'blocks', 'layoutOrder'] as const;\n\nconst registry = new Map<string, Record<string, unknown>>();\n\n/**\n * Register page-level structured content the SDK can't infer (title, summary,\n * product fields, arbitrary JSON), keyed by page path. Call at module load.\n */\nexport function defineAgentContent(page: string, content: Record<string, unknown>): void {\n registry.set(page, content);\n}\n\n/** Look up registered content for a page. */\nexport function getAgentContent(page: string): Record<string, unknown> | undefined {\n return registry.get(page);\n}\n\n/** Clear the registry — intended for tests. */\nexport function clearAgentContent(): void {\n registry.clear();\n}\n\n/**\n * Merge SDK-known data with developer-supplied content into a single feed.\n * Developer content fills in title/summary/etc. but can never overwrite the\n * SDK-authoritative fields (`page`, `blocks`, `layoutOrder`).\n */\nexport function buildAgentFeed(input: {\n page: string;\n blocks: AgentBlock[];\n layoutOrder?: string[];\n content?: Record<string, unknown>;\n}): AgentFeed {\n const supplied = input.content ?? getAgentContent(input.page) ?? {};\n const safe: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(supplied)) {\n if (!(RESERVED_FIELDS as readonly string[]).includes(k)) safe[k] = v;\n }\n const feed: AgentFeed = {\n ...safe,\n page: input.page,\n blocks: input.blocks,\n };\n if (input.layoutOrder) feed.layoutOrder = input.layoutOrder;\n return feed;\n}\n\n/**\n * Render the feed as a server-rendered inline JSON-LD `<script>` string. `<` is\n * escaped to `<` so embedded content cannot break out of the script\n * element. MUST be emitted on the server — passive crawlers never run client JS.\n */\nexport function renderAgentJsonLd(feed: AgentFeed): string {\n return `<script type=\"application/ld+json\">${renderAgentJsonLdBody(feed)}</script>`;\n}\n\n/**\n * The escaped JSON-LD body only (no `<script>` wrapper). For React server\n * components, inject via `<script type=\"application/ld+json\"\n * dangerouslySetInnerHTML={{ __html: renderAgentJsonLdBody(feed) }} />`.\n */\nexport function renderAgentJsonLdBody(feed: AgentFeed): string {\n return JSON.stringify({ '@context': 'https://schema.org', '@type': 'WebPage', ...feed })\n .replace(/</g, '\\\\u003c');\n}\n\n/** Render the feed as Markdown for agents that negotiate `text/markdown`. */\nexport function renderAgentMarkdown(feed: AgentFeed): string {\n const lines: string[] = [];\n if (feed.title) lines.push(`# ${feed.title}`, '');\n if (feed.summary) lines.push(String(feed.summary), '');\n\n for (const [k, v] of Object.entries(feed)) {\n if (['page', 'title', 'summary', 'blocks', 'layoutOrder'].includes(k)) continue;\n lines.push(`## ${k}`, '', '```json', JSON.stringify(v, null, 2), '```', '');\n }\n\n if (feed.blocks.length > 0) {\n lines.push('## blocks', '');\n for (const b of feed.blocks) {\n lines.push(`- **${b.id}** → variant \\`${b.variant}\\``);\n if (b.content !== undefined) {\n lines.push('', ' ```json', JSON.stringify(b.content, null, 2), ' ```');\n }\n }\n lines.push('');\n }\n\n return lines.join('\\n').trimEnd() + '\\n';\n}\n","// Fire-and-forget server-side log of a known AI-agent fetch to crawler_requests\n// (via POST /v1/crawler-events). Machine telemetry — no cookie, no session.\n// MUST NOT throw or be awaited into the render path.\nexport type AgentFetchLog = {\n baseUrl: string; // API base ending in /v1\n apiKey: string; // public pk_ key\n path: string;\n botName: string;\n userAgent?: string;\n};\n\nexport function logAgentFetch(entry: AgentFetchLog, deps: { fetchImpl?: typeof fetch } = {}): void {\n const doFetch = deps.fetchImpl ?? fetch;\n try {\n void doFetch(`${entry.baseUrl}/crawler-events`, {\n method: 'POST',\n headers: { 'content-type': 'application/json', authorization: `Bearer ${entry.apiKey}` },\n body: JSON.stringify({\n path: entry.path,\n botName: entry.botName,\n userAgent: entry.userAgent ?? null,\n source: 'ssr',\n }),\n }).catch(() => {});\n } catch {\n /* never break render */\n }\n}\n","/**\n * `createAgentFeed` — a framework-standard Route Handler (Web `Request` →\n * `Response`) that serves the agent-readable feed via HTTP content negotiation:\n * `text/markdown` (Accept header or `.md` URL) → Markdown, otherwise JSON.\n *\n * This is the secondary channel of the agent-readable design — for agents that\n * *ask* (coding agents, agents the customer controls, future crawlers). The\n * primary channel is the server-rendered inline JSON-LD from `<AdaptiveRoot>`.\n *\n * Every fetch is reported to `onRead` (best-effort) so it can be logged to\n * `crawler_requests` and counted in the dashboard traffic breakdown.\n */\nimport { matchedAgentToken } from '@sentientui/core';\nimport { renderAgentMarkdown, type AgentFeed } from '../agent-feed.js';\n\nexport type AgentFeedReadEntry = {\n path: string;\n userAgent: string | null;\n botName: string | null;\n};\n\nexport type AgentFeedRouteConfig = {\n /** Resolve the feed for a request (winning variants + layout + dev content). */\n getFeed: (request: Request) => Promise<AgentFeed> | AgentFeed;\n /** Best-effort per-fetch hook — log to `crawler_requests` here. Never awaited into the response. */\n onRead?: (entry: AgentFeedReadEntry) => void | Promise<void>;\n};\n\nfunction wantsMarkdown(url: URL, accept: string): boolean {\n return url.pathname.endsWith('.md') || accept.toLowerCase().includes('text/markdown');\n}\n\nexport function createAgentFeed(\n config: AgentFeedRouteConfig,\n): (request: Request) => Promise<Response> {\n return async (request: Request): Promise<Response> => {\n const url = new URL(request.url);\n const accept = request.headers.get('accept') ?? '';\n const userAgent = request.headers.get('user-agent');\n // Strip the .md/.json suffix so the feed path matches the page path.\n const path = url.pathname.replace(/\\.(md|json)$/, '');\n\n if (config.onRead) {\n try {\n void Promise.resolve(\n config.onRead({ path, userAgent, botName: matchedAgentToken(userAgent ?? '') }),\n ).catch(() => {});\n } catch {\n /* logging must never break the response */\n }\n }\n\n const feed = await config.getFeed(request);\n\n if (wantsMarkdown(url, accept)) {\n return new Response(renderAgentMarkdown(feed), {\n headers: { 'content-type': 'text/markdown; charset=utf-8' },\n });\n }\n return new Response(JSON.stringify(feed), {\n headers: { 'content-type': 'application/json; charset=utf-8' },\n });\n };\n}\n"],"mappings":"+lBAAA,OAAS,wBAAAA,GAAsB,gBAAAC,GAAc,wBAAAC,GAAsB,qBAAAC,OAAyB,mBAC5F,OAAS,sBAAAC,OAA0B,2BAEnC,OAAS,WAAAC,GAAS,WAAAC,OAAe,eCAjC,OAAS,wBAAAC,OAAkD,mBAC3D,OAAS,kBAAAC,OAAsB,qBA4E3B,cAAAC,OAAA,oBAvCJ,SAASC,EAAeC,EAAuB,CAC7C,OAAO,KAAK,UAAUA,CAAK,EAAE,QAAQ,KAAM,SAAS,CACtD,CAGO,SAASC,GAAkBC,EAA2C,CAC3E,OAAIA,EAAM,QAEN,mDAGCA,EAAM,MACH,kFAAoFH,EAAeG,EAAM,KAAK,EAAI,KAClH,I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AAW,GAC9D,MAAO,CAAE,GAAAF,EAAI,QAAS,OAAOqF,GAAY,SAAWA,EAAUC,IAAU,OAAY,YAAYA,CAAK,GAAK,EAAG,CAC/G,CAAC,CACH,EACA,YAAa1B,GAAA,KAAAA,EAAsB,OACnC,QAAShC,EAAU,OACrB,CAAC,EAED,OACEhC,GAAAF,GAAA,CACG,UAAAqF,GACDpF,EAAC,UACC,KAAK,sBACL,MAAOmC,EACP,wBAAyB,CAAE,OAAQ0D,GAAsBL,EAAI,CAAE,EACjE,EACCF,IACH,CAEJ","names":["deriveSessionSegment","exposedStage","extractTrackedParams","matchedAgentToken","consentFromCookies","cookies","headers","renderPrePaintScript","confidenceBand","jsx","inlineJsString","value","personaScriptBody","props","SentientPersonaScript","preloadAssignments","preloadAssignmentsDetailed","readSessionCookie","trackServerGoal","preloadDecisions","defaultSessionId","loadAdaptiveAssignments","components","options","_a","_b","_c","sessionId","readSessionCookie","assignments","unified","preloadAssignmentsDetailed","loadAdaptiveDecision","_d","_e","_f","_g","_h","_i","_j","preloadDecisions","fallback","mod","outcome","e","result","__spreadProps","__spreadValues","AdaptiveRootClient","RESERVED_FIELDS","registry","defineAgentContent","page","content","getAgentContent","buildAgentFeed","input","_a","_b","supplied","getAgentContent","safe","k","v","RESERVED_FIELDS","feed","__spreadProps","__spreadValues","renderAgentJsonLdBody","feed","__spreadValues","renderAgentMarkdown","lines","k","v","b","logAgentFetch","entry","deps","_a","_b","doFetch","e","matchedAgentToken","wantsMarkdown","url","accept","createAgentFeed","config","request","_a","userAgent","path","matchedAgentToken","e","feed","renderAgentMarkdown","matchedAgentToken","uaTokenMatch","agentIntent","classifiedAgents","Fragment","jsx","jsxs","DEFAULT_API_BASE_URL","assignmentsToBlocks","assignments","id","v","_a","rawCookie","header","name","part","eq","AdaptiveRoot","props","_b","_c","_d","_e","_f","_g","_h","components","sections","slots","registrySlotIdsProp","registrySlots","appOrigin","searchParams","pathname","initialAssignmentsOverride","ssrSessionIdProp","timeoutMs","agentFeed","captureAgents","nonce","children","providerProps","__objRest","headerStore","headers","host","resolvedOrigin","userAgent","referer","utmParams","clickIds","extractTrackedParams","doNotTrack","sessionSegment","deriveSessionSegment","cookieStore","cookies","cf","consent","consentFromCookies","skipSsr","keyless","baseUrl","agentPath","agentBot","matchedAgentToken","logAgentFetch","initialAssignments","initialUnified","initialLayoutOrder","initialSlots","initialSlotConfig","initialPalette","initialVocabulary","initialPersona","initialStage","ssrSessionId","registrySlotIds","d","renderCaps","__spreadValues","registry","decision","loadAdaptiveDecision","__spreadProps","exposedStage","result","loadAdaptiveAssignments","personaScript","SentientPersonaScript","client","AdaptiveRootClient","feed","buildAgentFeed","decided","first","c","renderAgentJsonLdBody"]}
|
package/dist/server.d.cts
CHANGED
|
@@ -1,12 +1,16 @@
|
|
|
1
|
+
import * as _sentientui_core from '@sentientui/core';
|
|
1
2
|
import * as _sentientui_core_server from '@sentientui/core/server';
|
|
2
3
|
import { ServerAssignments } from '@sentientui/core/server';
|
|
3
|
-
export { DecideResult, ServerAssignConfig, ServerAssignments, SlotDeclInput, SlotResult, preloadAssignments, preloadDecisions, readSessionCookie } from '@sentientui/core/server';
|
|
4
|
+
export { DecideResult, ServerAssignConfig, ServerAssignments, SlotDeclInput, SlotResult, preloadAssignments, preloadDecisions, readSessionCookie, trackServerGoal } from '@sentientui/core/server';
|
|
4
5
|
|
|
5
6
|
/** Return value of `loadAdaptiveAssignments` — includes the session ID used for SSR. */
|
|
6
7
|
type LoadAdaptiveAssignmentsResult = {
|
|
7
8
|
assignments: ServerAssignments;
|
|
8
9
|
/** The session ID used for SSR assignment. Pass as `ssrSessionId` to `<AdaptiveProvider>`. */
|
|
9
10
|
sessionId: string;
|
|
11
|
+
/** Components the operator moved onto the shared track: not in
|
|
12
|
+
* `assignments`. Pass as `initialUnified` to `<AdaptiveProvider>`. */
|
|
13
|
+
unified: string[];
|
|
10
14
|
};
|
|
11
15
|
type LoadAdaptiveAssignmentsOptions = {
|
|
12
16
|
/** Next.js `cookies()` return value, or any object with `get(name)`. */
|
|
@@ -87,6 +91,13 @@ type LoadAdaptiveDecisionOptions = LoadAdaptiveAssignmentsOptions & {
|
|
|
87
91
|
* recording a close-out trial for every published slot on every page.
|
|
88
92
|
*/
|
|
89
93
|
registrySlotIds?: string[];
|
|
94
|
+
/**
|
|
95
|
+
* Registry mode: what each slot on this page can render, keyed by slot id
|
|
96
|
+
* (see `preloadDecisions`). Ids without an entry get core's default caps.
|
|
97
|
+
* A hybrid `<Adaptive variants>{children}</Adaptive>` needs its entry: the
|
|
98
|
+
* server draws `authored.<key>` only for keys the page declares here.
|
|
99
|
+
*/
|
|
100
|
+
renderCaps?: Record<string, Omit<_sentientui_core.RenderCaps, 'fp'>>;
|
|
90
101
|
};
|
|
91
102
|
/**
|
|
92
103
|
* SSR helper for pages with a declared section layout and/or adaptive slots.
|
package/dist/server.d.ts
CHANGED
|
@@ -1,12 +1,16 @@
|
|
|
1
|
+
import * as _sentientui_core from '@sentientui/core';
|
|
1
2
|
import * as _sentientui_core_server from '@sentientui/core/server';
|
|
2
3
|
import { ServerAssignments } from '@sentientui/core/server';
|
|
3
|
-
export { DecideResult, ServerAssignConfig, ServerAssignments, SlotDeclInput, SlotResult, preloadAssignments, preloadDecisions, readSessionCookie } from '@sentientui/core/server';
|
|
4
|
+
export { DecideResult, ServerAssignConfig, ServerAssignments, SlotDeclInput, SlotResult, preloadAssignments, preloadDecisions, readSessionCookie, trackServerGoal } from '@sentientui/core/server';
|
|
4
5
|
|
|
5
6
|
/** Return value of `loadAdaptiveAssignments` — includes the session ID used for SSR. */
|
|
6
7
|
type LoadAdaptiveAssignmentsResult = {
|
|
7
8
|
assignments: ServerAssignments;
|
|
8
9
|
/** The session ID used for SSR assignment. Pass as `ssrSessionId` to `<AdaptiveProvider>`. */
|
|
9
10
|
sessionId: string;
|
|
11
|
+
/** Components the operator moved onto the shared track: not in
|
|
12
|
+
* `assignments`. Pass as `initialUnified` to `<AdaptiveProvider>`. */
|
|
13
|
+
unified: string[];
|
|
10
14
|
};
|
|
11
15
|
type LoadAdaptiveAssignmentsOptions = {
|
|
12
16
|
/** Next.js `cookies()` return value, or any object with `get(name)`. */
|
|
@@ -87,6 +91,13 @@ type LoadAdaptiveDecisionOptions = LoadAdaptiveAssignmentsOptions & {
|
|
|
87
91
|
* recording a close-out trial for every published slot on every page.
|
|
88
92
|
*/
|
|
89
93
|
registrySlotIds?: string[];
|
|
94
|
+
/**
|
|
95
|
+
* Registry mode: what each slot on this page can render, keyed by slot id
|
|
96
|
+
* (see `preloadDecisions`). Ids without an entry get core's default caps.
|
|
97
|
+
* A hybrid `<Adaptive variants>{children}</Adaptive>` needs its entry: the
|
|
98
|
+
* server draws `authored.<key>` only for keys the page declares here.
|
|
99
|
+
*/
|
|
100
|
+
renderCaps?: Record<string, Omit<_sentientui_core.RenderCaps, 'fp'>>;
|
|
90
101
|
};
|
|
91
102
|
/**
|
|
92
103
|
* SSR helper for pages with a declared section layout and/or adaptive slots.
|
package/dist/server.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var b=Object.create;var c=Object.defineProperty,x=Object.defineProperties,K=Object.getOwnPropertyDescriptor,U=Object.getOwnPropertyDescriptors,h=Object.getOwnPropertyNames,D=Object.getOwnPropertySymbols,_=Object.getPrototypeOf,R=Object.prototype.hasOwnProperty,T=Object.prototype.propertyIsEnumerable;var P=(e,s,r)=>s in e?c(e,s,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[s]=r,u=(e,s)=>{for(var r in s||(s={}))R.call(s,r)&&P(e,r,s[r]);if(D)for(var r of D(s))T.call(s,r)&&P(e,r,s[r]);return e},m=(e,s)=>x(e,U(s));var w=(e,s)=>{for(var r in s)c(e,r,{get:s[r],enumerable:!0})},C=(e,s,r,t)=>{if(s&&typeof s=="object"||typeof s=="function")for(let i of h(s))!R.call(e,i)&&i!==r&&c(e,i,{get:()=>s[i],enumerable:!(t=K(s,i))||t.enumerable});return e};var N=(e,s,r)=>(r=e!=null?b(_(e)):{},C(s||!e||!e.__esModule?c(r,"default",{value:e,enumerable:!0}):r,e)),M=e=>C(c({},"__esModule",{value:!0}),e);var F={};w(F,{loadAdaptiveAssignments:()=>V,loadAdaptiveDecision:()=>B,preloadAssignments:()=>n.preloadAssignments,preloadDecisions:()=>E.preloadDecisions,readSessionCookie:()=>n.readSessionCookie,trackServerGoal:()=>n.trackServerGoal});module.exports=M(F);var n=require("@sentientui/core/server"),E=require("@sentientui/core/server");function O(){return typeof crypto!="undefined"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`snt-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}async function V(e,s){var g,a,o;let r=(o=(a=(0,n.readSessionCookie)(s.cookies,s.apiKey))!=null?a:(g=s.createSessionId)==null?void 0:g.call(s))!=null?o:O(),{assignments:t,unified:i}=await(0,n.preloadAssignmentsDetailed)(e,r,{apiKey:s.apiKey,baseUrl:s.baseUrl,origin:s.origin,userAgent:s.userAgent,referer:s.referer,utmParams:s.utmParams,clickIds:s.clickIds,landingPath:s.landingPath,doNotTrack:s.doNotTrack,timeoutMs:s.timeoutMs,persona:s.persona},{unified:!0});return{assignments:t,sessionId:r,unified:i}}async function B(e){var a,o,A,p,y,f,I,v,k,L;let{preloadDecisions:s,readSessionCookie:r}=await import("@sentientui/core/server"),t=(A=(o=r(e.cookies,e.apiKey))!=null?o:(a=e.createSessionId)==null?void 0:a.call(e))!=null?A:O();if(!(typeof e.apiKey=="string"&&e.apiKey.startsWith("pk_"))){let S={layoutOrder:(p=e.sections)!=null?p:[],assignments:{},slots:{},persona:"unknown",confidence:0,sessionId:t};try{let l=await import("@sentientui/core/local");if(!l.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."),S;let d=l.createLocalEngine({sessionId:t}).decide({sections:e.sections,components:(y=e.components)!=null?y:[],slots:(f=e.slots)!=null?f:[]});return{layoutOrder:(v=(I=d.layoutOrder)!=null?I:e.sections)!=null?v:[],assignments:d.assignments,slots:d.slots,persona:d.persona,confidence:d.confidence,sessionId:t}}catch(l){return S}}let g=await s(m(u({sections:e.sections,components:(k=e.components)!=null?k:[],slots:(L=e.slots)!=null?L:[],slotsFrom:e.slotsFrom,registrySlotIds:e.registrySlotIds},e.renderCaps?{renderCaps:e.renderCaps}:{}),{unifiedCaps:!0}),t,{apiKey:e.apiKey,baseUrl:e.baseUrl,origin:e.origin,userAgent:e.userAgent,referer:e.referer,utmParams:e.utmParams,clickIds:e.clickIds,landingPath:e.landingPath,doNotTrack:e.doNotTrack,timeoutMs:e.timeoutMs,persona:e.persona});return m(u({},g),{sessionId:t})}0&&(module.exports={loadAdaptiveAssignments,loadAdaptiveDecision,preloadAssignments,preloadDecisions,readSessionCookie,trackServerGoal});
|
|
2
2
|
//# sourceMappingURL=server.js.map
|