@sentientui/core 0.23.0 → 0.25.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunk-2NVSFI4V.mjs +2 -0
- package/dist/chunk-2NVSFI4V.mjs.map +1 -0
- package/dist/chunk-RL5B6M4G.mjs +2 -0
- package/dist/chunk-RL5B6M4G.mjs.map +1 -0
- package/dist/chunk-WKXD7KI3.mjs +2 -0
- package/dist/chunk-WKXD7KI3.mjs.map +1 -0
- package/dist/chunk-Z6ILOYBD.mjs +2 -0
- package/dist/chunk-Z6ILOYBD.mjs.map +1 -0
- package/dist/{index-BbrtAtrY.d.ts → index-BjVvN7cU.d.ts} +1 -1
- package/dist/{index-CXxvWxCB.d.cts → index-Cd0gMdJv.d.cts} +1 -1
- package/dist/index-engagement.d.cts +1 -1
- package/dist/index-engagement.d.ts +1 -1
- package/dist/index-engagement.js +1 -1
- package/dist/index-engagement.js.map +1 -1
- package/dist/index-engagement.mjs +1 -1
- package/dist/index-engagement.mjs.map +1 -1
- package/dist/index-graph.d.cts +3 -3
- package/dist/index-graph.d.ts +3 -3
- package/dist/index-graph.js +1 -1
- package/dist/index-graph.js.map +1 -1
- package/dist/index-graph.mjs +1 -1
- package/dist/index-local.d.cts +2 -2
- package/dist/index-local.d.ts +2 -2
- package/dist/index-server.d.cts +10 -2
- package/dist/index-server.d.ts +10 -2
- package/dist/index-server.js +1 -1
- package/dist/index-server.js.map +1 -1
- package/dist/index-server.mjs +1 -1
- package/dist/index-server.mjs.map +1 -1
- package/dist/index-topics.d.cts +16 -1
- package/dist/index-topics.d.ts +16 -1
- package/dist/index-topics.js +1 -1
- package/dist/index-topics.js.map +1 -1
- package/dist/index-topics.mjs +1 -1
- package/dist/index-topics.mjs.map +1 -1
- package/dist/index.d.cts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1 -1
- package/dist/{session-meta-BVvq5RBB.d.cts → session-meta-C-bMqVeq.d.cts} +32 -1
- package/dist/{session-meta-BVvq5RBB.d.ts → session-meta-C-bMqVeq.d.ts} +32 -1
- package/package.json +2 -2
- package/dist/chunk-2RH7I6AP.mjs +0 -2
- package/dist/chunk-2RH7I6AP.mjs.map +0 -1
- package/dist/chunk-EWP6FTHE.mjs +0 -2
- package/dist/chunk-EWP6FTHE.mjs.map +0 -1
- package/dist/chunk-KIP52DUJ.mjs +0 -2
- package/dist/chunk-KIP52DUJ.mjs.map +0 -1
- package/dist/chunk-QNEYUJJJ.mjs +0 -2
- package/dist/chunk-QNEYUJJJ.mjs.map +0 -1
package/dist/index-graph.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{a as w}from"./chunk-KIP52DUJ.mjs";import{a as v,f as A}from"./chunk-EWP6FTHE.mjs";import{A as Z,B as O,a as V,b as W,c as J,d as X,g as we,h as Te,i as ve,j as Ae,k as Ne,l as xe,m as _e,n as Oe,o as Re,p as Me,q as De,r as Pe,s as ke,t as Ge,u as $e,v as Le,w as je,x as Q,y as x,z as _}from"./chunk-2RH7I6AP.mjs";import{a as N,b as C,c as b,j,k as K,l as U,m as F,n as q,p as z,q as B,r as H,s as Y}from"./chunk-QNEYUJJJ.mjs";import{a as y,b as E}from"./chunk-TMCGHANO.mjs";var R="_snt_graph_edges",ee={pricing:["features","faq"],features:["pricing"],faq:["pricing"],social_proof:["cta"],cta:["social_proof","hero","trust"],hero:["cta"],comparison:["pricing"],trust:["cta"]};function te(e){var t;return(t=ee[e])!=null?t:[]}function ne(e,t){try{let n=localStorage.getItem(e);return n?JSON.parse(n):t}catch(n){return t}}function oe(e,t){try{localStorage.setItem(e,JSON.stringify(t))}catch(n){}}var re=new Set(["pricing","hero","social_proof","cta","features","faq","comparison","trust","navigation","generic"]);function se(e){return re.has(e)?e:"generic"}function M(e){try{let t=new URL(e);return`${t.origin}${t.pathname}`}catch(t){return"/"}}function ae(e,t,n){let a=`${e}:${t}:${n.join(",")}`,c=5381;for(let i=0;i<a.length;i++)c=(c<<5)+c+a.charCodeAt(i)&4294967295;return(c>>>0).toString(16).padStart(8,"0")}function D(e){let t=new Map,n=new Map,a=`_snt_graph_nodes${N(e==null?void 0:e.apiKey)}`,c=()=>{typeof window!="undefined"&&oe(a,[...t.values()])};if(typeof window!="undefined"){let i=ne(a,[]);for(let o of i)t.set(o.componentId,o);try{localStorage.removeItem(R)}catch(o){}}return{addPageNode(i){t.set(i.componentId,i),c()},addStructuralEdge(i){let o=`${i.fromComponentId}->${i.toComponentId}`;n.set(o,i)},syncOnce(){var o,m;if(!(e!=null&&e.syncUrl)||typeof window=="undefined")return;let i=[...t.values()];if(i.length!==0)try{let u=new Map;for(let r of i){let p=(o=u.get(r.semanticType))!=null?o:[];p.push(r),u.set(r.semanticType,p)}let s=[],d=new Set;for(let r of i)for(let p of te(r.semanticType)){let l=(m=u.get(p))!=null?m:[];for(let h of l){if(h.componentId===r.componentId)continue;let S=`semantic:${r.componentId}->${h.componentId}`;d.has(S)||(d.add(S),s.push({fromComponentId:r.componentId,toComponentId:h.componentId,type:"semantic",weight:.4,confidence:.9}))}}let f=new Set(i.map(r=>r.componentId));for(let r of n.values()){if(!f.has(r.fromComponentId)||!f.has(r.toComponentId))continue;let p=`structural:${r.fromComponentId}->${r.toComponentId}`;d.has(p)||(d.add(p),s.push({fromComponentId:r.fromComponentId,toComponentId:r.toComponentId,type:"structural",weight:r.weight,confidence:1}))}let g=E(y(y({pageUrl:M(window.location.href)},e.sessionId?{sessionId:e.sessionId}:{}),e.projectId?{projectId:e.projectId}:{}),{nodes:i.map(r=>{let p=se(r.semanticType);return{componentId:r.componentId,semanticType:p,answers:r.answers,contentHash:ae(r.componentId,p,r.answers),prominenceScore:r.prominenceScore,depthInPage:r.depth}}),edges:s});fetch(e.syncUrl,{method:"POST",keepalive:!0,headers:y({"Content-Type":"application/json"},e.apiKey?{Authorization:`Bearer ${e.apiKey}`}:{}),body:JSON.stringify(g)}).catch(()=>{})}catch(u){}},snapshot(){return{pageNodes:[...t.values()],capturedAt:Date.now()}},destroy(){if(typeof window!="undefined")try{localStorage.removeItem(a),localStorage.removeItem(R)}catch(i){}}}}var ie=new Set(["SECTION","ARTICLE","MAIN","DIV","ASIDE"]),ce="h1, h2, h3",de="[data-sentient-id], section[aria-label], article[aria-label], main[aria-label], aside[aria-label]",P=30,pe=1500,ue={scan:async()=>({nodes:[],edges:[],scannedAt:0}),observe:()=>{},getProminenceScore:()=>0,destroy:()=>{}};function k(e,t,n){return n<=t?0:Math.max(0,Math.min(1,(e-t)/(n-t)))}function le(e){var t,n,a;try{let c=e;for(let i of Object.keys(c)){if(!i.startsWith("__reactFiber")&&!i.startsWith("__reactInternalInstance"))continue;let o=c[i],m=(a=(t=o==null?void 0:o.type)==null?void 0:t.displayName)!=null?a:(n=o==null?void 0:o.type)==null?void 0:n.name;if(m&&m.length>1)return m}}catch(c){}}function me(e){let t={};for(let n of Array.from(e.attributes))n.name.startsWith("data-")&&(t[n.name]=n.value);return t}var G=new Set(v);function fe(e){let t=e.getAttribute("data-sentient-type");if(t&&G.has(t))return t;let n=e.getAttribute("role");return n&&G.has(n)?n:A(e)}function ge(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 he(e){let t=[],n=e;for(;n;){let a=n.parentElement;if(!a){t.push(n.tagName.toLowerCase());break}let c=Array.prototype.indexOf.call(a.children,n);t.push(`${n.tagName.toLowerCase()}[${c}]`),n=a}return t.reverse().join("/")}function Se(e){var n;let t=(n=e.getAttribute("data-sentient-id"))!=null?n:e.getAttribute("id");return t||`${e.tagName.toLowerCase()}-${ge(he(e))}`}function ye(e){let t=0,n=e.parentElement;for(;n;)t++,n=n.parentElement;return t}function T(e,t){var a,c,i,o;let n=e.querySelector(ce);return{componentId:Se(e),semanticType:fe(e),ariaLabel:(a=e.getAttribute("aria-label"))!=null?a:void 0,headingText:(i=(c=n==null?void 0:n.textContent)==null?void 0:c.trim())!=null?i:void 0,isAboveFold:e.getBoundingClientRect().top<window.innerHeight,prominenceScore:t(e),depth:ye(e),reactComponentName:le(e),dataAttributes:me(e),locator:(o=w(e,e.ownerDocument))!=null?o:void 0}}function $(e){var i;let t=[],n=new Set,a="__root__",c=new Map;for(let[o,m]of e){let u=o.parentElement,s=a;for(;u;){if(e.has(u)){s=e.get(u);let f=e.get(o),g=`${s}->${f}`;!n.has(g)&&s!==f&&(n.add(g),t.push({fromComponentId:s,toComponentId:f,weight:.6}));break}u=u.parentElement}let d=(i=c.get(s))!=null?i:[];d.push(o),c.set(s,d)}for(let o of c.values()){if(o.length<2)continue;let m=o.length>P?o.slice(0,P):o;for(let u=0;u<m.length;u++)for(let s=u+1;s<m.length;s++){if(t.length>=pe)return t;let d=e.get(m[u]),f=e.get(m[s]);if(d===f)continue;let g=`${d}->${f}::sib`,r=`${f}->${d}::sib`;n.has(g)||(n.add(g),t.push({fromComponentId:d,toComponentId:f,weight:.3})),n.has(r)||(n.add(r),t.push({fromComponentId:f,toComponentId:d,weight:.3}))}}return t}function Ee(e){let t=[],n=new Set,a=new Map;return document.querySelectorAll("[data-sentient-id]").forEach(o=>{if(o instanceof Element&&!n.has(o)){n.add(o);let m=T(o,e);t.push(m),a.set(o,m.componentId)}}),document.querySelectorAll("section, article, main, aside").forEach(o=>{if(!(o instanceof Element)||n.has(o))return;let m=o.hasAttribute("aria-label"),u=o.hasAttribute("data-sentient-id");if(!m&&!u)return;n.add(o);let s=T(o,e);t.push(s),a.set(o,s.componentId)}),{nodes:t,edges:$(a),elementToId:a}}function L(){if(typeof window=="undefined")return ue;let e=null,t=0,n=null,a=new Map,c=u=>{try{let s=window.getComputedStyle(u),d=parseFloat(s.fontSize)||12,f=parseFloat(s.zIndex)||0,g=u.getBoundingClientRect(),r=Math.max(g.top,0),p=window.innerHeight||1,l=1/(r/p+1),h=k(d,12,48)*.4+l*.4+k(f,0,100)*.2;return Math.max(0,Math.min(1,h))}catch(s){return .5}};return{scan:()=>new Promise(u=>{let s=()=>{let{nodes:d,edges:f,elementToId:g}=Ee(c);a.clear();for(let[r,p]of g)a.set(r,p);u({nodes:d,edges:f,scannedAt:Date.now()})};try{typeof requestIdleCallback=="function"?t=requestIdleCallback(s,{timeout:100}):s()}catch(d){s()}}),observe:u=>{n=u;try{e=new MutationObserver(s=>{let d=[],f=new Set;for(let r of s)r.type==="childList"&&r.addedNodes.forEach(p=>{if(!(p instanceof Element))return;let l=[];ie.has(p.tagName)&&(p.hasAttribute("data-sentient-id")||p.hasAttribute("aria-label"))&&l.push(p);try{p.querySelectorAll(de).forEach(h=>l.push(h))}catch(h){}for(let h of l){if(a.has(h))continue;let S=T(h,c);d.push(S),f.add(S.componentId),a.set(h,S.componentId)}});if(d.length===0||!n)return;for(let r of[...a.keys()])r.isConnected||a.delete(r);let g=$(a).filter(r=>f.has(r.fromComponentId)||f.has(r.toComponentId));n({nodes:d,edges:g,addedAt:Date.now()})}),e.observe(document.body,{childList:!0,subtree:!0})}catch(s){}},getProminenceScore:c,destroy:()=>{if(e&&(e.disconnect(),e=null),t&&typeof cancelIdleCallback=="function")try{cancelIdleCallback(t)}catch(u){}t=0,n=null,a.clear()}}}var Ie="https://api.sentient-ui.com/v1/events";function Ce(e){var n;let t=a=>{try{let c=document.cookie.match(new RegExp(`(?:^|; )${a}=([^;]*)`));return c?decodeURIComponent(c[1]):void 0}catch(c){return}};return(n=e?t(b(e)):void 0)!=null?n:t(C)}var I=new Map;function be(e){var r;let t=O(e),n=e.respectDoNotTrack!==!1&&_(),a=e.consent===!1||n,c=typeof e.apiKey=="string"&&e.apiKey.startsWith("pk_"),i=e.localMode===!0||!c;if(!e.graph||i||typeof window=="undefined")return t;if(a)return n||x(e.apiKey,p=>be(p)),t;let o=I.get(e.apiKey);if(o)try{o()}catch(p){}let m=L(),u=(r=e.ingestUrl)!=null?r:Ie,s=D({syncUrl:u.replace(/\/events\/?$/,"/graph/sync"),apiKey:e.apiKey,projectId:e.apiKey,sessionId:Ce(e.apiKey)});m.scan().then(p=>{for(let l of p.nodes)s.addPageNode({id:l.componentId,componentId:l.componentId,semanticType:l.semanticType,answers:e.captureDomText&&l.headingText?[l.headingText]:[],prominenceScore:l.prominenceScore,depth:l.depth});for(let l of p.edges)s.addStructuralEdge(l);s.syncOnce()});let d=null,f=()=>{d!==null&&clearTimeout(d),d=setTimeout(()=>{d=null,s.syncOnce()},500)};m.observe(p=>{for(let l of p.nodes)s.addPageNode({id:l.componentId,componentId:l.componentId,semanticType:l.semanticType,answers:e.captureDomText&&l.headingText?[l.headingText]:[],prominenceScore:l.prominenceScore,depth:l.depth});for(let l of p.edges)s.addStructuralEdge(l);f()});let g=()=>{d!==null&&(clearTimeout(d),d=null),m.destroy(),s.destroy(),I.get(e.apiKey)===g&&I.delete(e.apiKey)};return I.set(e.apiKey,g),E(y({},t),{getGraph:()=>s.snapshot(),dispose:()=>{g(),t.dispose()},destroy:()=>{g(),t.destroy()}})}export{Te as BLOCK_ALIGNS,_e as BLOCK_EMPHASES,Me as BLOCK_FITS,we as BLOCK_GAPS,De as BLOCK_GRID_COLUMNS,Pe as BLOCK_HEADING_LEVELS,ve as BLOCK_JUSTIFIES,Re as BLOCK_RATIOS,Ae as BLOCK_SIZES,Oe as BLOCK_TEXT_ALIGNS,xe as BLOCK_TONES,Ne as BLOCK_WEIGHTS,C as LEGACY_SESSION_COOKIE_NAME,Le as MAX_BLOCK_ARMS,$e as MAX_BLOCK_CHILDREN,Ge as MAX_BLOCK_DEPTH,ke as MAX_BLOCK_NODES,je as MAX_BLOCK_TEXT_LEN,V as SNAPSHOT_STORAGE_KEY_PREFIX,Y as armOfResult,Q as attachMicroSignalDetectors,B as baselineResultFor,H as baselineSlots,q as deriveSessionSegment,j as detectDeviceClass,F as detectTimeOfDay,K as detectTrafficSource,Z as grantConsent,be as init,_ as isDoNotTrackEnabled,w as locatorFromElement,W as readSnapshot,U as referrerDomainFromReferer,X as renderPrePaintScript,M as sanitizePageUrl,b as sessionCookieName,z as toWireSlot,J as writeSnapshot};
|
|
1
|
+
import{a as w}from"./chunk-WKXD7KI3.mjs";import{a as v,g as A}from"./chunk-Z6ILOYBD.mjs";import{A as Z,B as O,a as V,b as W,c as J,d as X,g as we,h as Te,i as ve,j as Ae,k as Ne,l as xe,m as _e,n as Oe,o as Re,p as Me,q as De,r as Pe,s as ke,t as Ge,u as $e,v as Le,w as je,x as Q,y as x,z as _}from"./chunk-RL5B6M4G.mjs";import{a as N,b as C,c as b,j,k as K,l as U,o as F,p as q,r as z,s as B,t as H,u as Y}from"./chunk-2NVSFI4V.mjs";import{a as y,b as E}from"./chunk-TMCGHANO.mjs";var R="_snt_graph_edges",ee={pricing:["features","faq"],features:["pricing"],faq:["pricing"],social_proof:["cta"],cta:["social_proof","hero","trust"],hero:["cta"],comparison:["pricing"],trust:["cta"]};function te(e){var t;return(t=ee[e])!=null?t:[]}function ne(e,t){try{let n=localStorage.getItem(e);return n?JSON.parse(n):t}catch(n){return t}}function oe(e,t){try{localStorage.setItem(e,JSON.stringify(t))}catch(n){}}var re=new Set(["pricing","hero","social_proof","cta","features","faq","comparison","trust","navigation","generic"]);function se(e){return re.has(e)?e:"generic"}function M(e){try{let t=new URL(e);return`${t.origin}${t.pathname}`}catch(t){return"/"}}function ae(e,t,n){let a=`${e}:${t}:${n.join(",")}`,c=5381;for(let i=0;i<a.length;i++)c=(c<<5)+c+a.charCodeAt(i)&4294967295;return(c>>>0).toString(16).padStart(8,"0")}function D(e){let t=new Map,n=new Map,a=`_snt_graph_nodes${N(e==null?void 0:e.apiKey)}`,c=()=>{typeof window!="undefined"&&oe(a,[...t.values()])};if(typeof window!="undefined"){let i=ne(a,[]);for(let o of i)t.set(o.componentId,o);try{localStorage.removeItem(R)}catch(o){}}return{addPageNode(i){t.set(i.componentId,i),c()},addStructuralEdge(i){let o=`${i.fromComponentId}->${i.toComponentId}`;n.set(o,i)},syncOnce(){var o,m;if(!(e!=null&&e.syncUrl)||typeof window=="undefined")return;let i=[...t.values()];if(i.length!==0)try{let u=new Map;for(let r of i){let p=(o=u.get(r.semanticType))!=null?o:[];p.push(r),u.set(r.semanticType,p)}let s=[],d=new Set;for(let r of i)for(let p of te(r.semanticType)){let l=(m=u.get(p))!=null?m:[];for(let h of l){if(h.componentId===r.componentId)continue;let S=`semantic:${r.componentId}->${h.componentId}`;d.has(S)||(d.add(S),s.push({fromComponentId:r.componentId,toComponentId:h.componentId,type:"semantic",weight:.4,confidence:.9}))}}let f=new Set(i.map(r=>r.componentId));for(let r of n.values()){if(!f.has(r.fromComponentId)||!f.has(r.toComponentId))continue;let p=`structural:${r.fromComponentId}->${r.toComponentId}`;d.has(p)||(d.add(p),s.push({fromComponentId:r.fromComponentId,toComponentId:r.toComponentId,type:"structural",weight:r.weight,confidence:1}))}let g=E(y(y({pageUrl:M(window.location.href)},e.sessionId?{sessionId:e.sessionId}:{}),e.projectId?{projectId:e.projectId}:{}),{nodes:i.map(r=>{let p=se(r.semanticType);return{componentId:r.componentId,semanticType:p,answers:r.answers,contentHash:ae(r.componentId,p,r.answers),prominenceScore:r.prominenceScore,depthInPage:r.depth}}),edges:s});fetch(e.syncUrl,{method:"POST",keepalive:!0,headers:y({"Content-Type":"application/json"},e.apiKey?{Authorization:`Bearer ${e.apiKey}`}:{}),body:JSON.stringify(g)}).catch(()=>{})}catch(u){}},snapshot(){return{pageNodes:[...t.values()],capturedAt:Date.now()}},destroy(){if(typeof window!="undefined")try{localStorage.removeItem(a),localStorage.removeItem(R)}catch(i){}}}}var ie=new Set(["SECTION","ARTICLE","MAIN","DIV","ASIDE"]),ce="h1, h2, h3",de="[data-sentient-id], section[aria-label], article[aria-label], main[aria-label], aside[aria-label]",P=30,pe=1500,ue={scan:async()=>({nodes:[],edges:[],scannedAt:0}),observe:()=>{},getProminenceScore:()=>0,destroy:()=>{}};function k(e,t,n){return n<=t?0:Math.max(0,Math.min(1,(e-t)/(n-t)))}function le(e){var t,n,a;try{let c=e;for(let i of Object.keys(c)){if(!i.startsWith("__reactFiber")&&!i.startsWith("__reactInternalInstance"))continue;let o=c[i],m=(a=(t=o==null?void 0:o.type)==null?void 0:t.displayName)!=null?a:(n=o==null?void 0:o.type)==null?void 0:n.name;if(m&&m.length>1)return m}}catch(c){}}function me(e){let t={};for(let n of Array.from(e.attributes))n.name.startsWith("data-")&&(t[n.name]=n.value);return t}var G=new Set(v);function fe(e){let t=e.getAttribute("data-sentient-type");if(t&&G.has(t))return t;let n=e.getAttribute("role");return n&&G.has(n)?n:A(e)}function ge(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 he(e){let t=[],n=e;for(;n;){let a=n.parentElement;if(!a){t.push(n.tagName.toLowerCase());break}let c=Array.prototype.indexOf.call(a.children,n);t.push(`${n.tagName.toLowerCase()}[${c}]`),n=a}return t.reverse().join("/")}function Se(e){var n;let t=(n=e.getAttribute("data-sentient-id"))!=null?n:e.getAttribute("id");return t||`${e.tagName.toLowerCase()}-${ge(he(e))}`}function ye(e){let t=0,n=e.parentElement;for(;n;)t++,n=n.parentElement;return t}function T(e,t){var a,c,i,o;let n=e.querySelector(ce);return{componentId:Se(e),semanticType:fe(e),ariaLabel:(a=e.getAttribute("aria-label"))!=null?a:void 0,headingText:(i=(c=n==null?void 0:n.textContent)==null?void 0:c.trim())!=null?i:void 0,isAboveFold:e.getBoundingClientRect().top<window.innerHeight,prominenceScore:t(e),depth:ye(e),reactComponentName:le(e),dataAttributes:me(e),locator:(o=w(e,e.ownerDocument))!=null?o:void 0}}function $(e){var i;let t=[],n=new Set,a="__root__",c=new Map;for(let[o,m]of e){let u=o.parentElement,s=a;for(;u;){if(e.has(u)){s=e.get(u);let f=e.get(o),g=`${s}->${f}`;!n.has(g)&&s!==f&&(n.add(g),t.push({fromComponentId:s,toComponentId:f,weight:.6}));break}u=u.parentElement}let d=(i=c.get(s))!=null?i:[];d.push(o),c.set(s,d)}for(let o of c.values()){if(o.length<2)continue;let m=o.length>P?o.slice(0,P):o;for(let u=0;u<m.length;u++)for(let s=u+1;s<m.length;s++){if(t.length>=pe)return t;let d=e.get(m[u]),f=e.get(m[s]);if(d===f)continue;let g=`${d}->${f}::sib`,r=`${f}->${d}::sib`;n.has(g)||(n.add(g),t.push({fromComponentId:d,toComponentId:f,weight:.3})),n.has(r)||(n.add(r),t.push({fromComponentId:f,toComponentId:d,weight:.3}))}}return t}function Ee(e){let t=[],n=new Set,a=new Map;return document.querySelectorAll("[data-sentient-id]").forEach(o=>{if(o instanceof Element&&!n.has(o)){n.add(o);let m=T(o,e);t.push(m),a.set(o,m.componentId)}}),document.querySelectorAll("section, article, main, aside").forEach(o=>{if(!(o instanceof Element)||n.has(o))return;let m=o.hasAttribute("aria-label"),u=o.hasAttribute("data-sentient-id");if(!m&&!u)return;n.add(o);let s=T(o,e);t.push(s),a.set(o,s.componentId)}),{nodes:t,edges:$(a),elementToId:a}}function L(){if(typeof window=="undefined")return ue;let e=null,t=0,n=null,a=new Map,c=u=>{try{let s=window.getComputedStyle(u),d=parseFloat(s.fontSize)||12,f=parseFloat(s.zIndex)||0,g=u.getBoundingClientRect(),r=Math.max(g.top,0),p=window.innerHeight||1,l=1/(r/p+1),h=k(d,12,48)*.4+l*.4+k(f,0,100)*.2;return Math.max(0,Math.min(1,h))}catch(s){return .5}};return{scan:()=>new Promise(u=>{let s=()=>{let{nodes:d,edges:f,elementToId:g}=Ee(c);a.clear();for(let[r,p]of g)a.set(r,p);u({nodes:d,edges:f,scannedAt:Date.now()})};try{typeof requestIdleCallback=="function"?t=requestIdleCallback(s,{timeout:100}):s()}catch(d){s()}}),observe:u=>{n=u;try{e=new MutationObserver(s=>{let d=[],f=new Set;for(let r of s)r.type==="childList"&&r.addedNodes.forEach(p=>{if(!(p instanceof Element))return;let l=[];ie.has(p.tagName)&&(p.hasAttribute("data-sentient-id")||p.hasAttribute("aria-label"))&&l.push(p);try{p.querySelectorAll(de).forEach(h=>l.push(h))}catch(h){}for(let h of l){if(a.has(h))continue;let S=T(h,c);d.push(S),f.add(S.componentId),a.set(h,S.componentId)}});if(d.length===0||!n)return;for(let r of[...a.keys()])r.isConnected||a.delete(r);let g=$(a).filter(r=>f.has(r.fromComponentId)||f.has(r.toComponentId));n({nodes:d,edges:g,addedAt:Date.now()})}),e.observe(document.body,{childList:!0,subtree:!0})}catch(s){}},getProminenceScore:c,destroy:()=>{if(e&&(e.disconnect(),e=null),t&&typeof cancelIdleCallback=="function")try{cancelIdleCallback(t)}catch(u){}t=0,n=null,a.clear()}}}var Ie="https://api.sentient-ui.com/v1/events";function Ce(e){var n;let t=a=>{try{let c=document.cookie.match(new RegExp(`(?:^|; )${a}=([^;]*)`));return c?decodeURIComponent(c[1]):void 0}catch(c){return}};return(n=e?t(b(e)):void 0)!=null?n:t(C)}var I=new Map;function be(e){var r;let t=O(e),n=e.respectDoNotTrack!==!1&&_(),a=e.consent===!1||n,c=typeof e.apiKey=="string"&&e.apiKey.startsWith("pk_"),i=e.localMode===!0||!c;if(!e.graph||i||typeof window=="undefined")return t;if(a)return n||x(e.apiKey,p=>be(p)),t;let o=I.get(e.apiKey);if(o)try{o()}catch(p){}let m=L(),u=(r=e.ingestUrl)!=null?r:Ie,s=D({syncUrl:u.replace(/\/events\/?$/,"/graph/sync"),apiKey:e.apiKey,projectId:e.apiKey,sessionId:Ce(e.apiKey)});m.scan().then(p=>{for(let l of p.nodes)s.addPageNode({id:l.componentId,componentId:l.componentId,semanticType:l.semanticType,answers:e.captureDomText&&l.headingText?[l.headingText]:[],prominenceScore:l.prominenceScore,depth:l.depth});for(let l of p.edges)s.addStructuralEdge(l);s.syncOnce()});let d=null,f=()=>{d!==null&&clearTimeout(d),d=setTimeout(()=>{d=null,s.syncOnce()},500)};m.observe(p=>{for(let l of p.nodes)s.addPageNode({id:l.componentId,componentId:l.componentId,semanticType:l.semanticType,answers:e.captureDomText&&l.headingText?[l.headingText]:[],prominenceScore:l.prominenceScore,depth:l.depth});for(let l of p.edges)s.addStructuralEdge(l);f()});let g=()=>{d!==null&&(clearTimeout(d),d=null),m.destroy(),s.destroy(),I.get(e.apiKey)===g&&I.delete(e.apiKey)};return I.set(e.apiKey,g),E(y({},t),{getGraph:()=>s.snapshot(),dispose:()=>{g(),t.dispose()},destroy:()=>{g(),t.destroy()}})}export{Te as BLOCK_ALIGNS,_e as BLOCK_EMPHASES,Me as BLOCK_FITS,we as BLOCK_GAPS,De as BLOCK_GRID_COLUMNS,Pe as BLOCK_HEADING_LEVELS,ve as BLOCK_JUSTIFIES,Re as BLOCK_RATIOS,Ae as BLOCK_SIZES,Oe as BLOCK_TEXT_ALIGNS,xe as BLOCK_TONES,Ne as BLOCK_WEIGHTS,C as LEGACY_SESSION_COOKIE_NAME,Le as MAX_BLOCK_ARMS,$e as MAX_BLOCK_CHILDREN,Ge as MAX_BLOCK_DEPTH,ke as MAX_BLOCK_NODES,je as MAX_BLOCK_TEXT_LEN,V as SNAPSHOT_STORAGE_KEY_PREFIX,Y as armOfResult,Q as attachMicroSignalDetectors,B as baselineResultFor,H as baselineSlots,q as deriveSessionSegment,j as detectDeviceClass,F as detectTimeOfDay,K as detectTrafficSource,Z as grantConsent,be as init,_ as isDoNotTrackEnabled,w as locatorFromElement,W as readSnapshot,U as referrerDomainFromReferer,X as renderPrePaintScript,M as sanitizePageUrl,b as sessionCookieName,z as toWireSlot,J as writeSnapshot};
|
|
2
2
|
//# sourceMappingURL=index-graph.mjs.map
|
package/dist/index-local.d.cts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { G as DecideOutcome } from './index-
|
|
2
|
-
import { b as SlotDeclInput } from './session-meta-
|
|
1
|
+
import { G as DecideOutcome } from './index-Cd0gMdJv.cjs';
|
|
2
|
+
import { b as SlotDeclInput } from './session-meta-C-bMqVeq.cjs';
|
|
3
3
|
import '@sentientui/policy';
|
|
4
4
|
|
|
5
5
|
/**
|
package/dist/index-local.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { G as DecideOutcome } from './index-
|
|
2
|
-
import { b as SlotDeclInput } from './session-meta-
|
|
1
|
+
import { G as DecideOutcome } from './index-BjVvN7cU.js';
|
|
2
|
+
import { b as SlotDeclInput } from './session-meta-C-bMqVeq.js';
|
|
3
3
|
import '@sentientui/policy';
|
|
4
4
|
|
|
5
5
|
/**
|
package/dist/index-server.d.cts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { b as SlotDeclInput } from './session-meta-
|
|
2
|
-
export { S as SessionUpsertPayload, h as buildSessionUpsertPayload, j as deriveSessionSegment, k as detectDeviceClass, l as detectTimeOfDay, m as detectTrafficSource, r as referrerDomainFromReferer } from './session-meta-
|
|
1
|
+
import { b as SlotDeclInput } from './session-meta-C-bMqVeq.cjs';
|
|
2
|
+
export { C as CLICK_ID_KEYS, S as SessionUpsertPayload, h as buildSessionUpsertPayload, j as deriveSessionSegment, k as detectDeviceClass, l as detectTimeOfDay, m as detectTrafficSource, n as extractTrackedParams, r as referrerDomainFromReferer } from './session-meta-C-bMqVeq.cjs';
|
|
3
3
|
import { SlotResult } from '@sentientui/policy';
|
|
4
4
|
export { SlotResult } from '@sentientui/policy';
|
|
5
5
|
|
|
@@ -21,6 +21,14 @@ type ServerAssignConfig = {
|
|
|
21
21
|
/** From `Referer` request header. */
|
|
22
22
|
referer?: string;
|
|
23
23
|
utmParams?: Record<string, string>;
|
|
24
|
+
/**
|
|
25
|
+
* Ad-platform click IDs (gclid, fbclid, ttclid, …) from the landing URL.
|
|
26
|
+
* Derive both this and `utmParams` with `extractTrackedParams(searchParams)`
|
|
27
|
+
* — the Referer header never carries the landing page's own query string, so
|
|
28
|
+
* without these two fields SSR-minted sessions have no campaign attribution
|
|
29
|
+
* until the client SDK hydrates.
|
|
30
|
+
*/
|
|
31
|
+
clickIds?: Record<string, string>;
|
|
24
32
|
/**
|
|
25
33
|
* Set true when the request carries a tracking opt-out — `DNT: 1` or
|
|
26
34
|
* `Sec-GPC: 1`. When set, the SSR helpers skip the session upsert and the
|
package/dist/index-server.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { b as SlotDeclInput } from './session-meta-
|
|
2
|
-
export { S as SessionUpsertPayload, h as buildSessionUpsertPayload, j as deriveSessionSegment, k as detectDeviceClass, l as detectTimeOfDay, m as detectTrafficSource, r as referrerDomainFromReferer } from './session-meta-
|
|
1
|
+
import { b as SlotDeclInput } from './session-meta-C-bMqVeq.js';
|
|
2
|
+
export { C as CLICK_ID_KEYS, S as SessionUpsertPayload, h as buildSessionUpsertPayload, j as deriveSessionSegment, k as detectDeviceClass, l as detectTimeOfDay, m as detectTrafficSource, n as extractTrackedParams, r as referrerDomainFromReferer } from './session-meta-C-bMqVeq.js';
|
|
3
3
|
import { SlotResult } from '@sentientui/policy';
|
|
4
4
|
export { SlotResult } from '@sentientui/policy';
|
|
5
5
|
|
|
@@ -21,6 +21,14 @@ type ServerAssignConfig = {
|
|
|
21
21
|
/** From `Referer` request header. */
|
|
22
22
|
referer?: string;
|
|
23
23
|
utmParams?: Record<string, string>;
|
|
24
|
+
/**
|
|
25
|
+
* Ad-platform click IDs (gclid, fbclid, ttclid, …) from the landing URL.
|
|
26
|
+
* Derive both this and `utmParams` with `extractTrackedParams(searchParams)`
|
|
27
|
+
* — the Referer header never carries the landing page's own query string, so
|
|
28
|
+
* without these two fields SSR-minted sessions have no campaign attribution
|
|
29
|
+
* until the client SDK hydrates.
|
|
30
|
+
*/
|
|
31
|
+
clickIds?: Record<string, string>;
|
|
24
32
|
/**
|
|
25
33
|
* Set true when the request carries a tracking opt-out — `DNT: 1` or
|
|
26
34
|
* `Sec-GPC: 1`. When set, the SSR helpers skip the session upsert and the
|
package/dist/index-server.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var R=Object.defineProperty,q=Object.defineProperties,H=Object.getOwnPropertyDescriptor,Q=Object.getOwnPropertyDescriptors,V=Object.getOwnPropertyNames,L=Object.getOwnPropertySymbols;var N=Object.prototype.hasOwnProperty,X=Object.prototype.propertyIsEnumerable;var $=(r,e,t)=>e in r?R(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,c=(r,e)=>{for(var t in e||(e={}))N.call(e,t)&&$(r,t,e[t]);if(L)for(var t of L(e))X.call(e,t)&&$(r,t,e[t]);return r},j=(r,e)=>q(r,Q(e));var Z=(r,e)=>{for(var t in e)R(r,t,{get:e[t],enumerable:!0})},ee=(r,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of V(e))!N.call(r,n)&&n!==t&&R(r,n,{get:()=>e[n],enumerable:!(s=H(e,n))||s.enumerable});return r};var te=r=>ee(R({},"__esModule",{value:!0}),r);var oe={};Z(oe,{CLICK_ID_KEYS:()=>k,buildSessionUpsertPayload:()=>y,deriveSessionSegment:()=>G,detectDeviceClass:()=>I,detectTimeOfDay:()=>w,detectTrafficSource:()=>x,extractTrackedParams:()=>M,preloadAssignments:()=>z,preloadDecisions:()=>Y,readSessionCookie:()=>J,referrerDomainFromReferer:()=>C});module.exports=te(oe);var re=["GPTBot","ChatGPT-User","OAI-SearchBot","ClaudeBot","Claude-User","Claude-SearchBot","PerplexityBot","Perplexity-User","Google-Extended","Applebot-Extended","Meta-ExternalAgent","Bytespider","CCBot","Amazonbot","cohere-ai","Diffbot"];function ne(r){return se(r)!==null}function se(r){var t;if(!r)return null;let e=r.toLowerCase();return(t=re.find(s=>e.includes(s.toLowerCase())))!=null?t:null}function I(r){let e=r.toLowerCase();return/ipad|tablet|playbook|kindle|silk/.test(e)?"tablet":/mobi|iphone|ipod|android.*mobile|phone/.test(e)?"mobile":"desktop"}function x(r,e){if(!r)return"direct";try{let t=new URL(r);if(e)try{if(new URL(e).host===t.host)return"direct"}catch(n){}let s=t.hostname.toLowerCase();return/(^|\.)(google|bing|duckduckgo|yahoo)\./.test(s)?"search":/(^|\.)(twitter\.com|x\.com|facebook\.com|linkedin\.com|reddit\.com|t\.co)$/.test(s)?"social":"referral"}catch(t){return"direct"}}function C(r){if(!r)return null;try{return new URL(r).hostname}catch(e){return null}}var k=["gclid","gbraid","wbraid","fbclid","ttclid","msclkid","twclid","li_fat_id"];function M(r){let e={},t={};try{let s=typeof r=="string"||r instanceof URLSearchParams?new URLSearchParams(r):Object.entries(r).flatMap(([n,o])=>{let l=Array.isArray(o)?o[0]:o;return l===void 0?[]:[[n,l]]});for(let[n,o]of s)n.startsWith("utm_")?n in e||(e[n]=o):k.includes(n)&&(n in t||(t[n]=o))}catch(s){}return{utmParams:e,clickIds:t}}function w(r){let e=r.getHours();return e<6?"night":e<12?"morning":e<18?"afternoon":"evening"}function G(r){let e=y("__segment__",r);return`${e.deviceClass}:${e.trafficSource}`}function y(r,e){var o,l,m,g,i,d,u,f;let t=(l=(o=e==null?void 0:e.userAgent)==null?void 0:o.trim())!=null?l:"",s=(g=(m=e==null?void 0:e.referer)==null?void 0:m.trim())!=null?g:"",n=(i=e==null?void 0:e.now)!=null?i:new Date;return{sessionId:r,ephemeral:!1,utmParams:(d=e==null?void 0:e.utmParams)!=null?d:{},clickIds:(u=e==null?void 0:e.clickIds)!=null?u:{},deviceClass:t?I(t):"desktop",trafficSource:s?x(s,e==null?void 0:e.appOrigin):"direct",referrerDomain:C(s),timeOfDay:w(n),dayOfWeek:(f=["sun","mon","tue","wed","thu","fri","sat"][n.getDay()])!=null?f:"sun",automation:(e==null?void 0:e.webdriver)===!0||ne(t)}}function ie(r){return r?`_${r.slice(0,12)}`:""}var D="_snt_uid";function K(r){return`${D}${ie(r)}`}var h=require("@sentientui/policy");function O(r){return c(c(c({id:r.id},r.arms?{arms:[...r.arms]}:{}),r.dims?{dims:Object.fromEntries(Object.entries(r.dims).map(([e,t])=>[e,[...t]]))}:{}),r.baseline!==void 0?{baseline:r.baseline}:{})}function P(r){let e=O(r);return(0,h.slotResultFor)(e,(0,h.slotBaselineArm)(e))}function F(r){let e={};for(let t of r)e[t.id]=P(t);return e}var W=1e3;function A(r,e,t){let s=new AbortController,n=setTimeout(()=>s.abort(),t);return fetch(r,j(c({},e),{signal:s.signal})).finally(()=>clearTimeout(n))}async function z(r,e,t){var g;if(t.doNotTrack)return{};let s=(g=t.timeoutMs)!=null?g:W,n={"Content-Type":"application/json",Authorization:`Bearer ${t.apiKey}`};t.origin&&(n.Origin=t.origin);let o=c(c({},y(e,{userAgent:t.userAgent,referer:t.referer,utmParams:t.utmParams,clickIds:t.clickIds,appOrigin:t.origin})),t.persona?{persona:t.persona}:{});try{let i=await A(`${t.baseUrl}/sessions`,{method:"POST",headers:n,body:JSON.stringify(o)},s);if(i.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(!i.ok){let d=await i.json().catch(()=>({}));console.error(`[SentientUI] preloadAssignments: session upsert failed (${i.status})`,d)}}catch(i){console.error("[SentientUI] preloadAssignments: session upsert threw",i)}let l=await Promise.allSettled(r.map(async({id:i,variantIds:d})=>{let u=await A(`${t.baseUrl}/assign`,{method:"POST",headers:n,body:JSON.stringify({sessionId:e,componentId:i,variantIds:d})},s);if(!u.ok){let b=await u.json().catch(()=>({}));return console.error(`[SentientUI] preloadAssignments: assign failed for "${i}" (${u.status})`,b),null}let f=await u.json();return{id:i,variantId:f.variantId}})),m={};for(let i of l)i.status==="fulfilled"&&i.value&&(m[i.value.id]=i.value.variantId);return m}function J(r,e){var t,s,n,o;return(o=(n=e?(t=r.get(K(e)))==null?void 0:t.value:void 0)!=null?n:(s=r.get(D))==null?void 0:s.value)!=null?o:null}async function Y(r,e,t){var g,i,d,u,f,b,U,T,v,_,E;let s=(g=t.timeoutMs)!=null?g:W,n=(i=r.slots)!=null?i:[],o={layoutOrder:(d=r.sections)!=null?d:[],assignments:{},slots:F(n),persona:"unknown",confidence:0};if(t.doNotTrack)return o;let l={"Content-Type":"application/json",Authorization:`Bearer ${t.apiKey}`};t.origin&&(l.Origin=t.origin);let m=c(c({},y(e,{userAgent:t.userAgent,referer:t.referer,utmParams:t.utmParams,clickIds:t.clickIds,appOrigin:t.origin})),t.persona?{persona:t.persona}:{});try{let a=await A(`${t.baseUrl}/sessions`,{method:"POST",headers:l,body:JSON.stringify(m)},s);if(!a.ok){let p=await a.json().catch(()=>({}));console.error(`[SentientUI] preloadDecisions: session upsert failed (${a.status})`,p)}}catch(a){console.error("[SentientUI] preloadDecisions: session upsert threw",a)}try{let a=await A(`${t.baseUrl}/decide`,{method:"POST",headers:l,body:JSON.stringify(c(c({sessionId:e,sections:((u=r.sections)!=null?u:[]).map(S=>({id:S})),components:r.components},n.length>0?{slots:n.map(O)}:{}),t.persona?{persona:t.persona}:{}))},s);if(!a.ok){let S=await a.json().catch(()=>({}));return console.error(`[SentientUI] preloadDecisions: decide failed (${a.status})`,S),o}let p=await a.json(),B={};for(let S of n)B[S.id]=(b=(f=p.slots)==null?void 0:f[S.id])!=null?b:P(S);return{layoutOrder:(T=(U=p.layoutOrder)!=null?U:r.sections)!=null?T:[],assignments:(v=p.assignments)!=null?v:{},slots:B,persona:(_=p.persona)!=null?_:"unknown",confidence:(E=p.confidence)!=null?E:0}}catch(a){return console.error("[SentientUI] preloadDecisions: decide threw",a),o}}0&&(module.exports={CLICK_ID_KEYS,buildSessionUpsertPayload,deriveSessionSegment,detectDeviceClass,detectTimeOfDay,detectTrafficSource,extractTrackedParams,preloadAssignments,preloadDecisions,readSessionCookie,referrerDomainFromReferer});
|
|
2
2
|
//# sourceMappingURL=index-server.js.map
|
package/dist/index-server.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index-server.ts","../src/session-meta.ts","../src/storage-key.ts","../src/slots.ts","../src/server.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, readSessionCookie, preloadDecisions } from './server.js';\nexport type { ServerAssignConfig, ServerAssignments, DecideResult, SlotDeclInput, SlotResult } from './server.js';\n\nexport {\n deriveSessionSegment,\n buildSessionUpsertPayload,\n detectDeviceClass,\n detectTrafficSource,\n detectTimeOfDay,\n referrerDomainFromReferer,\n} from './session-meta.js';\nexport type { SessionUpsertPayload } from './session-meta.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): 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 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\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 deviceClass: string;\n trafficSource: 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 now?: Date;\n /** `navigator.webdriver` value from the browser, when available. */\n webdriver?: boolean;\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 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 };\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 * 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\nexport type { SlotDeclInput, SlotResult };\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 /** 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 * 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/** componentId → assigned variantId */\nexport type ServerAssignments = Record<string, string>;\n\ntype AssignResult = { variantId: string; assignmentTtlMs: number };\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 // Opted-out visitor (DNT/GPC): render defaults, mint no session (audit P4).\n if (config.doNotTrack) return {};\n\n const timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${config.apiKey}`,\n };\n if (config.origin) {\n headers.Origin = config.origin;\n }\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 appOrigin: config.origin,\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 { method: 'POST', headers, body: JSON.stringify({ sessionId, componentId: id, variantIds }) },\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 };\n }),\n );\n\n const assignments: ServerAssignments = {};\n for (const result of results) {\n if (result.status === 'fulfilled' && result.value) {\n assignments[result.value.id] = result.value.variantId;\n }\n }\n return assignments;\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};\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 },\n sessionId: string,\n config: ServerAssignConfig,\n): Promise<DecideResult> {\n const timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n const declaredSlots = params.slots ?? [];\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: Record<string, string> = {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${config.apiKey}`,\n };\n if (config.origin) headers.Origin = config.origin;\n\n const sessionBody = {\n ...buildSessionUpsertPayload(sessionId, {\n userAgent: config.userAgent,\n referer: config.referer,\n utmParams: config.utmParams,\n appOrigin: config.origin,\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 ...(config.persona ? { persona: config.persona } : {}),\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 persona?: string;\n confidence?: number;\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\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 };\n } catch (err) {\n console.error('[SentientUI] preloadDecisions: decide threw', err);\n return fallback;\n }\n}\n"],"mappings":"owBAAA,IAAAA,GAAA,GAAAC,EAAA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AAStB,EAAK,CACZ,eAAQ,MAAM,8CAA+CA,CAAG,EACzDwB,CACT,CACF","names":["index_server_exports","__export","buildSessionUpsertPayload","deriveSessionSegment","detectDeviceClass","detectTimeOfDay","detectTrafficSource","preloadAssignments","preloadDecisions","readSessionCookie","referrerDomainFromReferer","__toCommonJS","agentUaList","uaTokenMatch","userAgent","matchedAgentToken","_a","s","token","detectDeviceClass","userAgent","s","detectTrafficSource","referrer","appOrigin","refUrl","e","host","referrerDomainFromReferer","detectTimeOfDay","d","h","deriveSessionSegment","opts","body","buildSessionUpsertPayload","sessionId","_a","_b","_c","_d","_e","_f","_g","ua","referer","now","uaTokenMatch","storageSuffix","apiKey","LEGACY_SESSION_COOKIE_NAME","sessionCookieName","import_policy","toWireSlot","d","__spreadValues","dim","values","baselineResultFor","decl","baselineSlots","decls","out","DEFAULT_TIMEOUT_MS","fetchWithTimeout","url","init","timeoutMs","controller","timer","__spreadProps","__spreadValues","preloadAssignments","components","sessionId","config","_a","headers","sessionBody","buildSessionUpsertPayload","res","body","err","results","id","variantIds","assignments","result","readSessionCookie","cookies","apiKey","_b","_c","_d","sessionCookieName","LEGACY_SESSION_COOKIE_NAME","preloadDecisions","params","_e","_f","_g","_h","_i","_j","_k","declaredSlots","fallback","baselineSlots","sessionRes","toWireSlot","data","slots","d","baselineResultFor"]}
|
|
1
|
+
{"version":3,"sources":["../src/index-server.ts","../src/session-meta.ts","../src/storage-key.ts","../src/slots.ts","../src/server.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, readSessionCookie, preloadDecisions } from './server.js';\nexport type { ServerAssignConfig, ServerAssignments, 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","/** 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): 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 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 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 },\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 };\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 * 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\nexport type { SlotDeclInput, SlotResult };\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 /** 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 * 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/** componentId → assigned variantId */\nexport type ServerAssignments = Record<string, string>;\n\ntype AssignResult = { variantId: string; assignmentTtlMs: number };\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 // Opted-out visitor (DNT/GPC): render defaults, mint no session (audit P4).\n if (config.doNotTrack) return {};\n\n const timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${config.apiKey}`,\n };\n if (config.origin) {\n headers.Origin = config.origin;\n }\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 }),\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 { method: 'POST', headers, body: JSON.stringify({ sessionId, componentId: id, variantIds }) },\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 };\n }),\n );\n\n const assignments: ServerAssignments = {};\n for (const result of results) {\n if (result.status === 'fulfilled' && result.value) {\n assignments[result.value.id] = result.value.variantId;\n }\n }\n return assignments;\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};\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 },\n sessionId: string,\n config: ServerAssignConfig,\n): Promise<DecideResult> {\n const timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n const declaredSlots = params.slots ?? [];\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: Record<string, string> = {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${config.apiKey}`,\n };\n if (config.origin) headers.Origin = config.origin;\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 }),\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 ...(config.persona ? { persona: config.persona } : {}),\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 persona?: string;\n confidence?: number;\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\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 };\n } catch (err) {\n console.error('[SentientUI] preloadDecisions: decide threw', err);\n return fallback;\n }\n}\n"],"mappings":"uwBAAA,IAAAA,GAAA,GAAAC,EAAAD,GAAA,mBAAAE,EAAA,8BAAAC,EAAA,yBAAAC,EAAA,sBAAAC,EAAA,oBAAAC,EAAA,wBAAAC,EAAA,yBAAAC,EAAA,uBAAAC,EAAA,qBAAAC,EAAA,sBAAAC,EAAA,8BAAAC,IAAA,eAAAC,GAAAb,ICQO,IAAMc,GAAiC,CAC5C,SACA,eACA,gBACA,YACA,cACA,mBACA,gBACA,kBACA,kBACA,oBACA,qBACA,aACA,QACA,YACA,YACA,SACF,EAGO,SAASC,GAAaC,EAA4B,CACvD,OAAOC,GAAkBD,CAAS,IAAM,IAC1C,CAGO,SAASC,GAAkBD,EAAkC,CAjCpE,IAAAE,EAkCE,GAAI,CAACF,EAAW,OAAO,KACvB,IAAMG,EAAIH,EAAU,YAAY,EAChC,OAAOE,EAAAJ,GAAY,KAAMM,GAAUD,EAAE,SAASC,EAAM,YAAY,CAAC,CAAC,IAA3D,KAAAF,EAAgE,IACzE,CA8CO,SAASG,EAAkBC,EAA2B,CAC3D,IAAMC,EAAID,EAAU,YAAY,EAChC,MAAI,mCAAmC,KAAKC,CAAC,EAAU,SACnD,yCAAyC,KAAKA,CAAC,EAAU,SACtD,SACT,CAEO,SAASC,EAAoBC,EAAkBC,EAA4B,CAChF,GAAI,CAACD,EAAU,MAAO,SACtB,GAAI,CACF,IAAME,EAAS,IAAI,IAAIF,CAAQ,EAC/B,GAAIC,EACF,GAAI,CACF,GAAI,IAAI,IAAIA,CAAS,EAAE,OAASC,EAAO,KAAM,MAAO,QACtD,OAAQC,EAAA,CAER,CAEF,IAAMC,EAAOF,EAAO,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","detectTimeOfDay","detectTrafficSource","extractTrackedParams","preloadAssignments","preloadDecisions","readSessionCookie","referrerDomainFromReferer","__toCommonJS","agentUaList","uaTokenMatch","userAgent","matchedAgentToken","_a","s","token","detectDeviceClass","userAgent","s","detectTrafficSource","referrer","appOrigin","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","uaTokenMatch","storageSuffix","apiKey","LEGACY_SESSION_COOKIE_NAME","sessionCookieName","import_policy","toWireSlot","d","__spreadValues","dim","values","baselineResultFor","decl","baselineSlots","decls","out","DEFAULT_TIMEOUT_MS","fetchWithTimeout","url","init","timeoutMs","controller","timer","__spreadProps","__spreadValues","preloadAssignments","components","sessionId","config","_a","headers","sessionBody","buildSessionUpsertPayload","res","body","err","results","id","variantIds","assignments","result","readSessionCookie","cookies","apiKey","_b","_c","_d","sessionCookieName","LEGACY_SESSION_COOKIE_NAME","preloadDecisions","params","_e","_f","_g","_h","_i","_j","_k","declaredSlots","fallback","baselineSlots","sessionRes","toWireSlot","data","slots","d","baselineResultFor"]}
|
package/dist/index-server.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{b as
|
|
1
|
+
import{b as D,c as U,j,k as $,l as N,m as M,n as E,o as _,p as K,q as b,r as k,s as P,t as C}from"./chunk-2NVSFI4V.mjs";import{a as l,b as w}from"./chunk-TMCGHANO.mjs";var x=1e3;function A(r,i,e){let o=new AbortController,t=setTimeout(()=>o.abort(),e);return fetch(r,w(l({},i),{signal:o.signal})).finally(()=>clearTimeout(t))}async function B(r,i,e){var g;if(e.doNotTrack)return{};let o=(g=e.timeoutMs)!=null?g:x,t={"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`};e.origin&&(t.Origin=e.origin);let a=l(l({},b(i,{userAgent:e.userAgent,referer:e.referer,utmParams:e.utmParams,clickIds:e.clickIds,appOrigin:e.origin})),e.persona?{persona:e.persona}:{});try{let s=await A(`${e.baseUrl}/sessions`,{method:"POST",headers:t,body:JSON.stringify(a)},o);if(s.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(!s.ok){let p=await s.json().catch(()=>({}));console.error(`[SentientUI] preloadAssignments: session upsert failed (${s.status})`,p)}}catch(s){console.error("[SentientUI] preloadAssignments: session upsert threw",s)}let m=await Promise.allSettled(r.map(async({id:s,variantIds:p})=>{let c=await A(`${e.baseUrl}/assign`,{method:"POST",headers:t,body:JSON.stringify({sessionId:i,componentId:s,variantIds:p})},o);if(!c.ok){let f=await c.json().catch(()=>({}));return console.error(`[SentientUI] preloadAssignments: assign failed for "${s}" (${c.status})`,f),null}let y=await c.json();return{id:s,variantId:y.variantId}})),S={};for(let s of m)s.status==="fulfilled"&&s.value&&(S[s.value.id]=s.value.variantId);return S}function J(r,i){var e,o,t,a;return(a=(t=i?(e=r.get(U(i)))==null?void 0:e.value:void 0)!=null?t:(o=r.get(D))==null?void 0:o.value)!=null?a:null}async function F(r,i,e){var g,s,p,c,y,f,I,R,h,v,O;let o=(g=e.timeoutMs)!=null?g:x,t=(s=r.slots)!=null?s:[],a={layoutOrder:(p=r.sections)!=null?p:[],assignments:{},slots:C(t),persona:"unknown",confidence:0};if(e.doNotTrack)return a;let m={"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`};e.origin&&(m.Origin=e.origin);let S=l(l({},b(i,{userAgent:e.userAgent,referer:e.referer,utmParams:e.utmParams,clickIds:e.clickIds,appOrigin:e.origin})),e.persona?{persona:e.persona}:{});try{let n=await A(`${e.baseUrl}/sessions`,{method:"POST",headers:m,body:JSON.stringify(S)},o);if(!n.ok){let d=await n.json().catch(()=>({}));console.error(`[SentientUI] preloadDecisions: session upsert failed (${n.status})`,d)}}catch(n){console.error("[SentientUI] preloadDecisions: session upsert threw",n)}try{let n=await A(`${e.baseUrl}/decide`,{method:"POST",headers:m,body:JSON.stringify(l(l({sessionId:i,sections:((c=r.sections)!=null?c:[]).map(u=>({id:u})),components:r.components},t.length>0?{slots:t.map(k)}:{}),e.persona?{persona:e.persona}:{}))},o);if(!n.ok){let u=await n.json().catch(()=>({}));return console.error(`[SentientUI] preloadDecisions: decide failed (${n.status})`,u),a}let d=await n.json(),T={};for(let u of t)T[u.id]=(f=(y=d.slots)==null?void 0:y[u.id])!=null?f:P(u);return{layoutOrder:(R=(I=d.layoutOrder)!=null?I:r.sections)!=null?R:[],assignments:(h=d.assignments)!=null?h:{},slots:T,persona:(v=d.persona)!=null?v:"unknown",confidence:(O=d.confidence)!=null?O:0}}catch(n){return console.error("[SentientUI] preloadDecisions: decide threw",n),a}}export{M as CLICK_ID_KEYS,b as buildSessionUpsertPayload,K as deriveSessionSegment,j as detectDeviceClass,_ as detectTimeOfDay,$ as detectTrafficSource,E as extractTrackedParams,B as preloadAssignments,F as preloadDecisions,J as readSessionCookie,N as referrerDomainFromReferer};
|
|
2
2
|
//# sourceMappingURL=index-server.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/server.ts"],"sourcesContent":["/**\n * Server-side helpers for SSR variant pre-loading.\n * Pure fetch — no DOM APIs. Safe in Node.js, Edge, and Deno runtimes.\n */\nimport { buildSessionUpsertPayload } from './session-meta.js';\nimport { LEGACY_SESSION_COOKIE_NAME, sessionCookieName } from './storage-key.js';\nimport {\n toWireSlot,\n baselineResultFor,\n baselineSlots,\n type SlotDeclInput,\n type SlotResult,\n} from './slots.js';\n\nexport type { SlotDeclInput, SlotResult };\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 /** 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 * 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/** componentId → assigned variantId */\nexport type ServerAssignments = Record<string, string>;\n\ntype AssignResult = { variantId: string; assignmentTtlMs: number };\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 // Opted-out visitor (DNT/GPC): render defaults, mint no session (audit P4).\n if (config.doNotTrack) return {};\n\n const timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${config.apiKey}`,\n };\n if (config.origin) {\n headers.Origin = config.origin;\n }\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 appOrigin: config.origin,\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 { method: 'POST', headers, body: JSON.stringify({ sessionId, componentId: id, variantIds }) },\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 };\n }),\n );\n\n const assignments: ServerAssignments = {};\n for (const result of results) {\n if (result.status === 'fulfilled' && result.value) {\n assignments[result.value.id] = result.value.variantId;\n }\n }\n return assignments;\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};\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 },\n sessionId: string,\n config: ServerAssignConfig,\n): Promise<DecideResult> {\n const timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n const declaredSlots = params.slots ?? [];\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: Record<string, string> = {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${config.apiKey}`,\n };\n if (config.origin) headers.Origin = config.origin;\n\n const sessionBody = {\n ...buildSessionUpsertPayload(sessionId, {\n userAgent: config.userAgent,\n referer: config.referer,\n utmParams: config.utmParams,\n appOrigin: config.origin,\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 ...(config.persona ? { persona: config.persona } : {}),\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 persona?: string;\n confidence?: number;\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\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 };\n } catch (err) {\n console.error('[SentientUI] preloadDecisions: decide threw', err);\n return fallback;\n }\n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MAAM,KAAO,CAAC,EAAE,EAC9C,eAAQ,MAAM,iDAAiDA,EAAI,MAAM,IAAKC,CAAI,EAC3EyB,CACT,CACA,IAAMI,EAAQ,MAAM9B,EAAI,KAAK,EAQvB+B,EAAoC,CAAC,EAC3C,QAAWC,KAAKP,EAEdM,EAAMC,EAAE,EAAE,GAAIb,GAAAD,EAAAY,EAAK,QAAL,YAAAZ,EAAac,EAAE,MAAf,KAAAb,EAAsBc,EAAkBD,CAAC,EAGzD,MAAO,CACL,aAAaX,GAAAD,EAAAU,EAAK,cAAL,KAAAV,EAAoBH,EAAO,WAA3B,KAAAI,EAAuC,CAAC,EACrD,aAAaC,EAAAQ,EAAK,cAAL,KAAAR,EAAoB,CAAC,EAClC,MAAAS,EACA,SAASR,EAAAO,EAAK,UAAL,KAAAP,EAAgB,UACzB,YAAYC,EAAAM,EAAK,aAAL,KAAAN,EAAmB,CACjC,CACF,OAAStB,EAAK,CACZ,eAAQ,MAAM,8CAA+CA,CAAG,EACzDwB,CACT,CACF","names":["DEFAULT_TIMEOUT_MS","fetchWithTimeout","url","init","timeoutMs","controller","timer","__spreadProps","__spreadValues","preloadAssignments","components","sessionId","config","_a","headers","sessionBody","buildSessionUpsertPayload","res","body","err","results","id","variantIds","assignments","result","readSessionCookie","cookies","apiKey","_b","_c","_d","sessionCookieName","LEGACY_SESSION_COOKIE_NAME","preloadDecisions","params","_e","_f","_g","_h","_i","_j","_k","declaredSlots","fallback","baselineSlots","sessionRes","toWireSlot","data","slots","d","baselineResultFor"]}
|
|
1
|
+
{"version":3,"sources":["../src/server.ts"],"sourcesContent":["/**\n * Server-side helpers for SSR variant pre-loading.\n * Pure fetch — no DOM APIs. Safe in Node.js, Edge, and Deno runtimes.\n */\nimport { buildSessionUpsertPayload } from './session-meta.js';\nimport { LEGACY_SESSION_COOKIE_NAME, sessionCookieName } from './storage-key.js';\nimport {\n toWireSlot,\n baselineResultFor,\n baselineSlots,\n type SlotDeclInput,\n type SlotResult,\n} from './slots.js';\n\nexport type { SlotDeclInput, SlotResult };\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 /** 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 * 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/** componentId → assigned variantId */\nexport type ServerAssignments = Record<string, string>;\n\ntype AssignResult = { variantId: string; assignmentTtlMs: number };\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 // Opted-out visitor (DNT/GPC): render defaults, mint no session (audit P4).\n if (config.doNotTrack) return {};\n\n const timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${config.apiKey}`,\n };\n if (config.origin) {\n headers.Origin = config.origin;\n }\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 }),\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 { method: 'POST', headers, body: JSON.stringify({ sessionId, componentId: id, variantIds }) },\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 };\n }),\n );\n\n const assignments: ServerAssignments = {};\n for (const result of results) {\n if (result.status === 'fulfilled' && result.value) {\n assignments[result.value.id] = result.value.variantId;\n }\n }\n return assignments;\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};\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 },\n sessionId: string,\n config: ServerAssignConfig,\n): Promise<DecideResult> {\n const timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n const declaredSlots = params.slots ?? [];\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: Record<string, string> = {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${config.apiKey}`,\n };\n if (config.origin) headers.Origin = config.origin;\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 }),\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 ...(config.persona ? { persona: config.persona } : {}),\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 persona?: string;\n confidence?: number;\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\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 };\n } catch (err) {\n console.error('[SentientUI] preloadDecisions: decide threw', err);\n return fallback;\n }\n}\n"],"mappings":"wKA0EA,IAAMA,EAAqB,IAE3B,SAASC,EACPC,EACAC,EACAC,EACmB,CACnB,IAAMC,EAAa,IAAI,gBACjBC,EAAQ,WAAW,IAAMD,EAAW,MAAM,EAAGD,CAAS,EAC5D,OAAO,MAAMF,EAAKK,EAAAC,EAAA,GAAKL,GAAL,CAAW,OAAQE,EAAW,MAAO,EAAC,EAAE,QAAQ,IAChE,aAAaC,CAAK,CACpB,CACF,CAqBA,eAAsBG,EACpBC,EACAC,EACAC,EAC4B,CA/G9B,IAAAC,EAiHE,GAAID,EAAO,WAAY,MAAO,CAAC,EAE/B,IAAMR,GAAYS,EAAAD,EAAO,YAAP,KAAAC,EAAoBb,EAChCc,EAAkC,CACtC,eAAgB,mBAChB,cAAe,UAAUF,EAAO,MAAM,EACxC,EACIA,EAAO,SACTE,EAAQ,OAASF,EAAO,QAK1B,IAAMG,EAAcP,IAAA,GACfQ,EAA0BL,EAAW,CACtC,UAAWC,EAAO,UAClB,QAASA,EAAO,QAChB,UAAWA,EAAO,UAClB,SAAUA,EAAO,SACjB,UAAWA,EAAO,MACpB,CAAC,GACGA,EAAO,QAAU,CAAE,QAASA,EAAO,OAAQ,EAAI,CAAC,GAGtD,GAAI,CACF,IAAMK,EAAM,MAAMhB,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EA,GAAI,CACF,IAAMF,EAAM,MAAMhB,EAChB,GAAGW,EAAO,OAAO,UACjB,CACE,OAAQ,OACR,QAAAE,EACA,KAAM,KAAK,UAAUN,IAAA,CACnB,UAAAG,EACA,WAAWmB,EAAAI,EAAO,WAAP,KAAAJ,EAAmB,CAAC,GAAG,IAAKT,IAAQ,CAAE,GAAAA,CAAG,EAAE,EACtD,WAAYa,EAAO,YACfQ,EAAc,OAAS,EAAI,CAAE,MAAOA,EAAc,IAAII,CAAU,CAAE,EAAI,CAAC,GACvElC,EAAO,QAAU,CAAE,QAASA,EAAO,OAAQ,EAAI,CAAC,EACrD,CACH,EACAR,CACF,EACA,GAAI,CAACa,EAAI,GAAI,CACX,IAAMC,EAAO,MAAMD,EAAI,KAAK,EAAE,MAAM,KAAO,CAAC,EAAE,EAC9C,eAAQ,MAAM,iDAAiDA,EAAI,MAAM,IAAKC,CAAI,EAC3EyB,CACT,CACA,IAAMI,EAAQ,MAAM9B,EAAI,KAAK,EAQvB+B,EAAoC,CAAC,EAC3C,QAAWC,KAAKP,EAEdM,EAAMC,EAAE,EAAE,GAAIb,GAAAD,EAAAY,EAAK,QAAL,YAAAZ,EAAac,EAAE,MAAf,KAAAb,EAAsBc,EAAkBD,CAAC,EAGzD,MAAO,CACL,aAAaX,GAAAD,EAAAU,EAAK,cAAL,KAAAV,EAAoBH,EAAO,WAA3B,KAAAI,EAAuC,CAAC,EACrD,aAAaC,EAAAQ,EAAK,cAAL,KAAAR,EAAoB,CAAC,EAClC,MAAAS,EACA,SAASR,EAAAO,EAAK,UAAL,KAAAP,EAAgB,UACzB,YAAYC,EAAAM,EAAK,aAAL,KAAAN,EAAmB,CACjC,CACF,OAAStB,EAAK,CACZ,eAAQ,MAAM,8CAA+CA,CAAG,EACzDwB,CACT,CACF","names":["DEFAULT_TIMEOUT_MS","fetchWithTimeout","url","init","timeoutMs","controller","timer","__spreadProps","__spreadValues","preloadAssignments","components","sessionId","config","_a","headers","sessionBody","buildSessionUpsertPayload","res","body","err","results","id","variantIds","assignments","result","readSessionCookie","cookies","apiKey","_b","_c","_d","sessionCookieName","LEGACY_SESSION_COOKIE_NAME","preloadDecisions","params","_e","_f","_g","_h","_i","_j","_k","declaredSlots","fallback","baselineSlots","sessionRes","toWireSlot","data","slots","d","baselineResultFor"]}
|
package/dist/index-topics.d.cts
CHANGED
|
@@ -1,6 +1,21 @@
|
|
|
1
1
|
import { T as TopicRule, a as SectionFeatures } from './classify-DYlSjkFP.cjs';
|
|
2
2
|
export { b as SemanticType } from './classify-DYlSjkFP.cjs';
|
|
3
3
|
|
|
4
|
+
/**
|
|
5
|
+
* Version of the classification BEHAVIOUR (rules + taxonomy + stages), read by
|
|
6
|
+
* the server's shadow-label rollout (section-classify.ts): a project whose
|
|
7
|
+
* promoted version differs gets new labels written to SHADOW only, while its
|
|
8
|
+
* old labels keep serving until an operator promotes (with one-click rollback,
|
|
9
|
+
* the A4 pattern).
|
|
10
|
+
*
|
|
11
|
+
* BUMP THIS whenever a change here or in ./classify.ts alters what any section
|
|
12
|
+
* would be labelled — rule edits, threshold changes, new stages, taxonomy
|
|
13
|
+
* moves. Comment-only and refactor-only changes do not bump. The corpus gates
|
|
14
|
+
* catch accuracy regressions; this constant is what keeps a deliberate
|
|
15
|
+
* improvement from silently re-labelling every live project's serving rows on
|
|
16
|
+
* their next audit.
|
|
17
|
+
*/
|
|
18
|
+
declare const CLASSIFIER_VERSION = "2026-09-05";
|
|
4
19
|
declare const CLASSIFIER_TOPICS: readonly TopicRule[];
|
|
5
20
|
/** Which classifier stage produced the label. Persisted as provenance (the
|
|
6
21
|
* `page_semantics.source` column distinguishes structured_data from
|
|
@@ -18,4 +33,4 @@ declare function classifyTopic(f: SectionFeatures): TopicRule & {
|
|
|
18
33
|
stage: ClassifierStage;
|
|
19
34
|
};
|
|
20
35
|
|
|
21
|
-
export { CLASSIFIER_TOPICS, SectionFeatures, TopicRule, classifyTopic };
|
|
36
|
+
export { CLASSIFIER_TOPICS, CLASSIFIER_VERSION, SectionFeatures, TopicRule, classifyTopic };
|
package/dist/index-topics.d.ts
CHANGED
|
@@ -1,6 +1,21 @@
|
|
|
1
1
|
import { T as TopicRule, a as SectionFeatures } from './classify-DYlSjkFP.js';
|
|
2
2
|
export { b as SemanticType } from './classify-DYlSjkFP.js';
|
|
3
3
|
|
|
4
|
+
/**
|
|
5
|
+
* Version of the classification BEHAVIOUR (rules + taxonomy + stages), read by
|
|
6
|
+
* the server's shadow-label rollout (section-classify.ts): a project whose
|
|
7
|
+
* promoted version differs gets new labels written to SHADOW only, while its
|
|
8
|
+
* old labels keep serving until an operator promotes (with one-click rollback,
|
|
9
|
+
* the A4 pattern).
|
|
10
|
+
*
|
|
11
|
+
* BUMP THIS whenever a change here or in ./classify.ts alters what any section
|
|
12
|
+
* would be labelled — rule edits, threshold changes, new stages, taxonomy
|
|
13
|
+
* moves. Comment-only and refactor-only changes do not bump. The corpus gates
|
|
14
|
+
* catch accuracy regressions; this constant is what keeps a deliberate
|
|
15
|
+
* improvement from silently re-labelling every live project's serving rows on
|
|
16
|
+
* their next audit.
|
|
17
|
+
*/
|
|
18
|
+
declare const CLASSIFIER_VERSION = "2026-09-05";
|
|
4
19
|
declare const CLASSIFIER_TOPICS: readonly TopicRule[];
|
|
5
20
|
/** Which classifier stage produced the label. Persisted as provenance (the
|
|
6
21
|
* `page_semantics.source` column distinguishes structured_data from
|
|
@@ -18,4 +33,4 @@ declare function classifyTopic(f: SectionFeatures): TopicRule & {
|
|
|
18
33
|
stage: ClassifierStage;
|
|
19
34
|
};
|
|
20
35
|
|
|
21
|
-
export { CLASSIFIER_TOPICS, SectionFeatures, TopicRule, classifyTopic };
|
|
36
|
+
export { CLASSIFIER_TOPICS, CLASSIFIER_VERSION, SectionFeatures, TopicRule, classifyTopic };
|
package/dist/index-topics.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var p=Object.defineProperty,
|
|
1
|
+
"use strict";var p=Object.defineProperty,h=Object.defineProperties,w=Object.getOwnPropertyDescriptor,v=Object.getOwnPropertyDescriptors,T=Object.getOwnPropertyNames,l=Object.getOwnPropertySymbols;var g=Object.prototype.hasOwnProperty,S=Object.prototype.propertyIsEnumerable;var b=(e,t,r)=>t in e?p(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,n=(e,t)=>{for(var r in t||(t={}))g.call(t,r)&&b(e,r,t[r]);if(l)for(var r of l(t))S.call(t,r)&&b(e,r,t[r]);return e},i=(e,t)=>h(e,v(t));var x=(e,t)=>{for(var r in t)p(e,r,{get:t[r],enumerable:!0})},_=(e,t,r,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of T(t))!g.call(e,o)&&o!==r&&p(e,o,{get:()=>t[o],enumerable:!(s=w(t,o))||s.enumerable});return e};var R=e=>_(p({},"__esModule",{value:!0}),e);var I={};x(I,{CLASSIFIER_TOPICS:()=>u,CLASSIFIER_VERSION:()=>m,classifyTopic:()=>y});module.exports=R(I);var C={banner:"hero",navigation:"navigation",contentinfo:"footer"};function d(e){let t=e.ariaRole?C[e.ariaRole.toLowerCase()]:void 0;if(t)return t;if(e.tag==="nav")return"navigation";if(e.tag==="footer")return"footer";if(e.tag==="header")return e.actionCount>=5?"navigation":"hero";let r=`${e.idClass} ${e.headingText}`.toLowerCase();return/\b(navbar|nav-bar|navigation|site-nav|main-nav|topbar|footer)\b/.test(r)?/footer/.test(r)?"footer":"navigation":/\b(hero|masthead|jumbotron)\b/i.test(e.idClass)?"hero":null}function f(e){return e.actionCount>=1&&e.textLength>0&&e.textLength<200?"cta":"generic"}var m="2026-09-05",u=[{topic:"navigation",parent:"navigation",role:"structural"},{topic:"footer",parent:"navigation",role:"structural"},{topic:"breadcrumb",parent:"navigation",role:"structural"},{topic:"cookie_banner",parent:"navigation",role:"structural"},{topic:"hero",parent:"hero",role:"converter"},{topic:"pricing_plans",parent:"pricing",role:"converter"},{topic:"quote",parent:"pricing",role:"converter"},{topic:"financing",parent:"pricing",role:"persuader"},{topic:"faq",parent:"faq",role:"persuader"},{topic:"comparison",parent:"comparison",role:"persuader"},{topic:"reviews",parent:"social_proof",role:"persuader"},{topic:"testimonials",parent:"social_proof",role:"persuader"},{topic:"case_study",parent:"social_proof",role:"persuader"},{topic:"brands",parent:"social_proof",role:"persuader"},{topic:"awards",parent:"social_proof",role:"persuader"},{topic:"gallery",parent:"social_proof",role:"persuader"},{topic:"stats",parent:"social_proof",role:"persuader"},{topic:"insurance",parent:"trust",role:"persuader"},{topic:"warranty",parent:"trust",role:"persuader"},{topic:"certifications",parent:"trust",role:"persuader"},{topic:"security",parent:"trust",role:"persuader"},{topic:"guarantee",parent:"trust",role:"persuader"},{topic:"about",parent:"trust",role:"persuader"},{topic:"team",parent:"trust",role:"persuader"},{topic:"services",parent:"features",role:"persuader"},{topic:"features",parent:"features",role:"persuader"},{topic:"process",parent:"features",role:"persuader"},{topic:"menu",parent:"features",role:"persuader"},{topic:"inventory",parent:"features",role:"converter"},{topic:"integrations",parent:"features",role:"persuader"},{topic:"booking",parent:"cta",role:"converter"},{topic:"contact_form",parent:"cta",role:"converter"},{topic:"newsletter",parent:"cta",role:"converter"},{topic:"hours",parent:"cta",role:"persuader"},{topic:"location",parent:"cta",role:"persuader"},{topic:"cta",parent:"cta",role:"converter"},{topic:"blog",parent:"generic",role:"persuader"},{topic:"careers",parent:"generic",role:"persuader"},{topic:"legal",parent:"generic",role:"persuader"},{topic:"generic",parent:"generic",role:"persuader"}],k=new Map(u.map(e=>[e.topic,e]));function c(e){var t;return(t=k.get(e))!=null?t:{topic:"generic",parent:"generic",role:"persuader"}}var E=[["cookie_banner",/\bcookies?\b[^.]{0,20}\b(banner|notice|consent|policy)\b|consent banner/i],["breadcrumb",/\bbreadcrumbs?\b/i],["insurance",/\b(insurance|insurer|insured)\b/i],["warranty",/\b(warrant(y|ies)|guarantees?|guaranteed)\b/i],["certifications",/\b(certifi|accredit|licen[cs]ed)\b|approved by|iso ?\d/i],["security",/\b(security|privacy|compliance|gdpr|encrypt)\b|soc ?2/i],["about",/why choose|why us|about us|our story|who we are|years? (of )?(experience|serving)/i],["team",/our team|meet the team|our people|our staff/i],["reviews",/\b(reviews?|ratings?|testimonial)\b|what our customers say/i],["brands",/\b(brands?|partners?|manufacturers?|logos)\b|we work with|trusted by|loved by/i],["gallery",/\b(galler(y|ies)|photos?)\b|before and after/i],["case_study",/case stud|selected work|portfolio|our projects?|recent work/i],["awards",/\b(awards?|accolades?)\b/i],["pricing_plans",/\b(pricing|price list|per month|\/mo|subscriptions?)\b|\bplans?\b(?=[^.]{0,40}(from|start|month|year|[$€£]))/i],["quote",/get a quote|request a quote|free estimate|get an estimate/i],["financing",/\b(financ(e|ing)|instal?ments?)\b|payment plan|pay monthly/i],["booking",/\b(book|booking|reserve|reservation|appointments?)\b|schedule a/i],["newsletter",/\b(newsletter|subscribe)\b|join our (list|mailing)|mailing list/i],["contact_form",/contact us|get in touch|start a project|\benquir|\binquir|send us/i],["hours",/opening hours|\bhours\b|open (mon|tue|wed|thu|fri|sat|sun)/i],["location",/find us|our location|directions|where we are|visit us/i],["menu",/\b(menus?|dishes)\b|our food/i],["inventory",/\bbest ?sellers?\b|\b(shop|products?|collection)\b|our range|in stock/i],["process",/our process|how it works|the process|what to expect|\bsteps?\b/i],["services",/\b(services?|repairs?|treatments?|specialit|specialt)\b|what we (do|offer)/i],["integrations",/\bintegrations?\b|works with|connects? to/i],["features",/\b(features?|benefits?|capabilit)\b|what you get/i],["faq",/\bfaq\b|frequently asked|common questions?/i],["comparison",/\b(compare|comparison|versus)\b|\bvs\./i],["blog",/\b(blog|news|articles?|insights?)\b/i],["careers",/\b(careers?|jobs?)\b|join (the|our) team|we.re hiring/i],["legal",/\bterms\b|privacy policy|cookie policy|\blegal\b/i]],A={FAQPage:"faq",Question:"faq",Review:"reviews",AggregateRating:"reviews",Offer:"pricing_plans",AggregateOffer:"pricing_plans",PriceSpecification:"pricing_plans",Service:"services",Product:"inventory",ItemList:"inventory",Menu:"menu",MenuSection:"menu",LocalBusiness:"location",PostalAddress:"location",OpeningHoursSpecification:"hours",BreadcrumbList:"breadcrumb",ImageGallery:"gallery",JobPosting:"careers",BlogPosting:"blog",Article:"blog",Organization:"about"},q=[["pricing_plans",/(?:[$€£]\s?\d[\d,.]*\s*(?:\/|per\s)\s*(?:mo|month|yr|year|seat|user))|(?:\b(?:starter|basic|pro|growth|premium|enterprise)\b[^.]{0,60}[$€£]\s?\d)/i],["reviews",/(?:★{2,})|(?:\b\d(?:\.\d)?\s*(?:out of|\/)\s*5\b)|(?:\brated\b)|(?:["“][^"”]{20,160}["”]\s*[—–-]\s*[A-Z][a-z]+)/],["guarantee",/\b(?:money[- ]back guarantee|free returns?|returns? within|refund(?:s)? within|cancel anytime)\b/i],["security",/\b(?:encrypted|soc ?2|iso ?27001|gdpr[- ]compliant)\b/i],["comparison",/\b(?:vs|versus)\b\.?[^.!?]{0,80}\b(?:compare|comparison|plans?|features?|alternative)\b|\bhow (?:we|it) compares?\b/i]];function y(e){var s;let t=d(e);if(t)return i(n({},c(t)),{strength:"strong",stage:"structural"});for(let o of(s=e.structuredTypes)!=null?s:[]){let a=A[o];if(a)return i(n({},c(a)),{strength:"strong",stage:"structured_data"})}let r=`${e.idClass} ${e.headingText}`.toLowerCase();for(let[o,a]of E)if(a.test(r))return i(n({},c(o)),{strength:"strong",stage:"keyword"});for(let[o,a]of q)if(a.test(e.bodyText))return i(n({},c(o)),{strength:"strong",stage:"content"});return i(n({},c(f(e))),{strength:"weak",stage:"fallback"})}0&&(module.exports={CLASSIFIER_TOPICS,CLASSIFIER_VERSION,classifyTopic});
|
|
2
2
|
//# sourceMappingURL=index-topics.js.map
|