@sentientui/core 0.31.1 → 0.32.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 we,c as De,e as Pe,j as Le,k as Me,l as Ke,n as Ne,o as Ge,r as Fe,s as ke,u as Ue}from"./chunk-2NVSFI4V.mjs";import{a as P,b as de}from"./chunk-TMCGHANO.mjs";function xe(){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 t="";for(let o=0;o<16;o++)t+=e[o].toString(16).padStart(2,"0"),(o===3||o===5||o===7||o===9)&&(t+="-");return t}}catch(e){}return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})}var Bt="_snt_uid",Dt=365,be="_snt_uid";function Pt(){return xe()}function ft(e){try{let t=document.cookie.match(new RegExp(`(?:^|; )${e}=([^;]*)`));return t?decodeURIComponent(t[1]):null}catch(t){return null}}function Lt(e,t,o){try{document.cookie=`${e}=${encodeURIComponent(t)}; max-age=${o}; SameSite=strict; path=/`}catch(p){}}function $e(e){try{return localStorage.getItem(e)}catch(t){return null}}function mt(e,t){try{return localStorage.setItem(e,t),!0}catch(o){return!1}}function yt(e){try{return sessionStorage.getItem(e)}catch(t){return null}}function Mt(e,t){try{return sessionStorage.setItem(e,t),!0}catch(o){return!1}}function Kt(e){try{sessionStorage.removeItem(e)}catch(t){}}function Nt(e){try{return document.cookie=`${e}_probe=1; max-age=1; SameSite=strict; path=/`,document.cookie.indexOf(`${e}_probe=1`)!==-1}catch(t){return!1}}function Gt(e){try{localStorage.removeItem(e)}catch(t){}}function Ft(e){try{document.cookie=`${e}=; max-age=0; SameSite=strict; path=/`}catch(t){}}var Ut={getSessionId:()=>null,isEphemeral:()=>!1,destroy:()=>{}};function Ee(e){var u,m,b,x,K,G,R;if(typeof window=="undefined")return Ut;let t=we(e==null?void 0:e.apiKey),o=(u=e==null?void 0:e.cookieName)!=null?u:De(e==null?void 0:e.apiKey),p=`${be}${t}`,S=`${be}_tomb${t}`,i=((m=e==null?void 0:e.cookieTTLDays)!=null?m:Dt)*24*60*60,d=L=>L&&L.length>0?L:null,g=()=>{var L,B;return t&&!(e!=null&&e.cookieName)&&$e(S)===null?(B=(L=d(ft(Bt)))!=null?L:d($e(be)))!=null?B:d(yt(be)):null},r=(R=(G=(K=(x=(b=d(ft(o)))!=null?b:d($e(p)))!=null?x:d(yt(p)))!=null?K:g())!=null?G:d(e==null?void 0:e.ssrSessionId))!=null?R:Pt();Lt(o,r,i);let s=mt(p,r),a=Nt(o),k=s?!1:Mt(p,r),T=!s&&!a&&!k;return{getSessionId:()=>r,isEphemeral:()=>T,destroy:()=>{r=null,Ft(o),Gt(p),Kt(p),t&&!(e!=null&&e.cookieName)&&mt(S,"1")}}}function Y(e){return Math.min(6e4,1e3*2**Math.min(e,6))}function ce(e){if(e.ok===!0)return"delivered";let{status:t}=e;return typeof t!="number"?"retry":t>=200&&t<300?"delivered":t>=400&&t<500&&t!==429?"dropped":"retry"}function Ie(e,t){try{let o=localStorage.getItem(e);if(!o)return[];let p=JSON.parse(o);return Array.isArray(p)?(localStorage.removeItem(e),p.slice(-t)):[]}catch(o){return[]}}function oe(e,t,o){try{let p=(()=>{try{let c=localStorage.getItem(o);if(!c)return[];let i=JSON.parse(c);return Array.isArray(i)?i:[]}catch(c){return[]}})(),S=new Map;for(let c of p)S.set(c.id,c);for(let c of e)S.set(c.id,c);localStorage.setItem(o,JSON.stringify([...S.values()].slice(-t)))}catch(p){}}function _e(e,t){try{let o=localStorage.getItem(t);if(!o)return;let p=JSON.parse(o);if(!Array.isArray(p))return;let S=new Set(e),c=p.filter(i=>!S.has(i.id));if(c.length===p.length)return;c.length===0?localStorage.removeItem(t):localStorage.setItem(t,JSON.stringify(c))}catch(o){}}var $t=500,Wt=56*1024;function We(e){return`_snt_retry_${e.slice(0,12)}`}var jt={push:()=>{},flush:()=>{},destroy:()=>{}};function St(e){var V,X,ge;if(typeof window=="undefined")return jt;let t=(V=e.flushIntervalMs)!=null?V:5e3,o=(X=e.maxBatchSize)!=null?X:20,p=(ge=e.maxRetrySize)!=null?ge:100,S=e.ingestUrl,c=e.apiKey,i=We(c),d=[],g=new Set,r=[],s=v=>{for(let O of v)a.delete(O),!g.has(O)&&(g.add(O),r.push(O));for(;r.length>$t;){let O=r.shift();O&&g.delete(O)}_e(v,i)},a=new Set,k=()=>{for(;d.length>p;){let v=d.shift();v&&a.delete(v.id)}},T=v=>{g.has(v.id)||a.has(v.id)||(a.add(v.id),d.push(v),k())},u=v=>{for(let O of v)g.has(O.id)||(a.add(O.id),d.push(O));k()},m=Ie(i,p);for(let v of m)T(v);let b=0,x=0,K=(v,O=!0)=>{if(v.length===0)return;let j=JSON.stringify(v),Q=v.map(H=>H.id),z;try{z=fetch(S,{method:"POST",keepalive:!0,body:j,headers:{"Content-Type":"application/json",Authorization:`Bearer ${c}`}})}catch(H){oe(v,p,i),u(v),x++,b=Date.now()+Y(x);return}let se=H=>{if(ce(H)!=="retry"){if(!H.ok&&O){let re=v.filter(ie=>ie.eventType!=="pageview");if(re.length>0&&re.length<v.length){s(v.filter(ie=>ie.eventType==="pageview").map(ie=>ie.id)),K(re,!1);return}}s(Q),x=0,b=0;return}oe(v,p,i),u(v),x++,b=Date.now()+Y(x)};z instanceof Promise?z.then(se).catch(()=>{oe(v,p,i),u(v),x++,b=Date.now()+Y(x)}):se(z)},G=typeof TextEncoder!="undefined"?new TextEncoder:null,R=v=>G?G.encode(v).length:v.length,L=v=>{let O=[],j=2;for(let Q of v){let z=R(JSON.stringify(Q))+1;if(O.length>0&&j+z>Wt||O.length>=o)break;O.push(Q),j+=z}return O},B=()=>{try{if(Date.now()<b)return;for(;d.length>0&&!(Date.now()<b);){let v=d.filter(j=>!g.has(j.id));if(d.length=0,v.length===0)break;let O=L(v);if(O.length===0)break;O.length<v.length&&d.push(...v.slice(O.length)),K(O)}}catch(v){}},h=!0,I=null;I=setInterval(()=>{h&&B()},t);let Z=()=>{document.visibilityState==="hidden"&&B()},W=()=>{B()};return document.addEventListener("visibilitychange",Z),window.addEventListener("pagehide",W),{push(v){T(v),d.length>=o&&B()},flush:B,destroy(){h=!1,I!==null&&(clearInterval(I),I=null),document.removeEventListener("visibilitychange",Z),window.removeEventListener("pagehide",W),B()}}}var zt=200;function je(e){return`_snt_goal_retry_${e.slice(0,12)}`}var Ht={send:()=>{},flush:()=>{},destroy:()=>{}};function ht(e){var R,L,B;if(typeof window=="undefined")return Ht;let t=(R=e.flushIntervalMs)!=null?R:5e3,o=(L=e.maxRetrySize)!=null?L:100,p=(B=e.maxPerFlush)!=null?B:5,S=je(e.apiKey),c=[],i=new Set,d=new Set,g=[],r=0,s=0,a=!1,k=h=>{for(i.delete(h.id),d.has(h.id)||(d.add(h.id),g.push(h.id));g.length>zt;){let I=g.shift();I&&d.delete(I)}_e([h.id],S)},T=h=>{oe([h],o,S),!d.has(h.id)&&!i.has(h.id)&&(i.add(h.id),c.push(h)),Date.now()>=r&&(s++,r=Date.now()+Y(s))},u=h=>{let I;try{I=fetch(e.url,{method:"POST",keepalive:!0,body:h.body,headers:e.headers})}catch(W){T(h);return}let Z=W=>{var X;let V=ce(W);if(V==="retry"){T(h);return}V==="dropped"&&((X=e.onDrop)==null||X.call(e,h,W.status)),k(h),s=0,r=0};I instanceof Promise?I.then(Z).catch(()=>T(h)):Z(I)},m=()=>{try{if(a||Date.now()<r)return;let h=0;for(;c.length>0&&h<p&&!(Date.now()<r);){let I=c.shift();i.delete(I.id),!d.has(I.id)&&(h++,u(I))}}catch(h){}},b=Ie(S,o);for(let h of b)i.has(h.id)||(i.add(h.id),c.push(h));b.length>0&&oe(b,o,S);let x=setInterval(m,t),K=()=>{document.visibilityState==="hidden"&&m()},G=()=>m();return document.addEventListener("visibilitychange",K),window.addEventListener("pagehide",G),{send(h){if(!a&&!(d.has(h.id)||i.has(h.id))){if(Date.now()<r){oe([h],o,S),i.add(h.id),c.push(h);return}u(h)}},flush:m,destroy(){clearInterval(x),document.removeEventListener("visibilitychange",K),window.removeEventListener("pagehide",G),m(),a=!0}}}var Qt=1800*1e3;function Ce(e,t){return`${encodeURIComponent(e)}:${encodeURIComponent(t)}`}function vt(e=Qt,t){let o=new Map,p=`_snt_asgn${we(t)}_`,S=(r,s)=>`${p}${encodeURIComponent(r)}:${encodeURIComponent(s)}`,c=r=>{let s=r.slice(p.length),a=s.indexOf(":");if(a<0)return null;try{return{componentId:decodeURIComponent(s.slice(0,a)),segment:decodeURIComponent(s.slice(a+1))}}catch(k){return null}},i=()=>{try{let r=[];for(let s=0;s<localStorage.length;s++){let a=localStorage.key(s);a!=null&&a.startsWith(p)&&r.push(a)}return r}catch(r){return[]}},d=r=>r.assignedAt+(r.ttlMs&&r.ttlMs>0?r.ttlMs:e)<Date.now();return typeof window!="undefined"&&(()=>{for(let r of i())try{let s=localStorage.getItem(r);if(!s)continue;let a=JSON.parse(s);if(d(a)){localStorage.removeItem(r);continue}let k=c(r);if(!k)continue;o.set(Ce(k.componentId,k.segment),a)}catch(s){}})(),{get(r,s){let a=o.get(Ce(r,s));return a?d(a)?(o.delete(Ce(r,s)),null):a:null},set(r,s,a){let k=Ce(r,s);o.set(k,a);try{localStorage.setItem(S(r,s),JSON.stringify(a))}catch(T){}},clear(){o.clear();for(let r of i())try{localStorage.removeItem(r)}catch(s){}}}}var ue="_snt_snap:",Jt=["low","medium","high"];function Se(e){try{let t=localStorage.getItem(ue+e);if(!t)return null;let o=JSON.parse(t);return!o||typeof o!="object"||o.v!==1||typeof o.persona!="string"||typeof o.band!="string"||!Jt.includes(o.band)||typeof o.slots!="object"||o.slots===null||Array.isArray(o.slots)||!(o.layoutOrder===null||Array.isArray(o.layoutOrder))||typeof o.savedAt!="number"||!(o.slotConfig===void 0||typeof o.slotConfig=="object"&&o.slotConfig!==null&&!Array.isArray(o.slotConfig))?null:o}catch(t){return null}}function he(e,t){try{localStorage.setItem(ue+e,JSON.stringify(t))}catch(o){}}function Vt(e){return"(function(){try{var r=localStorage.getItem("+JSON.stringify(ue+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 Et}from"@sentientui/policy";import{confidenceBand as ze}from"@sentientui/policy";var He="[sentient] No API key configured \u2014 nothing is being learned. Set NEXT_PUBLIC_SENTIENT_API_KEY or pass localMode: true for local development.",kt="[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.",wt=!1,Te=!1;function Xt(){var e;try{return(e=new URLSearchParams(window.location.search).get("sentient_persona"))!=null?e:void 0}catch(t){return}}function xt(e){var r;let t=Ee({ssrSessionId:e.ssrSessionId,apiKey:e.apiKey}),o=(r=t.getSessionId())!=null?r:"local",p=Xt(),S=import("@sentientui/core/local").then(s=>{let a=s;return a.LOCAL_ENGINE_AVAILABLE?(wt||(wt=!0,console.info(kt)),a):(Te||(Te=!0,console.error(He)),null)}).catch(()=>(Te||(Te=!0,console.error(He)),null)),c=null,i={low:.15,medium:.5,high:.85},d=(()=>{var a;if(e.initialPersona)return P({},e.initialPersona);let s=Se(e.apiKey||"local");return s?{persona:s.persona,confidence:(a=i[s.band])!=null?a:.15}:null})();function g(s){let a=document.documentElement;a.dataset.sentientPersona===void 0&&(a.dataset.sentientPersona=s.persona,a.dataset.sentientConfidence=ze(s.confidence))}return{isLocal:!0,async decide(s){var T,u,m;let a=await S;if(!a)return null;let k=a.createLocalEngine({sessionId:o,forcedPersona:p}).decide(s);return c=de(P({},k),{layoutOrder:(u=(T=k.layoutOrder)!=null?T:c==null?void 0:c.layoutOrder)!=null?u:null,slots:P(P({},(m=c==null?void 0:c.slots)!=null?m:{}),k.slots)}),he(e.apiKey||"local",{v:1,persona:c.persona,band:ze(c.confidence),slots:c.slots,layoutOrder:c.layoutOrder,savedAt:Date.now()}),g(k),k},getSlotResult(s){var a,k,T;return(T=(k=c==null?void 0:c.slots[s])!=null?k:(a=e.initialSlots)==null?void 0:a[s])!=null?T:null},getSlotConfig(s){var a,k;return(k=(a=e.initialSlotConfig)==null?void 0:a[s])!=null?k:null},getSitePalette(){var s;return(s=e.initialPalette)!=null?s:null},reportSlots(){},getPersona(){let s=c!=null?c:d;return s?{persona:s.persona,confidence:s.confidence,band:ze(s.confidence)}:null},async assign(s,a){var u;let k=await S;return!k||!a||a.length===0?a!=null&&a[0]?{variantId:a[0],assignmentTtlMs:0}:null:{variantId:(u=k.createLocalEngine({sessionId:o,forcedPersona:p}).decide({components:[{id:s,variantIds:a}]}).assignments[s])!=null?u:a[0],assignmentTtlMs:0}},track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},getAssignment:()=>null,fetchWeights:()=>Promise.resolve([]),getGraph:()=>({pageNodes:[],capturedAt:0}),flush:()=>{},dispose:()=>{},destroy:()=>t.destroy()}}var bt=/^(\*|\/[^\s?#*]*(\/\*)?)$/;function Qe(e){let t=e.split(/[?#]/)[0]||"/";return t.length>1?t.replace(/\/+$/,"")||"/":t}function qt(e,t){if(e===void 0||!bt.test(e))return!1;if(e==="*")return!0;let o=Qe(t);if(e.endsWith("/*")){let p=Qe(e.slice(0,-2));return o.startsWith(p==="/"?"/":`${p}/`)&&o!==p}return o===Qe(e)}var Rn=["none","sm","md","lg"],Bn=["start","center","end","stretch"],Dn=["start","center","end","between"],Pn=["sm","md","lg"],Ln=["normal","medium","bold"],Mn=["default","muted","accent"],Kn=["primary","secondary","ghost"],Nn=["left","center","right"],Gn=["auto","square","landscape","wide"],Fn=["cover","contain"],Un=[2,3,4],$n=[2,3,4],Wn=["default","raised"],jn=["none","sm","md","lg"],zn=["measure"],Hn=["input","textarea","select"],Qn=["text","email","number","tel"],Jn=5,Vn=8,Xn=64,qn=5,Yn=12,Zn=4,eo=500;function Yt(e){if(e==null||typeof e!="object"||Array.isArray(e))return!1;let t=e;return t.type==="form"?!0:Array.isArray(t.children)?t.children.some(Yt):!1}var Je="sentient-reveal",pe="sentient-revealed",Zt=240,Oe=!1;function en(){var e;Oe=!1,typeof document!="undefined"&&((e=document.getElementById(Je))==null||e.remove())}function tn(e){if(Oe||e.getElementById(Je)){Oe=!0;return}let t=e.createElement("style");t.id=Je,t.textContent=`@media (prefers-reduced-motion: no-preference){@keyframes ${pe}{from{opacity:.55;transform:translateY(2px)}to{opacity:1;transform:none}}.${pe}{animation:${pe} 240ms cubic-bezier(.2,.6,.2,1) both}}`,e.head.appendChild(t),Oe=!0}function nn(e,t={}){var S;let o=(S=t.doc)!=null?S:typeof document!="undefined"?document:void 0;if(!o||!(e instanceof Element)||(t.arm!==void 0&&e.setAttribute("data-sentient-arm",t.arm),t.persona!==void 0&&e.setAttribute("data-sentient-persona",t.persona),t.previous!==void 0&&t.previous===e.textContent))return!1;tn(o),e.classList.remove(pe),e.offsetWidth,e.classList.add(pe);let p=()=>{e.classList.remove(pe),e.removeEventListener("animationend",p)};return e.addEventListener("animationend",p),!0}function on(e,t,o,p){let S=[];{let d=!1,g=[],r=()=>{if(d)return;let s=Date.now();for(g.push(s);g.length>0&&s-g[0]>500;)g.shift();g.length>=3&&(d=!0,e("rage_click"))};t.addEventListener("click",r),S.push(()=>t.removeEventListener("click",r))}{let c=!1,i=d=>{if(c||!(d.target instanceof Node)||!t.contains(d.target)&&t!==d.target)return;c=!0;let g=typeof window!="undefined"?window.getSelection():null,r=g?g.toString().length:0;e("text_copy",{selectionLength:r})};document.addEventListener("copy",i),S.push(()=>document.removeEventListener("copy",i))}{let c=!1,i=!1,d=null,g=()=>{d!==null&&(clearTimeout(d),d=null)},r=()=>{c||!i||(g(),d=setTimeout(()=>{!c&&i&&(c=!0,e("scroll_hesitation"))},3e3))},s=()=>{g(),r()},a=T=>{for(let u of T)i=u.intersectionRatio>.3,i?r():g()},k=new IntersectionObserver(a,{threshold:[.3]});k.observe(t),window.addEventListener("scroll",s,{passive:!0}),S.push(()=>{k.disconnect(),window.removeEventListener("scroll",s),g()})}if((p==null?void 0:p.tabLoss)!==!1){let c=!1,i=o!=null?o:Date.now(),d=()=>{if(c||document.visibilityState!=="hidden")return;let g=Date.now()-i;g<15e3&&(c=!0,e("tab_loss",{timeOnPage:g}))};document.addEventListener("visibilitychange",d),S.push(()=>document.removeEventListener("visibilitychange",d))}return()=>{for(let c of S)c()}}function sn(){var e;return typeof process=="undefined"||((e=process.env)==null?void 0:e.NODE_ENV)!=="production"}var It="https://api.sentient-ui.com/v1/events",$=new Map,_t=null;function Io(e,t){let o=$.get(e);o&&o.upgrade&&(o.reinit=t)}function rn(e){return"value"in e||"currency"in e||"externalId"in e||"metadata"in e||"weight"in e||"stepIndex"in e}var an=3;function Ve(){return xe()}function Ae(){var e;if(typeof window!="undefined")return((e=window.location)==null?void 0:e.pathname)||void 0}function ln(){let e=new WeakMap,t=new Map,o=!1,p=(d,g,r)=>{let s=d.get(g);return r===null?s?!0:(d.set(g,new Set),!1):s?s.has(r)?!0:(s.add(r),!1):(d.set(g,new Set([r])),!1)},S=typeof window!="undefined"&&"event"in window,c=()=>{if(!S)return;let d=window.event;return typeof Event=="function"&&d instanceof Event?d:void 0},i=()=>{if(S){Promise.resolve().then(()=>{o=!1,t.clear()});return}let d=!1,g=()=>{d||(d=!0,o=!1,t.clear())};if(setTimeout(g,0),typeof MessageChannel=="function"){let r=new MessageChannel;r.port1.onmessage=()=>{r.port1.close(),r.port2.close(),g()},r.port2.postMessage(0)}};return{firedBefore(d,g){let r=c();if(r){let a=e.get(r);return a||(a=new Map,e.set(r,a)),p(a,d,g)}let s=p(t,d,g);return!s&&!o&&(o=!0,i()),s}}}var Ct=new Set;function dn(e,t,o){let p=typeof window=="undefined"?null:window.history;if(!p)return()=>{};let S=!1,c,i=()=>{if(S)return;let r=Ae();!r||r===c||(c=r,e.track({projectId:t,componentId:"__page__",eventType:"pageview",payload:{}}),o(`${t}:${r}`))},d=[];for(let r of["pushState","replaceState"]){let s=p[r],a=function(...k){let T=s.apply(this,k);return i(),T};p[r]=a,d.push([r,s,a])}window.addEventListener("popstate",i);let g=Ae();return g&&Ct.has(`${t}:${g}`)?c=g:i(),()=>{if(!S){S=!0,window.removeEventListener("popstate",i);for(let[r,s,a]of d)p[r]===a&&(p[r]=s)}}}var ve={track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},getAssignment:()=>null,assign:()=>Promise.resolve(null),decide:()=>Promise.resolve(null),getSlotResult:()=>null,getSlotConfig:()=>null,getSitePalette:()=>null,reportSlots:()=>{},getPersona:()=>null,fetchWeights:()=>Promise.resolve([]),getGraph:()=>({pageNodes:[],capturedAt:0}),flush:()=>{},dispose:()=>{},destroy:()=>{}};function cn(){try{return Ne(window.location.search)}catch(e){return{utmParams:{},clickIds:{}}}}function Tt(e){return e.replace(/\/events\/?$/,"")}function Ot(){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(t=>t==="1"||t==="yes")}function _o(e){var g;if(typeof window=="undefined")return;let t=e!=null?e:_t;if(!t){console.warn("[sentient] grantConsent() called before init()");return}let o=$.get(t);if(!o){console.warn("[sentient] grantConsent() called before init()");return}let{config:p,upgrade:S,reinit:c}=o;if(!S){o.upgradeBlockedReason&&console.warn(o.upgradeBlockedReason);return}if(p.respectDoNotTrack!==!1&&Ot())return;let i=(c!=null?c:pn)(de(P({},p),{consent:!0}));S(i);let d=(g=$.get(t))==null?void 0:g.dispose;$.set(t,{config:de(P({},p),{consent:!0}),upgrade:null,dispose:d})}function un(e){var T;let t=e.preConsentBehavior==="statistical_winner",o=Tt((T=e.ingestUrl)!=null?T:It),p={"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`},S=new Map,c=new Map,i={track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},getAssignment:()=>null,fetchWeights:()=>Promise.resolve([]),assign(u,m,b){if(!t)return Promise.resolve(null);let x=S.get(u);return x?Promise.resolve(x):Xe(c,u,async()=>{try{let K=new URLSearchParams({componentId:u});for(let B of m!=null?m:[])K.append("variantIds[]",B);let G=await fetch(`${o}/winner?${K.toString()}`,{headers:p});if(!G.ok)return m!=null&&m[0]?{variantId:m[0],assignmentTtlMs:0}:null;let L={variantId:(await G.json()).variantId,assignmentTtlMs:0};return S.set(u,L),L}catch(K){return m!=null&&m[0]?{variantId:m[0],assignmentTtlMs:0}:null}})},decide:()=>Promise.resolve(null),getSlotResult:()=>null,getSlotConfig:()=>null,getSitePalette:()=>null,reportSlots:()=>{},getPersona:()=>null,getGraph:()=>({pageNodes:[],capturedAt:0}),flush:()=>{},dispose:()=>{},destroy:()=>{}},d=!1,g=new Set,r=[],s=[],a={track:u=>i.track(u),goal:((u,m,b,x)=>i.goal(u,m,b,x)),componentGoal:(u,m,b)=>i.componentGoal(u,m,b),identify:u=>i.identify(u),getAssignment:(u,m)=>i.getAssignment(u,m),assign:(u,m,b,x)=>i.assign(u,m,b,x),decide:u=>i.decide(u),getSlotResult:u=>i.getSlotResult(u),isSlotDecided:u=>{var m,b;return(b=(m=i.isSlotDecided)==null?void 0:m.call(i,u))!=null?b:!0},getSlotConfig:u=>i.getSlotConfig(u),getSitePalette:()=>i.getSitePalette(),reportSlots:(u,m)=>i.reportSlots(u,m),requestSlots:(u,m)=>{var b;return d?(b=i.requestSlots)==null?void 0:b.call(i,u,m):r.push([u,m])},decideSlots:u=>{var m;return d?(m=i.decideSlots)==null?void 0:m.call(i,u):s.push(...u)},cancelSlots:u=>{var b;if(d)return(b=i.cancelSlots)==null?void 0:b.call(i,u);let m=new Set(u);for(let x of r)x[0]=x[0].filter(K=>!m.has(K));s=s.filter(x=>!m.has(x.id))},onSlotsChanged:u=>(g.add(u),()=>{g.delete(u)}),getPersona:()=>i.getPersona(),fetchWeights:()=>i.fetchWeights(),getGraph:()=>i.getGraph(),flush:()=>i.flush(),dispose:()=>i.dispose(),destroy:()=>i.destroy()};function k(u){var m,b,x;i=u,d=!0,(m=u.onSlotsChanged)==null||m.call(u,()=>g.forEach(K=>K()));for(let[K,G]of r.splice(0))K.length>0&&((b=u.requestSlots)==null||b.call(u,K,G));s.length>0&&((x=u.decideSlots)==null||x.call(u,s.splice(0)))}return{proxy:a,setInner:k}}function Xe(e,t,o){let p=e.get(t);if(p)return p;let S=(async()=>{try{return await o()}finally{e.delete(t)}})();return e.set(t,S),S}function pn(e){var nt,ot,st,rt,it,at,lt,dt,ct,ut;if(typeof window=="undefined")return ve;_t=e.apiKey||"local";let t=$.get(e.apiKey||"local");if(t!=null&&t.dispose)try{t.dispose()}catch(n){}let o=e.respectDoNotTrack!==!1&&Ot(),p=e.consent===!1||o,S=typeof e.apiKey=="string"&&e.apiKey.startsWith("pk_");if(e.localMode===!0||!S&&e.localMode!==!1)return $.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."}),p?ve:xt(e);if(p){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."),$.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."}),ve;let{proxy:n,setInner:l}=un(e);return $.set(e.apiKey,{config:e,upgrade:o?null:l}),n}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."),ve;if(e.ingestUrl==="")return console.warn("[sentient] init() called with an empty ingestUrl. SDK disabled."),ve;let c=(nt=e.ingestUrl)!=null?nt:It,i=Date.now(),d=Ee({ssrSessionId:e.ssrSessionId,apiKey:e.apiKey}),g=vt(void 0,e.apiKey),r=St({ingestUrl:c,apiKey:e.apiKey}),s=Tt(c),a={"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`},k=new Set,T=ht({url:`${s}/goals`,apiKey:e.apiKey,headers:a,onDrop:(n,l)=>{if(!e.debug){if(k.has(l))return;k.add(l)}console.warn(`[sentient] goal dropped (HTTP ${l}) \u2014 this will not be retried. `+(l===400?"The session was not found: call init() and let the session upsert complete before firing goals.":l===401||l===403?"Check the API key and that this origin is on the project allowlist.":"See the response status for the cause."),n)}}),u=Le((ot=navigator.userAgent)!=null?ot:""),m=window.location.origin,b=Me((st=document.referrer)!=null?st:"",m),x=(rt=e.sessionSegment)!=null?rt:`${u}:${b}`,K=new Map,G=new Map,R=new Map,L=new Set,B=new Map,h=null,I=null,Z=new Set,W=new Set,V=new Map,X=null,ge=/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,127}$/,v=new Set,O=new Set,j=new Set,Q=new Map,z=null,se=new Set,H=new Map,re=null,ie=2,qe=new Map,Re=!1,Ye=(n,l,f)=>{var y;let w=new Set,_=1;for(let E of n){l.delete(E);let C=((y=qe.get(E))!=null?y:0)+1;qe.set(E,C),C<=ie&&(w.add(E),C>_&&(_=C))}w.size>0&&setTimeout(()=>{Re||f(w)},Y(_))},Ze=n=>{for(let l of n)R.has(l.id)||R.set(l.id,ke(l))};if(e.initialSlots)for(let[n,l]of Object.entries(e.initialSlots))R.set(n,l),L.add(n);if(e.initialSlotConfig)for(let[n,l]of Object.entries(e.initialSlotConfig))B.set(n,l);e.initialPalette&&(h=e.initialPalette);let ee=Se(e.apiKey);if(ee){for(let[n,l]of Object.entries(ee.slots))R.has(n)||R.set(n,l);for(let[n,l]of Object.entries((it=ee.slotConfig)!=null?it:{}))B.has(n)||B.set(n,l);!h&&ee.palette&&(h=ee.palette)}let et={low:.15,medium:.5,high:.85};if(e.initialPersona)I=P({},e.initialPersona);else{let n=document.documentElement.dataset;n.sentientPersona?I={persona:n.sentientPersona,confidence:(lt=et[(at=n.sentientConfidence)!=null?at:"low"])!=null?lt:.15}:ee&&(I={persona:ee.persona,confidence:(dt=et[ee.band])!=null?dt:.15})}if(e.initialAssignments)for(let[n,l]of Object.entries(e.initialAssignments))g.set(n,x,{variantId:l,assignedAt:Date.now(),segment:x,confidence:1});let te=Promise.resolve(),tt=d.getSessionId();if(tt){let n=Ke((ct=document.referrer)!=null?ct:""),{utmParams:l,clickIds:f}=cn(),w=P(P(P(P({sessionId:tt,deviceClass:u,trafficSource:b,referrerDomain:n,utmParams:l,clickIds:f,timeOfDay:Ge(new Date),dayOfWeek:["sun","mon","tue","wed","thu","fri","sat"][new Date().getDay()],ephemeral:d.isEphemeral(),automation:typeof navigator!="undefined"&&navigator.webdriver===!0||Pe((ut=navigator.userAgent)!=null?ut:"")},e.userId?{userId:e.userId}:{}),e.persona?{persona:e.persona}:{}),e.country?{country:e.country}:{}),e.sdk?{sdk:e.sdk.name,sdkVersion:e.sdk.version}:{}),_=async()=>{for(let y=0;;y++){try{let E=await fetch(`${s}/sessions`,{method:"POST",keepalive:!0,body:JSON.stringify(w),headers:a});if(E.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(E.ok||ce(E)==="dropped")return}catch(E){}if(y>=an){console.warn("[SentientUI] Could not register the session after retries. Conversions in this visit may not be recorded.");return}await new Promise(E=>setTimeout(E,Y(y+1)))}};try{te=_()}catch(y){}}e.debug&&(console.log("[sentient] initialized",{context:e.context}),window.__sentient={client:null,queue:r});let At=ln(),ae=null,Be=!1,N={goal(n,l={},f=1,w=0){var ne,fe,me,ye,le,A,q;let _=d.getSessionId();if(!_)return;let y=rn(l)?l:{metadata:l},E=[n,(ne=y.externalId)!=null?ne:"",(fe=y.stepIndex)!=null?fe:w,(me=y.weight)!=null?me:f].join("\0"),C=y.value!==void 0?`${y.value}\0${(ye=y.currency)!=null?ye:""}`:null;if(At.firedBefore(E,C)){e.debug&&console.log(`[sentient] goal("${n}") already recorded for this action \u2014 not sent twice`);return}let M=Ve(),F={sessionId:_,name:n,metadata:(le=y.metadata)!=null?le:{},weight:(A=y.weight)!=null?A:f,stepIndex:(q=y.stepIndex)!=null?q:w,goalId:M,value:y.value,currency:y.currency,externalId:y.externalId};e.debug&&console.log("[sentient] goal",F);let U={id:M,body:JSON.stringify(F)};te.then(()=>T.send(U))},componentGoal(n,l,f){var M,F,U;let w=d.getSessionId();if(!w)return;let _=g.get(n,x),y=_?null:(M=R.get(n))!=null?M:null;if(!_&&y===null){e.debug&&console.warn(`[sentient] componentGoal("${n}"): no assignment or slot decision yet \u2014 render its <Adaptive>/adaptive hook or call assign()/decide() before recording a goal.`);return}if(!_&&!L.has(n)){e.debug&&console.warn(`[sentient] componentGoal("${n}"): slot not decided this session \u2014 not attributed`);return}let E=_?_.variantId:Ue(y),C={id:Ve(),sessionId:w,projectId:e.apiKey,componentId:n,variantId:E,eventType:"goal_achieved",goalType:l,payload:P({reward:(F=f==null?void 0:f.reward)!=null?F:1,goalValue:f==null?void 0:f.value,currency:f==null?void 0:f.currency},(U=f==null?void 0:f.metadata)!=null?U:{}),timestamp:Date.now(),timeInSession:Date.now()-i,path:Ae()};e.debug&&console.log("[sentient] componentGoal",C),te.then(()=>r.push(C))},identify(n){let l=d.getSessionId();l&&te.then(()=>{fetch(`${s}/sessions`,{method:"POST",keepalive:!0,body:JSON.stringify({sessionId:l,userId:n,ephemeral:d.isEphemeral()}),headers:a}).catch(()=>{})})},track(n){let l=d.getSessionId();if(!l||n.eventType==="variant_assigned"&&R.get(n.componentId)!==void 0&&!L.has(n.componentId)&&!g.get(n.componentId,x))return;let f=de(P({path:Ae()},n),{id:Ve(),sessionId:l,timestamp:Date.now(),timeInSession:Date.now()-i});e.debug&&console.log("[sentient] track",f),te.then(()=>r.push(f))},getAssignment(n,l){return g.get(n,l)},async assign(n,l,f,w){let _=d.getSessionId();if(!_)return null;let y=g.get(n,x);if(y&&(l!=null&&l.length||y.content!==void 0)){let E=y.ttlMs&&y.ttlMs>0?Math.max(0,y.assignedAt+y.ttlMs-Date.now()):0;return{variantId:y.variantId,assignmentTtlMs:E,content:y.content}}return Xe(K,n,async()=>{await te;try{let E={sessionId:_,componentId:n,variantIds:l};w!==void 0?E.agentDataByVariant=w:f!==void 0&&(E.agentData=f);let C=await fetch(`${s}/assign`,{method:"POST",body:JSON.stringify(E),headers:a});if(!C.ok)return null;let M=await C.json();return g.set(n,x,P({variantId:M.variantId,assignedAt:Date.now(),segment:x,confidence:1,content:M.content},M.assignmentTtlMs&&M.assignmentTtlMs>0?{ttlMs:M.assignmentTtlMs}:{})),M}catch(E){return null}})},async decide(n){var y,E;let l=d.getSessionId();if(!l)return null;let f=(y=n.slots)!=null?y:[],w={sessionId:l};n.sections&&n.sections.length>0&&(w.sections=n.sections.map(C=>({id:C}))),w.components=(E=n.components)!=null?E:[],f.length>0&&(w.slots=f.map(Fe)),n.slotsFrom==="registry"&&(w.slotsFrom="registry",n.registrySlotIds&&(w.registrySlotIds=n.registrySlotIds),n.bootstrap===!1&&(w.bootstrap=!1)),n.v&&(w.v=n.v),typeof n.pp=="number"&&(w.pp=n.pp),e.persona&&(w.persona=e.persona);let _=JSON.stringify(w);return Xe(G,_,async()=>{var C,M,F,U,ne,fe,me,ye;await te;try{let le=await fetch(`${s}/decide`,{method:"POST",body:_,headers:a});if(!le.ok)return Ze(f),null;let A=await le.json(),q={};for(let D of f){let J=(C=A.slots)==null?void 0:C[D.id];if(J!==void 0){q[D.id]=J,R.set(D.id,J),L.add(D.id);continue}let pt=R.get(D.id);if(pt!==void 0)q[D.id]=pt;else{let gt=ke(D);q[D.id]=gt,R.set(D.id,gt)}}if(A.slots)for(let[D,J]of Object.entries(A.slots))D in q||(q[D]=J,R.set(D,J),L.add(D));let Rt=I!=null&&I.persona!=="unknown";A.persona&&!(A.persona==="unknown"&&Rt)?I={persona:A.persona,confidence:(M=A.confidence)!=null?M:0}:I||(I={persona:"unknown",confidence:0});for(let[D,J]of Object.entries((F=A.assignments)!=null?F:{}))g.set(D,x,{variantId:J,assignedAt:Date.now(),segment:x,confidence:1});if(A.slotConfig)for(let[D,J]of Object.entries(A.slotConfig))B.set(D,J);A.palette&&(h=A.palette);for(let D of(U=n.registrySlotIds)!=null?U:[])(ne=A.slotConfig)!=null&&ne[D]||(B.delete(D),R.delete(D),L.delete(D));return he(e.apiKey,P(P({v:1,persona:I.persona,band:Et(I.confidence),slots:Object.fromEntries(R),layoutOrder:(fe=A.layoutOrder)!=null?fe:null,savedAt:Date.now()},B.size>0?{slotConfig:Object.fromEntries(B)}:{}),h?{palette:h}:{})),P(P(P(P({layoutOrder:(me=A.layoutOrder)!=null?me:null,assignments:(ye=A.assignments)!=null?ye:{},slots:q,persona:I.persona,confidence:I.confidence},A.slotConfig?{slotConfig:A.slotConfig}:{}),A.goals?{goals:A.goals}:{}),A.sectionMap?{sectionMap:A.sectionMap}:{}),A.palette?{palette:A.palette}:{})}catch(le){return Ze(f),null}})},getSlotResult(n){var l;return(l=R.get(n))!=null?l:null},isSlotDecided(n){return L.has(n)},getSlotConfig(n){var l;return(l=B.get(n))!=null?l:null},reportSlots(n,l){for(let f of n)if(!(typeof f!="string"||f.length===0)){if(!ge.test(f)){sn()&&!v.has(f)&&(v.add(f),console.warn(`[sentient] reportSlots: slot id ${JSON.stringify(f)} will not register \u2014 ids must start with a letter or digit and contain only letters, digits, '_' or '-' (max 128 chars): /^[a-zA-Z0-9][a-zA-Z0-9_-]{0,127}$/.`));continue}if(!Z.has(f)){Z.add(f),W.add(f);let w=l==null?void 0:l[f];if(typeof w=="string"){let _=w.replace(/\s+/g," ").trim().slice(0,400);_!==""&&V.set(f,_)}}}W.size===0||X!=null||(X=setTimeout(()=>{X=null;let f=[...W];W.clear();for(let w=0;w<f.length;w+=20){let _=f.slice(w,w+20),y={};for(let E of _){let C=V.get(E);C!==void 0&&(y[E]=C,V.delete(E))}fetch(`${s}/slots/observed`,{method:"POST",headers:a,body:JSON.stringify(P({slotIds:_},Object.keys(y).length>0?{baselineTexts:y}:{}))}).catch(()=>{})}},1e3))},requestSlots(n,l){for(let f of n)j.has(f)||(j.add(f),ge.test(f)?Q.set(f,l==null?void 0:l[f]):N.reportSlots([f]));Q.size===0||z!=null||(z=setTimeout(()=>{z=null;let f=[...Q];Q.clear();for(let w=0;w<f.length;w+=50){let _=f.slice(w,w+50);N.decide({slotsFrom:"registry",registrySlotIds:_.map(([y])=>y),bootstrap:!1}).then(y=>{var E;if(y){let C={},M=[];for(let[F,U]of _)(E=y.slotConfig)!=null&&E[F]||(M.push(F),U&&(C[F]=U));M.length>0&&N.reportSlots(M,C)}else Ye(_.map(([C])=>C),j,C=>{var F;let M={};for(let[U,ne]of _)C.has(U)&&ne&&(M[U]=ne);(F=N.requestSlots)==null||F.call(N,[...C],M)});O.forEach(C=>C())})}},0))},decideSlots(n){for(let l of n)se.has(l.id)||(se.add(l.id),H.set(l.id,l));H.size===0||re!=null||(re=setTimeout(()=>{re=null;let l=[...H.values()];H.clear();for(let f=0;f<l.length;f+=30){let w=l.slice(f,f+30);N.decide({slots:w}).then(_=>{_||Ye(w.map(y=>y.id),se,y=>{var E;return(E=N.decideSlots)==null?void 0:E.call(N,w.filter(C=>y.has(C.id)))}),O.forEach(y=>y())})}},0))},cancelSlots(n){for(let l of n)Q.delete(l)&&j.delete(l),H.delete(l)&&se.delete(l)},onSlotsChanged(n){return O.add(n),()=>{O.delete(n)}},getSitePalette(){return h},getPersona(){return I?{persona:I.persona,confidence:I.confidence,band:Et(I.confidence)}:null},async fetchWeights(){var n;try{let l=await fetch(`${s}/weights`,{headers:a});return l.ok?(n=(await l.json()).components)!=null?n:[]:[]}catch(l){return[]}},getGraph(){return{pageNodes:[],capturedAt:0}},flush(){r.flush(),T.flush()},dispose(){var n;ae==null||ae(),Be=!0,Re=!0,r.destroy(),T.destroy(),((n=$.get(e.apiKey))==null?void 0:n.dispose)===N.dispose&&$.delete(e.apiKey),e.debug&&console.log("[sentient] disposed")},destroy(){var n;ae==null||ae(),Be=!0,Re=!0,r.destroy(),T.destroy(),d.destroy(),g.clear(),((n=$.get(e.apiKey))==null?void 0:n.dispose)===N.dispose&&$.delete(e.apiKey);try{localStorage.removeItem(ue+e.apiKey),localStorage.removeItem(We(e.apiKey)),localStorage.removeItem(je(e.apiKey))}catch(l){}e.debug&&console.log("[sentient] destroyed")}};if($.set(e.apiKey,{config:e,upgrade:null,dispose:N.dispose}),ae=dn(N,e.apiKey,n=>{te.then(()=>{Be||Ct.add(n)})}),e.debug){let n=window;n.__sentient&&(n.__sentient.client=N)}return N}export{ue as a,Se as b,he as c,Vt as d,He as e,kt as f,bt as g,qt as h,Rn as i,Bn as j,Dn as k,Pn as l,Ln as m,Mn as n,Kn as o,Nn as p,Gn as q,Fn as r,Un as s,$n as t,Wn as u,jn as v,zn as w,Hn as x,Qn as y,Jn as z,Vn as A,Xn as B,qn as C,Yn as D,Zn as E,eo as F,Yt as G,Zt as H,en as I,nn as J,on as K,Io as L,Ot as M,_o as N,pn as O};
2
+ //# sourceMappingURL=chunk-EVYMV2C6.mjs.map