@sentientui/react 0.19.0 → 0.19.1
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.
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var
|
|
1
|
+
var pe=Object.defineProperty,le=Object.defineProperties;var ue=Object.getOwnPropertyDescriptors;var w=Object.getOwnPropertySymbols;var G=Object.prototype.hasOwnProperty,z=Object.prototype.propertyIsEnumerable;var q=(e,t,n)=>t in e?pe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,y=(e,t)=>{for(var n in t||(t={}))G.call(t,n)&&q(e,n,t[n]);if(w)for(var n of w(t))z.call(t,n)&&q(e,n,t[n]);return e},S=(e,t)=>le(e,ue(t));var Y=(e,t)=>{var n={};for(var s in e)G.call(e,s)&&t.indexOf(s)<0&&(n[s]=e[s]);if(e!=null&&w)for(var s of w(e))t.indexOf(s)<0&&z.call(e,s)&&(n[s]=e[s]);return n};import{deriveSessionSegment as Oe,matchedAgentToken as we}from"@sentientui/core";import{cookies as Pe,headers as Le}from"next/headers";import{renderPrePaintScript as me}from"@sentientui/core";import{confidenceBand as fe}from"@sentientui/policy";import{jsx as ye}from"react/jsx-runtime";function Q(e){return JSON.stringify(e).replace(/</g,"\\u003c")}function Ae(e){return e.persona?'(function(){try{var d=document.documentElement;if(d.hasAttribute("data-sentient-persona"))return;d.setAttribute("data-sentient-persona",'+Q(e.persona.persona)+');d.setAttribute("data-sentient-confidence",'+Q(fe(e.persona.confidence))+");}catch(e){}})();":me(e.apiKey)}function Z(e){return ye("script",{"data-sentient-persona-script":"",nonce:e.nonce,dangerouslySetInnerHTML:{__html:Ae(e)}})}import{preloadAssignments as he,readSessionCookie as ve}from"@sentientui/core/server";import{preloadDecisions as je}from"@sentientui/core/server";function ee(){return typeof crypto!="undefined"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`snt-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}async function te(e,t){var r,o,i;let n=(i=(o=ve(t.cookies))!=null?o:(r=t.createSessionId)==null?void 0:r.call(t))!=null?i:ee();return{assignments:await he(e,n,{apiKey:t.apiKey,baseUrl:t.baseUrl,origin:t.origin,userAgent:t.userAgent,referer:t.referer,doNotTrack:t.doNotTrack,timeoutMs:t.timeoutMs}),sessionId:n}}async function ne(e){var i,c,p,I,k,x,a,l,u,h;let{preloadDecisions:t,readSessionCookie:n}=await import("@sentientui/core/server"),s=(p=(c=n(e.cookies))!=null?c:(i=e.createSessionId)==null?void 0:i.call(e))!=null?p:ee();if(!(typeof e.apiKey=="string"&&e.apiKey.startsWith("pk_"))){let d={layoutOrder:(I=e.sections)!=null?I:[],assignments:{},slots:{},persona:"unknown",confidence:0,sessionId:s};try{let m=await import("@sentientui/core/local");if(!m.LOCAL_ENGINE_AVAILABLE)return console.error("[sentient] No API key configured \u2014 nothing is being learned. Set NEXT_PUBLIC_SENTIENT_API_KEY or pass localMode: true for local development."),d;let f=m.createLocalEngine({sessionId:s}).decide({sections:e.sections,components:(k=e.components)!=null?k:[],slots:(x=e.slots)!=null?x:[]});return{layoutOrder:(l=(a=f.layoutOrder)!=null?a:e.sections)!=null?l:[],assignments:f.assignments,slots:f.slots,persona:f.persona,confidence:f.confidence,sessionId:s}}catch(m){return d}}let o=await t({sections:e.sections,components:(u=e.components)!=null?u:[],slots:(h=e.slots)!=null?h:[]},s,{apiKey:e.apiKey,baseUrl:e.baseUrl,origin:e.origin,userAgent:e.userAgent,referer:e.referer,doNotTrack:e.doNotTrack,timeoutMs:e.timeoutMs});return S(y({},o),{sessionId:s})}import{AdaptiveRootClient as Fe}from"./adaptive-root-client.js";var Se=["page","blocks","layoutOrder"],se=new Map;function ke(e,t){se.set(e,t)}function be(e){return se.get(e)}function E(e){var r,o;let t=(o=(r=e.content)!=null?r:be(e.page))!=null?o:{},n={};for(let[i,c]of Object.entries(t))Se.includes(i)||(n[i]=c);let s=S(y({},n),{page:e.page,blocks:e.blocks});return e.layoutOrder&&(s.layoutOrder=e.layoutOrder),s}function re(e){return JSON.stringify(y({"@context":"https://schema.org","@type":"WebPage"},e)).replace(/</g,"\\u003c")}function oe(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 ie(e,t={}){var s,r;let n=(s=t.fetchImpl)!=null?s:fetch;try{n(`${e.baseUrl}/crawler-events`,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e.apiKey}`},body:JSON.stringify({path:e.path,botName:e.botName,userAgent:(r=e.userAgent)!=null?r:null,source:"ssr"})}).catch(()=>{})}catch(o){}}import{matchedAgentToken as Re}from"@sentientui/core";function Ie(e,t){return e.pathname.endsWith(".md")||t.toLowerCase().includes("text/markdown")}function xe(e){return async t=>{var c;let n=new URL(t.url),s=(c=t.headers.get("accept"))!=null?c:"",r=t.headers.get("user-agent"),o=n.pathname.replace(/\.(md|json)$/,"");if(e.onRead)try{Promise.resolve(e.onRead({path:o,userAgent:r,botName:Re(r!=null?r:"")})).catch(()=>{})}catch(p){}let i=await e.getFeed(t);return Ie(n,s)?new Response(oe(i),{headers:{"content-type":"text/markdown; charset=utf-8"}}):new Response(JSON.stringify(i),{headers:{"content-type":"application/json; charset=utf-8"}})}}import{matchedAgentToken as at,uaTokenMatch as ct,agentIntent as dt,classifiedAgents as gt}from"@sentientui/core";import{Fragment as ae,jsx as D,jsxs as ce}from"react/jsx-runtime";var Ne="https://api.sentient-ui.com/v1";function Ee(e){return Object.entries(e).map(([t,n])=>{var s;return{id:t,variant:typeof n=="string"?n:(s=n==null?void 0:n.variantId)!=null?s:""}})}async function nt(e){var M,j,J,$,V,H,W,X;let B=e,{components:t=[],sections:n,slots:s,appOrigin:r,initialAssignments:o,ssrSessionId:i,timeoutMs:c,agentFeed:p,captureAgents:I,nonce:k,children:x}=B,a=Y(B,["components","sections","slots","appOrigin","initialAssignments","ssrSessionId","timeoutMs","agentFeed","captureAgents","nonce","children"]),l=await Le(),u=l.get("host");!r&&process.env.NODE_ENV==="production"&&!u&&console.error("[SentientUI] AdaptiveRoot: Host header is absent and no appOrigin was provided. Pass appOrigin explicitly \u2014 the https://localhost fallback will likely fail allowed_origins validation.");let h=r!=null?r:process.env.NODE_ENV==="production"?`https://${u!=null?u:"localhost"}`:"http://localhost:3001",d=(M=l.get("user-agent"))!=null?M:void 0,m=(j=l.get("referer"))!=null?j:void 0,f=l.get("dnt")==="1"||l.get("sec-gpc")==="1",de=Oe({userAgent:d,referer:m,appOrigin:h}),P=await Pe(),A=a.consentFrom,L=(V=a.consent)!=null?V:A!=null&&A.cookie&&!A.check?((J=P.get(A.cookie))==null?void 0:J.value)===(($=A.value)!=null?$:"accepted"):void 0,F=f||L===!1||A!=null&&L!==!0,N=a.apiBaseUrl?a.apiBaseUrl.replace(/\/$/,""):Ne,K=(W=(H=p==null?void 0:p.path)!=null?H:l.get("x-pathname"))!=null?W:"/",T=we(d!=null?d:"");I!==!1&&T&&ie({baseUrl:N,apiKey:a.apiKey,path:K,botName:T,userAgent:d});let v,b=null,U,R=null,O;if(o)v=o,O=i;else if(F)v={};else if(n&&n.length>0||s&&s.length>0){let g=await ne({sections:n!=null?n:[],components:t,slots:s,cookies:P,apiKey:a.apiKey,baseUrl:N,origin:h,userAgent:d,referer:m,doNotTrack:F,timeoutMs:c});v=g.assignments,b=g.layoutOrder,U=g.slots,R=g.persona!==void 0?{persona:g.persona,confidence:(X=g.confidence)!=null?X:0}:null,O=g.sessionId}else{let g=await te(t,{cookies:P,apiKey:a.apiKey,baseUrl:N,origin:h,userAgent:d,referer:m,doNotTrack:F,timeoutMs:c});v=g.assignments,O=g.sessionId}let _=D(Z,{apiKey:a.apiKey,persona:R,nonce:k}),C=D(Fe,S(y({},a),{consent:L,initialAssignments:v,initialLayoutOrder:b,initialSlots:U,initialPersona:R!=null?R:void 0,sessionSegment:de,ssrSessionId:O,children:x}));if(!p)return ce(ae,{children:[_,C]});let ge=E({page:K,blocks:Ee(v),layoutOrder:b!=null?b:void 0,content:p.content});return ce(ae,{children:[_,D("script",{type:"application/ld+json",nonce:k,dangerouslySetInnerHTML:{__html:re(ge)}}),C]})}export{nt as AdaptiveRoot,dt as agentIntent,E as buildAgentFeedFor,gt as classifiedAgents,xe as createAgentFeed,ke as defineAgentContent,at as matchedAgentToken,ct 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, matchedAgentToken } from '@sentientui/core';\nimport type { SlotDeclInput, SlotResult } from '@sentientui/core';\nimport { cookies, headers } from 'next/headers';\nimport type { ReactNode } from 'react';\nimport type { AdaptiveProviderProps } from '../provider.js';\nimport { SentientPersonaScript } from '../persona-script.js';\nimport {\n loadAdaptiveAssignments,\n loadAdaptiveDecision,\n type ServerAssignments,\n} from '../server.js';\nimport { AdaptiveRootClient } from './adaptive-root-client.js';\nimport { buildAgentFeed, renderAgentJsonLdBody, type AgentBlock } from '../agent-feed.js';\nimport { logAgentFetch } from './log-agent-fetch.js';\n\nexport { createAgentFeed } from './agent-feed-route.js';\nexport type { AgentFeedRouteConfig, AgentFeedReadEntry } from './agent-feed-route.js';\nexport { defineAgentContent, buildAgentFeed as buildAgentFeedFor } from '../agent-feed.js';\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 'initialAssignments' | 'onAssignment' | 'initialSlots' | 'initialPersona'\n> & {\n /**\n * Components to assign server-side (SEO-safe). Optional — omit when the\n * tree uses only slots/sections, or assigns client-side via hooks.\n */\n components?: PreloadComponent[];\n /**\n * Declare page section IDs in their default order. When provided,\n * AdaptiveRoot calls `/v1/decide` (single round trip) instead of\n * individual `/v1/assign` calls, and `useLayoutOrder()` returns the\n * persona-specific order on first render.\n *\n * @example sections={['hero', 'pricing', 'features', 'social_proof']}\n */\n sections?: string[];\n /**\n * Adaptive-slot declarations used by `useAdaptiveTokens` / `AdaptiveGroup`\n * in this tree. Declaring them here decides them in the same SSR\n * round trip, so their values serialize into the server HTML.\n */\n slots?: SlotDeclInput[];\n /** App origin — must be in the project's `allowed_origins`. */\n appOrigin?: string;\n /** Override: when set no network fetch is made. Useful for tests. */\n initialAssignments?: ServerAssignments;\n /**\n * Milliseconds to wait for the API before rendering default variants.\n * Defaults to 1000. The hot path typically returns in well under 150 ms;\n * the full 1 s budget is only reached on a cold start or an API\n * geographically distant from your SSR host. Lower it if your API is\n * co-located and warm.\n */\n timeoutMs?: number;\n /**\n * When set, AdaptiveRoot emits a server-rendered inline JSON-LD block\n * describing the page's winning variants, layout order, and developer-supplied\n * content — readable by passive AI crawlers (which do not run JS). Invisible to\n * humans (a JSON-LD script renders no visible DOM). Omit to emit nothing.\n */\n agentFeed?: {\n /** Page path for the feed. Falls back to the `x-pathname` request header, then '/'. */\n path?: string;\n /** Structured page content. Falls back to the `defineAgentContent` registry for this path. */\n content?: Record<string, unknown>;\n };\n /**\n * When true (default), a known AI-agent fetch (matched by user-agent —\n * GPTBot, ChatGPT-User, Claude-User, PerplexityBot, …) is logged server-side\n * to your agent analytics. Machine telemetry only (no cookie, no session);\n * fire-and-forget, never affects render. Set false to opt out.\n */\n captureAgents?: boolean;\n /**\n * CSP nonce for the inline persona (and optional agent JSON-LD) scripts.\n * Pass through from Next.js middleware / `headers()` when using a strict CSP.\n */\n nonce?: string;\n children: ReactNode;\n};\n\n/** Build agent blocks from SSR assignments (Record<id, variantId | { variantId }>). */\nfunction assignmentsToBlocks(assignments: ServerAssignments): AgentBlock[] {\n return Object.entries(assignments as Record<string, unknown>).map(([id, v]) => ({\n id,\n variant: typeof v === 'string' ? v : ((v as { variantId?: string })?.variantId ?? ''),\n }));\n}\n\n/**\n * Next.js Server Component that resolves variant assignments (and optionally\n * section layout order) server-side for zero layout shift on first paint.\n *\n * When `sections` is provided, a single `POST /v1/decide` call returns both\n * the persona-specific section order and all component assignments.\n * Without `sections`, individual `/v1/assign` calls are made per component.\n *\n * @example\n * // app/page.tsx — with section layout\n * import { AdaptiveRoot } from '@sentientui/react/next';\n *\n * export default async function Page() {\n * return (\n * <AdaptiveRoot\n * apiKey={process.env.NEXT_PUBLIC_SENTIENT_API_KEY!}\n * context=\"landing\"\n * sections={['hero', 'pricing', 'features', 'social_proof']}\n * components={[\n * { id: 'hero_cta', variantIds: ['default', 'accent'] },\n * ]}\n * >\n * <HeroSection />\n * <PricingSection />\n * <FeaturesSection />\n * <SocialProofSection />\n * </AdaptiveRoot>\n * );\n * }\n */\nexport async function AdaptiveRoot(props: AdaptiveRootProps): Promise<JSX.Element> {\n const {\n components = [],\n sections,\n slots,\n appOrigin,\n initialAssignments: initialAssignmentsOverride,\n ssrSessionId: ssrSessionIdProp,\n timeoutMs,\n agentFeed,\n captureAgents,\n nonce,\n children,\n ...providerProps\n } = props;\n\n const headerStore = await headers();\n const host = headerStore.get('host');\n if (!appOrigin && process.env.NODE_ENV === 'production' && !host) {\n console.error(\n '[SentientUI] AdaptiveRoot: Host header is absent and no appOrigin was provided. ' +\n 'Pass appOrigin explicitly — the https://localhost fallback will likely fail allowed_origins validation.',\n );\n }\n const resolvedOrigin = appOrigin ??\n (process.env.NODE_ENV === 'production'\n ? `https://${host ?? 'localhost'}`\n : 'http://localhost:3001');\n const userAgent = headerStore.get('user-agent') ?? undefined;\n const referer = headerStore.get('referer') ?? undefined;\n // Honor a tracking opt-out at SSR: `DNT: 1` or the legally-enforceable\n // `Sec-GPC: 1`. When set we skip the session upsert + assign/decide so no\n // session row is minted for the visitor (audit P4) — matching the client SDK,\n // which already no-ops for these signals.\n const doNotTrack = headerStore.get('dnt') === '1' || headerStore.get('sec-gpc') === '1';\n // `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 // A `check()` source runs in the browser and cannot be evaluated here, so it\n // stays gated until the client resolves it. An explicit `consent` prop always\n // wins — it is the escape hatch for apps that track consent elsewhere.\n const consentFrom = providerProps.consentFrom;\n const consent =\n providerProps.consent ??\n (consentFrom?.cookie && !consentFrom.check\n ? cookieStore.get(consentFrom.cookie)?.value === (consentFrom.value ?? 'accepted')\n : undefined);\n\n // Consent must gate the SERVER too, not just the client. Without this 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\") and forcing sites\n // to hide AdaptiveRoot behind a conditional render, which is what made\n // consent-after-load cost a full server round trip.\n const consentGated = consent === false || (consentFrom != null && consent !== true);\n const skipSsr = doNotTrack || consentGated;\n\n // SSR preload MUST hit the same API host the client will use, otherwise the\n // SSR-minted session lives on the wrong host and the client's first /assign\n // misses it and re-mints — silently breaking SSR→client continuity for any\n // non-default / self-hosted deployment. The client derives its base from\n // apiBaseUrl too (see provider.tsx), so thread the same value here.\n const baseUrl = providerProps.apiBaseUrl\n ? providerProps.apiBaseUrl.replace(/\\/$/, '')\n : DEFAULT_API_BASE_URL;\n\n // Server-side agent-fetch capture (spec: nextjs-agent-fetch-capture). JS-less\n // assistants (GPTBot / ChatGPT-User / Claude-User / PerplexityBot / …) never\n // run client JS, but they trigger SSR — so AdaptiveRoot sees their UA here.\n // Fire-and-forget; never blocks or breaks render. `agentPath` is reused by the\n // agentFeed JSON-LD below.\n const agentPath = agentFeed?.path ?? headerStore.get('x-pathname') ?? '/';\n const agentBot = matchedAgentToken(userAgent ?? '');\n if (captureAgents !== false && agentBot) {\n logAgentFetch({ baseUrl, apiKey: providerProps.apiKey, path: agentPath, botName: agentBot, userAgent });\n }\n\n let initialAssignments: ServerAssignments;\n let initialLayoutOrder: string[] | null = null;\n let initialSlots: Record<string, SlotResult> | undefined;\n let initialPersona: { persona: string; confidence: number } | null = null;\n let ssrSessionId: string | undefined;\n\n if (initialAssignmentsOverride) {\n initialAssignments = initialAssignmentsOverride;\n ssrSessionId = ssrSessionIdProp;\n } else if (consentGated) {\n // Nothing server-side: no decide, no assign, no session. Components fall\n // back to `ssrFallback`, and the client starts only if the visitor later\n // consents — via the `consent` prop or grantConsent(), neither of which\n // needs a page reload.\n initialAssignments = {};\n } else if ((sections && sections.length > 0) || (slots && slots.length > 0)) {\n const decision = await loadAdaptiveDecision({\n sections: sections ?? [],\n components,\n slots,\n cookies: cookieStore,\n apiKey: providerProps.apiKey,\n baseUrl,\n origin: resolvedOrigin,\n userAgent,\n referer,\n doNotTrack: skipSsr,\n timeoutMs,\n });\n initialAssignments = decision.assignments;\n initialLayoutOrder = decision.layoutOrder;\n initialSlots = decision.slots;\n initialPersona =\n decision.persona !== undefined\n ? { persona: decision.persona, confidence: decision.confidence ?? 0 }\n : null;\n ssrSessionId = decision.sessionId;\n } else {\n const result = await loadAdaptiveAssignments(components, {\n cookies: cookieStore,\n apiKey: providerProps.apiKey,\n baseUrl,\n origin: resolvedOrigin,\n userAgent,\n referer,\n doNotTrack: skipSsr,\n timeoutMs,\n });\n initialAssignments = result.assignments;\n ssrSessionId = result.sessionId;\n }\n\n // Single-writer inline script — ALWAYS the first child, before any markup\n // that CSS keyed on the persona attributes could style.\n const personaScript = (\n <SentientPersonaScript apiKey={providerProps.apiKey} persona={initialPersona} nonce={nonce} />\n );\n\n const client = (\n <AdaptiveRootClient\n {...providerProps}\n // 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 initialSlots={initialSlots}\n initialPersona={initialPersona ?? undefined}\n sessionSegment={sessionSegment}\n ssrSessionId={ssrSessionId}\n >\n {children}\n </AdaptiveRootClient>\n );\n\n if (!agentFeed) {\n return (\n <>\n {personaScript}\n {client}\n </>\n );\n }\n\n // Server-rendered inline JSON-LD for AI crawlers. Emitted only on the server\n // path so passive crawlers (no JS) see it in the raw HTML. The body escapes\n // '<' so page content cannot break out of the <script> element.\n const feed = buildAgentFeed({\n page: agentPath,\n blocks: assignmentsToBlocks(initialAssignments),\n layoutOrder: initialLayoutOrder ?? undefined,\n content: agentFeed.content,\n });\n\n return (\n <>\n {personaScript}\n <script\n type=\"application/ld+json\"\n nonce={nonce}\n dangerouslySetInnerHTML={{ __html: renderAgentJsonLdBody(feed) }}\n />\n {client}\n </>\n );\n}\n","import { renderPrePaintScript } from '@sentientui/core';\nimport { confidenceBand } from '@sentientui/policy';\n\nexport type SentientPersonaScriptProps = {\n /** Publishable API key — selects the localStorage snapshot in the fallback path. */\n apiKey: string;\n /**\n * CSP nonce for the inline pre-paint script. Pass the same nonce your\n * `Content-Security-Policy` `script-src` allows (e.g. from Next.js middleware).\n * Required for strict CSP deployments that block `'unsafe-inline'`.\n */\n nonce?: string;\n /**\n * SSR-decided persona (from `loadAdaptiveDecision`). When present the\n * script embeds the literal values; when absent it reads the local\n * decision snapshot (SPA / return-visit path).\n */\n persona?: { persona: string; confidence: number } | null;\n};\n\n/** JSON string literal that is also safe inside an inline <script> element. */\nfunction inlineJsString(value: string): string {\n return JSON.stringify(value).replace(/</g, '\\\\u003c');\n}\n\n/** Exported for tests. Builds the inline JS (concatenation only — no backticks). */\nexport function personaScriptBody(props: SentientPersonaScriptProps): string {\n if (props.persona) {\n return (\n '(function(){try{var d=document.documentElement;' +\n 'if(d.hasAttribute(\"data-sentient-persona\"))return;' +\n 'd.setAttribute(\"data-sentient-persona\",' + inlineJsString(props.persona.persona) + ');' +\n 'd.setAttribute(\"data-sentient-confidence\",' + inlineJsString(confidenceBand(props.persona.confidence)) + ');' +\n '}catch(e){}})();'\n );\n }\n return renderPrePaintScript(props.apiKey);\n}\n\n/**\n * Single writer of the Rung-1a `<html>` attributes\n * (`data-sentient-persona`, `data-sentient-confidence`), executed pre-paint.\n *\n * `AdaptiveRoot` renders this automatically as its first child. For Pages\n * Router / Remix, render it yourself in `_document` / the root layout.\n *\n * IMPORTANT (install docs): add `suppressHydrationWarning` to your `<html>`\n * element — this script mutates documentElement before React hydrates it\n * (the same pattern next-themes uses). The client SDK adopts the attributes\n * as truth and never rewrites them mid-session.\n */\nexport function SentientPersonaScript(props: SentientPersonaScriptProps): JSX.Element {\n return (\n <script\n data-sentient-persona-script=\"\"\n nonce={props.nonce}\n dangerouslySetInnerHTML={{ __html: personaScriptBody(props) }}\n />\n );\n}\n","/**\n * Server-only helpers for Next.js / SSR. No React or DOM APIs.\n */\nimport {\n preloadAssignments,\n readSessionCookie,\n type ServerAssignConfig,\n type ServerAssignments,\n} from '@sentientui/core/server';\n\nexport { preloadAssignments, readSessionCookie };\nexport type { ServerAssignConfig, ServerAssignments };\n\n/** Return value of `loadAdaptiveAssignments` — includes the session ID used for SSR. */\nexport type LoadAdaptiveAssignmentsResult = {\n assignments: ServerAssignments;\n /** The session ID used for SSR assignment. Pass as `ssrSessionId` to `<AdaptiveProvider>`. */\n sessionId: string;\n};\n\nexport type LoadAdaptiveAssignmentsOptions = {\n /** Next.js `cookies()` return value, or any object with `get(name)`. */\n cookies: { get(name: string): { value: string } | undefined };\n apiKey: string;\n baseUrl: string;\n /** Used when `_snt_uid` is absent (e.g. first visit, many crawlers). */\n createSessionId?: () => string;\n /** Must match a value in the project's `allowed_origins` (e.g. `http://localhost:3001`). */\n origin?: string;\n /** From Next.js `headers().get('user-agent')` — aligns SSR segment with the client. */\n userAgent?: string;\n /** From Next.js `headers().get('referer')`. */\n referer?: string;\n /** Set true when the request carries `DNT: 1` or `Sec-GPC: 1` — skips the SSR session upsert + assignment so no session is minted for an opted-out visitor (audit P4). `AdaptiveRoot` sets this automatically from the request headers. */\n doNotTrack?: boolean;\n /** Milliseconds to wait for the API before returning default variants. Defaults to 1000 (typical decide is well under 150 ms; the full budget is only reached on a cold start or a distant API). */\n timeoutMs?: number;\n};\n\nfunction defaultSessionId(): string {\n if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {\n return crypto.randomUUID();\n }\n return `snt-${Date.now()}-${Math.random().toString(36).slice(2, 11)}`;\n}\n\n/**\n * Fetches bandit assignments on the server for SEO-safe HTML.\n * Pass `assignments` as `initialAssignments` and `sessionId` as `ssrSessionId`\n * on `<AdaptiveProvider>` so the client adopts the same session on first visit.\n */\nexport async function loadAdaptiveAssignments(\n components: Array<{ id: string; variantIds: string[] }>,\n options: LoadAdaptiveAssignmentsOptions,\n): Promise<LoadAdaptiveAssignmentsResult> {\n const sessionId =\n readSessionCookie(options.cookies) ??\n options.createSessionId?.() ??\n defaultSessionId();\n\n const assignments = await preloadAssignments(components, sessionId, {\n apiKey: options.apiKey,\n baseUrl: options.baseUrl,\n origin: options.origin,\n userAgent: options.userAgent,\n referer: options.referer,\n doNotTrack: options.doNotTrack,\n timeoutMs: options.timeoutMs,\n });\n\n return { assignments, sessionId };\n}\n\nexport { preloadDecisions } from '@sentientui/core/server';\nexport type { DecideResult, SlotDeclInput, SlotResult } from '@sentientui/core/server';\n\n/** Return value of `loadAdaptiveDecision` — includes the session ID used for SSR. */\nexport type LoadAdaptiveDecisionResult = import('@sentientui/core/server').DecideResult & {\n sessionId: string;\n};\n\nexport type LoadAdaptiveDecisionOptions = LoadAdaptiveAssignmentsOptions & {\n /**\n * Section IDs in default order. Passed to /v1/decide as the candidate\n * layout. Optional since 0.13.0 — slot-only pages may omit it (at least\n * one of `sections`/`components`/`slots` must be non-empty).\n */\n sections?: string[];\n /** Components to assign in the same decide call. */\n components?: Array<{ id: string; variantIds?: string[] }>;\n /** Adaptive-slot declarations (useAdaptiveTokens / AdaptiveGroup) to decide server-side. */\n slots?: import('@sentientui/core/server').SlotDeclInput[];\n};\n\n/**\n * SSR helper for pages with a declared section layout and/or adaptive slots.\n * Calls `/v1/decide` instead of multiple `/v1/assign` round trips.\n * Pass `sessionId` as `ssrSessionId` on `<AdaptiveProvider>` so the client\n * adopts the same session on first visit.\n *\n * Keyless: with no valid `pk_` key this never fetches (no timeout burn).\n * Under the `development` export condition the decision is computed by the\n * deterministic local engine with the same sessionId the client will adopt —\n * server and client agree by construction. In production the engine resolves\n * to a stub and defaults are returned with one console.error.\n */\nexport async function loadAdaptiveDecision(\n options: LoadAdaptiveDecisionOptions,\n): Promise<LoadAdaptiveDecisionResult> {\n const { preloadDecisions, readSessionCookie } = await import('@sentientui/core/server');\n\n const sessionId =\n readSessionCookie(options.cookies) ??\n options.createSessionId?.() ??\n defaultSessionId();\n\n const keyValid = typeof options.apiKey === 'string' && options.apiKey.startsWith('pk_');\n if (!keyValid) {\n const fallback: LoadAdaptiveDecisionResult = {\n layoutOrder: options.sections ?? [],\n assignments: {},\n slots: {},\n persona: 'unknown',\n confidence: 0,\n sessionId,\n };\n try {\n const mod = (await import('@sentientui/core/local')) as unknown as {\n LOCAL_ENGINE_AVAILABLE: boolean;\n createLocalEngine(opts: { sessionId: string }): {\n decide(input: {\n sections?: string[];\n components?: Array<{ id: string; variantIds?: string[] }>;\n slots?: LoadAdaptiveDecisionOptions['slots'];\n }): {\n layoutOrder: string[] | null;\n assignments: Record<string, string>;\n slots: Record<string, string | Record<string, string>>;\n persona: string;\n confidence: number;\n };\n };\n };\n if (!mod.LOCAL_ENGINE_AVAILABLE) {\n // Pinned message — must byte-match PROD_KEYLESS_ERROR in @sentientui/core.\n console.error(\n '[sentient] No API key configured — nothing is being learned. Set NEXT_PUBLIC_SENTIENT_API_KEY or pass localMode: true for local development.',\n );\n return fallback;\n }\n const outcome = mod.createLocalEngine({ sessionId }).decide({\n sections: options.sections,\n components: options.components ?? [],\n slots: options.slots ?? [],\n });\n return {\n layoutOrder: outcome.layoutOrder ?? options.sections ?? [],\n assignments: outcome.assignments,\n slots: outcome.slots,\n persona: outcome.persona,\n confidence: outcome.confidence,\n sessionId,\n };\n } catch {\n return fallback;\n }\n }\n\n const result = await preloadDecisions(\n {\n sections: options.sections,\n components: options.components ?? [],\n slots: options.slots ?? [],\n },\n sessionId,\n {\n apiKey: options.apiKey,\n baseUrl: options.baseUrl,\n origin: options.origin,\n userAgent: options.userAgent,\n referer: options.referer,\n doNotTrack: options.doNotTrack,\n timeoutMs: options.timeoutMs,\n },\n );\n\n return { ...result, sessionId };\n}\n","/**\n * Agent-readable content feed. Merges SDK-known data (winning variants, layout\n * order) with developer-supplied page content, and renders it either as a\n * server-rendered inline JSON-LD block (read by passive AI crawlers, which do\n * not run JS) or as Markdown (for agents that content-negotiate `text/markdown`).\n *\n * No React or DOM APIs — safe to import in server components, route handlers,\n * and middleware.\n */\n\nexport type AgentBlock = {\n /** Component ID. */\n id: string;\n /** Winning variant ID currently served. */\n variant: string;\n /** Agent-readable data attached to the served variant, if any. */\n content?: unknown;\n};\n\nexport type AgentFeed = {\n page: string;\n title?: string;\n summary?: string;\n layoutOrder?: string[];\n blocks: AgentBlock[];\n /** Developer-supplied extra fields (products, specs, arbitrary JSON). */\n [key: string]: unknown;\n};\n\n/** Fields the SDK owns — developer content can never overwrite these. */\nconst RESERVED_FIELDS = ['page', 'blocks', 'layoutOrder'] as const;\n\nconst registry = new Map<string, Record<string, unknown>>();\n\n/**\n * Register page-level structured content the SDK can't infer (title, summary,\n * product fields, arbitrary JSON), keyed by page path. Call at module load.\n */\nexport function defineAgentContent(page: string, content: Record<string, unknown>): void {\n registry.set(page, content);\n}\n\n/** Look up registered content for a page. */\nexport function getAgentContent(page: string): Record<string, unknown> | undefined {\n return registry.get(page);\n}\n\n/** Clear the registry — intended for tests. */\nexport function clearAgentContent(): void {\n registry.clear();\n}\n\n/**\n * Merge SDK-known data with developer-supplied content into a single feed.\n * Developer content fills in title/summary/etc. but can never overwrite the\n * SDK-authoritative fields (`page`, `blocks`, `layoutOrder`).\n */\nexport function buildAgentFeed(input: {\n page: string;\n blocks: AgentBlock[];\n layoutOrder?: string[];\n content?: Record<string, unknown>;\n}): AgentFeed {\n const supplied = input.content ?? getAgentContent(input.page) ?? {};\n const safe: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(supplied)) {\n if (!(RESERVED_FIELDS as readonly string[]).includes(k)) safe[k] = v;\n }\n const feed: AgentFeed = {\n ...safe,\n page: input.page,\n blocks: input.blocks,\n };\n if (input.layoutOrder) feed.layoutOrder = input.layoutOrder;\n return feed;\n}\n\n/**\n * Render the feed as a server-rendered inline JSON-LD `<script>` string. `<` is\n * escaped to `<` so embedded content cannot break out of the script\n * element. MUST be emitted on the server — passive crawlers never run client JS.\n */\nexport function renderAgentJsonLd(feed: AgentFeed): string {\n return `<script type=\"application/ld+json\">${renderAgentJsonLdBody(feed)}</script>`;\n}\n\n/**\n * The escaped JSON-LD body only (no `<script>` wrapper). For React server\n * components, inject via `<script type=\"application/ld+json\"\n * dangerouslySetInnerHTML={{ __html: renderAgentJsonLdBody(feed) }} />`.\n */\nexport function renderAgentJsonLdBody(feed: AgentFeed): string {\n return JSON.stringify({ '@context': 'https://schema.org', '@type': 'WebPage', ...feed })\n .replace(/</g, '\\\\u003c');\n}\n\n/** Render the feed as Markdown for agents that negotiate `text/markdown`. */\nexport function renderAgentMarkdown(feed: AgentFeed): string {\n const lines: string[] = [];\n if (feed.title) lines.push(`# ${feed.title}`, '');\n if (feed.summary) lines.push(String(feed.summary), '');\n\n for (const [k, v] of Object.entries(feed)) {\n if (['page', 'title', 'summary', 'blocks', 'layoutOrder'].includes(k)) continue;\n lines.push(`## ${k}`, '', '```json', JSON.stringify(v, null, 2), '```', '');\n }\n\n if (feed.blocks.length > 0) {\n lines.push('## blocks', '');\n for (const b of feed.blocks) {\n lines.push(`- **${b.id}** → variant \\`${b.variant}\\``);\n if (b.content !== undefined) {\n lines.push('', ' ```json', JSON.stringify(b.content, null, 2), ' ```');\n }\n }\n lines.push('');\n }\n\n return lines.join('\\n').trimEnd() + '\\n';\n}\n","// Fire-and-forget server-side log of a known AI-agent fetch to crawler_requests\n// (via POST /v1/crawler-events). Machine telemetry — no cookie, no session.\n// MUST NOT throw or be awaited into the render path.\nexport type AgentFetchLog = {\n baseUrl: string; // API base ending in /v1\n apiKey: string; // public pk_ key\n path: string;\n botName: string;\n userAgent?: string;\n};\n\nexport function logAgentFetch(entry: AgentFetchLog, deps: { fetchImpl?: typeof fetch } = {}): void {\n const doFetch = deps.fetchImpl ?? fetch;\n try {\n void doFetch(`${entry.baseUrl}/crawler-events`, {\n method: 'POST',\n headers: { 'content-type': 'application/json', authorization: `Bearer ${entry.apiKey}` },\n body: JSON.stringify({\n path: entry.path,\n botName: entry.botName,\n userAgent: entry.userAgent ?? null,\n source: 'ssr',\n }),\n }).catch(() => {});\n } catch {\n /* never break render */\n }\n}\n","/**\n * `createAgentFeed` — a framework-standard Route Handler (Web `Request` →\n * `Response`) that serves the agent-readable feed via HTTP content negotiation:\n * `text/markdown` (Accept header or `.md` URL) → Markdown, otherwise JSON.\n *\n * This is the secondary channel of the agent-readable design — for agents that\n * *ask* (coding agents, agents the customer controls, future crawlers). The\n * primary channel is the server-rendered inline JSON-LD from `<AdaptiveRoot>`.\n *\n * Every fetch is reported to `onRead` (best-effort) so it can be logged to\n * `crawler_requests` and counted in the dashboard traffic breakdown.\n */\nimport { matchedAgentToken } from '@sentientui/core';\nimport { renderAgentMarkdown, type AgentFeed } from '../agent-feed.js';\n\nexport type AgentFeedReadEntry = {\n path: string;\n userAgent: string | null;\n botName: string | null;\n};\n\nexport type AgentFeedRouteConfig = {\n /** Resolve the feed for a request (winning variants + layout + dev content). */\n getFeed: (request: Request) => Promise<AgentFeed> | AgentFeed;\n /** Best-effort per-fetch hook — log to `crawler_requests` here. Never awaited into the response. */\n onRead?: (entry: AgentFeedReadEntry) => void | Promise<void>;\n};\n\nfunction wantsMarkdown(url: URL, accept: string): boolean {\n return url.pathname.endsWith('.md') || accept.toLowerCase().includes('text/markdown');\n}\n\nexport function createAgentFeed(\n config: AgentFeedRouteConfig,\n): (request: Request) => Promise<Response> {\n return async (request: Request): Promise<Response> => {\n const url = new URL(request.url);\n const accept = request.headers.get('accept') ?? '';\n const userAgent = request.headers.get('user-agent');\n // Strip the .md/.json suffix so the feed path matches the page path.\n const path = url.pathname.replace(/\\.(md|json)$/, '');\n\n if (config.onRead) {\n try {\n void Promise.resolve(\n config.onRead({ path, userAgent, botName: matchedAgentToken(userAgent ?? '') }),\n ).catch(() => {});\n } catch {\n /* logging must never break the response */\n }\n }\n\n const feed = await config.getFeed(request);\n\n if (wantsMarkdown(url, accept)) {\n return new Response(renderAgentMarkdown(feed), {\n headers: { 'content-type': 'text/markdown; charset=utf-8' },\n });\n }\n return new Response(JSON.stringify(feed), {\n headers: { 'content-type': 'application/json; charset=utf-8' },\n });\n };\n}\n"],"mappings":"qlBAAA,OAAS,wBAAAA,GAA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xFmC,EACJ9D,EAAC+D,GAAAC,EAAAC,EAAA,GACKpC,GADL,CAIC,QAASc,EACT,mBAAoBQ,EACpB,mBAAoBC,EACpB,aAAcC,EACd,eAAgBC,GAAA,KAAAA,EAAkB,OAClC,eAAgBhB,GAChB,aAAciB,EAEb,SAAA3B,GACH,EAGF,GAAI,CAACH,EACH,OACExB,GAAAF,GAAA,CACG,UAAA6D,EACAE,GACH,EAOJ,IAAMI,GAAOC,EAAe,CAC1B,KAAMpB,EACN,OAAQ5C,GAAoBgD,CAAkB,EAC9C,YAAaC,GAAA,KAAAA,EAAsB,OACnC,QAAS3B,EAAU,OACrB,CAAC,EAED,OACExB,GAAAF,GAAA,CACG,UAAA6D,EACD5D,EAAC,UACC,KAAK,sBACL,MAAO2B,EACP,wBAAyB,CAAE,OAAQyC,GAAsBF,EAAI,CAAE,EACjE,EACCJ,GACH,CAEJ","names":["deriveSessionSegment","matchedAgentToken","cookies","headers","renderPrePaintScript","confidenceBand","jsx","inlineJsString","value","personaScriptBody","props","SentientPersonaScript","preloadAssignments","readSessionCookie","preloadDecisions","defaultSessionId","loadAdaptiveAssignments","components","options","_a","_b","_c","sessionId","readSessionCookie","preloadAssignments","loadAdaptiveDecision","_d","_e","_f","_g","_h","_i","_j","preloadDecisions","fallback","mod","outcome","e","result","__spreadProps","__spreadValues","AdaptiveRootClient","RESERVED_FIELDS","registry","defineAgentContent","page","content","getAgentContent","buildAgentFeed","input","_a","_b","supplied","getAgentContent","safe","k","v","RESERVED_FIELDS","feed","__spreadProps","__spreadValues","renderAgentJsonLdBody","feed","__spreadValues","renderAgentMarkdown","lines","k","v","b","logAgentFetch","entry","deps","_a","_b","doFetch","e","matchedAgentToken","wantsMarkdown","url","accept","createAgentFeed","config","request","_a","userAgent","path","matchedAgentToken","e","feed","renderAgentMarkdown","matchedAgentToken","uaTokenMatch","agentIntent","classifiedAgents","Fragment","jsx","jsxs","DEFAULT_API_BASE_URL","assignmentsToBlocks","assignments","id","v","_a","AdaptiveRoot","props","_b","_c","_d","_e","_f","_g","_h","_i","components","sections","slots","appOrigin","initialAssignmentsOverride","ssrSessionIdProp","timeoutMs","agentFeed","captureAgents","nonce","children","providerProps","__objRest","headerStore","headers","host","resolvedOrigin","userAgent","referer","doNotTrack","sessionSegment","deriveSessionSegment","cookieStore","cookies","consentFrom","consent","consentGated","skipSsr","baseUrl","agentPath","agentBot","matchedAgentToken","logAgentFetch","initialAssignments","initialLayoutOrder","initialSlots","initialPersona","ssrSessionId","decision","loadAdaptiveDecision","result","loadAdaptiveAssignments","personaScript","SentientPersonaScript","client","AdaptiveRootClient","__spreadProps","__spreadValues","feed","buildAgentFeed","renderAgentJsonLdBody"]}
|
|
1
|
+
{"version":3,"sources":["../../src/next/adaptive-root.tsx","../../src/persona-script.tsx","../../src/server.ts","../../src/agent-feed.ts","../../src/next/log-agent-fetch.ts","../../src/next/agent-feed-route.ts"],"sourcesContent":["import { deriveSessionSegment, matchedAgentToken } from '@sentientui/core';\nimport type { SlotDeclInput, SlotResult } from '@sentientui/core';\nimport { cookies, headers } from 'next/headers';\nimport type { ReactNode } from 'react';\nimport type { AdaptiveProviderProps } from '../provider.js';\nimport { SentientPersonaScript } from '../persona-script.js';\nimport {\n loadAdaptiveAssignments,\n loadAdaptiveDecision,\n type ServerAssignments,\n} from '../server.js';\nimport { AdaptiveRootClient } from './adaptive-root-client.js';\nimport { buildAgentFeed, renderAgentJsonLdBody, type AgentBlock } from '../agent-feed.js';\nimport { logAgentFetch } from './log-agent-fetch.js';\n\nexport { createAgentFeed } from './agent-feed-route.js';\nexport type { AgentFeedRouteConfig, AgentFeedReadEntry } from './agent-feed-route.js';\nexport { defineAgentContent, buildAgentFeed as buildAgentFeedFor } from '../agent-feed.js';\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 'initialAssignments' | 'onAssignment' | 'initialSlots' | 'initialPersona'\n> & {\n /**\n * Components to assign server-side (SEO-safe). Optional — omit when the\n * tree uses only slots/sections, or assigns client-side via hooks.\n */\n components?: PreloadComponent[];\n /**\n * Declare page section IDs in their default order. When provided,\n * AdaptiveRoot calls `/v1/decide` (single round trip) instead of\n * individual `/v1/assign` calls, and `useLayoutOrder()` returns the\n * persona-specific order on first render.\n *\n * @example sections={['hero', 'pricing', 'features', 'social_proof']}\n */\n sections?: string[];\n /**\n * Adaptive-slot declarations used by `useAdaptiveTokens` / `AdaptiveGroup`\n * in this tree. Declaring them here decides them in the same SSR\n * round trip, so their values serialize into the server HTML.\n */\n slots?: SlotDeclInput[];\n /** App origin — must be in the project's `allowed_origins`. */\n appOrigin?: string;\n /** Override: when set no network fetch is made. Useful for tests. */\n initialAssignments?: ServerAssignments;\n /**\n * Milliseconds to wait for the API before rendering default variants.\n * Defaults to 1000. The hot path typically returns in well under 150 ms;\n * the full 1 s budget is only reached on a cold start or an API\n * geographically distant from your SSR host. Lower it if your API is\n * co-located and warm.\n */\n timeoutMs?: number;\n /**\n * When set, AdaptiveRoot emits a server-rendered inline JSON-LD block\n * describing the page's winning variants, layout order, and developer-supplied\n * content — readable by passive AI crawlers (which do not run JS). Invisible to\n * humans (a JSON-LD script renders no visible DOM). Omit to emit nothing.\n */\n agentFeed?: {\n /** Page path for the feed. Falls back to the `x-pathname` request header, then '/'. */\n path?: string;\n /** Structured page content. Falls back to the `defineAgentContent` registry for this path. */\n content?: Record<string, unknown>;\n };\n /**\n * When true (default), a known AI-agent fetch (matched by user-agent —\n * GPTBot, ChatGPT-User, Claude-User, PerplexityBot, …) is logged server-side\n * to your agent analytics. Machine telemetry only (no cookie, no session);\n * fire-and-forget, never affects render. Set false to opt out.\n */\n captureAgents?: boolean;\n /**\n * CSP nonce for the inline persona (and optional agent JSON-LD) scripts.\n * Pass through from Next.js middleware / `headers()` when using a strict CSP.\n */\n nonce?: string;\n children: ReactNode;\n};\n\n/** Build agent blocks from SSR assignments (Record<id, variantId | { variantId }>). */\nfunction assignmentsToBlocks(assignments: ServerAssignments): AgentBlock[] {\n return Object.entries(assignments as Record<string, unknown>).map(([id, v]) => ({\n id,\n variant: typeof v === 'string' ? v : ((v as { variantId?: string })?.variantId ?? ''),\n }));\n}\n\n/**\n * Next.js Server Component that resolves variant assignments (and optionally\n * section layout order) server-side for zero layout shift on first paint.\n *\n * When `sections` is provided, a single `POST /v1/decide` call returns both\n * the persona-specific section order and all component assignments.\n * Without `sections`, individual `/v1/assign` calls are made per component.\n *\n * @example\n * // app/page.tsx — with section layout\n * import { AdaptiveRoot } from '@sentientui/react/next';\n *\n * export default async function Page() {\n * return (\n * <AdaptiveRoot\n * apiKey={process.env.NEXT_PUBLIC_SENTIENT_API_KEY!}\n * context=\"landing\"\n * sections={['hero', 'pricing', 'features', 'social_proof']}\n * components={[\n * { id: 'hero_cta', variantIds: ['default', 'accent'] },\n * ]}\n * >\n * <HeroSection />\n * <PricingSection />\n * <FeaturesSection />\n * <SocialProofSection />\n * </AdaptiveRoot>\n * );\n * }\n */\nexport async function AdaptiveRoot(props: AdaptiveRootProps): Promise<JSX.Element> {\n const {\n components = [],\n sections,\n slots,\n appOrigin,\n initialAssignments: initialAssignmentsOverride,\n ssrSessionId: ssrSessionIdProp,\n timeoutMs,\n agentFeed,\n captureAgents,\n nonce,\n children,\n ...providerProps\n } = props;\n\n const headerStore = await headers();\n const host = headerStore.get('host');\n if (!appOrigin && process.env.NODE_ENV === 'production' && !host) {\n console.error(\n '[SentientUI] AdaptiveRoot: Host header is absent and no appOrigin was provided. ' +\n 'Pass appOrigin explicitly — the https://localhost fallback will likely fail allowed_origins validation.',\n );\n }\n const resolvedOrigin = appOrigin ??\n (process.env.NODE_ENV === 'production'\n ? `https://${host ?? 'localhost'}`\n : 'http://localhost:3001');\n const userAgent = headerStore.get('user-agent') ?? undefined;\n const referer = headerStore.get('referer') ?? undefined;\n // Honor a tracking opt-out at SSR: `DNT: 1` or the legally-enforceable\n // `Sec-GPC: 1`. When set we skip the session upsert + assign/decide so no\n // session row is minted for the visitor (audit P4) — matching the client SDK,\n // which already no-ops for these signals.\n const doNotTrack = headerStore.get('dnt') === '1' || headerStore.get('sec-gpc') === '1';\n // `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 // A `check()` source runs in the browser and cannot be evaluated here, so it\n // stays gated until the client resolves it. An explicit `consent` prop always\n // wins — it is the escape hatch for apps that track consent elsewhere.\n //\n // Consent gates the SERVER too, not just the client: without it the SSR\n // decide/assign still ran and still minted a session row for a visitor who\n // had not consented, contradicting the documented contract (\"no SDK is\n // initialised, no cookies are written, no events are sent\").\n const cf = providerProps.consentFrom;\n const consent =\n providerProps.consent ??\n (cf?.cookie && !cf.check\n ? cookieStore.get(cf.cookie)?.value === (cf.value ?? 'accepted')\n : undefined);\n const skipSsr = doNotTrack || consent === false || (cf != null && consent !== true);\n\n // SSR preload MUST hit the same API host the client will use, otherwise the\n // SSR-minted session lives on the wrong host and the client's first /assign\n // misses it and re-mints — silently breaking SSR→client continuity for any\n // non-default / self-hosted deployment. The client derives its base from\n // apiBaseUrl too (see provider.tsx), so thread the same value here.\n const baseUrl = providerProps.apiBaseUrl\n ? providerProps.apiBaseUrl.replace(/\\/$/, '')\n : DEFAULT_API_BASE_URL;\n\n // Server-side agent-fetch capture (spec: nextjs-agent-fetch-capture). JS-less\n // assistants (GPTBot / ChatGPT-User / Claude-User / PerplexityBot / …) never\n // run client JS, but they trigger SSR — so AdaptiveRoot sees their UA here.\n // Fire-and-forget; never blocks or breaks render. `agentPath` is reused by the\n // agentFeed JSON-LD below.\n const agentPath = agentFeed?.path ?? headerStore.get('x-pathname') ?? '/';\n const agentBot = matchedAgentToken(userAgent ?? '');\n if (captureAgents !== false && agentBot) {\n logAgentFetch({ baseUrl, apiKey: providerProps.apiKey, path: agentPath, botName: agentBot, userAgent });\n }\n\n let initialAssignments: ServerAssignments;\n let initialLayoutOrder: string[] | null = null;\n let initialSlots: Record<string, SlotResult> | undefined;\n let initialPersona: { persona: string; confidence: number } | null = null;\n let ssrSessionId: string | undefined;\n\n if (initialAssignmentsOverride) {\n initialAssignments = initialAssignmentsOverride;\n ssrSessionId = ssrSessionIdProp;\n } else if (skipSsr) {\n // Nothing server-side: no decide, no assign, no session. Components fall\n // back to `ssrFallback`, and the client starts only if the visitor later\n // consents — via the `consent` prop or grantConsent(), neither of which\n // needs a page reload.\n initialAssignments = {};\n } else if ((sections && sections.length > 0) || (slots && slots.length > 0)) {\n const decision = await loadAdaptiveDecision({\n sections: sections ?? [],\n components,\n slots,\n cookies: cookieStore,\n apiKey: providerProps.apiKey,\n baseUrl,\n origin: resolvedOrigin,\n userAgent,\n referer,\n doNotTrack: skipSsr,\n timeoutMs,\n });\n initialAssignments = decision.assignments;\n initialLayoutOrder = decision.layoutOrder;\n initialSlots = decision.slots;\n initialPersona =\n decision.persona !== undefined\n ? { persona: decision.persona, confidence: decision.confidence ?? 0 }\n : null;\n ssrSessionId = decision.sessionId;\n } else {\n const result = await loadAdaptiveAssignments(components, {\n cookies: cookieStore,\n apiKey: providerProps.apiKey,\n baseUrl,\n origin: resolvedOrigin,\n userAgent,\n referer,\n doNotTrack: skipSsr,\n timeoutMs,\n });\n initialAssignments = result.assignments;\n ssrSessionId = result.sessionId;\n }\n\n // Single-writer inline script — ALWAYS the first child, before any markup\n // that CSS keyed on the persona attributes could style.\n const personaScript = (\n <SentientPersonaScript apiKey={providerProps.apiKey} persona={initialPersona} nonce={nonce} />\n );\n\n const client = (\n <AdaptiveRootClient\n {...providerProps}\n // 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 initialSlots={initialSlots}\n initialPersona={initialPersona ?? undefined}\n sessionSegment={sessionSegment}\n ssrSessionId={ssrSessionId}\n >\n {children}\n </AdaptiveRootClient>\n );\n\n if (!agentFeed) {\n return (\n <>\n {personaScript}\n {client}\n </>\n );\n }\n\n // Server-rendered inline JSON-LD for AI crawlers. Emitted only on the server\n // path so passive crawlers (no JS) see it in the raw HTML. The body escapes\n // '<' so page content cannot break out of the <script> element.\n const feed = buildAgentFeed({\n page: agentPath,\n blocks: assignmentsToBlocks(initialAssignments),\n layoutOrder: initialLayoutOrder ?? undefined,\n content: agentFeed.content,\n });\n\n return (\n <>\n {personaScript}\n <script\n type=\"application/ld+json\"\n nonce={nonce}\n dangerouslySetInnerHTML={{ __html: renderAgentJsonLdBody(feed) }}\n />\n {client}\n </>\n );\n}\n","import { renderPrePaintScript } from '@sentientui/core';\nimport { confidenceBand } from '@sentientui/policy';\n\nexport type SentientPersonaScriptProps = {\n /** Publishable API key — selects the localStorage snapshot in the fallback path. */\n apiKey: string;\n /**\n * CSP nonce for the inline pre-paint script. Pass the same nonce your\n * `Content-Security-Policy` `script-src` allows (e.g. from Next.js middleware).\n * Required for strict CSP deployments that block `'unsafe-inline'`.\n */\n nonce?: string;\n /**\n * SSR-decided persona (from `loadAdaptiveDecision`). When present the\n * script embeds the literal values; when absent it reads the local\n * decision snapshot (SPA / return-visit path).\n */\n persona?: { persona: string; confidence: number } | null;\n};\n\n/** JSON string literal that is also safe inside an inline <script> element. */\nfunction inlineJsString(value: string): string {\n return JSON.stringify(value).replace(/</g, '\\\\u003c');\n}\n\n/** Exported for tests. Builds the inline JS (concatenation only — no backticks). */\nexport function personaScriptBody(props: SentientPersonaScriptProps): string {\n if (props.persona) {\n return (\n '(function(){try{var d=document.documentElement;' +\n 'if(d.hasAttribute(\"data-sentient-persona\"))return;' +\n 'd.setAttribute(\"data-sentient-persona\",' + inlineJsString(props.persona.persona) + ');' +\n 'd.setAttribute(\"data-sentient-confidence\",' + inlineJsString(confidenceBand(props.persona.confidence)) + ');' +\n '}catch(e){}})();'\n );\n }\n return renderPrePaintScript(props.apiKey);\n}\n\n/**\n * Single writer of the Rung-1a `<html>` attributes\n * (`data-sentient-persona`, `data-sentient-confidence`), executed pre-paint.\n *\n * `AdaptiveRoot` renders this automatically as its first child. For Pages\n * Router / Remix, render it yourself in `_document` / the root layout.\n *\n * IMPORTANT (install docs): add `suppressHydrationWarning` to your `<html>`\n * element — this script mutates documentElement before React hydrates it\n * (the same pattern next-themes uses). The client SDK adopts the attributes\n * as truth and never rewrites them mid-session.\n */\nexport function SentientPersonaScript(props: SentientPersonaScriptProps): JSX.Element {\n return (\n <script\n data-sentient-persona-script=\"\"\n nonce={props.nonce}\n dangerouslySetInnerHTML={{ __html: personaScriptBody(props) }}\n />\n );\n}\n","/**\n * Server-only helpers for Next.js / SSR. No React or DOM APIs.\n */\nimport {\n preloadAssignments,\n readSessionCookie,\n type ServerAssignConfig,\n type ServerAssignments,\n} from '@sentientui/core/server';\n\nexport { preloadAssignments, readSessionCookie };\nexport type { ServerAssignConfig, ServerAssignments };\n\n/** Return value of `loadAdaptiveAssignments` — includes the session ID used for SSR. */\nexport type LoadAdaptiveAssignmentsResult = {\n assignments: ServerAssignments;\n /** The session ID used for SSR assignment. Pass as `ssrSessionId` to `<AdaptiveProvider>`. */\n sessionId: string;\n};\n\nexport type LoadAdaptiveAssignmentsOptions = {\n /** Next.js `cookies()` return value, or any object with `get(name)`. */\n cookies: { get(name: string): { value: string } | undefined };\n apiKey: string;\n baseUrl: string;\n /** Used when `_snt_uid` is absent (e.g. first visit, many crawlers). */\n createSessionId?: () => string;\n /** Must match a value in the project's `allowed_origins` (e.g. `http://localhost:3001`). */\n origin?: string;\n /** From Next.js `headers().get('user-agent')` — aligns SSR segment with the client. */\n userAgent?: string;\n /** From Next.js `headers().get('referer')`. */\n referer?: string;\n /** Set true when the request carries `DNT: 1` or `Sec-GPC: 1` — skips the SSR session upsert + assignment so no session is minted for an opted-out visitor (audit P4). `AdaptiveRoot` sets this automatically from the request headers. */\n doNotTrack?: boolean;\n /** Milliseconds to wait for the API before returning default variants. Defaults to 1000 (typical decide is well under 150 ms; the full budget is only reached on a cold start or a distant API). */\n timeoutMs?: number;\n};\n\nfunction defaultSessionId(): string {\n if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {\n return crypto.randomUUID();\n }\n return `snt-${Date.now()}-${Math.random().toString(36).slice(2, 11)}`;\n}\n\n/**\n * Fetches bandit assignments on the server for SEO-safe HTML.\n * Pass `assignments` as `initialAssignments` and `sessionId` as `ssrSessionId`\n * on `<AdaptiveProvider>` so the client adopts the same session on first visit.\n */\nexport async function loadAdaptiveAssignments(\n components: Array<{ id: string; variantIds: string[] }>,\n options: LoadAdaptiveAssignmentsOptions,\n): Promise<LoadAdaptiveAssignmentsResult> {\n const sessionId =\n readSessionCookie(options.cookies) ??\n options.createSessionId?.() ??\n defaultSessionId();\n\n const assignments = await preloadAssignments(components, sessionId, {\n apiKey: options.apiKey,\n baseUrl: options.baseUrl,\n origin: options.origin,\n userAgent: options.userAgent,\n referer: options.referer,\n doNotTrack: options.doNotTrack,\n timeoutMs: options.timeoutMs,\n });\n\n return { assignments, sessionId };\n}\n\nexport { preloadDecisions } from '@sentientui/core/server';\nexport type { DecideResult, SlotDeclInput, SlotResult } from '@sentientui/core/server';\n\n/** Return value of `loadAdaptiveDecision` — includes the session ID used for SSR. */\nexport type LoadAdaptiveDecisionResult = import('@sentientui/core/server').DecideResult & {\n sessionId: string;\n};\n\nexport type LoadAdaptiveDecisionOptions = LoadAdaptiveAssignmentsOptions & {\n /**\n * Section IDs in default order. Passed to /v1/decide as the candidate\n * layout. Optional since 0.13.0 — slot-only pages may omit it (at least\n * one of `sections`/`components`/`slots` must be non-empty).\n */\n sections?: string[];\n /** Components to assign in the same decide call. */\n components?: Array<{ id: string; variantIds?: string[] }>;\n /** Adaptive-slot declarations (useAdaptiveTokens / AdaptiveGroup) to decide server-side. */\n slots?: import('@sentientui/core/server').SlotDeclInput[];\n};\n\n/**\n * SSR helper for pages with a declared section layout and/or adaptive slots.\n * Calls `/v1/decide` instead of multiple `/v1/assign` round trips.\n * Pass `sessionId` as `ssrSessionId` on `<AdaptiveProvider>` so the client\n * adopts the same session on first visit.\n *\n * Keyless: with no valid `pk_` key this never fetches (no timeout burn).\n * Under the `development` export condition the decision is computed by the\n * deterministic local engine with the same sessionId the client will adopt —\n * server and client agree by construction. In production the engine resolves\n * to a stub and defaults are returned with one console.error.\n */\nexport async function loadAdaptiveDecision(\n options: LoadAdaptiveDecisionOptions,\n): Promise<LoadAdaptiveDecisionResult> {\n const { preloadDecisions, readSessionCookie } = await import('@sentientui/core/server');\n\n const sessionId =\n readSessionCookie(options.cookies) ??\n options.createSessionId?.() ??\n defaultSessionId();\n\n const keyValid = typeof options.apiKey === 'string' && options.apiKey.startsWith('pk_');\n if (!keyValid) {\n const fallback: LoadAdaptiveDecisionResult = {\n layoutOrder: options.sections ?? [],\n assignments: {},\n slots: {},\n persona: 'unknown',\n confidence: 0,\n sessionId,\n };\n try {\n const mod = (await import('@sentientui/core/local')) as unknown as {\n LOCAL_ENGINE_AVAILABLE: boolean;\n createLocalEngine(opts: { sessionId: string }): {\n decide(input: {\n sections?: string[];\n components?: Array<{ id: string; variantIds?: string[] }>;\n slots?: LoadAdaptiveDecisionOptions['slots'];\n }): {\n layoutOrder: string[] | null;\n assignments: Record<string, string>;\n slots: Record<string, string | Record<string, string>>;\n persona: string;\n confidence: number;\n };\n };\n };\n if (!mod.LOCAL_ENGINE_AVAILABLE) {\n // Pinned message — must byte-match PROD_KEYLESS_ERROR in @sentientui/core.\n console.error(\n '[sentient] No API key configured — nothing is being learned. Set NEXT_PUBLIC_SENTIENT_API_KEY or pass localMode: true for local development.',\n );\n return fallback;\n }\n const outcome = mod.createLocalEngine({ sessionId }).decide({\n sections: options.sections,\n components: options.components ?? [],\n slots: options.slots ?? [],\n });\n return {\n layoutOrder: outcome.layoutOrder ?? options.sections ?? [],\n assignments: outcome.assignments,\n slots: outcome.slots,\n persona: outcome.persona,\n confidence: outcome.confidence,\n sessionId,\n };\n } catch {\n return fallback;\n }\n }\n\n const result = await preloadDecisions(\n {\n sections: options.sections,\n components: options.components ?? [],\n slots: options.slots ?? [],\n },\n sessionId,\n {\n apiKey: options.apiKey,\n baseUrl: options.baseUrl,\n origin: options.origin,\n userAgent: options.userAgent,\n referer: options.referer,\n doNotTrack: options.doNotTrack,\n timeoutMs: options.timeoutMs,\n },\n );\n\n return { ...result, sessionId };\n}\n","/**\n * Agent-readable content feed. Merges SDK-known data (winning variants, layout\n * order) with developer-supplied page content, and renders it either as a\n * server-rendered inline JSON-LD block (read by passive AI crawlers, which do\n * not run JS) or as Markdown (for agents that content-negotiate `text/markdown`).\n *\n * No React or DOM APIs — safe to import in server components, route handlers,\n * and middleware.\n */\n\nexport type AgentBlock = {\n /** Component ID. */\n id: string;\n /** Winning variant ID currently served. */\n variant: string;\n /** Agent-readable data attached to the served variant, if any. */\n content?: unknown;\n};\n\nexport type AgentFeed = {\n page: string;\n title?: string;\n summary?: string;\n layoutOrder?: string[];\n blocks: AgentBlock[];\n /** Developer-supplied extra fields (products, specs, arbitrary JSON). */\n [key: string]: unknown;\n};\n\n/** Fields the SDK owns — developer content can never overwrite these. */\nconst RESERVED_FIELDS = ['page', 'blocks', 'layoutOrder'] as const;\n\nconst registry = new Map<string, Record<string, unknown>>();\n\n/**\n * Register page-level structured content the SDK can't infer (title, summary,\n * product fields, arbitrary JSON), keyed by page path. Call at module load.\n */\nexport function defineAgentContent(page: string, content: Record<string, unknown>): void {\n registry.set(page, content);\n}\n\n/** Look up registered content for a page. */\nexport function getAgentContent(page: string): Record<string, unknown> | undefined {\n return registry.get(page);\n}\n\n/** Clear the registry — intended for tests. */\nexport function clearAgentContent(): void {\n registry.clear();\n}\n\n/**\n * Merge SDK-known data with developer-supplied content into a single feed.\n * Developer content fills in title/summary/etc. but can never overwrite the\n * SDK-authoritative fields (`page`, `blocks`, `layoutOrder`).\n */\nexport function buildAgentFeed(input: {\n page: string;\n blocks: AgentBlock[];\n layoutOrder?: string[];\n content?: Record<string, unknown>;\n}): AgentFeed {\n const supplied = input.content ?? getAgentContent(input.page) ?? {};\n const safe: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(supplied)) {\n if (!(RESERVED_FIELDS as readonly string[]).includes(k)) safe[k] = v;\n }\n const feed: AgentFeed = {\n ...safe,\n page: input.page,\n blocks: input.blocks,\n };\n if (input.layoutOrder) feed.layoutOrder = input.layoutOrder;\n return feed;\n}\n\n/**\n * Render the feed as a server-rendered inline JSON-LD `<script>` string. `<` is\n * escaped to `<` so embedded content cannot break out of the script\n * element. MUST be emitted on the server — passive crawlers never run client JS.\n */\nexport function renderAgentJsonLd(feed: AgentFeed): string {\n return `<script type=\"application/ld+json\">${renderAgentJsonLdBody(feed)}</script>`;\n}\n\n/**\n * The escaped JSON-LD body only (no `<script>` wrapper). For React server\n * components, inject via `<script type=\"application/ld+json\"\n * dangerouslySetInnerHTML={{ __html: renderAgentJsonLdBody(feed) }} />`.\n */\nexport function renderAgentJsonLdBody(feed: AgentFeed): string {\n return JSON.stringify({ '@context': 'https://schema.org', '@type': 'WebPage', ...feed })\n .replace(/</g, '\\\\u003c');\n}\n\n/** Render the feed as Markdown for agents that negotiate `text/markdown`. */\nexport function renderAgentMarkdown(feed: AgentFeed): string {\n const lines: string[] = [];\n if (feed.title) lines.push(`# ${feed.title}`, '');\n if (feed.summary) lines.push(String(feed.summary), '');\n\n for (const [k, v] of Object.entries(feed)) {\n if (['page', 'title', 'summary', 'blocks', 'layoutOrder'].includes(k)) continue;\n lines.push(`## ${k}`, '', '```json', JSON.stringify(v, null, 2), '```', '');\n }\n\n if (feed.blocks.length > 0) {\n lines.push('## blocks', '');\n for (const b of feed.blocks) {\n lines.push(`- **${b.id}** → variant \\`${b.variant}\\``);\n if (b.content !== undefined) {\n lines.push('', ' ```json', JSON.stringify(b.content, null, 2), ' ```');\n }\n }\n lines.push('');\n }\n\n return lines.join('\\n').trimEnd() + '\\n';\n}\n","// Fire-and-forget server-side log of a known AI-agent fetch to crawler_requests\n// (via POST /v1/crawler-events). Machine telemetry — no cookie, no session.\n// MUST NOT throw or be awaited into the render path.\nexport type AgentFetchLog = {\n baseUrl: string; // API base ending in /v1\n apiKey: string; // public pk_ key\n path: string;\n botName: string;\n userAgent?: string;\n};\n\nexport function logAgentFetch(entry: AgentFetchLog, deps: { fetchImpl?: typeof fetch } = {}): void {\n const doFetch = deps.fetchImpl ?? fetch;\n try {\n void doFetch(`${entry.baseUrl}/crawler-events`, {\n method: 'POST',\n headers: { 'content-type': 'application/json', authorization: `Bearer ${entry.apiKey}` },\n body: JSON.stringify({\n path: entry.path,\n botName: entry.botName,\n userAgent: entry.userAgent ?? null,\n source: 'ssr',\n }),\n }).catch(() => {});\n } catch {\n /* never break render */\n }\n}\n","/**\n * `createAgentFeed` — a framework-standard Route Handler (Web `Request` →\n * `Response`) that serves the agent-readable feed via HTTP content negotiation:\n * `text/markdown` (Accept header or `.md` URL) → Markdown, otherwise JSON.\n *\n * This is the secondary channel of the agent-readable design — for agents that\n * *ask* (coding agents, agents the customer controls, future crawlers). The\n * primary channel is the server-rendered inline JSON-LD from `<AdaptiveRoot>`.\n *\n * Every fetch is reported to `onRead` (best-effort) so it can be logged to\n * `crawler_requests` and counted in the dashboard traffic breakdown.\n */\nimport { matchedAgentToken } from '@sentientui/core';\nimport { renderAgentMarkdown, type AgentFeed } from '../agent-feed.js';\n\nexport type AgentFeedReadEntry = {\n path: string;\n userAgent: string | null;\n botName: string | null;\n};\n\nexport type AgentFeedRouteConfig = {\n /** Resolve the feed for a request (winning variants + layout + dev content). */\n getFeed: (request: Request) => Promise<AgentFeed> | AgentFeed;\n /** Best-effort per-fetch hook — log to `crawler_requests` here. Never awaited into the response. */\n onRead?: (entry: AgentFeedReadEntry) => void | Promise<void>;\n};\n\nfunction wantsMarkdown(url: URL, accept: string): boolean {\n return url.pathname.endsWith('.md') || accept.toLowerCase().includes('text/markdown');\n}\n\nexport function createAgentFeed(\n config: AgentFeedRouteConfig,\n): (request: Request) => Promise<Response> {\n return async (request: Request): Promise<Response> => {\n const url = new URL(request.url);\n const accept = request.headers.get('accept') ?? '';\n const userAgent = request.headers.get('user-agent');\n // Strip the .md/.json suffix so the feed path matches the page path.\n const path = url.pathname.replace(/\\.(md|json)$/, '');\n\n if (config.onRead) {\n try {\n void Promise.resolve(\n config.onRead({ path, userAgent, botName: matchedAgentToken(userAgent ?? '') }),\n ).catch(() => {});\n } catch {\n /* logging must never break the response */\n }\n }\n\n const feed = await config.getFeed(request);\n\n if (wantsMarkdown(url, accept)) {\n return new Response(renderAgentMarkdown(feed), {\n headers: { 'content-type': 'text/markdown; charset=utf-8' },\n });\n }\n return new Response(JSON.stringify(feed), {\n headers: { 'content-type': 'application/json; charset=utf-8' },\n });\n };\n}\n"],"mappings":"qlBAAA,OAAS,wBAAAA,GAAsB,qBAAAC,OAAyB,mBAExD,OAAS,WAAAC,GAAS,WAAAC,OAAe,eCFjC,OAAS,wBAAAC,OAA4B,mBACrC,OAAS,kBAAAC,OAAsB,qBAoD3B,cAAAC,OAAA,oBAhCJ,SAASC,EAAeC,EAAuB,CAC7C,OAAO,KAAK,UAAUA,CAA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ACExB,GAAAF,GAAA,CACG,UAAA4D,EACAE,GACH,EAOJ,IAAMI,GAAOC,EAAe,CAC1B,KAAMpB,EACN,OAAQ3C,GAAoB+C,CAAkB,EAC9C,YAAaC,GAAA,KAAAA,EAAsB,OACnC,QAAS1B,EAAU,OACrB,CAAC,EAED,OACExB,GAAAF,GAAA,CACG,UAAA4D,EACD3D,EAAC,UACC,KAAK,sBACL,MAAO2B,EACP,wBAAyB,CAAE,OAAQwC,GAAsBF,EAAI,CAAE,EACjE,EACCJ,GACH,CAEJ","names":["deriveSessionSegment","matchedAgentToken","cookies","headers","renderPrePaintScript","confidenceBand","jsx","inlineJsString","value","personaScriptBody","props","SentientPersonaScript","preloadAssignments","readSessionCookie","preloadDecisions","defaultSessionId","loadAdaptiveAssignments","components","options","_a","_b","_c","sessionId","readSessionCookie","preloadAssignments","loadAdaptiveDecision","_d","_e","_f","_g","_h","_i","_j","preloadDecisions","fallback","mod","outcome","e","result","__spreadProps","__spreadValues","AdaptiveRootClient","RESERVED_FIELDS","registry","defineAgentContent","page","content","getAgentContent","buildAgentFeed","input","_a","_b","supplied","getAgentContent","safe","k","v","RESERVED_FIELDS","feed","__spreadProps","__spreadValues","renderAgentJsonLdBody","feed","__spreadValues","renderAgentMarkdown","lines","k","v","b","logAgentFetch","entry","deps","_a","_b","doFetch","e","matchedAgentToken","wantsMarkdown","url","accept","createAgentFeed","config","request","_a","userAgent","path","matchedAgentToken","e","feed","renderAgentMarkdown","matchedAgentToken","uaTokenMatch","agentIntent","classifiedAgents","Fragment","jsx","jsxs","DEFAULT_API_BASE_URL","assignmentsToBlocks","assignments","id","v","_a","AdaptiveRoot","props","_b","_c","_d","_e","_f","_g","_h","_i","components","sections","slots","appOrigin","initialAssignmentsOverride","ssrSessionIdProp","timeoutMs","agentFeed","captureAgents","nonce","children","providerProps","__objRest","headerStore","headers","host","resolvedOrigin","userAgent","referer","doNotTrack","sessionSegment","deriveSessionSegment","cookieStore","cookies","cf","consent","skipSsr","baseUrl","agentPath","agentBot","matchedAgentToken","logAgentFetch","initialAssignments","initialLayoutOrder","initialSlots","initialPersona","ssrSessionId","decision","loadAdaptiveDecision","result","loadAdaptiveAssignments","personaScript","SentientPersonaScript","client","AdaptiveRootClient","__spreadProps","__spreadValues","feed","buildAgentFeed","renderAgentJsonLdBody"]}
|