@sentientui/core 0.21.3 → 0.22.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.
@@ -0,0 +1,2 @@
1
+ import{a as fe,c as Ee,e as Ie,j as _e,k as Ce,l as Ae,m as Te,p as Oe,q as me,s as Re}from"./chunk-QNEYUJJJ.mjs";import{a as _,b as se}from"./chunk-TMCGHANO.mjs";function ye(){try{if(typeof crypto!="undefined"&&typeof crypto.randomUUID=="function")return crypto.randomUUID()}catch(e){}try{if(typeof crypto!="undefined"&&typeof crypto.getRandomValues=="function"){let e=new Uint8Array(16);crypto.getRandomValues(e),e[6]=e[6]&15|64,e[8]=e[8]&63|128;let n="";for(let s=0;s<16;s++)n+=e[s].toString(16).padStart(2,"0"),(s===3||s===5||s===7||s===9)&&(n+="-");return n}}catch(e){}return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let n=Math.random()*16|0;return(e==="x"?n:n&3|8).toString(16)})}var ot="_snt_uid",st=365,he="_snt_uid";function rt(){return ye()}function $e(e){try{let n=document.cookie.match(new RegExp(`(?:^|; )${e}=([^;]*)`));return n?decodeURIComponent(n[1]):null}catch(n){return null}}function it(e,n,s){try{document.cookie=`${e}=${encodeURIComponent(n)}; max-age=${s}; SameSite=strict; path=/`}catch(d){}}function Be(e){try{return localStorage.getItem(e)}catch(n){return null}}function We(e,n){try{return localStorage.setItem(e,n),!0}catch(s){return!1}}function je(e){try{return sessionStorage.getItem(e)}catch(n){return null}}function at(e,n){try{return sessionStorage.setItem(e,n),!0}catch(s){return!1}}function lt(e){try{sessionStorage.removeItem(e)}catch(n){}}function ct(e){try{return document.cookie=`${e}_probe=1; max-age=1; SameSite=strict; path=/`,document.cookie.indexOf(`${e}_probe=1`)!==-1}catch(n){return!1}}function dt(e){try{localStorage.removeItem(e)}catch(n){}}function ut(e){try{document.cookie=`${e}=; max-age=0; SameSite=strict; path=/`}catch(n){}}var pt={getSessionId:()=>null,isEphemeral:()=>!1,destroy:()=>{}};function Se(e){var x,O,R,E,G,F,C;if(typeof window=="undefined")return pt;let n=fe(e==null?void 0:e.apiKey),s=(x=e==null?void 0:e.cookieName)!=null?x:Ee(e==null?void 0:e.apiKey),d=`${he}${n}`,f=`${he}_tomb${n}`,l=((O=e==null?void 0:e.cookieTTLDays)!=null?O:st)*24*60*60,i=v=>v&&v.length>0?v:null,u=()=>{var v,L;return n&&!(e!=null&&e.cookieName)&&Be(f)===null?(L=(v=i($e(ot)))!=null?v:i(Be(he)))!=null?L:i(je(he)):null},r=(C=(F=(G=(E=(R=i($e(s)))!=null?R:i(Be(d)))!=null?E:i(je(d)))!=null?G:u())!=null?F:i(e==null?void 0:e.ssrSessionId))!=null?C:rt();it(s,r,l);let t=We(d,r),o=ct(s),y=t?!1:at(d,r),h=!t&&!o&&!y;return{getSessionId:()=>r,isEphemeral:()=>h,destroy:()=>{r=null,ut(s),dt(d),lt(d),n&&!(e!=null&&e.cookieName)&&We(f,"1")}}}function X(e){return Math.min(6e4,1e3*2**Math.min(e,6))}function re(e){if(e.ok===!0)return"delivered";let{status:n}=e;return typeof n!="number"?"retry":n>=200&&n<300?"delivered":n>=400&&n<500&&n!==429?"dropped":"retry"}function ve(e,n){try{let s=localStorage.getItem(e);if(!s)return[];let d=JSON.parse(s);return Array.isArray(d)?(localStorage.removeItem(e),d.slice(-n)):[]}catch(s){return[]}}function Y(e,n,s){try{let d=(()=>{try{let a=localStorage.getItem(s);if(!a)return[];let l=JSON.parse(a);return Array.isArray(l)?l:[]}catch(a){return[]}})(),f=new Map;for(let a of d)f.set(a.id,a);for(let a of e)f.set(a.id,a);localStorage.setItem(s,JSON.stringify([...f.values()].slice(-n)))}catch(d){}}function we(e,n){try{let s=localStorage.getItem(n);if(!s)return;let d=JSON.parse(s);if(!Array.isArray(d))return;let f=new Set(e),a=d.filter(l=>!f.has(l.id));if(a.length===d.length)return;a.length===0?localStorage.removeItem(n):localStorage.setItem(n,JSON.stringify(a))}catch(s){}}var gt=500,ft=56*1024;function Le(e){return`_snt_retry_${e.slice(0,12)}`}var mt={push:()=>{},flush:()=>{},destroy:()=>{}};function He(e){var q,M,te;if(typeof window=="undefined")return mt;let n=(q=e.flushIntervalMs)!=null?q:5e3,s=(M=e.maxBatchSize)!=null?M:20,d=(te=e.maxRetrySize)!=null?te:100,f=e.ingestUrl,a=e.apiKey,l=Le(a),i=[],u=new Set,r=[],t=g=>{for(let k of g)o.delete(k),!u.has(k)&&(u.add(k),r.push(k));for(;r.length>gt;){let k=r.shift();k&&u.delete(k)}we(g,l)},o=new Set,y=()=>{for(;i.length>d;){let g=i.shift();g&&o.delete(g.id)}},h=g=>{u.has(g.id)||o.has(g.id)||(o.add(g.id),i.push(g),y())},x=g=>{for(let k of g)u.has(k.id)||(o.add(k.id),i.push(k));y()},O=ve(l,d);for(let g of O)h(g);let R=0,E=0,G=(g,k=!0)=>{if(g.length===0)return;let j=JSON.stringify(g),Z=g.map(Q=>Q.id),$;try{$=fetch(f,{method:"POST",keepalive:!0,body:j,headers:{"Content-Type":"application/json",Authorization:`Bearer ${a}`}})}catch(Q){Y(g,d,l),x(g),E++,R=Date.now()+X(E);return}let ae=Q=>{if(re(Q)!=="retry"){if(!Q.ok&&k){let ne=g.filter(z=>z.eventType!=="pageview");if(ne.length>0&&ne.length<g.length){t(g.filter(z=>z.eventType==="pageview").map(z=>z.id)),G(ne,!1);return}}t(Z),E=0,R=0;return}Y(g,d,l),x(g),E++,R=Date.now()+X(E)};$ instanceof Promise?$.then(ae).catch(()=>{Y(g,d,l),x(g),E++,R=Date.now()+X(E)}):ae($)},F=typeof TextEncoder!="undefined"?new TextEncoder:null,C=g=>F?F.encode(g).length:g.length,v=g=>{let k=[],j=2;for(let Z of g){let $=C(JSON.stringify(Z))+1;if(k.length>0&&j+$>ft||k.length>=s)break;k.push(Z),j+=$}return k},L=()=>{try{if(Date.now()<R)return;for(;i.length>0&&!(Date.now()<R);){let g=i.filter(j=>!u.has(j.id));if(i.length=0,g.length===0)break;let k=v(g);if(k.length===0)break;k.length<g.length&&i.push(...g.slice(k.length)),G(k)}}catch(g){}},m=!0,T=null;T=setInterval(()=>{m&&L()},n);let P=()=>{document.visibilityState==="hidden"&&L()},W=()=>{L()};return document.addEventListener("visibilitychange",P),window.addEventListener("pagehide",W),{push(g){h(g),i.length>=s&&L()},flush:L,destroy(){m=!1,T!==null&&(clearInterval(T),T=null),document.removeEventListener("visibilitychange",P),window.removeEventListener("pagehide",W),L()}}}var yt=200;function De(e){return`_snt_goal_retry_${e.slice(0,12)}`}var ht={send:()=>{},flush:()=>{},destroy:()=>{}};function Qe(e){var C,v,L;if(typeof window=="undefined")return ht;let n=(C=e.flushIntervalMs)!=null?C:5e3,s=(v=e.maxRetrySize)!=null?v:100,d=(L=e.maxPerFlush)!=null?L:5,f=De(e.apiKey),a=[],l=new Set,i=new Set,u=[],r=0,t=0,o=!1,y=m=>{for(l.delete(m.id),i.has(m.id)||(i.add(m.id),u.push(m.id));u.length>yt;){let T=u.shift();T&&i.delete(T)}we([m.id],f)},h=m=>{Y([m],s,f),!i.has(m.id)&&!l.has(m.id)&&(l.add(m.id),a.push(m)),Date.now()>=r&&(t++,r=Date.now()+X(t))},x=m=>{let T;try{T=fetch(e.url,{method:"POST",keepalive:!0,body:m.body,headers:e.headers})}catch(W){h(m);return}let P=W=>{var M;let q=re(W);if(q==="retry"){h(m);return}q==="dropped"&&((M=e.onDrop)==null||M.call(e,m,W.status)),y(m),t=0,r=0};T instanceof Promise?T.then(P).catch(()=>h(m)):P(T)},O=()=>{try{if(o||Date.now()<r)return;let m=0;for(;a.length>0&&m<d&&!(Date.now()<r);){let T=a.shift();l.delete(T.id),!i.has(T.id)&&(m++,x(T))}}catch(m){}},R=ve(f,s);for(let m of R)l.has(m.id)||(l.add(m.id),a.push(m));R.length>0&&Y(R,s,f);let E=setInterval(O,n),G=()=>{document.visibilityState==="hidden"&&O()},F=()=>O();return document.addEventListener("visibilitychange",G),window.addEventListener("pagehide",F),{send(m){if(!o&&!(i.has(m.id)||l.has(m.id))){if(Date.now()<r){Y([m],s,f),l.add(m.id),a.push(m);return}x(m)}},flush:O,destroy(){clearInterval(E),document.removeEventListener("visibilitychange",G),window.removeEventListener("pagehide",F),O(),o=!0}}}var St=1800*1e3;function ke(e,n){return`${encodeURIComponent(e)}:${encodeURIComponent(n)}`}function ze(e=St,n){let s=new Map,d=`_snt_asgn${fe(n)}_`,f=(r,t)=>`${d}${encodeURIComponent(r)}:${encodeURIComponent(t)}`,a=r=>{let t=r.slice(d.length),o=t.indexOf(":");if(o<0)return null;try{return{componentId:decodeURIComponent(t.slice(0,o)),segment:decodeURIComponent(t.slice(o+1))}}catch(y){return null}},l=()=>{try{let r=[];for(let t=0;t<localStorage.length;t++){let o=localStorage.key(t);o!=null&&o.startsWith(d)&&r.push(o)}return r}catch(r){return[]}},i=r=>r.assignedAt+(r.ttlMs&&r.ttlMs>0?r.ttlMs:e)<Date.now();return typeof window!="undefined"&&(()=>{for(let r of l())try{let t=localStorage.getItem(r);if(!t)continue;let o=JSON.parse(t);if(i(o)){localStorage.removeItem(r);continue}let y=a(r);if(!y)continue;s.set(ke(y.componentId,y.segment),o)}catch(t){}})(),{get(r,t){let o=s.get(ke(r,t));return o?i(o)?(s.delete(ke(r,t)),null):o:null},set(r,t,o){let y=ke(r,t);s.set(y,o);try{localStorage.setItem(f(r,t),JSON.stringify(o))}catch(h){}},clear(){s.clear();for(let r of l())try{localStorage.removeItem(r)}catch(t){}}}}var ie="_snt_snap:",vt=["low","medium","high"];function de(e){try{let n=localStorage.getItem(ie+e);if(!n)return null;let s=JSON.parse(n);return!s||typeof s!="object"||s.v!==1||typeof s.persona!="string"||typeof s.band!="string"||!vt.includes(s.band)||typeof s.slots!="object"||s.slots===null||Array.isArray(s.slots)||!(s.layoutOrder===null||Array.isArray(s.layoutOrder))||typeof s.savedAt!="number"||!(s.slotConfig===void 0||typeof s.slotConfig=="object"&&s.slotConfig!==null&&!Array.isArray(s.slotConfig))?null:s}catch(n){return null}}function ue(e,n){try{localStorage.setItem(ie+e,JSON.stringify(n))}catch(s){}}function wt(e){return"(function(){try{var r=localStorage.getItem("+JSON.stringify(ie+e).replace(/</g,"\\u003c")+');if(!r)return;var s=JSON.parse(r);if(!s||s.v!==1||typeof s.persona!=="string"||typeof s.band!=="string")return;var d=document.documentElement;if(d.hasAttribute("data-sentient-persona"))return;d.setAttribute("data-sentient-persona",s.persona);d.setAttribute("data-sentient-confidence",s.band);}catch(e){}})();'}import{confidenceBand as Ye}from"@sentientui/policy";import{confidenceBand as Pe}from"@sentientui/policy";var Me="[sentient] No API key configured \u2014 nothing is being learned. Set NEXT_PUBLIC_SENTIENT_API_KEY or pass localMode: true for local development.",Ve="[sentient] Local mode \u2014 decisions are simulated on-device and nothing is sent over the network. Add an API key to learn from real traffic.",Je=!1,be=!1;function kt(){var e;try{return(e=new URLSearchParams(window.location.search).get("sentient_persona"))!=null?e:void 0}catch(n){return}}function Xe(e){var r;let n=Se({ssrSessionId:e.ssrSessionId,apiKey:e.apiKey}),s=(r=n.getSessionId())!=null?r:"local",d=kt(),f=import("@sentientui/core/local").then(t=>{let o=t;return o.LOCAL_ENGINE_AVAILABLE?(Je||(Je=!0,console.info(Ve)),o):(be||(be=!0,console.error(Me)),null)}).catch(()=>(be||(be=!0,console.error(Me)),null)),a=null,l={low:.15,medium:.5,high:.85},i=(()=>{var o;if(e.initialPersona)return _({},e.initialPersona);let t=de(e.apiKey||"local");return t?{persona:t.persona,confidence:(o=l[t.band])!=null?o:.15}:null})();function u(t){let o=document.documentElement;o.dataset.sentientPersona===void 0&&(o.dataset.sentientPersona=t.persona,o.dataset.sentientConfidence=Pe(t.confidence))}return{isLocal:!0,async decide(t){var h,x,O;let o=await f;if(!o)return null;let y=o.createLocalEngine({sessionId:s,forcedPersona:d}).decide(t);return a=se(_({},y),{layoutOrder:(x=(h=y.layoutOrder)!=null?h:a==null?void 0:a.layoutOrder)!=null?x:null,slots:_(_({},(O=a==null?void 0:a.slots)!=null?O:{}),y.slots)}),ue(e.apiKey||"local",{v:1,persona:a.persona,band:Pe(a.confidence),slots:a.slots,layoutOrder:a.layoutOrder,savedAt:Date.now()}),u(y),y},getSlotResult(t){var o,y,h;return(h=(y=a==null?void 0:a.slots[t])!=null?y:(o=e.initialSlots)==null?void 0:o[t])!=null?h:null},getPersona(){let t=a!=null?a:i;return t?{persona:t.persona,confidence:t.confidence,band:Pe(t.confidence)}:null},async assign(t,o){var x;let y=await f;return!y||!o||o.length===0?o!=null&&o[0]?{variantId:o[0],assignmentTtlMs:0}:null:{variantId:(x=y.createLocalEngine({sessionId:s,forcedPersona:d}).decide({components:[{id:t,variantIds:o}]}).assignments[t])!=null?x:o[0],assignmentTtlMs:0}},track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},getAssignment:()=>null,fetchWeights:()=>Promise.resolve([]),getGraph:()=>({pageNodes:[],capturedAt:0}),dispose:()=>{},destroy:()=>n.destroy()}}var zt=["none","sm","md","lg"],Jt=["start","center","end","stretch"],Vt=["start","center","end","between"],Xt=["sm","md","lg"],Yt=["normal","medium","bold"],qt=["default","muted","accent"],Zt=["primary","secondary","ghost"],en=["left","center","right"],tn=["auto","square","landscape","wide"],nn=["cover","contain"],on=[2,3,4],sn=[2,3,4],rn=64,an=5,ln=12,cn=4,dn=500;function bt(e,n,s,d){let f=[];{let i=!1,u=[],r=()=>{if(i)return;let t=Date.now();for(u.push(t);u.length>0&&t-u[0]>500;)u.shift();u.length>=3&&(i=!0,e("rage_click"))};n.addEventListener("click",r),f.push(()=>n.removeEventListener("click",r))}{let a=!1,l=i=>{if(a||!(i.target instanceof Node)||!n.contains(i.target)&&n!==i.target)return;a=!0;let u=typeof window!="undefined"?window.getSelection():null,r=u?u.toString().length:0;e("text_copy",{selectionLength:r})};document.addEventListener("copy",l),f.push(()=>document.removeEventListener("copy",l))}{let a=!1,l=!1,i=null,u=()=>{i!==null&&(clearTimeout(i),i=null)},r=()=>{a||!l||(u(),i=setTimeout(()=>{!a&&l&&(a=!0,e("scroll_hesitation"))},3e3))},t=()=>{u(),r()},o=h=>{for(let x of h)l=x.intersectionRatio>.3,l?r():u()},y=new IntersectionObserver(o,{threshold:[.3]});y.observe(n),window.addEventListener("scroll",t,{passive:!0}),f.push(()=>{y.disconnect(),window.removeEventListener("scroll",t),u()})}if((d==null?void 0:d.tabLoss)!==!1){let a=!1,l=s!=null?s:Date.now(),i=()=>{if(a||document.visibilityState!=="hidden")return;let u=Date.now()-l;u<15e3&&(a=!0,e("tab_loss",{timeOnPage:u}))};document.addEventListener("visibilitychange",i),f.push(()=>document.removeEventListener("visibilitychange",i))}return()=>{for(let a of f)a()}}var qe="https://api.sentient-ui.com/v1/events",N=new Map,Ze=null;function Bn(e,n){let s=N.get(e);s&&s.upgrade&&(s.reinit=n)}function xt(e){return"value"in e||"currency"in e||"externalId"in e||"metadata"in e||"weight"in e||"stepIndex"in e}var Et=3;function Ke(){return ye()}function xe(){var e;if(typeof window!="undefined")return((e=window.location)==null?void 0:e.pathname)||void 0}function It(){let e=new WeakMap,n=new Map,s=!1,d=(i,u,r)=>{let t=i.get(u);return r===null?t?!0:(i.set(u,new Set),!1):t?t.has(r)?!0:(t.add(r),!1):(i.set(u,new Set([r])),!1)},f=typeof window!="undefined"&&"event"in window,a=()=>{if(!f)return;let i=window.event;return typeof Event=="function"&&i instanceof Event?i:void 0},l=()=>{if(f){Promise.resolve().then(()=>{s=!1,n.clear()});return}let i=!1,u=()=>{i||(i=!0,s=!1,n.clear())};if(setTimeout(u,0),typeof MessageChannel=="function"){let r=new MessageChannel;r.port1.onmessage=()=>{r.port1.close(),r.port2.close(),u()},r.port2.postMessage(0)}};return{firedBefore(i,u){let r=a();if(r){let o=e.get(r);return o||(o=new Map,e.set(r,o)),d(o,i,u)}let t=d(n,i,u);return!t&&!s&&(s=!0,l()),t}}}var et=new Set;function _t(e,n,s){let d=typeof window=="undefined"?null:window.history;if(!d)return()=>{};let f=!1,a,l=()=>{if(f)return;let r=xe();!r||r===a||(a=r,e.track({projectId:n,componentId:"__page__",eventType:"pageview",payload:{}}),s(`${n}:${r}`))},i=[];for(let r of["pushState","replaceState"]){let t=d[r],o=function(...y){let h=t.apply(this,y);return l(),h};d[r]=o,i.push([r,t,o])}window.addEventListener("popstate",l);let u=xe();return u&&et.has(`${n}:${u}`)?a=u:l(),()=>{if(!f){f=!0,window.removeEventListener("popstate",l);for(let[r,t,o]of i)d[r]===o&&(d[r]=t)}}}var pe={track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},getAssignment:()=>null,assign:()=>Promise.resolve(null),decide:()=>Promise.resolve(null),getSlotResult:()=>null,getPersona:()=>null,fetchWeights:()=>Promise.resolve([]),getGraph:()=>({pageNodes:[],capturedAt:0}),dispose:()=>{},destroy:()=>{}};function Ct(){try{let e={},n=new URLSearchParams(window.location.search);for(let[s,d]of n)s.startsWith("utm_")&&(e[s]=d);return e}catch(e){return{}}}function tt(e){return e.replace(/\/events\/?$/,"")}function nt(){return typeof navigator!="undefined"&&navigator.globalPrivacyControl===!0?!0:[typeof navigator!="undefined"?navigator.doNotTrack:void 0,typeof window!="undefined"?window.doNotTrack:void 0,typeof navigator!="undefined"?navigator.msDoNotTrack:void 0].some(n=>n==="1"||n==="yes")}function Ln(e){var u;if(typeof window=="undefined")return;let n=e!=null?e:Ze;if(!n){console.warn("[sentient] grantConsent() called before init()");return}let s=N.get(n);if(!s){console.warn("[sentient] grantConsent() called before init()");return}let{config:d,upgrade:f,reinit:a}=s;if(!f){s.upgradeBlockedReason&&console.warn(s.upgradeBlockedReason);return}if(d.respectDoNotTrack!==!1&&nt())return;let l=(a!=null?a:Tt)(se(_({},d),{consent:!0}));f(l);let i=(u=N.get(n))==null?void 0:u.dispose;N.set(n,{config:se(_({},d),{consent:!0}),upgrade:null,dispose:i})}function At(e){var r;let n=e.preConsentBehavior==="statistical_winner",s=tt((r=e.ingestUrl)!=null?r:qe),d={"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`},f=new Map,a=new Map,l={track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},getAssignment:()=>null,fetchWeights:()=>Promise.resolve([]),assign(t,o,y){if(!n)return Promise.resolve(null);let h=f.get(t);return h?Promise.resolve(h):Ne(a,t,async()=>{try{let x=new URLSearchParams({componentId:t});for(let G of o!=null?o:[])x.append("variantIds[]",G);let O=await fetch(`${s}/winner?${x.toString()}`,{headers:d});if(!O.ok)return o!=null&&o[0]?{variantId:o[0],assignmentTtlMs:0}:null;let E={variantId:(await O.json()).variantId,assignmentTtlMs:0};return f.set(t,E),E}catch(x){return o!=null&&o[0]?{variantId:o[0],assignmentTtlMs:0}:null}})},decide:()=>Promise.resolve(null),getSlotResult:()=>null,getPersona:()=>null,getGraph:()=>({pageNodes:[],capturedAt:0}),dispose:()=>{},destroy:()=>{}},i={track:t=>l.track(t),goal:((t,o,y,h)=>l.goal(t,o,y,h)),componentGoal:(t,o,y)=>l.componentGoal(t,o,y),identify:t=>l.identify(t),getAssignment:(t,o)=>l.getAssignment(t,o),assign:(t,o,y,h)=>l.assign(t,o,y,h),decide:t=>l.decide(t),getSlotResult:t=>l.getSlotResult(t),getPersona:()=>l.getPersona(),fetchWeights:()=>l.fetchWeights(),getGraph:()=>l.getGraph(),dispose:()=>l.dispose(),destroy:()=>l.destroy()};function u(t){l=t}return{proxy:i,setInner:u}}function Ne(e,n,s){let d=e.get(n);if(d)return d;let f=(async()=>{try{return await s()}finally{e.delete(n)}})();return e.set(n,f),f}function Tt(e){var k,j,Z,$,ae,Q,ne,z,Ge;if(typeof window=="undefined")return pe;Ze=e.apiKey||"local";let n=N.get(e.apiKey||"local");if(n!=null&&n.dispose)try{n.dispose()}catch(c){}let s=e.respectDoNotTrack!==!1&&nt(),d=e.consent===!1||s,f=typeof e.apiKey=="string"&&e.apiKey.startsWith("pk_");if(e.localMode===!0||!f&&e.localMode!==!1)return N.set(e.apiKey||"local",{config:e,upgrade:null,upgradeBlockedReason:"[sentient] grantConsent(): this client is keyless/local \u2014 there is no hosted client to upgrade to. Configure a pk_ API key to enable tracking."}),d?pe:Xe(e);if(d){if(!e.apiKey||!e.apiKey.startsWith("pk_"))return e.preConsentBehavior==="statistical_winner"&&console.warn("[sentient] init() called with an invalid apiKey \u2014 expected a pk_ public key. SDK disabled."),N.set(e.apiKey||"local",{config:e,upgrade:null,upgradeBlockedReason:"[sentient] grantConsent(): the client was initialized with an invalid apiKey (expected a pk_ public key) \u2014 consent cannot enable tracking."}),pe;let{proxy:c,setInner:p}=At(e);return N.set(e.apiKey,{config:e,upgrade:s?null:p}),c}if(!e.apiKey||!e.apiKey.startsWith("pk_"))return console.warn("[sentient] init() called with an invalid apiKey \u2014 expected a pk_ public key. SDK disabled."),pe;if(e.ingestUrl==="")return console.warn("[sentient] init() called with an empty ingestUrl. SDK disabled."),pe;let a=(k=e.ingestUrl)!=null?k:qe,l=Date.now(),i=Se({ssrSessionId:e.ssrSessionId,apiKey:e.apiKey}),u=ze(void 0,e.apiKey),r=He({ingestUrl:a,apiKey:e.apiKey}),t=tt(a),o={"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`},y=new Set,h=Qe({url:`${t}/goals`,apiKey:e.apiKey,headers:o,onDrop:(c,p)=>{if(!e.debug){if(y.has(p))return;y.add(p)}console.warn(`[sentient] goal dropped (HTTP ${p}) \u2014 this will not be retried. `+(p===400?"The session was not found: call init() and let the session upsert complete before firing goals.":p===401||p===403?"Check the API key and that this origin is on the project allowlist.":"See the response status for the cause."),c)}}),x=_e((j=navigator.userAgent)!=null?j:""),O=window.location.origin,R=Ce((Z=document.referrer)!=null?Z:"",O),E=($=e.sessionSegment)!=null?$:`${x}:${R}`,G=new Map,F=new Map,C=new Map,v=null,L=c=>{for(let p of c)C.has(p.id)||C.set(p.id,me(p))};if(e.initialSlots)for(let[c,p]of Object.entries(e.initialSlots))C.set(c,p);let m=de(e.apiKey);if(m)for(let[c,p]of Object.entries(m.slots))C.has(c)||C.set(c,p);let T={low:.15,medium:.5,high:.85};if(e.initialPersona)v=_({},e.initialPersona);else{let c=document.documentElement.dataset;c.sentientPersona?v={persona:c.sentientPersona,confidence:(Q=T[(ae=c.sentientConfidence)!=null?ae:"low"])!=null?Q:.15}:m&&(v={persona:m.persona,confidence:(ne=T[m.band])!=null?ne:.15})}if(e.initialAssignments)for(let[c,p]of Object.entries(e.initialAssignments))u.set(c,E,{variantId:p,assignedAt:Date.now(),segment:E,confidence:1});let P=Promise.resolve(),W=i.getSessionId();if(W){let c=Ae((z=document.referrer)!=null?z:""),p=_(_(_({sessionId:W,deviceClass:x,trafficSource:R,referrerDomain:c,utmParams:Ct(),timeOfDay:Te(new Date),dayOfWeek:["sun","mon","tue","wed","thu","fri","sat"][new Date().getDay()],ephemeral:i.isEphemeral(),automation:typeof navigator!="undefined"&&navigator.webdriver===!0||Ie((Ge=navigator.userAgent)!=null?Ge:"")},e.userId?{userId:e.userId}:{}),e.persona?{persona:e.persona}:{}),e.country?{country:e.country}:{}),S=async()=>{for(let I=0;;I++){try{let A=await fetch(`${t}/sessions`,{method:"POST",keepalive:!0,body:JSON.stringify(p),headers:o});if(A.status===402){console.warn("[SentientUI] Session limit exceeded for this project. The bandit will stop learning until the limit resets. Upgrade at sentient-ui.com/pricing");return}if(A.ok||re(A)==="dropped")return}catch(A){}if(I>=Et){console.warn("[SentientUI] Could not register the session after retries. Conversions in this visit may not be recorded.");return}await new Promise(A=>setTimeout(A,X(I+1)))}};try{P=S()}catch(I){}}e.debug&&(console.log("[sentient] initialized",{context:e.context}),window.__sentient={client:null,queue:r});let q=It(),M=null,te=!1,g={goal(c,p={},S=1,I=0){var le,ce,oe,b,H,ge,B;let A=i.getSessionId();if(!A)return;let w=xt(p)?p:{metadata:p},K=[c,(le=w.externalId)!=null?le:"",(ce=w.stepIndex)!=null?ce:I,(oe=w.weight)!=null?oe:S].join("\0"),U=w.value!==void 0?`${w.value}\0${(b=w.currency)!=null?b:""}`:null;if(q.firedBefore(K,U)){e.debug&&console.log(`[sentient] goal("${c}") already recorded for this action \u2014 not sent twice`);return}let D=Ke(),J={sessionId:A,name:c,metadata:(H=w.metadata)!=null?H:{},weight:(ge=w.weight)!=null?ge:S,stepIndex:(B=w.stepIndex)!=null?B:I,goalId:D,value:w.value,currency:w.currency,externalId:w.externalId};e.debug&&console.log("[sentient] goal",J);let ee={id:D,body:JSON.stringify(J)};P.then(()=>h.send(ee))},componentGoal(c,p,S){var D,J,ee;let I=i.getSessionId();if(!I)return;let A=u.get(c,E),w=A?null:(D=C.get(c))!=null?D:null;if(!A&&w===null){e.debug&&console.warn(`[sentient] componentGoal("${c}"): no assignment or slot decision yet \u2014 render its <Adaptive>/adaptive hook or call assign()/decide() before recording a goal.`);return}let K=A?A.variantId:Re(w),U={id:Ke(),sessionId:I,projectId:e.apiKey,componentId:c,variantId:K,eventType:"goal_achieved",goalType:p,payload:_({reward:(J=S==null?void 0:S.reward)!=null?J:1,goalValue:S==null?void 0:S.value,currency:S==null?void 0:S.currency},(ee=S==null?void 0:S.metadata)!=null?ee:{}),timestamp:Date.now(),timeInSession:Date.now()-l,path:xe()};e.debug&&console.log("[sentient] componentGoal",U),P.then(()=>r.push(U))},identify(c){let p=i.getSessionId();p&&P.then(()=>{fetch(`${t}/sessions`,{method:"POST",keepalive:!0,body:JSON.stringify({sessionId:p,userId:c,ephemeral:i.isEphemeral()}),headers:o}).catch(()=>{})})},track(c){let p=i.getSessionId();if(!p)return;let S=se(_({path:xe()},c),{id:Ke(),sessionId:p,timestamp:Date.now(),timeInSession:Date.now()-l});e.debug&&console.log("[sentient] track",S),P.then(()=>r.push(S))},getAssignment(c,p){return u.get(c,p)},async assign(c,p,S,I){let A=i.getSessionId();if(!A)return null;let w=u.get(c,E);if(w&&(p!=null&&p.length||w.content!==void 0)){let K=w.ttlMs&&w.ttlMs>0?Math.max(0,w.assignedAt+w.ttlMs-Date.now()):0;return{variantId:w.variantId,assignmentTtlMs:K,content:w.content}}return Ne(G,c,async()=>{await P;try{let K={sessionId:A,componentId:c,variantIds:p};I!==void 0?K.agentDataByVariant=I:S!==void 0&&(K.agentData=S);let U=await fetch(`${t}/assign`,{method:"POST",body:JSON.stringify(K),headers:o});if(!U.ok)return null;let D=await U.json();return u.set(c,E,_({variantId:D.variantId,assignedAt:Date.now(),segment:E,confidence:1,content:D.content},D.assignmentTtlMs&&D.assignmentTtlMs>0?{ttlMs:D.assignmentTtlMs}:{})),D}catch(K){return null}})},async decide(c){var w,K;let p=i.getSessionId();if(!p)return null;let S=(w=c.slots)!=null?w:[],I={sessionId:p};c.sections&&c.sections.length>0&&(I.sections=c.sections.map(U=>({id:U}))),I.components=(K=c.components)!=null?K:[],S.length>0&&(I.slots=S.map(Oe)),c.slotsFrom==="registry"&&(I.slotsFrom="registry"),c.v&&(I.v=c.v),e.persona&&(I.persona=e.persona);let A=JSON.stringify(I);return Ne(F,A,async()=>{var U,D,J,ee,le,ce;await P;try{let oe=await fetch(`${t}/decide`,{method:"POST",body:A,headers:o});if(!oe.ok)return L(S),null;let b=await oe.json(),H={};for(let B of S){let V=(U=b.slots)==null?void 0:U[B.id];if(V!==void 0){H[B.id]=V,C.set(B.id,V);continue}let Ue=C.get(B.id);if(Ue!==void 0)H[B.id]=Ue;else{let Fe=me(B);H[B.id]=Fe,C.set(B.id,Fe)}}if(b.slots)for(let[B,V]of Object.entries(b.slots))B in H||(H[B]=V,C.set(B,V));let ge=v!=null&&v.persona!=="unknown";b.persona&&!(b.persona==="unknown"&&ge)?v={persona:b.persona,confidence:(D=b.confidence)!=null?D:0}:v||(v={persona:"unknown",confidence:0});for(let[B,V]of Object.entries((J=b.assignments)!=null?J:{}))u.set(B,E,{variantId:V,assignedAt:Date.now(),segment:E,confidence:1});return ue(e.apiKey,_(_({v:1,persona:v.persona,band:Ye(v.confidence),slots:Object.fromEntries(C),layoutOrder:(ee=b.layoutOrder)!=null?ee:null,savedAt:Date.now()},b.slotConfig?{slotConfig:b.slotConfig}:{}),b.palette?{palette:b.palette}:{})),_(_(_(_({layoutOrder:(le=b.layoutOrder)!=null?le:null,assignments:(ce=b.assignments)!=null?ce:{},slots:H,persona:v.persona,confidence:v.confidence},b.slotConfig?{slotConfig:b.slotConfig}:{}),b.goals?{goals:b.goals}:{}),b.sectionMap?{sectionMap:b.sectionMap}:{}),b.palette?{palette:b.palette}:{})}catch(oe){return L(S),null}})},getSlotResult(c){var p;return(p=C.get(c))!=null?p:null},getPersona(){return v?{persona:v.persona,confidence:v.confidence,band:Ye(v.confidence)}:null},async fetchWeights(){var c;try{let p=await fetch(`${t}/weights`,{headers:o});return p.ok?(c=(await p.json()).components)!=null?c:[]:[]}catch(p){return[]}},getGraph(){return{pageNodes:[],capturedAt:0}},dispose(){var c;M==null||M(),te=!0,r.destroy(),h.destroy(),((c=N.get(e.apiKey))==null?void 0:c.dispose)===g.dispose&&N.delete(e.apiKey),e.debug&&console.log("[sentient] disposed")},destroy(){var c;M==null||M(),te=!0,r.destroy(),h.destroy(),i.destroy(),u.clear(),((c=N.get(e.apiKey))==null?void 0:c.dispose)===g.dispose&&N.delete(e.apiKey);try{localStorage.removeItem(ie+e.apiKey),localStorage.removeItem(Le(e.apiKey)),localStorage.removeItem(De(e.apiKey))}catch(p){}e.debug&&console.log("[sentient] destroyed")}};if(N.set(e.apiKey,{config:e,upgrade:null,dispose:g.dispose}),M=_t(g,e.apiKey,c=>{P.then(()=>{te||et.add(c)})}),e.debug){let c=window;c.__sentient&&(c.__sentient.client=g)}return g}export{ie as a,de as b,ue as c,wt as d,Me as e,Ve as f,zt as g,Jt as h,Vt as i,Xt as j,Yt as k,qt as l,Zt as m,en as n,tn as o,nn as p,on as q,sn as r,rn as s,an as t,ln as u,cn as v,dn as w,bt as x,Bn as y,nt as z,Ln as A,Tt as B};
2
+ //# sourceMappingURL=chunk-2RH7I6AP.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/uuid.ts","../src/session.ts","../src/durable.ts","../src/queue.ts","../src/goal-queue.ts","../src/cache.ts","../src/snapshot.ts","../src/index.ts","../src/local-mode.ts","../src/blocks.ts","../src/micro-signals.ts"],"sourcesContent":["/** Shared RFC 4122 v4 UUID generator. */\n\n/**\n * Returns a random RFC 4122 v4 UUID.\n *\n * Resolution order, each falling through only on absence/throw:\n * 1. `crypto.randomUUID()` — requires a **secure context** (HTTPS/localhost),\n * so it is absent on plain `http://` (non-localhost) pages.\n * 2. `crypto.getRandomValues()` — a CSPRNG that, unlike `randomUUID`, *is*\n * available in insecure contexts, so ids stay cryptographically random\n * exactly where step 1 is unavailable.\n * 3. `Math.random()` — last resort only when no Web Crypto exists at all.\n * These ids are anonymous analytics session/event keys (not secrets or\n * authenticators), so a well-formed value the Postgres `uuid` column accepts\n * matters more than PRNG quality here — and the generator must never throw\n * (a missing/malformed id would break session creation and the host page).\n */\nexport function randomUuidV4(): string {\n try {\n if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {\n return crypto.randomUUID();\n }\n } catch {\n /* fall through to getRandomValues */\n }\n try {\n if (typeof crypto !== 'undefined' && typeof crypto.getRandomValues === 'function') {\n const buf = new Uint8Array(16);\n crypto.getRandomValues(buf);\n buf[6] = (buf[6]! & 0x0f) | 0x40; // version 4\n buf[8] = (buf[8]! & 0x3f) | 0x80; // variant 10\n let out = '';\n for (let i = 0; i < 16; i++) {\n out += buf[i]!.toString(16).padStart(2, '0');\n if (i === 3 || i === 5 || i === 7 || i === 9) out += '-';\n }\n return out;\n }\n } catch {\n /* fall through to the Math.random() builder */\n }\n return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {\n const r = (Math.random() * 16) | 0;\n return (c === 'x' ? r : (r & 0x3) | 0x8).toString(16);\n });\n}\n","/** Manages anonymous session identity with cookie + localStorage layers. */\n\nimport { randomUuidV4 } from './uuid.js';\nimport { sessionCookieName, storageSuffix } from './storage-key.js';\n\nexport type SessionConfig = {\n cookieName?: string;\n cookieTTLDays?: number;\n /**\n * Public apiKey — namespaces the `_snt_uid` cookie + storage per project, so\n * two projects on the same exact origin don't share a visitor id (which would\n * cross-contaminate sessions server-side). Omit in local mode.\n */\n apiKey?: string;\n /**\n * Session ID generated during SSR (e.g. from `loadAdaptiveAssignments`).\n * Used as the fallback when no existing cookie or localStorage entry is found,\n * so the client adopts the same session the server used for variant assignment\n * on first visit rather than generating a new, orphaned ID.\n */\n ssrSessionId?: string;\n};\n\nexport type SessionManager = {\n getSessionId(): string | null;\n /** True when neither cookie nor localStorage could be written — id is in-memory only. */\n isEphemeral(): boolean;\n destroy(): void;\n};\n\nconst DEFAULT_COOKIE_NAME = '_snt_uid';\nconst DEFAULT_COOKIE_TTL_DAYS = 365;\nconst STORAGE_KEY = '_snt_uid';\n\n/**\n * Generates a unique session identifier. Always an RFC 4122 v4 UUID — the id is\n * stored server-side in a Postgres `uuid` column, so the insecure-context\n * fallback must not emit a malformed value (see `randomUuidV4`).\n */\nfunction generateSessionId(): string {\n return randomUuidV4();\n}\n\nfunction readCookie(name: string): string | null {\n try {\n const match = document.cookie.match(new RegExp(`(?:^|; )${name}=([^;]*)`));\n return match ? decodeURIComponent(match[1]) : null;\n } catch {\n return null;\n }\n}\n\nfunction writeCookie(name: string, value: string, maxAgeSeconds: number): void {\n try {\n document.cookie = `${name}=${encodeURIComponent(value)}; max-age=${maxAgeSeconds}; SameSite=strict; path=/`;\n } catch {\n /* ignore */\n }\n}\n\nfunction readLocalStorage(key: string): string | null {\n try {\n return localStorage.getItem(key);\n } catch {\n return null;\n }\n}\n\nfunction writeLocalStorage(key: string, value: string): boolean {\n try {\n localStorage.setItem(key, value);\n return true;\n } catch {\n return false;\n }\n}\n\nfunction readSessionStorage(key: string): string | null {\n try {\n return sessionStorage.getItem(key);\n } catch {\n return null;\n }\n}\n\nfunction writeSessionStorage(key: string, value: string): boolean {\n try {\n sessionStorage.setItem(key, value);\n return true;\n } catch {\n return false;\n }\n}\n\nfunction removeSessionStorage(key: string): void {\n try {\n sessionStorage.removeItem(key);\n } catch {\n /* ignore */\n }\n}\n\nfunction probeCookieWritable(name: string): boolean {\n try {\n document.cookie = `${name}_probe=1; max-age=1; SameSite=strict; path=/`;\n return document.cookie.indexOf(`${name}_probe=1`) !== -1;\n } catch {\n return false;\n }\n}\n\nfunction removeLocalStorage(key: string): void {\n try {\n localStorage.removeItem(key);\n } catch {\n /* ignore */\n }\n}\n\nfunction clearCookie(name: string): void {\n try {\n document.cookie = `${name}=; max-age=0; SameSite=strict; path=/`;\n } catch {\n /* ignore */\n }\n}\n\nconst SSR_MANAGER: SessionManager = {\n getSessionId: () => null,\n isEphemeral: () => false,\n destroy: () => undefined,\n};\n\n/**\n * Initializes session management. Returns a no-op manager in SSR environments.\n */\nexport function initSession(config?: SessionConfig): SessionManager {\n if (typeof window === 'undefined') {\n return SSR_MANAGER;\n }\n\n // Namespace the visitor-id keys per project so multiple keys on one origin\n // don't share a `_snt_uid` (see storage-key.ts). An explicit cookieName still\n // wins for callers that manage their own naming. sessionCookieName is the\n // shared writer/reader name — the SSR reader and graph sync derive the same\n // string from it, so they can't drift back to the bare name.\n const suffix = storageSuffix(config?.apiKey);\n const cookieName = config?.cookieName ?? sessionCookieName(config?.apiKey);\n const storageKey = `${STORAGE_KEY}${suffix}`;\n // Forget-me tombstone for the legacy fallback below. destroy() deletes only\n // this project's SUFFIXED keys — deleting the bare pre-namespacing ones\n // would reset every other project on a shared origin — so without a marker\n // the next init()'s readLegacy() re-adopted the exact identity the visitor\n // had just asked to forget. The marker carries the same per-project suffix,\n // so other projects keep adopting the bare id exactly as before.\n const legacyTombstoneKey = `${STORAGE_KEY}_tomb${suffix}`;\n const cookieTTLDays = config?.cookieTTLDays ?? DEFAULT_COOKIE_TTL_DAYS;\n const maxAgeSeconds = cookieTTLDays * 24 * 60 * 60;\n\n // Treat an empty string from any layer as absent. A `_snt_uid=` cookie with no\n // value (or an empty localStorage/sessionStorage entry) decodes to '', which is\n // not nullish — a plain `??` chain would keep it and persist it for a year,\n // leaving getSessionId() falsy so every track/goal/upsert bails out and the\n // visitor is permanently muted with no way to regenerate. Coercing '' to null\n // lets the chain fall through to a real id (or a freshly generated one).\n const nonEmpty = (value: string | null | undefined): string | null =>\n value && value.length > 0 ? value : null;\n\n // Legacy fallback: visitors identified BEFORE per-project namespacing carry\n // their id under the bare `_snt_uid` names. Without this read, the rollout of\n // the suffixed names reset every existing visitor's identity — a fresh session\n // row per visitor, broken sticky assignments, persona continuity lost. The id\n // is adopted (re-written under the suffixed names below) but the legacy keys\n // are left in place: deleting them would reset the OTHER projects on a shared\n // origin that haven't migrated it yet. Skipped when the caller manages its own\n // cookieName — the bare `_snt_uid` was never theirs — and when there is no\n // suffix (local mode still uses the bare names directly).\n // The tombstone (written by destroy()) blocks this fallback for THIS project\n // only — a forgotten visitor must come back a stranger, not resurrected from\n // the bare keys that other projects still legitimately share.\n const readLegacy = (): string | null =>\n suffix && !config?.cookieName && readLocalStorage(legacyTombstoneKey) === null\n ? nonEmpty(readCookie(DEFAULT_COOKIE_NAME)) ??\n nonEmpty(readLocalStorage(STORAGE_KEY)) ??\n nonEmpty(readSessionStorage(STORAGE_KEY))\n : null;\n\n let sessionId: string | null =\n nonEmpty(readCookie(cookieName)) ??\n nonEmpty(readLocalStorage(storageKey)) ??\n nonEmpty(readSessionStorage(storageKey)) ??\n readLegacy() ??\n nonEmpty(config?.ssrSessionId) ??\n generateSessionId();\n\n writeCookie(cookieName, sessionId, maxAgeSeconds);\n const lsOk = writeLocalStorage(storageKey, sessionId);\n const cookieOk = probeCookieWritable(cookieName);\n // Always write sessionStorage when localStorage fails — it covers same-tab\n // navigation even in strict storage environments.\n const ssOk = !lsOk ? writeSessionStorage(storageKey, sessionId) : false;\n const ephemeral = !lsOk && !cookieOk && !ssOk;\n\n return {\n getSessionId: () => sessionId,\n isEphemeral: () => ephemeral,\n destroy: () => {\n sessionId = null;\n clearCookie(cookieName);\n removeLocalStorage(storageKey);\n removeSessionStorage(storageKey);\n // See legacyTombstoneKey: the bare `_snt_uid` keys stay for the other\n // projects on this origin, but this project's next init() must not\n // re-adopt them — that quietly undid the forget-me it just performed.\n if (suffix && !config?.cookieName) writeLocalStorage(legacyTombstoneKey, '1');\n },\n };\n}\n","/**\n * Reliability primitives shared by every outbound SDK transport.\n *\n * Extracted from queue.ts so the goal sender cannot drift from the event\n * queue on the three decisions that decide whether data survives: which\n * responses are worth retrying, how long to wait, and how the cross-reload\n * bucket is read and written. Behaviour is byte-identical to the versions\n * these replace.\n */\n\nconst MAX_BACKOFF_MS = 60_000;\n/** 2^6 s = 64 s, already past MAX_BACKOFF_MS — the cap that stops the shift overflowing. */\nconst BACKOFF_EXPONENT_CAP = 6;\n\n/** Delay before the next attempt after `consecutiveFailures` failed ones (1-based). */\nexport function backoffDelayMs(consecutiveFailures: number): number {\n return Math.min(MAX_BACKOFF_MS, 1000 * 2 ** Math.min(consecutiveFailures, BACKOFF_EXPONENT_CAP));\n}\n\n/** What one delivery attempt achieved. `dropped` is terminal but unsuccessful. */\nexport type DeliveryOutcome = 'delivered' | 'dropped' | 'retry';\n\n/**\n * Classifies a response into the three outcomes that matter to a transport.\n *\n * 2xx delivered. A 4xx other than 429 will never succeed however many times we\n * try it (bad key, rejected body, unknown session), so retrying it loops\n * forever and starves real data out of the bucket — drop it, but distinctly,\n * so callers can tell the developer. 429 and 5xx are transient.\n *\n * `ok` is consulted before `status` deliberately: it is the semantic check, and\n * it keeps stubs that set only `ok` (used throughout the SDK test suite)\n * behaving as they did before this was extracted. An unrecognizable response\n * with neither is treated as retryable, matching the original queue.\n */\nexport function classifyResponse(res: { ok?: boolean; status?: number }): DeliveryOutcome {\n if (res.ok === true) return 'delivered';\n const { status } = res;\n if (typeof status !== 'number') return 'retry';\n if (status >= 200 && status < 300) return 'delivered';\n if (status >= 400 && status < 500 && status !== 429) return 'dropped';\n return 'retry';\n}\n\n/** Anything a persisted bucket can hold: it needs a stable server-side dedupe id. */\nexport type Identified = { id: string };\n\n/**\n * Reads a persisted bucket AND clears it — the caller takes ownership of the\n * items and is responsible for re-persisting any that fail again. Returns the\n * newest `max` entries; a corrupt or absent bucket reads as empty.\n */\nexport function drainBucket<T extends Identified>(storageKey: string, max: number): T[] {\n try {\n const raw = localStorage.getItem(storageKey);\n if (!raw) return [];\n const parsed = JSON.parse(raw) as T[];\n if (!Array.isArray(parsed)) return [];\n localStorage.removeItem(storageKey);\n return parsed.slice(-max);\n } catch {\n return [];\n }\n}\n\n/**\n * Merges `items` into the persisted bucket, de-duped by id (last write wins)\n * before the size cap. The dedupe matters: a batch that 5xx's repeatedly\n * in-session hands the same ids back on every retry, and without it each retry\n * appends another copy and `slice(-max)` evicts other distinct failed items to\n * make room for the duplicates.\n */\nexport function writeBucket<T extends Identified>(items: T[], max: number, storageKey: string): void {\n try {\n const existing = (() => {\n try {\n const raw = localStorage.getItem(storageKey);\n if (!raw) return [] as T[];\n const parsed = JSON.parse(raw) as T[];\n return Array.isArray(parsed) ? parsed : ([] as T[]);\n } catch {\n return [] as T[];\n }\n })();\n const byId = new Map<string, T>();\n for (const e of existing) byId.set(e.id, e);\n for (const e of items) byId.set(e.id, e);\n localStorage.setItem(storageKey, JSON.stringify([...byId.values()].slice(-max)));\n } catch {\n /* storage unavailable — the in-memory retry path still applies */\n }\n}\n\n/**\n * Removes the given ids from the persisted bucket. Called once an item is\n * acknowledged so a transient failure that was written to localStorage isn't\n * replayed on the next page load after the in-session retry succeeded.\n */\nexport function purgeBucket(ids: string[], storageKey: string): void {\n try {\n const raw = localStorage.getItem(storageKey);\n if (!raw) return;\n const parsed = JSON.parse(raw) as Identified[];\n if (!Array.isArray(parsed)) return;\n const drop = new Set(ids);\n const remaining = parsed.filter((e) => !drop.has(e.id));\n if (remaining.length === parsed.length) return; // nothing to remove\n if (remaining.length === 0) localStorage.removeItem(storageKey);\n else localStorage.setItem(storageKey, JSON.stringify(remaining));\n } catch {\n /* ignore */\n }\n}\n","/** Batched event queue with reliable transport (fetch + keepalive, localStorage retry). */\n\nimport { backoffDelayMs, classifyResponse, drainBucket, purgeBucket, writeBucket } from './durable.js';\n\nexport type EventType =\n | 'variant_assigned'\n | 'goal_achieved'\n | 'scroll_depth'\n | 'dwell'\n | 'cursor_signal'\n | 'component_visible'\n | 'component_exited'\n | 'micro_signal'\n // A funnel DECLARATION, not telemetry: the server upserts the funnel entity\n // and never stores it in raw_events. Listed here so callers can express it\n // without casting through the track() signature.\n | 'funnel_declared'\n // One per page load and per SPA route change, so a visit's journey through the\n // site is reconstructable. Carries `path` and nothing else.\n | 'pageview';\n\nexport type SentientEvent = {\n id: string;\n sessionId: string;\n projectId: string;\n componentId: string;\n variantId?: string;\n eventType: EventType;\n goalType?: string;\n /**\n * Page path the event happened on, e.g. `/pricing`. Set automatically from\n * `location.pathname` — deliberately NOT `location.href`, so query strings\n * (which routinely carry emails, reset tokens and order ids) never leave the\n * browser. The server re-strips them anyway; this is the first of two gates.\n * Undefined outside a browser (SSR), where there is no page to name.\n */\n path?: string;\n payload: Record<string, unknown>;\n timestamp: number;\n timeInSession: number;\n};\n\nexport type QueueConfig = {\n ingestUrl: string;\n apiKey: string;\n flushIntervalMs?: number;\n maxBatchSize?: number;\n maxRetrySize?: number;\n};\n\nexport type EventQueue = {\n push(event: SentientEvent): void;\n flush(): void;\n destroy(): void;\n};\n\nconst MAX_SENT_IDS = 500;\n// 64 KB is the per-origin keepalive budget on every modern browser. We split unload\n// flushes into chunks below this to avoid the whole batch being dropped.\nconst KEEPALIVE_BUDGET_BYTES = 56 * 1024;\n\n/**\n * Persisted retry-bucket key, namespaced by apiKey prefix so multiple projects\n * on the same origin each get their own bucket. Exported so the client's\n * forget-me teardown can remove it.\n */\nexport function retryStorageKey(apiKey: string): string {\n return `_snt_retry_${apiKey.slice(0, 12)}`;\n}\n\nconst SSR_QUEUE: EventQueue = {\n push: () => undefined,\n flush: () => undefined,\n destroy: () => undefined,\n};\n\n/**\n * Creates a batched event queue with periodic and lifecycle-triggered flushes.\n */\nexport function createEventQueue(config: QueueConfig): EventQueue {\n if (typeof window === 'undefined') {\n return SSR_QUEUE;\n }\n\n const flushIntervalMs = config.flushIntervalMs ?? 5000;\n const maxBatchSize = config.maxBatchSize ?? 20;\n const maxRetrySize = config.maxRetrySize ?? 100;\n const ingestUrl = config.ingestUrl;\n const apiKey = config.apiKey;\n const RETRY_KEY = retryStorageKey(apiKey);\n\n const queue: SentientEvent[] = [];\n const sentIds = new Set<string>();\n const sentIdOrder: string[] = [];\n\n const markSent = (ids: string[]): void => {\n for (const id of ids) {\n queuedIds.delete(id); // free the in-flight slot\n if (sentIds.has(id)) continue;\n sentIds.add(id);\n sentIdOrder.push(id);\n }\n while (sentIdOrder.length > MAX_SENT_IDS) {\n const oldest = sentIdOrder.shift();\n if (oldest) sentIds.delete(oldest);\n }\n // A batch that previously 5xx'd was persisted to the cross-reload retry\n // backstop. Now that it's acknowledged (delivered, or 4xx-dropped as\n // unretryable), drop those ids from localStorage too — otherwise the next\n // page load would replay an already-handled event. `sentIds` is in-memory\n // only, so it can't suppress that cross-reload duplicate on its own.\n purgeBucket(ids, RETRY_KEY);\n };\n\n // Tracks IDs currently in `queue` or in flight (handed to transportBatch\n // but not yet confirmed). Entries are removed on markSent or when an event\n // is dropped, so the set stays bounded by in-flight + queued size.\n const queuedIds = new Set<string>();\n\n // Bound the in-memory queue at the same cap as the persisted retry bucket\n // (maxRetrySize). During a sustained outage flush() keeps re-enqueueing every\n // failed batch while the page keeps producing events, and only the\n // localStorage bucket was capped — so a multi-hour outage on a long-lived\n // SPA tab grew this array without limit. Drop-oldest, matching writeBucket's\n // slice(-max) shed policy: the newest events are the ones a recovering\n // server can still use.\n const capQueue = (): void => {\n while (queue.length > maxRetrySize) {\n const dropped = queue.shift();\n if (dropped) queuedIds.delete(dropped.id);\n }\n };\n\n const enqueue = (event: SentientEvent): void => {\n if (sentIds.has(event.id) || queuedIds.has(event.id)) return;\n queuedIds.add(event.id);\n queue.push(event);\n capQueue();\n };\n\n // A retryable failure hands the batch back to the in-memory queue so the\n // backoff-gated interval flush retries it in-session (localStorage is only the\n // cross-reload backstop). The ids are still tracked in queuedIds — they were\n // pulled from `queue` on flush but never markSent — so we re-add them WITHOUT\n // going through enqueue (which would skip them as already-queued) and without\n // deleting/re-adding queuedIds. Already-sent events are never re-queued, and a\n // single event stays a single copy: `queue` is fully drained each flush.\n const requeueFailed = (batch: SentientEvent[]): void => {\n for (const event of batch) {\n if (sentIds.has(event.id)) continue;\n queuedIds.add(event.id); // idempotent — keeps id-tracking consistent\n queue.push(event);\n }\n // Failed batches count against the same bound as fresh pushes — this path\n // is exactly the one that grew unbounded during an outage (see capQueue).\n capQueue();\n };\n\n const retryEvents = drainBucket<SentientEvent>(RETRY_KEY, maxRetrySize);\n for (const event of retryEvents) {\n enqueue(event);\n }\n\n // Pause flushing until backoff expires.\n let backoffUntil = 0;\n let consecutiveFailures = 0;\n\n // Authenticated transport. keepalive: true gives unload-survival; we still await\n // the response so 5xx/429 actually surface and we can retry.\n const transportBatch = (batch: SentientEvent[], salvage = true): void => {\n if (batch.length === 0) return;\n const body = JSON.stringify(batch);\n const ids = batch.map((e) => e.id);\n\n let pending: Promise<Response> | Response;\n try {\n pending = fetch(ingestUrl, {\n method: 'POST',\n keepalive: true,\n body,\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${apiKey}`,\n },\n });\n } catch {\n // Synchronous throw (typically jsdom in tests, or extreme browser failure).\n writeBucket(batch, maxRetrySize, RETRY_KEY);\n requeueFailed(batch);\n consecutiveFailures++;\n backoffUntil = Date.now() + backoffDelayMs(consecutiveFailures);\n return;\n }\n\n // fetch can sometimes return a value directly (tests using stubGlobal). Handle both.\n const handleResponse = (res: Response): void => {\n if (classifyResponse(res) !== 'retry') {\n // An API older than migration 108 400s the whole batch over the unknown\n // 'pageview' type, and a 4xx is terminal — which silently dropped the\n // co-batched exposures and goals too. Re-send once without the\n // pageviews (valid on the old API); the pageviews themselves are\n // unsendable there and are dropped as delivered.\n if (!res.ok && salvage) {\n const rest = batch.filter((e) => e.eventType !== 'pageview');\n if (rest.length > 0 && rest.length < batch.length) {\n markSent(batch.filter((e) => e.eventType === 'pageview').map((e) => e.id));\n transportBatch(rest, false);\n return;\n }\n }\n // 2xx = success. 4xx (except 429) will never succeed — drop them rather than loop.\n markSent(ids);\n consecutiveFailures = 0;\n backoffUntil = 0;\n return;\n }\n // 5xx / 429 → retry with backoff.\n writeBucket(batch, maxRetrySize, RETRY_KEY);\n requeueFailed(batch);\n consecutiveFailures++;\n backoffUntil = Date.now() + backoffDelayMs(consecutiveFailures);\n };\n\n if (pending instanceof Promise) {\n pending.then(handleResponse).catch(() => {\n writeBucket(batch, maxRetrySize, RETRY_KEY);\n requeueFailed(batch);\n consecutiveFailures++;\n backoffUntil = Date.now() + backoffDelayMs(consecutiveFailures);\n });\n } else {\n handleResponse(pending);\n }\n };\n\n // Pack events into a batch that stays under the keepalive byte budget AND the\n // configured event-count cap. Returns the prefix of `pool` that fits.\n // Uses UTF-8 byte length (not char count) — emoji/CJK payloads can be 3–4×\n // larger as bytes and would otherwise blow the keepalive budget.\n const encoder = typeof TextEncoder !== 'undefined' ? new TextEncoder() : null;\n const byteLength = (s: string): number =>\n encoder ? encoder.encode(s).length : s.length;\n const packBatch = (pool: SentientEvent[]): SentientEvent[] => {\n const out: SentientEvent[] = [];\n let bytes = 2; // for the surrounding []\n for (const e of pool) {\n const size = byteLength(JSON.stringify(e)) + 1; // +1 for comma\n if (out.length > 0 && bytes + size > KEEPALIVE_BUDGET_BYTES) break;\n if (out.length >= maxBatchSize) break;\n out.push(e);\n bytes += size;\n }\n return out;\n };\n\n const flush = (): void => {\n try {\n if (Date.now() < backoffUntil) return;\n while (queue.length > 0) {\n // Re-check inside the loop: transportBatch can set backoffUntil\n // synchronously (a sync throw or a same-tick Response) and re-enqueue the\n // failed batch, so a mid-drain backoff must stop further chunks this tick\n // (otherwise the just-re-enqueued batch would immediately retry-loop).\n if (Date.now() < backoffUntil) break;\n const pending = queue.filter((e) => !sentIds.has(e.id));\n queue.length = 0;\n if (pending.length === 0) break;\n const batch = packBatch(pending);\n if (batch.length === 0) break;\n // Put anything we didn't pack back on the queue for the next tick.\n if (batch.length < pending.length) {\n queue.push(...pending.slice(batch.length));\n }\n transportBatch(batch);\n }\n } catch {\n /* never throw */\n }\n };\n\n let flushTimerActive = true;\n let intervalId: ReturnType<typeof setInterval> | null = null;\n\n intervalId = setInterval(() => {\n if (!flushTimerActive) return;\n flush();\n }, flushIntervalMs);\n\n const onVisibilityChange = (): void => {\n if (document.visibilityState === 'hidden') {\n flush();\n }\n };\n\n // `pagehide` (not `beforeunload`): a `beforeunload` listener can disqualify a\n // page from the back/forward cache. `pagehide` fires on real unloads AND on\n // bfcache eviction, and `visibilitychange:hidden` already covers most leaves,\n // so flush-on-leave stays covered without inhibiting bfcache.\n const onPageHide = (): void => {\n flush();\n };\n\n document.addEventListener('visibilitychange', onVisibilityChange);\n window.addEventListener('pagehide', onPageHide);\n\n return {\n push(event: SentientEvent): void {\n enqueue(event);\n if (queue.length >= maxBatchSize) {\n flush();\n }\n },\n flush,\n destroy(): void {\n flushTimerActive = false;\n if (intervalId !== null) {\n clearInterval(intervalId);\n intervalId = null;\n }\n document.removeEventListener('visibilitychange', onVisibilityChange);\n window.removeEventListener('pagehide', onPageHide);\n flush();\n },\n };\n}\n","/**\n * Durable transport for `POST /v1/goals`.\n *\n * A conversion is the single most valuable event the SDK emits, and it used to\n * be the least reliable one: `goal()` fired a bare `fetch(...).catch(() => {})`,\n * which only observes network-layer failures. A 429 (the per-IP limit is 100\n * req/min, and shared egress — corporate NAT, carriers, storefront proxies —\n * hits it routinely), a 5xx, or a 400 all RESOLVE, so the catch never ran and\n * the response was discarded unread. The conversion was gone with no retry and\n * nothing surfaced to the developer.\n *\n * This gives goals the same guarantees the event queue has always had: retry\n * with backoff in-session, a localStorage bucket that survives reload, and\n * dedupe by id. Retry is safe because `goalId` is a client-generated UUID that\n * the server dedupes on (`ON CONFLICT DO NOTHING`) — the safety was already\n * there, it just wasn't used.\n *\n * Unlike events, `/v1/goals` takes ONE goal per request, so this is a serial\n * sender rather than a batcher, and a flush sends at most `maxPerFlush` so a\n * backlog drains at a pace the rate limiter tolerates instead of re-triggering\n * the 429 that created it.\n */\n\nimport { backoffDelayMs, classifyResponse, drainBucket, purgeBucket, writeBucket } from './durable.js';\n\n/** One queued conversion. `id` is the goalId — the server's dedupe key. */\nexport type PendingGoal = {\n id: string;\n /** Pre-serialized request body, so a persisted goal replays byte-identically. */\n body: string;\n};\n\nexport type GoalQueueConfig = {\n /** Absolute URL of the goals endpoint. */\n url: string;\n apiKey: string;\n headers: Record<string, string>;\n flushIntervalMs?: number;\n maxRetrySize?: number;\n maxPerFlush?: number;\n /** Called when a goal is permanently dropped (non-retryable status), so the\n * client can warn in debug mode. Never called for retryable failures. */\n onDrop?: (goal: PendingGoal, status: number) => void;\n};\n\nexport type GoalQueue = {\n /** Sends immediately; on a retryable failure the goal is queued and retried. */\n send(goal: PendingGoal): void;\n flush(): void;\n destroy(): void;\n};\n\nconst MAX_SENT_IDS = 200;\n\n/**\n * Persisted goal-retry bucket key, namespaced by apiKey prefix so multiple\n * projects on one origin keep separate buckets. Exported so the client's\n * forget-me teardown can remove it.\n */\nexport function goalRetryStorageKey(apiKey: string): string {\n return `_snt_goal_retry_${apiKey.slice(0, 12)}`;\n}\n\nconst SSR_GOAL_QUEUE: GoalQueue = {\n send: () => undefined,\n flush: () => undefined,\n destroy: () => undefined,\n};\n\nexport function createGoalQueue(config: GoalQueueConfig): GoalQueue {\n if (typeof window === 'undefined') return SSR_GOAL_QUEUE;\n\n const flushIntervalMs = config.flushIntervalMs ?? 5000;\n const maxRetrySize = config.maxRetrySize ?? 100;\n const maxPerFlush = config.maxPerFlush ?? 5;\n const RETRY_KEY = goalRetryStorageKey(config.apiKey);\n\n const pending: PendingGoal[] = [];\n const pendingIds = new Set<string>();\n const sentIds = new Set<string>();\n const sentIdOrder: string[] = [];\n\n let backoffUntil = 0;\n let consecutiveFailures = 0;\n let disposed = false;\n\n const markSent = (goal: PendingGoal): void => {\n pendingIds.delete(goal.id);\n if (!sentIds.has(goal.id)) {\n sentIds.add(goal.id);\n sentIdOrder.push(goal.id);\n }\n while (sentIdOrder.length > MAX_SENT_IDS) {\n const oldest = sentIdOrder.shift();\n if (oldest) sentIds.delete(oldest);\n }\n // Acknowledged (delivered, or dropped as unretryable) — clear it from the\n // cross-reload bucket so the next page load doesn't replay it.\n purgeBucket([goal.id], RETRY_KEY);\n };\n\n const markFailed = (goal: PendingGoal): void => {\n writeBucket([goal], maxRetrySize, RETRY_KEY);\n if (!sentIds.has(goal.id) && !pendingIds.has(goal.id)) {\n pendingIds.add(goal.id);\n pending.push(goal);\n }\n // One failed ROUND counts once, however many goals were in flight. flush()\n // launches up to maxPerFlush transports synchronously, so counting per goal\n // turned a single bad tick into consecutiveFailures=5 and a 32s backoff\n // where the first failure warrants 2s. queue.ts counts per batch; match it.\n if (Date.now() >= backoffUntil) {\n consecutiveFailures++;\n backoffUntil = Date.now() + backoffDelayMs(consecutiveFailures);\n }\n };\n\n const transport = (goal: PendingGoal): void => {\n let res: Promise<Response> | Response;\n try {\n res = fetch(config.url, {\n method: 'POST',\n keepalive: true,\n body: goal.body,\n headers: config.headers,\n });\n } catch {\n // Synchronous throw (jsdom in tests, or extreme browser failure).\n markFailed(goal);\n return;\n }\n\n const handle = (r: Response): void => {\n const outcome = classifyResponse(r);\n if (outcome === 'retry') {\n markFailed(goal);\n return;\n }\n // Terminal either way, but a drop is a wiring bug the developer can fix —\n // a 400 \"session not found\", a 401 from a misconfigured origin allowlist —\n // and used to be swallowed entirely. Say so instead of failing silently.\n if (outcome === 'dropped') config.onDrop?.(goal, r.status);\n markSent(goal);\n consecutiveFailures = 0;\n backoffUntil = 0;\n };\n\n // fetch can return a plain value under test stubs. Handle both.\n if (res instanceof Promise) res.then(handle).catch(() => markFailed(goal));\n else handle(res);\n };\n\n const flush = (): void => {\n try {\n if (disposed) return;\n if (Date.now() < backoffUntil) return;\n let sentThisTick = 0;\n while (pending.length > 0 && sentThisTick < maxPerFlush) {\n if (Date.now() < backoffUntil) break; // a same-tick failure re-armed backoff\n const goal = pending.shift()!;\n pendingIds.delete(goal.id);\n if (sentIds.has(goal.id)) continue;\n sentThisTick++;\n transport(goal);\n }\n } catch {\n /* never throw from a lifecycle handler */\n }\n };\n\n // Replay anything a previous page load failed to deliver. Left for the first\n // interval tick rather than sent now, so a page that reloads under an ongoing\n // outage doesn't stampede the endpoint during init.\n const restored = drainBucket<PendingGoal>(RETRY_KEY, maxRetrySize);\n for (const goal of restored) {\n if (!pendingIds.has(goal.id)) {\n pendingIds.add(goal.id);\n pending.push(goal);\n }\n }\n // drainBucket CLEARS storage as it reads, but only maxPerFlush goals leave per\n // tick — so a 40-goal backlog moved to memory and the visitor navigating two\n // seconds later lost the 35 that hadn't been sent yet. Put them straight back;\n // markSent purges each id individually once it is actually acknowledged.\n if (restored.length > 0) writeBucket(restored, maxRetrySize, RETRY_KEY);\n\n const intervalId = setInterval(flush, flushIntervalMs);\n const onVisibilityChange = (): void => {\n if (document.visibilityState === 'hidden') flush();\n };\n const onPageHide = (): void => flush();\n document.addEventListener('visibilitychange', onVisibilityChange);\n window.addEventListener('pagehide', onPageHide);\n\n return {\n send(goal: PendingGoal): void {\n if (disposed) return;\n if (sentIds.has(goal.id) || pendingIds.has(goal.id)) return;\n // A conversion goes out now — it is often the last thing that happens\n // before a redirect to a thank-you page. Only a failure makes it queued.\n if (Date.now() < backoffUntil) {\n // Persist BEFORE parking it in memory. A goal only ever reached the\n // cross-reload bucket via markFailed — i.e. only after a failed attempt\n // — so a conversion queued during someone else's backoff lived in memory\n // alone, and flush() early-returns while backoff is armed, so pagehide\n // could not rescue it either. A purchase firing 300ms after a rate-limited\n // add_to_cart was lost on the checkout redirect: exactly the outage this\n // queue exists to survive.\n writeBucket([goal], maxRetrySize, RETRY_KEY);\n pendingIds.add(goal.id);\n pending.push(goal);\n return;\n }\n transport(goal);\n },\n flush,\n destroy(): void {\n clearInterval(intervalId);\n document.removeEventListener('visibilitychange', onVisibilityChange);\n window.removeEventListener('pagehide', onPageHide);\n flush();\n disposed = true;\n },\n };\n}\n","/** Synchronous variant assignment cache (memory + localStorage). */\n\nimport { storageSuffix } from './storage-key.js';\n\nexport type Assignment = {\n variantId: string;\n assignedAt: number;\n segment: string;\n confidence: number;\n content?: string;\n /**\n * Per-entry expiry (ms from `assignedAt`). When present it overrides the\n * cache-wide default TTL — lets the server-provided `assignmentTtlMs` govern\n * how long this specific assignment stays valid. Persists across reloads.\n */\n ttlMs?: number;\n};\n\nexport type AssignmentCache = {\n get(componentId: string, segment: string): Assignment | null;\n set(componentId: string, segment: string, assignment: Assignment): void;\n /** Drops every entry, memory and localStorage — the forget-me path. */\n clear(): void;\n};\n\nconst DEFAULT_TTL_MS = 30 * 60 * 1000;\n\nfunction cacheKey(componentId: string, segment: string): string {\n // URI-encode each part (same scheme as storageKey) and join with a literal\n // ':'. Since encodeURIComponent escapes ':', the separator is unambiguous —\n // otherwise a segment like `device:source` could collide two distinct\n // (componentId, segment) pairs onto the same raw `${id}:${segment}` string.\n return `${encodeURIComponent(componentId)}:${encodeURIComponent(segment)}`;\n}\n\n/**\n * Creates an assignment cache with optional TTL (default 30 minutes). Pass the\n * project's `apiKey` so the localStorage keys are namespaced per project —\n * otherwise two projects on the same origin share cached assignments.\n */\nexport function createAssignmentCache(ttlMs: number = DEFAULT_TTL_MS, apiKey?: string): AssignmentCache {\n const memory = new Map<string, Assignment>();\n\n // Per-project localStorage prefix. No apiKey (local mode) → the legacy\n // `_snt_asgn_` prefix so single-project behavior is unchanged.\n const keyPrefix = `_snt_asgn${storageSuffix(apiKey)}_`;\n\n const storageKey = (componentId: string, segment: string): string =>\n `${keyPrefix}${encodeURIComponent(componentId)}:${encodeURIComponent(segment)}`;\n\n const parseStorageKey = (key: string): { componentId: string; segment: string } | null => {\n const suffix = key.slice(keyPrefix.length);\n const sep = suffix.indexOf(':');\n if (sep < 0) return null;\n try {\n return {\n componentId: decodeURIComponent(suffix.slice(0, sep)),\n segment: decodeURIComponent(suffix.slice(sep + 1)),\n };\n } catch {\n return null;\n }\n };\n\n const listStorageKeys = (): string[] => {\n try {\n const keys: string[] = [];\n for (let i = 0; i < localStorage.length; i++) {\n const key = localStorage.key(i);\n if (key?.startsWith(keyPrefix)) {\n keys.push(key);\n }\n }\n return keys;\n } catch {\n return [];\n }\n };\n\n // Honor a per-entry TTL (server-provided assignmentTtlMs) when present; fall\n // back to the cache-wide default otherwise.\n const isExpired = (assignment: Assignment): boolean =>\n assignment.assignedAt + (assignment.ttlMs && assignment.ttlMs > 0 ? assignment.ttlMs : ttlMs) < Date.now();\n\n const restoreFromStorage = (): void => {\n for (const key of listStorageKeys()) {\n try {\n const raw = localStorage.getItem(key);\n if (!raw) continue;\n const assignment = JSON.parse(raw) as Assignment;\n if (isExpired(assignment)) {\n localStorage.removeItem(key);\n continue;\n }\n const parsed = parseStorageKey(key);\n if (!parsed) continue;\n memory.set(cacheKey(parsed.componentId, parsed.segment), assignment);\n } catch {\n /* ignore corrupt entries */\n }\n }\n };\n\n if (typeof window !== 'undefined') {\n restoreFromStorage();\n }\n\n return {\n get(componentId: string, segment: string): Assignment | null {\n const entry = memory.get(cacheKey(componentId, segment));\n if (!entry) return null;\n if (isExpired(entry)) {\n memory.delete(cacheKey(componentId, segment));\n return null;\n }\n return entry;\n },\n\n set(componentId: string, segment: string, assignment: Assignment): void {\n const key = cacheKey(componentId, segment);\n memory.set(key, assignment);\n try {\n localStorage.setItem(storageKey(componentId, segment), JSON.stringify(assignment));\n } catch {\n /* ignore */\n }\n },\n\n clear(): void {\n memory.clear();\n for (const storageK of listStorageKeys()) {\n try {\n localStorage.removeItem(storageK);\n } catch {\n /* ignore */\n }\n }\n },\n };\n}\n","/**\n * Decision snapshot: the SPA / return-visit pre-paint source. Written after\n * every successful decide; read by the inline pre-paint script (before any\n * framework code runs) and by init() to seed slot/persona state.\n */\nimport type { SlotResult } from './slots.js';\nimport type { BlockNode, SitePalette } from './blocks.js';\n\nexport const SNAPSHOT_STORAGE_KEY_PREFIX = '_snt_snap:';\n\n/** Versioned compound locator: resolve id → dataAttr → selector, then verify\n * against fingerprint. Lets a slot survive DOM/markup drift. */\nexport type CompoundLocator = {\n v?: number;\n id?: string;\n dataAttr?: { name: string; value: string };\n selector?: string;\n urlMatch?: string;\n fingerprint?: { tag?: string; text?: string };\n semanticId?: string;\n};\n\n/** Bounded, declarative operations a registry arm may apply to its element.\n * The style set is a fixed whitelist (validated server-side); no arbitrary CSS,\n * HTML, or JS ever. `text` is applied via textContent; https-only URLs.\n * moveBefore/moveAfter (exactly one) reposition the element relative to a\n * uniquely-resolving sibling anchor — post-decide only, never pre-paint. */\nexport type SlotOps = {\n text?: string;\n style?: Record<string, string>;\n hidden?: boolean;\n href?: string;\n imageSrc?: string;\n imageAlt?: string;\n moveBefore?: CompoundLocator;\n moveAfter?: CompoundLocator;\n};\n\n/** Registry-mode apply info per slot: where to apply and what to set. Stored so\n * a returning visitor's pre-paint can reapply it. `target` is the Phase-2 bare\n * selector; `locator` (Phase 3) is the compound locator, preferred when present. */\nexport type SlotConfigEntry = {\n kind: 'tokens' | 'arms';\n target?: string;\n locator?: CompoundLocator;\n content?: string;\n ops?: SlotOps;\n /** Composition Blocks per arm — ALL arms, not just the served one, because\n * Option-B rendering pre-paints every arm hidden and reveals the served one\n * (spec §6). Holdout sessions receive the baseline arm's tree only, so the\n * control group's DOM stays meaningful. Absent for non-composition slots. */\n blocks?: Record<string, BlockNode>;\n};\n\nexport type DecisionSnapshot = {\n v: 1;\n persona: string;\n band: 'low' | 'medium' | 'high';\n slots: Record<string, SlotResult>;\n layoutOrder: string[] | null;\n savedAt: number;\n // Additive (kept at v:1 so existing snapshots stay valid — bumping the version\n // would flush every returning visitor's snapshot and flash the baseline once).\n // Present only for registry-mode (no-code) installs.\n slotConfig?: Record<string, SlotConfigEntry>;\n /** Derived site palette for Composition Block rendering — cached so the\n * pre-paint render already looks native (a palette that pops in post-decide\n * would be its own flash). */\n palette?: SitePalette;\n};\n\nconst BANDS = ['low', 'medium', 'high'];\n\n/** Returns null on missing, corrupt, or wrong-version data — never throws. */\nexport function readSnapshot(apiKey: string): DecisionSnapshot | null {\n try {\n const raw = localStorage.getItem(SNAPSHOT_STORAGE_KEY_PREFIX + apiKey);\n if (!raw) return null;\n const p = JSON.parse(raw) as Partial<DecisionSnapshot> | null;\n if (\n !p ||\n typeof p !== 'object' ||\n p.v !== 1 ||\n typeof p.persona !== 'string' ||\n typeof p.band !== 'string' ||\n !BANDS.includes(p.band) ||\n typeof p.slots !== 'object' ||\n p.slots === null ||\n Array.isArray(p.slots) ||\n !(p.layoutOrder === null || Array.isArray(p.layoutOrder)) ||\n typeof p.savedAt !== 'number' ||\n // slotConfig is optional; when present it must be a plain object.\n !(p.slotConfig === undefined || (typeof p.slotConfig === 'object' && p.slotConfig !== null && !Array.isArray(p.slotConfig)))\n ) {\n return null;\n }\n return p as DecisionSnapshot;\n } catch {\n return null;\n }\n}\n\n/** Best-effort persist — storage failures are swallowed. */\nexport function writeSnapshot(apiKey: string, snap: DecisionSnapshot): void {\n try {\n localStorage.setItem(SNAPSHOT_STORAGE_KEY_PREFIX + apiKey, JSON.stringify(snap));\n } catch {\n /* private mode / quota — the snapshot is an optimization, never a requirement */\n }\n}\n\n/**\n * Inline pre-paint script (Rung 1a): reads the snapshot and sets\n * `data-sentient-persona` / `data-sentient-confidence` on <html> before\n * first paint. Single-writer: it never overwrites attributes already set.\n *\n * Safety properties (pinned by tests):\n * - apiKey goes through JSON.stringify, then '<' is escaped to <, so a\n * hostile key can neither break the JS string nor terminate the <script>.\n * - Built by string concatenation and contains no backticks, so the output\n * survives being embedded in template-literal-based renderers.\n */\nexport function renderPrePaintScript(apiKey: string): string {\n const key = JSON.stringify(SNAPSHOT_STORAGE_KEY_PREFIX + apiKey).replace(/</g, '\\\\u003c');\n return (\n '(function(){try{' +\n 'var r=localStorage.getItem(' + key + ');if(!r)return;' +\n 'var s=JSON.parse(r);' +\n 'if(!s||s.v!==1||typeof s.persona!==\"string\"||typeof s.band!==\"string\")return;' +\n 'var d=document.documentElement;' +\n 'if(d.hasAttribute(\"data-sentient-persona\"))return;' +\n 'd.setAttribute(\"data-sentient-persona\",s.persona);' +\n 'd.setAttribute(\"data-sentient-confidence\",s.band);' +\n '}catch(e){}})();'\n );\n}\n","import { initSession, type SessionConfig, type SessionManager } from './session';\nimport {\n createEventQueue,\n retryStorageKey,\n type EventQueue,\n type EventType,\n type QueueConfig,\n type SentientEvent,\n} from './queue';\nimport {\n createGoalQueue,\n goalRetryStorageKey,\n type GoalQueue,\n} from './goal-queue';\nimport {\n createAssignmentCache,\n type Assignment,\n} from './cache';\nimport type {\n GraphConfig,\n GraphSnapshot,\n} from './graph';\nimport {\n detectDeviceClass,\n detectTrafficSource,\n detectTimeOfDay,\n referrerDomainFromReferer,\n uaTokenMatch,\n} from './session-meta.js';\nimport {\n toWireSlot,\n baselineResultFor,\n armOfResult,\n type SlotDeclInput,\n type SlotResult,\n} from './slots.js';\nimport { readSnapshot, writeSnapshot, SNAPSHOT_STORAGE_KEY_PREFIX, type SlotConfigEntry, type CompoundLocator } from './snapshot.js';\nimport { confidenceBand } from '@sentientui/policy';\nimport { createLocalModeClient } from './local-mode.js';\nimport { randomUuidV4 } from './uuid.js';\nimport { backoffDelayMs, classifyResponse } from './durable.js';\n\nexport { PROD_KEYLESS_ERROR, LOCAL_MODE_BANNER } from './local-mode.js';\n\n// The one source of truth for the session cookie's name — every out-of-package\n// reader (react devtools, integrator SSR code) must derive the name from this\n// instead of hard-coding `_snt_uid`, which is only the pre-namespacing fallback.\nexport { sessionCookieName, LEGACY_SESSION_COOKIE_NAME } from './storage-key.js';\n\nexport {\n detectDeviceClass,\n detectTrafficSource,\n detectTimeOfDay,\n deriveSessionSegment,\n referrerDomainFromReferer,\n uaTokenMatch,\n matchedAgentToken,\n agentUaList,\n agentIntent,\n classifiedAgents,\n AGENT_INTENTS,\n} from './session-meta.js';\nexport type { AgentIntent } from './session-meta.js';\n\nconst DEFAULT_INGEST_URL = 'https://api.sentient-ui.com/v1/events';\n\n// Keyed by apiKey so multiple init() calls (HMR, multi-project) don't collide.\nconst _clients = new Map<string, {\n config: SentientConfig;\n upgrade: ((c: SentientClient) => void) | null;\n // Why grantConsent() cannot upgrade this entry (keyless/local mode, invalid\n // key). grantConsent() warns with this instead of silently no-oping — a CMP\n // callback wired to it otherwise LOOKED like it worked while nothing ever\n // started tracking. Absent for entries where the silent no-op IS the\n // documented contract (DNT-blocked, already upgraded).\n upgradeBlockedReason?: string;\n // Set by an alternate entry point (the /graph entry) whose gated init\n // deferred extra resources: grantConsent() must re-run THAT entry's init —\n // upgrading through the lean init() produced a post-consent client that\n // never mounted the DOM scanner, silently losing graph capture.\n reinit?: (c: SentientConfig) => SentientClient;\n // Teardown for the live client bound to this key (stops its queue interval +\n // unload listeners). Present only for the full tracking client; the no-op /\n // pre-consent / local entries have nothing to tear down. Called before a\n // re-init for the same key replaces it, so timers/listeners can't leak.\n dispose?: () => void;\n}>();\nlet _lastApiKey: string | null = null;\n\n/**\n * @internal Wires an alternate entry point's init as grantConsent()'s upgrade\n * path for `apiKey`. The /graph entry calls this when its init is gated on\n * consent: without it, grantConsent() upgraded through the LEAN init, so a\n * graph-configured page granted consent but never mounted the scanner (the\n * graph resources exist only in the /graph entry). No-op unless the entry is\n * actually upgradeable — DNT-blocked and local entries register no hook.\n */\nexport function _registerConsentUpgradeInit(\n apiKey: string,\n reinit: (config: SentientConfig) => SentientClient,\n): void {\n const entry = _clients.get(apiKey);\n if (entry && entry.upgrade) entry.reinit = reinit;\n}\n\nexport type SentientConfig = {\n apiKey: string;\n context: 'landing' | 'ecommerce' | 'saas' | 'marketplace';\n /** @internal — not exposed to users; defaults to the hosted SentientUI API. */\n ingestUrl?: string;\n debug?: boolean;\n /**\n * Pre-seeded assignments from `preloadAssignments()` (SSR).\n * Seeds the local cache so `assign()` returns without a network call for\n * listed code variants, guaranteeing server and client render the same\n * variant on first paint. Managed-text components (assign with no\n * variantIds) still fetch once when the seed carries no content.\n */\n initialAssignments?: Record<string, string>;\n /**\n * Segment used for SSR preload (`device:source`). When set with `initialAssignments`,\n * seeds the assignment cache under this key so hydration matches the server bandit row.\n */\n sessionSegment?: string;\n /**\n * Consent gate. When `false`, returns a no-op client and performs no tracking.\n * Defaults to `true`. Re-call `init()` (via `AdaptiveProvider` consent prop) when\n * the user grants or revokes consent mid-session.\n */\n consent?: boolean;\n /**\n * Behavior before consent is granted. `'statistical_winner'` fetches the\n * best-performing variant via `GET /v1/winner` — no session or tracking data\n * is stored. `'control'` (default) shows `variantIds[0]` with no API call.\n * Applies when tracking is gated off — either `consent: false` or an active\n * Do Not Track signal.\n */\n preConsentBehavior?: 'statistical_winner' | 'control';\n /**\n * Whether to honor the browser's Do Not Track (DNT) signal. Defaults to `true`.\n * When `true` and the visitor has DNT enabled, the SDK sets no cookies and\n * sends no tracking data — behaving exactly as `consent: false` (still serving\n * the read-only `preConsentBehavior` winner if configured), and `grantConsent()`\n * will not upgrade it. Set `false` to make your own consent gate authoritative.\n */\n respectDoNotTrack?: boolean;\n userId?: string;\n /**\n * Declared persona — the role your app already knows for this visitor\n * (e.g. 'admin', 'evaluator'). Must be a key in the project's persona\n * vocabulary (dashboard → Settings → Personas); unrecognized values are\n * ignored server-side and surfaced in the dashboard so you can add them.\n * Declared personas are served at full confidence, overriding the inferred\n * one. Keep it a low-cardinality role label — never a user id or email.\n */\n persona?: string;\n /**\n * Session ID generated server-side (from `loadAdaptiveAssignments` / `loadAdaptiveDecision`).\n * When provided, the client adopts this ID on first visit instead of generating a new one,\n * ensuring events and goals are attributed to the same session the server used for assignment.\n */\n ssrSessionId?: string;\n /**\n * ISO 3166-1 alpha-2 country code for the visitor. When provided (e.g. from\n * the `CF-IPCountry` header in a Next.js server component), it is included in\n * the session upsert so country-based segmentation works without client-side\n * geo lookup.\n */\n country?: string;\n /**\n * Pre-seeded slot results from `preloadDecisions()` / `loadAdaptiveDecision()`\n * (SSR). Seeds the local slot state so `getSlotResult()` agrees with the\n * server-rendered markup on first paint.\n */\n initialSlots?: Record<string, SlotResult>;\n /**\n * Persona decided during SSR. Takes priority over the html-attribute\n * adoption and the local snapshot.\n */\n initialPersona?: { persona: string; confidence: number };\n /**\n * Keyless local mode. 'auto' (default) simulates decisions on-device when no\n * valid API key is configured — but only in development builds (the\n * `development` export condition); production bundles physically exclude the\n * engine. `true` forces the local engine regardless of key (escape hatch);\n * `false` restores the silent keyless no-op.\n */\n localMode?: 'auto' | boolean;\n};\n\nexport type AssignResult = { variantId: string; assignmentTtlMs: number; content?: string };\n\nexport type { SlotDeclInput, SlotResult };\nexport { armOfResult, baselineResultFor, baselineSlots, toWireSlot } from './slots.js';\n\nexport {\n SNAPSHOT_STORAGE_KEY_PREFIX,\n readSnapshot,\n writeSnapshot,\n renderPrePaintScript,\n} from './snapshot.js';\nexport type { DecisionSnapshot, SlotConfigEntry, SlotOps, CompoundLocator } from './snapshot.js';\nexport * from './blocks.js';\n\n/** An editor-defined goal delivered with a registry-mode decision, for the\n * snippet to install delegated listeners from. */\nexport type GoalDefinition = {\n goalId: string;\n event: 'click' | 'form_submit' | 'url_reached' | 'scroll_depth';\n locator?: CompoundLocator;\n urlPattern?: string;\n slotId?: string;\n /** scroll_depth only: fraction of the page (0–1] that counts as read. */\n threshold?: number;\n};\n\n/** One served section-classification row (registry mode): where it is on the\n * page (url match + compound locator) and its semantic type. The snippet\n * resolves the locator to build capture's `typeOf` hook. */\nexport type SectionMapEntry = {\n urlMatch: string;\n locator: CompoundLocator;\n type: string;\n};\n\nexport type DecideOutcome = {\n layoutOrder: string[] | null;\n assignments: Record<string, string>;\n slots: Record<string, SlotResult>;\n persona: string;\n confidence: number;\n // Registry mode only: where/what to apply for server-defined slots.\n slotConfig?: Record<string, SlotConfigEntry>;\n // Registry mode only: editor-defined goals to wire up.\n goals?: GoalDefinition[];\n // Registry mode only: served section-classification map the snippet turns\n // into capture's `typeOf` hook.\n sectionMap?: SectionMapEntry[];\n // Registry mode only: derived site palette for Composition Block rendering.\n palette?: import('./blocks.js').SitePalette;\n};\n\nexport type DecideInput = {\n sections?: string[];\n components?: Array<{ id: string; variantIds?: string[] }>;\n slots?: SlotDeclInput[];\n // 'registry' → serve the project's published slot_definitions in addition to\n // any declared slots (registry wins on id collision). Default 'request'.\n slotsFrom?: 'request' | 'registry';\n /**\n * Caller's build version (e.g. the snippet's `__SNIPPET_VERSION__`), sent\n * as `v` on the wire. Additive/best-effort: the server persists it for\n * version-skew reporting (see apps/api decide route) and ignores it\n * entirely on older deployments. Omit if the caller has no version to report.\n */\n v?: string;\n};\n\nexport type WeightEntry = { variantId: string; pulls: number; avgReward: number | null };\nexport type ComponentWeightEntry = { componentId: string; updatedAt: number; variants: WeightEntry[] };\n\n/** Options accepted by goal() (and inherited by componentGoal / the React\n * hooks / the snippet) — one shape everywhere (spec §5). */\nexport type GoalOptions = {\n /** Revenue of this conversion, in the project currency. */\n value?: number;\n /** ISO-4217 code, only when it differs from the project currency. */\n currency?: string;\n /** Merchant order/transaction id — dedupes retries, enables refunds later. */\n externalId?: string;\n /** Extra fields merged into the event payload / goal metadata. */\n metadata?: Record<string, unknown>;\n /** Advanced: partial-credit weight in [0,1] (composite steps). */\n weight?: number;\n /** Advanced: funnel step index (0-based). */\n stepIndex?: number;\n};\n\n/** goal()'s second arg is the options object iff it carries a reserved key;\n * anything else keeps the legacy bare-metadata interpretation. Reserved keys\n * inside legacy metadata were inert on the server, so reinterpretation is the\n * upgrade the sender wanted (spec §5). */\nfunction isGoalOptions(v: Record<string, unknown>): boolean {\n return 'value' in v || 'currency' in v || 'externalId' in v || 'metadata' in v || 'weight' in v || 'stepIndex' in v;\n}\n\nexport type ComponentGoalOptions = GoalOptions & {\n /** Reward credited to the served variant (0–1). Defaults to 1. */\n reward?: number;\n};\n\nexport type SentientClient = {\n track(\n event: Omit<SentientEvent, 'id' | 'sessionId' | 'timestamp' | 'timeInSession'>,\n ): void;\n goal(name: string, options?: GoalOptions): void;\n /** @deprecated positional form — prefer goal(name, options). */\n goal(name: string, metadata?: Record<string, unknown>, weight?: number, stepIndex?: number): void;\n /**\n * Records a conversion attributed to the variant currently served for\n * `componentId`, so it feeds the per-variant CVR funnel. Resolves the served\n * variant from the local assignment cache — no need to pass variantId or\n * projectId. No-ops if the component has not been assigned yet (render its\n * `<Adaptive>`/call `assign()` first). Prefer this over bare `goal()` for\n * variant experiments; `goal()` is session-level only (no component attribution).\n */\n componentGoal(componentId: string, goalType: string, opts?: ComponentGoalOptions): void;\n identify(userId: string): void;\n getAssignment(componentId: string, segment: string): Assignment | null;\n /** Server-side variant assignment. Caches the result locally per (component, segment). */\n assign(componentId: string, variantIds?: string[], agentData?: unknown, agentDataByVariant?: Record<string, unknown>): Promise<AssignResult | null>;\n /**\n * Single-roundtrip decision for layout sections, component variants, and\n * adaptive slots. Awaits the session upsert (like `assign`) so the server\n * never decides for a session row that doesn't exist yet. A response\n * without a `slots` field means the server predates slots — every declared\n * slot resolves to its baseline and no retry is made.\n */\n decide(input: DecideInput): Promise<DecideOutcome | null>;\n /** Slot result served this session (decide result, SSR seed, snapshot, or failure baseline). Null when unknown. */\n getSlotResult(slotId: string): SlotResult | null;\n /** Current persona estimate. Band is always `confidenceBand(confidence)`. Null when nothing is known yet. */\n getPersona(): { persona: string; confidence: number; band: 'low' | 'medium' | 'high' } | null;\n /** Fetches current bandit weights for all components in this project. Used by the provider to keep live-weight polling fresh. */\n fetchWeights(): Promise<ComponentWeightEntry[]>;\n getGraph(): GraphSnapshot;\n /**\n * Routine teardown: stops timers/listeners and flushes pending events, but\n * KEEPS the visitor identity, decision snapshot, and retry bucket. Use for\n * component unmount / re-init (framework providers call this on cleanup).\n */\n dispose(): void;\n /**\n * Consent-revocation / forget-me teardown: everything `dispose()` does,\n * plus deletion of the visitor identity (`_snt_uid`), the decision\n * snapshot, and the persisted retry bucket. The next visit starts as a\n * brand-new visitor.\n */\n destroy(): void;\n /** True when this client is the keyless local-mode client (dev only). */\n readonly isLocal?: boolean;\n};\n\n// SSR preload helpers moved to the `@sentientui/core/server` entry in 0.6.0 so\n// ~200 lines of Node-only fetch logic stop shipping in the browser bundle.\n\nexport { attachMicroSignalDetectors } from './micro-signals.js';\nexport type { MicroSignalEmitter, MicroSignalType } from './micro-signals.js';\n\nexport type {\n SessionConfig,\n SessionManager,\n EventType,\n SentientEvent,\n QueueConfig,\n Assignment,\n GraphSnapshot,\n GraphConfig,\n};\n\n/** Attempts after the first for the session upsert — see upsertSession. */\nconst SESSION_UPSERT_RETRIES = 3;\n\nfunction generateEventId(): string {\n return randomUuidV4();\n}\n\n/**\n * The page an event happened on.\n *\n * `location.pathname` ONLY — never `href` or `search`. Query strings on real\n * sites carry emails, reset tokens, order ids and session ids, and none of that\n * should leave the browser for analytics. The server strips them again\n * (domain/page-path.ts) because a hand-rolled integration can post whatever it\n * likes; this is the first of the two gates, and the one that means the data\n * never travels at all.\n *\n * Undefined outside a browser: during SSR there is no page to name, and an\n * invented one would be wrong for every reader.\n */\nfunction currentPath(): string | undefined {\n if (typeof window === 'undefined') return undefined;\n return window.location?.pathname || undefined;\n}\n\n/**\n * Decides whether a goal() call belongs to a user action already recorded.\n *\n * This used to be a clock: a latch cleared on the next macrotask, so anything\n * inside that window counted as \"the same action\". A clock cannot tell the two\n * cases apart, and it got the expensive one wrong. The window can be JUMPED —\n * a macrotask scheduled to close it runs after any timer already armed, which\n * every real page and every sibling test in a worker has — so a genuinely\n * separate conversion landed in a window that should have shut, and was\n * swallowed rather than queued: gone, with no retry able to rescue it because\n * nothing was ever handed to the queue.\n *\n * So ask the question the clock was approximating. Two nested components\n * reacting to one click are, exactly, two listeners in one event DISPATCH, and\n * the platform already hands us that identity: `window.event` is the same Event\n * object for every listener of one dispatch, a different object for the next\n * click, and undefined outside dispatch entirely. Keying on the event object\n * makes \"one action\" a fact rather than a deadline — no timer to lose a race\n * with, no fake-timer or background-throttle hazard, and no way for a second\n * click to be mistaken for the first however long the page stalls between them.\n *\n * Goals fired outside any dispatch (an effect on mount, a page goal) have no\n * event to key on, and fall back to one SYNCHRONOUS flush — closed on a\n * microtask. That is exact too, and for the same reason the old macrotask\n * window was not: microtasks always drain before the next macrotask, so no\n * pending timer can jump this window. A user cannot perform two actions inside\n * one synchronous block, so anything sharing it is a double-fire, not a repeat.\n *\n * A microtask is deliberately NOT used for the dispatch case: the HTML spec\n * runs a microtask checkpoint between listeners once the JS stack empties, so\n * it would split one click into two and double-count the revenue this collapse\n * exists to protect. That is why the dispatch case keys on the event instead,\n * and why a host without `window.event` keeps the old macrotask window — too\n * loose, but erring toward the old behaviour rather than toward double-counting.\n */\nfunction createActionLatch(): { firedBefore(actionKey: string, valueKey: string | null): boolean } {\n // Per window, per action key: the set of value identities already recorded.\n // An entry with an empty set means a VALUELESS fire was recorded. The split\n // exists because value cannot simply live inside one flat key: an inner\n // component declaring `value: 50` nested in an outer wrapper with the same\n // goal but NO value produced two distinct keys — two rows for one click.\n // Within a window, a valueless fire is absorbed by ANY record of the same\n // action (the valued row already carries the order, and a valueless\n // duplicate would inflate Hits), while a valued fire is collapsed only by an\n // IDENTICAL (value, currency) record — $50 and $70 stay two orders\n // (CONTRACTS §1). A valued fire landing AFTER a valueless one still records:\n // the valueless row has already been handed to the queue (often already on\n // the wire) and cannot be retracted, and losing the money would be the worse\n // error — server-side credit clamps the extra valueless hit at min(1, MAX\n // weight), so the cost is one inflated Hit, not corrupted revenue. Listener\n // order makes the benign ordering the common one: the inner (valued)\n // component's listener runs before the wrapper's in a bubbling dispatch.\n const byEvent = new WeakMap<object, Map<string, Set<string>>>();\n const byFlush = new Map<string, Set<string>>();\n let flushOpen = false;\n\n const alreadyRecorded = (map: Map<string, Set<string>>, actionKey: string, valueKey: string | null): boolean => {\n const values = map.get(actionKey);\n if (valueKey === null) {\n if (values) return true;\n map.set(actionKey, new Set());\n return false;\n }\n if (!values) {\n map.set(actionKey, new Set([valueKey]));\n return false;\n }\n if (values.has(valueKey)) return true;\n values.add(valueKey);\n return false;\n };\n\n // Standardised as Window.event and present in every current browser, but a\n // capability check keeps exotic hosts on the path they have always had.\n const hasWindowEvent = typeof window !== 'undefined' && 'event' in window;\n\n const currentEvent = (): object | undefined => {\n if (!hasWindowEvent) return undefined;\n const ev = (window as unknown as { event?: unknown }).event;\n // Must be a real same-realm Event, not merely an object. Window.event is\n // [Replaceable]: a classic script doing `event = {...}` at top level (an\n // implicit or sloppy global on plenty of host pages) permanently shadows\n // the accessor with a data property. Accepting any object then returned\n // that SAME object forever — its WeakMap entry never died, so every later\n // conversion looked like a re-fire of the first action and ALL repeat\n // conversions were silently dropped for the session. `instanceof Event`\n // cannot be true for such a literal; a cross-realm Event (iframe) fails it\n // too and merely falls back to the flush window, which is safe.\n // (typeof guard: a host with `window` but no Event constructor must fall\n // back, not throw a ReferenceError from inside goal().)\n return typeof Event === 'function' && ev instanceof Event ? ev : undefined;\n };\n\n const closeFlushWindow = (): void => {\n if (hasWindowEvent) {\n // A promise microtask, not queueMicrotask: fake-timer setups can replace\n // queueMicrotask, and this window closing is what keeps repeat\n // conversions from being swallowed.\n void Promise.resolve().then(() => {\n flushOpen = false;\n byFlush.clear();\n });\n return;\n }\n let done = false;\n const clear = (): void => {\n if (done) return;\n done = true;\n flushOpen = false;\n byFlush.clear();\n };\n setTimeout(clear, 0);\n if (typeof MessageChannel === 'function') {\n const ch = new MessageChannel();\n ch.port1.onmessage = () => {\n ch.port1.close();\n ch.port2.close();\n clear();\n };\n ch.port2.postMessage(0);\n }\n };\n\n return {\n firedBefore(actionKey: string, valueKey: string | null): boolean {\n const ev = currentEvent();\n if (ev) {\n let keys = byEvent.get(ev);\n if (!keys) {\n keys = new Map<string, Set<string>>();\n // Keyed weakly: the Map dies with the Event object, so a long session\n // of clicks accumulates nothing.\n byEvent.set(ev, keys);\n }\n return alreadyRecorded(keys, actionKey, valueKey);\n }\n const collapsed = alreadyRecorded(byFlush, actionKey, valueKey);\n if (!collapsed && !flushOpen) {\n flushOpen = true;\n closeFlushWindow();\n }\n return collapsed;\n },\n };\n}\n\n/**\n * Emits one `pageview` per page load and per SPA route change.\n *\n * Patches pushState/replaceState rather than polling: a route change is a\n * discrete event, and polling would either miss fast back-to-back navigations or\n * burn a timer on every page for the entire session. popstate covers\n * back/forward, which history patching does not see.\n *\n * Deduplicates on pathname, because frameworks routinely replaceState several\n * times for one navigation (query/hash updates, scroll restoration) and each\n * would otherwise look like another page in the visitor's journey.\n */\n/** Pages already recorded this page lifetime, keyed project:path. dispose()\n * flushes, so without this a consent-change or StrictMode re-init delivered a\n * second landing pageview for a page the previous client already sent. */\nconst emittedPages = new Set<string>();\n\nfunction startPageviewTracking(\n client: SentientClient,\n projectId: string,\n // Called with the page key after emitting; the caller marks emittedPages only\n // once the event reached a LIVE queue. Marking at emit time instead turned\n // StrictMode's mount→dispose→mount into zero delivered landings: the first\n // mount's event dies in the destroyed queue, and the mark suppressed the\n // second mount's — the one that actually ships.\n markDelivered: (key: string) => void,\n): () => void {\n const h = typeof window === 'undefined' ? null : window.history;\n if (!h) return () => undefined;\n\n // The stop handle exists because init() runs again on every consent change,\n // StrictMode double-invoke and HMR: without it each init wrapped history\n // again and the old wrapper kept emitting through the DISPOSED client, so one\n // navigation produced one pageview per init that ever happened.\n let stopped = false;\n let last: string | undefined;\n const emit = (): void => {\n if (stopped) return;\n const path = currentPath();\n if (!path || path === last) return;\n last = path;\n // '__page__' is a sentinel componentId: the ingest schema requires one, and\n // every component reader filters on variant_id IS NOT NULL or a specific\n // event_type, so it never surfaces as a component.\n client.track({ projectId, componentId: '__page__', eventType: 'pageview', payload: {} });\n markDelivered(`${projectId}:${path}`);\n };\n\n const installed: Array<['pushState' | 'replaceState', History['pushState'], History['pushState']]> = [];\n for (const name of ['pushState', 'replaceState'] as const) {\n const orig = h[name];\n const wrapper = function (this: History, ...a: unknown[]) {\n const r = (orig as (...x: unknown[]) => unknown).apply(this, a);\n emit();\n return r;\n } as History[typeof name];\n h[name] = wrapper;\n installed.push([name, orig, wrapper]);\n }\n window.addEventListener('popstate', emit);\n\n // The landing page itself — once per (project, path) per page lifetime. When\n // it was already sent, `last` is still primed so the next real navigation\n // emits exactly once.\n const landing = currentPath();\n if (landing && emittedPages.has(`${projectId}:${landing}`)) last = landing;\n else emit();\n\n return () => {\n if (stopped) return;\n stopped = true;\n window.removeEventListener('popstate', emit);\n for (const [name, orig, wrapper] of installed) {\n // Restore only while ours is still on top; if something wrapped over it,\n // unhooking would sever their chain — the stopped flag already makes ours\n // a passthrough.\n if (h[name] === wrapper) h[name] = orig;\n }\n };\n}\n\nconst SSR_CLIENT: SentientClient = {\n track: () => undefined,\n goal: () => undefined,\n componentGoal: () => undefined,\n identify: () => undefined,\n getAssignment: () => null,\n assign: () => Promise.resolve(null),\n decide: () => Promise.resolve(null),\n getSlotResult: () => null,\n getPersona: () => null,\n fetchWeights: () => Promise.resolve([]),\n getGraph: () => ({ pageNodes: [], capturedAt: 0 }),\n dispose: () => undefined,\n destroy: () => undefined,\n};\n\nfunction readUtmParams(): Record<string, string> {\n try {\n const out: Record<string, string> = {};\n const sp = new URLSearchParams(window.location.search);\n for (const [k, v] of sp) {\n if (k.startsWith('utm_')) out[k] = v;\n }\n return out;\n } catch {\n return {};\n }\n}\n\nfunction deriveBaseUrl(ingestUrl: string): string {\n return ingestUrl.replace(/\\/events\\/?$/, '');\n}\n\n/**\n * Detects whether the visitor has signalled a tracking opt-out. Honors Global\n * Privacy Control (`navigator.globalPrivacyControl`) — the legally-enforceable\n * CCPA/CPRA signal — as well as Do Not Track (`navigator.doNotTrack`, the legacy\n * `window.doNotTrack` on older Firefox, and `navigator.msDoNotTrack` on old\n * IE/Edge). GPC is a boolean; DNT is opt-out only when explicitly `'1'`/`'yes'`.\n */\nexport function isDoNotTrackEnabled(): boolean {\n // GPC is a boolean flag, checked separately from the DNT string signals.\n if (\n typeof navigator !== 'undefined' &&\n (navigator as unknown as { globalPrivacyControl?: boolean }).globalPrivacyControl === true\n ) {\n return true;\n }\n const signals = [\n typeof navigator !== 'undefined' ? navigator.doNotTrack : undefined,\n typeof window !== 'undefined'\n ? (window as unknown as { doNotTrack?: string | null }).doNotTrack\n : undefined,\n typeof navigator !== 'undefined'\n ? (navigator as unknown as { msDoNotTrack?: string | null }).msDoNotTrack\n : undefined,\n ];\n return signals.some((v) => v === '1' || v === 'yes');\n}\n\n/**\n * Upgrades a pre-consent client (any client created with `consent: false`, in\n * either `preConsentBehavior` mode) to a fully-tracking client, in place and\n * with no page reload. Call this from your consent management platform callback.\n * For React apps, prefer updating the `consent` prop on `<AdaptiveProvider>`.\n * Pass `apiKey` to target a specific project; omit to upgrade the most-recently-initialized client.\n */\nexport function grantConsent(apiKey?: string): void {\n if (typeof window === 'undefined') return;\n\n const key = apiKey ?? _lastApiKey;\n if (!key) {\n console.warn('[sentient] grantConsent() called before init()');\n return;\n }\n\n const entry = _clients.get(key);\n if (!entry) {\n console.warn('[sentient] grantConsent() called before init()');\n return;\n }\n\n const { config, upgrade, reinit } = entry;\n if (!upgrade) {\n // Keyless/local and invalid-key clients register no upgrade hook — there\n // is no hosted client to swap in. This used to return SILENTLY, so a CMP\n // callback wired to grantConsent() looked like it worked while nothing\n // ever started tracking. DNT-blocked and already-upgraded entries carry no\n // reason and stay quiet: for them the no-op is the documented contract.\n if (entry.upgradeBlockedReason) console.warn(entry.upgradeBlockedReason);\n return;\n }\n\n // Honor an active Do Not Track signal — consent cannot override a global opt-out.\n if (config.respectDoNotTrack !== false && isDoNotTrackEnabled()) return;\n\n // Upgrade through the entry point that ran the gated init when one\n // registered itself (see _registerConsentUpgradeInit) — the lean init knows\n // nothing about that entry's extra resources (the /graph scanner).\n const fullClient = (reinit ?? init)({ ...config, consent: true });\n upgrade(fullClient);\n // init() just registered the full client (with its dispose) under `key`.\n // Preserve that dispose so a later re-init/teardown can still tear it down —\n // we only need to clear the upgrade hook now that consent is granted.\n const disposed = _clients.get(key)?.dispose;\n _clients.set(key, { config: { ...config, consent: true }, upgrade: null, dispose: disposed });\n}\n\nfunction createPreConsentProxy(config: SentientConfig): { proxy: SentientClient; setInner: (c: SentientClient) => void } {\n // 'control' (the default) must reach the network zero times before consent.\n // The proxy still exists so grantConsent() has something to upgrade in place\n // — without it, a site wanting no pre-consent traffic could only start\n // tracking by reloading the page.\n const servesWinner = config.preConsentBehavior === 'statistical_winner';\n const baseUrl = deriveBaseUrl(config.ingestUrl ?? DEFAULT_INGEST_URL);\n const authHeaders = {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${config.apiKey}`,\n } as const;\n\n // Pre-consent winners are read-only and render-driven: every mounted\n // component re-calls assign() on every render, and without a result cache or\n // in-flight coalescing each call refired GET /v1/winner — the full client\n // has inflightAssigns for exactly this. Successful winners are cached for\n // the pre-consent phase (the winner is stable, and a flip mid-visit would be\n // a variant flash anyway); failure fallbacks are NOT cached, so a recovering\n // server gets asked again. Both maps die with the proxy on upgrade.\n const winnerCache = new Map<string, AssignResult>();\n const inflightWinners = new Map<string, Promise<AssignResult | null>>();\n\n let inner: SentientClient = {\n track: () => undefined,\n goal: () => undefined,\n componentGoal: () => undefined,\n identify: () => undefined,\n getAssignment: () => null,\n fetchWeights: () => Promise.resolve([]),\n assign(componentId, variantIds, _agentData?) {\n // Control mode: no request. Callers fall back to variantIds[0] through\n // ssrFallback, exactly as they did against the old no-op client.\n if (!servesWinner) return Promise.resolve(null);\n const cached = winnerCache.get(componentId);\n if (cached) return Promise.resolve(cached);\n return coalesce(inflightWinners, componentId, async (): Promise<AssignResult | null> => {\n try {\n const params = new URLSearchParams({ componentId });\n for (const v of variantIds ?? []) params.append('variantIds[]', v);\n const res = await fetch(`${baseUrl}/winner?${params.toString()}`, {\n headers: authHeaders,\n });\n if (!res.ok) return variantIds?.[0] ? { variantId: variantIds[0], assignmentTtlMs: 0 } : null;\n const body = (await res.json()) as { variantId: string };\n const result: AssignResult = { variantId: body.variantId, assignmentTtlMs: 0 };\n winnerCache.set(componentId, result);\n return result;\n } catch {\n return variantIds?.[0] ? { variantId: variantIds[0], assignmentTtlMs: 0 } : null;\n }\n });\n },\n decide: () => Promise.resolve(null),\n getSlotResult: () => null,\n getPersona: () => null,\n getGraph: () => ({ pageNodes: [], capturedAt: 0 }),\n dispose: () => undefined,\n destroy: () => undefined,\n };\n\n const proxy: SentientClient = {\n track: (e) => inner.track(e),\n // Cast: a single arrow can't structurally satisfy the overloaded member;\n // the passthrough forwards both call shapes untouched.\n goal: ((n: string, m?: Record<string, unknown>, w?: number, s?: number) => inner.goal(n, m, w, s)) as SentientClient['goal'],\n componentGoal: (c, g, o) => inner.componentGoal(c, g, o),\n identify: (u) => inner.identify(u),\n getAssignment: (c, s) => inner.getAssignment(c, s),\n assign: (c, v, a, av) => inner.assign(c, v, a, av),\n decide: (i) => inner.decide(i),\n getSlotResult: (s) => inner.getSlotResult(s),\n getPersona: () => inner.getPersona(),\n fetchWeights: () => inner.fetchWeights(),\n getGraph: () => inner.getGraph(),\n dispose: () => inner.dispose(),\n destroy: () => inner.destroy(),\n };\n\n function setInner(fullClient: SentientClient) {\n inner = fullClient;\n }\n\n return { proxy, setInner };\n}\n\n/**\n * Shares one promise among concurrent calls with the same key — assign() and\n * decide() both use this so N same-tick requests (several mounted slots\n * sharing a component id; per-slot lazy decides) cost one roundtrip. The map\n * entry lives exactly as long as the request is in flight: a settled result\n * must NOT serve later calls (a sequential re-request is a fresh decision —\n * caching lives elsewhere), and a failed one must not wedge the key. No\n * `.finally()` — that's ES2018 and this file ships in the es2017 snippet\n * bundle (the SNIP-5 lesson).\n */\nfunction coalesce<T>(inflight: Map<string, Promise<T>>, key: string, run: () => Promise<T>): Promise<T> {\n const hit = inflight.get(key);\n if (hit) return hit;\n const request = (async (): Promise<T> => {\n try {\n return await run();\n } finally {\n inflight.delete(key);\n }\n })();\n inflight.set(key, request);\n return request;\n}\n\n/**\n * Initializes the Sentient client. Returns a no-op client during SSR.\n */\nexport function init(config: SentientConfig): SentientClient {\n if (typeof window === 'undefined') {\n return SSR_CLIENT;\n }\n\n // `|| 'local'`: keyless clients register under the 'local' fallback key\n // below, and `_lastApiKey = ''` is falsy — so a no-arg grantConsent() after\n // a keyless init() warned \"called before init()\" even though init() DID run,\n // instead of resolving that entry (and its blocked-upgrade explanation).\n _lastApiKey = config.apiKey || 'local';\n\n // A re-init for the same key (HMR, consent toggle, provider remount) supersedes\n // the prior client. Dispose it first so its queue's setInterval and\n // visibilitychange/pagehide listeners don't leak — the map only ever held its\n // config, so without this the old client kept flushing forever.\n const prevEntry = _clients.get(config.apiKey || 'local');\n if (prevEntry?.dispose) {\n try {\n prevEntry.dispose();\n } catch {\n /* teardown must never throw on re-init */\n }\n }\n\n // DNT/GPC (a global opt-out) or an explicit `consent: false` must be evaluated\n // BEFORE the local-mode branch: createLocalModeClient() calls initSession()\n // unconditionally, so a gated visitor would otherwise be issued the 365-day\n // `_snt_uid` identity cookie in keyless/local mode (audit P2). DNT/GPC also\n // gates tracking off even when the site passes `consent: true`, and blocks\n // `grantConsent()` from upgrading.\n const dntBlocked = config.respectDoNotTrack !== false && isDoNotTrackEnabled();\n const gated = config.consent === false || dntBlocked;\n\n // Keyless local mode. `localMode: true` forces the local engine (documented\n // escape hatch); 'auto' (default) engages it only when no valid key is\n // present. In production builds `@sentientui/core/local` resolves to a stub\n // and this degrades to a no-op client + one console.error per page load\n // (createLocalModeClient handles that), so no NODE_ENV check is needed here.\n const keyValid = typeof config.apiKey === 'string' && config.apiKey.startsWith('pk_');\n if (config.localMode === true || (!keyValid && config.localMode !== false)) {\n // One registration for both arms (they used to duplicate this set call).\n // upgrade stays null — there is no hosted client to swap in — but the\n // reason lets grantConsent() explain that instead of no-oping silently.\n _clients.set(config.apiKey || 'local', {\n config,\n upgrade: null,\n upgradeBlockedReason:\n '[sentient] grantConsent(): this client is keyless/local — there is no hosted client to upgrade to. Configure a pk_ API key to enable tracking.',\n });\n // A gated visitor must never get the identity cookie. Local mode has no\n // server to serve a statistical winner from, so return a plain no-op.\n if (gated) return SSR_CLIENT;\n return createLocalModeClient(config);\n }\n\n if (gated) {\n if (!config.apiKey || !config.apiKey.startsWith('pk_')) {\n if (config.preConsentBehavior === 'statistical_winner') {\n console.warn('[sentient] init() called with an invalid apiKey — expected a pk_ public key. SDK disabled.');\n }\n // Registered under the same 'local' fallback key the local branch uses:\n // `config.apiKey` here can be '', and a ''-keyed entry was unreachable\n // by a no-arg grantConsent() (falsy `_lastApiKey`), which then wrongly\n // warned \"called before init()\".\n _clients.set(config.apiKey || 'local', {\n config,\n upgrade: null,\n upgradeBlockedReason:\n '[sentient] grantConsent(): the client was initialized with an invalid apiKey (expected a pk_ public key) — consent cannot enable tracking.',\n });\n return SSR_CLIENT;\n }\n // Every gated client gets an upgradeable proxy, not just the winner-serving\n // one — otherwise grantConsent() is silently dead for the 'control' default\n // and the site has to reload to start tracking. Control mode still makes no\n // request; the proxy only exists so consent can swap the inner client.\n const { proxy, setInner } = createPreConsentProxy(config);\n // Under DNT the read-only winner still serves, but consent can never\n // upgrade it to tracking — so drop the upgrade hook.\n _clients.set(config.apiKey, { config, upgrade: dntBlocked ? null : setInner });\n return proxy;\n }\n\n if (!config.apiKey || !config.apiKey.startsWith('pk_')) {\n console.warn('[sentient] init() called with an invalid apiKey — expected a pk_ public key. SDK disabled.');\n return SSR_CLIENT;\n }\n\n if (config.ingestUrl === '') {\n console.warn('[sentient] init() called with an empty ingestUrl. SDK disabled.');\n return SSR_CLIENT;\n }\n\n const resolvedIngestUrl = config.ingestUrl ?? DEFAULT_INGEST_URL;\n\n const sessionStart = Date.now();\n const session = initSession({ ssrSessionId: config.ssrSessionId, apiKey: config.apiKey });\n const assignmentCache = createAssignmentCache(undefined, config.apiKey);\n const eventQueue = createEventQueue({ ingestUrl: resolvedIngestUrl, apiKey: config.apiKey });\n const baseUrl = deriveBaseUrl(resolvedIngestUrl);\n\n const authHeaders = {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${config.apiKey}`,\n } as const;\n\n // Conversions get the same durable transport the event queue has always had:\n // retry with backoff, a cross-reload bucket, dedupe on the server's goalId.\n // One warning per distinct drop status per page load (see onDrop below).\n const warnedDropStatuses = new Set<number>();\n const goalQueue: GoalQueue = createGoalQueue({\n url: `${baseUrl}/goals`,\n apiKey: config.apiKey,\n headers: authHeaders,\n onDrop: (goal, status) => {\n // NOT debug-gated. CONTRACTS §7 says a dropped goal is reported to the\n // developer and never swallowed, but this returned early unless debug was\n // on — so in production a rate-limited or misconfigured project lost every\n // conversion with no signal anywhere. Warn once per (status, page load):\n // enough to be discoverable in a console or an error reporter, quiet\n // enough that a broken integration cannot flood the page.\n if (!config.debug) {\n if (warnedDropStatuses.has(status)) return;\n warnedDropStatuses.add(status);\n }\n console.warn(\n `[sentient] goal dropped (HTTP ${status}) — this will not be retried. ` +\n (status === 400\n ? 'The session was not found: call init() and let the session upsert complete before firing goals.'\n : status === 401 || status === 403\n ? 'Check the API key and that this origin is on the project allowlist.'\n : 'See the response status for the cause.'),\n goal,\n );\n },\n });\n\n const deviceClass = detectDeviceClass(navigator.userAgent ?? '');\n // No window guard here: init() already returned SSR_CLIENT at the top when\n // window is undefined, so the old `typeof window` ternary was dead code.\n const appOrigin = window.location.origin;\n const trafficSource = detectTrafficSource(document.referrer ?? '', appOrigin);\n const sessionSegment =\n config.sessionSegment ?? `${deviceClass}:${trafficSource}`;\n const inflightAssigns = new Map<string, Promise<AssignResult | null>>();\n // Mirrors inflightAssigns for decide(): per-slot lazy-decide patterns (see\n // local-mode's merge comment — one decide({ slots: [decl] }) per mounted\n // slot, all in the same tick) otherwise issue N roundtrips and N snapshot\n // rewrites for one page. Keyed by the full request payload, never just \"a\n // decide is running\": coalescing {slots:[a]} with {slots:[b]} would hand\n // slot b's caller an outcome that never decided b.\n const inflightDecides = new Map<string, Promise<DecideOutcome | null>>();\n\n // --- Adaptive-slot state (decide) ---\n // Results served for this session, keyed by slot id. Written by decide();\n // read by getSlotResult() (Task 3.3) and componentGoal's slot fallback.\n const slotStore = new Map<string, SlotResult>();\n let personaState: { persona: string; confidence: number } | null = null;\n\n // On decide failure every declared slot must still resolve — to its baseline.\n // Never overwrite a previously served result.\n const seedSlotBaselines = (decls: SlotDeclInput[]): void => {\n for (const d of decls) {\n if (!slotStore.has(d.id)) slotStore.set(d.id, baselineResultFor(d));\n }\n };\n\n // Seed slot/persona state. Priority: explicit SSR seeds → snapshot.\n if (config.initialSlots) {\n for (const [slotId, result] of Object.entries(config.initialSlots)) {\n slotStore.set(slotId, result);\n }\n }\n const seedSnapshot = readSnapshot(config.apiKey);\n if (seedSnapshot) {\n for (const [slotId, result] of Object.entries(seedSnapshot.slots)) {\n if (!slotStore.has(slotId)) slotStore.set(slotId, result);\n }\n }\n\n // Band-only persona sources (html attrs, snapshot) become a band-consistent\n // numeric confidence so confidenceBand(confidence) always equals the band.\n const BAND_CONFIDENCE: Record<string, number> = { low: 0.15, medium: 0.5, high: 0.85 };\n if (config.initialPersona) {\n personaState = { ...config.initialPersona };\n } else {\n // Single-writer rule: the inline pre-paint script owns the <html>\n // attributes. The client ADOPTS them as truth and never rewrites them\n // mid-session (next visit's script picks up the new snapshot instead).\n const ds = document.documentElement.dataset;\n if (ds.sentientPersona) {\n personaState = {\n persona: ds.sentientPersona,\n confidence: BAND_CONFIDENCE[ds.sentientConfidence ?? 'low'] ?? 0.15,\n };\n } else if (seedSnapshot) {\n personaState = {\n persona: seedSnapshot.persona,\n confidence: BAND_CONFIDENCE[seedSnapshot.band] ?? 0.15,\n };\n }\n }\n\n // Seed SSR-preloaded assignments into the local cache so assign() finds a\n // cache hit immediately — no network call, no variant flash on hydration.\n if (config.initialAssignments) {\n for (const [componentId, variantId] of Object.entries(config.initialAssignments)) {\n assignmentCache.set(componentId, sessionSegment, {\n variantId,\n assignedAt: Date.now(),\n segment: sessionSegment,\n confidence: 1,\n });\n }\n }\n\n // Upsert session metadata once on init. assign() awaits this promise so\n // the server isn't asked to assign for a session row that doesn't exist yet.\n let sessionReady: Promise<void> = Promise.resolve();\n\n const sessionId = session.getSessionId();\n if (sessionId) {\n const referrerDomain = referrerDomainFromReferer(document.referrer ?? '');\n const sessionBody = {\n sessionId,\n deviceClass,\n trafficSource,\n referrerDomain,\n utmParams: readUtmParams(),\n timeOfDay: detectTimeOfDay(new Date()),\n dayOfWeek: ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'][new Date().getDay()],\n ephemeral: session.isEphemeral(),\n // Likely-automation hint: navigator.webdriver (set under automation\n // control) or a known agent token in the UA. Probabilistic — used for\n // metrics + bandit exclusion server-side, never to change what's served.\n automation:\n (typeof navigator !== 'undefined' && navigator.webdriver === true) ||\n uaTokenMatch(navigator.userAgent ?? ''),\n ...(config.userId ? { userId: config.userId } : {}),\n ...(config.persona ? { persona: config.persona } : {}),\n ...(config.country ? { country: config.country } : {}),\n };\n // The session row is a PRECONDITION for every conversion: /v1/goals answers\n // 400 session_not_found without it, and the durable queue classifies a 4xx\n // as terminal — so a session upsert that fails silently turns every later\n // conversion into a permanent drop. That is not hypothetical: /v1/sessions\n // carries the same per-IP limiter as /v1/goals, so under shared egress\n // (offices, mobile carriers, corporate NAT) the SESSION call 429s first and\n // the goals that follow are dropped for good. Retry it, so a transient\n // failure costs a moment rather than the visit's whole conversion history.\n const upsertSession = async (): Promise<undefined> => {\n for (let attempt = 0; ; attempt++) {\n try {\n const res = await fetch(`${baseUrl}/sessions`, {\n method: 'POST',\n keepalive: true,\n body: JSON.stringify(sessionBody),\n headers: authHeaders,\n });\n if (res.status === 402) {\n console.warn(\n '[SentientUI] Session limit exceeded for this project. The bandit will stop learning until the limit resets. Upgrade at sentient-ui.com/pricing',\n );\n return undefined; // terminal: retrying a quota will not clear it\n }\n if (res.ok || classifyResponse(res) === 'dropped') return undefined;\n } catch {\n /* network failure — same retry path as a 5xx */\n }\n if (attempt >= SESSION_UPSERT_RETRIES) {\n // Say so once: from here every conversion this visit will 400, and\n // that used to be entirely silent.\n console.warn(\n '[SentientUI] Could not register the session after retries. Conversions in this visit may not be recorded.',\n );\n return undefined;\n }\n await new Promise((r) => setTimeout(r, backoffDelayMs(attempt + 1)));\n }\n };\n try {\n sessionReady = upsertSession();\n } catch {\n /* never throw on init */\n }\n }\n\n if (config.debug) {\n console.log('[sentient] initialized', { context: config.context });\n (\n window as unknown as {\n __sentient?: {\n client: SentientClient;\n queue: EventQueue;\n };\n }\n ).__sentient = {\n client: null as unknown as SentientClient,\n queue: eventQueue,\n };\n }\n\n // One user action must record ONE session-level conversion per goal name.\n // Nested components each fire their declared goal on the same click (every\n // <Adaptive>/hook path calls componentGoal() AND goal()), so a hero nested\n // inside a CTA wrapper wrote two goal_events rows for one click: harmless for\n // a weight-1.0 goal (close-out clamps at 1) but a 0.3-weight step summed to\n // 0.6, and the Goals page counts Hits as COUNT(*) either way.\n //\n // The scope is one event dispatch, not one session and no longer one task:\n // see createActionLatch. A session-wide latch would swallow genuine repeat\n // conversions (two purchases in one visit are two conversions), and a\n // time-boxed one did exactly that whenever the box outlived the action.\n // Calls carrying distinct externalIds are never collapsed — those are, by\n // definition, distinct orders.\n const firedThisAction = createActionLatch();\n\n // Set once tracking starts; dispose() and destroy() call it so a replaced\n // client stops watching history instead of emitting forever. The flag records\n // teardown for the delivery-marking below, which runs on a later microtask.\n let stopPageviews: (() => void) | null = null;\n let pageviewsTornDown = false;\n\n const client: SentientClient = {\n goal(name: string, metadataOrOpts: Record<string, unknown> = {}, weight = 1.0, stepIndex = 0) {\n const sid = session.getSessionId();\n if (!sid) return;\n const opts: GoalOptions = isGoalOptions(metadataOrOpts)\n ? (metadataOrOpts as GoalOptions)\n : { metadata: metadataOrOpts };\n // stepIndex and weight are part of the key: funnel steps share a goal\n // name and differ by stepIndex, so collapsing on name alone dropped a\n // step fired in the same handler. Only IDENTICAL calls are one action.\n //\n // value and currency key the payload SEPARATELY (the latch's valueKey),\n // not as more segments of the flat key, and for a costlier reason: they\n // are the money. Flattened out of the key entirely, a $50 order and a\n // $70 order landing in one window collapsed into a single $50 record —\n // the client half of CONTRACTS §1 \"two orders are worth two orders\",\n // which the server already honours (migration 119 records the repeat if\n // it arrives; this is what stopped it arriving). But flattened INTO the\n // key, a valued inner component nested in a valueless wrapper made two\n // keys out of one click — two rows for one order. So the latch compares\n // values only between valued fires ($50 vs $70 stays two records) and\n // lets a valued record absorb a valueless re-fire of the same action\n // (see createActionLatch for the one asymmetric case).\n //\n // NOT metadata: every nested <Adaptive>/hook path stamps its own\n // componentId and variantId in there, so keying on it would make the\n // duplicate this latch exists to collapse look distinct again.\n const actionKey = [\n name,\n opts.externalId ?? '',\n opts.stepIndex ?? stepIndex,\n opts.weight ?? weight,\n ].join('\\0');\n const valueKey = opts.value !== undefined ? `${opts.value}\\0${opts.currency ?? ''}` : null;\n if (firedThisAction.firedBefore(actionKey, valueKey)) {\n if (config.debug) {\n console.log(`[sentient] goal(\"${name}\") already recorded for this action — not sent twice`);\n }\n return;\n }\n const goalId = generateEventId();\n // undefined values vanish at JSON.stringify time, so optional fields\n // need no conditional assembly.\n const body = {\n sessionId: sid,\n name,\n metadata: opts.metadata ?? {},\n weight: opts.weight ?? weight,\n stepIndex: opts.stepIndex ?? stepIndex,\n goalId,\n value: opts.value,\n currency: opts.currency,\n externalId: opts.externalId,\n };\n if (config.debug) {\n console.log('[sentient] goal', body);\n }\n // Serialize once, here: the queued copy must replay byte-identically\n // (same goalId) so a retry dedupes server-side instead of double-counting.\n const payload = { id: goalId, body: JSON.stringify(body) };\n sessionReady.then(() => goalQueue.send(payload));\n },\n\n componentGoal(componentId, goalType, opts) {\n const sid = session.getSessionId();\n if (!sid) return;\n // Variant experiments resolve from the assignment cache; adaptive slots\n // (useAdaptiveTokens / AdaptiveGroup) resolve from the slot state, using\n // the canonical arm string as the attributed variantId.\n const assignment = assignmentCache.get(componentId, sessionSegment);\n const slotResult = assignment ? null : slotStore.get(componentId) ?? null;\n if (!assignment && slotResult === null) {\n if (config.debug) {\n console.warn(\n `[sentient] componentGoal(\"${componentId}\"): no assignment or slot decision yet — render its <Adaptive>/adaptive hook or call assign()/decide() before recording a goal.`,\n );\n }\n return;\n }\n const attributedVariantId = assignment ? assignment.variantId : armOfResult(slotResult!);\n const fullEvent: SentientEvent = {\n id: generateEventId(),\n sessionId: sid,\n projectId: config.apiKey,\n componentId,\n variantId: attributedVariantId,\n eventType: 'goal_achieved',\n goalType,\n // undefined goalValue/currency vanish at JSON.stringify time.\n payload: {\n reward: opts?.reward ?? 1,\n goalValue: opts?.value,\n currency: opts?.currency,\n ...(opts?.metadata ?? {}),\n },\n timestamp: Date.now(),\n timeInSession: Date.now() - sessionStart,\n path: currentPath(),\n };\n if (config.debug) {\n console.log('[sentient] componentGoal', fullEvent);\n }\n sessionReady.then(() => eventQueue.push(fullEvent));\n },\n\n identify(userId) {\n const sid = session.getSessionId();\n if (!sid) return;\n sessionReady.then(() => {\n fetch(`${baseUrl}/sessions`, {\n method: 'POST',\n keepalive: true,\n body: JSON.stringify({ sessionId: sid, userId, ephemeral: session.isEphemeral() }),\n headers: authHeaders,\n }).catch(() => undefined);\n });\n },\n\n track(event) {\n const sessionId = session.getSessionId();\n if (!sessionId) return;\n\n const fullEvent: SentientEvent = {\n // `path` first so an explicit event.path from the caller wins over the\n // ambient one — a server-side or replayed event knows its page better\n // than location does.\n path: currentPath(),\n ...event,\n id: generateEventId(),\n sessionId,\n timestamp: Date.now(),\n timeInSession: Date.now() - sessionStart,\n };\n\n if (config.debug) {\n console.log('[sentient] track', fullEvent);\n }\n\n sessionReady.then(() => eventQueue.push(fullEvent));\n },\n\n getAssignment(componentId, segment) {\n return assignmentCache.get(componentId, segment);\n },\n\n async assign(componentId, variantIds, agentData?, agentDataByVariant?) {\n const sid = session.getSessionId();\n if (!sid) return null;\n\n const cached = assignmentCache.get(componentId, sessionSegment);\n // When variantIds are provided (A/B code variant), a cache hit is always final.\n // When variantIds are absent (managed text component), only hit the cache if content\n // is present — a seed from initialAssignments has no content and must still fetch.\n if (cached && (variantIds?.length || cached.content !== undefined)) {\n // Surface the entry's remaining TTL (server-provided when set) instead of\n // a hardcoded 0, so callers can reason about when a re-assign is due.\n const remainingTtlMs =\n cached.ttlMs && cached.ttlMs > 0\n ? Math.max(0, cached.assignedAt + cached.ttlMs - Date.now())\n : 0;\n return { variantId: cached.variantId, assignmentTtlMs: remainingTtlMs, content: cached.content };\n }\n\n // Coalesce concurrent assigns for the same component (e.g. several\n // mounted slots sharing one id) into a single network request.\n return coalesce(inflightAssigns, componentId, async () => {\n await sessionReady;\n try {\n const body: Record<string, unknown> = { sessionId: sid, componentId, variantIds };\n if (agentDataByVariant !== undefined) body.agentDataByVariant = agentDataByVariant;\n else if (agentData !== undefined) body.agentData = agentData;\n const res = await fetch(`${baseUrl}/assign`, {\n method: 'POST',\n body: JSON.stringify(body),\n headers: authHeaders,\n });\n if (!res.ok) return null;\n const result = (await res.json()) as AssignResult;\n assignmentCache.set(componentId, sessionSegment, {\n variantId: result.variantId,\n assignedAt: Date.now(),\n segment: sessionSegment,\n confidence: 1,\n content: result.content,\n // Honor the server's TTL as this entry's expiry; omit when absent/0\n // so the cache falls back to its default (DEFAULT_TTL_MS).\n ...(result.assignmentTtlMs && result.assignmentTtlMs > 0\n ? { ttlMs: result.assignmentTtlMs }\n : {}),\n });\n return result;\n } catch {\n return null;\n }\n });\n },\n\n async decide(input) {\n const sid = session.getSessionId();\n if (!sid) return null;\n const declared = input.slots ?? [];\n\n const body: Record<string, unknown> = { sessionId: sid };\n if (input.sections && input.sections.length > 0) {\n body.sections = input.sections.map((id) => ({ id }));\n }\n body.components = input.components ?? [];\n if (declared.length > 0) body.slots = declared.map(toWireSlot);\n if (input.slotsFrom === 'registry') body.slotsFrom = 'registry';\n if (input.v) body.v = input.v;\n // Declared persona rides on decide too: SSR-first flows can race the\n // session upsert, and the decide-body value wins for this decision.\n if (config.persona) body.persona = config.persona;\n\n // Coalesce concurrent IDENTICAL decides into one request + one snapshot\n // write, keyed by the serialized wire payload (also reused as the fetch\n // body). Never key on just \"a decide is running\": coalescing {slots:[a]}\n // with {slots:[b]} would hand slot b's caller an outcome that never\n // decided b. The wire projection is a safe key even though toWireSlot\n // strips SDK-only decl fields — the baselines synthesized for omitted\n // slots below go through baselineResultFor, which projects with the\n // same toWireSlot, so identical payloads imply identical outcomes.\n const decideKey = JSON.stringify(body);\n return coalesce(inflightDecides, decideKey, async () => {\n await sessionReady;\n try {\n const res = await fetch(`${baseUrl}/decide`, {\n method: 'POST',\n body: decideKey,\n headers: authHeaders,\n });\n if (!res.ok) {\n seedSlotBaselines(declared);\n return null;\n }\n const data = (await res.json()) as {\n layoutOrder?: string[] | null;\n assignments?: Record<string, string>;\n slots?: Record<string, SlotResult>;\n slotConfig?: Record<string, SlotConfigEntry>;\n goals?: GoalDefinition[];\n sectionMap?: SectionMapEntry[];\n palette?: import('./blocks.js').SitePalette;\n persona?: string;\n confidence?: number;\n };\n\n const slots: Record<string, SlotResult> = {};\n for (const d of declared) {\n // `data.slots === undefined` means the server predates the slots\n // contract: serve the declared baseline everywhere, do NOT retry.\n // (Distinct from `slots: {}`, which also falls back per-slot.)\n const served = data.slots?.[d.id];\n if (served !== undefined) {\n slots[d.id] = served;\n slotStore.set(d.id, served);\n continue;\n }\n // Slot omitted from the response → synthesize a baseline for the\n // RETURN value, but apply the same never-overwrite rule the failure\n // path (seedSlotBaselines) has always had. This success path used\n // to write unconditionally, so a partial response — or a pre-slots\n // server — clobbered SSR-seeded and previously-served results with\n // synthetic baselines.\n const prior = slotStore.get(d.id);\n if (prior !== undefined) {\n slots[d.id] = prior;\n } else {\n const baseline = baselineResultFor(d);\n slots[d.id] = baseline;\n slotStore.set(d.id, baseline);\n }\n }\n // Registry mode: the server returns slots the request never declared.\n // Take them verbatim (classic mode returns only declared slots, so this\n // union is a no-op there — back-compatible). These are real served\n // results, so they may overwrite the store, unlike the baselines above.\n if (data.slots) {\n for (const [slotId, result] of Object.entries(data.slots)) {\n if (!(slotId in slots)) {\n slots[slotId] = result;\n slotStore.set(slotId, result);\n }\n }\n }\n // Only overwrite persona when the response actually carries one, and\n // never downgrade a known persona to 'unknown' — a decide that omits\n // persona (or returns 'unknown') must not clobber a good SSR/snapshot/\n // initialPersona value, and must not persist that regression below.\n const known = personaState != null && personaState.persona !== 'unknown';\n if (data.persona && !(data.persona === 'unknown' && known)) {\n personaState = { persona: data.persona, confidence: data.confidence ?? 0 };\n } else if (!personaState) {\n personaState = { persona: 'unknown', confidence: 0 };\n }\n\n // Seed component assignments so <Adaptive>/assign() agree with this\n // decide (same shape as the initialAssignments seed above).\n for (const [componentId, variantId] of Object.entries(data.assignments ?? {})) {\n assignmentCache.set(componentId, sessionSegment, {\n variantId,\n assignedAt: Date.now(),\n segment: sessionSegment,\n confidence: 1,\n });\n }\n\n // Persist for the next visit's pre-paint (SPA cache-first pattern).\n writeSnapshot(config.apiKey, {\n v: 1,\n persona: personaState.persona,\n band: confidenceBand(personaState.confidence),\n slots: Object.fromEntries(slotStore),\n layoutOrder: data.layoutOrder ?? null,\n savedAt: Date.now(),\n ...(data.slotConfig ? { slotConfig: data.slotConfig } : {}),\n ...(data.palette ? { palette: data.palette } : {}),\n });\n\n return {\n layoutOrder: data.layoutOrder ?? null,\n assignments: data.assignments ?? {},\n slots,\n persona: personaState.persona,\n confidence: personaState.confidence,\n ...(data.slotConfig ? { slotConfig: data.slotConfig } : {}),\n ...(data.goals ? { goals: data.goals } : {}),\n ...(data.sectionMap ? { sectionMap: data.sectionMap } : {}),\n ...(data.palette ? { palette: data.palette } : {}),\n };\n } catch {\n seedSlotBaselines(declared);\n return null;\n }\n });\n },\n\n getSlotResult(slotId) {\n return slotStore.get(slotId) ?? null;\n },\n\n getPersona() {\n if (!personaState) return null;\n return {\n persona: personaState.persona,\n confidence: personaState.confidence,\n band: confidenceBand(personaState.confidence),\n };\n },\n\n async fetchWeights() {\n try {\n const res = await fetch(`${baseUrl}/weights`, { headers: authHeaders });\n if (!res.ok) return [];\n const data = (await res.json()) as { components: ComponentWeightEntry[] };\n return data.components ?? [];\n } catch {\n return [];\n }\n },\n\n getGraph() {\n return { pageNodes: [], capturedAt: 0 };\n },\n\n dispose() {\n // Stops the flush timer and unload listeners (with a final flush) but\n // leaves identity, snapshot, and retry buckets for the next client.\n stopPageviews?.();\n pageviewsTornDown = true;\n eventQueue.destroy();\n goalQueue.destroy();\n // Drop the registry entry so a later re-init doesn't try to dispose an\n // already-torn-down client (and so the map doesn't pin this closure).\n if (_clients.get(config.apiKey)?.dispose === client.dispose) {\n _clients.delete(config.apiKey);\n }\n if (config.debug) {\n console.log('[sentient] disposed');\n }\n },\n\n destroy() {\n stopPageviews?.();\n pageviewsTornDown = true;\n eventQueue.destroy();\n goalQueue.destroy();\n session.destroy();\n // The assignment cache persists in localStorage (`_snt_asgn_*`) with a\n // 30-minute default TTL — left in place, a revoked visitor returning\n // within that window was handed their previous personalized variants\n // back, so forget-me wasn't total.\n assignmentCache.clear();\n if (_clients.get(config.apiKey)?.dispose === client.dispose) {\n _clients.delete(config.apiKey);\n }\n // Forget-me must be total: a surviving decision snapshot would\n // re-personalize the next visit via the pre-paint script, and a\n // persisted retry bucket would re-send events for the deleted identity.\n try {\n localStorage.removeItem(SNAPSHOT_STORAGE_KEY_PREFIX + config.apiKey);\n localStorage.removeItem(retryStorageKey(config.apiKey));\n localStorage.removeItem(goalRetryStorageKey(config.apiKey));\n } catch {\n /* storage unavailable — nothing persisted to remove */\n }\n if (config.debug) {\n console.log('[sentient] destroyed');\n }\n },\n };\n\n _clients.set(config.apiKey, { config, upgrade: null, dispose: client.dispose });\n\n stopPageviews = startPageviewTracking(client, config.apiKey, (key) => {\n // track() defers its enqueue on sessionReady; chaining after it means this\n // runs once the push has happened. If the client was torn down first, the\n // event went into a destroyed queue and never ships — leave the page\n // unmarked so the replacement client's emit is the one that counts.\n void sessionReady.then(() => {\n if (!pageviewsTornDown) emittedPages.add(key);\n });\n });\n\n if (config.debug) {\n const win = window as unknown as { __sentient?: { client: SentientClient } };\n if (win.__sentient) {\n win.__sentient.client = client;\n }\n }\n\n return client;\n}\n","/**\n * Keyless local mode — client factory.\n *\n * This module ships in the MAIN core bundle and contains no engine code: the\n * engine arrives through a dynamic import of the bare specifier\n * `@sentientui/core/local`, which the consumer's bundler resolves through the\n * development/production export conditions. In production builds that\n * specifier is the stub, and this client degrades to a no-op plus one\n * console.error per page load.\n */\nimport { initSession } from './session.js';\nimport { readSnapshot, writeSnapshot } from './snapshot.js';\nimport { confidenceBand } from '@sentientui/policy';\nimport type {\n DecideOutcome,\n SentientClient,\n SentientConfig,\n SlotDeclInput,\n} from './index.js';\n\ntype LocalEngineModule = {\n LOCAL_ENGINE_AVAILABLE: boolean;\n createLocalEngine(opts: { sessionId: string; forcedPersona?: string }): {\n decide(input: {\n sections?: string[];\n components?: Array<{ id: string; variantIds?: string[] }>;\n slots?: SlotDeclInput[];\n }): DecideOutcome;\n };\n};\n\nexport const PROD_KEYLESS_ERROR =\n '[sentient] No API key configured — nothing is being learned. Set NEXT_PUBLIC_SENTIENT_API_KEY or pass localMode: true for local development.';\n\nexport const LOCAL_MODE_BANNER =\n '[sentient] Local mode — decisions are simulated on-device and nothing is sent over the network. Add an API key to learn from real traffic.';\n\n// Once-per-page-load guards (module state resets on reload).\nlet bannerShown = false;\nlet prodErrorShown = false;\n\n/** @internal test hook */\nexport function __resetLocalModeLogGuards(): void {\n bannerShown = false;\n prodErrorShown = false;\n}\n\n/** Mirrors the ?sentient_variant= override pattern; validated by the engine. */\nfunction readPersonaOverrideFromUrl(): string | undefined {\n try {\n return new URLSearchParams(window.location.search).get('sentient_persona') ?? undefined;\n } catch {\n return undefined;\n }\n}\n\nexport function createLocalModeClient(config: SentientConfig): SentientClient {\n const session = initSession({ ssrSessionId: config.ssrSessionId, apiKey: config.apiKey });\n const sessionId = session.getSessionId() ?? 'local';\n const forcedPersona = readPersonaOverrideFromUrl();\n\n // The specifier MUST stay a bare package subpath (never a relative path) so\n // the consumer's bundler applies the development/production export\n // conditions. tsup keeps it external (see tsup.config.ts).\n const modPromise: Promise<LocalEngineModule | null> = import('@sentientui/core/local')\n .then((mod) => {\n const m = mod as unknown as LocalEngineModule;\n if (!m.LOCAL_ENGINE_AVAILABLE) {\n if (!prodErrorShown) {\n prodErrorShown = true;\n console.error(PROD_KEYLESS_ERROR);\n }\n return null;\n }\n if (!bannerShown) {\n bannerShown = true;\n console.info(LOCAL_MODE_BANNER);\n }\n return m;\n })\n .catch(() => {\n if (!prodErrorShown) {\n prodErrorShown = true;\n console.error(PROD_KEYLESS_ERROR);\n }\n return null;\n });\n\n let lastOutcome: DecideOutcome | null = null;\n\n // Pre-first-decide persona seed. The hosted client serves config.initialPersona\n // (SSR) and then the persisted snapshot before its first decide; local mode\n // returned null until the first decide resolved, so a locally-developed page\n // rendered its default persona on first paint and diverged from what the\n // same code shows against production. Band-only snapshot sources map to the\n // same band-consistent confidences the hosted client uses, so\n // confidenceBand(confidence) always round-trips to the stored band.\n const BAND_CONFIDENCE: Record<string, number> = { low: 0.15, medium: 0.5, high: 0.85 };\n const seedPersona = ((): { persona: string; confidence: number } | null => {\n if (config.initialPersona) return { ...config.initialPersona };\n const snap = readSnapshot(config.apiKey || 'local');\n if (snap) return { persona: snap.persona, confidence: BAND_CONFIDENCE[snap.band] ?? 0.15 };\n return null;\n })();\n\n function applyPersonaAttributes(outcome: DecideOutcome): void {\n // Single-writer rule: adopt attributes already written (e.g. by the\n // AdaptiveRoot inline script); only write when nothing has yet.\n const el = document.documentElement;\n if (el.dataset.sentientPersona === undefined) {\n el.dataset.sentientPersona = outcome.persona;\n el.dataset.sentientConfidence = confidenceBand(outcome.confidence);\n }\n }\n\n return {\n isLocal: true,\n\n async decide(input) {\n const mod = await modPromise;\n if (!mod) return null;\n const outcome = mod.createLocalEngine({ sessionId, forcedPersona }).decide(input);\n // Accumulate across calls: slots decide lazily one at a time (per-slot\n // decide from useSlotResult), so a later decide must not evict results\n // an earlier one served. Same (sessionId, persona) → merging is safe.\n lastOutcome = {\n ...outcome,\n layoutOrder: outcome.layoutOrder ?? lastOutcome?.layoutOrder ?? null,\n slots: { ...(lastOutcome?.slots ?? {}), ...outcome.slots },\n };\n writeSnapshot(config.apiKey || 'local', {\n v: 1,\n persona: lastOutcome.persona,\n band: confidenceBand(lastOutcome.confidence),\n slots: lastOutcome.slots,\n layoutOrder: lastOutcome.layoutOrder,\n savedAt: Date.now(),\n });\n applyPersonaAttributes(outcome);\n return outcome;\n },\n\n getSlotResult(slotId) {\n return lastOutcome?.slots[slotId] ?? config.initialSlots?.[slotId] ?? null;\n },\n\n getPersona() {\n const p = lastOutcome ?? seedPersona;\n if (!p) return null;\n return {\n persona: p.persona,\n confidence: p.confidence,\n band: confidenceBand(p.confidence),\n };\n },\n\n async assign(componentId, variantIds) {\n const mod = await modPromise;\n if (!mod || !variantIds || variantIds.length === 0) {\n return variantIds?.[0] ? { variantId: variantIds[0], assignmentTtlMs: 0 } : null;\n }\n const outcome = mod\n .createLocalEngine({ sessionId, forcedPersona })\n .decide({ components: [{ id: componentId, variantIds }] });\n return { variantId: outcome.assignments[componentId] ?? variantIds[0], assignmentTtlMs: 0 };\n },\n\n // Local mode never talks to the network: the tracking surface no-ops.\n track: () => undefined,\n goal: () => undefined,\n componentGoal: () => undefined,\n identify: () => undefined,\n getAssignment: () => null,\n fetchWeights: () => Promise.resolve([]),\n getGraph: () => ({ pageNodes: [], capturedAt: 0 }),\n dispose: () => undefined, // no timers/network in local mode; keep the session\n destroy: () => session.destroy(),\n };\n}\n","/**\n * Composition Blocks (spec: 2026-08-20-nocode-composition-variants-design.md §4).\n *\n * A bounded, TYPED component tree — never HTML — that a registry arm may carry\n * (`published_config.arms[].blocks`). The vocabulary is the whitelist: every\n * prop value is an enumerated token, validated server-side before publish\n * (apps/api/src/domain/composition-blocks.ts) and rendered client-side through\n * document.createElement + property assignment only. No innerHTML/outerHTML/\n * insertAdjacentHTML exists anywhere on this path — the security property is\n * preserved by never accepting HTML, not by sanitizing it, which is why there\n * is no sanitizer to keep honest.\n *\n * Token lists live here (not in the API domain like SlotOps' mirrors) because\n * three parties must agree byte-for-byte: the server validator, the snippet\n * renderer, and eventually the React renderer (§11) — a drifted copy would let\n * a published arm fail to render, which the fail-safe turns into an invisibly\n * missing section, not an error.\n */\n\nexport const BLOCK_GAPS = ['none', 'sm', 'md', 'lg'] as const;\nexport const BLOCK_ALIGNS = ['start', 'center', 'end', 'stretch'] as const;\nexport const BLOCK_JUSTIFIES = ['start', 'center', 'end', 'between'] as const;\nexport const BLOCK_SIZES = ['sm', 'md', 'lg'] as const;\nexport const BLOCK_WEIGHTS = ['normal', 'medium', 'bold'] as const;\nexport const BLOCK_TONES = ['default', 'muted', 'accent'] as const;\nexport const BLOCK_EMPHASES = ['primary', 'secondary', 'ghost'] as const;\nexport const BLOCK_TEXT_ALIGNS = ['left', 'center', 'right'] as const;\nexport const BLOCK_RATIOS = ['auto', 'square', 'landscape', 'wide'] as const;\nexport const BLOCK_FITS = ['cover', 'contain'] as const;\nexport const BLOCK_GRID_COLUMNS = [2, 3, 4] as const;\nexport const BLOCK_HEADING_LEVELS = [2, 3, 4] as const;\n\nexport type BlockGap = (typeof BLOCK_GAPS)[number];\nexport type BlockAlign = (typeof BLOCK_ALIGNS)[number];\nexport type BlockJustify = (typeof BLOCK_JUSTIFIES)[number];\nexport type BlockSize = (typeof BLOCK_SIZES)[number];\nexport type BlockWeight = (typeof BLOCK_WEIGHTS)[number];\nexport type BlockTone = (typeof BLOCK_TONES)[number];\nexport type BlockEmphasis = (typeof BLOCK_EMPHASES)[number];\nexport type BlockTextAlign = (typeof BLOCK_TEXT_ALIGNS)[number];\nexport type BlockRatio = (typeof BLOCK_RATIOS)[number];\nexport type BlockFit = (typeof BLOCK_FITS)[number];\n\n/** Flex row/column container. */\nexport type StackBlock = {\n type: 'stack';\n direction: 'row' | 'column';\n children: BlockNode[];\n gap?: BlockGap;\n align?: BlockAlign;\n justify?: BlockJustify;\n wrap?: boolean;\n};\n\n/** 2–4 equal-column grid container. */\nexport type GridBlock = {\n type: 'grid';\n columns: (typeof BLOCK_GRID_COLUMNS)[number];\n children: BlockNode[];\n gap?: BlockGap;\n align?: BlockAlign;\n};\n\n/** Paragraph / label. */\nexport type TextBlock = {\n type: 'text';\n value: string;\n size?: BlockSize;\n weight?: BlockWeight;\n tone?: BlockTone;\n align?: BlockTextAlign;\n};\n\n/** h2–h4 — never h1 (the page owns its h1). */\nexport type HeadingBlock = {\n type: 'heading';\n value: string;\n level: (typeof BLOCK_HEADING_LEVELS)[number];\n size?: BlockSize;\n align?: BlockTextAlign;\n};\n\n/** Link styled as a button. `tag` feeds agent legibility (agentDataByVariant). */\nexport type ButtonBlock = {\n type: 'button';\n label: string;\n href: string;\n emphasis?: BlockEmphasis;\n size?: BlockSize;\n tag?: string;\n};\n\n/** Inline text link. */\nexport type LinkBlock = {\n type: 'link';\n label: string;\n href: string;\n tag?: string;\n};\n\n/** Image. `alt` is required; empty only with an explicit `decorative: true`. */\nexport type ImageBlock = {\n type: 'image';\n src: string;\n alt: string;\n decorative?: boolean;\n ratio?: BlockRatio;\n fit?: BlockFit;\n};\n\n/** Eyebrow / pill. */\nexport type BadgeBlock = {\n type: 'badge';\n value: string;\n tone?: BlockTone;\n};\n\n/** Vertical rhythm. */\nexport type SpacerBlock = {\n type: 'spacer';\n size: BlockSize;\n};\n\nexport type BlockNode =\n | StackBlock\n | GridBlock\n | TextBlock\n | HeadingBlock\n | ButtonBlock\n | LinkBlock\n | ImageBlock\n | BadgeBlock\n | SpacerBlock;\n\n/** The derived site palette (spec §4 \"Colour and type: derived, not chosen\").\n * Sampled by the on-site editor from the live page's own buttons — computed\n * styles, so values are plain colors (rgb/hex), never var()/url() — validated\n * server-side, stored per project, and served with the decision so injected\n * blocks render in the merchant's own primary color and corner radius.\n * Absent → the renderer's neutral inherit-first defaults. */\nexport type SitePalette = {\n primaryBg: string;\n primaryText: string;\n radius: string;\n};\n\n// Structural caps. Total-nodes and depth bound the render cost of one arm;\n// the arms cap bounds Option B's DOM weight (every arm pre-renders hidden, so\n// DOM cost is arms × nodes — spec §6 proposed 4 and nothing has argued it up).\nexport const MAX_BLOCK_NODES = 64;\nexport const MAX_BLOCK_DEPTH = 5;\nexport const MAX_BLOCK_CHILDREN = 12;\nexport const MAX_BLOCK_ARMS = 4;\nexport const MAX_BLOCK_TEXT_LEN = 500;\n","export type MicroSignalEmitter = (\n signalType: 'rage_click' | 'text_copy' | 'scroll_hesitation' | 'tab_loss',\n extra?: Record<string, unknown>,\n) => void;\n\nexport type MicroSignalType = Parameters<MicroSignalEmitter>[0];\n\n/**\n * Attaches passive behavioral detectors to `node`. Calls `emit` when a signal\n * fires. Each signal type fires at most once per call to this function.\n * Returns a cleanup function that removes all listeners.\n */\nexport function attachMicroSignalDetectors(\n emit: MicroSignalEmitter,\n node: Element,\n variantAssignedAt?: number,\n options?: { tabLoss?: boolean },\n): () => void {\n const cleanups: Array<() => void> = [];\n\n // --- Rage click: 3+ clicks within 500ms ---\n {\n const WINDOW_MS = 500;\n const THRESHOLD = 3;\n let firedOnce = false;\n const timestamps: number[] = [];\n\n const onClick = (): void => {\n if (firedOnce) return;\n const now = Date.now();\n timestamps.push(now);\n while (timestamps.length > 0 && now - timestamps[0]! > WINDOW_MS) {\n timestamps.shift();\n }\n if (timestamps.length >= THRESHOLD) {\n firedOnce = true;\n emit('rage_click');\n }\n };\n\n node.addEventListener('click', onClick);\n cleanups.push(() => node.removeEventListener('click', onClick));\n }\n\n // --- Text copy: copy event within node ---\n {\n let firedOnce = false;\n\n const onCopy = (e: Event): void => {\n if (firedOnce) return;\n if (!(e.target instanceof Node)) return;\n if (!node.contains(e.target) && node !== e.target) return;\n firedOnce = true;\n const sel = typeof window !== 'undefined' ? window.getSelection() : null;\n const selectionLength = sel ? sel.toString().length : 0;\n emit('text_copy', { selectionLength });\n };\n\n document.addEventListener('copy', onCopy);\n cleanups.push(() => document.removeEventListener('copy', onCopy));\n }\n\n // --- Scroll hesitation: scroll stops 3s while component visible ---\n {\n let firedOnce = false;\n let isVisible = false;\n let hesitationTimer: ReturnType<typeof setTimeout> | null = null;\n\n const clearHesitation = (): void => {\n if (hesitationTimer !== null) {\n clearTimeout(hesitationTimer);\n hesitationTimer = null;\n }\n };\n\n const startHesitation = (): void => {\n if (firedOnce || !isVisible) return;\n clearHesitation();\n hesitationTimer = setTimeout(() => {\n if (!firedOnce && isVisible) {\n firedOnce = true;\n emit('scroll_hesitation');\n }\n }, 3000);\n };\n\n const onScroll = (): void => {\n clearHesitation();\n startHesitation();\n };\n\n const ioCallback = (entries: IntersectionObserverEntry[]): void => {\n for (const entry of entries) {\n isVisible = entry.intersectionRatio > 0.3;\n if (!isVisible) clearHesitation();\n else startHesitation();\n }\n };\n const io = new IntersectionObserver(ioCallback, { threshold: [0.3] });\n io.observe(node);\n window.addEventListener('scroll', onScroll, { passive: true });\n\n cleanups.push(() => {\n io.disconnect();\n window.removeEventListener('scroll', onScroll);\n clearHesitation();\n });\n }\n\n // --- Tab loss: tab hidden within 15s of variant_assigned ---\n // Document-level (not node-scoped), so callers that attach detectors to many\n // nodes at once (e.g. the snippet's per-option slot signals) can opt out on all\n // but one node to avoid emitting a duplicate tab_loss per node (audit M5).\n if (options?.tabLoss !== false) {\n let firedOnce = false;\n const assignedAt = variantAssignedAt ?? Date.now();\n\n const onVisibility = (): void => {\n if (firedOnce) return;\n if (document.visibilityState !== 'hidden') return;\n const elapsed = Date.now() - assignedAt;\n if (elapsed < 15_000) {\n firedOnce = true;\n emit('tab_loss', { timeOnPage: elapsed });\n }\n };\n\n document.addEventListener('visibilitychange', onVisibility);\n cleanups.push(() => document.removeEventListener('visibilitychange', onVisibility));\n }\n\n return () => {\n for (const c of cleanups) c();\n };\n}\n"],"mappings":"mKAiBO,SAASA,IAAuB,CACrC,GAAI,CACF,GAAI,OAAO,QAAW,aAAe,OAAO,OAAO,YAAe,WAChE,OAAO,OAAO,WAAW,CAE7B,OAAQ,GAER,CACA,GAAI,CACF,GAAI,OAAO,QAAW,aAAe,OAAO,OAAO,iBAAoB,WAAY,CACjF,IAAMC,EAAM,IAAI,WAAW,EAAE,EAC7B,OAAO,gBAAgBA,CAAG,E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,EAAO,MAAM,IAA1B,YAAA9C,EAA6B,WAAYqB,EAAO,SAClDjC,EAAS,OAAO0D,EAAO,MAAM,EAK/B,GAAI,CACF,aAAa,WAAWoI,GAA8BpI,EAAO,MAAM,EACnE,aAAa,WAAWqI,GAAgBrI,EAAO,MAAM,CAAC,EACtD,aAAa,WAAWsI,GAAoBtI,EAAO,MAAM,CAAC,CAC5D,OAAQsB,EAAA,CAER,CACItB,EAAO,OACT,QAAQ,IAAI,sBAAsB,CAEtC,CACF,EAcA,GAZA1D,EAAS,IAAI0D,EAAO,OAAQ,CAAE,OAAAA,EAAQ,QAAS,KAAM,QAASzB,EAAO,OAAQ,CAAC,EAE9E0H,EAAgB3H,GAAsBC,EAAQyB,EAAO,OAASD,GAAQ,CAK/DsF,EAAa,KAAK,IAAM,CACtBa,IAAmB7H,GAAa,IAAI0B,CAAG,CAC9C,CAAC,CACH,CAAC,EAEGC,EAAO,MAAO,CAChB,IAAMuI,EAAM,OACRA,EAAI,aACNA,EAAI,WAAW,OAAShK,EAE5B,CAEA,OAAOA,CACT","names":["randomUuidV4","buf","out","i","c","r","DEFAULT_COOKIE_NAME","DEFAULT_COOKIE_TTL_DAYS","STORAGE_KEY","generateSessionId","randomUuidV4","readCookie","name","match","e","writeCookie","value","maxAgeSeconds","readLocalStorage","key","writeLocalStorage","readSessionStorage","writeSessionStorage","removeSessionStorage","probeCookieWritable","removeLocalStorage","clearCookie","SSR_MANAGER","initSession","config","_a","_b","_c","_d","_e","_f","_g","suffix","storageSuffix","cookieName","sessionCookieName","storageKey","legacyTombstoneKey","nonEmpty","readLegacy","sessionId","lsOk","cookieOk","ssOk","ephemeral","backoffDelayMs","consecutiveFailures","classifyResponse","res","status","drainBucket","storageKey","max","raw","parsed","e","writeBucket","items","existing","byId","purgeBucket","ids","drop","remaining","MAX_SENT_IDS","KEEPALIVE_BUDGET_BYTES","retryStorageKey","apiKey","SSR_QUEUE","createEventQueue","config","_a","_b","_c","flushIntervalMs","maxBatchSize","maxRetrySize","ingestUrl","RETRY_KEY","queue","sentIds","sentIdOrder","markSent","ids","id","queuedIds","oldest","purgeBucket","capQueue","dropped","enqueue","event","requeueFailed","batch","retryEvents","drainBucket","backoffUntil","consecutiveFailures","transportBatch","salvage","body","e","pending","writeBucket","backoffDelayMs","handleResponse","res","classifyResponse","rest","encoder","byteLength","s","packBatch","pool","out","bytes","size","flush","flushTimerActive","intervalId","onVisibilityChange","onPageHide","MAX_SENT_IDS","goalRetryStorageKey","apiKey","SSR_GOAL_QUEUE","createGoalQueue","config","_a","_b","_c","flushIntervalMs","maxRetrySize","maxPerFlush","RETRY_KEY","pending","pendingIds","sentIds","sentIdOrder","backoffUntil","consecutiveFailures","disposed","markSent","goal","oldest","purgeBucket","markFailed","writeBucket","backoffDelayMs","transport","res","e","handle","r","outcome","classifyResponse","flush","sentThisTick","restored","drainBucket","intervalId","onVisibilityChange","onPageHide","DEFAULT_TTL_MS","cacheKey","componentId","segment","createAssignmentCache","ttlMs","apiKey","memory","keyPrefix","storageSuffix","storageKey","parseStorageKey","key","suffix","sep","e","listStorageKeys","keys","i","isExpired","assignment","raw","parsed","entry","storageK","SNAPSHOT_STORAGE_KEY_PREFIX","BANDS","readSnapshot","apiKey","raw","p","e","writeSnapshot","snap","renderPrePaintScript","confidenceBand","confidenceBand","PROD_KEYLESS_ERROR","LOCAL_MODE_BANNER","bannerShown","prodErrorShown","readPersonaOverrideFromUrl","_a","e","createLocalModeClient","config","session","initSession","sessionId","forcedPersona","modPromise","mod","m","bannerShown","LOCAL_MODE_BANNER","prodErrorShown","PROD_KEYLESS_ERROR","lastOutcome","BAND_CONFIDENCE","seedPersona","__spreadValues","snap","readSnapshot","applyPersonaAttributes","outcome","el","confidenceBand","input","_b","_c","__spreadProps","writeSnapshot","slotId","p","componentId","variantIds","BLOCK_GAPS","BLOCK_ALIGNS","BLOCK_JUSTIFIES","BLOCK_SIZES","BLOCK_WEIGHTS","BLOCK_TONES","BLOCK_EMPHASES","BLOCK_TEXT_ALIGNS","BLOCK_RATIOS","BLOCK_FITS","BLOCK_GRID_COLUMNS","BLOCK_HEADING_LEVELS","MAX_BLOCK_NODES","MAX_BLOCK_DEPTH","MAX_BLOCK_CHILDREN","MAX_BLOCK_ARMS","MAX_BLOCK_TEXT_LEN","attachMicroSignalDetectors","emit","node","variantAssignedAt","options","cleanups","firedOnce","timestamps","onClick","now","onCopy","e","sel","selectionLength","isVisible","hesitationTimer","clearHesitation","startHesitation","onScroll","ioCallback","entries","entry","io","assignedAt","onVisibility","elapsed","c","DEFAULT_INGEST_URL","_clients","_lastApiKey","_registerConsentUpgradeInit","apiKey","reinit","entry","isGoalOptions","v","SESSION_UPSERT_RETRIES","generateEventId","randomUuidV4","currentPath","_a","createActionLatch","byEvent","byFlush","flushOpen","alreadyRecorded","map","actionKey","valueKey","values","hasWindowEvent","currentEvent","ev","closeFlushWindow","done","clear","ch","keys","collapsed","emittedPages","startPageviewTracking","client","projectId","markDelivered","h","stopped","last","emit","path","installed","name","orig","wrapper","a","r","landing","SSR_CLIENT","readUtmParams","out","sp","k","deriveBaseUrl","ingestUrl","isDoNotTrackEnabled","grantConsent","key","config","upgrade","fullClient","init","__spreadProps","__spreadValues","disposed","createPreConsentProxy","servesWinner","baseUrl","authHeaders","winnerCache","inflightWinners","inner","componentId","variantIds","_agentData","cached","coalesce","params","res","result","e","proxy","n","m","w","s","c","g","o","u","av","i","setInner","inflight","run","hit","request","_b","_c","_d","_e","_f","_g","_h","_i","prevEntry","dntBlocked","gated","keyValid","createLocalModeClient","resolvedIngestUrl","sessionStart","session","initSession","assignmentCache","createAssignmentCache","eventQueue","createEventQueue","warnedDropStatuses","goalQueue","createGoalQueue","goal","status","deviceClass","detectDeviceClass","appOrigin","trafficSource","detectTrafficSource","sessionSegment","inflightAssigns","inflightDecides","slotStore","personaState","seedSlotBaselines","decls","d","baselineResultFor","slotId","seedSnapshot","readSnapshot","BAND_CONFIDENCE","ds","variantId","sessionReady","sessionId","referrerDomain","referrerDomainFromReferer","sessionBody","detectTimeOfDay","uaTokenMatch","upsertSession","attempt","classifyResponse","backoffDelayMs","firedThisAction","stopPageviews","pageviewsTornDown","metadataOrOpts","weight","stepIndex","sid","opts","goalId","body","payload","goalType","assignment","slotResult","attributedVariantId","armOfResult","fullEvent","userId","event","segment","agentData","agentDataByVariant","remainingTtlMs","input","declared","id","toWireSlot","decideKey","data","slots","served","prior","baseline","known","writeSnapshot","confidenceBand","SNAPSHOT_STORAGE_KEY_PREFIX","retryStorageKey","goalRetryStorageKey","win"]}
@@ -207,7 +207,7 @@ type Assignment = {
207
207
  type AssignmentCache = {
208
208
  get(componentId: string, segment: string): Assignment | null;
209
209
  set(componentId: string, segment: string, assignment: Assignment): void;
210
- invalidate(componentId: string): void;
210
+ /** Drops every entry, memory and localStorage — the forget-me path. */
211
211
  clear(): void;
212
212
  };
213
213
 
@@ -242,8 +242,6 @@ type GraphClient = {
242
242
  /** One-shot batch sync of all current page nodes to the backend. */
243
243
  syncOnce(): void;
244
244
  snapshot(): GraphSnapshot;
245
- serialize(): string;
246
- restore(data: string): void;
247
245
  destroy(): void;
248
246
  };
249
247
  /**
@@ -368,6 +366,15 @@ declare function attachMicroSignalDetectors(emit: MicroSignalEmitter, node: Elem
368
366
  tabLoss?: boolean;
369
367
  }): () => void;
370
368
 
369
+ /**
370
+ * @internal Wires an alternate entry point's init as grantConsent()'s upgrade
371
+ * path for `apiKey`. The /graph entry calls this when its init is gated on
372
+ * consent: without it, grantConsent() upgraded through the LEAN init, so a
373
+ * graph-configured page granted consent but never mounted the scanner (the
374
+ * graph resources exist only in the /graph entry). No-op unless the entry is
375
+ * actually upgradeable — DNT-blocked and local entries register no hook.
376
+ */
377
+ declare function _registerConsentUpgradeInit(apiKey: string, reinit: (config: SentientConfig) => SentientClient): void;
371
378
  type SentientConfig = {
372
379
  apiKey: string;
373
380
  context: 'landing' | 'ecommerce' | 'saas' | 'marketplace';
@@ -612,4 +619,4 @@ declare function grantConsent(apiKey?: string): void;
612
619
  */
613
620
  declare function init(config: SentientConfig): SentientClient;
614
621
 
615
- export { type MicroSignalType as $, type AssignResult as A, BLOCK_ALIGNS as B, type ComponentGoalOptions as C, type ComponentWeightEntry as D, type CompoundLocator as E, type DecideInput as F, type DecideOutcome as G, type DecisionSnapshot as H, type EventQueue as I, type EventType as J, type GoalDefinition as K, type GoalOptions as L, type GraphClient as M, type GraphConfig as N, type GraphSnapshot as O, type GridBlock as P, type HeadingBlock as Q, type ImageBlock as R, LEGACY_SESSION_COOKIE_NAME as S, LOCAL_MODE_BANNER as T, type LinkBlock as U, MAX_BLOCK_ARMS as V, MAX_BLOCK_CHILDREN as W, MAX_BLOCK_DEPTH as X, MAX_BLOCK_NODES as Y, MAX_BLOCK_TEXT_LEN as Z, type MicroSignalEmitter as _, type Assignment as a, PROD_KEYLESS_ERROR as a0, type PageNode as a1, type QueueConfig as a2, SNAPSHOT_STORAGE_KEY_PREFIX as a3, type SectionMapEntry as a4, type SentientClient as a5, type SentientConfig as a6, type SentientEvent as a7, type SessionConfig as a8, type SessionManager as a9, type SitePalette as aa, type SlotConfigEntry as ab, type SlotOps as ac, type SpacerBlock as ad, type StackBlock as ae, type TextBlock as af, type WeightEntry as ag, attachMicroSignalDetectors as ah, grantConsent as ai, init as aj, isDoNotTrackEnabled as ak, readSnapshot as al, renderPrePaintScript as am, sanitizePageUrl as an, sessionCookieName as ao, writeSnapshot as ap, type AssignmentCache as b, BLOCK_EMPHASES as c, BLOCK_FITS as d, BLOCK_GAPS as e, BLOCK_GRID_COLUMNS as f, BLOCK_HEADING_LEVELS as g, BLOCK_JUSTIFIES as h, BLOCK_RATIOS as i, BLOCK_SIZES as j, BLOCK_TEXT_ALIGNS as k, BLOCK_TONES as l, BLOCK_WEIGHTS as m, type BadgeBlock as n, type BlockAlign as o, type BlockEmphasis as p, type BlockFit as q, type BlockGap as r, type BlockJustify as s, type BlockNode as t, type BlockRatio as u, type BlockSize as v, type BlockTextAlign as w, type BlockTone as x, type BlockWeight as y, type ButtonBlock as z };
622
+ export { type MicroSignalType as $, type AssignResult as A, BLOCK_ALIGNS as B, type ComponentGoalOptions as C, type ComponentWeightEntry as D, type CompoundLocator as E, type DecideInput as F, type DecideOutcome as G, type DecisionSnapshot as H, type EventQueue as I, type EventType as J, type GoalDefinition as K, type GoalOptions as L, type GraphClient as M, type GraphConfig as N, type GraphSnapshot as O, type GridBlock as P, type HeadingBlock as Q, type ImageBlock as R, LEGACY_SESSION_COOKIE_NAME as S, LOCAL_MODE_BANNER as T, type LinkBlock as U, MAX_BLOCK_ARMS as V, MAX_BLOCK_CHILDREN as W, MAX_BLOCK_DEPTH as X, MAX_BLOCK_NODES as Y, MAX_BLOCK_TEXT_LEN as Z, type MicroSignalEmitter as _, type Assignment as a, PROD_KEYLESS_ERROR as a0, type PageNode as a1, type QueueConfig as a2, SNAPSHOT_STORAGE_KEY_PREFIX as a3, type SectionMapEntry as a4, type SentientClient as a5, type SentientConfig as a6, type SentientEvent as a7, type SessionConfig as a8, type SessionManager as a9, type SitePalette as aa, type SlotConfigEntry as ab, type SlotOps as ac, type SpacerBlock as ad, type StackBlock as ae, type TextBlock as af, type WeightEntry as ag, _registerConsentUpgradeInit as ah, attachMicroSignalDetectors as ai, grantConsent as aj, init as ak, isDoNotTrackEnabled as al, readSnapshot as am, renderPrePaintScript as an, sanitizePageUrl as ao, sessionCookieName as ap, writeSnapshot as aq, type AssignmentCache as b, BLOCK_EMPHASES as c, BLOCK_FITS as d, BLOCK_GAPS as e, BLOCK_GRID_COLUMNS as f, BLOCK_HEADING_LEVELS as g, BLOCK_JUSTIFIES as h, BLOCK_RATIOS as i, BLOCK_SIZES as j, BLOCK_TEXT_ALIGNS as k, BLOCK_TONES as l, BLOCK_WEIGHTS as m, type BadgeBlock as n, type BlockAlign as o, type BlockEmphasis as p, type BlockFit as q, type BlockGap as r, type BlockJustify as s, type BlockNode as t, type BlockRatio as u, type BlockSize as v, type BlockTextAlign as w, type BlockTone as x, type BlockWeight as y, type ButtonBlock as z };