@sentientui/react 0.8.4 → 0.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +13 -0
- package/dist/index.d.cts +81 -1
- package/dist/index.d.ts +81 -1
- package/dist/index.js +3 -1
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +3 -1
- package/dist/index.mjs.map +1 -1
- package/dist/next/adaptive-root-client.d.ts +1 -61
- package/dist/next/adaptive-root-client.js +1 -1
- package/dist/next/adaptive-root-client.js.map +1 -1
- package/dist/next/adaptive-root.d.ts +101 -1
- package/dist/next/adaptive-root.js +3 -1
- package/dist/next/adaptive-root.js.map +1 -1
- package/package.json +2 -2
package/dist/index.mjs
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
1
|
'use client';
|
|
2
|
-
var ue=Object.defineProperty;var Q=Object.getOwnPropertySymbols;var de=Object.prototype.hasOwnProperty,ge=Object.prototype.propertyIsEnumerable;var Y=(e,t,n)=>t in e?ue(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,H=(e,t)=>{for(var n in t||(t={}))de.call(t,n)&&Y(e,n,t[n]);if(Q)for(var n of Q(t))ge.call(t,n)&&Y(e,n,t[n]);return e};import{createContext as fe,useContext as T,useEffect as ee,useMemo as me,useState as te}from"react";import{detectDeviceClass as pe,detectTrafficSource as ve,init as ye}from"@sentientui/core";var Z=new Map,D=new Map;function B(e,t){let n=D.get(e);return n||(n=new Set,D.set(e,n)),n.add(t),()=>{n.delete(t),n.size===0&&D.delete(e)}}function J(e,t){Z.set(e,t);let n=D.get(e);if(n)for(let s of n)try{s(t)}catch(i){}}function X(e){var t;return(t=Z.get(e))!=null?t:null}import{jsx as be}from"react/jsx-runtime";function he(){var e,t;if(typeof window=="undefined")return"desktop:direct";try{let n=pe((e=navigator.userAgent)!=null?e:""),s=ve((t=document.referrer)!=null?t:"",window.location.origin);return`${n}:${s}`}catch(n){return"desktop:direct"}}var O=fe({client:null,apiKey:"",initialAssignments:{},sessionSegment:"desktop:direct",ssrFallback:"first",onAssignment:void 0,initialLayoutOrder:null});function Se(e){var c;let[t,n]=te(null),[s]=te(()=>{var a;return(a=e.sessionSegment)!=null?a:he()});ee(()=>{if(e.consent===!1&&!e.preConsentBehavior){n(m=>(m==null||m.destroy(),null));return}let a=ye({apiKey:e.apiKey,context:e.context,debug:e.debug,initialAssignments:e.initialAssignments,sessionSegment:s,consent:e.consent,preConsentBehavior:e.preConsentBehavior,ssrSessionId:e.ssrSessionId});return n(a),()=>{a.destroy()}},[e.consent]),ee(()=>{if(!t)return;let a=!1,m=async()=>{if(a)return;let x;try{x=await t.fetchWeights()}catch(o){return}if(!a)for(let o of x){let L={componentId:o.componentId,updatedAt:o.updatedAt,variants:o.variants.map(u=>{var p;return{variantId:u.variantId,pulls:u.pulls,avgReward:(p=u.avgReward)!=null?p:0}})};J(o.componentId,L)}};m();let w=setInterval(()=>{m()},6e4);return()=>{a=!0,clearInterval(w)}},[t]);let i=(c=e.ssrFallback)!=null?c:"first",A=me(()=>{var a,m;return{client:t,apiKey:e.apiKey,initialAssignments:(a=e.initialAssignments)!=null?a:{},sessionSegment:s,ssrFallback:i,onAssignment:e.onAssignment,initialLayoutOrder:(m=e.initialLayoutOrder)!=null?m:null}},[t,e.apiKey,e.initialAssignments,s,i,e.onAssignment,e.initialLayoutOrder]);return be(O.Provider,{value:A,children:e.children})}function E(){return T(O).client}function N(){return T(O).apiKey}function z(){return T(O).initialAssignments}function K(){return T(O).sessionSegment}function ne(){return T(O).ssrFallback}function V(){return T(O).onAssignment}function Ae(){return T(O).initialLayoutOrder}import{memo as Ce,useEffect as M,useMemo as oe,useRef as j,useState as Ie}from"react";import{attachMicroSignalDetectors as ke}from"@sentientui/core";import{useEffect as U,useRef as ie,useState as we}from"react";function xe(e){var n;if(typeof window=="undefined")return null;let t=(n=window.__sentient_overrides)==null?void 0:n[e];if(t)return t;try{let s=new URLSearchParams(window.location.search);for(let i of s.getAll("sentient_variant")){let A=i.indexOf(":");if(A!==-1&&i.slice(0,A)===e)return i.slice(A+1)}}catch(s){}return null}function re(e,t){var s;let n=null;for(let i of e.variants)t.includes(i.variantId)&&(!n||i.avgReward>n.avgReward)&&(n={variantId:i.variantId,avgReward:i.avgReward});return(s=n==null?void 0:n.variantId)!=null?s:null}function q(e,t,n,s){let i=z(),A=ne(),c=E(),a=K(),m=V(),w=ie(null),x=xe(e),o=x&&t.includes(x)?x:null,L=ie(null);o&&L.current!==o&&(L.current=o,console.info(`[sentient] override active: ${e} -> ${o}`));let u=(()=>{var r,l;if(o)return{variantId:o,content:null,isLoading:!1};if(!c){let g=i[e];return g&&t.includes(g)?{variantId:g,content:null,isLoading:!1}:A==="first"&&t.length>0?{variantId:t[0],content:null,isLoading:!1}:{variantId:null,content:null,isLoading:!0}}let d=c.getAssignment(e,a);if(d&&(t.includes(d.variantId)||d.content))return{variantId:d.variantId,content:(r=d.content)!=null?r:null,isLoading:!1};let v=X(e);if(v){let g=re(v,t);if(g)return{variantId:g,content:null,isLoading:!1}}return{variantId:(l=t[0])!=null?l:null,content:null,isLoading:!1}})(),[p,y]=we(u),G=d=>{m&&w.current!==d&&(w.current=d,m(e,d))};return U(()=>{var v;if(o||!c)return;let d=c.getAssignment(e,a);if(d&&(t.includes(d.variantId)||d.content)){y({variantId:d.variantId,content:(v=d.content)!=null?v:null,isLoading:!1}),G(d.variantId);return}y(r=>{var l;return r.variantId?r:{variantId:(l=t[0])!=null?l:null,content:null,isLoading:!1}})},[o,c,e,a]),U(()=>{if(o||!c)return;let d=c.getAssignment(e,a);if(d&&t.includes(d.variantId))return;let v=!1;return c.assign(e,t,n,s).then(r=>{var l;v||r&&(!t.includes(r.variantId)&&!r.content||(y({variantId:r.variantId,content:(l=r.content)!=null?l:null,isLoading:!1}),G(r.variantId)))}),()=>{v=!0}},[o,c,e,a]),U(()=>{if(!o&&c)return B(e,d=>{var l;let v=c.getAssignment(e,a);if(v&&(t.includes(v.variantId)||v.content)){y({variantId:v.variantId,content:(l=v.content)!=null?l:null,isLoading:!1});return}let r=re(d,t);r&&y({variantId:r,content:null,isLoading:!1})})},[o,c,e,a]),o?{variantId:o,content:null,isLoading:!1}:p}import{jsx as Te}from"react/jsx-runtime";function Ee(e){return typeof e=="string"?{type:"click"}:e}var Le=3e4;function Ge(e,t){try{let n=`_snt_pv_${e}_${t}`;return sessionStorage.getItem(n)?!1:(sessionStorage.setItem(n,"1"),!0)}catch(n){return!0}}function Re(e){if(!(e instanceof Element))return!1;let t=e.tagName.toLowerCase();return t==="a"||t==="button"?!0:e.getAttribute("role")==="button"}function se(e,t,n){if(n){try{let i=e;for(;i&&i!==t;){if(i.matches(n))return!0;i=i.parentElement}}catch(i){}return!1}let s=e;for(;s&&s!==t;){if(Re(s))return!0;s=s.parentElement}return!1}function _e(e){var d,v;let t=E(),n=N(),s=oe(()=>Object.keys(e.variants),[e.variants]),{variantId:i,content:A}=q(e.id,s,e.agentData,e.agentDataByVariant),c=j(null),[a,m]=Ie(!1);M(()=>{m(!0)},[]);let w=j(!1),x=j(new Set),o=j(null),L=typeof e.goal=="string"?e.goal:JSON.stringify(e.goal),u=oe(()=>Ee(e.goal),[L]),p=typeof e.goal=="string"?e.goal:u.type;if(M(()=>{var g,I;if(!t||!i||!n||o.current===i)return;let r=(I=(g=c.current)==null?void 0:g.innerHTML)!=null?I:"";if(!r)return;o.current=i;let l=r!==""&&Ge(e.id,i);t.track({projectId:n,componentId:e.id,variantId:i,eventType:"variant_assigned",payload:l?{previewHtml:r.slice(0,Le)}:{}})},[t,i,n,e.id,a,A]),M(()=>{w.current=!1,x.current=new Set},[i,u]),M(()=>{if(!t||!i)return;let r=c.current;if(!r)return;let l=null,g=0,I=()=>{g=Date.now(),l=setTimeout(()=>{t.track({projectId:n,componentId:e.id,variantId:i,eventType:"cursor_signal",payload:{hoverDuration:Date.now()-g}}),l=null},800)},h=()=>{l!==null&&(clearTimeout(l),l=null)};return r.addEventListener("mouseenter",I),r.addEventListener("mouseleave",h),()=>{r.removeEventListener("mouseenter",I),r.removeEventListener("mouseleave",h),l!==null&&clearTimeout(l)}},[t,i,n,e.id]),M(()=>{if(!t||!i)return;let r=c.current;if(!r)return;let l=Date.now();return ke((g,I={})=>{var f,b,k;t.track({projectId:n,componentId:e.id,variantId:i,eventType:"micro_signal",payload:H({signalType:g},I)});let h=(f=e.microSignalGoals)==null?void 0:f[g];if(!h||x.current.has(g))return;x.current.add(g);let W=typeof h=="string"?h:h.name,S=typeof h=="string"?1:(b=h.weight)!=null?b:1,C=typeof h=="string"?0:(k=h.stepIndex)!=null?k:0;t.goal(W,H({signalType:g},I),S,C)},r,l)},[t,i,n,e.id,e.microSignalGoals]),M(()=>{if(!t||!i)return;let r=c.current;if(!r)return;if(u.type==="weighted_composite"){let S=new Set,C=[];return u.steps.forEach(({goal:f,name:b,weight:k},F)=>{let $=()=>{S.has(F)||(S.add(F),t.track({projectId:n,componentId:e.id,variantId:i,eventType:"goal_achieved",goalType:b,payload:{reward:k}}),t.goal(b,{},k,F))};if(f.type==="click"){let R=_=>{let P=_.target;P instanceof Element&&se(P,r,f.selector)&&$()};r.addEventListener("click",R),C.push(()=>r.removeEventListener("click",R));return}if(f.type==="form_submit"){let R=_=>{_.target instanceof HTMLFormElement&&r.contains(_.target)&&$()};r.addEventListener("submit",R),C.push(()=>r.removeEventListener("submit",R));return}if(f.type==="scroll_depth"){let R=Math.max(0,Math.min(1,f.threshold)),_=new IntersectionObserver(P=>{for(let ce of P)if(ce.intersectionRatio>=R){$(),_.disconnect();break}},{threshold:[R]});_.observe(r),C.push(()=>_.disconnect())}}),()=>{for(let f of C)f()}}let l=()=>{w.current||(w.current=!0,t.track({projectId:n,componentId:e.id,variantId:i,eventType:"goal_achieved",goalType:p,payload:{reward:1}}),t.goal(p,{componentId:e.id,variantId:i},1,0))},g=u.type==="composite"?u.all:[u],I=new Set(g.map((S,C)=>C)),h=S=>{I.delete(S),I.size===0&&l()},W=[];return g.forEach((S,C)=>{if(S.type==="click"){let f=b=>{let k=b.target;k instanceof Element&&se(k,r,S.selector)&&(u.type==="composite"?h(C):l())};r.addEventListener("click",f),W.push(()=>r.removeEventListener("click",f));return}if(S.type==="form_submit"){let f=b=>{b.target instanceof HTMLFormElement&&r.contains(b.target)&&(u.type==="composite"?h(C):l())};r.addEventListener("submit",f),W.push(()=>r.removeEventListener("submit",f));return}if(S.type==="scroll_depth"){let f=Math.max(0,Math.min(1,S.threshold)),b=new IntersectionObserver(k=>{for(let F of k)if(F.intersectionRatio>=f){u.type==="composite"?h(C):l(),b.disconnect();break}},{threshold:[f]});b.observe(r),W.push(()=>b.disconnect());return}}),()=>{for(let S of W)S()}},[t,i,n,e.id,u,p]),e.clientOnly&&(!a||!t)||!i)return null;let y=(d=e.variants[i])!=null?d:null,G=y===null?A:null;return((v=process==null?void 0:process.env)==null?void 0:v.NODE_ENV)!=="production"&&y===null&&G===null&&console.warn(`[sentient] <Adaptive id="${e.id}"> was assigned variant "${i}" but no matching key exists in props.variants. If this is a dashboard-managed text variant, use <AdaptiveText id="${e.id}"> instead.`),Te("div",{ref:c,"data-sentient-id":e.id,"data-sentient-variant":i,children:y!=null?y:G})}var Oe=Ce(_e,(e,t)=>{if(e.id!==t.id||JSON.stringify(e.goal)!==JSON.stringify(t.goal)||e.microSignalGoals!==t.microSignalGoals)return!1;if(e.variants===t.variants)return!0;let n=Object.keys(e.variants),s=Object.keys(t.variants);return n.length!==s.length?!1:n.every(i=>i in t.variants)});import{useEffect as ae,useRef as We,useState as le}from"react";import{jsx as Fe}from"react/jsx-runtime";function Me({id:e,default:t,component:n="span",className:s}){let i=E(),A=N(),c=V(),a=K(),m=We(null),[w,x]=le(()=>{var u,p;return(p=(u=i==null?void 0:i.getAssignment(e,a))==null?void 0:u.content)!=null?p:null}),[o,L]=le(()=>{var u,p;return(p=(u=i==null?void 0:i.getAssignment(e,a))==null?void 0:u.variantId)!=null?p:null});return ae(()=>{var p;if(!i||((p=i.getAssignment(e,a))==null?void 0:p.content)!==void 0)return;let u=!1;return i.assign(e).then(y=>{var G;if(!u){if(!y){((G=process==null?void 0:process.env)==null?void 0:G.NODE_ENV)!=="production"&&console.warn(`[sentient] <AdaptiveText id="${e}"> assignment failed \u2014 showing default text.`);return}L(y.variantId),y.content&&x(y.content)}}),()=>{u=!0}},[i,e,a]),ae(()=>{!i||!o||!A||m.current!==o&&(m.current=o,i.track({projectId:A,componentId:e,variantId:o,eventType:"variant_assigned",payload:{}}),c==null||c(e,o))},[i,o,A,e,c]),Fe(n,{className:s,children:w!=null?w:t})}import{useCallback as Pe}from"react";function De(e){let t=E();return Pe((n,s)=>{t==null||t.componentGoal(e,n,s)},[t,e])}import{deriveSessionSegment as Ne}from"@sentientui/core";export{Oe as Adaptive,Se as AdaptiveProvider,Me as AdaptiveText,Ne as detectSegment,X as getWeights,B as subscribeWeights,J as updateWeights,De as useAdaptiveGoal,q as useAssignment,z as useInitialAssignments,Ae as useLayoutOrder,E as useSentient};
|
|
2
|
+
var me=Object.defineProperty,pe=Object.defineProperties;var ve=Object.getOwnPropertyDescriptors;var Y=Object.getOwnPropertySymbols;var ye=Object.prototype.hasOwnProperty,he=Object.prototype.propertyIsEnumerable;var Z=(e,t,n)=>t in e?me(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,_=(e,t)=>{for(var n in t||(t={}))ye.call(t,n)&&Z(e,n,t[n]);if(Y)for(var n of Y(t))he.call(t,n)&&Z(e,n,t[n]);return e},P=(e,t)=>pe(e,ve(t));import{createContext as Ae,useContext as T,useEffect as te,useMemo as Se,useState as ne}from"react";import{detectDeviceClass as be,detectTrafficSource as ke,init as we}from"@sentientui/core";var ee=new Map,j=new Map;function H(e,t){let n=j.get(e);return n||(n=new Set,j.set(e,n)),n.add(t),()=>{n.delete(t),n.size===0&&j.delete(e)}}function X(e,t){ee.set(e,t);let n=j.get(e);if(n)for(let o of n)try{o(t)}catch(i){}}function z(e){var t;return(t=ee.get(e))!=null?t:null}import{jsx as Ie}from"react/jsx-runtime";function xe(){var e,t;if(typeof window=="undefined")return"desktop:direct";try{let n=be((e=navigator.userAgent)!=null?e:""),o=ke((t=document.referrer)!=null?t:"",window.location.origin);return`${n}:${o}`}catch(n){return"desktop:direct"}}var F=Ae({client:null,apiKey:"",initialAssignments:{},sessionSegment:"desktop:direct",ssrFallback:"first",onAssignment:void 0,initialLayoutOrder:null});function Ce(e){var l;let[t,n]=ne(null),[o]=ne(()=>{var s;return(s=e.sessionSegment)!=null?s:xe()});te(()=>{if(e.consent===!1&&!e.preConsentBehavior){n(p=>(p==null||p.destroy(),null));return}let s={apiKey:e.apiKey,context:e.context,debug:e.debug,initialAssignments:e.initialAssignments,sessionSegment:o,consent:e.consent,preConsentBehavior:e.preConsentBehavior,respectDoNotTrack:e.respectDoNotTrack,ssrSessionId:e.ssrSessionId,country:e.country},A=!1,f=null;return e.enableGraph?import("@sentientui/core/graph").then(({init:p})=>{A||(f=p(P(_({},s),{graph:!0})),n(f))}):(f=we(s),n(f)),()=>{A=!0,f==null||f.destroy()}},[e.consent]),te(()=>{if(!t)return;let s=!1,A=async()=>{if(s)return;let p;try{p=await t.fetchWeights()}catch(a){return}if(!s)for(let a of p){let L={componentId:a.componentId,updatedAt:a.updatedAt,variants:a.variants.map(u=>{var y;return{variantId:u.variantId,pulls:u.pulls,avgReward:(y=u.avgReward)!=null?y:0}})};X(a.componentId,L)}};A();let f=setInterval(()=>{A()},6e4);return()=>{s=!0,clearInterval(f)}},[t]);let i=(l=e.ssrFallback)!=null?l:"first",v=Se(()=>{var s,A;return{client:t,apiKey:e.apiKey,initialAssignments:(s=e.initialAssignments)!=null?s:{},sessionSegment:o,ssrFallback:i,onAssignment:e.onAssignment,initialLayoutOrder:(A=e.initialLayoutOrder)!=null?A:null}},[t,e.apiKey,e.initialAssignments,o,i,e.onAssignment,e.initialLayoutOrder]);return Ie(F.Provider,{value:v,children:e.children})}function I(){return T(F).client}function K(){return T(F).apiKey}function U(){return T(F).initialAssignments}function V(){return T(F).sessionSegment}function ie(){return T(F).ssrFallback}function $(){return T(F).onAssignment}function Ee(){return T(F).initialLayoutOrder}import{memo as Ge,useEffect as M,useMemo as se,useRef as J,useState as Oe}from"react";import{attachMicroSignalDetectors as _e}from"@sentientui/core";import{useEffect as q,useRef as re,useState as Le}from"react";function Re(e){var n;if(typeof window=="undefined")return null;let t=(n=window.__sentient_overrides)==null?void 0:n[e];if(t)return t;try{let o=new URLSearchParams(window.location.search);for(let i of o.getAll("sentient_variant")){let v=i.indexOf(":");if(v!==-1&&i.slice(0,v)===e)return i.slice(v+1)}}catch(o){}return null}function oe(e,t){var o;let n=null;for(let i of e.variants)t.includes(i.variantId)&&(!n||i.avgReward>n.avgReward)&&(n={variantId:i.variantId,avgReward:i.avgReward});return(o=n==null?void 0:n.variantId)!=null?o:null}function Q(e,t,n,o){let i=U(),v=ie(),l=I(),s=V(),A=$(),f=re(null),p=Re(e),a=p&&t.includes(p)?p:null,L=re(null);a&&L.current!==a&&(L.current=a,console.info(`[sentient] override active: ${e} -> ${a}`));let u=(()=>{var r,c;if(a)return{variantId:a,content:null,isLoading:!1};if(!l){let g=i[e];return g&&t.includes(g)?{variantId:g,content:null,isLoading:!1}:v==="first"&&t.length>0?{variantId:t[0],content:null,isLoading:!1}:{variantId:null,content:null,isLoading:!0}}let d=l.getAssignment(e,s);if(d&&(t.includes(d.variantId)||d.content))return{variantId:d.variantId,content:(r=d.content)!=null?r:null,isLoading:!1};let h=z(e);if(h){let g=oe(h,t);if(g)return{variantId:g,content:null,isLoading:!1}}return{variantId:(c=t[0])!=null?c:null,content:null,isLoading:!1}})(),[y,S]=Le(u),R=d=>{A&&f.current!==d&&(f.current=d,A(e,d))};return q(()=>{var h;if(a||!l)return;let d=l.getAssignment(e,s);if(d&&(t.includes(d.variantId)||d.content)){S({variantId:d.variantId,content:(h=d.content)!=null?h:null,isLoading:!1}),R(d.variantId);return}S(r=>{var c;return r.variantId?r:{variantId:(c=t[0])!=null?c:null,content:null,isLoading:!1}})},[a,l,e,s]),q(()=>{if(a||!l)return;let d=l.getAssignment(e,s);if(d&&t.includes(d.variantId))return;let h=!1;return l.assign(e,t,n,o).then(r=>{var c;h||r&&(!t.includes(r.variantId)&&!r.content||(S({variantId:r.variantId,content:(c=r.content)!=null?c:null,isLoading:!1}),R(r.variantId)))}),()=>{h=!0}},[a,l,e,s]),q(()=>{if(!a&&l)return H(e,d=>{var c;let h=l.getAssignment(e,s);if(h&&(t.includes(h.variantId)||h.content)){S({variantId:h.variantId,content:(c=h.content)!=null?c:null,isLoading:!1});return}let r=oe(d,t);r&&S({variantId:r,content:null,isLoading:!1})})},[a,l,e,s]),a?{variantId:a,content:null,isLoading:!1}:y}import{jsx as Pe}from"react/jsx-runtime";function Fe(e){return typeof e=="string"?{type:"click"}:e}var Te=3e4;function We(e,t){try{let n=`_snt_pv_${e}_${t}`;return sessionStorage.getItem(n)?!1:(sessionStorage.setItem(n,"1"),!0)}catch(n){return!0}}function Me(e){if(!(e instanceof Element))return!1;let t=e.tagName.toLowerCase();return t==="a"||t==="button"?!0:e.getAttribute("role")==="button"}function ae(e,t,n){if(n){try{let i=e;for(;i&&i!==t;){if(i.matches(n))return!0;i=i.parentElement}}catch(i){}return!1}let o=e;for(;o&&o!==t;){if(Me(o))return!0;o=o.parentElement}return!1}function De(e){var d,h;let t=I(),n=K(),o=se(()=>Object.keys(e.variants),[e.variants]),{variantId:i,content:v}=Q(e.id,o,e.agentData,e.agentDataByVariant),l=J(null),[s,A]=Oe(!1);M(()=>{A(!0)},[]);let f=J(!1),p=J(new Set),a=J(null),L=typeof e.goal=="string"?e.goal:JSON.stringify(e.goal),u=se(()=>Fe(e.goal),[L]),y=typeof e.goal=="string"?e.goal:u.type;if(M(()=>{var g,C;if(!t||!i||!n||a.current===i)return;let r=(C=(g=l.current)==null?void 0:g.innerHTML)!=null?C:"";if(!r)return;a.current=i;let c=r!==""&&We(e.id,i);t.track({projectId:n,componentId:e.id,variantId:i,eventType:"variant_assigned",payload:c?{previewHtml:r.slice(0,Te)}:{}})},[t,i,n,e.id,s,v]),M(()=>{f.current=!1,p.current=new Set},[i,u]),M(()=>{if(!t||!i)return;let r=l.current;if(!r)return;let c=null,g=0,C=()=>{g=Date.now(),c=setTimeout(()=>{t.track({projectId:n,componentId:e.id,variantId:i,eventType:"cursor_signal",payload:{hoverDuration:Date.now()-g}}),c=null},800)},b=()=>{c!==null&&(clearTimeout(c),c=null)};return r.addEventListener("mouseenter",C),r.addEventListener("mouseleave",b),()=>{r.removeEventListener("mouseenter",C),r.removeEventListener("mouseleave",b),c!==null&&clearTimeout(c)}},[t,i,n,e.id]),M(()=>{if(!t||!i)return;let r=l.current;if(!r)return;let c=Date.now();return _e((g,C={})=>{var m,w,E;t.track({projectId:n,componentId:e.id,variantId:i,eventType:"micro_signal",payload:_({signalType:g},C)});let b=(m=e.microSignalGoals)==null?void 0:m[g];if(!b||p.current.has(g))return;p.current.add(g);let W=typeof b=="string"?b:b.name,k=typeof b=="string"?1:(w=b.weight)!=null?w:1,x=typeof b=="string"?0:(E=b.stepIndex)!=null?E:0;t.goal(W,_({signalType:g},C),k,x)},r,c)},[t,i,n,e.id,e.microSignalGoals]),M(()=>{if(!t||!i)return;let r=l.current;if(!r)return;if(u.type==="weighted_composite"){let k=new Set,x=[];return u.steps.forEach(({goal:m,name:w,weight:E},D)=>{let B=()=>{k.has(D)||(k.add(D),t.track({projectId:n,componentId:e.id,variantId:i,eventType:"goal_achieved",goalType:w,payload:{reward:E}}),t.goal(w,{},E,D))};if(m.type==="click"){let G=O=>{let N=O.target;N instanceof Element&&ae(N,r,m.selector)&&B()};r.addEventListener("click",G),x.push(()=>r.removeEventListener("click",G));return}if(m.type==="form_submit"){let G=O=>{O.target instanceof HTMLFormElement&&r.contains(O.target)&&B()};r.addEventListener("submit",G),x.push(()=>r.removeEventListener("submit",G));return}if(m.type==="scroll_depth"){let G=Math.max(0,Math.min(1,m.threshold)),O=new IntersectionObserver(N=>{for(let fe of N)if(fe.intersectionRatio>=G){B(),O.disconnect();break}},{threshold:[G]});O.observe(r),x.push(()=>O.disconnect())}}),()=>{for(let m of x)m()}}let c=()=>{f.current||(f.current=!0,t.track({projectId:n,componentId:e.id,variantId:i,eventType:"goal_achieved",goalType:y,payload:{reward:1}}),t.goal(y,{componentId:e.id,variantId:i},1,0))},g=u.type==="composite"?u.all:[u],C=new Set(g.map((k,x)=>x)),b=k=>{C.delete(k),C.size===0&&c()},W=[];return g.forEach((k,x)=>{if(k.type==="click"){let m=w=>{let E=w.target;E instanceof Element&&ae(E,r,k.selector)&&(u.type==="composite"?b(x):c())};r.addEventListener("click",m),W.push(()=>r.removeEventListener("click",m));return}if(k.type==="form_submit"){let m=w=>{w.target instanceof HTMLFormElement&&r.contains(w.target)&&(u.type==="composite"?b(x):c())};r.addEventListener("submit",m),W.push(()=>r.removeEventListener("submit",m));return}if(k.type==="scroll_depth"){let m=Math.max(0,Math.min(1,k.threshold)),w=new IntersectionObserver(E=>{for(let D of E)if(D.intersectionRatio>=m){u.type==="composite"?b(x):c(),w.disconnect();break}},{threshold:[m]});w.observe(r),W.push(()=>w.disconnect());return}}),()=>{for(let k of W)k()}},[t,i,n,e.id,u,y]),e.clientOnly&&(!s||!t)||!i)return null;let S=(d=e.variants[i])!=null?d:null,R=S===null?v:null;return((h=process==null?void 0:process.env)==null?void 0:h.NODE_ENV)!=="production"&&S===null&&R===null&&console.warn(`[sentient] <Adaptive id="${e.id}"> was assigned variant "${i}" but no matching key exists in props.variants. If this is a dashboard-managed text variant, use <AdaptiveText id="${e.id}"> instead.`),Pe("div",{ref:l,"data-sentient-id":e.id,"data-sentient-variant":i,children:S!=null?S:R})}var Ne=Ge(De,(e,t)=>{if(e.id!==t.id||JSON.stringify(e.goal)!==JSON.stringify(t.goal)||e.microSignalGoals!==t.microSignalGoals)return!1;if(e.variants===t.variants)return!0;let n=Object.keys(e.variants),o=Object.keys(t.variants);return n.length!==o.length?!1:n.every(i=>i in t.variants)});import{useEffect as le,useRef as je,useState as ce}from"react";import{jsx as Ve}from"react/jsx-runtime";function Ke({id:e,default:t,component:n="span",className:o}){let i=I(),v=K(),l=$(),s=V(),A=je(null),[f,p]=ce(()=>{var u,y;return(y=(u=i==null?void 0:i.getAssignment(e,s))==null?void 0:u.content)!=null?y:null}),[a,L]=ce(()=>{var u,y;return(y=(u=i==null?void 0:i.getAssignment(e,s))==null?void 0:u.variantId)!=null?y:null});return le(()=>{var y;if(!i||((y=i.getAssignment(e,s))==null?void 0:y.content)!==void 0)return;let u=!1;return i.assign(e).then(S=>{var R;if(!u){if(!S){((R=process==null?void 0:process.env)==null?void 0:R.NODE_ENV)!=="production"&&console.warn(`[sentient] <AdaptiveText id="${e}"> assignment failed \u2014 showing default text.`);return}L(S.variantId),S.content&&p(S.content)}}),()=>{u=!0}},[i,e,s]),le(()=>{!i||!a||!v||A.current!==a&&(A.current=a,i.track({projectId:v,componentId:e,variantId:a,eventType:"variant_assigned",payload:{}}),l==null||l(e,a))},[i,a,v,e,l]),Ve(n,{className:o,children:f!=null?f:t})}import{useCallback as $e}from"react";function Je(e){let t=I();return $e((n,o)=>{t==null||t.componentGoal(e,n,o)},[t,e])}import{deriveSessionSegment as Be}from"@sentientui/core";var He=["page","blocks","layoutOrder"],ue=new Map;function Xe(e,t){ue.set(e,t)}function de(e){return ue.get(e)}function ze(e){var i,v;let t=(v=(i=e.content)!=null?i:de(e.page))!=null?v:{},n={};for(let[l,s]of Object.entries(t))He.includes(l)||(n[l]=s);let o=P(_({},n),{page:e.page,blocks:e.blocks});return e.layoutOrder&&(o.layoutOrder=e.layoutOrder),o}function Ue(e){return`<script type="application/ld+json">${ge(e)}</script>`}function ge(e){return JSON.stringify(_({"@context":"https://schema.org","@type":"WebPage"},e)).replace(/</g,"\\u003c")}function qe(e){let t=[];e.title&&t.push(`# ${e.title}`,""),e.summary&&t.push(String(e.summary),"");for(let[n,o]of Object.entries(e))["page","title","summary","blocks","layoutOrder"].includes(n)||t.push(`## ${n}`,"","```json",JSON.stringify(o,null,2),"```","");if(e.blocks.length>0){t.push("## blocks","");for(let n of e.blocks)t.push(`- **${n.id}** \u2192 variant \`${n.variant}\``),n.content!==void 0&&t.push(""," ```json",JSON.stringify(n.content,null,2)," ```");t.push("")}return t.join(`
|
|
3
|
+
`).trimEnd()+`
|
|
4
|
+
`}export{Ne as Adaptive,Ce as AdaptiveProvider,Ke as AdaptiveText,ze as buildAgentFeed,Xe as defineAgentContent,Be as detectSegment,de as getAgentContent,z as getWeights,Ue as renderAgentJsonLd,ge as renderAgentJsonLdBody,qe as renderAgentMarkdown,H as subscribeWeights,X as updateWeights,Je as useAdaptiveGoal,Q as useAssignment,U as useInitialAssignments,Ee as useLayoutOrder,I as useSentient};
|
|
3
5
|
//# sourceMappingURL=index.mjs.map
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/provider.tsx","../src/weights-store.ts","../src/adaptive.tsx","../src/use-assignment.ts","../src/adaptive-text.tsx","../src/use-adaptive-goal.ts","../src/segment.ts"],"sourcesContent":["'use client';\n\ndeclare const process: { env?: { NODE_ENV?: string } } | undefined;\n\nimport { createContext, useContext, useEffect, useMemo, useState, type ReactNode } from 'react';\nimport {\n detectDeviceClass,\n detectTrafficSource,\n init,\n type SentientClient,\n type SentientConfig,\n} from '@sentientui/core';\nimport { update as updateWeightsStore, type ComponentWeights } from './weights-store.js';\n\n/**\n * Mirrors the segment derivation inside core `init()` so the cache key used\n * by `useAssignment` always matches the key `assign()` writes under. Before\n * this, the context defaulted to 'desktop:direct' while core used the\n * detected segment — a systematic cache miss for every integration that\n * didn't pass `sessionSegment` explicitly.\n */\nfunction deriveDefaultSegment(): string {\n if (typeof window === 'undefined') return 'desktop:direct';\n try {\n const device = detectDeviceClass(navigator.userAgent ?? '');\n const source = detectTrafficSource(document.referrer ?? '', window.location.origin);\n return `${device}:${source}`;\n } catch {\n return 'desktop:direct';\n }\n}\n\n/** How to render adaptive slots during SSR when assignments are not preloaded. */\nexport type SsrFallback = 'first' | 'none';\n\ntype AdaptiveContextValue = {\n client: SentientClient | null;\n // The publishable API key (pk_…). Historically named `projectId` because the\n // API uses it as the project identifier on the wire, but it is the API key,\n // not the project UUID. Field renamed for clarity.\n apiKey: string;\n initialAssignments: Record<string, string>;\n sessionSegment: string;\n ssrFallback: SsrFallback;\n onAssignment: ((componentId: string, variantId: string) => void) | undefined;\n initialLayoutOrder: string[] | null;\n};\n\nconst AdaptiveContext = createContext<AdaptiveContextValue>({\n client: null,\n apiKey: '',\n initialAssignments: {},\n sessionSegment: 'desktop:direct',\n ssrFallback: 'first',\n onAssignment: undefined,\n initialLayoutOrder: null,\n});\n\nexport type AdaptiveProviderProps = {\n apiKey: string;\n context: SentientConfig['context'];\n debug?: boolean;\n /**\n * SSR-preloaded assignments from `preloadAssignments()` / `loadAdaptiveAssignments()`.\n * Passed through to `useAssignment` as synchronous initial state so crawlers and\n * the first paint see real content (recommended for SEO).\n */\n initialAssignments?: Record<string, string>;\n /**\n * Bandit segment from SSR (`device:source`). Keeps cache, assign, and worker\n * weights on one row — must match `loadAdaptiveAssignments` / session upsert.\n */\n sessionSegment?: string;\n /**\n * When no `initialAssignments` exist for a component, `'first'` renders\n * `variantIds[0]` in server HTML (safe default for SEO). Use `'none'` only for\n * decorative slots marked `clientOnly`.\n * @default 'first'\n */\n ssrFallback?: SsrFallback;\n /**\n * Consent gate. When `false` the SDK is not initialised and no events are\n * sent. Flip to `true` (e.g. after the user accepts the cookie banner) to\n * initialise and begin tracking.\n */\n consent?: boolean;\n /**\n * Behavior before consent is granted. Pass `'statistical_winner'` to serve the\n * best-performing variant via `GET /v1/winner` with zero tracking while the\n * consent banner is showing. Requires `consent: false`.\n * @see SentientConfig.preConsentBehavior\n */\n preConsentBehavior?: 'statistical_winner' | 'control';\n /**\n * Called once per component the first time a variant is resolved for that\n * component in this session. Use to forward assignments to your own analytics\n * (Mixpanel, PostHog, Segment, etc.) without having to wrap `useAssignment`.\n */\n onAssignment?: (componentId: string, variantId: string) => void;\n /**\n * SSR-preloaded section order from `loadAdaptiveDecision()`.\n * Pass the `layoutOrder` field from `DecideResult`. When set,\n * `useLayoutOrder()` returns this on first render so there is no layout shift.\n */\n initialLayoutOrder?: string[] | null;\n /**\n * Session ID generated during SSR (the `sessionId` field returned by\n * `loadAdaptiveAssignments` / `loadAdaptiveDecision`). When provided and no\n * existing session cookie or localStorage entry is found, the client adopts\n * this ID so events and goals are attributed to the same session the server\n * used for variant assignment.\n */\n ssrSessionId?: string;\n children: ReactNode;\n};\n\n/**\n * Initialises the Sentient core SDK in a useEffect (SSR-safe) and exposes the\n * client via React context. Re-initialises when `consent` changes.\n */\nexport function AdaptiveProvider(props: AdaptiveProviderProps): JSX.Element {\n const [client, setClient] = useState<SentientClient | null>(null);\n // Derived once per mount: identical to what core init() computes, so cache\n // reads (context segment) and cache writes (core segment) always agree.\n const [sessionSegment] = useState(() => props.sessionSegment ?? deriveDefaultSegment());\n\n useEffect(() => {\n // When consent is explicitly false with no preConsentBehavior, tear down any existing client.\n if (props.consent === false && !props.preConsentBehavior) {\n setClient((prev: SentientClient | null) => {\n prev?.destroy();\n return null;\n });\n return;\n }\n\n const c = init({\n apiKey: props.apiKey,\n context: props.context,\n debug: props.debug,\n initialAssignments: props.initialAssignments,\n sessionSegment,\n consent: props.consent,\n preConsentBehavior: props.preConsentBehavior,\n ssrSessionId: props.ssrSessionId,\n });\n setClient(c);\n return () => {\n c.destroy();\n };\n // Re-init when consent changes. Other props are intentionally stable.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [props.consent]);\n\n // Poll /v1/weights every 60 s so long-lived sessions see updated bandit weights\n // without a page reload. useAssignment subscribers react via weights-store.\n useEffect(() => {\n if (!client) return;\n let cancelled = false;\n const poll = async (): Promise<void> => {\n if (cancelled) return;\n let entries;\n try {\n entries = await client.fetchWeights();\n } catch {\n // Network/transient error: skip this cycle and retry on the next\n // interval. Swallowed deliberately so a failed poll never surfaces as\n // an unhandled rejection.\n return;\n }\n if (cancelled) return;\n for (const entry of entries) {\n const weights: ComponentWeights = {\n componentId: entry.componentId,\n updatedAt: entry.updatedAt,\n variants: entry.variants.map((v) => ({\n variantId: v.variantId,\n pulls: v.pulls,\n avgReward: v.avgReward ?? 0,\n })),\n };\n updateWeightsStore(entry.componentId, weights);\n }\n };\n void poll();\n const timerId = setInterval(() => void poll(), 60_000);\n return () => {\n cancelled = true;\n clearInterval(timerId);\n };\n }, [client]);\n\n const ssrFallback = props.ssrFallback ?? 'first';\n\n // Memoized so unrelated parent re-renders don't cascade through every\n // useSentient / useAssignment consumer via a fresh context object.\n const value = useMemo<AdaptiveContextValue>(\n () => ({\n client,\n apiKey: props.apiKey,\n initialAssignments: props.initialAssignments ?? {},\n sessionSegment,\n ssrFallback,\n onAssignment: props.onAssignment,\n initialLayoutOrder: props.initialLayoutOrder ?? null,\n }),\n [\n client,\n props.apiKey,\n props.initialAssignments,\n sessionSegment,\n ssrFallback,\n props.onAssignment,\n props.initialLayoutOrder,\n ],\n );\n\n return (\n <AdaptiveContext.Provider value={value}>\n {props.children}\n </AdaptiveContext.Provider>\n );\n}\n\n/**\n * Returns the SentientClient, or null until the provider has finished\n * initialising on the client.\n */\nexport function useSentient(): SentientClient | null {\n return useContext(AdaptiveContext).client;\n}\n\n/** Internal: publishable API key carried alongside the client. */\nexport function useAdaptiveApiKey(): string {\n return useContext(AdaptiveContext).apiKey;\n}\n\n/**\n * @deprecated Renamed to `useAdaptiveApiKey`. Kept as an alias so external\n * imports from earlier versions of this package keep working. Will be removed\n * in 1.0.0.\n */\nlet warnedProjectIdAlias = false;\nexport function useAdaptiveProjectId(): string {\n if (\n !warnedProjectIdAlias &&\n typeof process !== 'undefined' &&\n process.env?.NODE_ENV !== 'production'\n ) {\n warnedProjectIdAlias = true;\n console.warn(\n '[@sentientui/react] useAdaptiveProjectId is deprecated; use useAdaptiveApiKey. Will be removed in 1.0.0.',\n );\n }\n return useAdaptiveApiKey();\n}\n\n/** Internal: SSR-preloaded assignments for hydration-safe first render. */\nexport function useInitialAssignments(): Record<string, string> {\n return useContext(AdaptiveContext).initialAssignments;\n}\n\n/** Internal: bandit segment aligned with SSR session upsert. */\nexport function useSessionSegment(): string {\n return useContext(AdaptiveContext).sessionSegment;\n}\n\n/** Internal: SSR fallback strategy when a slot has no preloaded assignment. */\nexport function useSsrFallback(): SsrFallback {\n return useContext(AdaptiveContext).ssrFallback;\n}\n\n/** Internal: forwarding hook for consumer analytics integration. */\nexport function useOnAssignment(): ((componentId: string, variantId: string) => void) | undefined {\n return useContext(AdaptiveContext).onAssignment;\n}\n\n/**\n * Returns the persona-specific section order from SSR, or null when no\n * sections were declared on AdaptiveRoot or reliability is below threshold.\n */\nexport function useLayoutOrder(): string[] | null {\n return useContext(AdaptiveContext).initialLayoutOrder;\n}\n","/** Per-component weights store with isolated subscriptions. */\n\nexport type VariantWeight = {\n variantId: string;\n pulls: number;\n avgReward: number;\n};\n\nexport type ComponentWeights = {\n componentId: string;\n variants: VariantWeight[];\n updatedAt: number;\n};\n\ntype Listener = (weights: ComponentWeights) => void;\n\nconst store = new Map<string, ComponentWeights>();\nconst listeners = new Map<string, Set<Listener>>();\n\n/**\n * Subscribes a listener to a single component. Returns an unsubscribe function.\n * Updates to other components never trigger this listener.\n */\nexport function subscribe(componentId: string, cb: Listener): () => void {\n let set = listeners.get(componentId);\n if (!set) {\n set = new Set();\n listeners.set(componentId, set);\n }\n set.add(cb);\n return () => {\n set!.delete(cb);\n if (set!.size === 0) listeners.delete(componentId);\n };\n}\n\n/**\n * Replaces the weights for a component and notifies only that component's\n * subscribers.\n */\nexport function update(componentId: string, weights: ComponentWeights): void {\n store.set(componentId, weights);\n const set = listeners.get(componentId);\n if (!set) return;\n for (const cb of set) {\n try {\n cb(weights);\n } catch {\n /* never throw to other listeners */\n }\n }\n}\n\n/**\n * Returns the latest known weights for a component, or null if none seen.\n */\nexport function getWeights(componentId: string): ComponentWeights | null {\n return store.get(componentId) ?? null;\n}\n\n/** Test-only: wipe the entire store. */\nexport function _resetWeightsStore(): void {\n store.clear();\n listeners.clear();\n}\n","'use client';\n\ndeclare const process: { env?: { NODE_ENV?: string } } | undefined;\n\nimport { memo, useEffect, useMemo, useRef, useState, type ReactNode } from 'react';\nimport { attachMicroSignalDetectors, type MicroSignalType } from '@sentientui/core';\nimport { useAdaptiveApiKey, useSentient } from './provider.js';\nimport { useAssignment } from './use-assignment.js';\n\nexport type ScrollDepthGoal = { type: 'scroll_depth'; threshold: number };\nexport type ClickGoal = { type: 'click'; selector?: string };\nexport type FormSubmitGoal = { type: 'form_submit' };\nexport type CompositeGoal = { type: 'composite'; all: GoalConfig[] };\nexport type WeightedStep = { goal: GoalConfig; name: string; weight: number };\nexport type WeightedCompositeGoal = { type: 'weighted_composite'; steps: WeightedStep[] };\nexport type GoalConfig = ScrollDepthGoal | ClickGoal | FormSubmitGoal | CompositeGoal | WeightedCompositeGoal;\n\n/** Maps a detected micro-signal to a named session goal (`client.goal`). */\nexport type MicroSignalGoalConfig = string | { name: string; weight?: number; stepIndex?: number };\nexport type MicroSignalGoals = Partial<Record<MicroSignalType, MicroSignalGoalConfig>>;\n\nexport type AdaptiveProps = {\n id: string;\n variants: Record<string, ReactNode>;\n goal: string | GoalConfig;\n /**\n * When a passive micro-signal fires on this component, also record a named goal.\n * Use for inferred goals surfaced in the dashboard (e.g. rage_click → 'confused_by_hero').\n */\n microSignalGoals?: MicroSignalGoals;\n /**\n * When true, renders nothing during SSR and before client hydration.\n * Use when you cannot pass `initialAssignments` and prefer a blank slot over\n * a hydration mismatch. Tradeoff: minor CLS on first paint.\n */\n clientOnly?: boolean;\n /**\n * Variant-specific structured data for AI agent consumption via /sentient.json and\n * GET /v1/agent/layout. Keyed by variant ID — only the assigned variant's entry is stored,\n * so agents see only the content currently being served to visitors.\n *\n * Prefer this over `agentData` when variants have meaningfully different content.\n */\n agentDataByVariant?: Record<string, unknown>;\n /** @deprecated Use agentDataByVariant for variant-specific content. Stored as-is for the assigned variant. */\n agentData?: unknown;\n};\n\nfunction normalize(goal: string | GoalConfig): GoalConfig {\n if (typeof goal === 'string') return { type: 'click' };\n return goal;\n}\n\nconst PREVIEW_HTML_MAX_CHARS = 30_000;\n\n/**\n * previewHtml is the largest payload the SDK sends (up to 30 KB). The server\n * keeps the first-seen preview per (component, variant), so re-sending it on\n * every mount/navigation is pure waste — send it once per browser session.\n */\nfunction shouldSendPreviewHtml(componentId: string, variantId: string): boolean {\n try {\n const key = `_snt_pv_${componentId}_${variantId}`;\n if (sessionStorage.getItem(key)) return false;\n sessionStorage.setItem(key, '1');\n return true;\n } catch {\n // Storage unavailable (private mode, quota) — keep prior behavior.\n return true;\n }\n}\n\nfunction isClickableTarget(el: EventTarget | null): boolean {\n if (!(el instanceof Element)) return false;\n const tag = el.tagName.toLowerCase();\n if (tag === 'a' || tag === 'button') return true;\n const role = el.getAttribute('role');\n return role === 'button';\n}\n\nfunction findClickable(start: Element, container: Element, selector?: string): boolean {\n if (selector) {\n try {\n let cursor: Element | null = start;\n while (cursor && cursor !== container) {\n if (cursor.matches(selector)) return true;\n cursor = cursor.parentElement;\n }\n } catch {\n // Invalid CSS selector — treat as no match rather than breaking all click handlers.\n }\n return false;\n }\n let cursor: Element | null = start;\n while (cursor && cursor !== container) {\n if (isClickableTarget(cursor)) return true;\n cursor = cursor.parentElement;\n }\n return false;\n}\n\nfunction AdaptiveImpl(props: AdaptiveProps): JSX.Element | null {\n const client = useSentient();\n const apiKey = useAdaptiveApiKey();\n const variantIds = useMemo(() => Object.keys(props.variants), [props.variants]);\n const { variantId, content } = useAssignment(props.id, variantIds, props.agentData, props.agentDataByVariant);\n const containerRef = useRef<HTMLDivElement>(null);\n const [mounted, setMounted] = useState(false);\n\n useEffect(() => { setMounted(true); }, []);\n const goalFiredRef = useRef(false);\n const microGoalFiredRef = useRef<Set<MicroSignalType>>(new Set());\n const assignTrackedRef = useRef<string | null>(null);\n const goalKey = typeof props.goal === 'string' ? props.goal : JSON.stringify(props.goal);\n const goal = useMemo(() => normalize(props.goal), [goalKey]);\n const goalLabel = typeof props.goal === 'string' ? props.goal : goal.type;\n\n // Track variant_assigned exactly once per (component, variant) mount.\n // Captures innerHTML as previewHtml so the dashboard can render a live preview\n // without requiring manual registry calls. First-seen wins on the server.\n // `mounted` is in deps so the effect re-runs after clientOnly components hydrate\n // and their container div is actually in the DOM.\n useEffect(() => {\n if (!client || !variantId || !apiKey) return;\n if (assignTrackedRef.current === variantId) return;\n const rawHtml = containerRef.current?.innerHTML ?? '';\n // Wait until content is in the DOM; will re-run when mounted changes.\n if (!rawHtml) return;\n assignTrackedRef.current = variantId;\n const includePreview = rawHtml !== '' && shouldSendPreviewHtml(props.id, variantId);\n client.track({\n projectId: apiKey,\n componentId: props.id,\n variantId,\n eventType: 'variant_assigned',\n payload: includePreview ? { previewHtml: rawHtml.slice(0, PREVIEW_HTML_MAX_CHARS) } : {},\n });\n }, [client, variantId, apiKey, props.id, mounted, content]);\n\n // Reset goal latch when variant or goal changes.\n useEffect(() => {\n goalFiredRef.current = false;\n microGoalFiredRef.current = new Set();\n }, [variantId, goal]);\n\n // Emit cursor_signal after 800 ms of continuous hover.\n useEffect(() => {\n if (!client || !variantId) return;\n const node = containerRef.current;\n if (!node) return;\n\n let timerId: ReturnType<typeof setTimeout> | null = null;\n let hoverStart = 0;\n\n const onEnter = (): void => {\n hoverStart = Date.now();\n timerId = setTimeout(() => {\n client.track({\n projectId: apiKey,\n componentId: props.id,\n variantId: variantId!,\n eventType: 'cursor_signal',\n payload: { hoverDuration: Date.now() - hoverStart },\n });\n timerId = null;\n }, 800);\n };\n\n const onLeave = (): void => {\n if (timerId !== null) {\n clearTimeout(timerId);\n timerId = null;\n }\n };\n\n node.addEventListener('mouseenter', onEnter);\n node.addEventListener('mouseleave', onLeave);\n return () => {\n node.removeEventListener('mouseenter', onEnter);\n node.removeEventListener('mouseleave', onLeave);\n if (timerId !== null) clearTimeout(timerId);\n };\n }, [client, variantId, apiKey, props.id]);\n\n // Attach micro-signal detectors passively — rage click, text copy, scroll hesitation, tab loss.\n useEffect(() => {\n if (!client || !variantId) return;\n const node = containerRef.current;\n if (!node) return;\n const assignedAt = Date.now();\n return attachMicroSignalDetectors(\n (signalType, extra = {}) => {\n client.track({\n projectId: apiKey,\n componentId: props.id,\n variantId: variantId!,\n eventType: 'micro_signal',\n payload: { signalType, ...extra },\n });\n\n const mapping = props.microSignalGoals?.[signalType];\n if (!mapping || microGoalFiredRef.current.has(signalType)) return;\n microGoalFiredRef.current.add(signalType);\n const name = typeof mapping === 'string' ? mapping : mapping.name;\n const weight = typeof mapping === 'string' ? 1.0 : (mapping.weight ?? 1.0);\n const stepIndex = typeof mapping === 'string' ? 0 : (mapping.stepIndex ?? 0);\n client.goal(name, { signalType, ...extra }, weight, stepIndex);\n },\n node,\n assignedAt,\n );\n }, [client, variantId, apiKey, props.id, props.microSignalGoals]);\n\n // Attach goal tracking.\n useEffect(() => {\n if (!client || !variantId) return;\n const node = containerRef.current;\n if (!node) return;\n\n // --- Weighted composite: each step fires independently as it completes ---\n if (goal.type === 'weighted_composite') {\n const firedSteps = new Set<number>();\n const wcCleanups: Array<() => void> = [];\n\n goal.steps.forEach(({ goal: sub, name: stepName, weight: stepWeight }, idx) => {\n const fireStep = (): void => {\n if (firedSteps.has(idx)) return;\n firedSteps.add(idx);\n client.track({\n projectId: apiKey,\n componentId: props.id,\n variantId: variantId!,\n eventType: 'goal_achieved',\n goalType: stepName,\n payload: { reward: stepWeight },\n });\n client.goal(stepName, {}, stepWeight, idx);\n };\n\n if (sub.type === 'click') {\n const onClick = (e: MouseEvent): void => {\n const target = e.target;\n if (!(target instanceof Element)) return;\n if (!findClickable(target, node, sub.selector)) return;\n fireStep();\n };\n node.addEventListener('click', onClick);\n wcCleanups.push(() => node.removeEventListener('click', onClick));\n return;\n }\n\n if (sub.type === 'form_submit') {\n const onSubmit = (e: Event): void => {\n if (!(e.target instanceof HTMLFormElement)) return;\n if (!node.contains(e.target)) return;\n fireStep();\n };\n node.addEventListener('submit', onSubmit);\n wcCleanups.push(() => node.removeEventListener('submit', onSubmit));\n return;\n }\n\n if (sub.type === 'scroll_depth') {\n const threshold = Math.max(0, Math.min(1, sub.threshold));\n const io = new IntersectionObserver(\n (entries) => {\n for (const entry of entries) {\n if (entry.intersectionRatio >= threshold) {\n fireStep();\n io.disconnect();\n break;\n }\n }\n },\n { threshold: [threshold] },\n );\n io.observe(node);\n wcCleanups.push(() => io.disconnect());\n }\n });\n\n return () => {\n for (const c of wcCleanups) c();\n };\n }\n // --- End weighted composite ---\n\n const fireGoal = (): void => {\n if (goalFiredRef.current) return;\n goalFiredRef.current = true;\n client.track({\n projectId: apiKey,\n componentId: props.id,\n variantId,\n eventType: 'goal_achieved',\n goalType: goalLabel,\n payload: { reward: 1.0 },\n });\n client.goal(goalLabel, { componentId: props.id, variantId }, 1.0, 0);\n };\n\n const subgoals: GoalConfig[] = goal.type === 'composite' ? goal.all : [goal];\n const remaining = new Set<number>(subgoals.map((_, i) => i));\n const checkComposite = (idx: number): void => {\n remaining.delete(idx);\n if (remaining.size === 0) fireGoal();\n };\n\n const cleanups: Array<() => void> = [];\n\n subgoals.forEach((sub, idx) => {\n if (sub.type === 'click') {\n const onClick = (e: MouseEvent): void => {\n const target = e.target;\n if (!(target instanceof Element)) return;\n if (!findClickable(target, node, sub.selector)) return;\n if (goal.type === 'composite') checkComposite(idx);\n else fireGoal();\n };\n node.addEventListener('click', onClick);\n cleanups.push(() => node.removeEventListener('click', onClick));\n return;\n }\n\n if (sub.type === 'form_submit') {\n const onSubmit = (e: Event): void => {\n if (!(e.target instanceof HTMLFormElement)) return;\n if (!node.contains(e.target)) return;\n if (goal.type === 'composite') checkComposite(idx);\n else fireGoal();\n };\n node.addEventListener('submit', onSubmit);\n cleanups.push(() => node.removeEventListener('submit', onSubmit));\n return;\n }\n\n if (sub.type === 'scroll_depth') {\n const threshold = Math.max(0, Math.min(1, sub.threshold));\n const io = new IntersectionObserver(\n (entries) => {\n for (const entry of entries) {\n if (entry.intersectionRatio >= threshold) {\n if (goal.type === 'composite') checkComposite(idx);\n else fireGoal();\n io.disconnect();\n break;\n }\n }\n },\n { threshold: [threshold] },\n );\n io.observe(node);\n cleanups.push(() => io.disconnect());\n return;\n }\n });\n\n return () => {\n for (const c of cleanups) c();\n };\n }, [client, variantId, apiKey, props.id, goal, goalLabel]);\n\n // Decorative slots: empty in SSR HTML and until the client has mounted.\n if (props.clientOnly && (!mounted || !client)) return null;\n if (!variantId) return null;\n\n const jsxContent = props.variants[variantId] ?? null;\n const managedContent = jsxContent === null ? content : null;\n\n if (process?.env?.NODE_ENV !== 'production' && jsxContent === null && managedContent === null) {\n console.warn(\n `[sentient] <Adaptive id=\"${props.id}\"> was assigned variant \"${variantId}\" but no matching key exists in props.variants.` +\n ` If this is a dashboard-managed text variant, use <AdaptiveText id=\"${props.id}\"> instead.`,\n );\n }\n\n return (\n <div ref={containerRef} data-sentient-id={props.id} data-sentient-variant={variantId}>\n {jsxContent ?? managedContent}\n </div>\n );\n}\n\n/** Re-renders only when the chosen variant changes. */\nexport const Adaptive = memo(AdaptiveImpl, (prev, next) => {\n if (prev.id !== next.id) return false;\n if (JSON.stringify(prev.goal) !== JSON.stringify(next.goal)) return false;\n if (prev.microSignalGoals !== next.microSignalGoals) return false;\n if (prev.variants === next.variants) return true;\n const prevKeys = Object.keys(prev.variants);\n const nextKeys = Object.keys(next.variants);\n if (prevKeys.length !== nextKeys.length) return false;\n return prevKeys.every((k) => k in next.variants);\n});\n","import { useEffect, useRef, useState } from 'react';\nimport { type AssignResult } from '@sentientui/core';\nimport { useSentient, useInitialAssignments, useSessionSegment, useSsrFallback, useOnAssignment } from './provider.js';\nimport { subscribe, getWeights, type ComponentWeights } from './weights-store.js';\n\ndeclare global {\n interface Window { __sentient_overrides?: Record<string, string>; }\n}\n\nfunction getDevOverride(componentId: string): string | null {\n if (typeof window === 'undefined') return null;\n const global = window.__sentient_overrides?.[componentId];\n if (global) return global;\n try {\n const params = new URLSearchParams(window.location.search);\n for (const raw of params.getAll('sentient_variant')) {\n // sentient_variant=componentId:variantId (repeatable for multiple components)\n const sep = raw.indexOf(':');\n if (sep === -1) continue;\n if (raw.slice(0, sep) === componentId) return raw.slice(sep + 1);\n }\n } catch { /* non-browser env */ }\n return null;\n}\n\nexport type AssignmentState = {\n variantId: string | null;\n /** Populated when the assigned variant is a dashboard-managed text variant. */\n content: string | null;\n isLoading: boolean;\n};\n\nfunction pickFromWeights(weights: ComponentWeights, variantIds: string[]): string | null {\n let best: { variantId: string; avgReward: number } | null = null;\n for (const v of weights.variants) {\n if (!variantIds.includes(v.variantId)) continue;\n if (!best || v.avgReward > best.avgReward) {\n best = { variantId: v.variantId, avgReward: v.avgReward };\n }\n }\n return best?.variantId ?? null;\n}\n\n/**\n * Returns a sticky variant assignment for a component.\n *\n * First render reads the local SDK cache; if empty, falls back to a\n * deterministic default and asynchronously calls `/v1/assign`. The server\n * picks the actual variant via Thompson Sampling and the result replaces the fallback\n * on the next render. Subsequent paints read synchronously from cache —\n * no flicker, no loading state after first paint.\n */\nexport function useAssignment(componentId: string, variantIds: string[], agentData?: unknown, agentDataByVariant?: Record<string, unknown>): AssignmentState {\n const initialAssignments = useInitialAssignments();\n const ssrFallback = useSsrFallback();\n const client = useSentient();\n const segment = useSessionSegment();\n const onAssignment = useOnAssignment();\n const assignmentReportedRef = useRef<string | null>(null);\n\n // Dev override: URL param ?sentient_variant=componentId:variantId\n // or window.__sentient_overrides[componentId]. Short-circuits the bandit entirely.\n const devOverride = getDevOverride(componentId);\n const overrideVariant = devOverride && variantIds.includes(devOverride) ? devOverride : null;\n const overrideLoggedRef = useRef<string | null>(null);\n if (overrideVariant && overrideLoggedRef.current !== overrideVariant) {\n overrideLoggedRef.current = overrideVariant;\n console.info(`[sentient] override active: ${componentId} -> ${overrideVariant}`);\n }\n\n const initial = (() => {\n if (overrideVariant) {\n return { variantId: overrideVariant, content: null, isLoading: false };\n }\n // SSR / pre-hydration: no client yet. Use initialAssignments if provided so\n // the server and client first render agree on the same variant (no mismatch).\n if (!client) {\n const preloaded = initialAssignments[componentId];\n if (preloaded && variantIds.includes(preloaded)) {\n return { variantId: preloaded, content: null, isLoading: false };\n }\n if (ssrFallback === 'first' && variantIds.length > 0) {\n return { variantId: variantIds[0], content: null, isLoading: false };\n }\n return { variantId: null, content: null, isLoading: true };\n }\n const cached = client.getAssignment(componentId, segment);\n // Allow cached managed variants (content present) even if not in variantIds.\n if (cached && (variantIds.includes(cached.variantId) || cached.content)) {\n return { variantId: cached.variantId, content: cached.content ?? null, isLoading: false };\n }\n const weights = getWeights(componentId);\n if (weights) {\n const chosen = pickFromWeights(weights, variantIds);\n if (chosen) return { variantId: chosen, content: null, isLoading: false };\n }\n return { variantId: variantIds[0] ?? null, content: null, isLoading: false };\n })();\n\n const [state, setState] = useState<AssignmentState>(initial);\n\n // Helper: call onAssignment at most once per resolved variant.\n const reportAssignment = (variantId: string): void => {\n if (!onAssignment) return;\n if (assignmentReportedRef.current === variantId) return;\n assignmentReportedRef.current = variantId;\n onAssignment(componentId, variantId);\n };\n\n // As soon as the client is ready, unblock the UI immediately with variantIds[0]\n // (or a cached value) so the component never stays invisible while assign is\n // in-flight. The async assign call below then swaps to the bandit-chosen variant.\n useEffect(() => {\n if (overrideVariant) return;\n if (!client) return;\n const cached = client.getAssignment(componentId, segment);\n if (cached && (variantIds.includes(cached.variantId) || cached.content)) {\n setState({ variantId: cached.variantId, content: cached.content ?? null, isLoading: false });\n reportAssignment(cached.variantId);\n return;\n }\n setState((prev) => prev.variantId ? prev : { variantId: variantIds[0] ?? null, content: null, isLoading: false });\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [overrideVariant, client, componentId, segment]);\n\n // Ask the server for a real assignment when we have a client but no cached one.\n useEffect(() => {\n if (overrideVariant) return;\n if (!client) return;\n const cached = client.getAssignment(componentId, segment);\n if (cached && variantIds.includes(cached.variantId)) return;\n\n let cancelled = false;\n void client.assign(componentId, variantIds, agentData, agentDataByVariant).then((result: AssignResult | null) => {\n if (cancelled) return;\n if (!result) return;\n // Allow the result if it's a known code variant OR a managed text variant (has content).\n if (!variantIds.includes(result.variantId) && !result.content) return;\n setState({ variantId: result.variantId, content: result.content ?? null, isLoading: false });\n reportAssignment(result.variantId);\n });\n return () => { cancelled = true; };\n // variantIds intentionally excluded — changing variants mid-mount is unsupported\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [overrideVariant, client, componentId, segment]);\n\n // Live weight updates from the dashboard SSE stream (when wired).\n useEffect(() => {\n if (overrideVariant) return;\n if (!client) return;\n return subscribe(componentId, (weights) => {\n const cached = client.getAssignment(componentId, segment);\n if (cached && (variantIds.includes(cached.variantId) || cached.content)) {\n setState({ variantId: cached.variantId, content: cached.content ?? null, isLoading: false });\n return;\n }\n const chosen = pickFromWeights(weights, variantIds);\n if (chosen) setState({ variantId: chosen, content: null, isLoading: false });\n });\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [overrideVariant, client, componentId, segment]);\n\n if (overrideVariant) {\n return { variantId: overrideVariant, content: null, isLoading: false };\n }\n\n return state;\n}\n","'use client';\n\ndeclare const process: { env?: { NODE_ENV?: string } } | undefined;\n\nimport { useEffect, useRef, useState } from 'react';\nimport type { AssignResult } from '@sentientui/core';\nimport { useSentient, useAdaptiveApiKey, useOnAssignment, useSessionSegment } from './provider.js';\n\nexport type AdaptiveTextProps = {\n id: string;\n default: string;\n component?: keyof JSX.IntrinsicElements;\n className?: string;\n};\n\nexport function AdaptiveText({\n id,\n default: defaultText,\n component: Tag = 'span',\n className,\n}: AdaptiveTextProps) {\n const client = useSentient();\n const apiKey = useAdaptiveApiKey();\n const onAssignment = useOnAssignment();\n const segment = useSessionSegment();\n const trackedRef = useRef<string | null>(null);\n\n // Seed from cache synchronously so remounts don't flash back to defaultText.\n const [text, setText] = useState<string | null>(() =>\n client?.getAssignment(id, segment)?.content ?? null\n );\n const [variantId, setVariantId] = useState<string | null>(() =>\n client?.getAssignment(id, segment)?.variantId ?? null\n );\n\n useEffect(() => {\n if (!client) return;\n // Skip if content already cached; assign() re-checks internally but this avoids the async round-trip on remount.\n if (client.getAssignment(id, segment)?.content !== undefined) return;\n\n let cancelled = false;\n void client.assign(id).then((result: AssignResult | null) => {\n if (cancelled) return;\n if (!result) {\n if (process?.env?.NODE_ENV !== 'production') {\n console.warn(`[sentient] <AdaptiveText id=\"${id}\"> assignment failed — showing default text.`);\n }\n return;\n }\n setVariantId(result.variantId);\n if (result.content) setText(result.content);\n });\n return () => {\n cancelled = true;\n };\n }, [client, id, segment]);\n\n useEffect(() => {\n if (!client || !variantId || !apiKey) return;\n if (trackedRef.current === variantId) return;\n trackedRef.current = variantId;\n client.track({\n projectId: apiKey,\n componentId: id,\n variantId,\n eventType: 'variant_assigned',\n payload: {},\n });\n onAssignment?.(id, variantId);\n }, [client, variantId, apiKey, id, onAssignment]);\n\n return <Tag className={className}>{text ?? defaultText}</Tag>;\n}\n","import { useCallback } from 'react';\nimport type { ComponentGoalOptions } from '@sentientui/core';\nimport { useSentient } from './provider.js';\n\nexport type FireGoal = (goalType: string, opts?: ComponentGoalOptions) => void;\n\n/**\n * Returns a `fireGoal(goalType, opts?)` callback that records a conversion\n * attributed to the variant currently served for `componentId` — so it shows\n * up in the per-variant CVR funnel with no manual variantId/projectId plumbing.\n *\n * The served variant is resolved from the SDK's assignment cache (the same one\n * `<Adaptive id={componentId}>` populates), so render that component before\n * firing. Use this for imperative handlers (click, form submit, custom events);\n * for purely declarative goals prefer `<Adaptive goal={...}>`.\n *\n * @example\n * const fireContact = useAdaptiveGoal('hero_headline');\n * <button onClick={() => fireContact('hero_contact', { metadata: { method } })}>Call</button>\n */\nexport function useAdaptiveGoal(componentId: string): FireGoal {\n const client = useSentient();\n return useCallback<FireGoal>(\n (goalType, opts) => {\n client?.componentGoal(componentId, goalType, opts);\n },\n [client, componentId],\n );\n}\n","/** @deprecated Use `useSessionSegment()` from the provider, or `deriveSessionSegment` from `@sentientui/core`. */\nexport { deriveSessionSegment as detect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B,QAoBrB,SAASC,GAAgBC,EAA+B,CAC7D,IAAMC,EAASC,EAAY,EAC3B,OAAOC,GACL,CAACC,EAAUC,IAAS,CAClBJ,GAAA,MAAAA,EAAQ,cAAcD,EAAaI,EAAUC,EAC/C,EACA,CAACJ,EAAQD,CAAW,CACtB,CACF,CC3BA,OAAiC,wBAAxBM,OAA6C","names":["createContext","useContext","useEffect","useMemo","useState","detectDeviceClass","detectTrafficSource","init","store","listeners","subscribe","componentId","cb","set","update","weights","e","getWeights","_a","jsx","deriveDefaultSegment","_a","_b","device","detectDeviceClass","source","detectTrafficSource","e","AdaptiveContext","createContext","AdaptiveProvider","props","client","setClient","useState","sessionSegment","useEffect","prev","c","init","cancelled","poll","entries","entry","weights","v","update","timerId","ssrFallback","value","useMemo","useSentient","useContext","useAdaptiveApiKey","useInitialAssignments","useContext","AdaptiveContext","useSessionSegment","useSsrFallback","useOnAssignment","useLayoutOrder","memo","useEffect","useMemo","useRef","useState","attachMicroSignalDetectors","useEffect","useRef","useState","getDevOverride","componentId","_a","global","params","raw","sep","e","pickFromWeights","weights","variantIds","best","v","useAssignment","agentData","agentDataByVariant","initialAssignments","useInitialAssignments","ssrFallback","useSsrFallback","client","useSentient","segment","useSessionSegment","onAssignment","useOnAssignment","assignmentReportedRef","useRef","devOverride","overrideVariant","overrideLoggedRef","initial","_b","preloaded","cached","getWeights","chosen","state","setState","useState","reportAssignment","variantId","useEffect","prev","cancelled","result","subscribe","jsx","normalize","goal","PREVIEW_HTML_MAX_CHARS","shouldSendPreviewHtml","componentId","variantId","key","e","isClickableTarget","el","tag","findClickable","start","container","selector","cursor","AdaptiveImpl","props","_a","_b","client","useSentient","apiKey","useAdaptiveApiKey","variantIds","useMemo","content","useAssignment","containerRef","useRef","mounted","setMounted","useState","useEffect","goalFiredRef","microGoalFiredRef","assignTrackedRef","goalKey","goalLabel","rawHtml","includePreview","node","timerId","hoverStart","onEnter","onLeave","assignedAt","attachMicroSignalDetectors","signalType","extra","_c","__spreadValues","mapping","name","weight","stepIndex","firedSteps","wcCleanups","sub","stepName","stepWeight","idx","fireStep","onClick","target","onSubmit","threshold","io","entries","entry","c","fireGoal","subgoals","remaining","_","i","checkComposite","cleanups","jsxContent","managedContent","Adaptive","memo","prev","next","prevKeys","nextKeys","k","useEffect","useRef","useState","jsx","AdaptiveText","id","defaultText","Tag","className","client","useSentient","apiKey","useAdaptiveApiKey","onAssignment","useOnAssignment","segment","useSessionSegment","trackedRef","useRef","text","setText","useState","_a","_b","variantId","setVariantId","useEffect","cancelled","result","useCallback","useAdaptiveGoal","componentId","client","useSentient","useCallback","goalType","opts","deriveSessionSegment"]}
|
|
1
|
+
{"version":3,"sources":["../src/provider.tsx","../src/weights-store.ts","../src/adaptive.tsx","../src/use-assignment.ts","../src/adaptive-text.tsx","../src/use-adaptive-goal.ts","../src/segment.ts","../src/agent-feed.ts"],"sourcesContent":["'use client';\n\ndeclare const process: { env?: { NODE_ENV?: string } } | undefined;\n\nimport { createContext, useContext, useEffect, useMemo, useState, type ReactNode } from 'react';\nimport {\n detectDeviceClass,\n detectTrafficSource,\n init,\n type SentientClient,\n type SentientConfig,\n} from '@sentientui/core';\nimport { update as updateWeightsStore, type ComponentWeights } from './weights-store.js';\n\n/**\n * Mirrors the segment derivation inside core `init()` so the cache key used\n * by `useAssignment` always matches the key `assign()` writes under. Before\n * this, the context defaulted to 'desktop:direct' while core used the\n * detected segment — a systematic cache miss for every integration that\n * didn't pass `sessionSegment` explicitly.\n */\nfunction deriveDefaultSegment(): string {\n if (typeof window === 'undefined') return 'desktop:direct';\n try {\n const device = detectDeviceClass(navigator.userAgent ?? '');\n const source = detectTrafficSource(document.referrer ?? '', window.location.origin);\n return `${device}:${source}`;\n } catch {\n return 'desktop:direct';\n }\n}\n\n/** How to render adaptive slots during SSR when assignments are not preloaded. */\nexport type SsrFallback = 'first' | 'none';\n\ntype AdaptiveContextValue = {\n client: SentientClient | null;\n // The publishable API key (pk_…). Historically named `projectId` because the\n // API uses it as the project identifier on the wire, but it is the API key,\n // not the project UUID. Field renamed for clarity.\n apiKey: string;\n initialAssignments: Record<string, string>;\n sessionSegment: string;\n ssrFallback: SsrFallback;\n onAssignment: ((componentId: string, variantId: string) => void) | undefined;\n initialLayoutOrder: string[] | null;\n};\n\nconst AdaptiveContext = createContext<AdaptiveContextValue>({\n client: null,\n apiKey: '',\n initialAssignments: {},\n sessionSegment: 'desktop:direct',\n ssrFallback: 'first',\n onAssignment: undefined,\n initialLayoutOrder: null,\n});\n\nexport type AdaptiveProviderProps = {\n apiKey: string;\n context: SentientConfig['context'];\n debug?: boolean;\n /**\n * SSR-preloaded assignments from `preloadAssignments()` / `loadAdaptiveAssignments()`.\n * Passed through to `useAssignment` as synchronous initial state so crawlers and\n * the first paint see real content (recommended for SEO).\n */\n initialAssignments?: Record<string, string>;\n /**\n * Bandit segment from SSR (`device:source`). Keeps cache, assign, and worker\n * weights on one row — must match `loadAdaptiveAssignments` / session upsert.\n */\n sessionSegment?: string;\n /**\n * When no `initialAssignments` exist for a component, `'first'` renders\n * `variantIds[0]` in server HTML (safe default for SEO). Use `'none'` only for\n * decorative slots marked `clientOnly`.\n * @default 'first'\n */\n ssrFallback?: SsrFallback;\n /**\n * Consent gate. When `false` the SDK is not initialised and no events are\n * sent. Flip to `true` (e.g. after the user accepts the cookie banner) to\n * initialise and begin tracking.\n */\n consent?: boolean;\n /**\n * Behavior before consent is granted. Pass `'statistical_winner'` to serve the\n * best-performing variant via `GET /v1/winner` with zero tracking while the\n * consent banner is showing. Requires `consent: false`.\n * @see SentientConfig.preConsentBehavior\n */\n preConsentBehavior?: 'statistical_winner' | 'control';\n /**\n * Honor the browser's Do Not Track signal. Defaults to `true`: when DNT is\n * enabled the SDK sets no cookies and sends no tracking data (overriding\n * `consent: true`). Set `false` to make your own consent gate authoritative.\n * @see SentientConfig.respectDoNotTrack\n */\n respectDoNotTrack?: boolean;\n /**\n * Called once per component the first time a variant is resolved for that\n * component in this session. Use to forward assignments to your own analytics\n * (Mixpanel, PostHog, Segment, etc.) without having to wrap `useAssignment`.\n */\n onAssignment?: (componentId: string, variantId: string) => void;\n /**\n * SSR-preloaded section order from `loadAdaptiveDecision()`.\n * Pass the `layoutOrder` field from `DecideResult`. When set,\n * `useLayoutOrder()` returns this on first render so there is no layout shift.\n */\n initialLayoutOrder?: string[] | null;\n /**\n * Session ID generated during SSR (the `sessionId` field returned by\n * `loadAdaptiveAssignments` / `loadAdaptiveDecision`). When provided and no\n * existing session cookie or localStorage entry is found, the client adopts\n * this ID so events and goals are attributed to the same session the server\n * used for variant assignment.\n */\n ssrSessionId?: string;\n /**\n * ISO 3166-1 alpha-2 country code. Pass the value of the `CF-IPCountry`\n * header from your Next.js server component to populate country on landing\n * sessions without client-side geo lookup.\n */\n country?: string;\n /**\n * Enable DOM graph scanning + page-structure sync. When `true`, the provider\n * dynamically loads `@sentientui/core/graph` and uses its graph-capable\n * `init()` for the single client, so the SDK scans your page structure and\n * syncs it to power the dashboard graph page. Left off (default), the lean\n * bundle is used and the graph entry is never loaded.\n */\n enableGraph?: boolean;\n children: ReactNode;\n};\n\n/**\n * Initialises the Sentient core SDK in a useEffect (SSR-safe) and exposes the\n * client via React context. Re-initialises when `consent` changes.\n */\nexport function AdaptiveProvider(props: AdaptiveProviderProps): JSX.Element {\n const [client, setClient] = useState<SentientClient | null>(null);\n // Derived once per mount: identical to what core init() computes, so cache\n // reads (context segment) and cache writes (core segment) always agree.\n const [sessionSegment] = useState(() => props.sessionSegment ?? deriveDefaultSegment());\n\n useEffect(() => {\n // When consent is explicitly false with no preConsentBehavior, tear down any existing client.\n if (props.consent === false && !props.preConsentBehavior) {\n setClient((prev: SentientClient | null) => {\n prev?.destroy();\n return null;\n });\n return;\n }\n\n const config = {\n apiKey: props.apiKey,\n context: props.context,\n debug: props.debug,\n initialAssignments: props.initialAssignments,\n sessionSegment,\n consent: props.consent,\n preConsentBehavior: props.preConsentBehavior,\n respectDoNotTrack: props.respectDoNotTrack,\n ssrSessionId: props.ssrSessionId,\n country: props.country,\n };\n\n // Track the client created by this effect run so cleanup destroys exactly\n // the right one, and so a late-resolving dynamic import can bail if the\n // effect was already torn down (unmount / consent change).\n let cancelled = false;\n let created: SentientClient | null = null;\n\n if (props.enableGraph) {\n // Load the graph entry only when asked — keeps the DOM scanner out of the\n // lean bundle. The provider still creates ONE client (graph-capable).\n void import('@sentientui/core/graph').then(({ init: initGraph }) => {\n if (cancelled) return;\n created = initGraph({ ...config, graph: true });\n setClient(created);\n });\n } else {\n created = init(config);\n setClient(created);\n }\n\n return () => {\n cancelled = true;\n created?.destroy();\n };\n // Re-init when consent changes. Other props (incl. enableGraph) are\n // intentionally stable for a session.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [props.consent]);\n\n // Poll /v1/weights every 60 s so long-lived sessions see updated bandit weights\n // without a page reload. useAssignment subscribers react via weights-store.\n useEffect(() => {\n if (!client) return;\n let cancelled = false;\n const poll = async (): Promise<void> => {\n if (cancelled) return;\n let entries;\n try {\n entries = await client.fetchWeights();\n } catch {\n // Network/transient error: skip this cycle and retry on the next\n // interval. Swallowed deliberately so a failed poll never surfaces as\n // an unhandled rejection.\n return;\n }\n if (cancelled) return;\n for (const entry of entries) {\n const weights: ComponentWeights = {\n componentId: entry.componentId,\n updatedAt: entry.updatedAt,\n variants: entry.variants.map((v) => ({\n variantId: v.variantId,\n pulls: v.pulls,\n avgReward: v.avgReward ?? 0,\n })),\n };\n updateWeightsStore(entry.componentId, weights);\n }\n };\n void poll();\n const timerId = setInterval(() => void poll(), 60_000);\n return () => {\n cancelled = true;\n clearInterval(timerId);\n };\n }, [client]);\n\n const ssrFallback = props.ssrFallback ?? 'first';\n\n // Memoized so unrelated parent re-renders don't cascade through every\n // useSentient / useAssignment consumer via a fresh context object.\n const value = useMemo<AdaptiveContextValue>(\n () => ({\n client,\n apiKey: props.apiKey,\n initialAssignments: props.initialAssignments ?? {},\n sessionSegment,\n ssrFallback,\n onAssignment: props.onAssignment,\n initialLayoutOrder: props.initialLayoutOrder ?? null,\n }),\n [\n client,\n props.apiKey,\n props.initialAssignments,\n sessionSegment,\n ssrFallback,\n props.onAssignment,\n props.initialLayoutOrder,\n ],\n );\n\n return (\n <AdaptiveContext.Provider value={value}>\n {props.children}\n </AdaptiveContext.Provider>\n );\n}\n\n/**\n * Returns the SentientClient, or null until the provider has finished\n * initialising on the client.\n */\nexport function useSentient(): SentientClient | null {\n return useContext(AdaptiveContext).client;\n}\n\n/** Internal: publishable API key carried alongside the client. */\nexport function useAdaptiveApiKey(): string {\n return useContext(AdaptiveContext).apiKey;\n}\n\n/**\n * @deprecated Renamed to `useAdaptiveApiKey`. Kept as an alias so external\n * imports from earlier versions of this package keep working. Will be removed\n * in 1.0.0.\n */\nlet warnedProjectIdAlias = false;\nexport function useAdaptiveProjectId(): string {\n if (\n !warnedProjectIdAlias &&\n typeof process !== 'undefined' &&\n process.env?.NODE_ENV !== 'production'\n ) {\n warnedProjectIdAlias = true;\n console.warn(\n '[@sentientui/react] useAdaptiveProjectId is deprecated; use useAdaptiveApiKey. Will be removed in 1.0.0.',\n );\n }\n return useAdaptiveApiKey();\n}\n\n/** Internal: SSR-preloaded assignments for hydration-safe first render. */\nexport function useInitialAssignments(): Record<string, string> {\n return useContext(AdaptiveContext).initialAssignments;\n}\n\n/** Internal: bandit segment aligned with SSR session upsert. */\nexport function useSessionSegment(): string {\n return useContext(AdaptiveContext).sessionSegment;\n}\n\n/** Internal: SSR fallback strategy when a slot has no preloaded assignment. */\nexport function useSsrFallback(): SsrFallback {\n return useContext(AdaptiveContext).ssrFallback;\n}\n\n/** Internal: forwarding hook for consumer analytics integration. */\nexport function useOnAssignment(): ((componentId: string, variantId: string) => void) | undefined {\n return useContext(AdaptiveContext).onAssignment;\n}\n\n/**\n * Returns the persona-specific section order from SSR, or null when no\n * sections were declared on AdaptiveRoot or reliability is below threshold.\n */\nexport function useLayoutOrder(): string[] | null {\n return useContext(AdaptiveContext).initialLayoutOrder;\n}\n","/** Per-component weights store with isolated subscriptions. */\n\nexport type VariantWeight = {\n variantId: string;\n pulls: number;\n avgReward: number;\n};\n\nexport type ComponentWeights = {\n componentId: string;\n variants: VariantWeight[];\n updatedAt: number;\n};\n\ntype Listener = (weights: ComponentWeights) => void;\n\nconst store = new Map<string, ComponentWeights>();\nconst listeners = new Map<string, Set<Listener>>();\n\n/**\n * Subscribes a listener to a single component. Returns an unsubscribe function.\n * Updates to other components never trigger this listener.\n */\nexport function subscribe(componentId: string, cb: Listener): () => void {\n let set = listeners.get(componentId);\n if (!set) {\n set = new Set();\n listeners.set(componentId, set);\n }\n set.add(cb);\n return () => {\n set!.delete(cb);\n if (set!.size === 0) listeners.delete(componentId);\n };\n}\n\n/**\n * Replaces the weights for a component and notifies only that component's\n * subscribers.\n */\nexport function update(componentId: string, weights: ComponentWeights): void {\n store.set(componentId, weights);\n const set = listeners.get(componentId);\n if (!set) return;\n for (const cb of set) {\n try {\n cb(weights);\n } catch {\n /* never throw to other listeners */\n }\n }\n}\n\n/**\n * Returns the latest known weights for a component, or null if none seen.\n */\nexport function getWeights(componentId: string): ComponentWeights | null {\n return store.get(componentId) ?? null;\n}\n\n/** Test-only: wipe the entire store. */\nexport function _resetWeightsStore(): void {\n store.clear();\n listeners.clear();\n}\n","'use client';\n\ndeclare const process: { env?: { NODE_ENV?: string } } | undefined;\n\nimport { memo, useEffect, useMemo, useRef, useState, type ReactNode } from 'react';\nimport { attachMicroSignalDetectors, type MicroSignalType } from '@sentientui/core';\nimport { useAdaptiveApiKey, useSentient } from './provider.js';\nimport { useAssignment } from './use-assignment.js';\n\nexport type ScrollDepthGoal = { type: 'scroll_depth'; threshold: number };\nexport type ClickGoal = { type: 'click'; selector?: string };\nexport type FormSubmitGoal = { type: 'form_submit' };\nexport type CompositeGoal = { type: 'composite'; all: GoalConfig[] };\nexport type WeightedStep = { goal: GoalConfig; name: string; weight: number };\nexport type WeightedCompositeGoal = { type: 'weighted_composite'; steps: WeightedStep[] };\nexport type GoalConfig = ScrollDepthGoal | ClickGoal | FormSubmitGoal | CompositeGoal | WeightedCompositeGoal;\n\n/** Maps a detected micro-signal to a named session goal (`client.goal`). */\nexport type MicroSignalGoalConfig = string | { name: string; weight?: number; stepIndex?: number };\nexport type MicroSignalGoals = Partial<Record<MicroSignalType, MicroSignalGoalConfig>>;\n\nexport type AdaptiveProps = {\n id: string;\n variants: Record<string, ReactNode>;\n goal: string | GoalConfig;\n /**\n * When a passive micro-signal fires on this component, also record a named goal.\n * Use for inferred goals surfaced in the dashboard (e.g. rage_click → 'confused_by_hero').\n */\n microSignalGoals?: MicroSignalGoals;\n /**\n * When true, renders nothing during SSR and before client hydration.\n * Use when you cannot pass `initialAssignments` and prefer a blank slot over\n * a hydration mismatch. Tradeoff: minor CLS on first paint.\n */\n clientOnly?: boolean;\n /**\n * Variant-specific structured data for AI agent consumption via /sentient.json and\n * GET /v1/agent/layout. Keyed by variant ID — only the assigned variant's entry is stored,\n * so agents see only the content currently being served to visitors.\n *\n * Prefer this over `agentData` when variants have meaningfully different content.\n */\n agentDataByVariant?: Record<string, unknown>;\n /** @deprecated Use agentDataByVariant for variant-specific content. Stored as-is for the assigned variant. */\n agentData?: unknown;\n};\n\nfunction normalize(goal: string | GoalConfig): GoalConfig {\n if (typeof goal === 'string') return { type: 'click' };\n return goal;\n}\n\nconst PREVIEW_HTML_MAX_CHARS = 30_000;\n\n/**\n * previewHtml is the largest payload the SDK sends (up to 30 KB). The server\n * keeps the first-seen preview per (component, variant), so re-sending it on\n * every mount/navigation is pure waste — send it once per browser session.\n */\nfunction shouldSendPreviewHtml(componentId: string, variantId: string): boolean {\n try {\n const key = `_snt_pv_${componentId}_${variantId}`;\n if (sessionStorage.getItem(key)) return false;\n sessionStorage.setItem(key, '1');\n return true;\n } catch {\n // Storage unavailable (private mode, quota) — keep prior behavior.\n return true;\n }\n}\n\nfunction isClickableTarget(el: EventTarget | null): boolean {\n if (!(el instanceof Element)) return false;\n const tag = el.tagName.toLowerCase();\n if (tag === 'a' || tag === 'button') return true;\n const role = el.getAttribute('role');\n return role === 'button';\n}\n\nfunction findClickable(start: Element, container: Element, selector?: string): boolean {\n if (selector) {\n try {\n let cursor: Element | null = start;\n while (cursor && cursor !== container) {\n if (cursor.matches(selector)) return true;\n cursor = cursor.parentElement;\n }\n } catch {\n // Invalid CSS selector — treat as no match rather than breaking all click handlers.\n }\n return false;\n }\n let cursor: Element | null = start;\n while (cursor && cursor !== container) {\n if (isClickableTarget(cursor)) return true;\n cursor = cursor.parentElement;\n }\n return false;\n}\n\nfunction AdaptiveImpl(props: AdaptiveProps): JSX.Element | null {\n const client = useSentient();\n const apiKey = useAdaptiveApiKey();\n const variantIds = useMemo(() => Object.keys(props.variants), [props.variants]);\n const { variantId, content } = useAssignment(props.id, variantIds, props.agentData, props.agentDataByVariant);\n const containerRef = useRef<HTMLDivElement>(null);\n const [mounted, setMounted] = useState(false);\n\n useEffect(() => { setMounted(true); }, []);\n const goalFiredRef = useRef(false);\n const microGoalFiredRef = useRef<Set<MicroSignalType>>(new Set());\n const assignTrackedRef = useRef<string | null>(null);\n const goalKey = typeof props.goal === 'string' ? props.goal : JSON.stringify(props.goal);\n const goal = useMemo(() => normalize(props.goal), [goalKey]);\n const goalLabel = typeof props.goal === 'string' ? props.goal : goal.type;\n\n // Track variant_assigned exactly once per (component, variant) mount.\n // Captures innerHTML as previewHtml so the dashboard can render a live preview\n // without requiring manual registry calls. First-seen wins on the server.\n // `mounted` is in deps so the effect re-runs after clientOnly components hydrate\n // and their container div is actually in the DOM.\n useEffect(() => {\n if (!client || !variantId || !apiKey) return;\n if (assignTrackedRef.current === variantId) return;\n const rawHtml = containerRef.current?.innerHTML ?? '';\n // Wait until content is in the DOM; will re-run when mounted changes.\n if (!rawHtml) return;\n assignTrackedRef.current = variantId;\n const includePreview = rawHtml !== '' && shouldSendPreviewHtml(props.id, variantId);\n client.track({\n projectId: apiKey,\n componentId: props.id,\n variantId,\n eventType: 'variant_assigned',\n payload: includePreview ? { previewHtml: rawHtml.slice(0, PREVIEW_HTML_MAX_CHARS) } : {},\n });\n }, [client, variantId, apiKey, props.id, mounted, content]);\n\n // Reset goal latch when variant or goal changes.\n useEffect(() => {\n goalFiredRef.current = false;\n microGoalFiredRef.current = new Set();\n }, [variantId, goal]);\n\n // Emit cursor_signal after 800 ms of continuous hover.\n useEffect(() => {\n if (!client || !variantId) return;\n const node = containerRef.current;\n if (!node) return;\n\n let timerId: ReturnType<typeof setTimeout> | null = null;\n let hoverStart = 0;\n\n const onEnter = (): void => {\n hoverStart = Date.now();\n timerId = setTimeout(() => {\n client.track({\n projectId: apiKey,\n componentId: props.id,\n variantId: variantId!,\n eventType: 'cursor_signal',\n payload: { hoverDuration: Date.now() - hoverStart },\n });\n timerId = null;\n }, 800);\n };\n\n const onLeave = (): void => {\n if (timerId !== null) {\n clearTimeout(timerId);\n timerId = null;\n }\n };\n\n node.addEventListener('mouseenter', onEnter);\n node.addEventListener('mouseleave', onLeave);\n return () => {\n node.removeEventListener('mouseenter', onEnter);\n node.removeEventListener('mouseleave', onLeave);\n if (timerId !== null) clearTimeout(timerId);\n };\n }, [client, variantId, apiKey, props.id]);\n\n // Attach micro-signal detectors passively — rage click, text copy, scroll hesitation, tab loss.\n useEffect(() => {\n if (!client || !variantId) return;\n const node = containerRef.current;\n if (!node) return;\n const assignedAt = Date.now();\n return attachMicroSignalDetectors(\n (signalType, extra = {}) => {\n client.track({\n projectId: apiKey,\n componentId: props.id,\n variantId: variantId!,\n eventType: 'micro_signal',\n payload: { signalType, ...extra },\n });\n\n const mapping = props.microSignalGoals?.[signalType];\n if (!mapping || microGoalFiredRef.current.has(signalType)) return;\n microGoalFiredRef.current.add(signalType);\n const name = typeof mapping === 'string' ? mapping : mapping.name;\n const weight = typeof mapping === 'string' ? 1.0 : (mapping.weight ?? 1.0);\n const stepIndex = typeof mapping === 'string' ? 0 : (mapping.stepIndex ?? 0);\n client.goal(name, { signalType, ...extra }, weight, stepIndex);\n },\n node,\n assignedAt,\n );\n }, [client, variantId, apiKey, props.id, props.microSignalGoals]);\n\n // Attach goal tracking.\n useEffect(() => {\n if (!client || !variantId) return;\n const node = containerRef.current;\n if (!node) return;\n\n // --- Weighted composite: each step fires independently as it completes ---\n if (goal.type === 'weighted_composite') {\n const firedSteps = new Set<number>();\n const wcCleanups: Array<() => void> = [];\n\n goal.steps.forEach(({ goal: sub, name: stepName, weight: stepWeight }, idx) => {\n const fireStep = (): void => {\n if (firedSteps.has(idx)) return;\n firedSteps.add(idx);\n client.track({\n projectId: apiKey,\n componentId: props.id,\n variantId: variantId!,\n eventType: 'goal_achieved',\n goalType: stepName,\n payload: { reward: stepWeight },\n });\n client.goal(stepName, {}, stepWeight, idx);\n };\n\n if (sub.type === 'click') {\n const onClick = (e: MouseEvent): void => {\n const target = e.target;\n if (!(target instanceof Element)) return;\n if (!findClickable(target, node, sub.selector)) return;\n fireStep();\n };\n node.addEventListener('click', onClick);\n wcCleanups.push(() => node.removeEventListener('click', onClick));\n return;\n }\n\n if (sub.type === 'form_submit') {\n const onSubmit = (e: Event): void => {\n if (!(e.target instanceof HTMLFormElement)) return;\n if (!node.contains(e.target)) return;\n fireStep();\n };\n node.addEventListener('submit', onSubmit);\n wcCleanups.push(() => node.removeEventListener('submit', onSubmit));\n return;\n }\n\n if (sub.type === 'scroll_depth') {\n const threshold = Math.max(0, Math.min(1, sub.threshold));\n const io = new IntersectionObserver(\n (entries) => {\n for (const entry of entries) {\n if (entry.intersectionRatio >= threshold) {\n fireStep();\n io.disconnect();\n break;\n }\n }\n },\n { threshold: [threshold] },\n );\n io.observe(node);\n wcCleanups.push(() => io.disconnect());\n }\n });\n\n return () => {\n for (const c of wcCleanups) c();\n };\n }\n // --- End weighted composite ---\n\n const fireGoal = (): void => {\n if (goalFiredRef.current) return;\n goalFiredRef.current = true;\n client.track({\n projectId: apiKey,\n componentId: props.id,\n variantId,\n eventType: 'goal_achieved',\n goalType: goalLabel,\n payload: { reward: 1.0 },\n });\n client.goal(goalLabel, { componentId: props.id, variantId }, 1.0, 0);\n };\n\n const subgoals: GoalConfig[] = goal.type === 'composite' ? goal.all : [goal];\n const remaining = new Set<number>(subgoals.map((_, i) => i));\n const checkComposite = (idx: number): void => {\n remaining.delete(idx);\n if (remaining.size === 0) fireGoal();\n };\n\n const cleanups: Array<() => void> = [];\n\n subgoals.forEach((sub, idx) => {\n if (sub.type === 'click') {\n const onClick = (e: MouseEvent): void => {\n const target = e.target;\n if (!(target instanceof Element)) return;\n if (!findClickable(target, node, sub.selector)) return;\n if (goal.type === 'composite') checkComposite(idx);\n else fireGoal();\n };\n node.addEventListener('click', onClick);\n cleanups.push(() => node.removeEventListener('click', onClick));\n return;\n }\n\n if (sub.type === 'form_submit') {\n const onSubmit = (e: Event): void => {\n if (!(e.target instanceof HTMLFormElement)) return;\n if (!node.contains(e.target)) return;\n if (goal.type === 'composite') checkComposite(idx);\n else fireGoal();\n };\n node.addEventListener('submit', onSubmit);\n cleanups.push(() => node.removeEventListener('submit', onSubmit));\n return;\n }\n\n if (sub.type === 'scroll_depth') {\n const threshold = Math.max(0, Math.min(1, sub.threshold));\n const io = new IntersectionObserver(\n (entries) => {\n for (const entry of entries) {\n if (entry.intersectionRatio >= threshold) {\n if (goal.type === 'composite') checkComposite(idx);\n else fireGoal();\n io.disconnect();\n break;\n }\n }\n },\n { threshold: [threshold] },\n );\n io.observe(node);\n cleanups.push(() => io.disconnect());\n return;\n }\n });\n\n return () => {\n for (const c of cleanups) c();\n };\n }, [client, variantId, apiKey, props.id, goal, goalLabel]);\n\n // Decorative slots: empty in SSR HTML and until the client has mounted.\n if (props.clientOnly && (!mounted || !client)) return null;\n if (!variantId) return null;\n\n const jsxContent = props.variants[variantId] ?? null;\n const managedContent = jsxContent === null ? content : null;\n\n if (process?.env?.NODE_ENV !== 'production' && jsxContent === null && managedContent === null) {\n console.warn(\n `[sentient] <Adaptive id=\"${props.id}\"> was assigned variant \"${variantId}\" but no matching key exists in props.variants.` +\n ` If this is a dashboard-managed text variant, use <AdaptiveText id=\"${props.id}\"> instead.`,\n );\n }\n\n return (\n <div ref={containerRef} data-sentient-id={props.id} data-sentient-variant={variantId}>\n {jsxContent ?? managedContent}\n </div>\n );\n}\n\n/** Re-renders only when the chosen variant changes. */\nexport const Adaptive = memo(AdaptiveImpl, (prev, next) => {\n if (prev.id !== next.id) return false;\n if (JSON.stringify(prev.goal) !== JSON.stringify(next.goal)) return false;\n if (prev.microSignalGoals !== next.microSignalGoals) return false;\n if (prev.variants === next.variants) return true;\n const prevKeys = Object.keys(prev.variants);\n const nextKeys = Object.keys(next.variants);\n if (prevKeys.length !== nextKeys.length) return false;\n return prevKeys.every((k) => k in next.variants);\n});\n","import { useEffect, useRef, useState } from 'react';\nimport { type AssignResult } from '@sentientui/core';\nimport { useSentient, useInitialAssignments, useSessionSegment, useSsrFallback, useOnAssignment } from './provider.js';\nimport { subscribe, getWeights, type ComponentWeights } from './weights-store.js';\n\ndeclare global {\n interface Window { __sentient_overrides?: Record<string, string>; }\n}\n\nfunction getDevOverride(componentId: string): string | null {\n if (typeof window === 'undefined') return null;\n const global = window.__sentient_overrides?.[componentId];\n if (global) return global;\n try {\n const params = new URLSearchParams(window.location.search);\n for (const raw of params.getAll('sentient_variant')) {\n // sentient_variant=componentId:variantId (repeatable for multiple components)\n const sep = raw.indexOf(':');\n if (sep === -1) continue;\n if (raw.slice(0, sep) === componentId) return raw.slice(sep + 1);\n }\n } catch { /* non-browser env */ }\n return null;\n}\n\nexport type AssignmentState = {\n variantId: string | null;\n /** Populated when the assigned variant is a dashboard-managed text variant. */\n content: string | null;\n isLoading: boolean;\n};\n\nfunction pickFromWeights(weights: ComponentWeights, variantIds: string[]): string | null {\n let best: { variantId: string; avgReward: number } | null = null;\n for (const v of weights.variants) {\n if (!variantIds.includes(v.variantId)) continue;\n if (!best || v.avgReward > best.avgReward) {\n best = { variantId: v.variantId, avgReward: v.avgReward };\n }\n }\n return best?.variantId ?? null;\n}\n\n/**\n * Returns a sticky variant assignment for a component.\n *\n * First render reads the local SDK cache; if empty, falls back to a\n * deterministic default and asynchronously calls `/v1/assign`. The server\n * picks the actual variant via Thompson Sampling and the result replaces the fallback\n * on the next render. Subsequent paints read synchronously from cache —\n * no flicker, no loading state after first paint.\n */\nexport function useAssignment(componentId: string, variantIds: string[], agentData?: unknown, agentDataByVariant?: Record<string, unknown>): AssignmentState {\n const initialAssignments = useInitialAssignments();\n const ssrFallback = useSsrFallback();\n const client = useSentient();\n const segment = useSessionSegment();\n const onAssignment = useOnAssignment();\n const assignmentReportedRef = useRef<string | null>(null);\n\n // Dev override: URL param ?sentient_variant=componentId:variantId\n // or window.__sentient_overrides[componentId]. Short-circuits the bandit entirely.\n const devOverride = getDevOverride(componentId);\n const overrideVariant = devOverride && variantIds.includes(devOverride) ? devOverride : null;\n const overrideLoggedRef = useRef<string | null>(null);\n if (overrideVariant && overrideLoggedRef.current !== overrideVariant) {\n overrideLoggedRef.current = overrideVariant;\n console.info(`[sentient] override active: ${componentId} -> ${overrideVariant}`);\n }\n\n const initial = (() => {\n if (overrideVariant) {\n return { variantId: overrideVariant, content: null, isLoading: false };\n }\n // SSR / pre-hydration: no client yet. Use initialAssignments if provided so\n // the server and client first render agree on the same variant (no mismatch).\n if (!client) {\n const preloaded = initialAssignments[componentId];\n if (preloaded && variantIds.includes(preloaded)) {\n return { variantId: preloaded, content: null, isLoading: false };\n }\n if (ssrFallback === 'first' && variantIds.length > 0) {\n return { variantId: variantIds[0], content: null, isLoading: false };\n }\n return { variantId: null, content: null, isLoading: true };\n }\n const cached = client.getAssignment(componentId, segment);\n // Allow cached managed variants (content present) even if not in variantIds.\n if (cached && (variantIds.includes(cached.variantId) || cached.content)) {\n return { variantId: cached.variantId, content: cached.content ?? null, isLoading: false };\n }\n const weights = getWeights(componentId);\n if (weights) {\n const chosen = pickFromWeights(weights, variantIds);\n if (chosen) return { variantId: chosen, content: null, isLoading: false };\n }\n return { variantId: variantIds[0] ?? null, content: null, isLoading: false };\n })();\n\n const [state, setState] = useState<AssignmentState>(initial);\n\n // Helper: call onAssignment at most once per resolved variant.\n const reportAssignment = (variantId: string): void => {\n if (!onAssignment) return;\n if (assignmentReportedRef.current === variantId) return;\n assignmentReportedRef.current = variantId;\n onAssignment(componentId, variantId);\n };\n\n // As soon as the client is ready, unblock the UI immediately with variantIds[0]\n // (or a cached value) so the component never stays invisible while assign is\n // in-flight. The async assign call below then swaps to the bandit-chosen variant.\n useEffect(() => {\n if (overrideVariant) return;\n if (!client) return;\n const cached = client.getAssignment(componentId, segment);\n if (cached && (variantIds.includes(cached.variantId) || cached.content)) {\n setState({ variantId: cached.variantId, content: cached.content ?? null, isLoading: false });\n reportAssignment(cached.variantId);\n return;\n }\n setState((prev) => prev.variantId ? prev : { variantId: variantIds[0] ?? null, content: null, isLoading: false });\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [overrideVariant, client, componentId, segment]);\n\n // Ask the server for a real assignment when we have a client but no cached one.\n useEffect(() => {\n if (overrideVariant) return;\n if (!client) return;\n const cached = client.getAssignment(componentId, segment);\n if (cached && variantIds.includes(cached.variantId)) return;\n\n let cancelled = false;\n void client.assign(componentId, variantIds, agentData, agentDataByVariant).then((result: AssignResult | null) => {\n if (cancelled) return;\n if (!result) return;\n // Allow the result if it's a known code variant OR a managed text variant (has content).\n if (!variantIds.includes(result.variantId) && !result.content) return;\n setState({ variantId: result.variantId, content: result.content ?? null, isLoading: false });\n reportAssignment(result.variantId);\n });\n return () => { cancelled = true; };\n // variantIds intentionally excluded — changing variants mid-mount is unsupported\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [overrideVariant, client, componentId, segment]);\n\n // Live weight updates from the dashboard SSE stream (when wired).\n useEffect(() => {\n if (overrideVariant) return;\n if (!client) return;\n return subscribe(componentId, (weights) => {\n const cached = client.getAssignment(componentId, segment);\n if (cached && (variantIds.includes(cached.variantId) || cached.content)) {\n setState({ variantId: cached.variantId, content: cached.content ?? null, isLoading: false });\n return;\n }\n const chosen = pickFromWeights(weights, variantIds);\n if (chosen) setState({ variantId: chosen, content: null, isLoading: false });\n });\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [overrideVariant, client, componentId, segment]);\n\n if (overrideVariant) {\n return { variantId: overrideVariant, content: null, isLoading: false };\n }\n\n return state;\n}\n","'use client';\n\ndeclare const process: { env?: { NODE_ENV?: string } } | undefined;\n\nimport { useEffect, useRef, useState } from 'react';\nimport type { AssignResult } from '@sentientui/core';\nimport { useSentient, useAdaptiveApiKey, useOnAssignment, useSessionSegment } from './provider.js';\n\nexport type AdaptiveTextProps = {\n id: string;\n default: string;\n component?: keyof JSX.IntrinsicElements;\n className?: string;\n};\n\nexport function AdaptiveText({\n id,\n default: defaultText,\n component: Tag = 'span',\n className,\n}: AdaptiveTextProps) {\n const client = useSentient();\n const apiKey = useAdaptiveApiKey();\n const onAssignment = useOnAssignment();\n const segment = useSessionSegment();\n const trackedRef = useRef<string | null>(null);\n\n // Seed from cache synchronously so remounts don't flash back to defaultText.\n const [text, setText] = useState<string | null>(() =>\n client?.getAssignment(id, segment)?.content ?? null\n );\n const [variantId, setVariantId] = useState<string | null>(() =>\n client?.getAssignment(id, segment)?.variantId ?? null\n );\n\n useEffect(() => {\n if (!client) return;\n // Skip if content already cached; assign() re-checks internally but this avoids the async round-trip on remount.\n if (client.getAssignment(id, segment)?.content !== undefined) return;\n\n let cancelled = false;\n void client.assign(id).then((result: AssignResult | null) => {\n if (cancelled) return;\n if (!result) {\n if (process?.env?.NODE_ENV !== 'production') {\n console.warn(`[sentient] <AdaptiveText id=\"${id}\"> assignment failed — showing default text.`);\n }\n return;\n }\n setVariantId(result.variantId);\n if (result.content) setText(result.content);\n });\n return () => {\n cancelled = true;\n };\n }, [client, id, segment]);\n\n useEffect(() => {\n if (!client || !variantId || !apiKey) return;\n if (trackedRef.current === variantId) return;\n trackedRef.current = variantId;\n client.track({\n projectId: apiKey,\n componentId: id,\n variantId,\n eventType: 'variant_assigned',\n payload: {},\n });\n onAssignment?.(id, variantId);\n }, [client, variantId, apiKey, id, onAssignment]);\n\n return <Tag className={className}>{text ?? defaultText}</Tag>;\n}\n","import { useCallback } from 'react';\nimport type { ComponentGoalOptions } from '@sentientui/core';\nimport { useSentient } from './provider.js';\n\nexport type FireGoal = (goalType: string, opts?: ComponentGoalOptions) => void;\n\n/**\n * Returns a `fireGoal(goalType, opts?)` callback that records a conversion\n * attributed to the variant currently served for `componentId` — so it shows\n * up in the per-variant CVR funnel with no manual variantId/projectId plumbing.\n *\n * The served variant is resolved from the SDK's assignment cache (the same one\n * `<Adaptive id={componentId}>` populates), so render that component before\n * firing. Use this for imperative handlers (click, form submit, custom events);\n * for purely declarative goals prefer `<Adaptive goal={...}>`.\n *\n * @example\n * const fireContact = useAdaptiveGoal('hero_headline');\n * <button onClick={() => fireContact('hero_contact', { metadata: { method } })}>Call</button>\n */\nexport function useAdaptiveGoal(componentId: string): FireGoal {\n const client = useSentient();\n return useCallback<FireGoal>(\n (goalType, opts) => {\n client?.componentGoal(componentId, goalType, opts);\n },\n [client, componentId],\n );\n}\n","/** @deprecated Use `useSessionSegment()` from the provider, or `deriveSessionSegment` from `@sentientui/core`. */\nexport { deriveSessionSegment as detectSegment } from '@sentientui/core';\n","/**\n * Agent-readable content feed. Merges SDK-known data (winning variants, layout\n * order) with developer-supplied page content, and renders it either as a\n * server-rendered inline JSON-LD block (read by passive AI crawlers, which do\n * not run JS) or as Markdown (for agents that content-negotiate `text/markdown`).\n *\n * No React or DOM APIs — safe to import in server components, route handlers,\n * and middleware.\n */\n\nexport type AgentBlock = {\n /** Component ID. */\n id: string;\n /** Winning variant ID currently served. */\n variant: string;\n /** Agent-readable data attached to the served variant, if any. */\n content?: unknown;\n};\n\nexport type AgentFeed = {\n page: string;\n title?: string;\n summary?: string;\n layoutOrder?: string[];\n blocks: AgentBlock[];\n /** Developer-supplied extra fields (products, specs, arbitrary JSON). */\n [key: string]: unknown;\n};\n\n/** Fields the SDK owns — developer content can never overwrite these. */\nconst RESERVED_FIELDS = ['page', 'blocks', 'layoutOrder'] as const;\n\nconst registry = new Map<string, Record<string, unknown>>();\n\n/**\n * Register page-level structured content the SDK can't infer (title, summary,\n * product fields, arbitrary JSON), keyed by page path. Call at module load.\n */\nexport function defineAgentContent(page: string, content: Record<string, unknown>): void {\n registry.set(page, content);\n}\n\n/** Look up registered content for a page. */\nexport function getAgentContent(page: string): Record<string, unknown> | undefined {\n return registry.get(page);\n}\n\n/** Clear the registry — intended for tests. */\nexport function clearAgentContent(): void {\n registry.clear();\n}\n\n/**\n * Merge SDK-known data with developer-supplied content into a single feed.\n * Developer content fills in title/summary/etc. but can never overwrite the\n * SDK-authoritative fields (`page`, `blocks`, `layoutOrder`).\n */\nexport function buildAgentFeed(input: {\n page: string;\n blocks: AgentBlock[];\n layoutOrder?: string[];\n content?: Record<string, unknown>;\n}): AgentFeed {\n const supplied = input.content ?? getAgentContent(input.page) ?? {};\n const safe: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(supplied)) {\n if (!(RESERVED_FIELDS as readonly string[]).includes(k)) safe[k] = v;\n }\n const feed: AgentFeed = {\n ...safe,\n page: input.page,\n blocks: input.blocks,\n };\n if (input.layoutOrder) feed.layoutOrder = input.layoutOrder;\n return feed;\n}\n\n/**\n * Render the feed as a server-rendered inline JSON-LD `<script>` string. `<` is\n * escaped to `<` so embedded content cannot break out of the script\n * element. MUST be emitted on the server — passive crawlers never run client JS.\n */\nexport function renderAgentJsonLd(feed: AgentFeed): string {\n return `<script type=\"application/ld+json\">${renderAgentJsonLdBody(feed)}</script>`;\n}\n\n/**\n * The escaped JSON-LD body only (no `<script>` wrapper). For React server\n * components, inject via `<script type=\"application/ld+json\"\n * dangerouslySetInnerHTML={{ __html: renderAgentJsonLdBody(feed) }} />`.\n */\nexport function renderAgentJsonLdBody(feed: AgentFeed): string {\n return JSON.stringify({ '@context': 'https://schema.org', '@type': 'WebPage', ...feed })\n .replace(/</g, '\\\\u003c');\n}\n\n/** Render the feed as Markdown for agents that negotiate `text/markdown`. */\nexport function renderAgentMarkdown(feed: AgentFeed): string {\n const lines: string[] = [];\n if (feed.title) lines.push(`# ${feed.title}`, '');\n if (feed.summary) lines.push(String(feed.summary), '');\n\n for (const [k, v] of Object.entries(feed)) {\n if (['page', 'title', 'summary', 'blocks', 'layoutOrder'].includes(k)) continue;\n lines.push(`## ${k}`, '', '```json', JSON.stringify(v, null, 2), '```', '');\n }\n\n if (feed.blocks.length > 0) {\n lines.push('## blocks', '');\n for (const b of feed.blocks) {\n lines.push(`- **${b.id}** → variant \\`${b.variant}\\``);\n if (b.content !== undefined) {\n lines.push('', ' ```json', JSON.stringify(b.content, null, 2), ' ```');\n }\n }\n lines.push('');\n }\n\n return lines.join('\\n').trimEnd() + '\\n';\n}\n"],"mappings":";ubAIA,OAAS,iBAAAA,GAAe,cAAAC,EAAY,aAAAC,GAAW,WAAAC,GAAS,YAAAC,OAAgC,QACxF,OACE,qBAAAC,GACA,uBAAAC,GACA,QAAAC,OAGK,mBCKP,IAAMC,GAAQ,IAAI,IACZC,EAAY,IAAI,IAMf,SAASC,EAAUC,EAAqBC,EAA0B,CACvE,IAAIC,EAAMJ,EAAU,IAAIE,CAAW,EACnC,OAAKE,IACHA,EAAM,IAAI,IACVJ,EAAU,IAAIE,EAAaE,CAAG,GAEhCA,EAAI,IAAID,CAAE,EACH,IAAM,CACXC,EAAK,OAAOD,CAAE,EACVC,EAAK,OAAS,GAAGJ,EAAU,OAAOE,CAAW,CACnD,CACF,CAMO,SAASG,EAAOH,EAAqBI,EAAiC,CAC3EP,GAAM,IAAIG,EAAaI,CAAO,EAC9B,IAAMF,EAAMJ,EAAU,IAAIE,CAAW,EACrC,GAAKE,EACL,QAAWD,KAAMC,EACf,GAAI,CACFD,EAAGG,CAAO,CACZ,OAAQC,EAAA,CAER,CAEJ,CAKO,SAASC,EAAWN,EAA8C,CAxDzE,IAAAO,EAyDE,OAAOA,EAAAV,GAAM,IAAIG,CAAW,IAArB,KAAAO,EAA0B,IACnC,CD4MI,cAAAC,OAAA,o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,CAAC,EAAG,OAAO,EAG3ED,EAAM,KAAK,EAAE,CACf,CAEA,OAAOA,EAAM,KAAK;AAAA,CAAI,EAAE,QAAQ,EAAI;AAAA,CACtC","names":["createContext","useContext","useEffect","useMemo","useState","detectDeviceClass","detectTrafficSource","init","store","listeners","subscribe","componentId","cb","set","update","weights","e","getWeights","_a","jsx","deriveDefaultSegment","_a","_b","device","detectDeviceClass","source","detectTrafficSource","e","AdaptiveContext","createContext","AdaptiveProvider","props","client","setClient","useState","sessionSegment","useEffect","prev","config","cancelled","created","initGraph","__spreadProps","__spreadValues","init","poll","entries","entry","weights","v","update","timerId","ssrFallback","value","useMemo","useSentient","useContext","useAdaptiveApiKey","useInitialAssignments","useContext","AdaptiveContext","useSessionSegment","useSsrFallback","useOnAssignment","useLayoutOrder","memo","useEffect","useMemo","useRef","useState","attachMicroSignalDetectors","useEffect","useRef","useState","getDevOverride","componentId","_a","global","params","raw","sep","e","pickFromWeights","weights","variantIds","best","v","useAssignment","agentData","agentDataByVariant","initialAssignments","useInitialAssignments","ssrFallback","useSsrFallback","client","useSentient","segment","useSessionSegment","onAssignment","useOnAssignment","assignmentReportedRef","useRef","devOverride","overrideVariant","overrideLoggedRef","initial","_b","preloaded","cached","getWeights","chosen","state","setState","useState","reportAssignment","variantId","useEffect","prev","cancelled","result","subscribe","jsx","normalize","goal","PREVIEW_HTML_MAX_CHARS","shouldSendPreviewHtml","componentId","variantId","key","e","isClickableTarget","el","tag","findClickable","start","container","selector","cursor","AdaptiveImpl","props","_a","_b","client","useSentient","apiKey","useAdaptiveApiKey","variantIds","useMemo","content","useAssignment","containerRef","useRef","mounted","setMounted","useState","useEffect","goalFiredRef","microGoalFiredRef","assignTrackedRef","goalKey","goalLabel","rawHtml","includePreview","node","timerId","hoverStart","onEnter","onLeave","assignedAt","attachMicroSignalDetectors","signalType","extra","_c","__spreadValues","mapping","name","weight","stepIndex","firedSteps","wcCleanups","sub","stepName","stepWeight","idx","fireStep","onClick","target","onSubmit","threshold","io","entries","entry","c","fireGoal","subgoals","remaining","_","i","checkComposite","cleanups","jsxContent","managedContent","Adaptive","memo","prev","next","prevKeys","nextKeys","k","useEffect","useRef","useState","jsx","AdaptiveText","id","defaultText","Tag","className","client","useSentient","apiKey","useAdaptiveApiKey","onAssignment","useOnAssignment","segment","useSessionSegment","trackedRef","useRef","text","setText","useState","_a","_b","variantId","setVariantId","useEffect","cancelled","result","useCallback","useAdaptiveGoal","componentId","client","useSentient","useCallback","goalType","opts","deriveSessionSegment","RESERVED_FIELDS","registry","defineAgentContent","page","content","getAgentContent","buildAgentFeed","input","_a","_b","supplied","getAgentContent","safe","k","v","RESERVED_FIELDS","feed","__spreadProps","__spreadValues","renderAgentJsonLd","renderAgentJsonLdBody","renderAgentMarkdown","lines","b"]}
|
|
@@ -1,65 +1,5 @@
|
|
|
1
1
|
import { ReactNode } from 'react';
|
|
2
|
-
import {
|
|
3
|
-
|
|
4
|
-
/** How to render adaptive slots during SSR when assignments are not preloaded. */
|
|
5
|
-
type SsrFallback = 'first' | 'none';
|
|
6
|
-
type AdaptiveProviderProps = {
|
|
7
|
-
apiKey: string;
|
|
8
|
-
context: SentientConfig['context'];
|
|
9
|
-
debug?: boolean;
|
|
10
|
-
/**
|
|
11
|
-
* SSR-preloaded assignments from `preloadAssignments()` / `loadAdaptiveAssignments()`.
|
|
12
|
-
* Passed through to `useAssignment` as synchronous initial state so crawlers and
|
|
13
|
-
* the first paint see real content (recommended for SEO).
|
|
14
|
-
*/
|
|
15
|
-
initialAssignments?: Record<string, string>;
|
|
16
|
-
/**
|
|
17
|
-
* Bandit segment from SSR (`device:source`). Keeps cache, assign, and worker
|
|
18
|
-
* weights on one row — must match `loadAdaptiveAssignments` / session upsert.
|
|
19
|
-
*/
|
|
20
|
-
sessionSegment?: string;
|
|
21
|
-
/**
|
|
22
|
-
* When no `initialAssignments` exist for a component, `'first'` renders
|
|
23
|
-
* `variantIds[0]` in server HTML (safe default for SEO). Use `'none'` only for
|
|
24
|
-
* decorative slots marked `clientOnly`.
|
|
25
|
-
* @default 'first'
|
|
26
|
-
*/
|
|
27
|
-
ssrFallback?: SsrFallback;
|
|
28
|
-
/**
|
|
29
|
-
* Consent gate. When `false` the SDK is not initialised and no events are
|
|
30
|
-
* sent. Flip to `true` (e.g. after the user accepts the cookie banner) to
|
|
31
|
-
* initialise and begin tracking.
|
|
32
|
-
*/
|
|
33
|
-
consent?: boolean;
|
|
34
|
-
/**
|
|
35
|
-
* Behavior before consent is granted. Pass `'statistical_winner'` to serve the
|
|
36
|
-
* best-performing variant via `GET /v1/winner` with zero tracking while the
|
|
37
|
-
* consent banner is showing. Requires `consent: false`.
|
|
38
|
-
* @see SentientConfig.preConsentBehavior
|
|
39
|
-
*/
|
|
40
|
-
preConsentBehavior?: 'statistical_winner' | 'control';
|
|
41
|
-
/**
|
|
42
|
-
* Called once per component the first time a variant is resolved for that
|
|
43
|
-
* component in this session. Use to forward assignments to your own analytics
|
|
44
|
-
* (Mixpanel, PostHog, Segment, etc.) without having to wrap `useAssignment`.
|
|
45
|
-
*/
|
|
46
|
-
onAssignment?: (componentId: string, variantId: string) => void;
|
|
47
|
-
/**
|
|
48
|
-
* SSR-preloaded section order from `loadAdaptiveDecision()`.
|
|
49
|
-
* Pass the `layoutOrder` field from `DecideResult`. When set,
|
|
50
|
-
* `useLayoutOrder()` returns this on first render so there is no layout shift.
|
|
51
|
-
*/
|
|
52
|
-
initialLayoutOrder?: string[] | null;
|
|
53
|
-
/**
|
|
54
|
-
* Session ID generated during SSR (the `sessionId` field returned by
|
|
55
|
-
* `loadAdaptiveAssignments` / `loadAdaptiveDecision`). When provided and no
|
|
56
|
-
* existing session cookie or localStorage entry is found, the client adopts
|
|
57
|
-
* this ID so events and goals are attributed to the same session the server
|
|
58
|
-
* used for variant assignment.
|
|
59
|
-
*/
|
|
60
|
-
ssrSessionId?: string;
|
|
61
|
-
children: ReactNode;
|
|
62
|
-
};
|
|
2
|
+
import { AdaptiveProviderProps } from '@sentientui/react';
|
|
63
3
|
|
|
64
4
|
type AdaptiveRootClientProps = AdaptiveProviderProps & {
|
|
65
5
|
children: ReactNode;
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
'use client';
|
|
2
|
-
"use client";var
|
|
2
|
+
"use client";var d=Object.defineProperty;var r=Object.getOwnPropertySymbols;var v=Object.prototype.hasOwnProperty,a=Object.prototype.propertyIsEnumerable;var p=(o,e,t)=>e in o?d(o,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):o[e]=t,i=(o,e)=>{for(var t in e||(e={}))v.call(e,t)&&p(o,t,e[t]);if(r)for(var t of r(e))a.call(e,t)&&p(o,t,e[t]);return o};import{AdaptiveProvider as n}from"@sentientui/react";import{jsx as P}from"react/jsx-runtime";function c(o){return P(n,i({},o))}export{c as AdaptiveRootClient};
|
|
3
3
|
//# sourceMappingURL=adaptive-root-client.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/provider.tsx","../../src/weights-store.ts","../../src/next/adaptive-root-client.tsx"],"sourcesContent":["'use client';\n\ndeclare const process: { env?: { NODE_ENV?: string } } | undefined;\n\nimport { createContext, useContext, useEffect, useMemo, useState, type ReactNode } from 'react';\nimport {\n detectDeviceClass,\n detectTrafficSource,\n init,\n type SentientClient,\n type SentientConfig,\n} from '@sentientui/core';\nimport { update as updateWeightsStore, type ComponentWeights } from './weights-store.js';\n\n/**\n * Mirrors the segment derivation inside core `init()` so the cache key used\n * by `useAssignment` always matches the key `assign()` writes under. Before\n * this, the context defaulted to 'desktop:direct' while core used the\n * detected segment — a systematic cache miss for every integration that\n * didn't pass `sessionSegment` explicitly.\n */\nfunction deriveDefaultSegment(): string {\n if (typeof window === 'undefined') return 'desktop:direct';\n try {\n const device = detectDeviceClass(navigator.userAgent ?? '');\n const source = detectTrafficSource(document.referrer ?? '', window.location.origin);\n return `${device}:${source}`;\n } catch {\n return 'desktop:direct';\n }\n}\n\n/** How to render adaptive slots during SSR when assignments are not preloaded. */\nexport type SsrFallback = 'first' | 'none';\n\ntype AdaptiveContextValue = {\n client: SentientClient | null;\n // The publishable API key (pk_…). Historically named `projectId` because the\n // API uses it as the project identifier on the wire, but it is the API key,\n // not the project UUID. Field renamed for clarity.\n apiKey: string;\n initialAssignments: Record<string, string>;\n sessionSegment: string;\n ssrFallback: SsrFallback;\n onAssignment: ((componentId: string, variantId: string) => void) | undefined;\n initialLayoutOrder: string[] | null;\n};\n\nconst AdaptiveContext = createContext<AdaptiveContextValue>({\n client: null,\n apiKey: '',\n initialAssignments: {},\n sessionSegment: 'desktop:direct',\n ssrFallback: 'first',\n onAssignment: undefined,\n initialLayoutOrder: null,\n});\n\nexport type AdaptiveProviderProps = {\n apiKey: string;\n context: SentientConfig['context'];\n debug?: boolean;\n /**\n * SSR-preloaded assignments from `preloadAssignments()` / `loadAdaptiveAssignments()`.\n * Passed through to `useAssignment` as synchronous initial state so crawlers and\n * the first paint see real content (recommended for SEO).\n */\n initialAssignments?: Record<string, string>;\n /**\n * Bandit segment from SSR (`device:source`). Keeps cache, assign, and worker\n * weights on one row — must match `loadAdaptiveAssignments` / session upsert.\n */\n sessionSegment?: string;\n /**\n * When no `initialAssignments` exist for a component, `'first'` renders\n * `variantIds[0]` in server HTML (safe default for SEO). Use `'none'` only for\n * decorative slots marked `clientOnly`.\n * @default 'first'\n */\n ssrFallback?: SsrFallback;\n /**\n * Consent gate. When `false` the SDK is not initialised and no events are\n * sent. Flip to `true` (e.g. after the user accepts the cookie banner) to\n * initialise and begin tracking.\n */\n consent?: boolean;\n /**\n * Behavior before consent is granted. Pass `'statistical_winner'` to serve the\n * best-performing variant via `GET /v1/winner` with zero tracking while the\n * consent banner is showing. Requires `consent: false`.\n * @see SentientConfig.preConsentBehavior\n */\n preConsentBehavior?: 'statistical_winner' | 'control';\n /**\n * Called once per component the first time a variant is resolved for that\n * component in this session. Use to forward assignments to your own analytics\n * (Mixpanel, PostHog, Segment, etc.) without having to wrap `useAssignment`.\n */\n onAssignment?: (componentId: string, variantId: string) => void;\n /**\n * SSR-preloaded section order from `loadAdaptiveDecision()`.\n * Pass the `layoutOrder` field from `DecideResult`. When set,\n * `useLayoutOrder()` returns this on first render so there is no layout shift.\n */\n initialLayoutOrder?: string[] | null;\n /**\n * Session ID generated during SSR (the `sessionId` field returned by\n * `loadAdaptiveAssignments` / `loadAdaptiveDecision`). When provided and no\n * existing session cookie or localStorage entry is found, the client adopts\n * this ID so events and goals are attributed to the same session the server\n * used for variant assignment.\n */\n ssrSessionId?: string;\n children: ReactNode;\n};\n\n/**\n * Initialises the Sentient core SDK in a useEffect (SSR-safe) and exposes the\n * client via React context. Re-initialises when `consent` changes.\n */\nexport function AdaptiveProvider(props: AdaptiveProviderProps): JSX.Element {\n const [client, setClient] = useState<SentientClient | null>(null);\n // Derived once per mount: identical to what core init() computes, so cache\n // reads (context segment) and cache writes (core segment) always agree.\n const [sessionSegment] = useState(() => props.sessionSegment ?? deriveDefaultSegment());\n\n useEffect(() => {\n // When consent is explicitly false with no preConsentBehavior, tear down any existing client.\n if (props.consent === false && !props.preConsentBehavior) {\n setClient((prev: SentientClient | null) => {\n prev?.destroy();\n return null;\n });\n return;\n }\n\n const c = init({\n apiKey: props.apiKey,\n context: props.context,\n debug: props.debug,\n initialAssignments: props.initialAssignments,\n sessionSegment,\n consent: props.consent,\n preConsentBehavior: props.preConsentBehavior,\n ssrSessionId: props.ssrSessionId,\n });\n setClient(c);\n return () => {\n c.destroy();\n };\n // Re-init when consent changes. Other props are intentionally stable.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [props.consent]);\n\n // Poll /v1/weights every 60 s so long-lived sessions see updated bandit weights\n // without a page reload. useAssignment subscribers react via weights-store.\n useEffect(() => {\n if (!client) return;\n let cancelled = false;\n const poll = async (): Promise<void> => {\n if (cancelled) return;\n let entries;\n try {\n entries = await client.fetchWeights();\n } catch {\n // Network/transient error: skip this cycle and retry on the next\n // interval. Swallowed deliberately so a failed poll never surfaces as\n // an unhandled rejection.\n return;\n }\n if (cancelled) return;\n for (const entry of entries) {\n const weights: ComponentWeights = {\n componentId: entry.componentId,\n updatedAt: entry.updatedAt,\n variants: entry.variants.map((v) => ({\n variantId: v.variantId,\n pulls: v.pulls,\n avgReward: v.avgReward ?? 0,\n })),\n };\n updateWeightsStore(entry.componentId, weights);\n }\n };\n void poll();\n const timerId = setInterval(() => void poll(), 60_000);\n return () => {\n cancelled = true;\n clearInterval(timerId);\n };\n }, [client]);\n\n const ssrFallback = props.ssrFallback ?? 'first';\n\n // Memoized so unrelated parent re-renders don't cascade through every\n // useSentient / useAssignment consumer via a fresh context object.\n const value = useMemo<AdaptiveContextValue>(\n () => ({\n client,\n apiKey: props.apiKey,\n initialAssignments: props.initialAssignments ?? {},\n sessionSegment,\n ssrFallback,\n onAssignment: props.onAssignment,\n initialLayoutOrder: props.initialLayoutOrder ?? null,\n }),\n [\n client,\n props.apiKey,\n props.initialAssignments,\n sessionSegment,\n ssrFallback,\n props.onAssignment,\n props.initialLayoutOrder,\n ],\n );\n\n return (\n <AdaptiveContext.Provider value={value}>\n {props.children}\n </AdaptiveContext.Provider>\n );\n}\n\n/**\n * Returns the SentientClient, or null until the provider has finished\n * initialising on the client.\n */\nexport function useSentient(): SentientClient | null {\n return useContext(AdaptiveContext).client;\n}\n\n/** Internal: publishable API key carried alongside the client. */\nexport function useAdaptiveApiKey(): string {\n return useContext(AdaptiveContext).apiKey;\n}\n\n/**\n * @deprecated Renamed to `useAdaptiveApiKey`. Kept as an alias so external\n * imports from earlier versions of this package keep working. Will be removed\n * in 1.0.0.\n */\nlet warnedProjectIdAlias = false;\nexport function useAdaptiveProjectId(): string {\n if (\n !warnedProjectIdAlias &&\n typeof process !== 'undefined' &&\n process.env?.NODE_ENV !== 'production'\n ) {\n warnedProjectIdAlias = true;\n console.warn(\n '[@sentientui/react] useAdaptiveProjectId is deprecated; use useAdaptiveApiKey. Will be removed in 1.0.0.',\n );\n }\n return useAdaptiveApiKey();\n}\n\n/** Internal: SSR-preloaded assignments for hydration-safe first render. */\nexport function useInitialAssignments(): Record<string, string> {\n return useContext(AdaptiveContext).initialAssignments;\n}\n\n/** Internal: bandit segment aligned with SSR session upsert. */\nexport function useSessionSegment(): string {\n return useContext(AdaptiveContext).sessionSegment;\n}\n\n/** Internal: SSR fallback strategy when a slot has no preloaded assignment. */\nexport function useSsrFallback(): SsrFallback {\n return useContext(AdaptiveContext).ssrFallback;\n}\n\n/** Internal: forwarding hook for consumer analytics integration. */\nexport function useOnAssignment(): ((componentId: string, variantId: string) => void) | undefined {\n return useContext(AdaptiveContext).onAssignment;\n}\n\n/**\n * Returns the persona-specific section order from SSR, or null when no\n * sections were declared on AdaptiveRoot or reliability is below threshold.\n */\nexport function useLayoutOrder(): string[] | null {\n return useContext(AdaptiveContext).initialLayoutOrder;\n}\n","/** Per-component weights store with isolated subscriptions. */\n\nexport type VariantWeight = {\n variantId: string;\n pulls: number;\n avgReward: number;\n};\n\nexport type ComponentWeights = {\n componentId: string;\n variants: VariantWeight[];\n updatedAt: number;\n};\n\ntype Listener = (weights: ComponentWeights) => void;\n\nconst store = new Map<string, ComponentWeights>();\nconst listeners = new Map<string, Set<Listener>>();\n\n/**\n * Subscribes a listener to a single component. Returns an unsubscribe function.\n * Updates to other components never trigger this listener.\n */\nexport function subscribe(componentId: string, cb: Listener): () => void {\n let set = listeners.get(componentId);\n if (!set) {\n set = new Set();\n listeners.set(componentId, set);\n }\n set.add(cb);\n return () => {\n set!.delete(cb);\n if (set!.size === 0) listeners.delete(componentId);\n };\n}\n\n/**\n * Replaces the weights for a component and notifies only that component's\n * subscribers.\n */\nexport function update(componentId: string, weights: ComponentWeights): void {\n store.set(componentId, weights);\n const set = listeners.get(componentId);\n if (!set) return;\n for (const cb of set) {\n try {\n cb(weights);\n } catch {\n /* never throw to other listeners */\n }\n }\n}\n\n/**\n * Returns the latest known weights for a component, or null if none seen.\n */\nexport function getWeights(componentId: string): ComponentWeights | null {\n return store.get(componentId) ?? null;\n}\n\n/** Test-only: wipe the entire store. */\nexport function _resetWeightsStore(): void {\n store.clear();\n listeners.clear();\n}\n","'use client';\n\nimport type { ReactNode } from 'react';\nimport { AdaptiveProvider, type AdaptiveProviderProps } from '../provider.js';\n\nexport type AdaptiveRootClientProps = AdaptiveProviderProps & {\n children: ReactNode;\n};\n\n/** Client boundary for {@link AdaptiveRoot} — keeps context/hooks out of the server bundle. */\nexport function AdaptiveRootClient(props: AdaptiveRootClientProps): JSX.Element {\n return <AdaptiveProvider {...props} />;\n}\n"],"mappings":";sWAIA,OAAS,iBAAAA,EAAe,cAAAC,EAAY,aAAAC,EAAW,WAAAC,EAAS,YAAAC,MAAgC,QACxF,OACE,qBAAAC,EACA,uBAAAC,EACA,QAAAC,MAGK,mBCKP,IAAMC,EAAQ,IAAI,IACZC,EAAY,IAAI,IAuBf,SAASC,EAAOC,EAAqBC,EAAiC,CAC3EC,EAAM,IAAIF,EAAaC,CAAO,EAC9B,IAAME,EAAMC,EAAU,IAAIJ,CAAW,EACrC,GAAKG,EACL,QAAWE,KAAMF,EACf,GAAI,CACFE,EAAGJ,CAAO,CACZ,OAAQK,EAAA,CAER,CAEJ,CDuKI,cAAAC,MAAA,oBArMJ,SAASC,GAA+B,CArBxC,IAAAC,EAAAC,EAsBE,GAAI,OAAO,QAAW,YAAa,MAAO,iBAC1C,GAAI,CACF,IAAMC,EAASC,GAAkBH,EAAA,UAAU,YAAV,KAAAA,EAAuB,EAAE,EACpDI,EAASC,GAAoBJ,EAAA,SAAS,WAAT,KAAAA,EAAqB,GAAI,OAAO,SAAS,MAAM,EAClF,MAAO,GAAGC,CAAM,IAAIE,CAAM,EAC5B,OAAQE,EAAA,CACN,MAAO,gBACT,CACF,CAkBA,IAAMC,EAAkBC,EAAoC,CAC1D,OAAQ,KACR,OAAQ,GACR,mBAAoB,CAAC,EACrB,eAAgB,iBAChB,YAAa,QACb,aAAc,OACd,mBAAoB,IACtB,CAAC,EAgEM,SAASC,EAAiBC,EAA2C,CAxH5E,IAAAV,EAyHE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AM,CAAC,EAEX,IAAMgB,GAAc3B,EAAAU,EAAM,cAAN,KAAAV,EAAqB,QAInC4B,EAAQC,EACZ,IAAG,CArMP,IAAA7B,EAAAC,EAqMW,OACL,OAAAU,EACA,OAAQD,EAAM,OACd,oBAAoBV,EAAAU,EAAM,qBAAN,KAAAV,EAA4B,CAAC,EACjD,eAAAc,EACA,YAAAa,EACA,aAAcjB,EAAM,aACpB,oBAAoBT,EAAAS,EAAM,qBAAN,KAAAT,EAA4B,IAClD,GACA,CACEU,EACAD,EAAM,OACNA,EAAM,mBACNI,EACAa,EACAjB,EAAM,aACNA,EAAM,kBACR,CACF,EAEA,OACEZ,EAACS,EAAgB,SAAhB,CAAyB,MAAOqB,EAC9B,SAAAlB,EAAM,SACT,CAEJ,CEnNS,cAAAoB,MAAA,oBADF,SAASC,EAAmBC,EAA6C,CAC9E,OAAOF,EAACG,EAAAC,EAAA,GAAqBF,EAAO,CACtC","names":["createContext","useContext","useEffect","useMemo","useState","detectDeviceClass","detectTrafficSource","init","store","listeners","update","componentId","weights","store","set","listeners","cb","e","jsx","deriveDefaultSegment","_a","_b","device","detectDeviceClass","source","detectTrafficSource","e","AdaptiveContext","createContext","AdaptiveProvider","props","client","setClient","useState","sessionSegment","useEffect","prev","c","init","cancelled","poll","entries","entry","weights","v","update","timerId","ssrFallback","value","useMemo","jsx","AdaptiveRootClient","props","AdaptiveProvider","__spreadValues"]}
|
|
1
|
+
{"version":3,"sources":["../../src/next/adaptive-root-client.tsx"],"sourcesContent":["'use client';\n\nimport type { ReactNode } from 'react';\n// Import from the package entry (kept `external` in tsup) — NOT the relative\n// '../provider.js'. A relative import makes tsup inline a second copy of\n// provider.js into this /next bundle, which runs createContext() again and\n// yields a DISTINCT AdaptiveContext. The result: <AdaptiveRoot> populates its\n// own context while useSentient()/<Adaptive> (from the main entry) read a\n// different one that stays {client:null} forever — so no events/goals ever\n// fire. Importing the package specifier shares the single context singleton.\nimport { AdaptiveProvider, type AdaptiveProviderProps } from '@sentientui/react';\n\nexport type AdaptiveRootClientProps = AdaptiveProviderProps & {\n children: ReactNode;\n};\n\n/** Client boundary for {@link AdaptiveRoot} — keeps context/hooks out of the server bundle. */\nexport function AdaptiveRootClient(props: AdaptiveRootClientProps): JSX.Element {\n return <AdaptiveProvider {...props} />;\n}\n"],"mappings":";sWAUA,OAAS,oBAAAA,MAAoD,oBAQpD,cAAAC,MAAA,oBADF,SAASC,EAAmBC,EAA6C,CAC9E,OAAOF,EAACG,EAAAC,EAAA,GAAqBF,EAAO,CACtC","names":["AdaptiveProvider","jsx","AdaptiveRootClient","props","AdaptiveProvider","__spreadValues"]}
|