@sentientui/core 0.40.0 → 0.40.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2 +1,2 @@
1
- import{a as v}from"./chunk-WKXD7KI3.mjs";import{a as _,g as O}from"./chunk-Z6ILOYBD.mjs";import{A as ze,B as He,C as Ve,D as Ye,E as We,F as Je,G as Xe,H as Qe,I as Ze,J as et,K as tt,O as se,P as M,Q as P,R as ae,T as D,d as ne,e as oe,f as re,m as Oe,n as Me,o as Pe,p as De,q as Ge,r as ke,s as $e,t as Le,u as je,v as Ue,w as Ke,x as Fe,y as Be,z as qe}from"./chunk-IUT3UXTD.mjs";import{a as B,b as q,c as z,d as H}from"./chunk-B4A22OMG.mjs";import"./chunk-EVF5PQ4U.mjs";import{g as V,h as Y,i as W,l as J,m as X,o as Q,p as Z,q as ee,r as te}from"./chunk-7RF3JRZO.mjs";import{a as R,b as w,c as A}from"./chunk-J5EL7HKC.mjs";import{a as I,b}from"./chunk-TMCGHANO.mjs";var G="_snt_graph_edges",ie={pricing:["features","faq"],features:["pricing"],faq:["pricing"],social_proof:["cta"],cta:["social_proof","hero","trust"],hero:["cta"],comparison:["pricing"],trust:["cta"]};function ce(e){var t;return(t=ie[e])!=null?t:[]}function de(e,t){try{let n=localStorage.getItem(e);return n?JSON.parse(n):t}catch(n){return t}}function pe(e,t){try{localStorage.setItem(e,JSON.stringify(t))}catch(n){}}var ue=new Set(["pricing","hero","social_proof","cta","features","faq","comparison","trust","navigation","generic"]);function le(e){return ue.has(e)?e:"generic"}function k(e){try{let t=new URL(e);return`${t.origin}${t.pathname}`}catch(t){return"/"}}function me(e,t,n){let a=`${e}:${t}:${n.join(",")}`,s=5381;for(let o=0;o<a.length;o++)s=(s<<5)+s+a.charCodeAt(o)&4294967295;return(s>>>0).toString(16).padStart(8,"0")}function $(e){let t=new Map,n=new Map,a=`_snt_graph_nodes${R(e==null?void 0:e.apiKey)}`,s=()=>{typeof window!="undefined"&&pe(a,[...t.values()])};if(typeof window!="undefined"){let o=de(a,[]);for(let i of o)t.set(i.componentId,i);try{localStorage.removeItem(G)}catch(i){}}return{addPageNode(o){t.set(o.componentId,o),s()},addStructuralEdge(o){let i=`${o.fromComponentId}->${o.toComponentId}`;n.set(i,o)},syncOnce(){var i,c;if(!(e!=null&&e.syncUrl)||typeof window=="undefined")return;let o=[...t.values()];if(o.length!==0)try{let l=new Map;for(let r of o){let d=(i=l.get(r.semanticType))!=null?i:[];d.push(r),l.set(r.semanticType,d)}let u=[],m=new Set;for(let r of o)for(let d of ce(r.semanticType)){let p=(c=l.get(d))!=null?c:[];for(let S of p){if(S.componentId===r.componentId)continue;let f=`semantic:${r.componentId}->${S.componentId}`;m.has(f)||(m.add(f),u.push({fromComponentId:r.componentId,toComponentId:S.componentId,type:"semantic",weight:.4,confidence:.9}))}}let g=new Set(o.map(r=>r.componentId));for(let r of n.values()){if(!g.has(r.fromComponentId)||!g.has(r.toComponentId))continue;let d=`structural:${r.fromComponentId}->${r.toComponentId}`;m.has(d)||(m.add(d),u.push({fromComponentId:r.fromComponentId,toComponentId:r.toComponentId,type:"structural",weight:r.weight,confidence:1}))}let h=b(I(I({pageUrl:k(window.location.href)},e.sessionId?{sessionId:e.sessionId}:{}),e.projectId?{projectId:e.projectId}:{}),{nodes:o.map(r=>{let d=le(r.semanticType);return{componentId:r.componentId,semanticType:d,answers:r.answers,contentHash:me(r.componentId,d,r.answers),prominenceScore:r.prominenceScore,depthInPage:r.depth}}),edges:u});fetch(e.syncUrl,{method:"POST",keepalive:!0,headers:I({"Content-Type":"application/json"},e.apiKey?{Authorization:`Bearer ${e.apiKey}`}:{}),body:JSON.stringify(h)}).catch(()=>{})}catch(l){}},snapshot(){return{pageNodes:[...t.values()],capturedAt:Date.now()}},destroy(){if(typeof window!="undefined")try{localStorage.removeItem(a),localStorage.removeItem(G)}catch(o){}}}}var fe=new Set(["SECTION","ARTICLE","MAIN","DIV","ASIDE"]),ge=200,he="h1, h2, h3",Se="[data-sentient-id], section[aria-label], article[aria-label], main[aria-label], aside[aria-label]",L=30,ye=1500,Ee={scan:async()=>({nodes:[],edges:[],scannedAt:0}),observe:()=>{},getProminenceScore:()=>0,destroy:()=>{}};function j(e,t,n){return n<=t?0:Math.max(0,Math.min(1,(e-t)/(n-t)))}function Ie(e){var t,n,a;try{let s=e;for(let o of Object.keys(s)){if(!o.startsWith("__reactFiber")&&!o.startsWith("__reactInternalInstance"))continue;let i=s[o],c=(a=(t=i==null?void 0:i.type)==null?void 0:t.displayName)!=null?a:(n=i==null?void 0:i.type)==null?void 0:n.name;if(c&&c.length>1)return c}}catch(s){}}function Ce(e){let t={};for(let n of Array.from(e.attributes))n.name.startsWith("data-")&&(t[n.name]=n.value);return t}var x=new Set(_);function be(e,t){let n=e.getAttribute("data-sentient-id"),a=n?t==null?void 0:t[n]:void 0;if(a&&x.has(a))return a;let s=e.getAttribute("data-sentient-type");if(s&&x.has(s))return s;let o=e.getAttribute("role");return o&&x.has(o)?o:O(e)}function Te(e){let t=5381;for(let n=0;n<e.length;n++)t=(t<<5)+t+e.charCodeAt(n)&4294967295;return(t>>>0).toString(16).padStart(8,"0")}function we(e){let t=[],n=e;for(;n;){let a=n.parentElement;if(!a){t.push(n.tagName.toLowerCase());break}let s=Array.prototype.indexOf.call(a.children,n);t.push(`${n.tagName.toLowerCase()}[${s}]`),n=a}return t.reverse().join("/")}function Ae(e){var n;let t=(n=e.getAttribute("data-sentient-id"))!=null?n:e.getAttribute("id");return t||`${e.tagName.toLowerCase()}-${Te(we(e))}`}function ve(e){let t=0,n=e.parentElement;for(;n;)t++,n=n.parentElement;return t}function N(e,t,n){var s,o,i,c;let a=e.querySelector(he);return{componentId:Ae(e),semanticType:be(e,n),ariaLabel:(s=e.getAttribute("aria-label"))!=null?s:void 0,headingText:(i=(o=a==null?void 0:a.textContent)==null?void 0:o.trim())!=null?i:void 0,isAboveFold:e.getBoundingClientRect().top<window.innerHeight,prominenceScore:t(e),depth:ve(e),reactComponentName:Ie(e),dataAttributes:Ce(e),locator:(c=v(e,e.ownerDocument))!=null?c:void 0}}function U(e){var o;let t=[],n=new Set,a="__root__",s=new Map;for(let[i,c]of e){let l=i.parentElement,u=a;for(;l;){if(e.has(l)){u=e.get(l);let g=e.get(i),h=`${u}->${g}`;!n.has(h)&&u!==g&&(n.add(h),t.push({fromComponentId:u,toComponentId:g,weight:.6}));break}l=l.parentElement}let m=(o=s.get(u))!=null?o:[];m.push(i),s.set(u,m)}for(let i of s.values()){if(i.length<2)continue;let c=i.length>L?i.slice(0,L):i;for(let l=0;l<c.length;l++)for(let u=l+1;u<c.length;u++){if(t.length>=ye)return t;let m=e.get(c[l]),g=e.get(c[u]);if(m===g)continue;let h=`${m}->${g}::sib`,r=`${g}->${m}::sib`;n.has(h)||(n.add(h),t.push({fromComponentId:m,toComponentId:g,weight:.3})),n.has(r)||(n.add(r),t.push({fromComponentId:g,toComponentId:m,weight:.3}))}}return t}function xe(e,t){let n=[],a=new Set,s=new Map;return document.querySelectorAll("[data-sentient-id]").forEach(c=>{if(c instanceof Element&&!a.has(c)){a.add(c);let l=N(c,e,t);n.push(l),s.set(c,l.componentId)}}),document.querySelectorAll("section, article, main, aside").forEach(c=>{if(!(c instanceof Element)||a.has(c))return;let l=c.hasAttribute("aria-label"),u=c.hasAttribute("data-sentient-id");if(!l&&!u)return;a.add(c);let m=N(c,e,t);n.push(m),s.set(c,m.componentId)}),{nodes:n,edges:U(s),elementToId:s}}function K(e={}){let{sectionTypes:t}=e;if(typeof window=="undefined")return Ee;let n=null,a=0,s=null,o=new Map,i=r=>{try{let d=window.getComputedStyle(r),p=parseFloat(d.fontSize)||12,S=parseFloat(d.zIndex)||0,f=r.getBoundingClientRect(),E=Math.max(f.top,0),y=window.innerHeight||1,C=1/(E/y+1),F=j(p,12,48)*.4+C*.4+j(S,0,100)*.2;return Math.max(0,Math.min(1,F))}catch(d){return .5}},c=()=>new Promise(r=>{let d=()=>{let{nodes:p,edges:S,elementToId:f}=xe(i,t);o.clear();for(let[E,y]of f)o.set(E,y);r({nodes:p,edges:S,scannedAt:Date.now()})};try{typeof requestIdleCallback=="function"?a=requestIdleCallback(d,{timeout:100}):d()}catch(p){d()}}),l=new Set,u=null,m=()=>{u=null;let r=[...l];l.clear();let d=[],p=new Set;for(let f of r){if(!f.isConnected)continue;let E=[];fe.has(f.tagName)&&(f.hasAttribute("data-sentient-id")||f.hasAttribute("aria-label"))&&E.push(f);try{f.querySelectorAll(Se).forEach(y=>E.push(y))}catch(y){}for(let y of E){if(o.has(y))continue;let C=N(y,i,t);d.push(C),p.add(C.componentId),o.set(y,C.componentId)}}if(d.length===0||!s)return;for(let f of[...o.keys()])f.isConnected||o.delete(f);let S=U(o).filter(f=>p.has(f.fromComponentId)||p.has(f.toComponentId));s({nodes:d,edges:S,addedAt:Date.now()})};return{scan:c,observe:r=>{s=r;try{n=new MutationObserver(d=>{for(let p of d)p.type==="childList"&&p.addedNodes.forEach(S=>{S instanceof Element&&l.add(S)});l.size>0&&u===null&&(u=setTimeout(m,ge))}),n.observe(document.body,{childList:!0,subtree:!0})}catch(d){}},getProminenceScore:i,destroy:()=>{if(n&&(n.disconnect(),n=null),u!==null&&clearTimeout(u),u=null,l.clear(),a&&typeof cancelIdleCallback=="function")try{cancelIdleCallback(a)}catch(r){}a=0,s=null,o.clear()}}}var Ne="https://api.sentient-ui.com/v1/events";function Re(e){var n;let t=a=>{try{let s=document.cookie.match(new RegExp(`(?:^|; )${a}=([^;]*)`));return s?decodeURIComponent(s[1]):void 0}catch(s){return}};return(n=e?t(A(e)):void 0)!=null?n:t(w)}var T=new Map;function _e(e){var r;let t=D(e),n=e.respectDoNotTrack!==!1&&P(),a=e.consent===!1||n,s=typeof e.apiKey=="string"&&e.apiKey.startsWith("pk_"),o=e.localMode===!0||!s;if(!e.graph||o||typeof window=="undefined")return t;if(a)return n||M(e.apiKey,d=>_e(d)),t;let i=T.get(e.apiKey);if(i)try{i()}catch(d){}let c=K({sectionTypes:e.sectionTypes}),l=(r=e.ingestUrl)!=null?r:Ne,u=$({syncUrl:l.replace(/\/events\/?$/,"/graph/sync"),apiKey:e.apiKey,projectId:e.apiKey,sessionId:Re(e.apiKey)});c.scan().then(d=>{for(let p of d.nodes)u.addPageNode({id:p.componentId,componentId:p.componentId,semanticType:p.semanticType,answers:e.captureDomText&&p.headingText?[p.headingText]:[],prominenceScore:p.prominenceScore,depth:p.depth});for(let p of d.edges)u.addStructuralEdge(p);u.syncOnce()});let m=null,g=()=>{m!==null&&clearTimeout(m),m=setTimeout(()=>{m=null,u.syncOnce()},500)};c.observe(d=>{for(let p of d.nodes)u.addPageNode({id:p.componentId,componentId:p.componentId,semanticType:p.semanticType,answers:e.captureDomText&&p.headingText?[p.headingText]:[],prominenceScore:p.prominenceScore,depth:p.depth});for(let p of d.edges)u.addStructuralEdge(p);g()});let h=()=>{m!==null&&(clearTimeout(m),m=null),c.destroy(),u.destroy(),T.get(e.apiKey)===h&&T.delete(e.apiKey)};return T.set(e.apiKey,h),b(I({},t),{getGraph:()=>u.snapshot(),dispose:()=>{h(),t.dispose()},destroy:()=>{h(),t.destroy()}})}export{Me as BLOCK_ALIGNS,$e as BLOCK_EMPHASES,Ue as BLOCK_FITS,Oe as BLOCK_GAPS,Ke as BLOCK_GRID_COLUMNS,Fe as BLOCK_HEADING_LEVELS,Pe as BLOCK_JUSTIFIES,ze as BLOCK_MAX_WIDTHS,qe as BLOCK_PADS,je as BLOCK_RATIOS,De as BLOCK_SIZES,Be as BLOCK_SURFACES,Le as BLOCK_TEXT_ALIGNS,ke as BLOCK_TONES,Ge as BLOCK_WEIGHTS,He as FORM_FIELD_KINDS,Ve as FORM_INPUT_TYPES,w as LEGACY_SESSION_COOKIE_NAME,Ze as MAX_BLOCK_ARMS,Qe as MAX_BLOCK_CHILDREN,Xe as MAX_BLOCK_DEPTH,Je as MAX_BLOCK_NODES,et as MAX_BLOCK_TEXT_LEN,Ye as MAX_FORM_FIELDS,We as MAX_FORM_SELECT_OPTIONS,B as SNAPSHOT_STORAGE_KEY_PREFIX,ne as STAGE_ATTRIBUTE,te as armOfResult,se as attachMicroSignalDetectors,Z as baselineResultFor,ee as baselineSlots,tt as containsFormBlock,X as deriveSessionSegment,V as detectDeviceClass,J as detectTimeOfDay,Y as detectTrafficSource,oe as exposedStage,ae as grantConsent,_e as init,P as isDoNotTrackEnabled,v as locatorFromElement,q as readSnapshot,W as referrerDomainFromReferer,H as renderPrePaintScript,k as sanitizePageUrl,A as sessionCookieName,re as setStageAttribute,Q as toWireSlot,z as writeSnapshot};
1
+ import{a as v}from"./chunk-WKXD7KI3.mjs";import{a as _,g as O}from"./chunk-Z6ILOYBD.mjs";import{A as ze,B as He,C as Ve,D as Ye,E as We,F as Je,G as Xe,H as Qe,I as Ze,J as et,K as tt,O as se,P as M,Q as P,R as ae,T as D,d as ne,e as oe,f as re,m as Oe,n as Me,o as Pe,p as De,q as Ge,r as ke,s as $e,t as Le,u as je,v as Ue,w as Ke,x as Fe,y as Be,z as qe}from"./chunk-ZTQXHKHU.mjs";import{a as B,b as q,c as z,d as H}from"./chunk-FPOHOWJP.mjs";import"./chunk-EVF5PQ4U.mjs";import{g as V,h as Y,i as W,l as J,m as X,o as Q,p as Z,q as ee,r as te}from"./chunk-NBDVEYI5.mjs";import{a as R,b as w,c as A}from"./chunk-J5EL7HKC.mjs";import{a as I,b}from"./chunk-TMCGHANO.mjs";var G="_snt_graph_edges",ie={pricing:["features","faq"],features:["pricing"],faq:["pricing"],social_proof:["cta"],cta:["social_proof","hero","trust"],hero:["cta"],comparison:["pricing"],trust:["cta"]};function ce(e){var t;return(t=ie[e])!=null?t:[]}function de(e,t){try{let n=localStorage.getItem(e);return n?JSON.parse(n):t}catch(n){return t}}function pe(e,t){try{localStorage.setItem(e,JSON.stringify(t))}catch(n){}}var ue=new Set(["pricing","hero","social_proof","cta","features","faq","comparison","trust","navigation","generic"]);function le(e){return ue.has(e)?e:"generic"}function k(e){try{let t=new URL(e);return`${t.origin}${t.pathname}`}catch(t){return"/"}}function me(e,t,n){let a=`${e}:${t}:${n.join(",")}`,s=5381;for(let o=0;o<a.length;o++)s=(s<<5)+s+a.charCodeAt(o)&4294967295;return(s>>>0).toString(16).padStart(8,"0")}function $(e){let t=new Map,n=new Map,a=`_snt_graph_nodes${R(e==null?void 0:e.apiKey)}`,s=()=>{typeof window!="undefined"&&pe(a,[...t.values()])};if(typeof window!="undefined"){let o=de(a,[]);for(let i of o)t.set(i.componentId,i);try{localStorage.removeItem(G)}catch(i){}}return{addPageNode(o){t.set(o.componentId,o),s()},addStructuralEdge(o){let i=`${o.fromComponentId}->${o.toComponentId}`;n.set(i,o)},syncOnce(){var i,c;if(!(e!=null&&e.syncUrl)||typeof window=="undefined")return;let o=[...t.values()];if(o.length!==0)try{let l=new Map;for(let r of o){let d=(i=l.get(r.semanticType))!=null?i:[];d.push(r),l.set(r.semanticType,d)}let u=[],m=new Set;for(let r of o)for(let d of ce(r.semanticType)){let p=(c=l.get(d))!=null?c:[];for(let S of p){if(S.componentId===r.componentId)continue;let f=`semantic:${r.componentId}->${S.componentId}`;m.has(f)||(m.add(f),u.push({fromComponentId:r.componentId,toComponentId:S.componentId,type:"semantic",weight:.4,confidence:.9}))}}let g=new Set(o.map(r=>r.componentId));for(let r of n.values()){if(!g.has(r.fromComponentId)||!g.has(r.toComponentId))continue;let d=`structural:${r.fromComponentId}->${r.toComponentId}`;m.has(d)||(m.add(d),u.push({fromComponentId:r.fromComponentId,toComponentId:r.toComponentId,type:"structural",weight:r.weight,confidence:1}))}let h=b(I(I({pageUrl:k(window.location.href)},e.sessionId?{sessionId:e.sessionId}:{}),e.projectId?{projectId:e.projectId}:{}),{nodes:o.map(r=>{let d=le(r.semanticType);return{componentId:r.componentId,semanticType:d,answers:r.answers,contentHash:me(r.componentId,d,r.answers),prominenceScore:r.prominenceScore,depthInPage:r.depth}}),edges:u});fetch(e.syncUrl,{method:"POST",keepalive:!0,headers:I({"Content-Type":"application/json"},e.apiKey?{Authorization:`Bearer ${e.apiKey}`}:{}),body:JSON.stringify(h)}).catch(()=>{})}catch(l){}},snapshot(){return{pageNodes:[...t.values()],capturedAt:Date.now()}},destroy(){if(typeof window!="undefined")try{localStorage.removeItem(a),localStorage.removeItem(G)}catch(o){}}}}var fe=new Set(["SECTION","ARTICLE","MAIN","DIV","ASIDE"]),ge=200,he="h1, h2, h3",Se="[data-sentient-id], section[aria-label], article[aria-label], main[aria-label], aside[aria-label]",L=30,ye=1500,Ee={scan:async()=>({nodes:[],edges:[],scannedAt:0}),observe:()=>{},getProminenceScore:()=>0,destroy:()=>{}};function j(e,t,n){return n<=t?0:Math.max(0,Math.min(1,(e-t)/(n-t)))}function Ie(e){var t,n,a;try{let s=e;for(let o of Object.keys(s)){if(!o.startsWith("__reactFiber")&&!o.startsWith("__reactInternalInstance"))continue;let i=s[o],c=(a=(t=i==null?void 0:i.type)==null?void 0:t.displayName)!=null?a:(n=i==null?void 0:i.type)==null?void 0:n.name;if(c&&c.length>1)return c}}catch(s){}}function Ce(e){let t={};for(let n of Array.from(e.attributes))n.name.startsWith("data-")&&(t[n.name]=n.value);return t}var x=new Set(_);function be(e,t){let n=e.getAttribute("data-sentient-id"),a=n?t==null?void 0:t[n]:void 0;if(a&&x.has(a))return a;let s=e.getAttribute("data-sentient-type");if(s&&x.has(s))return s;let o=e.getAttribute("role");return o&&x.has(o)?o:O(e)}function Te(e){let t=5381;for(let n=0;n<e.length;n++)t=(t<<5)+t+e.charCodeAt(n)&4294967295;return(t>>>0).toString(16).padStart(8,"0")}function we(e){let t=[],n=e;for(;n;){let a=n.parentElement;if(!a){t.push(n.tagName.toLowerCase());break}let s=Array.prototype.indexOf.call(a.children,n);t.push(`${n.tagName.toLowerCase()}[${s}]`),n=a}return t.reverse().join("/")}function Ae(e){var n;let t=(n=e.getAttribute("data-sentient-id"))!=null?n:e.getAttribute("id");return t||`${e.tagName.toLowerCase()}-${Te(we(e))}`}function ve(e){let t=0,n=e.parentElement;for(;n;)t++,n=n.parentElement;return t}function N(e,t,n){var s,o,i,c;let a=e.querySelector(he);return{componentId:Ae(e),semanticType:be(e,n),ariaLabel:(s=e.getAttribute("aria-label"))!=null?s:void 0,headingText:(i=(o=a==null?void 0:a.textContent)==null?void 0:o.trim())!=null?i:void 0,isAboveFold:e.getBoundingClientRect().top<window.innerHeight,prominenceScore:t(e),depth:ve(e),reactComponentName:Ie(e),dataAttributes:Ce(e),locator:(c=v(e,e.ownerDocument))!=null?c:void 0}}function U(e){var o;let t=[],n=new Set,a="__root__",s=new Map;for(let[i,c]of e){let l=i.parentElement,u=a;for(;l;){if(e.has(l)){u=e.get(l);let g=e.get(i),h=`${u}->${g}`;!n.has(h)&&u!==g&&(n.add(h),t.push({fromComponentId:u,toComponentId:g,weight:.6}));break}l=l.parentElement}let m=(o=s.get(u))!=null?o:[];m.push(i),s.set(u,m)}for(let i of s.values()){if(i.length<2)continue;let c=i.length>L?i.slice(0,L):i;for(let l=0;l<c.length;l++)for(let u=l+1;u<c.length;u++){if(t.length>=ye)return t;let m=e.get(c[l]),g=e.get(c[u]);if(m===g)continue;let h=`${m}->${g}::sib`,r=`${g}->${m}::sib`;n.has(h)||(n.add(h),t.push({fromComponentId:m,toComponentId:g,weight:.3})),n.has(r)||(n.add(r),t.push({fromComponentId:g,toComponentId:m,weight:.3}))}}return t}function xe(e,t){let n=[],a=new Set,s=new Map;return document.querySelectorAll("[data-sentient-id]").forEach(c=>{if(c instanceof Element&&!a.has(c)){a.add(c);let l=N(c,e,t);n.push(l),s.set(c,l.componentId)}}),document.querySelectorAll("section, article, main, aside").forEach(c=>{if(!(c instanceof Element)||a.has(c))return;let l=c.hasAttribute("aria-label"),u=c.hasAttribute("data-sentient-id");if(!l&&!u)return;a.add(c);let m=N(c,e,t);n.push(m),s.set(c,m.componentId)}),{nodes:n,edges:U(s),elementToId:s}}function K(e={}){let{sectionTypes:t}=e;if(typeof window=="undefined")return Ee;let n=null,a=0,s=null,o=new Map,i=r=>{try{let d=window.getComputedStyle(r),p=parseFloat(d.fontSize)||12,S=parseFloat(d.zIndex)||0,f=r.getBoundingClientRect(),E=Math.max(f.top,0),y=window.innerHeight||1,C=1/(E/y+1),F=j(p,12,48)*.4+C*.4+j(S,0,100)*.2;return Math.max(0,Math.min(1,F))}catch(d){return .5}},c=()=>new Promise(r=>{let d=()=>{let{nodes:p,edges:S,elementToId:f}=xe(i,t);o.clear();for(let[E,y]of f)o.set(E,y);r({nodes:p,edges:S,scannedAt:Date.now()})};try{typeof requestIdleCallback=="function"?a=requestIdleCallback(d,{timeout:100}):d()}catch(p){d()}}),l=new Set,u=null,m=()=>{u=null;let r=[...l];l.clear();let d=[],p=new Set;for(let f of r){if(!f.isConnected)continue;let E=[];fe.has(f.tagName)&&(f.hasAttribute("data-sentient-id")||f.hasAttribute("aria-label"))&&E.push(f);try{f.querySelectorAll(Se).forEach(y=>E.push(y))}catch(y){}for(let y of E){if(o.has(y))continue;let C=N(y,i,t);d.push(C),p.add(C.componentId),o.set(y,C.componentId)}}if(d.length===0||!s)return;for(let f of[...o.keys()])f.isConnected||o.delete(f);let S=U(o).filter(f=>p.has(f.fromComponentId)||p.has(f.toComponentId));s({nodes:d,edges:S,addedAt:Date.now()})};return{scan:c,observe:r=>{s=r;try{n=new MutationObserver(d=>{for(let p of d)p.type==="childList"&&p.addedNodes.forEach(S=>{S instanceof Element&&l.add(S)});l.size>0&&u===null&&(u=setTimeout(m,ge))}),n.observe(document.body,{childList:!0,subtree:!0})}catch(d){}},getProminenceScore:i,destroy:()=>{if(n&&(n.disconnect(),n=null),u!==null&&clearTimeout(u),u=null,l.clear(),a&&typeof cancelIdleCallback=="function")try{cancelIdleCallback(a)}catch(r){}a=0,s=null,o.clear()}}}var Ne="https://api.sentient-ui.com/v1/events";function Re(e){var n;let t=a=>{try{let s=document.cookie.match(new RegExp(`(?:^|; )${a}=([^;]*)`));return s?decodeURIComponent(s[1]):void 0}catch(s){return}};return(n=e?t(A(e)):void 0)!=null?n:t(w)}var T=new Map;function _e(e){var r;let t=D(e),n=e.respectDoNotTrack!==!1&&P(),a=e.consent===!1||n,s=typeof e.apiKey=="string"&&e.apiKey.startsWith("pk_"),o=e.localMode===!0||!s;if(!e.graph||o||typeof window=="undefined")return t;if(a)return n||M(e.apiKey,d=>_e(d)),t;let i=T.get(e.apiKey);if(i)try{i()}catch(d){}let c=K({sectionTypes:e.sectionTypes}),l=(r=e.ingestUrl)!=null?r:Ne,u=$({syncUrl:l.replace(/\/events\/?$/,"/graph/sync"),apiKey:e.apiKey,projectId:e.apiKey,sessionId:Re(e.apiKey)});c.scan().then(d=>{for(let p of d.nodes)u.addPageNode({id:p.componentId,componentId:p.componentId,semanticType:p.semanticType,answers:e.captureDomText&&p.headingText?[p.headingText]:[],prominenceScore:p.prominenceScore,depth:p.depth});for(let p of d.edges)u.addStructuralEdge(p);u.syncOnce()});let m=null,g=()=>{m!==null&&clearTimeout(m),m=setTimeout(()=>{m=null,u.syncOnce()},500)};c.observe(d=>{for(let p of d.nodes)u.addPageNode({id:p.componentId,componentId:p.componentId,semanticType:p.semanticType,answers:e.captureDomText&&p.headingText?[p.headingText]:[],prominenceScore:p.prominenceScore,depth:p.depth});for(let p of d.edges)u.addStructuralEdge(p);g()});let h=()=>{m!==null&&(clearTimeout(m),m=null),c.destroy(),u.destroy(),T.get(e.apiKey)===h&&T.delete(e.apiKey)};return T.set(e.apiKey,h),b(I({},t),{getGraph:()=>u.snapshot(),dispose:()=>{h(),t.dispose()},destroy:()=>{h(),t.destroy()}})}export{Me as BLOCK_ALIGNS,$e as BLOCK_EMPHASES,Ue as BLOCK_FITS,Oe as BLOCK_GAPS,Ke as BLOCK_GRID_COLUMNS,Fe as BLOCK_HEADING_LEVELS,Pe as BLOCK_JUSTIFIES,ze as BLOCK_MAX_WIDTHS,qe as BLOCK_PADS,je as BLOCK_RATIOS,De as BLOCK_SIZES,Be as BLOCK_SURFACES,Le as BLOCK_TEXT_ALIGNS,ke as BLOCK_TONES,Ge as BLOCK_WEIGHTS,He as FORM_FIELD_KINDS,Ve as FORM_INPUT_TYPES,w as LEGACY_SESSION_COOKIE_NAME,Ze as MAX_BLOCK_ARMS,Qe as MAX_BLOCK_CHILDREN,Xe as MAX_BLOCK_DEPTH,Je as MAX_BLOCK_NODES,et as MAX_BLOCK_TEXT_LEN,Ye as MAX_FORM_FIELDS,We as MAX_FORM_SELECT_OPTIONS,B as SNAPSHOT_STORAGE_KEY_PREFIX,ne as STAGE_ATTRIBUTE,te as armOfResult,se as attachMicroSignalDetectors,Z as baselineResultFor,ee as baselineSlots,tt as containsFormBlock,X as deriveSessionSegment,V as detectDeviceClass,J as detectTimeOfDay,Y as detectTrafficSource,oe as exposedStage,ae as grantConsent,_e as init,P as isDoNotTrackEnabled,v as locatorFromElement,q as readSnapshot,W as referrerDomainFromReferer,H as renderPrePaintScript,k as sanitizePageUrl,A as sessionCookieName,re as setStageAttribute,Q as toWireSlot,z as writeSnapshot};
2
2
  //# sourceMappingURL=index-graph.mjs.map
@@ -1,4 +1,4 @@
1
- import { f as DecideOutcome } from './index-CN9VJxiW.cjs';
1
+ import { f as DecideOutcome } from './index-B7s2gvyU.cjs';
2
2
  import { e as SlotDeclInput } from './session-meta-BG8w53d7.cjs';
3
3
  import './style-vocabulary-Ba_g6_DD.cjs';
4
4
  import './region-skeleton-BRIVB-qf.cjs';
@@ -1,4 +1,4 @@
1
- import { f as DecideOutcome } from './index-CROWjwsJ.js';
1
+ import { f as DecideOutcome } from './index-BgEe5mKL.js';
2
2
  import { e as SlotDeclInput } from './session-meta-D9Wx2PtC.js';
3
3
  import './style-vocabulary-Ba_g6_DD.js';
4
4
  import './region-skeleton-BRIVB-qf.js';
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index-server.ts","../src/session-meta.ts","../src/storage-key.ts","../src/slots.ts","../src/server.ts","../src/agent-capture.ts"],"sourcesContent":["/**\n * Server-only entry (`@sentientui/core/server`). SSR preload helpers that are\n * never needed in the browser — kept out of the lean client bundle.\n */\n\nexport { preloadAssignments, preloadAssignmentsDetailed, readSessionCookie, preloadDecisions, trackServerGoal, signUserId, SERVER_GOAL_NAMESPACE } from './server.js';\nexport type { TrackServerGoalOptions, ServerAssignConfig, ServerAssignments, ServerAssignmentsDetailed, DecideResult, SlotDeclInput, SlotResult } from './server.js';\n\nexport {\n deriveSessionSegment,\n buildSessionUpsertPayload,\n detectDeviceClass,\n detectTrafficSource,\n detectTimeOfDay,\n extractTrackedParams,\n CLICK_ID_KEYS,\n referrerDomainFromReferer,\n} from './session-meta.js';\nexport type { SessionUpsertPayload } from './session-meta.js';\n\n// Server-side AI-assistant capture for any framework (capture spec §4.1).\nexport { captureAgentRequest, sentientAgentMiddleware, postAgentFetch } from './agent-capture.js';\nexport type { AgentCaptureOptions, CapturableRequest } from './agent-capture.js';\n","/** Session metadata helpers (browser + Node). No DOM APIs. */\n\n/**\n * Known AI-agent / crawler user-agent tokens. Matched case-insensitively as\n * substrings. This is maintained data — bot lists move monthly. Used both to\n * flag automation on sessions (agentic browsers that leak a token) and by the\n * server middleware / agent-feed route to identify crawler HTTP reads.\n */\nexport const agentUaList: readonly string[] = [\n 'GPTBot',\n 'ChatGPT-User',\n 'OAI-SearchBot',\n 'ClaudeBot',\n 'Claude-User',\n 'Claude-SearchBot',\n 'PerplexityBot',\n 'Perplexity-User',\n 'Google-Extended',\n 'Applebot-Extended',\n 'Meta-ExternalAgent',\n 'Bytespider',\n 'CCBot',\n 'Amazonbot',\n 'cohere-ai',\n 'Diffbot',\n];\n\n/** True when the user-agent contains a known AI-agent / crawler token. */\nexport function uaTokenMatch(userAgent: string): boolean {\n return matchedAgentToken(userAgent) !== null;\n}\n\n/** The first known agent token found in the user-agent, or null. */\nexport function matchedAgentToken(userAgent: string): string | null {\n if (!userAgent) return null;\n const s = userAgent.toLowerCase();\n return agentUaList.find((token) => s.includes(token.toLowerCase())) ?? null;\n}\n\n/**\n * Purpose category for an agent fetch, inferred from its published user-agent:\n * - `user` — a person asked an assistant to read the page, live (…-User UAs)\n * - `search` — indexing for an AI answer engine (…-SearchBot / SearchBot)\n * - `training` — model-training crawl (GPTBot, ClaudeBot, CCBot, …)\n * - `other` — not clearly AI, or an unknown/new token\n */\nexport type AgentIntent = 'user' | 'search' | 'training' | 'other';\n\n/** Intent per agent token. Maintained beside `agentUaList` — when you add or\n * rename a token above, set its intent here (a unit test enforces coverage). */\nexport const AGENT_INTENTS: Record<string, AgentIntent> = {\n 'GPTBot': 'training',\n 'ChatGPT-User': 'user',\n 'OAI-SearchBot': 'search',\n 'ClaudeBot': 'training',\n 'Claude-User': 'user',\n 'Claude-SearchBot': 'search',\n 'PerplexityBot': 'search',\n 'Perplexity-User': 'user',\n 'Google-Extended': 'training',\n 'Applebot-Extended': 'training',\n 'Meta-ExternalAgent': 'training',\n 'Bytespider': 'training',\n 'CCBot': 'training',\n 'Amazonbot': 'other',\n 'cohere-ai': 'training',\n 'Diffbot': 'other',\n};\n\n/** Intent for a matched bot token (case-insensitive); `other` for null/unknown. */\nexport function agentIntent(botName: string | null): AgentIntent {\n if (!botName) return 'other';\n const hit = agentUaList.find((t) => t.toLowerCase() === botName.toLowerCase());\n return (hit && AGENT_INTENTS[hit]) || 'other';\n}\n\n/** `agentUaList` grouped by intent — the \"which crawlers do you classify?\" reference. */\nexport function classifiedAgents(): Record<AgentIntent, string[]> {\n const out: Record<AgentIntent, string[]> = { user: [], search: [], training: [], other: [] };\n for (const t of agentUaList) out[AGENT_INTENTS[t] ?? 'other'].push(t);\n return out;\n}\n\nexport function detectDeviceClass(userAgent: string): string {\n const s = userAgent.toLowerCase();\n if (/ipad|tablet|playbook|kindle|silk/.test(s)) return 'tablet';\n if (/mobi|iphone|ipod|android.*mobile|phone/.test(s)) return 'mobile';\n return 'desktop';\n}\n\nexport function detectTrafficSource(referrer: string, appOrigin?: string, siteDomain?: string | null): string {\n if (!referrer) return 'direct';\n try {\n const refUrl = new URL(referrer);\n if (appOrigin) {\n try {\n if (new URL(appOrigin).host === refUrl.host) return 'direct';\n } catch {\n /* ignore invalid appOrigin */\n }\n }\n const host = refUrl.hostname.toLowerCase();\n // Another host of the same site (the shared cookie domain): ruttl.com →\n // app.ruttl.com is a page view inside the site, scored like one.\n if (siteDomain && `.${host}`.endsWith(`.${siteDomain}`)) return 'direct';\n if (/(^|\\.)(google|bing|duckduckgo|yahoo)\\./.test(host)) return 'search';\n // Anchor to the registrable domain (exact host or a subdomain of it) so\n // hosts like `x.company.com`, `t.company.io` or `linkedinsights.com` are not\n // misclassified as social by an unbounded substring match.\n if (/(^|\\.)(twitter\\.com|x\\.com|facebook\\.com|linkedin\\.com|reddit\\.com|t\\.co)$/.test(host)) return 'social';\n return 'referral';\n } catch {\n return 'direct';\n }\n}\n\nexport function referrerDomainFromReferer(referrer: string): string | null {\n if (!referrer) return null;\n try {\n return new URL(referrer).hostname;\n } catch {\n return null;\n }\n}\n\n/**\n * Ad-platform click-ID query params worth keeping. An ALLOWLIST, unlike the\n * `utm_` prefix match: unknown query keys here are unbounded-cardinality junk\n * (session tokens, cache busters) that would bloat the sessions table, so only\n * the IDs the major ad platforms actually append survive.\n *\n * gclid / gbraid / wbraid — Google Ads auto-tagging (search, YouTube, Display;\n * gbraid/wbraid are the iOS-14 privacy variants)\n * fbclid — Meta (Facebook + Instagram). Appended to EVERY outbound Meta\n * click, paid and organic alike — it identifies the platform, never spend.\n * ttclid — TikTok Ads\n * msclkid — Microsoft Ads (Bing)\n * twclid — X/Twitter Ads\n * li_fat_id — LinkedIn Ads\n */\nexport const CLICK_ID_KEYS: readonly string[] = [\n 'gclid',\n 'gbraid',\n 'wbraid',\n 'fbclid',\n 'ttclid',\n 'msclkid',\n 'twclid',\n 'li_fat_id',\n];\n\n/**\n * Splits a URL query into the attribution params the session upsert carries:\n * every `utm_`-prefixed key, plus allowlisted ad click IDs (CLICK_ID_KEYS).\n * Accepts a raw search string (\"?a=b\" or \"a=b\"), a URLSearchParams, or a\n * Next.js `searchParams` object (whose values may be string arrays — the\n * first occurrence wins, matching URLSearchParams iteration order).\n * Node-safe: no DOM APIs.\n */\nexport function extractTrackedParams(\n search: string | URLSearchParams | Record<string, string | string[] | undefined>,\n): { utmParams: Record<string, string>; clickIds: Record<string, string> } {\n const utmParams: Record<string, string> = {};\n const clickIds: Record<string, string> = {};\n try {\n const entries: Iterable<[string, string]> =\n typeof search === 'string' || search instanceof URLSearchParams\n ? new URLSearchParams(search)\n : Object.entries(search).flatMap(([k, v]): Array<[string, string]> => {\n const first = Array.isArray(v) ? v[0] : v;\n return first === undefined ? [] : [[k, first]];\n });\n for (const [k, v] of entries) {\n // First occurrence wins for duplicates — a repeated gclid in a mangled\n // URL must not let the later value silently replace the real one.\n if (k.startsWith('utm_')) {\n if (!(k in utmParams)) utmParams[k] = v;\n } else if (CLICK_ID_KEYS.includes(k)) {\n if (!(k in clickIds)) clickIds[k] = v;\n }\n }\n } catch {\n /* malformed input → empty attribution, never a throw at init() */\n }\n return { utmParams, clickIds };\n}\n\nexport function detectTimeOfDay(d: Date): string {\n const h = d.getHours();\n if (h < 6) return 'night';\n if (h < 12) return 'morning';\n if (h < 18) return 'afternoon';\n return 'evening';\n}\n\nexport type SessionUpsertPayload = {\n sessionId: string;\n ephemeral: boolean;\n utmParams: Record<string, string>;\n /** Allowlisted ad-platform click IDs from the landing URL (CLICK_ID_KEYS). */\n clickIds: Record<string, string>;\n deviceClass: string;\n trafficSource: string;\n /** Landing page path, no query string (arrival classification). */\n landingPath?: string;\n referrerDomain: string | null;\n timeOfDay: string;\n dayOfWeek: string;\n /**\n * True when this session is likely driven by automation — either\n * `navigator.webdriver` was set, or the user-agent carried a known agent\n * token. Probabilistic: a flag for metrics + bandit exclusion, never a gate.\n */\n automation: boolean;\n};\n\n/** Bandit segment key: `<device_class>:<traffic_source>`. */\nexport function deriveSessionSegment(opts?: {\n userAgent?: string;\n referer?: string;\n appOrigin?: string;\n}): string {\n const body = buildSessionUpsertPayload('__segment__', opts);\n return `${body.deviceClass}:${body.trafficSource}`;\n}\n\n/**\n * Builds a session upsert body aligned with the browser SDK so SSR assign uses\n * the same segment key (`device:source`) as the client after hydration.\n */\nexport function buildSessionUpsertPayload(\n sessionId: string,\n opts?: {\n userAgent?: string;\n referer?: string;\n appOrigin?: string;\n utmParams?: Record<string, string>;\n clickIds?: Record<string, string>;\n now?: Date;\n /** `navigator.webdriver` value from the browser, when available. */\n webdriver?: boolean;\n /** The landing page's path (no query string), when the caller knows it. */\n landingPath?: string;\n },\n): SessionUpsertPayload {\n const ua = opts?.userAgent?.trim() ?? '';\n const referer = opts?.referer?.trim() ?? '';\n const now = opts?.now ?? new Date();\n return {\n sessionId,\n ephemeral: false,\n utmParams: opts?.utmParams ?? {},\n clickIds: opts?.clickIds ?? {},\n deviceClass: ua ? detectDeviceClass(ua) : 'desktop',\n trafficSource: referer\n ? detectTrafficSource(referer, opts?.appOrigin)\n : 'direct',\n referrerDomain: referrerDomainFromReferer(referer),\n timeOfDay: detectTimeOfDay(now),\n dayOfWeek: ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'][now.getDay()] ?? 'sun',\n automation: opts?.webdriver === true || uaTokenMatch(ua),\n ...(opts?.landingPath ? { landingPath: opts.landingPath.split(/[?#]/)[0] } : {}),\n };\n}\n","/**\n * Per-project browser-storage namespace suffix, derived from the public apiKey.\n *\n * Multiple SentientUI projects (different `pk_` keys) can run on the same exact\n * origin. Storage keyed only by name (`_snt_uid`, `_snt_asgn_*`,\n * `_snt_graph_nodes`) would then collide across projects — the visitor id in\n * particular, whose session row is keyed globally server-side, would let one\n * project's traffic land on another's session. Suffixing every browser key with\n * the apiKey prefix isolates projects, matching the queue's existing\n * `_snt_retry_${apiKey.slice(0,12)}` convention.\n *\n * Returns `''` when no apiKey is available (local mode) so keys stay stable\n * there.\n */\nexport function storageSuffix(apiKey?: string): string {\n return apiKey ? `_${apiKey.slice(0, 12)}` : '';\n}\n\n/**\n * The bare, pre-namespacing session cookie name. Still read as a FALLBACK\n * everywhere the suffixed name is read, so visitors who got their identity\n * before per-project namespacing keep it instead of being minted a fresh one.\n */\nexport const LEGACY_SESSION_COOKIE_NAME = '_snt_uid';\n\n/**\n * The one place the session cookie's name is decided. The writer (session.ts)\n * and every reader (core/server.ts SSR helper, graph sync, react devtools) must\n * call THIS — when namespacing landed, the writer moved to the suffixed name\n * while three readers kept the bare `_snt_uid`, so every SSR request for a\n * returning visitor missed the cookie and minted a fresh orphan session (quota\n * inflation, broken sticky assignments and persona continuity), and graph sync\n * sent `sessionId: undefined`. Deriving both sides from one function makes that\n * drift impossible, and index.test.ts pins the reader against the writer.\n */\nexport function sessionCookieName(apiKey?: string): string {\n return `${LEGACY_SESSION_COOKIE_NAME}${storageSuffix(apiKey)}`;\n}\n\n// Forget-me generation per project, on window so every bundle on the page\n// sees it (the snippet and its lazy chunks each carry their own copy of these\n// modules). Every client and queue captures it when created and persists only\n// while it is unchanged: a forget can never be undone by a later grant — the\n// old boolean marker was cleared by the next tracking client, and a paused\n// client's in-flight decide then wrote the forgotten visitor back (grader\n// NEW-1), as could its queues' failed final flush (F8).\nconst GENS = '__sntForgetGen';\ntype GenMap = Record<string, number>;\nconst genMap = (): GenMap | undefined => {\n try {\n return (window as unknown as Record<string, GenMap | undefined>)[GENS];\n } catch {\n return undefined;\n }\n};\nexport function markForgotten(apiKey: string): void {\n try {\n const w = window as unknown as Record<string, GenMap>;\n const m = (w[GENS] ??= {});\n m[apiKey] = (m[apiKey] ?? 0) + 1;\n } catch {\n /* no window */\n }\n}\n/** Bumped by every forget-me for this project in this page. */\nexport function forgetGeneration(apiKey: string): number {\n return genMap()?.[apiKey] ?? 0;\n}\n","/**\n * Slot declaration helpers shared by the browser client (decide) and the\n * server preload path. Pure wrappers over @sentientui/policy.\n */\nimport {\n canonicalArm,\n slotBaselineArm,\n slotResultFor,\n type SlotDecl,\n type SlotResult,\n} from '@sentientui/policy';\n\n/** SDK-facing slot declaration. `dims` accepts readonly arrays (`as const`). */\nexport type SlotDeclInput = {\n id: string;\n arms?: string[];\n dims?: Record<string, readonly string[]>;\n baseline?: string | Record<string, string>;\n};\n\nexport type { SlotResult };\n\n/**\n * Whitelists the wire fields of a slot declaration. Anything an SDK layer\n * attached (goal configs, refs, …) is stripped so it never reaches the zod\n * schema on the API. Also normalizes readonly arrays to mutable ones.\n */\nexport function toWireSlot(d: SlotDeclInput): SlotDecl {\n return {\n id: d.id,\n ...(d.arms ? { arms: [...d.arms] } : {}),\n ...(d.dims\n ? {\n dims: Object.fromEntries(\n Object.entries(d.dims).map(([dim, values]) => [dim, [...values]]),\n ),\n }\n : {}),\n ...(d.baseline !== undefined ? { baseline: d.baseline } : {}),\n };\n}\n\n/** The declared (or default first-declared) baseline result for a slot. */\nexport function baselineResultFor(d: SlotDeclInput): SlotResult {\n const decl = toWireSlot(d);\n return slotResultFor(decl, slotBaselineArm(decl));\n}\n\n/** Baseline results for a whole declaration list, keyed by slot id. */\nexport function baselineSlots(decls: SlotDeclInput[]): Record<string, SlotResult> {\n const out: Record<string, SlotResult> = {};\n for (const d of decls) out[d.id] = baselineResultFor(d);\n return out;\n}\n\n/**\n * Canonical arm string of a slot result: dims results encode as sorted\n * `dim=value` pairs joined with '|'; arms results are the arm id verbatim.\n */\nexport function armOfResult(result: SlotResult): string {\n return typeof result === 'string' ? result : canonicalArm(result);\n}\n","/**\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":"kxBAAA,IAAAA,GAAA,GAAAC,GAAAD,GAAA,mBAAAE,EAAA,0BAAAC,EAAA,8BAAAC,EAAA,wBAAAC,EAAA,yBAAAC,EAAA,sBAAAC,EAAA,oBAAAC,EAAA,wBAAAC,EAAA,yBAAAC,EAAA,mBAAAC,EAAA,uBAAAC,GAAA,+BAAAC,EAAA,qBAAAC,GAAA,sBAAAC,GAAA,8BAAAC,EAAA,4BAAAC,GAAA,eAAAC,GAAA,oBAAAC,KAAA,eAAAC,GAAApB,ICQO,IAAMqB,GAAiC,CAC5C,SACA,eACA,gBACA,YACA,cACA,mBACA,gBACA,kBACA,kBACA,oBACA,qBACA,aACA,QACA,YACA,YACA,SACF,EAGO,SAASC,GAAaC,EAA4B,CACvD,OAAOC,EAAkBD,CAAS,IAAM,IAC1C,CAGO,SAASC,EAAkBD,EAAkC,CAjCpE,IAAAE,EAkCE,GAAI,CAACF,EAAW,OAA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AAAP,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":["index_server_exports","__export","CLICK_ID_KEYS","SERVER_GOAL_NAMESPACE","buildSessionUpsertPayload","captureAgentRequest","deriveSessionSegment","detectDeviceClass","detectTimeOfDay","detectTrafficSource","extractTrackedParams","postAgentFetch","preloadAssignments","preloadAssignmentsDetailed","preloadDecisions","readSessionCookie","referrerDomainFromReferer","sentientAgentMiddleware","signUserId","trackServerGoal","__toCommonJS","agentUaList","uaTokenMatch","userAgent","matchedAgentToken","_a","s","token","detectDeviceClass","userAgent","s","detectTrafficSource","referrer","appOrigin","siteDomain","refUrl","e","host","referrerDomainFromReferer","CLICK_ID_KEYS","extractTrackedParams","search","utmParams","clickIds","entries","k","v","first","detectTimeOfDay","d","h","deriveSessionSegment","opts","body","buildSessionUpsertPayload","sessionId","_a","_b","_c","_d","_e","_f","_g","_h","ua","referer","now","__spreadValues","uaTokenMatch","storageSuffix","apiKey","LEGACY_SESSION_COOKIE_NAME","sessionCookieName","import_policy","toWireSlot","d","__spreadValues","dim","values","baselineResultFor","decl","baselineSlots","decls","out","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","n","len","padded","view","h0","h1","h2","h3","h4","w","off","i","a","c","e","f","k","t","out","ov","v","uuidV5","name","namespace","hex","nsBytes","nameBytes","input","subtle","h","x","b","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/index-server.ts","../src/session-meta.ts","../src/storage-key.ts","../src/slots.ts","../src/server.ts","../src/agent-capture.ts"],"sourcesContent":["/**\n * Server-only entry (`@sentientui/core/server`). SSR preload helpers that are\n * never needed in the browser — kept out of the lean client bundle.\n */\n\nexport { preloadAssignments, preloadAssignmentsDetailed, readSessionCookie, preloadDecisions, trackServerGoal, signUserId, SERVER_GOAL_NAMESPACE } from './server.js';\nexport type { TrackServerGoalOptions, ServerAssignConfig, ServerAssignments, ServerAssignmentsDetailed, DecideResult, SlotDeclInput, SlotResult } from './server.js';\n\nexport {\n deriveSessionSegment,\n buildSessionUpsertPayload,\n detectDeviceClass,\n detectTrafficSource,\n detectTimeOfDay,\n extractTrackedParams,\n CLICK_ID_KEYS,\n referrerDomainFromReferer,\n} from './session-meta.js';\nexport type { SessionUpsertPayload } from './session-meta.js';\n\n// Server-side AI-assistant capture for any framework (capture spec §4.1).\nexport { captureAgentRequest, sentientAgentMiddleware, postAgentFetch } from './agent-capture.js';\nexport type { AgentCaptureOptions, CapturableRequest } from './agent-capture.js';\n","/** Session metadata helpers (browser + Node). No DOM APIs. */\n\n/**\n * Known AI-agent / crawler user-agent tokens. Matched case-insensitively as\n * substrings. This is maintained data — bot lists move monthly. Used both to\n * flag automation on sessions (agentic browsers that leak a token) and by the\n * server middleware / agent-feed route to identify crawler HTTP reads.\n */\nexport const agentUaList: readonly string[] = [\n 'GPTBot',\n 'ChatGPT-User',\n 'OAI-SearchBot',\n 'ClaudeBot',\n 'Claude-User',\n 'Claude-SearchBot',\n 'PerplexityBot',\n 'Perplexity-User',\n 'Google-Extended',\n 'Applebot-Extended',\n 'Meta-ExternalAgent',\n 'Bytespider',\n 'CCBot',\n 'Amazonbot',\n 'cohere-ai',\n 'Diffbot',\n];\n\n/** True when the user-agent contains a known AI-agent / crawler token. */\nexport function uaTokenMatch(userAgent: string): boolean {\n return matchedAgentToken(userAgent) !== null;\n}\n\n/** The first known agent token found in the user-agent, or null. */\nexport function matchedAgentToken(userAgent: string): string | null {\n if (!userAgent) return null;\n const s = userAgent.toLowerCase();\n return agentUaList.find((token) => s.includes(token.toLowerCase())) ?? null;\n}\n\n/**\n * Purpose category for an agent fetch, inferred from its published user-agent:\n * - `user` — a person asked an assistant to read the page, live (…-User UAs)\n * - `search` — indexing for an AI answer engine (…-SearchBot / SearchBot)\n * - `training` — model-training crawl (GPTBot, ClaudeBot, CCBot, …)\n * - `other` — not clearly AI, or an unknown/new token\n */\nexport type AgentIntent = 'user' | 'search' | 'training' | 'other';\n\n/** Intent per agent token. Maintained beside `agentUaList` — when you add or\n * rename a token above, set its intent here (a unit test enforces coverage). */\nexport const AGENT_INTENTS: Record<string, AgentIntent> = {\n 'GPTBot': 'training',\n 'ChatGPT-User': 'user',\n 'OAI-SearchBot': 'search',\n 'ClaudeBot': 'training',\n 'Claude-User': 'user',\n 'Claude-SearchBot': 'search',\n 'PerplexityBot': 'search',\n 'Perplexity-User': 'user',\n 'Google-Extended': 'training',\n 'Applebot-Extended': 'training',\n 'Meta-ExternalAgent': 'training',\n 'Bytespider': 'training',\n 'CCBot': 'training',\n 'Amazonbot': 'other',\n 'cohere-ai': 'training',\n 'Diffbot': 'other',\n};\n\n/** Intent for a matched bot token (case-insensitive); `other` for null/unknown. */\nexport function agentIntent(botName: string | null): AgentIntent {\n if (!botName) return 'other';\n const hit = agentUaList.find((t) => t.toLowerCase() === botName.toLowerCase());\n return (hit && AGENT_INTENTS[hit]) || 'other';\n}\n\n/** `agentUaList` grouped by intent — the \"which crawlers do you classify?\" reference. */\nexport function classifiedAgents(): Record<AgentIntent, string[]> {\n const out: Record<AgentIntent, string[]> = { user: [], search: [], training: [], other: [] };\n for (const t of agentUaList) out[AGENT_INTENTS[t] ?? 'other'].push(t);\n return out;\n}\n\nexport function detectDeviceClass(userAgent: string): string {\n const s = userAgent.toLowerCase();\n if (/ipad|tablet|playbook|kindle|silk/.test(s)) return 'tablet';\n if (/mobi|iphone|ipod|android.*mobile|phone/.test(s)) return 'mobile';\n return 'desktop';\n}\n\nexport function detectTrafficSource(referrer: string, appOrigin?: string, siteDomain?: string | null): string {\n if (!referrer) return 'direct';\n try {\n const refUrl = new URL(referrer);\n if (appOrigin) {\n try {\n if (new URL(appOrigin).host === refUrl.host) return 'direct';\n } catch {\n /* ignore invalid appOrigin */\n }\n }\n const host = refUrl.hostname.toLowerCase();\n // Another host of the same site (the shared cookie domain): example.com →\n // app.example.com is a page view inside the site, scored like one.\n if (siteDomain && `.${host}`.endsWith(`.${siteDomain}`)) return 'direct';\n if (/(^|\\.)(google|bing|duckduckgo|yahoo)\\./.test(host)) return 'search';\n // Anchor to the registrable domain (exact host or a subdomain of it) so\n // hosts like `x.company.com`, `t.company.io` or `linkedinsights.com` are not\n // misclassified as social by an unbounded substring match.\n if (/(^|\\.)(twitter\\.com|x\\.com|facebook\\.com|linkedin\\.com|reddit\\.com|t\\.co)$/.test(host)) return 'social';\n return 'referral';\n } catch {\n return 'direct';\n }\n}\n\nexport function referrerDomainFromReferer(referrer: string): string | null {\n if (!referrer) return null;\n try {\n return new URL(referrer).hostname;\n } catch {\n return null;\n }\n}\n\n/**\n * Ad-platform click-ID query params worth keeping. An ALLOWLIST, unlike the\n * `utm_` prefix match: unknown query keys here are unbounded-cardinality junk\n * (session tokens, cache busters) that would bloat the sessions table, so only\n * the IDs the major ad platforms actually append survive.\n *\n * gclid / gbraid / wbraid — Google Ads auto-tagging (search, YouTube, Display;\n * gbraid/wbraid are the iOS-14 privacy variants)\n * fbclid — Meta (Facebook + Instagram). Appended to EVERY outbound Meta\n * click, paid and organic alike — it identifies the platform, never spend.\n * ttclid — TikTok Ads\n * msclkid — Microsoft Ads (Bing)\n * twclid — X/Twitter Ads\n * li_fat_id — LinkedIn Ads\n */\nexport const CLICK_ID_KEYS: readonly string[] = [\n 'gclid',\n 'gbraid',\n 'wbraid',\n 'fbclid',\n 'ttclid',\n 'msclkid',\n 'twclid',\n 'li_fat_id',\n];\n\n/**\n * Splits a URL query into the attribution params the session upsert carries:\n * every `utm_`-prefixed key, plus allowlisted ad click IDs (CLICK_ID_KEYS).\n * Accepts a raw search string (\"?a=b\" or \"a=b\"), a URLSearchParams, or a\n * Next.js `searchParams` object (whose values may be string arrays — the\n * first occurrence wins, matching URLSearchParams iteration order).\n * Node-safe: no DOM APIs.\n */\nexport function extractTrackedParams(\n search: string | URLSearchParams | Record<string, string | string[] | undefined>,\n): { utmParams: Record<string, string>; clickIds: Record<string, string> } {\n const utmParams: Record<string, string> = {};\n const clickIds: Record<string, string> = {};\n try {\n const entries: Iterable<[string, string]> =\n typeof search === 'string' || search instanceof URLSearchParams\n ? new URLSearchParams(search)\n : Object.entries(search).flatMap(([k, v]): Array<[string, string]> => {\n const first = Array.isArray(v) ? v[0] : v;\n return first === undefined ? [] : [[k, first]];\n });\n for (const [k, v] of entries) {\n // First occurrence wins for duplicates — a repeated gclid in a mangled\n // URL must not let the later value silently replace the real one.\n if (k.startsWith('utm_')) {\n if (!(k in utmParams)) utmParams[k] = v;\n } else if (CLICK_ID_KEYS.includes(k)) {\n if (!(k in clickIds)) clickIds[k] = v;\n }\n }\n } catch {\n /* malformed input → empty attribution, never a throw at init() */\n }\n return { utmParams, clickIds };\n}\n\nexport function detectTimeOfDay(d: Date): string {\n const h = d.getHours();\n if (h < 6) return 'night';\n if (h < 12) return 'morning';\n if (h < 18) return 'afternoon';\n return 'evening';\n}\n\nexport type SessionUpsertPayload = {\n sessionId: string;\n ephemeral: boolean;\n utmParams: Record<string, string>;\n /** Allowlisted ad-platform click IDs from the landing URL (CLICK_ID_KEYS). */\n clickIds: Record<string, string>;\n deviceClass: string;\n trafficSource: string;\n /** Landing page path, no query string (arrival classification). */\n landingPath?: string;\n referrerDomain: string | null;\n timeOfDay: string;\n dayOfWeek: string;\n /**\n * True when this session is likely driven by automation — either\n * `navigator.webdriver` was set, or the user-agent carried a known agent\n * token. Probabilistic: a flag for metrics + bandit exclusion, never a gate.\n */\n automation: boolean;\n};\n\n/** Bandit segment key: `<device_class>:<traffic_source>`. */\nexport function deriveSessionSegment(opts?: {\n userAgent?: string;\n referer?: string;\n appOrigin?: string;\n}): string {\n const body = buildSessionUpsertPayload('__segment__', opts);\n return `${body.deviceClass}:${body.trafficSource}`;\n}\n\n/**\n * Builds a session upsert body aligned with the browser SDK so SSR assign uses\n * the same segment key (`device:source`) as the client after hydration.\n */\nexport function buildSessionUpsertPayload(\n sessionId: string,\n opts?: {\n userAgent?: string;\n referer?: string;\n appOrigin?: string;\n utmParams?: Record<string, string>;\n clickIds?: Record<string, string>;\n now?: Date;\n /** `navigator.webdriver` value from the browser, when available. */\n webdriver?: boolean;\n /** The landing page's path (no query string), when the caller knows it. */\n landingPath?: string;\n },\n): SessionUpsertPayload {\n const ua = opts?.userAgent?.trim() ?? '';\n const referer = opts?.referer?.trim() ?? '';\n const now = opts?.now ?? new Date();\n return {\n sessionId,\n ephemeral: false,\n utmParams: opts?.utmParams ?? {},\n clickIds: opts?.clickIds ?? {},\n deviceClass: ua ? detectDeviceClass(ua) : 'desktop',\n trafficSource: referer\n ? detectTrafficSource(referer, opts?.appOrigin)\n : 'direct',\n referrerDomain: referrerDomainFromReferer(referer),\n timeOfDay: detectTimeOfDay(now),\n dayOfWeek: ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'][now.getDay()] ?? 'sun',\n automation: opts?.webdriver === true || uaTokenMatch(ua),\n ...(opts?.landingPath ? { landingPath: opts.landingPath.split(/[?#]/)[0] } : {}),\n };\n}\n","/**\n * Per-project browser-storage namespace suffix, derived from the public apiKey.\n *\n * Multiple SentientUI projects (different `pk_` keys) can run on the same exact\n * origin. Storage keyed only by name (`_snt_uid`, `_snt_asgn_*`,\n * `_snt_graph_nodes`) would then collide across projects — the visitor id in\n * particular, whose session row is keyed globally server-side, would let one\n * project's traffic land on another's session. Suffixing every browser key with\n * the apiKey prefix isolates projects, matching the queue's existing\n * `_snt_retry_${apiKey.slice(0,12)}` convention.\n *\n * Returns `''` when no apiKey is available (local mode) so keys stay stable\n * there.\n */\nexport function storageSuffix(apiKey?: string): string {\n return apiKey ? `_${apiKey.slice(0, 12)}` : '';\n}\n\n/**\n * The bare, pre-namespacing session cookie name. Still read as a FALLBACK\n * everywhere the suffixed name is read, so visitors who got their identity\n * before per-project namespacing keep it instead of being minted a fresh one.\n */\nexport const LEGACY_SESSION_COOKIE_NAME = '_snt_uid';\n\n/**\n * The one place the session cookie's name is decided. The writer (session.ts)\n * and every reader (core/server.ts SSR helper, graph sync, react devtools) must\n * call THIS — when namespacing landed, the writer moved to the suffixed name\n * while three readers kept the bare `_snt_uid`, so every SSR request for a\n * returning visitor missed the cookie and minted a fresh orphan session (quota\n * inflation, broken sticky assignments and persona continuity), and graph sync\n * sent `sessionId: undefined`. Deriving both sides from one function makes that\n * drift impossible, and index.test.ts pins the reader against the writer.\n */\nexport function sessionCookieName(apiKey?: string): string {\n return `${LEGACY_SESSION_COOKIE_NAME}${storageSuffix(apiKey)}`;\n}\n\n// Forget-me generation per project, on window so every bundle on the page\n// sees it (the snippet and its lazy chunks each carry their own copy of these\n// modules). Every client and queue captures it when created and persists only\n// while it is unchanged: a forget can never be undone by a later grant — the\n// old boolean marker was cleared by the next tracking client, and a paused\n// client's in-flight decide then wrote the forgotten visitor back (grader\n// NEW-1), as could its queues' failed final flush (F8).\nconst GENS = '__sntForgetGen';\ntype GenMap = Record<string, number>;\nconst genMap = (): GenMap | undefined => {\n try {\n return (window as unknown as Record<string, GenMap | undefined>)[GENS];\n } catch {\n return undefined;\n }\n};\nexport function markForgotten(apiKey: string): void {\n try {\n const w = window as unknown as Record<string, GenMap>;\n const m = (w[GENS] ??= {});\n m[apiKey] = (m[apiKey] ?? 0) + 1;\n } catch {\n /* no window */\n }\n}\n/** Bumped by every forget-me for this project in this page. */\nexport function forgetGeneration(apiKey: string): number {\n return genMap()?.[apiKey] ?? 0;\n}\n","/**\n * Slot declaration helpers shared by the browser client (decide) and the\n * server preload path. Pure wrappers over @sentientui/policy.\n */\nimport {\n canonicalArm,\n slotBaselineArm,\n slotResultFor,\n type SlotDecl,\n type SlotResult,\n} from '@sentientui/policy';\n\n/** SDK-facing slot declaration. `dims` accepts readonly arrays (`as const`). */\nexport type SlotDeclInput = {\n id: string;\n arms?: string[];\n dims?: Record<string, readonly string[]>;\n baseline?: string | Record<string, string>;\n};\n\nexport type { SlotResult };\n\n/**\n * Whitelists the wire fields of a slot declaration. Anything an SDK layer\n * attached (goal configs, refs, …) is stripped so it never reaches the zod\n * schema on the API. Also normalizes readonly arrays to mutable ones.\n */\nexport function toWireSlot(d: SlotDeclInput): SlotDecl {\n return {\n id: d.id,\n ...(d.arms ? { arms: [...d.arms] } : {}),\n ...(d.dims\n ? {\n dims: Object.fromEntries(\n Object.entries(d.dims).map(([dim, values]) => [dim, [...values]]),\n ),\n }\n : {}),\n ...(d.baseline !== undefined ? { baseline: d.baseline } : {}),\n };\n}\n\n/** The declared (or default first-declared) baseline result for a slot. */\nexport function baselineResultFor(d: SlotDeclInput): SlotResult {\n const decl = toWireSlot(d);\n return slotResultFor(decl, slotBaselineArm(decl));\n}\n\n/** Baseline results for a whole declaration list, keyed by slot id. */\nexport function baselineSlots(decls: SlotDeclInput[]): Record<string, SlotResult> {\n const out: Record<string, SlotResult> = {};\n for (const d of decls) out[d.id] = baselineResultFor(d);\n return out;\n}\n\n/**\n * Canonical arm string of a slot result: dims results encode as sorted\n * `dim=value` pairs joined with '|'; arms results are the arm id verbatim.\n */\nexport function armOfResult(result: SlotResult): string {\n return typeof result === 'string' ? result : canonicalArm(result);\n}\n","/**\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":"kxBAAA,IAAAA,GAAA,GAAAC,GAAAD,GAAA,mBAAAE,EAAA,0BAAAC,EAAA,8BAAAC,EAAA,wBAAAC,EAAA,yBAAAC,EAAA,sBAAAC,EAAA,oBAAAC,EAAA,wBAAAC,EAAA,yBAAAC,EAAA,mBAAAC,EAAA,uBAAAC,GAAA,+BAAAC,EAAA,qBAAAC,GAAA,sBAAAC,GAAA,8BAAAC,EAAA,4BAAAC,GAAA,eAAAC,GAAA,oBAAAC,KAAA,eAAAC,GAAApB,ICQO,IAAMqB,GAAiC,CAC5C,SACA,eACA,gBACA,YACA,cACA,mBACA,gBACA,kBACA,kBACA,oBACA,qBACA,aACA,QACA,YACA,YACA,SACF,EAGO,SAASC,GAAaC,EAA4B,CACvD,OAAOC,EAAkBD,CAAS,IAAM,IAC1C,CAGO,SAASC,EAAkBD,EAAkC,CAjCpE,IAAAE,EAkCE,GAAI,CAACF,EAAW,OAAO,KACvB,IAAMG,EAAIH,EA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J,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":["index_server_exports","__export","CLICK_ID_KEYS","SERVER_GOAL_NAMESPACE","buildSessionUpsertPayload","captureAgentRequest","deriveSessionSegment","detectDeviceClass","detectTimeOfDay","detectTrafficSource","extractTrackedParams","postAgentFetch","preloadAssignments","preloadAssignmentsDetailed","preloadDecisions","readSessionCookie","referrerDomainFromReferer","sentientAgentMiddleware","signUserId","trackServerGoal","__toCommonJS","agentUaList","uaTokenMatch","userAgent","matchedAgentToken","_a","s","token","detectDeviceClass","userAgent","s","detectTrafficSource","referrer","appOrigin","siteDomain","refUrl","e","host","referrerDomainFromReferer","CLICK_ID_KEYS","extractTrackedParams","search","utmParams","clickIds","entries","k","v","first","detectTimeOfDay","d","h","deriveSessionSegment","opts","body","buildSessionUpsertPayload","sessionId","_a","_b","_c","_d","_e","_f","_g","_h","ua","referer","now","__spreadValues","uaTokenMatch","storageSuffix","apiKey","LEGACY_SESSION_COOKIE_NAME","sessionCookieName","import_policy","toWireSlot","d","__spreadValues","dim","values","baselineResultFor","decl","baselineSlots","decls","out","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","n","len","padded","view","h0","h1","h2","h3","h4","w","off","i","a","c","e","f","k","t","out","ov","v","uuidV5","name","namespace","hex","nsBytes","nameBytes","input","subtle","h","x","b","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,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-7RF3JRZO.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 _,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};
2
2
  //# sourceMappingURL=index-server.mjs.map
package/dist/index.d.cts CHANGED
@@ -1,5 +1,5 @@
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-CN9VJxiW.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-B7s2gvyU.cjs';
3
3
  export { A as AGENT_INTENTS, a as AgentIntent, C as CLICK_ID_KEYS, b as CompoundLocator, D as DecisionSnapshot, S as SNAPSHOT_STORAGE_KEY_PREFIX, d as SlotConfigEntry, e as SlotDeclInput, f as SlotOps, g as agentIntent, h as agentUaList, i as armOfResult, j as baselineResultFor, k as baselineSlots, m as classifiedAgents, n as deriveSessionSegment, o as detectDeviceClass, p as detectTimeOfDay, q as detectTrafficSource, r as extractTrackedParams, s as matchedAgentToken, t as readSnapshot, u as referrerDomainFromReferer, v as renderPrePaintScript, w as toWireSlot, x as uaTokenMatch, y as writeSnapshot } from './session-meta-BG8w53d7.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';
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
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-CROWjwsJ.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-BgEe5mKL.js';
3
3
  export { A as AGENT_INTENTS, a as AgentIntent, C as CLICK_ID_KEYS, b as CompoundLocator, D as DecisionSnapshot, S as SNAPSHOT_STORAGE_KEY_PREFIX, d as SlotConfigEntry, e as SlotDeclInput, f as SlotOps, g as agentIntent, h as agentUaList, i as armOfResult, j as baselineResultFor, k as baselineSlots, m as classifiedAgents, n as deriveSessionSegment, o as detectDeviceClass, p as detectTimeOfDay, q as detectTrafficSource, r as extractTrackedParams, s as matchedAgentToken, t as readSnapshot, u as referrerDomainFromReferer, v as renderPrePaintScript, w as toWireSlot, x as uaTokenMatch, y as writeSnapshot } from './session-meta-D9Wx2PtC.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';