@sentientui/core 0.40.2 → 0.41.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.
- package/dist/chunk-3HMJERH4.mjs +2 -0
- package/dist/chunk-3HMJERH4.mjs.map +1 -0
- package/dist/{chunk-ZTQXHKHU.mjs → chunk-KXA3X6T3.mjs} +2 -2
- package/dist/chunk-KXA3X6T3.mjs.map +1 -0
- package/dist/{index-BgEe5mKL.d.ts → index-C--aVpoo.d.ts} +1 -1
- package/dist/{index-B7s2gvyU.d.cts → index-DlJDNOWu.d.cts} +1 -1
- package/dist/index-engagement.js +1 -1
- package/dist/index-engagement.js.map +1 -1
- package/dist/index-engagement.mjs +1 -1
- package/dist/index-graph.d.cts +4 -4
- package/dist/index-graph.d.ts +4 -4
- package/dist/index-graph.js +1 -1
- package/dist/index-graph.js.map +1 -1
- package/dist/index-graph.mjs +1 -1
- package/dist/index-local.d.cts +2 -2
- package/dist/index-local.d.ts +2 -2
- package/dist/index-server.d.cts +2 -2
- package/dist/index-server.d.ts +2 -2
- package/dist/index-server.js +1 -1
- package/dist/index-server.js.map +1 -1
- package/dist/index-server.mjs +1 -1
- package/dist/index-server.mjs.map +1 -1
- package/dist/index.d.cts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1 -1
- package/dist/{session-meta-BG8w53d7.d.cts → session-meta-BqBaLZag.d.cts} +17 -1
- package/dist/{session-meta-D9Wx2PtC.d.ts → session-meta-D_kdNsaU.d.ts} +17 -1
- package/package.json +2 -2
- package/dist/chunk-NBDVEYI5.mjs +0 -2
- package/dist/chunk-NBDVEYI5.mjs.map +0 -1
- package/dist/chunk-ZTQXHKHU.mjs.map +0 -1
package/dist/index-server.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{c as _,g as H,h as J,i as z,j as Y,k as W,l as X,m as Q,n as k,o as $,p as j,q as M}from"./chunk-NBDVEYI5.mjs";import{b as E,c as D}from"./chunk-J5EL7HKC.mjs";import{a as m,b as I}from"./chunk-TMCGHANO.mjs";var Z="X-Sentient-Server-Key";function N(e){let r={"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`};return e.origin&&(r.Origin=e.origin),e.serverKey&&typeof window=="undefined"&&(r[Z]=e.serverKey),r}var F=1e3;function O(e,r,t){let i=new AbortController,n=setTimeout(()=>i.abort(),t);return fetch(e,I(m({},r),{signal:i.signal})).finally(()=>clearTimeout(n))}async function ee(e,r,t){return(await L(e,r,t)).assignments}async function L(e,r,t,i){var a;if(t.doNotTrack)return{assignments:{},unified:[]};let n=(a=t.timeoutMs)!=null?a:F,s=N(t),o=m(m({},k(r,{userAgent:t.userAgent,referer:t.referer,utmParams:t.utmParams,clickIds:t.clickIds,appOrigin:t.origin,landingPath:t.landingPath})),t.persona?{persona:t.persona}:{});try{let l=await O(`${t.baseUrl}/sessions`,{method:"POST",headers:s,body:JSON.stringify(o)},n);if(l.status===402)console.warn("[SentientUI] Session limit exceeded for this project. The bandit will stop learning until the limit resets. Upgrade at sentient-ui.com/pricing");else if(!l.ok){let h=await l.json().catch(()=>({}));console.error(`[SentientUI] preloadAssignments: session upsert failed (${l.status})`,h)}}catch(l){console.error("[SentientUI] preloadAssignments: session upsert threw",l)}let c=await Promise.allSettled(e.map(async({id:l,variantIds:h})=>{let b=await O(`${t.baseUrl}/assign`,{method:"POST",headers:s,body:JSON.stringify(m({sessionId:r,componentId:l,variantIds:h},i!=null&&i.unified?{caps:{unified:!0}}:{}))},n);if(!b.ok){let x=await b.json().catch(()=>({}));return console.error(`[SentientUI] preloadAssignments: assign failed for "${l}" (${b.status})`,x),null}let y=await b.json();return{id:l,variantId:y.variantId,unified:(i==null?void 0:i.unified)===!0&&y.unified===!0}})),p={},u=[];for(let l of c)l.status==="fulfilled"&&l.value&&(l.value.unified?u.push(l.value.id):p[l.value.id]=l.value.variantId);return{assignments:p,unified:u}}function te(e,r){var t,i,n,s;return(s=(n=r?(t=e.get(D(r)))==null?void 0:t.value:void 0)!=null?n:(i=e.get(E))==null?void 0:i.value)!=null?s:null}async function ne(e,r,t){var u,a,l,h,b,y,x,S,A,d,f,U;let i=(u=t.timeoutMs)!=null?u:F,n=(a=e.slots)!=null?a:[],s=null;e.slotsFrom==="registry"&&(Array.isArray(e.registrySlotIds)?s=e.registrySlotIds:console.error("[SentientUI] preloadDecisions: slotsFrom: 'registry' needs registrySlotIds (the <Adaptive id>s this page renders). An unscoped registry decide records a trial for every published slot on every page; falling back to request mode."));let o={layoutOrder:(l=e.sections)!=null?l:[],assignments:{},slots:M(n),persona:"unknown",confidence:0};if(t.doNotTrack)return o;let c=N(t),p=m(m({},k(r,{userAgent:t.userAgent,referer:t.referer,utmParams:t.utmParams,clickIds:t.clickIds,appOrigin:t.origin,landingPath:t.landingPath})),t.persona?{persona:t.persona}:{});try{let v=await O(`${t.baseUrl}/sessions`,{method:"POST",headers:c,body:JSON.stringify(p)},i);if(!v.ok){let g=await v.json().catch(()=>({}));console.error(`[SentientUI] preloadDecisions: session upsert failed (${v.status})`,g)}}catch(v){console.error("[SentientUI] preloadDecisions: session upsert threw",v)}try{let v=await O(`${t.baseUrl}/decide`,{method:"POST",headers:c,body:JSON.stringify(m(m(m(m({sessionId:r,sections:((h=e.sections)!=null?h:[]).map(w=>({id:w})),components:e.components},n.length>0?{slots:n.map($)}:{}),s!==null?{slotsFrom:"registry",registrySlotIds:s,bootstrap:!1,render:Object.fromEntries(s.map(w=>{var R,T;return[w,(T=(R=e.renderCaps)==null?void 0:R[w])!=null?T:{forms:!0,compose:!0,ops:!1}]}))}:{}),t.persona?{persona:t.persona}:{}),e.unifiedCaps?{caps:{unified:!0}}:{}))},i);if(!v.ok){let w=await v.json().catch(()=>({}));return console.error(`[SentientUI] preloadDecisions: decide failed (${v.status})`,w),o}let g=await v.json(),C={};for(let w of n)C[w.id]=(y=(b=g.slots)==null?void 0:b[w.id])!=null?y:j(w);for(let[w,R]of Object.entries((x=g.slots)!=null?x:{}))w in C||(C[w]=R);let q=g.slotConfig!==void 0&&typeof g.slotConfig=="object"&&g.slotConfig!==null&&!Array.isArray(g.slotConfig);return m(m(m(m(m(m({layoutOrder:(A=(S=g.layoutOrder)!=null?S:e.sections)!=null?A:[],assignments:(d=g.assignments)!=null?d:{},slots:C,persona:(f=g.persona)!=null?f:"unknown",confidence:(U=g.confidence)!=null?U:0},q?{slotConfig:g.slotConfig}:{}),g.palette?{palette:g.palette}:{}),g.vocabulary?{vocabulary:g.vocabulary}:{}),typeof g.stage=="string"?{stage:g.stage}:{}),typeof g.context=="string"?{context:g.context}:{}),e.unifiedCaps&&Array.isArray(g.unified)?{unified:g.unified.filter(w=>typeof w=="string")}:{})}catch(v){return console.error("[SentientUI] preloadDecisions: decide threw",v),o}}var G="3d8f5a21-7c64-4b19-8e0a-5f2c91d7b6e3";function re(e){let r=(b,y)=>b<<y|b>>>32-y,t=e.length,i=new Uint8Array((t+8>>6)*64+64);i.set(e),i[t]=128;let n=new DataView(i.buffer);n.setUint32(i.length-8,Math.floor(t*8/4294967296)),n.setUint32(i.length-4,t*8>>>0);let s=1732584193,o=4023233417,c=2562383102,p=271733878,u=3285377520,a=new Array(80);for(let b=0;b<i.length;b+=64){for(let f=0;f<16;f++)a[f]=n.getUint32(b+f*4);for(let f=16;f<80;f++)a[f]=r(a[f-3]^a[f-8]^a[f-14]^a[f-16],1);let y=s,x=o,S=c,A=p,d=u;for(let f=0;f<80;f++){let[U,v]=f<20?[x&S|~x&A,1518500249]:f<40?[x^S^A,1859775393]:f<60?[x&S|x&A|S&A,2400959708]:[x^S^A,3395469782],g=r(y,5)+U+d+v+a[f]|0;d=A,A=S,S=r(x,30),x=y,y=g}s=s+y|0,o=o+x|0,c=c+S|0,p=p+A|0,u=u+d|0}let l=new Uint8Array(20),h=new DataView(l.buffer);return[s,o,c,p,u].forEach((b,y)=>h.setUint32(y*4,b>>>0)),l}async function se(e,r){var u;let t=r.replace(/-/g,""),i=new Uint8Array(16);for(let a=0;a<16;a++)i[a]=parseInt(t.slice(a*2,a*2+2),16);let n=new TextEncoder().encode(e),s=new Uint8Array(16+n.length);s.set(i,0),s.set(n,16);let o=(u=globalThis.crypto)==null?void 0:u.subtle,c=(o?new Uint8Array(await o.digest("SHA-1",s)):re(s)).slice(0,16);c[6]=c[6]&15|80,c[8]=c[8]&63|128;let p=Array.from(c,a=>a.toString(16).padStart(2,"0")).join("");return`${p.slice(0,8)}-${p.slice(8,12)}-${p.slice(12,16)}-${p.slice(16,20)}-${p.slice(20,32)}`}var ie=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]);function P(e){let r=e.length*8,t=new Uint8Array(Math.ceil((e.length+9)/64)*64);t.set(e),t[e.length]=128;let i=new DataView(t.buffer);i.setUint32(t.length-8,Math.floor(r/4294967296)),i.setUint32(t.length-4,r>>>0);let n=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),s=new Uint32Array(64),o=(u,a)=>u>>>a|u<<32-a;for(let u=0;u<t.length;u+=64){for(let d=0;d<16;d++)s[d]=i.getUint32(u+d*4);for(let d=16;d<64;d++){let f=o(s[d-15],7)^o(s[d-15],18)^s[d-15]>>>3,U=o(s[d-2],17)^o(s[d-2],19)^s[d-2]>>>10;s[d]=s[d-16]+f+s[d-7]+U|0}let[a,l,h,b,y,x,S,A]=[n[0],n[1],n[2],n[3],n[4],n[5],n[6],n[7]];for(let d=0;d<64;d++){let f=A+(o(y,6)^o(y,11)^o(y,25))+(y&x^~y&S)+ie[d]+s[d]|0,U=(o(a,2)^o(a,13)^o(a,22))+(a&l^a&h^l&h)|0;A=S,S=x,x=y,y=b+f|0,b=h,h=l,l=a,a=f+U|0}n[0]=n[0]+a|0,n[1]=n[1]+l|0,n[2]=n[2]+h|0,n[3]=n[3]+b|0,n[4]=n[4]+y|0,n[5]=n[5]+x|0,n[6]=n[6]+S|0,n[7]=n[7]+A|0}let c=new Uint8Array(32),p=new DataView(c.buffer);return n.forEach((u,a)=>p.setUint32(a*4,u)),c}function oe(e,r){let t=new Uint8Array(64);t.set(e.length>64?P(e):e);let i=new Uint8Array(64+r.length),n=new Uint8Array(96);for(let s=0;s<64;s++)i[s]=t[s]^54,n[s]=t[s]^92;return i.set(r,64),n.set(P(i),64),P(n)}async function K(e,r){var c;let t=new TextEncoder,i=t.encode(e),n=t.encode(r),s=(c=globalThis.crypto)==null?void 0:c.subtle,o=s?new Uint8Array(await s.sign("HMAC",await s.importKey("raw",i,{name:"HMAC",hash:"SHA-256"},!1,["sign"]),n)):oe(i,n);return Array.from(o,p=>p.toString(16).padStart(2,"0")).join("")}async function ae(e,r,t){var s,o;if(typeof window!="undefined")return console.error("[SentientUI] signUserId is server-only: it needs the secret key. Compute the hash on your server and pass it to identify()."),"";let i=Math.floor(((s=t==null?void 0:t.now)!=null?s:Date.now())/1e3)+Math.min((o=t==null?void 0:t.ttlSeconds)!=null?o:86400,7*86400),n=await K(r,"sentient-identity-v1");return`v1.${i}.${await K(n,`${e}.${i}`)}`}var ce="https://api.sentient-ui.com/v1",le=5e3;async function de(e){var s,o;if(typeof window!="undefined")return console.error("[SentientUI] trackServerGoal is server-only: the secret key was not sent. Call it from a route handler, server action or webhook."),"failed";let r=e.sessionId?null:e.userId||null;if(!e.sessionId&&!r)return"skipped_no_visitor";if(e.name.includes(":"))return console.error('[SentientUI] trackServerGoal: goal names cannot contain ":" (nothing was sent).'),"failed";let t=(s=e.fetch)!=null?s:fetch,i=new AbortController,n;try{let c=new Promise((a,l)=>{var h;n=setTimeout(()=>{i.abort(),l(new Error("timeout"))},(h=e.timeoutMs)!=null?h:le)});c.catch(()=>{});let p=await se(r===null?`${e.sessionId}:${e.name}:${e.dedupeKey}`:`user:${e.serverKey}:${r}:${e.name}:${e.dedupeKey}`,G),u=await Promise.race([t(`${((o=e.apiBaseUrl)!=null?o:ce).replace(/\/+$/,"")}/goals`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e.serverKey}`},body:JSON.stringify(m(m(m(I(m({},r===null?{sessionId:e.sessionId}:{userId:r}),{name:e.name,goalId:p,externalId:e.dedupeKey}),e.value!==void 0?{value:e.value}:{}),e.currency!==void 0?{currency:e.currency}:{}),e.metadata!==void 0?{metadata:e.metadata}:{})),signal:i.signal}),c]);return u.ok?"recorded":r!==null&&u.status===404?(process.env.NODE_ENV!=="production"&&console.warn(`[SentientUI] trackServerGoal: no visit is linked to userId "${r}" yet, so "${e.name}" was not recorded. Identify the visitor in the browser first (<AdaptiveRoot userId>, or identify(userId, { userHash })) \u2014 once a project signs its identifies, only signed visits count.`),"skipped_no_visitor"):"failed"}catch(c){return"failed"}finally{n&&clearTimeout(n)}}var ue="https://api.sentient-ui.com/v1";function fe(e){try{return new URL(e,"http://localhost").pathname||"/"}catch(r){return e.split(/[?#]/,1)[0]||"/"}}function B(e,r){var i,n,s,o;let t=(i=r.fetchImpl)!=null?i:typeof fetch=="function"?fetch:void 0;if(!(!t||!r.apiKey))try{let c=t(`${(n=r.baseUrl)!=null?n:ue}/crawler-events`,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${r.apiKey}`},body:JSON.stringify({path:e.path,botName:e.botName,userAgent:e.userAgent,source:(s=r.source)!=null?s:"middleware"})}).catch(()=>{});(o=r.waitUntil)==null||o.call(r,c)}catch(c){}}function V(e,r){var n;let t="";try{t=(n=e.headers.get("user-agent"))!=null?n:""}catch(s){return!1}let i=_(t);return i?(B({path:fe(e.url),userAgent:t,botName:i},r),!0):!1}function ge(e){return(r,t,i)=>{var n,s,o;try{let c=r.headers["user-agent"],p=Array.isArray(c)?(n=c[0])!=null?n:"":c!=null?c:"";V({url:(o=(s=r.originalUrl)!=null?s:r.url)!=null?o:"/",headers:{get:u=>u.toLowerCase()==="user-agent"?p:null}},I(m({},e),{source:"middleware"}))}catch(c){}i()}}export{Y as CLICK_ID_KEYS,G as SERVER_GOAL_NAMESPACE,k as buildSessionUpsertPayload,V as captureAgentRequest,Q as deriveSessionSegment,H as detectDeviceClass,X as detectTimeOfDay,J as detectTrafficSource,W as extractTrackedParams,B as postAgentFetch,ee as preloadAssignments,L as preloadAssignmentsDetailed,ne as preloadDecisions,te as readSessionCookie,z as referrerDomainFromReferer,ge as sentientAgentMiddleware,ae as signUserId,de as trackServerGoal};
|
|
1
|
+
import{c as _,d as H,e as J,i as z,j as W,k as Y,l as X,m as Q,n as Z,o as ee,p as k,q as $,r as j,s as M}from"./chunk-3HMJERH4.mjs";import{b as P,c as D}from"./chunk-J5EL7HKC.mjs";import{a as m,b as I}from"./chunk-TMCGHANO.mjs";var te="X-Sentient-Server-Key";function N(e){let r={"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`};return e.origin&&(r.Origin=e.origin),e.serverKey&&typeof window=="undefined"&&(r[te]=e.serverKey),r}var F=1e3;function O(e,r,t){let i=new AbortController,n=setTimeout(()=>i.abort(),t);return fetch(e,I(m({},r),{signal:i.signal})).finally(()=>clearTimeout(n))}async function ne(e,r,t){return(await L(e,r,t)).assignments}async function L(e,r,t,i){var a;if(t.doNotTrack)return{assignments:{},unified:[]};let n=(a=t.timeoutMs)!=null?a:F,s=N(t),o=m(m({},k(r,{userAgent:t.userAgent,referer:t.referer,utmParams:t.utmParams,clickIds:t.clickIds,appOrigin:t.origin,landingPath:t.landingPath})),t.persona?{persona:t.persona}:{});try{let l=await O(`${t.baseUrl}/sessions`,{method:"POST",headers:s,body:JSON.stringify(o)},n);if(l.status===402)console.warn("[SentientUI] Session limit exceeded for this project. The bandit will stop learning until the limit resets. Upgrade at sentient-ui.com/pricing");else if(!l.ok){let h=await l.json().catch(()=>({}));console.error(`[SentientUI] preloadAssignments: session upsert failed (${l.status})`,h)}}catch(l){console.error("[SentientUI] preloadAssignments: session upsert threw",l)}let c=await Promise.allSettled(e.map(async({id:l,variantIds:h})=>{let b=await O(`${t.baseUrl}/assign`,{method:"POST",headers:s,body:JSON.stringify(m({sessionId:r,componentId:l,variantIds:h},i!=null&&i.unified?{caps:{unified:!0}}:{}))},n);if(!b.ok){let x=await b.json().catch(()=>({}));return console.error(`[SentientUI] preloadAssignments: assign failed for "${l}" (${b.status})`,x),null}let y=await b.json();return{id:l,variantId:y.variantId,unified:(i==null?void 0:i.unified)===!0&&y.unified===!0}})),p={},u=[];for(let l of c)l.status==="fulfilled"&&l.value&&(l.value.unified?u.push(l.value.id):p[l.value.id]=l.value.variantId);return{assignments:p,unified:u}}function re(e,r){var t,i,n,s;return(s=(n=r?(t=e.get(D(r)))==null?void 0:t.value:void 0)!=null?n:(i=e.get(P))==null?void 0:i.value)!=null?s:null}async function se(e,r,t){var u,a,l,h,b,y,x,S,A,d,f,U;let i=(u=t.timeoutMs)!=null?u:F,n=(a=e.slots)!=null?a:[],s=null;e.slotsFrom==="registry"&&(Array.isArray(e.registrySlotIds)?s=e.registrySlotIds:console.error("[SentientUI] preloadDecisions: slotsFrom: 'registry' needs registrySlotIds (the <Adaptive id>s this page renders). An unscoped registry decide records a trial for every published slot on every page; falling back to request mode."));let o={layoutOrder:(l=e.sections)!=null?l:[],assignments:{},slots:M(n),persona:"unknown",confidence:0};if(t.doNotTrack)return o;let c=N(t),p=m(m({},k(r,{userAgent:t.userAgent,referer:t.referer,utmParams:t.utmParams,clickIds:t.clickIds,appOrigin:t.origin,landingPath:t.landingPath})),t.persona?{persona:t.persona}:{});try{let v=await O(`${t.baseUrl}/sessions`,{method:"POST",headers:c,body:JSON.stringify(p)},i);if(!v.ok){let g=await v.json().catch(()=>({}));console.error(`[SentientUI] preloadDecisions: session upsert failed (${v.status})`,g)}}catch(v){console.error("[SentientUI] preloadDecisions: session upsert threw",v)}try{let v=await O(`${t.baseUrl}/decide`,{method:"POST",headers:c,body:JSON.stringify(m(m(m(m({sessionId:r,sections:((h=e.sections)!=null?h:[]).map(w=>({id:w})),components:e.components},n.length>0?{slots:n.map($)}:{}),s!==null?{slotsFrom:"registry",registrySlotIds:s,bootstrap:!1,render:Object.fromEntries(s.map(w=>{var R,E;return[w,(E=(R=e.renderCaps)==null?void 0:R[w])!=null?E:{forms:!0,compose:!0,ops:!1}]}))}:{}),t.persona?{persona:t.persona}:{}),e.unifiedCaps?{caps:{unified:!0}}:{}))},i);if(!v.ok){let w=await v.json().catch(()=>({}));return console.error(`[SentientUI] preloadDecisions: decide failed (${v.status})`,w),o}let g=await v.json(),C={};for(let w of n)C[w.id]=(y=(b=g.slots)==null?void 0:b[w.id])!=null?y:j(w);for(let[w,R]of Object.entries((x=g.slots)!=null?x:{}))w in C||(C[w]=R);let q=g.slotConfig!==void 0&&typeof g.slotConfig=="object"&&g.slotConfig!==null&&!Array.isArray(g.slotConfig);return m(m(m(m(m(m({layoutOrder:(A=(S=g.layoutOrder)!=null?S:e.sections)!=null?A:[],assignments:(d=g.assignments)!=null?d:{},slots:C,persona:(f=g.persona)!=null?f:"unknown",confidence:(U=g.confidence)!=null?U:0},q?{slotConfig:g.slotConfig}:{}),g.palette?{palette:g.palette}:{}),g.vocabulary?{vocabulary:g.vocabulary}:{}),typeof g.stage=="string"?{stage:g.stage}:{}),typeof g.context=="string"?{context:g.context}:{}),e.unifiedCaps&&Array.isArray(g.unified)?{unified:g.unified.filter(w=>typeof w=="string")}:{})}catch(v){return console.error("[SentientUI] preloadDecisions: decide threw",v),o}}var G="3d8f5a21-7c64-4b19-8e0a-5f2c91d7b6e3";function ie(e){let r=(b,y)=>b<<y|b>>>32-y,t=e.length,i=new Uint8Array((t+8>>6)*64+64);i.set(e),i[t]=128;let n=new DataView(i.buffer);n.setUint32(i.length-8,Math.floor(t*8/4294967296)),n.setUint32(i.length-4,t*8>>>0);let s=1732584193,o=4023233417,c=2562383102,p=271733878,u=3285377520,a=new Array(80);for(let b=0;b<i.length;b+=64){for(let f=0;f<16;f++)a[f]=n.getUint32(b+f*4);for(let f=16;f<80;f++)a[f]=r(a[f-3]^a[f-8]^a[f-14]^a[f-16],1);let y=s,x=o,S=c,A=p,d=u;for(let f=0;f<80;f++){let[U,v]=f<20?[x&S|~x&A,1518500249]:f<40?[x^S^A,1859775393]:f<60?[x&S|x&A|S&A,2400959708]:[x^S^A,3395469782],g=r(y,5)+U+d+v+a[f]|0;d=A,A=S,S=r(x,30),x=y,y=g}s=s+y|0,o=o+x|0,c=c+S|0,p=p+A|0,u=u+d|0}let l=new Uint8Array(20),h=new DataView(l.buffer);return[s,o,c,p,u].forEach((b,y)=>h.setUint32(y*4,b>>>0)),l}async function oe(e,r){var u;let t=r.replace(/-/g,""),i=new Uint8Array(16);for(let a=0;a<16;a++)i[a]=parseInt(t.slice(a*2,a*2+2),16);let n=new TextEncoder().encode(e),s=new Uint8Array(16+n.length);s.set(i,0),s.set(n,16);let o=(u=globalThis.crypto)==null?void 0:u.subtle,c=(o?new Uint8Array(await o.digest("SHA-1",s)):ie(s)).slice(0,16);c[6]=c[6]&15|80,c[8]=c[8]&63|128;let p=Array.from(c,a=>a.toString(16).padStart(2,"0")).join("");return`${p.slice(0,8)}-${p.slice(8,12)}-${p.slice(12,16)}-${p.slice(16,20)}-${p.slice(20,32)}`}var ae=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]);function T(e){let r=e.length*8,t=new Uint8Array(Math.ceil((e.length+9)/64)*64);t.set(e),t[e.length]=128;let i=new DataView(t.buffer);i.setUint32(t.length-8,Math.floor(r/4294967296)),i.setUint32(t.length-4,r>>>0);let n=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),s=new Uint32Array(64),o=(u,a)=>u>>>a|u<<32-a;for(let u=0;u<t.length;u+=64){for(let d=0;d<16;d++)s[d]=i.getUint32(u+d*4);for(let d=16;d<64;d++){let f=o(s[d-15],7)^o(s[d-15],18)^s[d-15]>>>3,U=o(s[d-2],17)^o(s[d-2],19)^s[d-2]>>>10;s[d]=s[d-16]+f+s[d-7]+U|0}let[a,l,h,b,y,x,S,A]=[n[0],n[1],n[2],n[3],n[4],n[5],n[6],n[7]];for(let d=0;d<64;d++){let f=A+(o(y,6)^o(y,11)^o(y,25))+(y&x^~y&S)+ae[d]+s[d]|0,U=(o(a,2)^o(a,13)^o(a,22))+(a&l^a&h^l&h)|0;A=S,S=x,x=y,y=b+f|0,b=h,h=l,l=a,a=f+U|0}n[0]=n[0]+a|0,n[1]=n[1]+l|0,n[2]=n[2]+h|0,n[3]=n[3]+b|0,n[4]=n[4]+y|0,n[5]=n[5]+x|0,n[6]=n[6]+S|0,n[7]=n[7]+A|0}let c=new Uint8Array(32),p=new DataView(c.buffer);return n.forEach((u,a)=>p.setUint32(a*4,u)),c}function ce(e,r){let t=new Uint8Array(64);t.set(e.length>64?T(e):e);let i=new Uint8Array(64+r.length),n=new Uint8Array(96);for(let s=0;s<64;s++)i[s]=t[s]^54,n[s]=t[s]^92;return i.set(r,64),n.set(T(i),64),T(n)}async function K(e,r){var c;let t=new TextEncoder,i=t.encode(e),n=t.encode(r),s=(c=globalThis.crypto)==null?void 0:c.subtle,o=s?new Uint8Array(await s.sign("HMAC",await s.importKey("raw",i,{name:"HMAC",hash:"SHA-256"},!1,["sign"]),n)):ce(i,n);return Array.from(o,p=>p.toString(16).padStart(2,"0")).join("")}async function le(e,r,t){var s,o;if(typeof window!="undefined")return console.error("[SentientUI] signUserId is server-only: it needs the secret key. Compute the hash on your server and pass it to identify()."),"";let i=Math.floor(((s=t==null?void 0:t.now)!=null?s:Date.now())/1e3)+Math.min((o=t==null?void 0:t.ttlSeconds)!=null?o:86400,7*86400),n=await K(r,"sentient-identity-v1");return`v1.${i}.${await K(n,`${e}.${i}`)}`}var de="https://api.sentient-ui.com/v1",ue=5e3;async function fe(e){var s,o;if(typeof window!="undefined")return console.error("[SentientUI] trackServerGoal is server-only: the secret key was not sent. Call it from a route handler, server action or webhook."),"failed";let r=e.sessionId?null:e.userId||null;if(!e.sessionId&&!r)return"skipped_no_visitor";if(e.name.includes(":"))return console.error('[SentientUI] trackServerGoal: goal names cannot contain ":" (nothing was sent).'),"failed";let t=(s=e.fetch)!=null?s:fetch,i=new AbortController,n;try{let c=new Promise((a,l)=>{var h;n=setTimeout(()=>{i.abort(),l(new Error("timeout"))},(h=e.timeoutMs)!=null?h:ue)});c.catch(()=>{});let p=await oe(r===null?`${e.sessionId}:${e.name}:${e.dedupeKey}`:`user:${e.serverKey}:${r}:${e.name}:${e.dedupeKey}`,G),u=await Promise.race([t(`${((o=e.apiBaseUrl)!=null?o:de).replace(/\/+$/,"")}/goals`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e.serverKey}`},body:JSON.stringify(m(m(m(I(m({},r===null?{sessionId:e.sessionId}:{userId:r}),{name:e.name,goalId:p,externalId:e.dedupeKey}),e.value!==void 0?{value:e.value}:{}),e.currency!==void 0?{currency:e.currency}:{}),e.metadata!==void 0?{metadata:e.metadata}:{})),signal:i.signal}),c]);return u.ok?"recorded":r!==null&&u.status===404?(process.env.NODE_ENV!=="production"&&console.warn(`[SentientUI] trackServerGoal: no visit is linked to userId "${r}" yet, so "${e.name}" was not recorded. Identify the visitor in the browser first (<AdaptiveRoot userId>, or identify(userId, { userHash })) \u2014 once a project signs its identifies, only signed visits count.`),"skipped_no_visitor"):"failed"}catch(c){return"failed"}finally{n&&clearTimeout(n)}}var ge="https://api.sentient-ui.com/v1";function ye(e){try{return new URL(e,"http://localhost").pathname||"/"}catch(r){return e.split(/[?#]/,1)[0]||"/"}}function B(e,r){var i,n,s,o;let t=(i=r.fetchImpl)!=null?i:typeof fetch=="function"?fetch:void 0;if(!(!t||!r.apiKey))try{let c=t(`${(n=r.baseUrl)!=null?n:ge}/crawler-events`,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${r.apiKey}`},body:JSON.stringify({path:e.path,botName:e.botName,userAgent:e.userAgent,source:(s=r.source)!=null?s:"middleware"})}).catch(()=>{});(o=r.waitUntil)==null||o.call(r,c)}catch(c){}}function V(e,r){var n;let t="";try{t=(n=e.headers.get("user-agent"))!=null?n:""}catch(s){return!1}let i=_(t);return i?(B({path:ye(e.url),userAgent:t,botName:i},r),!0):!1}function pe(e){return(r,t,i)=>{var n,s,o;try{let c=r.headers["user-agent"],p=Array.isArray(c)?(n=c[0])!=null?n:"":c!=null?c:"";V({url:(o=(s=r.originalUrl)!=null?s:r.url)!=null?o:"/",headers:{get:u=>u.toLowerCase()==="user-agent"?p:null}},I(m({},e),{source:"middleware"}))}catch(c){}i()}}export{H as CLASSIC_CRAWLER_TOKENS,X as CLICK_ID_KEYS,G as SERVER_GOAL_NAMESPACE,k as buildSessionUpsertPayload,V as captureAgentRequest,ee as deriveSessionSegment,z as detectDeviceClass,Z as detectTimeOfDay,W as detectTrafficSource,Q as extractTrackedParams,J as matchedCrawlerToken,B as postAgentFetch,ne as preloadAssignments,L as preloadAssignmentsDetailed,se as preloadDecisions,re as readSessionCookie,Y as referrerDomainFromReferer,pe as sentientAgentMiddleware,le as signUserId,fe as trackServerGoal};
|
|
2
2
|
//# sourceMappingURL=index-server.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/server.ts","../src/agent-capture.ts"],"sourcesContent":["/**\n * Server-side helpers for SSR variant pre-loading.\n * Pure fetch — no DOM APIs. Safe in Node.js, Edge, and Deno runtimes.\n */\nimport { buildSessionUpsertPayload } from './session-meta.js';\nimport { LEGACY_SESSION_COOKIE_NAME, sessionCookieName } from './storage-key.js';\nimport {\n toWireSlot,\n baselineResultFor,\n baselineSlots,\n type SlotDeclInput,\n type SlotResult,\n} from './slots.js';\n\nimport type { SlotConfigEntry } from './snapshot.js';\nimport type { RenderCaps } from './region-skeleton.js';\nimport type { SitePalette } from './blocks.js';\n\nexport type { SlotDeclInput, SlotResult, SlotConfigEntry, SitePalette };\n\nexport type ServerAssignConfig = {\n /** Public API key (pk_...). */\n apiKey: string;\n /**\n * Base URL of the Sentient API without trailing slash.\n * e.g. 'https://api.yourapp.com/v1'\n */\n baseUrl: string;\n /**\n * Browser origin of your app (e.g. `http://localhost:3001`). Required for `pk_`\n * keys — server-side fetch must send the same `Origin` the API allows.\n */\n origin?: string;\n /**\n * Optional: this project's SECRET key (sk_...), read from a server-only env\n * var. When set, SSR calls also send it as `X-Sentient-Server-Key`, which\n * proves they come from your server: the API then holds them to your plan's\n * per-key limit instead of the 100 requests/min per-IP cap meant for\n * browsers — without it, all SSR traffic from one server address shares that\n * one cap. Never set this in code that ships to the browser; it is ignored\n * (and not sent) when `window` exists.\n */\n serverKey?: string;\n /** From `User-Agent` request header (Next.js `headers()`). */\n userAgent?: string;\n /** From `Referer` request header. */\n referer?: string;\n utmParams?: Record<string, string>;\n /**\n * Ad-platform click IDs (gclid, fbclid, ttclid, …) from the landing URL.\n * Derive both this and `utmParams` with `extractTrackedParams(searchParams)`\n * — the Referer header never carries the landing page's own query string, so\n * without these two fields SSR-minted sessions have no campaign attribution\n * until the client SDK hydrates.\n */\n clickIds?: Record<string, string>;\n /**\n * The landing page's path (no query string). With it the server can tell a\n * paid click to a product page, or a Shopify `/discount/CODE` link, from any\n * other arrival on the FIRST decision of the visit.\n */\n landingPath?: string;\n /**\n * Set true when the request carries a tracking opt-out — `DNT: 1` or\n * `Sec-GPC: 1`. When set, the SSR helpers skip the session upsert and the\n * assign/decide call entirely: the page renders defaults/baseline and no\n * session row is minted for the visitor (audit P4). The client SDK already\n * no-ops for these visitors; this keeps the server from minting a session +\n * assignment on every page view before the client can.\n */\n doNotTrack?: boolean;\n /**\n * Declared persona — the role your app already knows for this visitor\n * (e.g. from your auth context during SSR). Same contract as the client\n * option: must be a vocabulary key; unrecognized values are ignored\n * server-side. Never a user id or email.\n */\n persona?: string;\n /**\n * Milliseconds to wait for the API before returning default variants.\n * Prevents slow/cold API from blocking SSR. Defaults to 1000 — the hot path\n * is served from in-process caches and typically returns in well under\n * 150 ms. The full 1 s budget is only reached on a cold start or an API\n * geographically distant from your SSR host, after which defaults render\n * with no layout shift. Lower it if your API is co-located and warm.\n */\n timeoutMs?: number;\n};\n\n/** Header carrying `serverKey` (apps/api lib/rate-limit.ts SERVER_KEY_HEADER). */\nexport const SERVER_KEY_HEADER = 'X-Sentient-Server-Key';\n\n/** Auth headers for an SSR call: the pk_, its Origin, and the optional server proof. */\nfunction ssrHeaders(config: ServerAssignConfig): Record<string, string> {\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${config.apiKey}`,\n };\n if (config.origin) headers.Origin = config.origin;\n // A secret key must never leave a browser: if this module was bundled\n // client-side by mistake, drop it rather than send it.\n if (config.serverKey && typeof window === 'undefined') headers[SERVER_KEY_HEADER] = config.serverKey;\n return headers;\n}\n\n/** componentId → assigned variantId */\nexport type ServerAssignments = Record<string, string>;\n\ntype AssignResult = { variantId: string; assignmentTtlMs: number; unified?: true };\n\n/** `preloadAssignmentsDetailed`'s answer: the assignments, plus the ids the\n * server handed back as moved to the shared track (only when asked). */\nexport type ServerAssignmentsDetailed = { assignments: ServerAssignments; unified: string[] };\n\nconst DEFAULT_TIMEOUT_MS = 1000;\n\nfunction fetchWithTimeout(\n url: string,\n init: RequestInit,\n timeoutMs: number,\n): Promise<Response> {\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), timeoutMs);\n return fetch(url, { ...init, signal: controller.signal }).finally(() =>\n clearTimeout(timer),\n );\n}\n\n/**\n * Fetches variant assignments server-side for all listed components.\n * Returns a map suitable for passing as `initialAssignments` to `<AdaptiveProvider>`.\n *\n * Call from Next.js layout, Server Component, or getServerSideProps.\n *\n * @example\n * ```tsx\n * const assignments = await preloadAssignments(\n * [\n * { id: 'hero', variantIds: ['hero-a', 'hero-b'] },\n * { id: 'cta', variantIds: ['cta-short', 'cta-long'] },\n * ],\n * sessionId, // read from cookies() or req.cookies\n * { apiKey: process.env.NEXT_PUBLIC_SENTIENT_API_KEY!, baseUrl: 'https://api.sentient-ui.com/v1' },\n * );\n * return <AdaptiveProvider ... initialAssignments={assignments}>{children}</AdaptiveProvider>;\n * ```\n */\nexport async function preloadAssignments(\n components: Array<{ id: string; variantIds: string[] }>,\n sessionId: string,\n config: ServerAssignConfig,\n): Promise<ServerAssignments> {\n return (await preloadAssignmentsDetailed(components, sessionId, config)).assignments;\n}\n\n/**\n * `preloadAssignments`, and also which components were moved onto the shared\n * track. With `opts.unified` each assign says the page can follow such a move:\n * a moved id is then not assigned (nothing is recorded for it) and comes back\n * in `unified`, for the page to render as a slot. Pass those ids to\n * `<AdaptiveProvider initialUnified>`. Without it a moved id is served its\n * frozen result read-only, as for any older SDK.\n */\nexport async function preloadAssignmentsDetailed(\n components: Array<{ id: string; variantIds: string[] }>,\n sessionId: string,\n config: ServerAssignConfig,\n opts?: { unified?: boolean },\n): Promise<ServerAssignmentsDetailed> {\n // Opted-out visitor (DNT/GPC): render defaults, mint no session (audit P4).\n if (config.doNotTrack) return { assignments: {}, unified: [] };\n\n const timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n const headers = ssrHeaders(config);\n\n // Session metadata must match the browser SDK so assign seeds variant_weights\n // under the same segment (not `unknown:unknown`).\n const sessionBody = {\n ...buildSessionUpsertPayload(sessionId, {\n userAgent: config.userAgent,\n referer: config.referer,\n utmParams: config.utmParams,\n clickIds: config.clickIds,\n appOrigin: config.origin,\n landingPath: config.landingPath,\n }),\n ...(config.persona ? { persona: config.persona } : {}),\n };\n\n try {\n const res = await fetchWithTimeout(\n `${config.baseUrl}/sessions`,\n { method: 'POST', headers, body: JSON.stringify(sessionBody) },\n timeoutMs,\n );\n if (res.status === 402) {\n console.warn(\n '[SentientUI] Session limit exceeded for this project. The bandit will stop learning until the limit resets. Upgrade at sentient-ui.com/pricing',\n );\n } else if (!res.ok) {\n const body = await res.json().catch(() => ({}));\n console.error(`[SentientUI] preloadAssignments: session upsert failed (${res.status})`, body);\n }\n } catch (err) {\n console.error('[SentientUI] preloadAssignments: session upsert threw', err);\n }\n\n const results = await Promise.allSettled(\n components.map(async ({ id, variantIds }) => {\n const res = await fetchWithTimeout(\n `${config.baseUrl}/assign`,\n {\n method: 'POST',\n headers,\n body: JSON.stringify({ sessionId, componentId: id, variantIds, ...(opts?.unified ? { caps: { unified: true } } : {}) }),\n },\n timeoutMs,\n );\n if (!res.ok) {\n const body = await res.json().catch(() => ({}));\n console.error(`[SentientUI] preloadAssignments: assign failed for \"${id}\" (${res.status})`, body);\n return null;\n }\n const body = (await res.json()) as AssignResult;\n return { id, variantId: body.variantId, unified: opts?.unified === true && body.unified === true };\n }),\n );\n\n const assignments: ServerAssignments = {};\n const unified: string[] = [];\n for (const result of results) {\n if (result.status === 'fulfilled' && result.value) {\n // A moved id's variantId is only its declared baseline, not an\n // assignment: seeding it would settle the page on the frozen run.\n if (result.value.unified) unified.push(result.value.id);\n else assignments[result.value.id] = result.value.variantId;\n }\n }\n return { assignments, unified };\n}\n\n/**\n * Reads the Sentient session cookie from a Next.js `ReadonlyRequestCookies` object\n * (the return value of `cookies()` from `next/headers`), or any object with a\n * `get(name: string)` method. Returns null if the cookie is absent.\n *\n * Pass the project's `apiKey`: the client writes the per-project SUFFIXED name\n * (`sessionCookieName` — see storage-key.ts), so reading only the bare\n * `_snt_uid` missed the cookie on every SSR request for a returning visitor and\n * minted a fresh orphan session each page view (quota inflation, broken sticky\n * assignments and persona continuity). The bare name is still read as a\n * fallback for identities minted before namespacing.\n */\nexport function readSessionCookie(\n cookies: { get(name: string): { value: string } | undefined },\n apiKey?: string,\n): string | null {\n return (\n (apiKey ? cookies.get(sessionCookieName(apiKey))?.value : undefined) ??\n cookies.get(LEGACY_SESSION_COOKIE_NAME)?.value ??\n null\n );\n}\n\nexport type DecideResult = {\n layoutOrder: string[];\n assignments: Record<string, string>;\n /** Slot results keyed by slot id. Baseline-resolved when the API omits/fails them. */\n slots: Record<string, SlotResult>;\n persona: string;\n confidence: number;\n /** Registry mode only: content/ops/blocks for server-defined slots. */\n slotConfig?: Record<string, SlotConfigEntry>;\n /** Registry mode only: site palette for block rendering. */\n palette?: SitePalette;\n /** Registry mode only: site styles the served Redesign arms borrow. */\n vocabulary?: import('./style-vocabulary.js').StyleVocabulary;\n /** The visit's funnel stage, raw — projects with stages on, treated visitors\n * only. Pass it through `exposedStage` before it reaches the page. */\n stage?: string;\n /** The visit's serving context. Never for the page. */\n context?: string;\n /** Requested components moved onto the shared track (only with\n * `unifiedCaps`): not in `assignments`; render each as a slot. */\n unified?: string[];\n};\n\n/**\n * Single-roundtrip SSR call returning layout order, component assignments,\n * and adaptive-slot results. Falls back to default section order + empty\n * assignments + baseline slots if the API is unavailable. A response without\n * a `slots` field means the server predates slots — every declared slot\n * resolves to its baseline (no retry).\n */\nexport async function preloadDecisions(\n params: {\n sections?: string[];\n components: Array<{ id: string; variantIds?: string[] }>;\n slots?: SlotDeclInput[];\n /** 'registry' serves the project's published slot_definitions as if declared\n * (and is the only way slotConfig/palette come back). Default 'request'.\n * Requires `registrySlotIds`: the `<Adaptive id>`s THIS page renders. */\n slotsFrom?: 'request' | 'registry';\n /**\n * Registry mode: decide only these published slot ids. Close-out turns\n * every slot decision into a trial without checking an exposure, so an\n * unscoped registry decide accrues trials — and session-level credit — for\n * every published slot on every page, including ones this page never\n * renders (CONTRACTS §2). Omitting it in registry mode is refused: the\n * call downgrades to request mode with one console.error, rather than\n * silently minting those trials.\n */\n registrySlotIds?: string[];\n /**\n * Registry mode: what each slot on this page can render (CONTRACTS §2).\n * The server has no DOM here, so no fingerprint is sent and a Rewrite arm\n * is assumed to match; a real mismatch is reported from the browser as\n * drift. Declare `forms: false` for slots without an `onFormSubmit`, or a\n * form arm can be drawn that this page will refuse. Default per slot:\n * `{ forms: true, compose: true, ops: false }`.\n */\n renderCaps?: Record<string, Omit<RenderCaps, 'fp'>>;\n /** The page renders a moved (unified) component on the shared track: such\n * ids in `components` come back in `unified` instead of `assignments`,\n * with nothing recorded. Without it they are served the frozen result. */\n unifiedCaps?: boolean;\n },\n sessionId: string,\n config: ServerAssignConfig,\n): Promise<DecideResult> {\n const timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n const declaredSlots = params.slots ?? [];\n let registryIds: string[] | null = null;\n if (params.slotsFrom === 'registry') {\n if (Array.isArray(params.registrySlotIds)) {\n registryIds = params.registrySlotIds;\n } else {\n console.error(\n \"[SentientUI] preloadDecisions: slotsFrom: 'registry' needs registrySlotIds (the <Adaptive id>s this page renders). \" +\n 'An unscoped registry decide records a trial for every published slot on every page; falling back to request mode.',\n );\n }\n }\n const fallback: DecideResult = {\n layoutOrder: params.sections ?? [],\n assignments: {},\n slots: baselineSlots(declaredSlots),\n persona: 'unknown',\n confidence: 0,\n };\n\n // Opted-out visitor (DNT/GPC): baseline layout/slots, mint no session (audit P4).\n if (config.doNotTrack) return fallback;\n\n const headers = ssrHeaders(config);\n\n const sessionBody = {\n ...buildSessionUpsertPayload(sessionId, {\n userAgent: config.userAgent,\n referer: config.referer,\n utmParams: config.utmParams,\n clickIds: config.clickIds,\n appOrigin: config.origin,\n landingPath: config.landingPath,\n }),\n ...(config.persona ? { persona: config.persona } : {}),\n };\n\n try {\n const sessionRes = await fetchWithTimeout(\n `${config.baseUrl}/sessions`,\n { method: 'POST', headers, body: JSON.stringify(sessionBody) },\n timeoutMs,\n );\n if (!sessionRes.ok) {\n const body = await sessionRes.json().catch(() => ({}));\n console.error(`[SentientUI] preloadDecisions: session upsert failed (${sessionRes.status})`, body);\n }\n } catch (err) {\n console.error('[SentientUI] preloadDecisions: session upsert threw', err);\n }\n\n try {\n const res = await fetchWithTimeout(\n `${config.baseUrl}/decide`,\n {\n method: 'POST',\n headers,\n body: JSON.stringify({\n sessionId,\n sections: (params.sections ?? []).map((id) => ({ id })),\n components: params.components,\n ...(declaredSlots.length > 0 ? { slots: declaredSlots.map(toWireSlot) } : {}),\n // bootstrap:false — editor goals and the section map are snippet\n // data the React SDK never reads. An EMPTY id list is meaningful\n // (\"nothing published is on this page\"): zero trials, still a decide.\n ...(registryIds !== null\n ? {\n slotsFrom: 'registry',\n registrySlotIds: registryIds,\n bootstrap: false,\n // Always sent, so the server knows this is an SDK that can\n // render Rewrite arms — no `render` field means legacy.\n render: Object.fromEntries(\n // compose: true — the React SDK (the SSR consumer) renders\n // Redesign trees since native generation phase 2.\n // ops: false — nothing here applies `ops`. Without it an\n // SSR'd <Adaptive id> matching a script-tag component was drawn\n // its ops-only version, rendered the original, and booked a trial.\n registryIds.map((id) => [id, params.renderCaps?.[id] ?? { forms: true, compose: true, ops: false }]),\n ),\n }\n : {}),\n ...(config.persona ? { persona: config.persona } : {}),\n ...(params.unifiedCaps ? { caps: { unified: true } } : {}),\n }),\n },\n timeoutMs,\n );\n if (!res.ok) {\n const body = await res.json().catch(() => ({}));\n console.error(`[SentientUI] preloadDecisions: decide failed (${res.status})`, body);\n return fallback;\n }\n const data = (await res.json()) as {\n layoutOrder?: string[];\n assignments?: Record<string, string>;\n slots?: Record<string, SlotResult>;\n slotConfig?: Record<string, SlotConfigEntry>;\n palette?: SitePalette;\n vocabulary?: import('./style-vocabulary.js').StyleVocabulary;\n persona?: string;\n confidence?: number;\n stage?: unknown;\n context?: unknown;\n unified?: unknown;\n };\n\n const slots: Record<string, SlotResult> = {};\n for (const d of declaredSlots) {\n // `data.slots === undefined` ⇒ server predates slots: baseline, no retry.\n slots[d.id] = data.slots?.[d.id] ?? baselineResultFor(d);\n }\n // Registry mode returns slots the request never declared — union them in\n // (same rule as the browser client), or an SSR page gets results for none\n // of its registry slots.\n for (const [slotId, result] of Object.entries(data.slots ?? {})) {\n if (!(slotId in slots)) slots[slotId] = result;\n }\n\n // Plain-object guard only (readSnapshot's rule): the server total-validated\n // the config at publish; a deep re-validation here would just drift.\n const slotConfigOk =\n data.slotConfig !== undefined && typeof data.slotConfig === 'object' && data.slotConfig !== null && !Array.isArray(data.slotConfig);\n\n return {\n layoutOrder: data.layoutOrder ?? params.sections ?? [],\n assignments: data.assignments ?? {},\n slots,\n persona: data.persona ?? 'unknown',\n confidence: data.confidence ?? 0,\n ...(slotConfigOk ? { slotConfig: data.slotConfig } : {}),\n ...(data.palette ? { palette: data.palette } : {}),\n ...(data.vocabulary ? { vocabulary: data.vocabulary } : {}),\n ...(typeof data.stage === 'string' ? { stage: data.stage } : {}),\n ...(typeof data.context === 'string' ? { context: data.context } : {}),\n ...(params.unifiedCaps && Array.isArray(data.unified)\n ? { unified: data.unified.filter((id): id is string => typeof id === 'string') }\n : {}),\n };\n } catch (err) {\n console.error('[SentientUI] preloadDecisions: decide threw', err);\n return fallback;\n }\n}\n\n/**\n * Fixed namespace for server-goal ids. It is public (it ships in this file), so\n * it adds no secrecy: the id's uniqueness comes from the session id it hashes\n * (see trackServerGoal). Never change it: a retried delivery must map to the\n * same goal id.\n */\nexport const SERVER_GOAL_NAMESPACE = '3d8f5a21-7c64-4b19-8e0a-5f2c91d7b6e3';\n\n/**\n * Pure-JS SHA-1 (FIPS 180-4) for runtimes without Web Crypto: Node 18 (our\n * engines floor is 18.18) has no unflagged `globalThis.crypto`, and without\n * this every server goal there would end 'failed'. @internal: exported for\n * the test vector only; not re-exported from the entry.\n */\nexport function sha1Fallback(data: Uint8Array): Uint8Array {\n const rotl = (x: number, n: number): number => (x << n) | (x >>> (32 - n));\n const len = data.length;\n const padded = new Uint8Array(((len + 8) >> 6) * 64 + 64);\n padded.set(data);\n padded[len] = 0x80;\n const view = new DataView(padded.buffer);\n view.setUint32(padded.length - 8, Math.floor((len * 8) / 0x100000000));\n view.setUint32(padded.length - 4, (len * 8) >>> 0);\n let h0 = 0x67452301, h1 = 0xefcdab89, h2 = 0x98badcfe, h3 = 0x10325476, h4 = 0xc3d2e1f0;\n const w = new Array<number>(80);\n for (let off = 0; off < padded.length; off += 64) {\n for (let i = 0; i < 16; i++) w[i] = view.getUint32(off + i * 4);\n for (let i = 16; i < 80; i++) w[i] = rotl(w[i - 3]! ^ w[i - 8]! ^ w[i - 14]! ^ w[i - 16]!, 1);\n let a = h0, b = h1, c = h2, d = h3, e = h4;\n for (let i = 0; i < 80; i++) {\n const [f, k] =\n i < 20 ? [(b & c) | (~b & d), 0x5a827999]\n : i < 40 ? [b ^ c ^ d, 0x6ed9eba1]\n : i < 60 ? [(b & c) | (b & d) | (c & d), 0x8f1bbcdc]\n : [b ^ c ^ d, 0xca62c1d6];\n const t = (rotl(a, 5) + f! + e + k! + w[i]!) | 0;\n e = d; d = c; c = rotl(b, 30); b = a; a = t;\n }\n h0 = (h0 + a) | 0; h1 = (h1 + b) | 0; h2 = (h2 + c) | 0; h3 = (h3 + d) | 0; h4 = (h4 + e) | 0;\n }\n const out = new Uint8Array(20);\n const ov = new DataView(out.buffer);\n [h0, h1, h2, h3, h4].forEach((v, i) => ov.setUint32(i * 4, v >>> 0));\n return out;\n}\n\n/**\n * RFC-4122 v5 UUID (SHA-1 over namespace bytes + name), via Web Crypto so this\n * file stays free of `node:` imports and `Buffer` (it also hosts the SSR\n * helpers, which run on Edge and Deno). @internal: exported for the test vector.\n */\nexport async function uuidV5(name: string, namespace: string): Promise<string> {\n const hex = namespace.replace(/-/g, '');\n const nsBytes = new Uint8Array(16);\n for (let i = 0; i < 16; i++) nsBytes[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);\n const nameBytes = new TextEncoder().encode(name);\n const input = new Uint8Array(16 + nameBytes.length);\n input.set(nsBytes, 0);\n input.set(nameBytes, 16);\n const subtle = globalThis.crypto?.subtle;\n const h = (subtle ? new Uint8Array(await subtle.digest('SHA-1', input)) : sha1Fallback(input)).slice(0, 16);\n h[6] = (h[6]! & 0x0f) | 0x50;\n h[8] = (h[8]! & 0x3f) | 0x80;\n const x = Array.from(h, (b) => b.toString(16).padStart(2, '0')).join('');\n return `${x.slice(0, 8)}-${x.slice(8, 12)}-${x.slice(12, 16)}-${x.slice(16, 20)}-${x.slice(20, 32)}`;\n}\n\n// Pure-JS SHA-256 for the same Node-18 gap sha1Fallback covers (no global\n// Web Crypto there, and this file takes no `node:` imports). @internal.\nconst K256 = new Uint32Array([\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,\n]);\nexport function sha256Fallback(data: Uint8Array): Uint8Array {\n const bitLen = data.length * 8;\n const padded = new Uint8Array(Math.ceil((data.length + 9) / 64) * 64);\n padded.set(data);\n padded[data.length] = 0x80;\n const pv = new DataView(padded.buffer);\n pv.setUint32(padded.length - 8, Math.floor(bitLen / 0x100000000));\n pv.setUint32(padded.length - 4, bitLen >>> 0);\n const h = new Uint32Array([0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19]);\n const w = new Uint32Array(64);\n const rotr = (x: number, n: number): number => (x >>> n) | (x << (32 - n));\n for (let off = 0; off < padded.length; off += 64) {\n for (let i = 0; i < 16; i++) w[i] = pv.getUint32(off + i * 4);\n for (let i = 16; i < 64; i++) {\n const s0 = rotr(w[i - 15]!, 7) ^ rotr(w[i - 15]!, 18) ^ (w[i - 15]! >>> 3);\n const s1 = rotr(w[i - 2]!, 17) ^ rotr(w[i - 2]!, 19) ^ (w[i - 2]! >>> 10);\n w[i] = (w[i - 16]! + s0 + w[i - 7]! + s1) | 0;\n }\n let [a, b, c, d, e, f, g, hh] = [h[0]!, h[1]!, h[2]!, h[3]!, h[4]!, h[5]!, h[6]!, h[7]!];\n for (let i = 0; i < 64; i++) {\n const t1 = (hh + (rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25)) + ((e & f) ^ (~e & g)) + K256[i]! + w[i]!) | 0;\n const t2 = ((rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22)) + ((a & b) ^ (a & c) ^ (b & c))) | 0;\n hh = g; g = f; f = e; e = (d + t1) | 0; d = c; c = b; b = a; a = (t1 + t2) | 0;\n }\n h[0] = (h[0]! + a) | 0; h[1] = (h[1]! + b) | 0; h[2] = (h[2]! + c) | 0; h[3] = (h[3]! + d) | 0;\n h[4] = (h[4]! + e) | 0; h[5] = (h[5]! + f) | 0; h[6] = (h[6]! + g) | 0; h[7] = (h[7]! + hh) | 0;\n }\n const out = new Uint8Array(32);\n const ov = new DataView(out.buffer);\n h.forEach((v, i) => ov.setUint32(i * 4, v));\n return out;\n}\n\nfunction hmacSha256Fallback(key: Uint8Array, msg: Uint8Array): Uint8Array {\n const k = new Uint8Array(64);\n k.set(key.length > 64 ? sha256Fallback(key) : key);\n const inner = new Uint8Array(64 + msg.length);\n const outer = new Uint8Array(64 + 32);\n for (let i = 0; i < 64; i++) {\n inner[i] = k[i]! ^ 0x36;\n outer[i] = k[i]! ^ 0x5c;\n }\n inner.set(msg, 64);\n outer.set(sha256Fallback(inner), 64);\n return sha256Fallback(outer);\n}\n\n/** HMAC-SHA256 as hex — Web Crypto when present, else the pure-JS fallback. */\nasync function hmacSha256Hex(key: string, msg: string): Promise<string> {\n const enc = new TextEncoder();\n const k = enc.encode(key);\n const m = enc.encode(msg);\n const subtle = globalThis.crypto?.subtle;\n const mac = subtle\n ? new Uint8Array(await subtle.sign('HMAC', await subtle.importKey('raw', k, { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']), m))\n : hmacSha256Fallback(k, m);\n return Array.from(mac, (b) => b.toString(16).padStart(2, '0')).join('');\n}\n\n/**\n * Verified identify: the `userHash` for `identify(userId, { userHash })`.\n * Compute it on YOUR server (it needs the secret key) and hand it to the page\n * with the user id — `<AdaptiveRoot userId>` from `@sentientui/react/next`\n * does both for you. Once a project sends verified identifies, only verified\n * bindings receive server goals by `userId` and carry a user's portrait\n * across devices: an unsigned identify is any browser's claim.\n *\n * The secret is derived from the secret key, so there is nothing new to\n * configure: `HMAC(sk, 'sentient-identity-v1')`, then `v1.<exp>.` + HMAC(that,\n * `${userId}.${exp}`) — the API stores the same derivation per server key.\n * Valid for `ttlSeconds` (default 24 h, at most 7 days).\n */\nexport async function signUserId(\n userId: string,\n serverKey: string,\n opts?: { ttlSeconds?: number; now?: number },\n): Promise<string> {\n if (typeof window !== 'undefined') {\n console.error('[SentientUI] signUserId is server-only: it needs the secret key. Compute the hash on your server and pass it to identify().');\n return '';\n }\n // The expiry is signed in, so a hash read off a page stops verifying: sign\n // per render (AdaptiveRoot does), not once per user. The API refuses more\n // than 7 days.\n // Clamped to the API's 7-day maximum: a longer TTL would yield a hash that\n // is refused, i.e. an identify that silently stays unverified.\n const exp = Math.floor((opts?.now ?? Date.now()) / 1000) + Math.min(opts?.ttlSeconds ?? 86_400, 7 * 86_400);\n const secret = await hmacSha256Hex(serverKey, 'sentient-identity-v1');\n return `v1.${exp}.${await hmacSha256Hex(secret, `${userId}.${exp}`)}`;\n}\n\nconst DEFAULT_GOAL_API_BASE = 'https://api.sentient-ui.com/v1';\nconst DEFAULT_GOAL_TIMEOUT_MS = 5000;\n\nexport type TrackServerGoalOptions = {\n /** Project SECRET key (sk_...), from a server-only env var. */\n serverKey: string;\n /** The visitor's session id: `readSessionCookie(cookies, apiKey)` in the same\n * request, or the id you stored from `client.getVisitorId()`. Null/empty\n * means nobody to credit: nothing is sent. */\n sessionId?: string | null;\n /** Your own user id, as passed to `client.identify()` in the browser — use it\n * when the backend never sees our visitor id (a webhook, a job, a signup\n * handled on another host). The API credits that user's most recently seen\n * visit in the project; with no such visit nothing is recorded and this\n * resolves 'skipped_no_visitor'. Ignored when `sessionId` is given. */\n userId?: string | null;\n /** Goal name, as defined in your project (e.g. 'purchase'). */\n name: string;\n /** Your own id for this conversion (order id, Stripe event id, user id).\n * Calling again with the same session + name + dedupeKey counts once. */\n dedupeKey: string;\n value?: number;\n currency?: string;\n metadata?: Record<string, unknown>;\n /** API base including `/v1`. Defaults to the hosted API. */\n apiBaseUrl?: string;\n fetch?: typeof fetch;\n /** Give up after this many ms. Default 5000. */\n timeoutMs?: number;\n};\n\n/**\n * Records a conversion from your server (route handler, server action,\n * webhook). Never throws; resolves 'recorded', 'skipped_no_visitor' (no\n * session to credit, nothing sent) or 'failed'.\n *\n * Hand-rolling this (cookie, deterministic id, sk_ call) was the only way to\n * count a webhook-confirmed conversion, and few customers would get the dedupe\n * right: a random goal id per attempt counts a retried webhook twice. The id\n * here is derived from session + name + dedupeKey, so replays collapse\n * server-side; dedupeKey is also sent as externalId, which the API dedupes per\n * (project, goal name) on its own.\n */\nexport async function trackServerGoal(\n opts: TrackServerGoalOptions,\n): Promise<'recorded' | 'skipped_no_visitor' | 'failed'> {\n // A secret key must never leave a browser (same rule as ssrHeaders).\n if (typeof window !== 'undefined') {\n console.error('[SentientUI] trackServerGoal is server-only: the secret key was not sent. Call it from a route handler, server action or webhook.');\n return 'failed';\n }\n const userId = opts.sessionId ? null : (opts.userId || null);\n if (!opts.sessionId && !userId) return 'skipped_no_visitor';\n // The id is derived from `${sessionId}:${name}:${dedupeKey}`, so a ':' in the\n // name would let ('a:b','c') and ('a','b:c') collide on one goal id and\n // silently merge two different conversions. Goal names never need one;\n // refuse it.\n if (opts.name.includes(':')) {\n console.error('[SentientUI] trackServerGoal: goal names cannot contain \":\" (nothing was sent).');\n return 'failed';\n }\n const doFetch = opts.fetch ?? fetch;\n const controller = new AbortController();\n let timer: ReturnType<typeof setTimeout> | undefined;\n try {\n const timedOut = new Promise<never>((_, reject) => {\n timer = setTimeout(() => {\n controller.abort();\n reject(new Error('timeout'));\n }, opts.timeoutMs ?? DEFAULT_GOAL_TIMEOUT_MS);\n });\n // Started before the (async) id hash so the budget covers the whole call;\n // the no-op catch keeps an early expiry from being an unhandled rejection.\n timedOut.catch(() => undefined);\n // The session id is part of the hash because goal_events.goal_id is\n // UNIQUE across ALL projects (migration 060) and the insert is a bare ON\n // CONFLICT DO NOTHING: hashed from name + dedupeKey alone, two tenants that\n // both send ('purchase', order #1001) derived the same id, and the second\n // tenant's conversion was silently dropped while this call still returned\n // 'recorded'; anyone with a pk_ could also pre-burn a guessable order id.\n // The session id is an unguessable per-project visitor key, so the id is\n // now unique per tenant. Retry dedupe does not depend on it alone: the\n // dedupeKey also rides as externalId (unique per project + goal name).\n // A user id is NOT unguessable or unique across tenants (\"42\" exists in\n // every customer's database), so the userId path keys the hash on the\n // secret key too — per-project and never guessable, the property the\n // session id gave the hash above. Rotating the key changes the id; retry\n // dedupe still holds through externalId.\n const goalId = await uuidV5(\n userId === null\n ? `${opts.sessionId}:${opts.name}:${opts.dedupeKey}`\n : `user:${opts.serverKey}:${userId}:${opts.name}:${opts.dedupeKey}`,\n SERVER_GOAL_NAMESPACE,\n );\n // Raced as well as aborted: a fetch that ignores its signal must still\n // not hold the caller (a webhook handler) past the timeout.\n const res = await Promise.race([\n doFetch(`${(opts.apiBaseUrl ?? DEFAULT_GOAL_API_BASE).replace(/\\/+$/, '')}/goals`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${opts.serverKey}` },\n body: JSON.stringify({\n ...(userId === null ? { sessionId: opts.sessionId } : { userId }),\n name: opts.name,\n goalId,\n externalId: opts.dedupeKey,\n ...(opts.value !== undefined ? { value: opts.value } : {}),\n ...(opts.currency !== undefined ? { currency: opts.currency } : {}),\n ...(opts.metadata !== undefined ? { metadata: opts.metadata } : {}),\n }),\n signal: controller.signal,\n }),\n timedOut,\n ]);\n if (res.ok) return 'recorded';\n // 404 visitor_not_found: no visit carries that user id (never identified,\n // or erased) — nobody to credit, the same outcome as no sessionId.\n if (userId !== null && res.status === 404) {\n // The silent version of this was the whole debugging experience of a\n // missing identify: the call \"worked\" and no conversion ever appeared.\n if (process.env.NODE_ENV !== 'production') {\n console.warn(`[SentientUI] trackServerGoal: no visit is linked to userId \"${userId}\" yet, so \"${opts.name}\" was not recorded. Identify the visitor in the browser first (<AdaptiveRoot userId>, or identify(userId, { userHash })) — once a project signs its identifies, only signed visits count.`);\n }\n return 'skipped_no_visitor';\n }\n return 'failed';\n } catch {\n return 'failed';\n } finally {\n if (timer) clearTimeout(timer);\n }\n}\n","// Server-side capture of AI-assistant fetches, for any framework.\n// Spec: docs/superpowers/specs/2026-09-23-server-side-agent-capture-design.md §4.1\n//\n// Assistants that fetch a page without running JavaScript (ChatGPT-User,\n// Claude-User, Perplexity-User, GPTBot, …) never execute the snippet or the\n// React SDK, so only the server that answered can see them. Until this, only\n// Next.js AdaptiveRoot logged them; every other site read \"no AI traffic\",\n// which is wrong rather than empty.\n//\n// OBSERVATION ONLY. Nothing here may change a response based on the user\n// agent: that is cloaking, and SentientUI never claims to adapt serving to\n// agents. These functions return nothing a caller could branch on except\n// \"did this look like an agent\", and log to crawler_requests — never to\n// sessions, never to training, never to billing.\n\nimport { matchedAgentToken } from './session-meta.js';\n\nconst DEFAULT_API_BASE_URL = 'https://api.sentient-ui.com/v1';\n\nexport type AgentCaptureOptions = {\n /** Your public `pk_` key — the same one the snippet uses. */\n apiKey: string;\n /** API base ending in `/v1`. Defaults to the hosted API. */\n baseUrl?: string;\n /** Which capture path saw the fetch. Shown per row on the dashboard. */\n source?: 'middleware' | 'edge' | 'ssr';\n /**\n * REQUIRED on edge runtimes (Vercel Routing Middleware, Cloudflare Workers,\n * Netlify Edge): they cancel outstanding work once the response is\n * returned, so a fire-and-forget request without it is silently dropped.\n * Pass the platform's `waitUntil` (`ctx.waitUntil.bind(ctx)` on Workers,\n * `waitUntil` from `@vercel/functions`). Node servers do not need it.\n */\n waitUntil?: (p: Promise<unknown>) => void;\n /** Injectable for tests. */\n fetchImpl?: typeof fetch;\n};\n\n/** The minimum of a request both the Fetch API `Request` and hand-rolled\n * objects satisfy. */\nexport type CapturableRequest = {\n url: string;\n headers: { get(name: string): string | null };\n};\n\n/** Pathname only: a query string can carry tokens, emails or campaign ids. */\nfunction pathOf(url: string): string {\n try {\n return new URL(url, 'http://localhost').pathname || '/';\n } catch {\n return url.split(/[?#]/, 1)[0] || '/';\n }\n}\n\n/**\n * Low-level sender: posts one agent fetch to `/v1/crawler-events`. Never\n * throws, never blocks. The API re-derives the agent from `userAgent`\n * itself, so `botName` is advisory.\n */\nexport function postAgentFetch(\n entry: { path: string; userAgent: string; botName: string },\n opts: AgentCaptureOptions,\n): void {\n const doFetch = opts.fetchImpl ?? (typeof fetch === 'function' ? fetch : undefined);\n if (!doFetch || !opts.apiKey) return;\n try {\n const p = doFetch(`${opts.baseUrl ?? DEFAULT_API_BASE_URL}/crawler-events`, {\n method: 'POST',\n headers: { 'content-type': 'application/json', authorization: `Bearer ${opts.apiKey}` },\n body: JSON.stringify({\n path: entry.path,\n botName: entry.botName,\n userAgent: entry.userAgent,\n source: opts.source ?? 'middleware',\n }),\n }).catch(() => undefined);\n opts.waitUntil?.(p);\n } catch {\n /* capture must never break the page it is observing */\n }\n}\n\n/**\n * Log this request if its user agent is a known AI assistant or crawler.\n * Works with a Fetch API `Request` (edge runtimes, Hono, Remix / React\n * Router, Astro, SvelteKit) or anything with `url` + `headers.get`.\n *\n * Returns whether the request matched, so a caller can skip its own work;\n * it must NOT be used to serve anything different. Non-matching requests —\n * nearly all of them — make no network call.\n */\nexport function captureAgentRequest(req: CapturableRequest, opts: AgentCaptureOptions): boolean {\n let userAgent = '';\n try {\n userAgent = req.headers.get('user-agent') ?? '';\n } catch {\n return false;\n }\n const botName = matchedAgentToken(userAgent);\n if (!botName) return false;\n postAgentFetch({ path: pathOf(req.url), userAgent, botName }, opts);\n return true;\n}\n\ntype ConnectRequest = {\n url?: string;\n originalUrl?: string;\n headers: Record<string, string | string[] | undefined>;\n};\n\n/**\n * Connect-style middleware (Express, Nitro / Nuxt on Node, Fastify via\n * middie, any `(req, res, next)` stack). Calls `next()` synchronously and\n * logs in the background; it never touches the response.\n */\nexport function sentientAgentMiddleware(\n opts: Omit<AgentCaptureOptions, 'waitUntil' | 'source'>,\n): (req: ConnectRequest, res: unknown, next: (err?: unknown) => void) => void {\n return (req, _res, next) => {\n try {\n const raw = req.headers['user-agent'];\n const ua = Array.isArray(raw) ? raw[0] ?? '' : raw ?? '';\n captureAgentRequest(\n { url: req.originalUrl ?? req.url ?? '/', headers: { get: (n) => (n.toLowerCase() === 'user-agent' ? ua : null) } },\n { ...opts, source: 'middleware' },\n );\n } catch {\n /* never block the request */\n }\n next();\n };\n}\n"],"mappings":"sNA0FO,IAAMA,EAAoB,wBAGjC,SAASC,EAAWC,EAAoD,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AAO,EACT,CACA,IAAMa,EAAUC,EAAkBF,CAAS,EAC3C,OAAKC,GACLZ,EAAe,CAAE,KAAMH,GAAOa,EAAI,GAAG,EAAG,UAAAC,EAAW,QAAAC,CAAQ,EAAGV,CAAI,EAC3D,IAFc,EAGvB,CAaO,SAASY,GACdZ,EAC4E,CAC5E,MAAO,CAACQ,EAAKK,EAAMC,IAAS,CAtH9B,IAAAb,EAAAC,EAAAC,EAuHI,GAAI,CACF,IAAMY,EAAMP,EAAI,QAAQ,YAAY,EAC9BQ,EAAK,MAAM,QAAQD,CAAG,GAAId,EAAAc,EAAI,CAAC,IAAL,KAAAd,EAAU,GAAKc,GAAA,KAAAA,EAAO,GACtDR,EACE,CAAE,KAAKJ,GAAAD,EAAAM,EAAI,cAAJ,KAAAN,EAAmBM,EAAI,MAAvB,KAAAL,EAA8B,IAAK,QAAS,CAAE,IAAMc,GAAOA,EAAE,YAAY,IAAM,aAAeD,EAAK,IAAM,CAAE,EAClHE,EAAAC,EAAA,GAAKnB,GAAL,CAAW,OAAQ,YAAa,EAClC,CACF,OAAQH,EAAA,CAER,CACAiB,EAAK,CACP,CACF","names":["SERVER_KEY_HEADER","ssrHeaders","config","headers","DEFAULT_TIMEOUT_MS","fetchWithTimeout","url","init","timeoutMs","controller","timer","__spreadProps","__spreadValues","preloadAssignments","components","sessionId","preloadAssignmentsDetailed","opts","_a","sessionBody","buildSessionUpsertPayload","res","body","err","results","id","variantIds","assignments","unified","result","readSessionCookie","cookies","apiKey","_b","_c","_d","sessionCookieName","LEGACY_SESSION_COOKIE_NAME","preloadDecisions","params","_e","_f","_g","_h","_i","_j","_k","_l","declaredSlots","registryIds","fallback","baselineSlots","sessionRes","toWireSlot","data","slots","d","baselineResultFor","slotId","slotConfigOk","SERVER_GOAL_NAMESPACE","sha1Fallback","rotl","x","n","len","padded","view","h0","h1","h2","h3","h4","w","off","i","a","b","c","e","f","k","t","out","ov","v","uuidV5","name","namespace","hex","nsBytes","nameBytes","input","subtle","h","K256","sha256Fallback","bitLen","pv","rotr","s0","s1","g","hh","t1","t2","hmacSha256Fallback","key","msg","inner","outer","hmacSha256Hex","enc","m","mac","signUserId","userId","serverKey","exp","secret","DEFAULT_GOAL_API_BASE","DEFAULT_GOAL_TIMEOUT_MS","trackServerGoal","doFetch","timedOut","_","reject","goalId","DEFAULT_API_BASE_URL","pathOf","url","e","postAgentFetch","entry","opts","_a","_b","_c","_d","doFetch","p","captureAgentRequest","req","userAgent","botName","matchedAgentToken","sentientAgentMiddleware","_res","next","raw","ua","n","__spreadProps","__spreadValues"]}
|
|
1
|
+
{"version":3,"sources":["../src/server.ts","../src/agent-capture.ts"],"sourcesContent":["/**\n * Server-side helpers for SSR variant pre-loading.\n * Pure fetch — no DOM APIs. Safe in Node.js, Edge, and Deno runtimes.\n */\nimport { buildSessionUpsertPayload } from './session-meta.js';\nimport { LEGACY_SESSION_COOKIE_NAME, sessionCookieName } from './storage-key.js';\nimport {\n toWireSlot,\n baselineResultFor,\n baselineSlots,\n type SlotDeclInput,\n type SlotResult,\n} from './slots.js';\n\nimport type { SlotConfigEntry } from './snapshot.js';\nimport type { RenderCaps } from './region-skeleton.js';\nimport type { SitePalette } from './blocks.js';\n\nexport type { SlotDeclInput, SlotResult, SlotConfigEntry, SitePalette };\n\nexport type ServerAssignConfig = {\n /** Public API key (pk_...). */\n apiKey: string;\n /**\n * Base URL of the Sentient API without trailing slash.\n * e.g. 'https://api.yourapp.com/v1'\n */\n baseUrl: string;\n /**\n * Browser origin of your app (e.g. `http://localhost:3001`). Required for `pk_`\n * keys — server-side fetch must send the same `Origin` the API allows.\n */\n origin?: string;\n /**\n * Optional: this project's SECRET key (sk_...), read from a server-only env\n * var. When set, SSR calls also send it as `X-Sentient-Server-Key`, which\n * proves they come from your server: the API then holds them to your plan's\n * per-key limit instead of the 100 requests/min per-IP cap meant for\n * browsers — without it, all SSR traffic from one server address shares that\n * one cap. Never set this in code that ships to the browser; it is ignored\n * (and not sent) when `window` exists.\n */\n serverKey?: string;\n /** From `User-Agent` request header (Next.js `headers()`). */\n userAgent?: string;\n /** From `Referer` request header. */\n referer?: string;\n utmParams?: Record<string, string>;\n /**\n * Ad-platform click IDs (gclid, fbclid, ttclid, …) from the landing URL.\n * Derive both this and `utmParams` with `extractTrackedParams(searchParams)`\n * — the Referer header never carries the landing page's own query string, so\n * without these two fields SSR-minted sessions have no campaign attribution\n * until the client SDK hydrates.\n */\n clickIds?: Record<string, string>;\n /**\n * The landing page's path (no query string). With it the server can tell a\n * paid click to a product page, or a Shopify `/discount/CODE` link, from any\n * other arrival on the FIRST decision of the visit.\n */\n landingPath?: string;\n /**\n * Set true when the request carries a tracking opt-out — `DNT: 1` or\n * `Sec-GPC: 1`. When set, the SSR helpers skip the session upsert and the\n * assign/decide call entirely: the page renders defaults/baseline and no\n * session row is minted for the visitor (audit P4). The client SDK already\n * no-ops for these visitors; this keeps the server from minting a session +\n * assignment on every page view before the client can.\n */\n doNotTrack?: boolean;\n /**\n * Declared persona — the role your app already knows for this visitor\n * (e.g. from your auth context during SSR). Same contract as the client\n * option: must be a vocabulary key; unrecognized values are ignored\n * server-side. Never a user id or email.\n */\n persona?: string;\n /**\n * Milliseconds to wait for the API before returning default variants.\n * Prevents slow/cold API from blocking SSR. Defaults to 1000 — the hot path\n * is served from in-process caches and typically returns in well under\n * 150 ms. The full 1 s budget is only reached on a cold start or an API\n * geographically distant from your SSR host, after which defaults render\n * with no layout shift. Lower it if your API is co-located and warm.\n */\n timeoutMs?: number;\n};\n\n/** Header carrying `serverKey` (apps/api lib/rate-limit.ts SERVER_KEY_HEADER). */\nexport const SERVER_KEY_HEADER = 'X-Sentient-Server-Key';\n\n/** Auth headers for an SSR call: the pk_, its Origin, and the optional server proof. */\nfunction ssrHeaders(config: ServerAssignConfig): Record<string, string> {\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${config.apiKey}`,\n };\n if (config.origin) headers.Origin = config.origin;\n // A secret key must never leave a browser: if this module was bundled\n // client-side by mistake, drop it rather than send it.\n if (config.serverKey && typeof window === 'undefined') headers[SERVER_KEY_HEADER] = config.serverKey;\n return headers;\n}\n\n/** componentId → assigned variantId */\nexport type ServerAssignments = Record<string, string>;\n\ntype AssignResult = { variantId: string; assignmentTtlMs: number; unified?: true };\n\n/** `preloadAssignmentsDetailed`'s answer: the assignments, plus the ids the\n * server handed back as moved to the shared track (only when asked). */\nexport type ServerAssignmentsDetailed = { assignments: ServerAssignments; unified: string[] };\n\nconst DEFAULT_TIMEOUT_MS = 1000;\n\nfunction fetchWithTimeout(\n url: string,\n init: RequestInit,\n timeoutMs: number,\n): Promise<Response> {\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), timeoutMs);\n return fetch(url, { ...init, signal: controller.signal }).finally(() =>\n clearTimeout(timer),\n );\n}\n\n/**\n * Fetches variant assignments server-side for all listed components.\n * Returns a map suitable for passing as `initialAssignments` to `<AdaptiveProvider>`.\n *\n * Call from Next.js layout, Server Component, or getServerSideProps.\n *\n * @example\n * ```tsx\n * const assignments = await preloadAssignments(\n * [\n * { id: 'hero', variantIds: ['hero-a', 'hero-b'] },\n * { id: 'cta', variantIds: ['cta-short', 'cta-long'] },\n * ],\n * sessionId, // read from cookies() or req.cookies\n * { apiKey: process.env.NEXT_PUBLIC_SENTIENT_API_KEY!, baseUrl: 'https://api.sentient-ui.com/v1' },\n * );\n * return <AdaptiveProvider ... initialAssignments={assignments}>{children}</AdaptiveProvider>;\n * ```\n */\nexport async function preloadAssignments(\n components: Array<{ id: string; variantIds: string[] }>,\n sessionId: string,\n config: ServerAssignConfig,\n): Promise<ServerAssignments> {\n return (await preloadAssignmentsDetailed(components, sessionId, config)).assignments;\n}\n\n/**\n * `preloadAssignments`, and also which components were moved onto the shared\n * track. With `opts.unified` each assign says the page can follow such a move:\n * a moved id is then not assigned (nothing is recorded for it) and comes back\n * in `unified`, for the page to render as a slot. Pass those ids to\n * `<AdaptiveProvider initialUnified>`. Without it a moved id is served its\n * frozen result read-only, as for any older SDK.\n */\nexport async function preloadAssignmentsDetailed(\n components: Array<{ id: string; variantIds: string[] }>,\n sessionId: string,\n config: ServerAssignConfig,\n opts?: { unified?: boolean },\n): Promise<ServerAssignmentsDetailed> {\n // Opted-out visitor (DNT/GPC): render defaults, mint no session (audit P4).\n if (config.doNotTrack) return { assignments: {}, unified: [] };\n\n const timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n const headers = ssrHeaders(config);\n\n // Session metadata must match the browser SDK so assign seeds variant_weights\n // under the same segment (not `unknown:unknown`).\n const sessionBody = {\n ...buildSessionUpsertPayload(sessionId, {\n userAgent: config.userAgent,\n referer: config.referer,\n utmParams: config.utmParams,\n clickIds: config.clickIds,\n appOrigin: config.origin,\n landingPath: config.landingPath,\n }),\n ...(config.persona ? { persona: config.persona } : {}),\n };\n\n try {\n const res = await fetchWithTimeout(\n `${config.baseUrl}/sessions`,\n { method: 'POST', headers, body: JSON.stringify(sessionBody) },\n timeoutMs,\n );\n if (res.status === 402) {\n console.warn(\n '[SentientUI] Session limit exceeded for this project. The bandit will stop learning until the limit resets. Upgrade at sentient-ui.com/pricing',\n );\n } else if (!res.ok) {\n const body = await res.json().catch(() => ({}));\n console.error(`[SentientUI] preloadAssignments: session upsert failed (${res.status})`, body);\n }\n } catch (err) {\n console.error('[SentientUI] preloadAssignments: session upsert threw', err);\n }\n\n const results = await Promise.allSettled(\n components.map(async ({ id, variantIds }) => {\n const res = await fetchWithTimeout(\n `${config.baseUrl}/assign`,\n {\n method: 'POST',\n headers,\n body: JSON.stringify({ sessionId, componentId: id, variantIds, ...(opts?.unified ? { caps: { unified: true } } : {}) }),\n },\n timeoutMs,\n );\n if (!res.ok) {\n const body = await res.json().catch(() => ({}));\n console.error(`[SentientUI] preloadAssignments: assign failed for \"${id}\" (${res.status})`, body);\n return null;\n }\n const body = (await res.json()) as AssignResult;\n return { id, variantId: body.variantId, unified: opts?.unified === true && body.unified === true };\n }),\n );\n\n const assignments: ServerAssignments = {};\n const unified: string[] = [];\n for (const result of results) {\n if (result.status === 'fulfilled' && result.value) {\n // A moved id's variantId is only its declared baseline, not an\n // assignment: seeding it would settle the page on the frozen run.\n if (result.value.unified) unified.push(result.value.id);\n else assignments[result.value.id] = result.value.variantId;\n }\n }\n return { assignments, unified };\n}\n\n/**\n * Reads the Sentient session cookie from a Next.js `ReadonlyRequestCookies` object\n * (the return value of `cookies()` from `next/headers`), or any object with a\n * `get(name: string)` method. Returns null if the cookie is absent.\n *\n * Pass the project's `apiKey`: the client writes the per-project SUFFIXED name\n * (`sessionCookieName` — see storage-key.ts), so reading only the bare\n * `_snt_uid` missed the cookie on every SSR request for a returning visitor and\n * minted a fresh orphan session each page view (quota inflation, broken sticky\n * assignments and persona continuity). The bare name is still read as a\n * fallback for identities minted before namespacing.\n */\nexport function readSessionCookie(\n cookies: { get(name: string): { value: string } | undefined },\n apiKey?: string,\n): string | null {\n return (\n (apiKey ? cookies.get(sessionCookieName(apiKey))?.value : undefined) ??\n cookies.get(LEGACY_SESSION_COOKIE_NAME)?.value ??\n null\n );\n}\n\nexport type DecideResult = {\n layoutOrder: string[];\n assignments: Record<string, string>;\n /** Slot results keyed by slot id. Baseline-resolved when the API omits/fails them. */\n slots: Record<string, SlotResult>;\n persona: string;\n confidence: number;\n /** Registry mode only: content/ops/blocks for server-defined slots. */\n slotConfig?: Record<string, SlotConfigEntry>;\n /** Registry mode only: site palette for block rendering. */\n palette?: SitePalette;\n /** Registry mode only: site styles the served Redesign arms borrow. */\n vocabulary?: import('./style-vocabulary.js').StyleVocabulary;\n /** The visit's funnel stage, raw — projects with stages on, treated visitors\n * only. Pass it through `exposedStage` before it reaches the page. */\n stage?: string;\n /** The visit's serving context. Never for the page. */\n context?: string;\n /** Requested components moved onto the shared track (only with\n * `unifiedCaps`): not in `assignments`; render each as a slot. */\n unified?: string[];\n};\n\n/**\n * Single-roundtrip SSR call returning layout order, component assignments,\n * and adaptive-slot results. Falls back to default section order + empty\n * assignments + baseline slots if the API is unavailable. A response without\n * a `slots` field means the server predates slots — every declared slot\n * resolves to its baseline (no retry).\n */\nexport async function preloadDecisions(\n params: {\n sections?: string[];\n components: Array<{ id: string; variantIds?: string[] }>;\n slots?: SlotDeclInput[];\n /** 'registry' serves the project's published slot_definitions as if declared\n * (and is the only way slotConfig/palette come back). Default 'request'.\n * Requires `registrySlotIds`: the `<Adaptive id>`s THIS page renders. */\n slotsFrom?: 'request' | 'registry';\n /**\n * Registry mode: decide only these published slot ids. Close-out turns\n * every slot decision into a trial without checking an exposure, so an\n * unscoped registry decide accrues trials — and session-level credit — for\n * every published slot on every page, including ones this page never\n * renders (CONTRACTS §2). Omitting it in registry mode is refused: the\n * call downgrades to request mode with one console.error, rather than\n * silently minting those trials.\n */\n registrySlotIds?: string[];\n /**\n * Registry mode: what each slot on this page can render (CONTRACTS §2).\n * The server has no DOM here, so no fingerprint is sent and a Rewrite arm\n * is assumed to match; a real mismatch is reported from the browser as\n * drift. Declare `forms: false` for slots without an `onFormSubmit`, or a\n * form arm can be drawn that this page will refuse. Default per slot:\n * `{ forms: true, compose: true, ops: false }`.\n */\n renderCaps?: Record<string, Omit<RenderCaps, 'fp'>>;\n /** The page renders a moved (unified) component on the shared track: such\n * ids in `components` come back in `unified` instead of `assignments`,\n * with nothing recorded. Without it they are served the frozen result. */\n unifiedCaps?: boolean;\n },\n sessionId: string,\n config: ServerAssignConfig,\n): Promise<DecideResult> {\n const timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n const declaredSlots = params.slots ?? [];\n let registryIds: string[] | null = null;\n if (params.slotsFrom === 'registry') {\n if (Array.isArray(params.registrySlotIds)) {\n registryIds = params.registrySlotIds;\n } else {\n console.error(\n \"[SentientUI] preloadDecisions: slotsFrom: 'registry' needs registrySlotIds (the <Adaptive id>s this page renders). \" +\n 'An unscoped registry decide records a trial for every published slot on every page; falling back to request mode.',\n );\n }\n }\n const fallback: DecideResult = {\n layoutOrder: params.sections ?? [],\n assignments: {},\n slots: baselineSlots(declaredSlots),\n persona: 'unknown',\n confidence: 0,\n };\n\n // Opted-out visitor (DNT/GPC): baseline layout/slots, mint no session (audit P4).\n if (config.doNotTrack) return fallback;\n\n const headers = ssrHeaders(config);\n\n const sessionBody = {\n ...buildSessionUpsertPayload(sessionId, {\n userAgent: config.userAgent,\n referer: config.referer,\n utmParams: config.utmParams,\n clickIds: config.clickIds,\n appOrigin: config.origin,\n landingPath: config.landingPath,\n }),\n ...(config.persona ? { persona: config.persona } : {}),\n };\n\n try {\n const sessionRes = await fetchWithTimeout(\n `${config.baseUrl}/sessions`,\n { method: 'POST', headers, body: JSON.stringify(sessionBody) },\n timeoutMs,\n );\n if (!sessionRes.ok) {\n const body = await sessionRes.json().catch(() => ({}));\n console.error(`[SentientUI] preloadDecisions: session upsert failed (${sessionRes.status})`, body);\n }\n } catch (err) {\n console.error('[SentientUI] preloadDecisions: session upsert threw', err);\n }\n\n try {\n const res = await fetchWithTimeout(\n `${config.baseUrl}/decide`,\n {\n method: 'POST',\n headers,\n body: JSON.stringify({\n sessionId,\n sections: (params.sections ?? []).map((id) => ({ id })),\n components: params.components,\n ...(declaredSlots.length > 0 ? { slots: declaredSlots.map(toWireSlot) } : {}),\n // bootstrap:false — editor goals and the section map are snippet\n // data the React SDK never reads. An EMPTY id list is meaningful\n // (\"nothing published is on this page\"): zero trials, still a decide.\n ...(registryIds !== null\n ? {\n slotsFrom: 'registry',\n registrySlotIds: registryIds,\n bootstrap: false,\n // Always sent, so the server knows this is an SDK that can\n // render Rewrite arms — no `render` field means legacy.\n render: Object.fromEntries(\n // compose: true — the React SDK (the SSR consumer) renders\n // Redesign trees since native generation phase 2.\n // ops: false — nothing here applies `ops`. Without it an\n // SSR'd <Adaptive id> matching a script-tag component was drawn\n // its ops-only version, rendered the original, and booked a trial.\n registryIds.map((id) => [id, params.renderCaps?.[id] ?? { forms: true, compose: true, ops: false }]),\n ),\n }\n : {}),\n ...(config.persona ? { persona: config.persona } : {}),\n ...(params.unifiedCaps ? { caps: { unified: true } } : {}),\n }),\n },\n timeoutMs,\n );\n if (!res.ok) {\n const body = await res.json().catch(() => ({}));\n console.error(`[SentientUI] preloadDecisions: decide failed (${res.status})`, body);\n return fallback;\n }\n const data = (await res.json()) as {\n layoutOrder?: string[];\n assignments?: Record<string, string>;\n slots?: Record<string, SlotResult>;\n slotConfig?: Record<string, SlotConfigEntry>;\n palette?: SitePalette;\n vocabulary?: import('./style-vocabulary.js').StyleVocabulary;\n persona?: string;\n confidence?: number;\n stage?: unknown;\n context?: unknown;\n unified?: unknown;\n };\n\n const slots: Record<string, SlotResult> = {};\n for (const d of declaredSlots) {\n // `data.slots === undefined` ⇒ server predates slots: baseline, no retry.\n slots[d.id] = data.slots?.[d.id] ?? baselineResultFor(d);\n }\n // Registry mode returns slots the request never declared — union them in\n // (same rule as the browser client), or an SSR page gets results for none\n // of its registry slots.\n for (const [slotId, result] of Object.entries(data.slots ?? {})) {\n if (!(slotId in slots)) slots[slotId] = result;\n }\n\n // Plain-object guard only (readSnapshot's rule): the server total-validated\n // the config at publish; a deep re-validation here would just drift.\n const slotConfigOk =\n data.slotConfig !== undefined && typeof data.slotConfig === 'object' && data.slotConfig !== null && !Array.isArray(data.slotConfig);\n\n return {\n layoutOrder: data.layoutOrder ?? params.sections ?? [],\n assignments: data.assignments ?? {},\n slots,\n persona: data.persona ?? 'unknown',\n confidence: data.confidence ?? 0,\n ...(slotConfigOk ? { slotConfig: data.slotConfig } : {}),\n ...(data.palette ? { palette: data.palette } : {}),\n ...(data.vocabulary ? { vocabulary: data.vocabulary } : {}),\n ...(typeof data.stage === 'string' ? { stage: data.stage } : {}),\n ...(typeof data.context === 'string' ? { context: data.context } : {}),\n ...(params.unifiedCaps && Array.isArray(data.unified)\n ? { unified: data.unified.filter((id): id is string => typeof id === 'string') }\n : {}),\n };\n } catch (err) {\n console.error('[SentientUI] preloadDecisions: decide threw', err);\n return fallback;\n }\n}\n\n/**\n * Fixed namespace for server-goal ids. It is public (it ships in this file), so\n * it adds no secrecy: the id's uniqueness comes from the session id it hashes\n * (see trackServerGoal). Never change it: a retried delivery must map to the\n * same goal id.\n */\nexport const SERVER_GOAL_NAMESPACE = '3d8f5a21-7c64-4b19-8e0a-5f2c91d7b6e3';\n\n/**\n * Pure-JS SHA-1 (FIPS 180-4) for runtimes without Web Crypto: Node 18 (our\n * engines floor is 18.18) has no unflagged `globalThis.crypto`, and without\n * this every server goal there would end 'failed'. @internal: exported for\n * the test vector only; not re-exported from the entry.\n */\nexport function sha1Fallback(data: Uint8Array): Uint8Array {\n const rotl = (x: number, n: number): number => (x << n) | (x >>> (32 - n));\n const len = data.length;\n const padded = new Uint8Array(((len + 8) >> 6) * 64 + 64);\n padded.set(data);\n padded[len] = 0x80;\n const view = new DataView(padded.buffer);\n view.setUint32(padded.length - 8, Math.floor((len * 8) / 0x100000000));\n view.setUint32(padded.length - 4, (len * 8) >>> 0);\n let h0 = 0x67452301, h1 = 0xefcdab89, h2 = 0x98badcfe, h3 = 0x10325476, h4 = 0xc3d2e1f0;\n const w = new Array<number>(80);\n for (let off = 0; off < padded.length; off += 64) {\n for (let i = 0; i < 16; i++) w[i] = view.getUint32(off + i * 4);\n for (let i = 16; i < 80; i++) w[i] = rotl(w[i - 3]! ^ w[i - 8]! ^ w[i - 14]! ^ w[i - 16]!, 1);\n let a = h0, b = h1, c = h2, d = h3, e = h4;\n for (let i = 0; i < 80; i++) {\n const [f, k] =\n i < 20 ? [(b & c) | (~b & d), 0x5a827999]\n : i < 40 ? [b ^ c ^ d, 0x6ed9eba1]\n : i < 60 ? [(b & c) | (b & d) | (c & d), 0x8f1bbcdc]\n : [b ^ c ^ d, 0xca62c1d6];\n const t = (rotl(a, 5) + f! + e + k! + w[i]!) | 0;\n e = d; d = c; c = rotl(b, 30); b = a; a = t;\n }\n h0 = (h0 + a) | 0; h1 = (h1 + b) | 0; h2 = (h2 + c) | 0; h3 = (h3 + d) | 0; h4 = (h4 + e) | 0;\n }\n const out = new Uint8Array(20);\n const ov = new DataView(out.buffer);\n [h0, h1, h2, h3, h4].forEach((v, i) => ov.setUint32(i * 4, v >>> 0));\n return out;\n}\n\n/**\n * RFC-4122 v5 UUID (SHA-1 over namespace bytes + name), via Web Crypto so this\n * file stays free of `node:` imports and `Buffer` (it also hosts the SSR\n * helpers, which run on Edge and Deno). @internal: exported for the test vector.\n */\nexport async function uuidV5(name: string, namespace: string): Promise<string> {\n const hex = namespace.replace(/-/g, '');\n const nsBytes = new Uint8Array(16);\n for (let i = 0; i < 16; i++) nsBytes[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);\n const nameBytes = new TextEncoder().encode(name);\n const input = new Uint8Array(16 + nameBytes.length);\n input.set(nsBytes, 0);\n input.set(nameBytes, 16);\n const subtle = globalThis.crypto?.subtle;\n const h = (subtle ? new Uint8Array(await subtle.digest('SHA-1', input)) : sha1Fallback(input)).slice(0, 16);\n h[6] = (h[6]! & 0x0f) | 0x50;\n h[8] = (h[8]! & 0x3f) | 0x80;\n const x = Array.from(h, (b) => b.toString(16).padStart(2, '0')).join('');\n return `${x.slice(0, 8)}-${x.slice(8, 12)}-${x.slice(12, 16)}-${x.slice(16, 20)}-${x.slice(20, 32)}`;\n}\n\n// Pure-JS SHA-256 for the same Node-18 gap sha1Fallback covers (no global\n// Web Crypto there, and this file takes no `node:` imports). @internal.\nconst K256 = new Uint32Array([\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,\n]);\nexport function sha256Fallback(data: Uint8Array): Uint8Array {\n const bitLen = data.length * 8;\n const padded = new Uint8Array(Math.ceil((data.length + 9) / 64) * 64);\n padded.set(data);\n padded[data.length] = 0x80;\n const pv = new DataView(padded.buffer);\n pv.setUint32(padded.length - 8, Math.floor(bitLen / 0x100000000));\n pv.setUint32(padded.length - 4, bitLen >>> 0);\n const h = new Uint32Array([0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19]);\n const w = new Uint32Array(64);\n const rotr = (x: number, n: number): number => (x >>> n) | (x << (32 - n));\n for (let off = 0; off < padded.length; off += 64) {\n for (let i = 0; i < 16; i++) w[i] = pv.getUint32(off + i * 4);\n for (let i = 16; i < 64; i++) {\n const s0 = rotr(w[i - 15]!, 7) ^ rotr(w[i - 15]!, 18) ^ (w[i - 15]! >>> 3);\n const s1 = rotr(w[i - 2]!, 17) ^ rotr(w[i - 2]!, 19) ^ (w[i - 2]! >>> 10);\n w[i] = (w[i - 16]! + s0 + w[i - 7]! + s1) | 0;\n }\n let [a, b, c, d, e, f, g, hh] = [h[0]!, h[1]!, h[2]!, h[3]!, h[4]!, h[5]!, h[6]!, h[7]!];\n for (let i = 0; i < 64; i++) {\n const t1 = (hh + (rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25)) + ((e & f) ^ (~e & g)) + K256[i]! + w[i]!) | 0;\n const t2 = ((rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22)) + ((a & b) ^ (a & c) ^ (b & c))) | 0;\n hh = g; g = f; f = e; e = (d + t1) | 0; d = c; c = b; b = a; a = (t1 + t2) | 0;\n }\n h[0] = (h[0]! + a) | 0; h[1] = (h[1]! + b) | 0; h[2] = (h[2]! + c) | 0; h[3] = (h[3]! + d) | 0;\n h[4] = (h[4]! + e) | 0; h[5] = (h[5]! + f) | 0; h[6] = (h[6]! + g) | 0; h[7] = (h[7]! + hh) | 0;\n }\n const out = new Uint8Array(32);\n const ov = new DataView(out.buffer);\n h.forEach((v, i) => ov.setUint32(i * 4, v));\n return out;\n}\n\nfunction hmacSha256Fallback(key: Uint8Array, msg: Uint8Array): Uint8Array {\n const k = new Uint8Array(64);\n k.set(key.length > 64 ? sha256Fallback(key) : key);\n const inner = new Uint8Array(64 + msg.length);\n const outer = new Uint8Array(64 + 32);\n for (let i = 0; i < 64; i++) {\n inner[i] = k[i]! ^ 0x36;\n outer[i] = k[i]! ^ 0x5c;\n }\n inner.set(msg, 64);\n outer.set(sha256Fallback(inner), 64);\n return sha256Fallback(outer);\n}\n\n/** HMAC-SHA256 as hex — Web Crypto when present, else the pure-JS fallback. */\nasync function hmacSha256Hex(key: string, msg: string): Promise<string> {\n const enc = new TextEncoder();\n const k = enc.encode(key);\n const m = enc.encode(msg);\n const subtle = globalThis.crypto?.subtle;\n const mac = subtle\n ? new Uint8Array(await subtle.sign('HMAC', await subtle.importKey('raw', k, { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']), m))\n : hmacSha256Fallback(k, m);\n return Array.from(mac, (b) => b.toString(16).padStart(2, '0')).join('');\n}\n\n/**\n * Verified identify: the `userHash` for `identify(userId, { userHash })`.\n * Compute it on YOUR server (it needs the secret key) and hand it to the page\n * with the user id — `<AdaptiveRoot userId>` from `@sentientui/react/next`\n * does both for you. Once a project sends verified identifies, only verified\n * bindings receive server goals by `userId` and carry a user's portrait\n * across devices: an unsigned identify is any browser's claim.\n *\n * The secret is derived from the secret key, so there is nothing new to\n * configure: `HMAC(sk, 'sentient-identity-v1')`, then `v1.<exp>.` + HMAC(that,\n * `${userId}.${exp}`) — the API stores the same derivation per server key.\n * Valid for `ttlSeconds` (default 24 h, at most 7 days).\n */\nexport async function signUserId(\n userId: string,\n serverKey: string,\n opts?: { ttlSeconds?: number; now?: number },\n): Promise<string> {\n if (typeof window !== 'undefined') {\n console.error('[SentientUI] signUserId is server-only: it needs the secret key. Compute the hash on your server and pass it to identify().');\n return '';\n }\n // The expiry is signed in, so a hash read off a page stops verifying: sign\n // per render (AdaptiveRoot does), not once per user. The API refuses more\n // than 7 days.\n // Clamped to the API's 7-day maximum: a longer TTL would yield a hash that\n // is refused, i.e. an identify that silently stays unverified.\n const exp = Math.floor((opts?.now ?? Date.now()) / 1000) + Math.min(opts?.ttlSeconds ?? 86_400, 7 * 86_400);\n const secret = await hmacSha256Hex(serverKey, 'sentient-identity-v1');\n return `v1.${exp}.${await hmacSha256Hex(secret, `${userId}.${exp}`)}`;\n}\n\nconst DEFAULT_GOAL_API_BASE = 'https://api.sentient-ui.com/v1';\nconst DEFAULT_GOAL_TIMEOUT_MS = 5000;\n\nexport type TrackServerGoalOptions = {\n /** Project SECRET key (sk_...), from a server-only env var. */\n serverKey: string;\n /** The visitor's session id: `readSessionCookie(cookies, apiKey)` in the same\n * request, or the id you stored from `client.getVisitorId()`. Null/empty\n * means nobody to credit: nothing is sent. */\n sessionId?: string | null;\n /** Your own user id, as passed to `client.identify()` in the browser — use it\n * when the backend never sees our visitor id (a webhook, a job, a signup\n * handled on another host). The API credits that user's most recently seen\n * visit in the project; with no such visit nothing is recorded and this\n * resolves 'skipped_no_visitor'. Ignored when `sessionId` is given. */\n userId?: string | null;\n /** Goal name, as defined in your project (e.g. 'purchase'). */\n name: string;\n /** Your own id for this conversion (order id, Stripe event id, user id).\n * Calling again with the same session + name + dedupeKey counts once. */\n dedupeKey: string;\n value?: number;\n currency?: string;\n metadata?: Record<string, unknown>;\n /** API base including `/v1`. Defaults to the hosted API. */\n apiBaseUrl?: string;\n fetch?: typeof fetch;\n /** Give up after this many ms. Default 5000. */\n timeoutMs?: number;\n};\n\n/**\n * Records a conversion from your server (route handler, server action,\n * webhook). Never throws; resolves 'recorded', 'skipped_no_visitor' (no\n * session to credit, nothing sent) or 'failed'.\n *\n * Hand-rolling this (cookie, deterministic id, sk_ call) was the only way to\n * count a webhook-confirmed conversion, and few customers would get the dedupe\n * right: a random goal id per attempt counts a retried webhook twice. The id\n * here is derived from session + name + dedupeKey, so replays collapse\n * server-side; dedupeKey is also sent as externalId, which the API dedupes per\n * (project, goal name) on its own.\n */\nexport async function trackServerGoal(\n opts: TrackServerGoalOptions,\n): Promise<'recorded' | 'skipped_no_visitor' | 'failed'> {\n // A secret key must never leave a browser (same rule as ssrHeaders).\n if (typeof window !== 'undefined') {\n console.error('[SentientUI] trackServerGoal is server-only: the secret key was not sent. Call it from a route handler, server action or webhook.');\n return 'failed';\n }\n const userId = opts.sessionId ? null : (opts.userId || null);\n if (!opts.sessionId && !userId) return 'skipped_no_visitor';\n // The id is derived from `${sessionId}:${name}:${dedupeKey}`, so a ':' in the\n // name would let ('a:b','c') and ('a','b:c') collide on one goal id and\n // silently merge two different conversions. Goal names never need one;\n // refuse it.\n if (opts.name.includes(':')) {\n console.error('[SentientUI] trackServerGoal: goal names cannot contain \":\" (nothing was sent).');\n return 'failed';\n }\n const doFetch = opts.fetch ?? fetch;\n const controller = new AbortController();\n let timer: ReturnType<typeof setTimeout> | undefined;\n try {\n const timedOut = new Promise<never>((_, reject) => {\n timer = setTimeout(() => {\n controller.abort();\n reject(new Error('timeout'));\n }, opts.timeoutMs ?? DEFAULT_GOAL_TIMEOUT_MS);\n });\n // Started before the (async) id hash so the budget covers the whole call;\n // the no-op catch keeps an early expiry from being an unhandled rejection.\n timedOut.catch(() => undefined);\n // The session id is part of the hash because goal_events.goal_id is\n // UNIQUE across ALL projects (migration 060) and the insert is a bare ON\n // CONFLICT DO NOTHING: hashed from name + dedupeKey alone, two tenants that\n // both send ('purchase', order #1001) derived the same id, and the second\n // tenant's conversion was silently dropped while this call still returned\n // 'recorded'; anyone with a pk_ could also pre-burn a guessable order id.\n // The session id is an unguessable per-project visitor key, so the id is\n // now unique per tenant. Retry dedupe does not depend on it alone: the\n // dedupeKey also rides as externalId (unique per project + goal name).\n // A user id is NOT unguessable or unique across tenants (\"42\" exists in\n // every customer's database), so the userId path keys the hash on the\n // secret key too — per-project and never guessable, the property the\n // session id gave the hash above. Rotating the key changes the id; retry\n // dedupe still holds through externalId.\n const goalId = await uuidV5(\n userId === null\n ? `${opts.sessionId}:${opts.name}:${opts.dedupeKey}`\n : `user:${opts.serverKey}:${userId}:${opts.name}:${opts.dedupeKey}`,\n SERVER_GOAL_NAMESPACE,\n );\n // Raced as well as aborted: a fetch that ignores its signal must still\n // not hold the caller (a webhook handler) past the timeout.\n const res = await Promise.race([\n doFetch(`${(opts.apiBaseUrl ?? DEFAULT_GOAL_API_BASE).replace(/\\/+$/, '')}/goals`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${opts.serverKey}` },\n body: JSON.stringify({\n ...(userId === null ? { sessionId: opts.sessionId } : { userId }),\n name: opts.name,\n goalId,\n externalId: opts.dedupeKey,\n ...(opts.value !== undefined ? { value: opts.value } : {}),\n ...(opts.currency !== undefined ? { currency: opts.currency } : {}),\n ...(opts.metadata !== undefined ? { metadata: opts.metadata } : {}),\n }),\n signal: controller.signal,\n }),\n timedOut,\n ]);\n if (res.ok) return 'recorded';\n // 404 visitor_not_found: no visit carries that user id (never identified,\n // or erased) — nobody to credit, the same outcome as no sessionId.\n if (userId !== null && res.status === 404) {\n // The silent version of this was the whole debugging experience of a\n // missing identify: the call \"worked\" and no conversion ever appeared.\n if (process.env.NODE_ENV !== 'production') {\n console.warn(`[SentientUI] trackServerGoal: no visit is linked to userId \"${userId}\" yet, so \"${opts.name}\" was not recorded. Identify the visitor in the browser first (<AdaptiveRoot userId>, or identify(userId, { userHash })) — once a project signs its identifies, only signed visits count.`);\n }\n return 'skipped_no_visitor';\n }\n return 'failed';\n } catch {\n return 'failed';\n } finally {\n if (timer) clearTimeout(timer);\n }\n}\n","// Server-side capture of AI-assistant fetches, for any framework.\n// Spec: docs/superpowers/specs/2026-09-23-server-side-agent-capture-design.md §4.1\n//\n// Assistants that fetch a page without running JavaScript (ChatGPT-User,\n// Claude-User, Perplexity-User, GPTBot, …) never execute the snippet or the\n// React SDK, so only the server that answered can see them. Until this, only\n// Next.js AdaptiveRoot logged them; every other site read \"no AI traffic\",\n// which is wrong rather than empty.\n//\n// OBSERVATION ONLY. Nothing here may change a response based on the user\n// agent: that is cloaking, and SentientUI never claims to adapt serving to\n// agents. These functions return nothing a caller could branch on except\n// \"did this look like an agent\", and log to crawler_requests — never to\n// sessions, never to training, never to billing.\n\nimport { matchedAgentToken } from './session-meta.js';\n\nconst DEFAULT_API_BASE_URL = 'https://api.sentient-ui.com/v1';\n\nexport type AgentCaptureOptions = {\n /** Your public `pk_` key — the same one the snippet uses. */\n apiKey: string;\n /** API base ending in `/v1`. Defaults to the hosted API. */\n baseUrl?: string;\n /** Which capture path saw the fetch. Shown per row on the dashboard. */\n source?: 'middleware' | 'edge' | 'ssr';\n /**\n * REQUIRED on edge runtimes (Vercel Routing Middleware, Cloudflare Workers,\n * Netlify Edge): they cancel outstanding work once the response is\n * returned, so a fire-and-forget request without it is silently dropped.\n * Pass the platform's `waitUntil` (`ctx.waitUntil.bind(ctx)` on Workers,\n * `waitUntil` from `@vercel/functions`). Node servers do not need it.\n */\n waitUntil?: (p: Promise<unknown>) => void;\n /** Injectable for tests. */\n fetchImpl?: typeof fetch;\n};\n\n/** The minimum of a request both the Fetch API `Request` and hand-rolled\n * objects satisfy. */\nexport type CapturableRequest = {\n url: string;\n headers: { get(name: string): string | null };\n};\n\n/** Pathname only: a query string can carry tokens, emails or campaign ids. */\nfunction pathOf(url: string): string {\n try {\n return new URL(url, 'http://localhost').pathname || '/';\n } catch {\n return url.split(/[?#]/, 1)[0] || '/';\n }\n}\n\n/**\n * Low-level sender: posts one agent fetch to `/v1/crawler-events`. Never\n * throws, never blocks. The API re-derives the agent from `userAgent`\n * itself, so `botName` is advisory.\n */\nexport function postAgentFetch(\n entry: { path: string; userAgent: string; botName: string },\n opts: AgentCaptureOptions,\n): void {\n const doFetch = opts.fetchImpl ?? (typeof fetch === 'function' ? fetch : undefined);\n if (!doFetch || !opts.apiKey) return;\n try {\n const p = doFetch(`${opts.baseUrl ?? DEFAULT_API_BASE_URL}/crawler-events`, {\n method: 'POST',\n headers: { 'content-type': 'application/json', authorization: `Bearer ${opts.apiKey}` },\n body: JSON.stringify({\n path: entry.path,\n botName: entry.botName,\n userAgent: entry.userAgent,\n source: opts.source ?? 'middleware',\n }),\n }).catch(() => undefined);\n opts.waitUntil?.(p);\n } catch {\n /* capture must never break the page it is observing */\n }\n}\n\n/**\n * Log this request if its user agent is a known AI assistant or crawler.\n * Works with a Fetch API `Request` (edge runtimes, Hono, Remix / React\n * Router, Astro, SvelteKit) or anything with `url` + `headers.get`.\n *\n * Returns whether the request matched, so a caller can skip its own work;\n * it must NOT be used to serve anything different. Non-matching requests —\n * nearly all of them — make no network call.\n */\nexport function captureAgentRequest(req: CapturableRequest, opts: AgentCaptureOptions): boolean {\n let userAgent = '';\n try {\n userAgent = req.headers.get('user-agent') ?? '';\n } catch {\n return false;\n }\n const botName = matchedAgentToken(userAgent);\n if (!botName) return false;\n postAgentFetch({ path: pathOf(req.url), userAgent, botName }, opts);\n return true;\n}\n\ntype ConnectRequest = {\n url?: string;\n originalUrl?: string;\n headers: Record<string, string | string[] | undefined>;\n};\n\n/**\n * Connect-style middleware (Express, Nitro / Nuxt on Node, Fastify via\n * middie, any `(req, res, next)` stack). Calls `next()` synchronously and\n * logs in the background; it never touches the response.\n */\nexport function sentientAgentMiddleware(\n opts: Omit<AgentCaptureOptions, 'waitUntil' | 'source'>,\n): (req: ConnectRequest, res: unknown, next: (err?: unknown) => void) => void {\n return (req, _res, next) => {\n try {\n const raw = req.headers['user-agent'];\n const ua = Array.isArray(raw) ? raw[0] ?? '' : raw ?? '';\n captureAgentRequest(\n { url: req.originalUrl ?? req.url ?? '/', headers: { get: (n) => (n.toLowerCase() === 'user-agent' ? ua : null) } },\n { ...opts, source: 'middleware' },\n );\n } catch {\n /* never block the request */\n }\n next();\n };\n}\n"],"mappings":"qOA0FO,IAAMA,GAAoB,wBAGjC,SAASC,EAAWC,EAAoD,CACtE,IAAMC,EAAkC,CACtC,eAAgB,mBAChB,cAAe,UAAUD,EAAO,MAAM,EACxC,EACA,OAAIA,EAAO,SAAQC,EAAQ,OAASD,EAAO,QAGvCA,EAAO,WAAa,OAAO,QAAW,cAAaC,EAAQH,EAAiB,EAAIE,EAAO,WACpFC,CACT,CAWA,IAAMC,EAAqB,IAE3B,SAASC,EACPC,EACAC,EACAC,EACmB,CACnB,IAAMC,EAAa,IAAI,gBACjBC,EAAQ,WAAW,IAAMD,EAAW,MAAM,EAAGD,CAAS,EAC5D,OAAO,MAAMF,EAAKK,EAAAC,EAAA,GAAKL,GAAL,CAAW,OAAQE,EAAW,MAAO,EAAC,EAAE,QAAQ,IAChE,aAAaC,CAAK,CACpB,CACF,CAqBA,eAAsBG,GACpBC,EACAC,EACAb,EAC4B,CAC5B,OAAQ,MAAMc,EAA2BF,EAAYC,EAAWb,CAAM,GAAG,WAC3E,CAUA,eAAsBc,EACpBF,EACAC,EACAb,EACAe,EACoC,CAxKtC,IAAAC,EA0KE,GAAIhB,EAAO,WAAY,MAAO,CAAE,YAAa,CAAC,EAAG,QAAS,CAAC,CAAE,EAE7D,IAAMM,GAAYU,EAAAhB,EAAO,YAAP,KAAAgB,EAAoBd,EAChCD,EAAUF,EAAWC,CAAM,EAI3BiB,EAAcP,IAAA,GACfQ,EAA0BL,EAAW,CACtC,UAAWb,EAAO,UAClB,QAASA,EAAO,QAChB,UAAWA,EAA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H,EAAK,SAAL,KAAAG,EAAe,YACzB,CAAC,CACH,CAAC,EAAE,MAAM,IAAG,EAAY,GACxBC,EAAAJ,EAAK,YAAL,MAAAI,EAAA,KAAAJ,EAAiBM,EACnB,OAAQT,EAAA,CAER,CACF,CAWO,SAASU,EAAoBC,EAAwBR,EAAoC,CA3FhG,IAAAC,EA4FE,IAAIQ,EAAY,GAChB,GAAI,CACFA,GAAYR,EAAAO,EAAI,QAAQ,IAAI,YAAY,IAA5B,KAAAP,EAAiC,EAC/C,OAAQJ,EAAA,CACN,MAAO,EACT,CACA,IAAMa,EAAUC,EAAkBF,CAAS,EAC3C,OAAKC,GACLZ,EAAe,CAAE,KAAMH,GAAOa,EAAI,GAAG,EAAG,UAAAC,EAAW,QAAAC,CAAQ,EAAGV,CAAI,EAC3D,IAFc,EAGvB,CAaO,SAASY,GACdZ,EAC4E,CAC5E,MAAO,CAACQ,EAAKK,EAAMC,IAAS,CAtH9B,IAAAb,EAAAC,EAAAC,EAuHI,GAAI,CACF,IAAMY,EAAMP,EAAI,QAAQ,YAAY,EAC9BQ,EAAK,MAAM,QAAQD,CAAG,GAAId,EAAAc,EAAI,CAAC,IAAL,KAAAd,EAAU,GAAKc,GAAA,KAAAA,EAAO,GACtDR,EACE,CAAE,KAAKJ,GAAAD,EAAAM,EAAI,cAAJ,KAAAN,EAAmBM,EAAI,MAAvB,KAAAL,EAA8B,IAAK,QAAS,CAAE,IAAMc,GAAOA,EAAE,YAAY,IAAM,aAAeD,EAAK,IAAM,CAAE,EAClHE,EAAAC,EAAA,GAAKnB,GAAL,CAAW,OAAQ,YAAa,EAClC,CACF,OAAQH,EAAA,CAER,CACAiB,EAAK,CACP,CACF","names":["SERVER_KEY_HEADER","ssrHeaders","config","headers","DEFAULT_TIMEOUT_MS","fetchWithTimeout","url","init","timeoutMs","controller","timer","__spreadProps","__spreadValues","preloadAssignments","components","sessionId","preloadAssignmentsDetailed","opts","_a","sessionBody","buildSessionUpsertPayload","res","body","err","results","id","variantIds","assignments","unified","result","readSessionCookie","cookies","apiKey","_b","_c","_d","sessionCookieName","LEGACY_SESSION_COOKIE_NAME","preloadDecisions","params","_e","_f","_g","_h","_i","_j","_k","_l","declaredSlots","registryIds","fallback","baselineSlots","sessionRes","toWireSlot","data","slots","d","baselineResultFor","slotId","slotConfigOk","SERVER_GOAL_NAMESPACE","sha1Fallback","rotl","x","n","len","padded","view","h0","h1","h2","h3","h4","w","off","i","a","b","c","e","f","k","t","out","ov","v","uuidV5","name","namespace","hex","nsBytes","nameBytes","input","subtle","h","K256","sha256Fallback","bitLen","pv","rotr","s0","s1","g","hh","t1","t2","hmacSha256Fallback","key","msg","inner","outer","hmacSha256Hex","enc","m","mac","signUserId","userId","serverKey","exp","secret","DEFAULT_GOAL_API_BASE","DEFAULT_GOAL_TIMEOUT_MS","trackServerGoal","doFetch","timedOut","_","reject","goalId","DEFAULT_API_BASE_URL","pathOf","url","e","postAgentFetch","entry","opts","_a","_b","_c","_d","doFetch","p","captureAgentRequest","req","userAgent","botName","matchedAgentToken","sentientAgentMiddleware","_res","next","raw","ua","n","__spreadProps","__spreadValues"]}
|
package/dist/index.d.cts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
export { B as BLOCK_ALIGNS, a as BLOCK_EMPHASES, b as BLOCK_FITS, c as BLOCK_GAPS, d as BLOCK_GRID_COLUMNS, e as BLOCK_HEADING_LEVELS, f as BLOCK_JUSTIFIES, g as BLOCK_MAX_WIDTHS, h as BLOCK_PADS, i as BLOCK_RATIOS, j as BLOCK_SIZES, k as BLOCK_SURFACES, l as BLOCK_TEXT_ALIGNS, m as BLOCK_TONES, n as BLOCK_WEIGHTS, o as BadgeBlock, p as BlockAlign, q as BlockEmphasis, r as BlockFit, s as BlockGap, t as BlockJustify, u as BlockMaxWidth, v as BlockNode, w as BlockPad, x as BlockRatio, y as BlockSize, z as BlockSurface, A as BlockTextAlign, C as BlockTone, D as BlockWeight, E as ButtonBlock, F as ComposeArm, G as DividerBlock, H as FORM_FIELD_KINDS, I as FORM_INPUT_TYPES, J as FormBlock, K as FormField, L as GridBlock, M as HeadingBlock, N as ImageBlock, P as LinkBlock, Q as MAX_BLOCK_ARMS, R as MAX_BLOCK_CHILDREN, S as MAX_BLOCK_DEPTH, T as MAX_BLOCK_NODES, U as MAX_BLOCK_TEXT_LEN, V as MAX_FORM_FIELDS, W as MAX_FORM_SELECT_OPTIONS, _ as SiteImage, $ as SitePalette, a0 as SpacerBlock, a1 as StackBlock, a2 as StyleEntry, a3 as StyleRole, a4 as StyleVocabulary, a5 as TextBlock, a6 as containsFormBlock } from './style-vocabulary-Ba_g6_DD.cjs';
|
|
2
|
-
export { A as AssignOptions, a as AssignResult, b as Assignment, d as AuthoredArmReport, C as ComponentGoalOptions, e as ComponentWeightEntry, D as DecideInput, f as DecideOutcome, g as EventType, G as GoalDefinition, h as GoalOptions, j as GraphConfig, k as GraphSnapshot, L as LEGACY_SESSION_COOKIE_NAME, l as LOCAL_MODE_BANNER, M as MicroSignalEmitter, m as MicroSignalType, P as PAGE_SCOPE_RE, n as PROD_KEYLESS_ERROR, Q as QueueConfig, R as REVEAL_MS, p as RevealOptions, S as STAGE_ATTRIBUTE, q as SectionMapEntry, r as SentientClient, s as SentientConfig, t as SentientEvent, u as SessionConfig, v as SessionManager, w as SkeletonReport, x as StageAttributes, W as WeightEntry, _ as _registerConsentUpgradeInit, y as applyNonce, z as attachMicroSignalDetectors, B as cspNonce, F as exposedStage, H as forgetGeneration, I as grantConsent, J as init, K as isDoNotTrackEnabled, N as normalizeUrlPattern, O as pageScopeMatches, T as resetRevealStyles, U as reveal, V as routeKey, Y as sessionCookieName, Z as setCspNonce, $ as setStageAttribute, a0 as urlMatches } from './index-
|
|
3
|
-
export { A as AGENT_INTENTS, a as AgentIntent, C as
|
|
2
|
+
export { A as AssignOptions, a as AssignResult, b as Assignment, d as AuthoredArmReport, C as ComponentGoalOptions, e as ComponentWeightEntry, D as DecideInput, f as DecideOutcome, g as EventType, G as GoalDefinition, h as GoalOptions, j as GraphConfig, k as GraphSnapshot, L as LEGACY_SESSION_COOKIE_NAME, l as LOCAL_MODE_BANNER, M as MicroSignalEmitter, m as MicroSignalType, P as PAGE_SCOPE_RE, n as PROD_KEYLESS_ERROR, Q as QueueConfig, R as REVEAL_MS, p as RevealOptions, S as STAGE_ATTRIBUTE, q as SectionMapEntry, r as SentientClient, s as SentientConfig, t as SentientEvent, u as SessionConfig, v as SessionManager, w as SkeletonReport, x as StageAttributes, W as WeightEntry, _ as _registerConsentUpgradeInit, y as applyNonce, z as attachMicroSignalDetectors, B as cspNonce, F as exposedStage, H as forgetGeneration, I as grantConsent, J as init, K as isDoNotTrackEnabled, N as normalizeUrlPattern, O as pageScopeMatches, T as resetRevealStyles, U as reveal, V as routeKey, Y as sessionCookieName, Z as setCspNonce, $ as setStageAttribute, a0 as urlMatches } from './index-DlJDNOWu.cjs';
|
|
3
|
+
export { A as AGENT_INTENTS, a as AgentIntent, C as CLASSIC_CRAWLER_TOKENS, b as CLICK_ID_KEYS, c as CompoundLocator, D as DecisionSnapshot, S as SNAPSHOT_STORAGE_KEY_PREFIX, e as SlotConfigEntry, f as SlotDeclInput, g as SlotOps, h as agentIntent, i as agentUaList, j as armOfResult, k as baselineResultFor, l as baselineSlots, n as classifiedAgents, o as deriveSessionSegment, p as detectDeviceClass, q as detectTimeOfDay, r as detectTrafficSource, s as extractTrackedParams, t as matchedAgentToken, u as matchedCrawlerToken, v as readSnapshot, w as referrerDomainFromReferer, x as renderPrePaintScript, y as toWireSlot, z as uaTokenMatch, B as writeSnapshot } from './session-meta-BqBaLZag.cjs';
|
|
4
4
|
export { A as ArmEdits, M as MAX_SKELETON_LEAVES, a as MAX_SKELETON_NODES, b as MAX_SKELETON_TEXT, R as RegionSkeleton, c as RenderCaps, S as ServedEdits, d as SkeletonNode, e as SkeletonRole } from './region-skeleton-BRIVB-qf.cjs';
|
|
5
5
|
export { ConsentPreset, ConsentSource, ConsentWatcher, forgetVisitor } from './index-consent.cjs';
|
|
6
6
|
export { SlotResult } from '@sentientui/policy';
|
package/dist/index.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
export { B as BLOCK_ALIGNS, a as BLOCK_EMPHASES, b as BLOCK_FITS, c as BLOCK_GAPS, d as BLOCK_GRID_COLUMNS, e as BLOCK_HEADING_LEVELS, f as BLOCK_JUSTIFIES, g as BLOCK_MAX_WIDTHS, h as BLOCK_PADS, i as BLOCK_RATIOS, j as BLOCK_SIZES, k as BLOCK_SURFACES, l as BLOCK_TEXT_ALIGNS, m as BLOCK_TONES, n as BLOCK_WEIGHTS, o as BadgeBlock, p as BlockAlign, q as BlockEmphasis, r as BlockFit, s as BlockGap, t as BlockJustify, u as BlockMaxWidth, v as BlockNode, w as BlockPad, x as BlockRatio, y as BlockSize, z as BlockSurface, A as BlockTextAlign, C as BlockTone, D as BlockWeight, E as ButtonBlock, F as ComposeArm, G as DividerBlock, H as FORM_FIELD_KINDS, I as FORM_INPUT_TYPES, J as FormBlock, K as FormField, L as GridBlock, M as HeadingBlock, N as ImageBlock, P as LinkBlock, Q as MAX_BLOCK_ARMS, R as MAX_BLOCK_CHILDREN, S as MAX_BLOCK_DEPTH, T as MAX_BLOCK_NODES, U as MAX_BLOCK_TEXT_LEN, V as MAX_FORM_FIELDS, W as MAX_FORM_SELECT_OPTIONS, _ as SiteImage, $ as SitePalette, a0 as SpacerBlock, a1 as StackBlock, a2 as StyleEntry, a3 as StyleRole, a4 as StyleVocabulary, a5 as TextBlock, a6 as containsFormBlock } from './style-vocabulary-Ba_g6_DD.js';
|
|
2
|
-
export { A as AssignOptions, a as AssignResult, b as Assignment, d as AuthoredArmReport, C as ComponentGoalOptions, e as ComponentWeightEntry, D as DecideInput, f as DecideOutcome, g as EventType, G as GoalDefinition, h as GoalOptions, j as GraphConfig, k as GraphSnapshot, L as LEGACY_SESSION_COOKIE_NAME, l as LOCAL_MODE_BANNER, M as MicroSignalEmitter, m as MicroSignalType, P as PAGE_SCOPE_RE, n as PROD_KEYLESS_ERROR, Q as QueueConfig, R as REVEAL_MS, p as RevealOptions, S as STAGE_ATTRIBUTE, q as SectionMapEntry, r as SentientClient, s as SentientConfig, t as SentientEvent, u as SessionConfig, v as SessionManager, w as SkeletonReport, x as StageAttributes, W as WeightEntry, _ as _registerConsentUpgradeInit, y as applyNonce, z as attachMicroSignalDetectors, B as cspNonce, F as exposedStage, H as forgetGeneration, I as grantConsent, J as init, K as isDoNotTrackEnabled, N as normalizeUrlPattern, O as pageScopeMatches, T as resetRevealStyles, U as reveal, V as routeKey, Y as sessionCookieName, Z as setCspNonce, $ as setStageAttribute, a0 as urlMatches } from './index-
|
|
3
|
-
export { A as AGENT_INTENTS, a as AgentIntent, C as
|
|
2
|
+
export { A as AssignOptions, a as AssignResult, b as Assignment, d as AuthoredArmReport, C as ComponentGoalOptions, e as ComponentWeightEntry, D as DecideInput, f as DecideOutcome, g as EventType, G as GoalDefinition, h as GoalOptions, j as GraphConfig, k as GraphSnapshot, L as LEGACY_SESSION_COOKIE_NAME, l as LOCAL_MODE_BANNER, M as MicroSignalEmitter, m as MicroSignalType, P as PAGE_SCOPE_RE, n as PROD_KEYLESS_ERROR, Q as QueueConfig, R as REVEAL_MS, p as RevealOptions, S as STAGE_ATTRIBUTE, q as SectionMapEntry, r as SentientClient, s as SentientConfig, t as SentientEvent, u as SessionConfig, v as SessionManager, w as SkeletonReport, x as StageAttributes, W as WeightEntry, _ as _registerConsentUpgradeInit, y as applyNonce, z as attachMicroSignalDetectors, B as cspNonce, F as exposedStage, H as forgetGeneration, I as grantConsent, J as init, K as isDoNotTrackEnabled, N as normalizeUrlPattern, O as pageScopeMatches, T as resetRevealStyles, U as reveal, V as routeKey, Y as sessionCookieName, Z as setCspNonce, $ as setStageAttribute, a0 as urlMatches } from './index-C--aVpoo.js';
|
|
3
|
+
export { A as AGENT_INTENTS, a as AgentIntent, C as CLASSIC_CRAWLER_TOKENS, b as CLICK_ID_KEYS, c as CompoundLocator, D as DecisionSnapshot, S as SNAPSHOT_STORAGE_KEY_PREFIX, e as SlotConfigEntry, f as SlotDeclInput, g as SlotOps, h as agentIntent, i as agentUaList, j as armOfResult, k as baselineResultFor, l as baselineSlots, n as classifiedAgents, o as deriveSessionSegment, p as detectDeviceClass, q as detectTimeOfDay, r as detectTrafficSource, s as extractTrackedParams, t as matchedAgentToken, u as matchedCrawlerToken, v as readSnapshot, w as referrerDomainFromReferer, x as renderPrePaintScript, y as toWireSlot, z as uaTokenMatch, B as writeSnapshot } from './session-meta-D_kdNsaU.js';
|
|
4
4
|
export { A as ArmEdits, M as MAX_SKELETON_LEAVES, a as MAX_SKELETON_NODES, b as MAX_SKELETON_TEXT, R as RegionSkeleton, c as RenderCaps, S as ServedEdits, d as SkeletonNode, e as SkeletonRole } from './region-skeleton-BRIVB-qf.js';
|
|
5
5
|
export { ConsentPreset, ConsentSource, ConsentWatcher, forgetVisitor } from './index-consent.js';
|
|
6
6
|
export { SlotResult } from '@sentientui/policy';
|