@sentientui/core 0.11.2 → 0.12.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +8 -4
- package/dist/chunk-G6ZN7Q63.mjs +1 -0
- package/dist/index-graph.js +1 -1
- package/dist/index-graph.mjs +1 -1
- package/dist/index.d.cts +12 -0
- package/dist/index.d.ts +12 -0
- package/dist/index.js +1 -1
- package/dist/index.mjs +1 -1
- package/llms.txt +4 -2
- package/package.json +1 -1
- package/dist/chunk-X2URHWFL.mjs +0 -1
package/README.md
CHANGED
|
@@ -33,7 +33,7 @@ client.componentGoal('hero_headline', 'trial_started');
|
|
|
33
33
|
client.goal('trial_started', { plan: 'pro' });
|
|
34
34
|
```
|
|
35
35
|
|
|
36
|
-
`init()` returns a no-op client during SSR (`typeof window === 'undefined'`)
|
|
36
|
+
`init()` returns a no-op client during SSR (`typeof window === 'undefined'`) or when `consent` is `false`. When `apiKey` does not start with `pk_`, it returns a no-op client in production builds, or the keyless local-mode client in development builds (see "Keyless local mode" below). The hosted ingest URL (`https://api.sentient-ui.com/v1/events`) is built in — no URL configuration required.
|
|
37
37
|
|
|
38
38
|
## API
|
|
39
39
|
|
|
@@ -44,7 +44,7 @@ client.goal('trial_started', { plan: 'pro' });
|
|
|
44
44
|
| `apiKey` | `string` | Public API key (`pk_…`) from the SentientUI dashboard. |
|
|
45
45
|
| `context` | `'landing' \| 'ecommerce' \| 'saas' \| 'marketplace'` | Local label only — echoed in `debug` logs, never sent to the server. Analytics grouping comes from the project's context type configured in the dashboard. |
|
|
46
46
|
| `consent` | `boolean` *(default `true`)* | When `false`, returns a no-op client (no cookies, no events). **The default is `true`** — for GDPR-style opt-in, pass `false` until your banner is accepted (see `preConsentBehavior`). |
|
|
47
|
-
| `preConsentBehavior` | `'
|
|
47
|
+
| `preConsentBehavior` | `'control' \| 'statistical_winner'` | What to render while `consent` is `false`: `'control'` (the default — shows `variantIds[0]`), or the read-only statistical winner via `/v1/winner` (no session, no events). |
|
|
48
48
|
| `respectDoNotTrack` | `boolean` *(default `true`)* | Honors the browser DNT signal — overrides `consent: true` and blocks `grantConsent()`. |
|
|
49
49
|
| `initialAssignments` | `Record<string, string>` | SSR-preloaded assignments. Seeds the cache so `assign()` returns without a network call for listed code variants. (Managed-text components still fetch once when the seed carries no content.) |
|
|
50
50
|
| `sessionSegment` | `string` | Segment from SSR (`device:source`). Must match the value used in `preloadAssignments`. |
|
|
@@ -106,9 +106,13 @@ Synchronously returns the cached assignment, or `null` if not yet assigned. Use
|
|
|
106
106
|
|
|
107
107
|
Returns the current `GraphSnapshot` (page nodes captured by the optional graph scanner — see "Optional: graph mode" below). Permanently returns an empty snapshot on the lean client; graph mode must be enabled at `init` time.
|
|
108
108
|
|
|
109
|
+
### `client.dispose()`
|
|
110
|
+
|
|
111
|
+
Routine cleanup: stops the flush timer and unload listeners (with a final flush) but **keeps the visitor identity, decision snapshot, and retry bucket**. Use this when a component or provider that owns the client unmounts or re-initializes — the visitor must survive it. `<AdaptiveProvider>` calls it for you on cleanup.
|
|
112
|
+
|
|
109
113
|
### `client.destroy()`
|
|
110
114
|
|
|
111
|
-
|
|
115
|
+
Everything `dispose()` does, plus **deletion of the visitor identity** — the 365-day `_snt_uid` cookie, local/session storage keys, the decision snapshot, and the persisted retry bucket. This is a consent-revocation/forget-me teardown, not a page-unload cleanup: calling it on every unload makes each visit a brand-new visitor and defeats "Visit 1 learns, Visit 2 converts". For unload, do nothing — the SDK already flushes on `visibilitychange`/`beforeunload` automatically.
|
|
112
116
|
|
|
113
117
|
## SSR helpers
|
|
114
118
|
|
|
@@ -204,7 +208,7 @@ import { init } from '@sentientui/core/graph';
|
|
|
204
208
|
const client = init({ apiKey: 'pk_…', context: 'saas', graph: true });
|
|
205
209
|
```
|
|
206
210
|
|
|
207
|
-
A client created by the lean `init` can never activate graph mode later (`getGraph()` stays empty). The lean bundle is ~8 KB gzip (CI budget: 10 KB); graph adds
|
|
211
|
+
A client created by the lean `init` can never activate graph mode later (`getGraph()` stays empty). The lean bundle is ~8 KB gzip (CI budget: 10 KB); graph adds ~3–4 KB gzip on top of the lean bundle (combined CI budget: 16 KB).
|
|
208
212
|
|
|
209
213
|
> **Using `@sentientui/react`?** Don't import this entry yourself — pass the
|
|
210
214
|
> `enableGraph` prop to `AdaptiveProvider` / `AdaptiveRoot` instead. The provider
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{b as re,d as ie,e as ae,f as le,g as ce,j as de,k as Z,m as ue}from"./chunk-SVYHTU5Z.mjs";import{a as A,b as K}from"./chunk-HGGX55FR.mjs";var Le="_snt_uid";var G="_snt_uid";function Ne(){try{if(typeof crypto!="undefined"&&typeof crypto.randomUUID=="function")return crypto.randomUUID()}catch(t){}let e=()=>Math.floor(Math.random()*4294967295).toString(16).padStart(8,"0");return`${e()}-${e()}-${e()}-${e()}`}function Me(e){try{let t=document.cookie.match(new RegExp(`(?:^|; )${e}=([^;]*)`));return t?decodeURIComponent(t[1]):null}catch(t){return null}}function Ue(e,t,r){try{document.cookie=`${e}=${encodeURIComponent(t)}; max-age=${r}; SameSite=strict; path=/`}catch(d){}}function Ke(e){try{return localStorage.getItem(e)}catch(t){return null}}function Ge(e,t){try{return localStorage.setItem(e,t),!0}catch(r){return!1}}function $e(e){try{return sessionStorage.getItem(e)}catch(t){return null}}function Be(e,t){try{return sessionStorage.setItem(e,t),!0}catch(r){return!1}}function We(e){try{sessionStorage.removeItem(e)}catch(t){}}function je(e){try{return document.cookie=`${e}_probe=1; max-age=1; SameSite=strict; path=/`,/(?:^|; )_snt_uid_probe=1/.test(document.cookie)||document.cookie.indexOf(`${e}_probe=1`)!==-1}catch(t){return!1}}function Fe(e){try{localStorage.removeItem(e)}catch(t){}}function Je(e){try{document.cookie=`${e}=; max-age=0; SameSite=strict; path=/`}catch(t){}}var Qe={getSessionId:()=>null,isEphemeral:()=>!1,destroy:()=>{}};function ee(e){var a,g,m,h,S,E;if(typeof window=="undefined")return Qe;let t=(a=e==null?void 0:e.cookieName)!=null?a:Le,d=((g=e==null?void 0:e.cookieTTLDays)!=null?g:365)*24*60*60,u=(E=(S=(h=(m=Me(t))!=null?m:Ke(G))!=null?h:$e(G))!=null?S:e==null?void 0:e.ssrSessionId)!=null?E:Ne();Ue(t,u,d);let n=Ge(G,u),c=je(t),o=n?!1:Be(G,u),s=!n&&!c&&!o;return{getSessionId:()=>u,isEphemeral:()=>s,destroy:()=>{u=null,Je(t),Fe(G),We(G)}}}function pe(e){return`_snt_retry_${e.slice(0,12)}`}var Ye={push:()=>{},flush:()=>{},destroy:()=>{}};function Ve(e,t){try{let r=localStorage.getItem(t);if(!r)return[];let d=JSON.parse(r);return Array.isArray(d)?(localStorage.removeItem(t),d.slice(-e)):[]}catch(r){return[]}}function ge(e,t,r){try{let u=[...(()=>{try{let n=localStorage.getItem(r);if(!n)return[];let c=JSON.parse(n);return Array.isArray(c)?c:[]}catch(n){return[]}})(),...e].slice(-t);localStorage.setItem(r,JSON.stringify(u))}catch(d){}}function Ie(e){var Q,Y,V;if(typeof window=="undefined")return Ye;let t=(Q=e.flushIntervalMs)!=null?Q:5e3,r=(Y=e.maxBatchSize)!=null?Y:20,d=(V=e.maxRetrySize)!=null?V:100,u=e.ingestUrl,n=e.apiKey,c=pe(n),o=[],s=new Set,a=[],g=p=>{for(let y of p)m.delete(y),!s.has(y)&&(s.add(y),a.push(y));for(;a.length>500;){let y=a.shift();y&&s.delete(y)}},m=new Set,h=p=>{s.has(p.id)||m.has(p.id)||(m.add(p.id),o.push(p))},S=Ve(d,c);for(let p of S)h(p);let E=0,v=0,w=p=>{if(p.length===0)return;let y=JSON.stringify(p),_=p.map(l=>l.id),k;try{k=fetch(u,{method:"POST",keepalive:!0,body:y,headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`}})}catch(l){ge(p,d,c);for(let f of _)m.delete(f);v++,E=Date.now()+Math.min(6e4,1e3*2**Math.min(v,6));return}let i=l=>{if(l.ok||l.status>=400&&l.status<500&&l.status!==429){g(_),v=0,E=0;return}ge(p,d,c);for(let f of _)m.delete(f);v++,E=Date.now()+Math.min(6e4,1e3*2**Math.min(v,6))};k instanceof Promise?k.then(i).catch(()=>{ge(p,d,c);for(let l of _)m.delete(l);v++,E=Date.now()+Math.min(6e4,1e3*2**Math.min(v,6))}):i(k)},W=typeof TextEncoder!="undefined"?new TextEncoder:null,L=p=>W?W.encode(p).length:p.length,q=p=>{let y=[],_=2;for(let k of p){let i=L(JSON.stringify(k))+1;if(y.length>0&&_+i>57344||y.length>=r)break;y.push(k),_+=i}return y},b=()=>{try{if(Date.now()<E)return;for(;o.length>0;){let p=o.filter(_=>!s.has(_.id));if(o.length=0,p.length===0)break;let y=q(p);if(y.length===0)break;y.length<p.length&&o.push(...p.slice(y.length)),w(y)}}catch(p){}},j=!0,N=null;N=setInterval(()=>{j&&b()},t);let F=()=>{document.visibilityState==="hidden"&&b()},J=()=>{b()};return document.addEventListener("visibilitychange",F),window.addEventListener("beforeunload",J),{push(p){h(p),o.length>=r&&b()},flush:b,destroy(){j=!1,N!==null&&(clearInterval(N),N=null),document.removeEventListener("visibilitychange",F),window.removeEventListener("beforeunload",J),b()}}}var me="_snt_asgn_";function te(e,t){return`${e}:${t}`}function ze(e,t){return`${me}${encodeURIComponent(e)}:${encodeURIComponent(t)}`}function _e(e){let t=e.slice(me.length),r=t.indexOf(":");if(r<0)return null;try{return{componentId:decodeURIComponent(t.slice(0,r)),segment:decodeURIComponent(t.slice(r+1))}}catch(d){return null}}function fe(){try{let e=[];for(let t=0;t<localStorage.length;t++){let r=localStorage.key(t);r!=null&&r.startsWith(me)&&e.push(r)}return e}catch(e){return[]}}function xe(e=18e5){let t=new Map,r=u=>u.assignedAt+e<Date.now();return typeof window!="undefined"&&(()=>{for(let u of fe())try{let n=localStorage.getItem(u);if(!n)continue;let c=JSON.parse(n);if(r(c)){localStorage.removeItem(u);continue}let o=_e(u);if(!o)continue;t.set(te(o.componentId,o.segment),c)}catch(n){}})(),{get(u,n){let c=t.get(te(u,n));return c?r(c)?(t.delete(te(u,n)),null):c:null},set(u,n,c){let o=te(u,n);t.set(o,c);try{localStorage.setItem(ze(u,n),JSON.stringify(c))}catch(s){}},invalidate(u){let n=`${u}:`;for(let c of[...t.keys()])c.startsWith(n)&&t.delete(c);for(let c of fe()){let o=_e(c);if((o==null?void 0:o.componentId)===u)try{localStorage.removeItem(c)}catch(s){}}},clear(){t.clear();for(let u of fe())try{localStorage.removeItem(u)}catch(n){}}}}var $="_snt_snap:",He=["low","medium","high"];function ye(e){try{let t=localStorage.getItem($+e);if(!t)return null;let r=JSON.parse(t);return!r||typeof r!="object"||r.v!==1||typeof r.persona!="string"||typeof r.band!="string"||!He.includes(r.band)||typeof r.slots!="object"||r.slots===null||Array.isArray(r.slots)||!(r.layoutOrder===null||Array.isArray(r.layoutOrder))||typeof r.savedAt!="number"?null:r}catch(t){return null}}function H(e,t){try{localStorage.setItem($+e,JSON.stringify(t))}catch(r){}}function Xe(e){return"(function(){try{var r=localStorage.getItem("+JSON.stringify($+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 Oe}from"@sentientui/policy";import{confidenceBand as Se}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.",ke="[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.",Ae=!1,ne=!1;function qe(){var e;try{return(e=new URLSearchParams(window.location.search).get("sentient_persona"))!=null?e:void 0}catch(t){return}}function Re(e){var o;let t=ee({ssrSessionId:e.ssrSessionId}),r=(o=t.getSessionId())!=null?o:"local",d=qe(),u=import("@sentientui/core/local").then(s=>{let a=s;return a.LOCAL_ENGINE_AVAILABLE?(Ae||(Ae=!0,console.info(ke)),a):(ne||(ne=!0,console.error(he)),null)}).catch(()=>(ne||(ne=!0,console.error(he)),null)),n=null;function c(s){let a=document.documentElement;a.dataset.sentientPersona===void 0&&(a.dataset.sentientPersona=s.persona,a.dataset.sentientConfidence=Se(s.confidence))}return{isLocal:!0,async decide(s){var m,h,S;let a=await u;if(!a)return null;let g=a.createLocalEngine({sessionId:r,forcedPersona:d}).decide(s);return n=K(A({},g),{layoutOrder:(h=(m=g.layoutOrder)!=null?m:n==null?void 0:n.layoutOrder)!=null?h:null,slots:A(A({},(S=n==null?void 0:n.slots)!=null?S:{}),g.slots)}),H(e.apiKey||"local",{v:1,persona:n.persona,band:Se(n.confidence),slots:n.slots,layoutOrder:n.layoutOrder,savedAt:Date.now()}),c(g),g},getSlotResult(s){var a,g,m;return(m=(g=n==null?void 0:n.slots[s])!=null?g:(a=e.initialSlots)==null?void 0:a[s])!=null?m:null},getPersona(){return n?{persona:n.persona,confidence:n.confidence,band:Se(n.confidence)}:null},async assign(s,a){var h;let g=await u;return!g||!a||a.length===0?a!=null&&a[0]?{variantId:a[0],assignmentTtlMs:0}:null:{variantId:(h=g.createLocalEngine({sessionId:r,forcedPersona:d}).decide({components:[{id:s,variantIds:a}]}).assignments[s])!=null?h:a[0],assignmentTtlMs:0}},track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},getAssignment:()=>null,fetchWeights:()=>Promise.resolve([]),getGraph:()=>({pageNodes:[],capturedAt:0}),dispose:()=>{},destroy:()=>t.destroy()}}function Ze(e,t,r){var u;let d=[];{let o=!1,s=[],a=()=>{if(o)return;let g=Date.now();for(s.push(g);s.length>0&&g-s[0]>500;)s.shift();s.length>=3&&(o=!0,e("rage_click"))};t.addEventListener("click",a),d.push(()=>t.removeEventListener("click",a))}{let n=!1,c=o=>{if(n||!(o.target instanceof Node)||!t.contains(o.target)&&t!==o.target)return;n=!0;let s=typeof window!="undefined"?window.getSelection():null,a=s?s.toString().length:0;e("text_copy",{selectionLength:a})};document.addEventListener("copy",c),d.push(()=>document.removeEventListener("copy",c))}{let n=!1,c=!1,o=null,s=()=>{o!==null&&(clearTimeout(o),o=null)},a=()=>{n||!c||(s(),o=setTimeout(()=>{!n&&c&&(n=!0,e("scroll_hesitation"))},3e3))},g=()=>{s(),a()},m=S=>{for(let E of S)c=E.intersectionRatio>.3,c?a():s()};typeof process!="undefined"&&((u=process.env)==null?void 0:u.NODE_ENV)!=="production"&&(window.__lastIOCallback=m);let h=new IntersectionObserver(m,{threshold:[.3]});h.observe(t),window.addEventListener("scroll",g,{passive:!0}),d.push(()=>{h.disconnect(),window.removeEventListener("scroll",g),s()})}{let n=!1,c=r!=null?r:Date.now(),o=()=>{if(n||document.visibilityState!=="hidden")return;let s=Date.now()-c;s<15e3&&(n=!0,e("tab_loss",{timeOnPage:s}))};document.addEventListener("visibilitychange",o),d.push(()=>document.removeEventListener("visibilitychange",o))}return()=>{for(let n of d)n()}}var De="https://api.sentient-ui.com/v1/events",B=new Map,Te=null;function ve(){try{if(typeof crypto!="undefined"&&typeof crypto.randomUUID=="function")return crypto.randomUUID()}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 X={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 et(){try{let e={},t=new URLSearchParams(window.location.search);for(let[r,d]of t)r.startsWith("utm_")&&(e[r]=d);return e}catch(e){return{}}}function Ce(e){return e.replace(/\/events\/?$/,"")}function Pe(){return[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 xt(e){if(typeof window=="undefined")return;let t=e!=null?e:Te;if(!t){console.warn("[sentient] grantConsent() called before init()");return}let r=B.get(t);if(!r){console.warn("[sentient] grantConsent() called before init()");return}let{config:d,upgrade:u}=r;if(!u||d.respectDoNotTrack!==!1&&Pe())return;let n=nt(K(A({},d),{consent:!0}));u(n),B.set(t,{config:K(A({},d),{consent:!0}),upgrade:null})}function tt(e){var c;let t=Ce((c=e.ingestUrl)!=null?c:De),r={"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`},d={track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},getAssignment:()=>null,fetchWeights:()=>Promise.resolve([]),async assign(o,s,a){try{let g=new URLSearchParams({componentId:o});for(let S of s!=null?s:[])g.append("variantIds[]",S);let m=await fetch(`${t}/winner?${g.toString()}`,{headers:r});return m.ok?{variantId:(await m.json()).variantId,assignmentTtlMs:0}:s!=null&&s[0]?{variantId:s[0],assignmentTtlMs:0}:null}catch(g){return s!=null&&s[0]?{variantId:s[0],assignmentTtlMs:0}:null}},decide:()=>Promise.resolve(null),getSlotResult:()=>null,getPersona:()=>null,getGraph:()=>({pageNodes:[],capturedAt:0}),dispose:()=>{},destroy:()=>{}},u={track:o=>d.track(o),goal:(o,s,a,g)=>d.goal(o,s,a,g),componentGoal:(o,s,a)=>d.componentGoal(o,s,a),identify:o=>d.identify(o),getAssignment:(o,s)=>d.getAssignment(o,s),assign:(o,s,a,g)=>d.assign(o,s,a,g),decide:o=>d.decide(o),getSlotResult:o=>d.getSlotResult(o),getPersona:()=>d.getPersona(),fetchWeights:()=>d.fetchWeights(),getGraph:()=>d.getGraph(),dispose:()=>d.dispose(),destroy:()=>d.destroy()};function n(o){d=o}return{proxy:u,setInner:n}}function nt(e){var F,J,Q,Y,V,p,y,_,k;if(typeof window=="undefined")return X;Te=e.apiKey;let t=typeof e.apiKey=="string"&&e.apiKey.startsWith("pk_");if(e.localMode===!0||!t&&e.localMode!==!1)return B.set(e.apiKey||"local",{config:e,upgrade:null}),Re(e);let r=e.respectDoNotTrack!==!1&&Pe();if(e.consent===!1||r){if(e.preConsentBehavior==="statistical_winner"){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."),X;let{proxy:i,setInner:l}=tt(e);return B.set(e.apiKey,{config:e,upgrade:r?null:l}),i}return B.set(e.apiKey,{config:e,upgrade:null}),X}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."),X;if(e.ingestUrl==="")return console.warn("[sentient] init() called with an empty ingestUrl. SDK disabled."),X;let d=(F=e.ingestUrl)!=null?F:De,u=Date.now(),n=ee({ssrSessionId:e.ssrSessionId}),c=xe(),o=Ie({ingestUrl:d,apiKey:e.apiKey}),s=Ce(d),a={"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`},g=ie((J=navigator.userAgent)!=null?J:""),m=typeof window!="undefined"?window.location.origin:void 0,h=ae((Q=document.referrer)!=null?Q:"",m),S=(Y=e.sessionSegment)!=null?Y:`${g}:${h}`,E=new Map,v=new Map,w=null,W=i=>{for(let l of i)v.has(l.id)||v.set(l.id,Z(l))};if(e.initialSlots)for(let[i,l]of Object.entries(e.initialSlots))v.set(i,l);let L=ye(e.apiKey);if(L)for(let[i,l]of Object.entries(L.slots))v.has(i)||v.set(i,l);let q={low:.15,medium:.5,high:.85};if(e.initialPersona)w=A({},e.initialPersona);else{let i=document.documentElement.dataset;i.sentientPersona?w={persona:i.sentientPersona,confidence:(p=q[(V=i.sentientConfidence)!=null?V:"low"])!=null?p:.15}:L&&(w={persona:L.persona,confidence:(y=q[L.band])!=null?y:.15})}if(e.initialAssignments)for(let[i,l]of Object.entries(e.initialAssignments))c.set(i,S,{variantId:l,assignedAt:Date.now(),segment:S,confidence:1});let b=Promise.resolve(),j=n.getSessionId();if(j){let i=le((_=document.referrer)!=null?_:""),l=A(A({sessionId:j,deviceClass:g,trafficSource:h,referrerDomain:i,utmParams:et(),timeOfDay:ce(new Date),dayOfWeek:["sun","mon","tue","wed","thu","fri","sat"][new Date().getDay()],ephemeral:n.isEphemeral(),automation:typeof navigator!="undefined"&&navigator.webdriver===!0||re((k=navigator.userAgent)!=null?k:"")},e.userId?{userId:e.userId}:{}),e.country?{country:e.country}:{});try{b=fetch(`${s}/sessions`,{method:"POST",keepalive:!0,body:JSON.stringify(l),headers:a}).then(f=>{f.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")}).catch(()=>{})}catch(f){}}e.debug&&(console.log("[sentient] initialized",{context:e.context}),window.__sentient={client:null,queue:o});let N={goal(i,l={},f=1,R=0){let I=n.getSessionId();if(!I)return;let x=ve();b.then(()=>{fetch(`${s}/goals`,{method:"POST",keepalive:!0,body:JSON.stringify({sessionId:I,name:i,metadata:l,weight:f,stepIndex:R,goalId:x}),headers:a}).catch(()=>{})})},componentGoal(i,l,f){var O,P,D;let R=n.getSessionId();if(!R)return;let I=c.get(i,S),x=I?null:(O=v.get(i))!=null?O:null;if(!I&&x===null){e.debug&&console.warn(`[sentient] componentGoal("${i}"): no assignment or slot decision yet \u2014 render its <Adaptive>/adaptive hook or call assign()/decide() before recording a goal.`);return}let M=I?I.variantId:ue(x),C={id:ve(),sessionId:R,projectId:e.apiKey,componentId:i,variantId:M,eventType:"goal_achieved",goalType:l,payload:A({reward:(P=f==null?void 0:f.reward)!=null?P:1},(D=f==null?void 0:f.metadata)!=null?D:{}),timestamp:Date.now(),timeInSession:Date.now()-u};e.debug&&console.log("[sentient] componentGoal",C),b.then(()=>o.push(C))},identify(i){let l=n.getSessionId();l&&b.then(()=>{fetch(`${s}/sessions`,{method:"POST",keepalive:!0,body:JSON.stringify({sessionId:l,userId:i,ephemeral:n.isEphemeral()}),headers:a}).catch(()=>{})})},track(i){let l=n.getSessionId();if(!l)return;let f=K(A({},i),{id:ve(),sessionId:l,timestamp:Date.now(),timeInSession:Date.now()-u});e.debug&&console.log("[sentient] track",f),b.then(()=>o.push(f))},getAssignment(i,l){return c.get(i,l)},async assign(i,l,f,R){let I=n.getSessionId();if(!I)return null;let x=c.get(i,S);if(x&&(l!=null&&l.length||x.content!==void 0))return{variantId:x.variantId,assignmentTtlMs:0,content:x.content};let M=E.get(i);if(M)return M;let C=(async()=>{await b;try{let O={sessionId:I,componentId:i,variantIds:l};R!==void 0?O.agentDataByVariant=R:f!==void 0&&(O.agentData=f);let P=await fetch(`${s}/assign`,{method:"POST",body:JSON.stringify(O),headers:a});if(!P.ok)return null;let D=await P.json();return c.set(i,S,{variantId:D.variantId,assignedAt:Date.now(),segment:S,confidence:1,content:D.content}),D}catch(O){return null}finally{E.delete(i)}})();return E.set(i,C),C},async decide(i){var R,I,x,M,C,O,P,D,Ee,we;let l=n.getSessionId();if(!l)return null;let f=(R=i.slots)!=null?R:[];await b;try{let z={sessionId:l};i.sections&&i.sections.length>0&&(z.sections=i.sections.map(T=>({id:T}))),z.components=(I=i.components)!=null?I:[],f.length>0&&(z.slots=f.map(de));let be=await fetch(`${s}/decide`,{method:"POST",body:JSON.stringify(z),headers:a});if(!be.ok)return W(f),null;let U=await be.json(),se={};for(let T of f)se[T.id]=(M=(x=U.slots)==null?void 0:x[T.id])!=null?M:Z(T);for(let[T,oe]of Object.entries(se))v.set(T,oe);w={persona:(C=U.persona)!=null?C:"unknown",confidence:(O=U.confidence)!=null?O:0};for(let[T,oe]of Object.entries((P=U.assignments)!=null?P:{}))c.set(T,S,{variantId:oe,assignedAt:Date.now(),segment:S,confidence:1});return H(e.apiKey,{v:1,persona:w.persona,band:Oe(w.confidence),slots:Object.fromEntries(v),layoutOrder:(D=U.layoutOrder)!=null?D:null,savedAt:Date.now()}),{layoutOrder:(Ee=U.layoutOrder)!=null?Ee:null,assignments:(we=U.assignments)!=null?we:{},slots:se,persona:w.persona,confidence:w.confidence}}catch(z){return W(f),null}},getSlotResult(i){var l;return(l=v.get(i))!=null?l:null},getPersona(){return w?{persona:w.persona,confidence:w.confidence,band:Oe(w.confidence)}:null},async fetchWeights(){var i;try{let l=await fetch(`${s}/weights`,{headers:a});return l.ok?(i=(await l.json()).components)!=null?i:[]:[]}catch(l){return[]}},getGraph(){return{pageNodes:[],capturedAt:0}},dispose(){o.destroy(),e.debug&&console.log("[sentient] disposed")},destroy(){o.destroy(),n.destroy();try{localStorage.removeItem($+e.apiKey),localStorage.removeItem(pe(e.apiKey))}catch(i){}e.debug&&console.log("[sentient] destroyed")}};if(B.set(e.apiKey,{config:e,upgrade:null}),e.debug){let i=window;i.__sentient&&(i.__sentient.client=N)}return N}export{$ as a,ye as b,H as c,Xe as d,he as e,ke as f,Ze as g,Pe as h,xt as i,nt as j};
|
package/dist/index-graph.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var Qe=Object.create;var Z=Object.defineProperty,Ve=Object.defineProperties,Ye=Object.getOwnPropertyDescriptor,qe=Object.getOwnPropertyDescriptors,Xe=Object.getOwnPropertyNames,Re=Object.getOwnPropertySymbols,Ze=Object.getPrototypeOf,De=Object.prototype.hasOwnProperty,et=Object.prototype.propertyIsEnumerable;var Oe=(e,t,n)=>t in e?Z(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,b=(e,t)=>{for(var n in t||(t={}))De.call(t,n)&&Oe(e,n,t[n]);if(Re)for(var n of Re(t))et.call(t,n)&&Oe(e,n,t[n]);return e},$=(e,t)=>Ve(e,qe(t));var tt=(e,t)=>{for(var n in t)Z(e,n,{get:t[n],enumerable:!0})},ke=(e,t,n,d)=>{if(t&&typeof t=="object"||typeof t=="function")for(let c of Xe(t))!De.call(e,c)&&c!==n&&Z(e,c,{get:()=>t[c],enumerable:!(d=Ye(t,c))||d.enumerable});return e};var nt=(e,t,n)=>(n=e!=null?Qe(Ze(e)):{},ke(t||!e||!e.__esModule?Z(n,"default",{value:e,enumerable:!0}):n,e)),ot=e=>ke(Z({},"__esModule",{value:!0}),e);var zt={};tt(zt,{deriveSessionSegment:()=>he,detectDeviceClass:()=>B,detectTimeOfDay:()=>F,detectTrafficSource:()=>j,init:()=>Jt,referrerDomainFromReferer:()=>W});module.exports=ot(zt);var rt="_snt_uid";var K="_snt_uid";function st(){try{if(typeof crypto!="undefined"&&typeof crypto.randomUUID=="function")return crypto.randomUUID()}catch(t){}let e=()=>Math.floor(Math.random()*4294967295).toString(16).padStart(8,"0");return`${e()}-${e()}-${e()}-${e()}`}function it(e){try{let t=document.cookie.match(new RegExp(`(?:^|; )${e}=([^;]*)`));return t?decodeURIComponent(t[1]):null}catch(t){return null}}function at(e,t,n){try{document.cookie=`${e}=${encodeURIComponent(t)}; max-age=${n}; SameSite=strict; path=/`}catch(d){}}function ct(e){try{return localStorage.getItem(e)}catch(t){return null}}function dt(e,t){try{return localStorage.setItem(e,t),!0}catch(n){return!1}}function lt(e){try{return sessionStorage.getItem(e)}catch(t){return null}}function ut(e,t){try{return sessionStorage.setItem(e,t),!0}catch(n){return!1}}function gt(e){try{sessionStorage.removeItem(e)}catch(t){}}function pt(e){try{return document.cookie=`${e}_probe=1; max-age=1; SameSite=strict; path=/`,/(?:^|; )_snt_uid_probe=1/.test(document.cookie)||document.cookie.indexOf(`${e}_probe=1`)!==-1}catch(t){return!1}}function ft(e){try{localStorage.removeItem(e)}catch(t){}}function mt(e){try{document.cookie=`${e}=; max-age=0; SameSite=strict; path=/`}catch(t){}}var ht={getSessionId:()=>null,isEphemeral:()=>!1,destroy:()=>{}};function oe(e){var r,u,f,m,p,S;if(typeof window=="undefined")return ht;let t=(r=e==null?void 0:e.cookieName)!=null?r:rt,d=((u=e==null?void 0:e.cookieTTLDays)!=null?u:365)*24*60*60,c=(S=(p=(m=(f=it(t))!=null?f:ct(K))!=null?m:lt(K))!=null?p:e==null?void 0:e.ssrSessionId)!=null?S:st();at(t,c,d);let o=dt(K,c),i=pt(t),a=o?!1:ut(K,c),s=!o&&!i&&!a;return{getSessionId:()=>c,isEphemeral:()=>s,destroy:()=>{c=null,mt(t),ft(K),gt(K)}}}var yt={push:()=>{},flush:()=>{},destroy:()=>{}};function St(e,t){try{let n=localStorage.getItem(t);if(!n)return[];let d=JSON.parse(n);return Array.isArray(d)?(localStorage.removeItem(t),d.slice(-e)):[]}catch(n){return[]}}function pe(e,t,n){try{let c=[...(()=>{try{let o=localStorage.getItem(n);if(!o)return[];let i=JSON.parse(o);return Array.isArray(i)?i:[]}catch(o){return[]}})(),...e].slice(-t);localStorage.setItem(n,JSON.stringify(c))}catch(d){}}function Ne(e){var V,Y,q;if(typeof window=="undefined")return yt;let t=(V=e.flushIntervalMs)!=null?V:5e3,n=(Y=e.maxBatchSize)!=null?Y:20,d=(q=e.maxRetrySize)!=null?q:100,c=e.ingestUrl,o=e.apiKey,i=`_snt_retry_${o.slice(0,12)}`,a=[],s=new Set,r=[],u=h=>{for(let w of h)f.delete(w),!s.has(w)&&(s.add(w),r.push(w));for(;r.length>500;){let w=r.shift();w&&s.delete(w)}},f=new Set,m=h=>{s.has(h.id)||f.has(h.id)||(f.add(h.id),a.push(h))},p=St(d,i);for(let h of p)m(h);let S=0,v=0,E=h=>{if(h.length===0)return;let w=JSON.stringify(h),x=h.map(g=>g.id),_;try{_=fetch(c,{method:"POST",keepalive:!0,body:w,headers:{"Content-Type":"application/json",Authorization:`Bearer ${o}`}})}catch(g){pe(h,d,i);for(let y of x)f.delete(y);v++,S=Date.now()+Math.min(6e4,1e3*2**Math.min(v,6));return}let l=g=>{if(g.ok||g.status>=400&&g.status<500&&g.status!==429){u(x),v=0,S=0;return}pe(h,d,i);for(let y of x)f.delete(y);v++,S=Date.now()+Math.min(6e4,1e3*2**Math.min(v,6))};_ instanceof Promise?_.then(l).catch(()=>{pe(h,d,i);for(let g of x)f.delete(g);v++,S=Date.now()+Math.min(6e4,1e3*2**Math.min(v,6))}):l(_)},k=typeof TextEncoder!="undefined"?new TextEncoder:null,L=h=>k?k.encode(h).length:h.length,ne=h=>{let w=[],x=2;for(let _ of h){let l=L(JSON.stringify(_))+1;if(w.length>0&&x+l>57344||w.length>=n)break;w.push(_),x+=l}return w},I=()=>{try{if(Date.now()<S)return;for(;a.length>0;){let h=a.filter(x=>!s.has(x.id));if(a.length=0,h.length===0)break;let w=ne(h);if(w.length===0)break;w.length<h.length&&a.push(...h.slice(w.length)),E(w)}}catch(h){}},z=!0,M=null;M=setInterval(()=>{z&&I()},t);let H=()=>{document.visibilityState==="hidden"&&I()},Q=()=>{I()};return document.addEventListener("visibilitychange",H),window.addEventListener("beforeunload",Q),{push(h){m(h),a.length>=n&&I()},flush:I,destroy(){z=!1,M!==null&&(clearInterval(M),M=null),document.removeEventListener("visibilitychange",H),window.removeEventListener("beforeunload",Q),I()}}}var me="_snt_asgn_";function re(e,t){return`${e}:${t}`}function vt(e,t){return`${me}${encodeURIComponent(e)}:${encodeURIComponent(t)}`}function Pe(e){let t=e.slice(me.length),n=t.indexOf(":");if(n<0)return null;try{return{componentId:decodeURIComponent(t.slice(0,n)),segment:decodeURIComponent(t.slice(n+1))}}catch(d){return null}}function fe(){try{let e=[];for(let t=0;t<localStorage.length;t++){let n=localStorage.key(t);n!=null&&n.startsWith(me)&&e.push(n)}return e}catch(e){return[]}}function Le(e=18e5){let t=new Map,n=c=>c.assignedAt+e<Date.now();return typeof window!="undefined"&&(()=>{for(let c of fe())try{let o=localStorage.getItem(c);if(!o)continue;let i=JSON.parse(o);if(n(i)){localStorage.removeItem(c);continue}let a=Pe(c);if(!a)continue;t.set(re(a.componentId,a.segment),i)}catch(o){}})(),{get(c,o){let i=t.get(re(c,o));return i?n(i)?(t.delete(re(c,o)),null):i:null},set(c,o,i){let a=re(c,o);t.set(a,i);try{localStorage.setItem(vt(c,o),JSON.stringify(i))}catch(s){}},invalidate(c){let o=`${c}:`;for(let i of[...t.keys()])i.startsWith(o)&&t.delete(i);for(let i of fe()){let a=Pe(i);if((a==null?void 0:a.componentId)===c)try{localStorage.removeItem(i)}catch(s){}}},clear(){t.clear();for(let c of fe())try{localStorage.removeItem(c)}catch(o){}}}}var Me=["GPTBot","ChatGPT-User","OAI-SearchBot","ClaudeBot","Claude-User","Claude-SearchBot","PerplexityBot","Perplexity-User","Google-Extended","Applebot-Extended","Meta-ExternalAgent","Bytespider","CCBot","Amazonbot","cohere-ai","Diffbot"];function se(e){return Ue(e)!==null}function Ue(e){var n;if(!e)return null;let t=e.toLowerCase();return(n=Me.find(d=>t.includes(d.toLowerCase())))!=null?n:null}function B(e){let t=e.toLowerCase();return/ipad|tablet|playbook|kindle|silk/.test(t)?"tablet":/mobi|iphone|ipod|android.*mobile|phone/.test(t)?"mobile":"desktop"}function j(e,t){if(!e)return"direct";try{let n=new URL(e);if(t)try{if(new URL(t).host===n.host)return"direct"}catch(c){}let d=n.hostname.toLowerCase();return/(^|\.)(google|bing|duckduckgo|yahoo)\./.test(d)?"search":/(^|\.)(twitter|x\.com|facebook|linkedin|reddit|t\.co)/.test(d)?"social":"referral"}catch(n){return"direct"}}function W(e){if(!e)return null;try{return new URL(e).hostname}catch(t){return null}}function F(e){let t=e.getHours();return t<6?"night":t<12?"morning":t<18?"afternoon":"evening"}function he(e){let t=wt("__segment__",e);return`${t.deviceClass}:${t.trafficSource}`}function wt(e,t){var o,i,a,s,r,u,f;let n=(i=(o=t==null?void 0:t.userAgent)==null?void 0:o.trim())!=null?i:"",d=(s=(a=t==null?void 0:t.referer)==null?void 0:a.trim())!=null?s:"",c=(r=t==null?void 0:t.now)!=null?r:new Date;return{sessionId:e,ephemeral:!1,utmParams:(u=t==null?void 0:t.utmParams)!=null?u:{},deviceClass:n?B(n):"desktop",trafficSource:d?j(d,t==null?void 0:t.appOrigin):"direct",referrerDomain:W(d),timeOfDay:F(c),dayOfWeek:(f=["sun","mon","tue","wed","thu","fri","sat"][c.getDay()])!=null?f:"sun",automation:(t==null?void 0:t.webdriver)===!0||se(n)}}var J=require("@sentientui/policy");function ie(e){return b(b(b({id:e.id},e.arms?{arms:[...e.arms]}:{}),e.dims?{dims:Object.fromEntries(Object.entries(e.dims).map(([t,n])=>[t,[...n]]))}:{}),e.baseline!==void 0?{baseline:e.baseline}:{})}function ae(e){let t=ie(e);return(0,J.slotResultFor)(t,(0,J.slotBaselineArm)(t))}function ye(e){return typeof e=="string"?e:(0,J.canonicalArm)(e)}var Se="_snt_snap:",Et=["low","medium","high"];function ve(e){try{let t=localStorage.getItem(Se+e);if(!t)return null;let n=JSON.parse(t);return!n||typeof n!="object"||n.v!==1||typeof n.persona!="string"||typeof n.band!="string"||!Et.includes(n.band)||typeof n.slots!="object"||n.slots===null||Array.isArray(n.slots)||!(n.layoutOrder===null||Array.isArray(n.layoutOrder))||typeof n.savedAt!="number"?null:n}catch(t){return null}}function ee(e,t){try{localStorage.setItem(Se+e,JSON.stringify(t))}catch(n){}}var be=require("@sentientui/policy");var de=require("@sentientui/policy");var we="[sentient] No API key configured \u2014 nothing is being learned. Set NEXT_PUBLIC_SENTIENT_API_KEY or pass localMode: true for local development.",$e="[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.",Ge=!1,ce=!1;function bt(){var e;try{return(e=new URLSearchParams(window.location.search).get("sentient_persona"))!=null?e:void 0}catch(t){return}}function Ke(e){var a;let t=oe({ssrSessionId:e.ssrSessionId}),n=(a=t.getSessionId())!=null?a:"local",d=bt(),c=import("@sentientui/core/local").then(s=>{let r=s;return r.LOCAL_ENGINE_AVAILABLE?(Ge||(Ge=!0,console.info($e)),r):(ce||(ce=!0,console.error(we)),null)}).catch(()=>(ce||(ce=!0,console.error(we)),null)),o=null;function i(s){let r=document.documentElement;r.dataset.sentientPersona===void 0&&(r.dataset.sentientPersona=s.persona,r.dataset.sentientConfidence=(0,de.confidenceBand)(s.confidence))}return{isLocal:!0,async decide(s){var f,m,p;let r=await c;if(!r)return null;let u=r.createLocalEngine({sessionId:n,forcedPersona:d}).decide(s);return o=$(b({},u),{layoutOrder:(m=(f=u.layoutOrder)!=null?f:o==null?void 0:o.layoutOrder)!=null?m:null,slots:b(b({},(p=o==null?void 0:o.slots)!=null?p:{}),u.slots)}),ee(e.apiKey||"local",{v:1,persona:o.persona,band:(0,de.confidenceBand)(o.confidence),slots:o.slots,layoutOrder:o.layoutOrder,savedAt:Date.now()}),i(u),u},getSlotResult(s){var r,u,f;return(f=(u=o==null?void 0:o.slots[s])!=null?u:(r=e.initialSlots)==null?void 0:r[s])!=null?f:null},getPersona(){return o?{persona:o.persona,confidence:o.confidence,band:(0,de.confidenceBand)(o.confidence)}:null},async assign(s,r){var m;let u=await c;return!u||!r||r.length===0?r!=null&&r[0]?{variantId:r[0],assignmentTtlMs:0}:null:{variantId:(m=u.createLocalEngine({sessionId:n,forcedPersona:d}).decide({components:[{id:s,variantIds:r}]}).assignments[s])!=null?m:r[0],assignmentTtlMs:0}},track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},getAssignment:()=>null,fetchWeights:()=>Promise.resolve([]),getGraph:()=>({pageNodes:[],capturedAt:0}),destroy:()=>t.destroy()}}var Be="https://api.sentient-ui.com/v1/events",le=new Map,It=null;function Ee(){try{if(typeof crypto!="undefined"&&typeof crypto.randomUUID=="function")return crypto.randomUUID()}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 te={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}),destroy:()=>{}};function Ct(){try{let e={},t=new URLSearchParams(window.location.search);for(let[n,d]of t)n.startsWith("utm_")&&(e[n]=d);return e}catch(e){return{}}}function je(e){return e.replace(/\/events\/?$/,"")}function xt(){return[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 At(e){var i;let t=je((i=e.ingestUrl)!=null?i:Be),n={"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`},d={track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},getAssignment:()=>null,fetchWeights:()=>Promise.resolve([]),async assign(a,s,r){try{let u=new URLSearchParams({componentId:a});for(let p of s!=null?s:[])u.append("variantIds[]",p);let f=await fetch(`${t}/winner?${u.toString()}`,{headers:n});return f.ok?{variantId:(await f.json()).variantId,assignmentTtlMs:0}:s!=null&&s[0]?{variantId:s[0],assignmentTtlMs:0}:null}catch(u){return s!=null&&s[0]?{variantId:s[0],assignmentTtlMs:0}:null}},decide:()=>Promise.resolve(null),getSlotResult:()=>null,getPersona:()=>null,getGraph:()=>({pageNodes:[],capturedAt:0}),destroy:()=>{}},c={track:a=>d.track(a),goal:(a,s,r,u)=>d.goal(a,s,r,u),componentGoal:(a,s,r)=>d.componentGoal(a,s,r),identify:a=>d.identify(a),getAssignment:(a,s)=>d.getAssignment(a,s),assign:(a,s,r,u)=>d.assign(a,s,r,u),decide:a=>d.decide(a),getSlotResult:a=>d.getSlotResult(a),getPersona:()=>d.getPersona(),fetchWeights:()=>d.fetchWeights(),getGraph:()=>d.getGraph(),destroy:()=>d.destroy()};function o(a){d=a}return{proxy:c,setInner:o}}function We(e){var H,Q,V,Y,q,h,w,x,_;if(typeof window=="undefined")return te;It=e.apiKey;let t=typeof e.apiKey=="string"&&e.apiKey.startsWith("pk_");if(e.localMode===!0||!t&&e.localMode!==!1)return le.set(e.apiKey||"local",{config:e,upgrade:null}),Ke(e);let n=e.respectDoNotTrack!==!1&&xt();if(e.consent===!1||n){if(e.preConsentBehavior==="statistical_winner"){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."),te;let{proxy:l,setInner:g}=At(e);return le.set(e.apiKey,{config:e,upgrade:n?null:g}),l}return le.set(e.apiKey,{config:e,upgrade:null}),te}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."),te;if(e.ingestUrl==="")return console.warn("[sentient] init() called with an empty ingestUrl. SDK disabled."),te;let d=(H=e.ingestUrl)!=null?H:Be,c=Date.now(),o=oe({ssrSessionId:e.ssrSessionId}),i=Le(),a=Ne({ingestUrl:d,apiKey:e.apiKey}),s=je(d),r={"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`},u=B((Q=navigator.userAgent)!=null?Q:""),f=typeof window!="undefined"?window.location.origin:void 0,m=j((V=document.referrer)!=null?V:"",f),p=(Y=e.sessionSegment)!=null?Y:`${u}:${m}`,S=new Map,v=new Map,E=null,k=l=>{for(let g of l)v.has(g.id)||v.set(g.id,ae(g))};if(e.initialSlots)for(let[l,g]of Object.entries(e.initialSlots))v.set(l,g);let L=ve(e.apiKey);if(L)for(let[l,g]of Object.entries(L.slots))v.has(l)||v.set(l,g);let ne={low:.15,medium:.5,high:.85};if(e.initialPersona)E=b({},e.initialPersona);else{let l=document.documentElement.dataset;l.sentientPersona?E={persona:l.sentientPersona,confidence:(h=ne[(q=l.sentientConfidence)!=null?q:"low"])!=null?h:.15}:L&&(E={persona:L.persona,confidence:(w=ne[L.band])!=null?w:.15})}if(e.initialAssignments)for(let[l,g]of Object.entries(e.initialAssignments))i.set(l,p,{variantId:g,assignedAt:Date.now(),segment:p,confidence:1});let I=Promise.resolve(),z=o.getSessionId();if(z){let l=W((x=document.referrer)!=null?x:""),g=b(b({sessionId:z,deviceClass:u,trafficSource:m,referrerDomain:l,utmParams:Ct(),timeOfDay:F(new Date),dayOfWeek:["sun","mon","tue","wed","thu","fri","sat"][new Date().getDay()],ephemeral:o.isEphemeral(),automation:typeof navigator!="undefined"&&navigator.webdriver===!0||se((_=navigator.userAgent)!=null?_:"")},e.userId?{userId:e.userId}:{}),e.country?{country:e.country}:{});try{I=fetch(`${s}/sessions`,{method:"POST",keepalive:!0,body:JSON.stringify(g),headers:r}).then(y=>{y.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")}).catch(()=>{})}catch(y){}}e.debug&&(console.log("[sentient] initialized",{context:e.context}),window.__sentient={client:null,queue:a});let M={goal(l,g={},y=1,T=0){let C=o.getSessionId();if(!C)return;let A=Ee();I.then(()=>{fetch(`${s}/goals`,{method:"POST",keepalive:!0,body:JSON.stringify({sessionId:C,name:l,metadata:g,weight:y,stepIndex:T,goalId:A}),headers:r}).catch(()=>{})})},componentGoal(l,g,y){var R,P,O;let T=o.getSessionId();if(!T)return;let C=i.get(l,p),A=C?null:(R=v.get(l))!=null?R:null;if(!C&&A===null){e.debug&&console.warn(`[sentient] componentGoal("${l}"): no assignment or slot decision yet \u2014 render its <Adaptive>/adaptive hook or call assign()/decide() before recording a goal.`);return}let U=C?C.variantId:ye(A),N={id:Ee(),sessionId:T,projectId:e.apiKey,componentId:l,variantId:U,eventType:"goal_achieved",goalType:g,payload:b({reward:(P=y==null?void 0:y.reward)!=null?P:1},(O=y==null?void 0:y.metadata)!=null?O:{}),timestamp:Date.now(),timeInSession:Date.now()-c};e.debug&&console.log("[sentient] componentGoal",N),I.then(()=>a.push(N))},identify(l){let g=o.getSessionId();g&&I.then(()=>{fetch(`${s}/sessions`,{method:"POST",keepalive:!0,body:JSON.stringify({sessionId:g,userId:l,ephemeral:o.isEphemeral()}),headers:r}).catch(()=>{})})},track(l){let g=o.getSessionId();if(!g)return;let y=$(b({},l),{id:Ee(),sessionId:g,timestamp:Date.now(),timeInSession:Date.now()-c});e.debug&&console.log("[sentient] track",y),I.then(()=>a.push(y))},getAssignment(l,g){return i.get(l,g)},async assign(l,g,y,T){let C=o.getSessionId();if(!C)return null;let A=i.get(l,p);if(A&&(g!=null&&g.length||A.content!==void 0))return{variantId:A.variantId,assignmentTtlMs:0,content:A.content};let U=S.get(l);if(U)return U;let N=(async()=>{await I;try{let R={sessionId:C,componentId:l,variantIds:g};T!==void 0?R.agentDataByVariant=T:y!==void 0&&(R.agentData=y);let P=await fetch(`${s}/assign`,{method:"POST",body:JSON.stringify(R),headers:r});if(!P.ok)return null;let O=await P.json();return i.set(l,p,{variantId:O.variantId,assignedAt:Date.now(),segment:p,confidence:1,content:O.content}),O}catch(R){return null}finally{S.delete(l)}})();return S.set(l,N),N},async decide(l){var T,C,A,U,N,R,P,O,Ae,_e;let g=o.getSessionId();if(!g)return null;let y=(T=l.slots)!=null?T:[];await I;try{let X={sessionId:g};l.sections&&l.sections.length>0&&(X.sections=l.sections.map(D=>({id:D}))),X.components=(C=l.components)!=null?C:[],y.length>0&&(X.slots=y.map(ie));let Te=await fetch(`${s}/decide`,{method:"POST",body:JSON.stringify(X),headers:r});if(!Te.ok)return k(y),null;let G=await Te.json(),ue={};for(let D of y)ue[D.id]=(U=(A=G.slots)==null?void 0:A[D.id])!=null?U:ae(D);for(let[D,ge]of Object.entries(ue))v.set(D,ge);E={persona:(N=G.persona)!=null?N:"unknown",confidence:(R=G.confidence)!=null?R:0};for(let[D,ge]of Object.entries((P=G.assignments)!=null?P:{}))i.set(D,p,{variantId:ge,assignedAt:Date.now(),segment:p,confidence:1});return ee(e.apiKey,{v:1,persona:E.persona,band:(0,be.confidenceBand)(E.confidence),slots:Object.fromEntries(v),layoutOrder:(O=G.layoutOrder)!=null?O:null,savedAt:Date.now()}),{layoutOrder:(Ae=G.layoutOrder)!=null?Ae:null,assignments:(_e=G.assignments)!=null?_e:{},slots:ue,persona:E.persona,confidence:E.confidence}}catch(X){return k(y),null}},getSlotResult(l){var g;return(g=v.get(l))!=null?g:null},getPersona(){return E?{persona:E.persona,confidence:E.confidence,band:(0,be.confidenceBand)(E.confidence)}:null},async fetchWeights(){var l;try{let g=await fetch(`${s}/weights`,{headers:r});return g.ok?(l=(await g.json()).components)!=null?l:[]:[]}catch(g){return[]}},getGraph(){return{pageNodes:[],capturedAt:0}},destroy(){a.destroy(),o.destroy(),e.debug&&console.log("[sentient] destroyed")}};if(le.set(e.apiKey,{config:e,upgrade:null}),e.debug){let l=window;l.__sentient&&(l.__sentient.client=M)}return M}var _t=new Set(["SECTION","ARTICLE","MAIN","DIV"]),Tt="h1, h2, h3",Rt={scan:async()=>({nodes:[],edges:[],scannedAt:0}),observe:()=>{},getProminenceScore:()=>0,destroy:()=>{}};function Ie(e,t,n){return n<=t?0:Math.max(0,Math.min(1,(e-t)/(n-t)))}function Ot(e){var t,n,d;try{let c=e;for(let o of Object.keys(c)){if(!o.startsWith("__reactFiber")&&!o.startsWith("__reactInternalInstance"))continue;let i=c[o],a=(d=(t=i==null?void 0:i.type)==null?void 0:t.displayName)!=null?d:(n=i==null?void 0:i.type)==null?void 0:n.name;if(a&&a.length>1)return a}}catch(c){}}function Dt(e){let t={};for(let n of Array.from(e.attributes))n.name.startsWith("data-")&&(t[n.name]=n.value);return t}function kt(e){let t=e.getAttribute("data-sentient-type");if(t)return t;let n=e.getAttribute("role");return n||"generic"}function Nt(e){var t,n;return(n=(t=e.getAttribute("data-sentient-id"))!=null?t:e.getAttribute("id"))!=null?n:e.tagName.toLowerCase()}function Pt(e){let t=0,n=e.parentElement;for(;n;)t++,n=n.parentElement;return t}function Ce(e,t){var d,c,o;let n=e.querySelector(Tt);return{componentId:Nt(e),semanticType:kt(e),ariaLabel:(d=e.getAttribute("aria-label"))!=null?d:void 0,headingText:(o=(c=n==null?void 0:n.textContent)==null?void 0:c.trim())!=null?o:void 0,isAboveFold:e.getBoundingClientRect().top<window.innerHeight,prominenceScore:t(e),depth:Pt(e),reactComponentName:Ot(e),dataAttributes:Dt(e)}}function Fe(e){var o;let t=[],n=new Set,d="__root__",c=new Map;for(let[i,a]of e){let s=i.parentElement,r=d;for(;s;){if(e.has(s)){r=e.get(s);let f=e.get(i),m=`${r}->${f}`;!n.has(m)&&r!==f&&(n.add(m),t.push({fromComponentId:r,toComponentId:f,weight:.6}));break}s=s.parentElement}let u=(o=c.get(r))!=null?o:[];u.push(i),c.set(r,u)}for(let i of c.values())if(!(i.length<2))for(let a=0;a<i.length;a++)for(let s=a+1;s<i.length;s++){let r=e.get(i[a]),u=e.get(i[s]);if(r===u)continue;let f=`${r}->${u}::sib`,m=`${u}->${r}::sib`;n.has(f)||(n.add(f),t.push({fromComponentId:r,toComponentId:u,weight:.3})),n.has(m)||(n.add(m),t.push({fromComponentId:u,toComponentId:r,weight:.3}))}return t}function Lt(e){let t=[],n=new Set,d=new Map;return document.querySelectorAll("[data-sentient-id]").forEach(i=>{if(i instanceof Element&&!n.has(i)){n.add(i);let a=Ce(i,e);t.push(a),d.set(i,a.componentId)}}),document.querySelectorAll("section, article, main, aside").forEach(i=>{if(!(i instanceof Element)||n.has(i))return;let a=i.hasAttribute("aria-label"),s=i.hasAttribute("data-sentient-id");if(!a&&!s)return;n.add(i);let r=Ce(i,e);t.push(r),d.set(i,r.componentId)}),{nodes:t,edges:Fe(d)}}function Je(){if(typeof window=="undefined")return Rt;let e=null,t=0,n=null,d=a=>{try{let s=window.getComputedStyle(a),r=parseFloat(s.fontSize)||12,u=parseFloat(s.zIndex)||0,f=a.getBoundingClientRect(),m=Math.max(f.top,0),p=window.innerHeight||1,S=1/(m/p+1),v=Ie(r,12,48)*.4+Ie(S,0,1)*.4+Ie(u,0,100)*.2;return Math.max(0,Math.min(1,v))}catch(s){return .5}};return{scan:()=>new Promise(a=>{let s=()=>{let{nodes:r,edges:u}=Lt(d);a({nodes:r,edges:u,scannedAt:Date.now()})};try{typeof requestIdleCallback=="function"?t=requestIdleCallback(s,{timeout:100}):s()}catch(r){s()}}),observe:a=>{n=a;try{e=new MutationObserver(s=>{let r=[],u=new Map;for(let f of s)f.type==="childList"&&f.addedNodes.forEach(m=>{if(!(m instanceof Element)||!_t.has(m.tagName))return;let p=m.hasAttribute("data-sentient-id"),S=m.hasAttribute("aria-label");if(!p&&!S)return;let v=Ce(m,d);r.push(v),u.set(m,v.componentId)});r.length>0&&n&&n({nodes:r,edges:Fe(u),addedAt:Date.now()})}),e.observe(document.body,{childList:!0,subtree:!0})}catch(s){}},getProminenceScore:d,destroy:()=>{if(e&&(e.disconnect(),e=null),t&&typeof cancelIdleCallback=="function")try{cancelIdleCallback(t)}catch(a){}t=0,n=null}}}var xe="_snt_graph_nodes",ze="_snt_graph_edges",Mt={pricing:["features","faq"],features:["pricing"],faq:["pricing"],social_proof:["cta"],cta:["social_proof","hero","trust"],hero:["cta"],comparison:["pricing"],trust:["cta"]};function Ut(e){var t;return(t=Mt[e])!=null?t:[]}function Gt(e,t){try{let n=localStorage.getItem(e);return n?JSON.parse(n):t}catch(n){return t}}function $t(e,t){try{localStorage.setItem(e,JSON.stringify(t))}catch(n){}}var Kt=new Set(["pricing","hero","social_proof","cta","features","faq","comparison","trust","navigation","generic"]);function Bt(e){return Kt.has(e)?e:"generic"}function jt(e,t,n){let d=`${e}:${t}:${n.join(",")}`,c=5381;for(let o=0;o<d.length;o++)c=(c<<5)+c+d.charCodeAt(o)&4294967295;return(c>>>0).toString(16).padStart(8,"0")}function He(e){let t=new Map,n=new Map,d=()=>{typeof window!="undefined"&&$t(xe,[...t.values()])},c=o=>{var i;try{let a=JSON.parse(o);t.clear();for(let s of(i=a.pageNodes)!=null?i:[])t.set(s.componentId,s)}catch(a){}};if(typeof window!="undefined"){let o=Gt(xe,[]);for(let i of o)t.set(i.componentId,i);try{localStorage.removeItem(ze)}catch(i){}}return{addPageNode(o){t.set(o.componentId,o),d()},addStructuralEdge(o){let i=`${o.fromComponentId}->${o.toComponentId}`;n.set(i,o)},syncOnce(){var i,a;if(!(e!=null&&e.syncUrl)||typeof window=="undefined")return;let o=[...t.values()];if(o.length!==0)try{let s=new Map;for(let p of o){let S=(i=s.get(p.semanticType))!=null?i:[];S.push(p),s.set(p.semanticType,S)}let r=[],u=new Set;for(let p of o)for(let S of Ut(p.semanticType)){let v=(a=s.get(S))!=null?a:[];for(let E of v){if(E.componentId===p.componentId)continue;let k=`semantic:${p.componentId}->${E.componentId}`;u.has(k)||(u.add(k),r.push({fromComponentId:p.componentId,toComponentId:E.componentId,type:"semantic",weight:.4,confidence:.9}))}}let f=new Set(o.map(p=>p.componentId));for(let p of n.values()){if(!f.has(p.fromComponentId)||!f.has(p.toComponentId))continue;let S=`structural:${p.fromComponentId}->${p.toComponentId}`;u.has(S)||(u.add(S),r.push({fromComponentId:p.fromComponentId,toComponentId:p.toComponentId,type:"structural",weight:p.weight,confidence:1}))}let m={pageUrl:window.location.href,nodes:o.map(p=>{let S=Bt(p.semanticType);return{componentId:p.componentId,semanticType:S,answers:p.answers,contentHash:jt(p.componentId,S,p.answers),prominenceScore:p.prominenceScore,depthInPage:p.depth}}),edges:r};fetch(e.syncUrl,{method:"POST",keepalive:!0,headers:b({"Content-Type":"application/json"},e.apiKey?{Authorization:`Bearer ${e.apiKey}`}:{}),body:JSON.stringify(m)}).catch(()=>{})}catch(s){}},snapshot(){return{pageNodes:[...t.values()],capturedAt:Date.now()}},serialize(){return JSON.stringify({pageNodes:[...t.values()]})},restore:c,destroy(){if(typeof window!="undefined")try{localStorage.removeItem(xe),localStorage.removeItem(ze)}catch(o){}}}}var Wt="https://api.sentient-ui.com/v1/events";function Ft(){try{let e=document.cookie.match(/(?:^|; )_snt_uid=([^;]*)/);return e?decodeURIComponent(e[1]):void 0}catch(e){return}}function Jt(e){var a;let t=We(e);if(!e.graph||typeof window=="undefined")return t;let n=Je(),d=(a=e.ingestUrl)!=null?a:Wt,c=He({syncUrl:d.replace(/\/events\/?$/,"/graph/sync"),apiKey:e.apiKey,projectId:e.apiKey,sessionId:Ft()});try{let s=localStorage.getItem("_snt_graph_nodes");s&&c.restore(JSON.stringify({pageNodes:JSON.parse(s)}))}catch(s){}n.scan().then(s=>{for(let r of s.nodes)c.addPageNode({id:r.componentId,componentId:r.componentId,semanticType:r.semanticType,answers:r.headingText?[r.headingText]:[],prominenceScore:r.prominenceScore,depth:r.depth});for(let r of s.edges)c.addStructuralEdge(r);c.syncOnce()});let o=null,i=()=>{o!==null&&clearTimeout(o),o=setTimeout(()=>{o=null,c.syncOnce()},500)};return n.observe(s=>{for(let r of s.nodes)c.addPageNode({id:r.componentId,componentId:r.componentId,semanticType:r.semanticType,answers:r.headingText?[r.headingText]:[],prominenceScore:r.prominenceScore,depth:r.depth});for(let r of s.edges)c.addStructuralEdge(r);i()}),$(b({},t),{getGraph:()=>c.snapshot(),destroy:()=>{o!==null&&clearTimeout(o),n.destroy(),c.destroy(),t.destroy()}})}0&&(module.exports={deriveSessionSegment,detectDeviceClass,detectTimeOfDay,detectTrafficSource,init,referrerDomainFromReferer});
|
|
1
|
+
"use strict";var Ye=Object.create;var Z=Object.defineProperty,Ve=Object.defineProperties,qe=Object.getOwnPropertyDescriptor,Xe=Object.getOwnPropertyDescriptors,Ze=Object.getOwnPropertyNames,Oe=Object.getOwnPropertySymbols,et=Object.getPrototypeOf,ke=Object.prototype.hasOwnProperty,tt=Object.prototype.propertyIsEnumerable;var De=(e,t,n)=>t in e?Z(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,b=(e,t)=>{for(var n in t||(t={}))ke.call(t,n)&&De(e,n,t[n]);if(Oe)for(var n of Oe(t))tt.call(t,n)&&De(e,n,t[n]);return e},K=(e,t)=>Ve(e,Xe(t));var nt=(e,t)=>{for(var n in t)Z(e,n,{get:t[n],enumerable:!0})},Ne=(e,t,n,d)=>{if(t&&typeof t=="object"||typeof t=="function")for(let c of Ze(t))!ke.call(e,c)&&c!==n&&Z(e,c,{get:()=>t[c],enumerable:!(d=qe(t,c))||d.enumerable});return e};var ot=(e,t,n)=>(n=e!=null?Ye(et(e)):{},Ne(t||!e||!e.__esModule?Z(n,"default",{value:e,enumerable:!0}):n,e)),rt=e=>Ne(Z({},"__esModule",{value:!0}),e);var Ht={};nt(Ht,{deriveSessionSegment:()=>Se,detectDeviceClass:()=>B,detectTimeOfDay:()=>W,detectTrafficSource:()=>j,init:()=>zt,referrerDomainFromReferer:()=>F});module.exports=rt(Ht);var st="_snt_uid";var $="_snt_uid";function it(){try{if(typeof crypto!="undefined"&&typeof crypto.randomUUID=="function")return crypto.randomUUID()}catch(t){}let e=()=>Math.floor(Math.random()*4294967295).toString(16).padStart(8,"0");return`${e()}-${e()}-${e()}-${e()}`}function at(e){try{let t=document.cookie.match(new RegExp(`(?:^|; )${e}=([^;]*)`));return t?decodeURIComponent(t[1]):null}catch(t){return null}}function ct(e,t,n){try{document.cookie=`${e}=${encodeURIComponent(t)}; max-age=${n}; SameSite=strict; path=/`}catch(d){}}function dt(e){try{return localStorage.getItem(e)}catch(t){return null}}function lt(e,t){try{return localStorage.setItem(e,t),!0}catch(n){return!1}}function ut(e){try{return sessionStorage.getItem(e)}catch(t){return null}}function gt(e,t){try{return sessionStorage.setItem(e,t),!0}catch(n){return!1}}function pt(e){try{sessionStorage.removeItem(e)}catch(t){}}function ft(e){try{return document.cookie=`${e}_probe=1; max-age=1; SameSite=strict; path=/`,/(?:^|; )_snt_uid_probe=1/.test(document.cookie)||document.cookie.indexOf(`${e}_probe=1`)!==-1}catch(t){return!1}}function mt(e){try{localStorage.removeItem(e)}catch(t){}}function yt(e){try{document.cookie=`${e}=; max-age=0; SameSite=strict; path=/`}catch(t){}}var ht={getSessionId:()=>null,isEphemeral:()=>!1,destroy:()=>{}};function re(e){var r,u,f,m,p,S;if(typeof window=="undefined")return ht;let t=(r=e==null?void 0:e.cookieName)!=null?r:st,d=((u=e==null?void 0:e.cookieTTLDays)!=null?u:365)*24*60*60,c=(S=(p=(m=(f=at(t))!=null?f:dt($))!=null?m:ut($))!=null?p:e==null?void 0:e.ssrSessionId)!=null?S:it();ct(t,c,d);let o=lt($,c),i=ft(t),a=o?!1:gt($,c),s=!o&&!i&&!a;return{getSessionId:()=>c,isEphemeral:()=>s,destroy:()=>{c=null,yt(t),mt($),pt($)}}}function me(e){return`_snt_retry_${e.slice(0,12)}`}var St={push:()=>{},flush:()=>{},destroy:()=>{}};function vt(e,t){try{let n=localStorage.getItem(t);if(!n)return[];let d=JSON.parse(n);return Array.isArray(d)?(localStorage.removeItem(t),d.slice(-e)):[]}catch(n){return[]}}function fe(e,t,n){try{let c=[...(()=>{try{let o=localStorage.getItem(n);if(!o)return[];let i=JSON.parse(o);return Array.isArray(i)?i:[]}catch(o){return[]}})(),...e].slice(-t);localStorage.setItem(n,JSON.stringify(c))}catch(d){}}function Pe(e){var Y,V,q;if(typeof window=="undefined")return St;let t=(Y=e.flushIntervalMs)!=null?Y:5e3,n=(V=e.maxBatchSize)!=null?V:20,d=(q=e.maxRetrySize)!=null?q:100,c=e.ingestUrl,o=e.apiKey,i=me(o),a=[],s=new Set,r=[],u=y=>{for(let E of y)f.delete(E),!s.has(E)&&(s.add(E),r.push(E));for(;r.length>500;){let E=r.shift();E&&s.delete(E)}},f=new Set,m=y=>{s.has(y.id)||f.has(y.id)||(f.add(y.id),a.push(y))},p=vt(d,i);for(let y of p)m(y);let S=0,v=0,w=y=>{if(y.length===0)return;let E=JSON.stringify(y),x=y.map(g=>g.id),_;try{_=fetch(c,{method:"POST",keepalive:!0,body:E,headers:{"Content-Type":"application/json",Authorization:`Bearer ${o}`}})}catch(g){fe(y,d,i);for(let h of x)f.delete(h);v++,S=Date.now()+Math.min(6e4,1e3*2**Math.min(v,6));return}let l=g=>{if(g.ok||g.status>=400&&g.status<500&&g.status!==429){u(x),v=0,S=0;return}fe(y,d,i);for(let h of x)f.delete(h);v++,S=Date.now()+Math.min(6e4,1e3*2**Math.min(v,6))};_ instanceof Promise?_.then(l).catch(()=>{fe(y,d,i);for(let g of x)f.delete(g);v++,S=Date.now()+Math.min(6e4,1e3*2**Math.min(v,6))}):l(_)},k=typeof TextEncoder!="undefined"?new TextEncoder:null,L=y=>k?k.encode(y).length:y.length,oe=y=>{let E=[],x=2;for(let _ of y){let l=L(JSON.stringify(_))+1;if(E.length>0&&x+l>57344||E.length>=n)break;E.push(_),x+=l}return E},I=()=>{try{if(Date.now()<S)return;for(;a.length>0;){let y=a.filter(x=>!s.has(x.id));if(a.length=0,y.length===0)break;let E=oe(y);if(E.length===0)break;E.length<y.length&&a.push(...y.slice(E.length)),w(E)}}catch(y){}},z=!0,M=null;M=setInterval(()=>{z&&I()},t);let H=()=>{document.visibilityState==="hidden"&&I()},Q=()=>{I()};return document.addEventListener("visibilitychange",H),window.addEventListener("beforeunload",Q),{push(y){m(y),a.length>=n&&I()},flush:I,destroy(){z=!1,M!==null&&(clearInterval(M),M=null),document.removeEventListener("visibilitychange",H),window.removeEventListener("beforeunload",Q),I()}}}var he="_snt_asgn_";function se(e,t){return`${e}:${t}`}function Et(e,t){return`${he}${encodeURIComponent(e)}:${encodeURIComponent(t)}`}function Le(e){let t=e.slice(he.length),n=t.indexOf(":");if(n<0)return null;try{return{componentId:decodeURIComponent(t.slice(0,n)),segment:decodeURIComponent(t.slice(n+1))}}catch(d){return null}}function ye(){try{let e=[];for(let t=0;t<localStorage.length;t++){let n=localStorage.key(t);n!=null&&n.startsWith(he)&&e.push(n)}return e}catch(e){return[]}}function Me(e=18e5){let t=new Map,n=c=>c.assignedAt+e<Date.now();return typeof window!="undefined"&&(()=>{for(let c of ye())try{let o=localStorage.getItem(c);if(!o)continue;let i=JSON.parse(o);if(n(i)){localStorage.removeItem(c);continue}let a=Le(c);if(!a)continue;t.set(se(a.componentId,a.segment),i)}catch(o){}})(),{get(c,o){let i=t.get(se(c,o));return i?n(i)?(t.delete(se(c,o)),null):i:null},set(c,o,i){let a=se(c,o);t.set(a,i);try{localStorage.setItem(Et(c,o),JSON.stringify(i))}catch(s){}},invalidate(c){let o=`${c}:`;for(let i of[...t.keys()])i.startsWith(o)&&t.delete(i);for(let i of ye()){let a=Le(i);if((a==null?void 0:a.componentId)===c)try{localStorage.removeItem(i)}catch(s){}}},clear(){t.clear();for(let c of ye())try{localStorage.removeItem(c)}catch(o){}}}}var Ue=["GPTBot","ChatGPT-User","OAI-SearchBot","ClaudeBot","Claude-User","Claude-SearchBot","PerplexityBot","Perplexity-User","Google-Extended","Applebot-Extended","Meta-ExternalAgent","Bytespider","CCBot","Amazonbot","cohere-ai","Diffbot"];function ie(e){return Ge(e)!==null}function Ge(e){var n;if(!e)return null;let t=e.toLowerCase();return(n=Ue.find(d=>t.includes(d.toLowerCase())))!=null?n:null}function B(e){let t=e.toLowerCase();return/ipad|tablet|playbook|kindle|silk/.test(t)?"tablet":/mobi|iphone|ipod|android.*mobile|phone/.test(t)?"mobile":"desktop"}function j(e,t){if(!e)return"direct";try{let n=new URL(e);if(t)try{if(new URL(t).host===n.host)return"direct"}catch(c){}let d=n.hostname.toLowerCase();return/(^|\.)(google|bing|duckduckgo|yahoo)\./.test(d)?"search":/(^|\.)(twitter|x\.com|facebook|linkedin|reddit|t\.co)/.test(d)?"social":"referral"}catch(n){return"direct"}}function F(e){if(!e)return null;try{return new URL(e).hostname}catch(t){return null}}function W(e){let t=e.getHours();return t<6?"night":t<12?"morning":t<18?"afternoon":"evening"}function Se(e){let t=wt("__segment__",e);return`${t.deviceClass}:${t.trafficSource}`}function wt(e,t){var o,i,a,s,r,u,f;let n=(i=(o=t==null?void 0:t.userAgent)==null?void 0:o.trim())!=null?i:"",d=(s=(a=t==null?void 0:t.referer)==null?void 0:a.trim())!=null?s:"",c=(r=t==null?void 0:t.now)!=null?r:new Date;return{sessionId:e,ephemeral:!1,utmParams:(u=t==null?void 0:t.utmParams)!=null?u:{},deviceClass:n?B(n):"desktop",trafficSource:d?j(d,t==null?void 0:t.appOrigin):"direct",referrerDomain:F(d),timeOfDay:W(c),dayOfWeek:(f=["sun","mon","tue","wed","thu","fri","sat"][c.getDay()])!=null?f:"sun",automation:(t==null?void 0:t.webdriver)===!0||ie(n)}}var J=require("@sentientui/policy");function ae(e){return b(b(b({id:e.id},e.arms?{arms:[...e.arms]}:{}),e.dims?{dims:Object.fromEntries(Object.entries(e.dims).map(([t,n])=>[t,[...n]]))}:{}),e.baseline!==void 0?{baseline:e.baseline}:{})}function ce(e){let t=ae(e);return(0,J.slotResultFor)(t,(0,J.slotBaselineArm)(t))}function ve(e){return typeof e=="string"?e:(0,J.canonicalArm)(e)}var ee="_snt_snap:",bt=["low","medium","high"];function Ee(e){try{let t=localStorage.getItem(ee+e);if(!t)return null;let n=JSON.parse(t);return!n||typeof n!="object"||n.v!==1||typeof n.persona!="string"||typeof n.band!="string"||!bt.includes(n.band)||typeof n.slots!="object"||n.slots===null||Array.isArray(n.slots)||!(n.layoutOrder===null||Array.isArray(n.layoutOrder))||typeof n.savedAt!="number"?null:n}catch(t){return null}}function te(e,t){try{localStorage.setItem(ee+e,JSON.stringify(t))}catch(n){}}var Ie=require("@sentientui/policy");var le=require("@sentientui/policy");var we="[sentient] No API key configured \u2014 nothing is being learned. Set NEXT_PUBLIC_SENTIENT_API_KEY or pass localMode: true for local development.",$e="[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.",Ke=!1,de=!1;function It(){var e;try{return(e=new URLSearchParams(window.location.search).get("sentient_persona"))!=null?e:void 0}catch(t){return}}function Be(e){var a;let t=re({ssrSessionId:e.ssrSessionId}),n=(a=t.getSessionId())!=null?a:"local",d=It(),c=import("@sentientui/core/local").then(s=>{let r=s;return r.LOCAL_ENGINE_AVAILABLE?(Ke||(Ke=!0,console.info($e)),r):(de||(de=!0,console.error(we)),null)}).catch(()=>(de||(de=!0,console.error(we)),null)),o=null;function i(s){let r=document.documentElement;r.dataset.sentientPersona===void 0&&(r.dataset.sentientPersona=s.persona,r.dataset.sentientConfidence=(0,le.confidenceBand)(s.confidence))}return{isLocal:!0,async decide(s){var f,m,p;let r=await c;if(!r)return null;let u=r.createLocalEngine({sessionId:n,forcedPersona:d}).decide(s);return o=K(b({},u),{layoutOrder:(m=(f=u.layoutOrder)!=null?f:o==null?void 0:o.layoutOrder)!=null?m:null,slots:b(b({},(p=o==null?void 0:o.slots)!=null?p:{}),u.slots)}),te(e.apiKey||"local",{v:1,persona:o.persona,band:(0,le.confidenceBand)(o.confidence),slots:o.slots,layoutOrder:o.layoutOrder,savedAt:Date.now()}),i(u),u},getSlotResult(s){var r,u,f;return(f=(u=o==null?void 0:o.slots[s])!=null?u:(r=e.initialSlots)==null?void 0:r[s])!=null?f:null},getPersona(){return o?{persona:o.persona,confidence:o.confidence,band:(0,le.confidenceBand)(o.confidence)}:null},async assign(s,r){var m;let u=await c;return!u||!r||r.length===0?r!=null&&r[0]?{variantId:r[0],assignmentTtlMs:0}:null:{variantId:(m=u.createLocalEngine({sessionId:n,forcedPersona:d}).decide({components:[{id:s,variantIds:r}]}).assignments[s])!=null?m:r[0],assignmentTtlMs:0}},track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},getAssignment:()=>null,fetchWeights:()=>Promise.resolve([]),getGraph:()=>({pageNodes:[],capturedAt:0}),dispose:()=>{},destroy:()=>t.destroy()}}var je="https://api.sentient-ui.com/v1/events",ue=new Map,Ct=null;function be(){try{if(typeof crypto!="undefined"&&typeof crypto.randomUUID=="function")return crypto.randomUUID()}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 ne={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 xt(){try{let e={},t=new URLSearchParams(window.location.search);for(let[n,d]of t)n.startsWith("utm_")&&(e[n]=d);return e}catch(e){return{}}}function Fe(e){return e.replace(/\/events\/?$/,"")}function At(){return[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 _t(e){var i;let t=Fe((i=e.ingestUrl)!=null?i:je),n={"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`},d={track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},getAssignment:()=>null,fetchWeights:()=>Promise.resolve([]),async assign(a,s,r){try{let u=new URLSearchParams({componentId:a});for(let p of s!=null?s:[])u.append("variantIds[]",p);let f=await fetch(`${t}/winner?${u.toString()}`,{headers:n});return f.ok?{variantId:(await f.json()).variantId,assignmentTtlMs:0}:s!=null&&s[0]?{variantId:s[0],assignmentTtlMs:0}:null}catch(u){return s!=null&&s[0]?{variantId:s[0],assignmentTtlMs:0}:null}},decide:()=>Promise.resolve(null),getSlotResult:()=>null,getPersona:()=>null,getGraph:()=>({pageNodes:[],capturedAt:0}),dispose:()=>{},destroy:()=>{}},c={track:a=>d.track(a),goal:(a,s,r,u)=>d.goal(a,s,r,u),componentGoal:(a,s,r)=>d.componentGoal(a,s,r),identify:a=>d.identify(a),getAssignment:(a,s)=>d.getAssignment(a,s),assign:(a,s,r,u)=>d.assign(a,s,r,u),decide:a=>d.decide(a),getSlotResult:a=>d.getSlotResult(a),getPersona:()=>d.getPersona(),fetchWeights:()=>d.fetchWeights(),getGraph:()=>d.getGraph(),dispose:()=>d.dispose(),destroy:()=>d.destroy()};function o(a){d=a}return{proxy:c,setInner:o}}function We(e){var H,Q,Y,V,q,y,E,x,_;if(typeof window=="undefined")return ne;Ct=e.apiKey;let t=typeof e.apiKey=="string"&&e.apiKey.startsWith("pk_");if(e.localMode===!0||!t&&e.localMode!==!1)return ue.set(e.apiKey||"local",{config:e,upgrade:null}),Be(e);let n=e.respectDoNotTrack!==!1&&At();if(e.consent===!1||n){if(e.preConsentBehavior==="statistical_winner"){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."),ne;let{proxy:l,setInner:g}=_t(e);return ue.set(e.apiKey,{config:e,upgrade:n?null:g}),l}return ue.set(e.apiKey,{config:e,upgrade:null}),ne}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."),ne;if(e.ingestUrl==="")return console.warn("[sentient] init() called with an empty ingestUrl. SDK disabled."),ne;let d=(H=e.ingestUrl)!=null?H:je,c=Date.now(),o=re({ssrSessionId:e.ssrSessionId}),i=Me(),a=Pe({ingestUrl:d,apiKey:e.apiKey}),s=Fe(d),r={"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`},u=B((Q=navigator.userAgent)!=null?Q:""),f=typeof window!="undefined"?window.location.origin:void 0,m=j((Y=document.referrer)!=null?Y:"",f),p=(V=e.sessionSegment)!=null?V:`${u}:${m}`,S=new Map,v=new Map,w=null,k=l=>{for(let g of l)v.has(g.id)||v.set(g.id,ce(g))};if(e.initialSlots)for(let[l,g]of Object.entries(e.initialSlots))v.set(l,g);let L=Ee(e.apiKey);if(L)for(let[l,g]of Object.entries(L.slots))v.has(l)||v.set(l,g);let oe={low:.15,medium:.5,high:.85};if(e.initialPersona)w=b({},e.initialPersona);else{let l=document.documentElement.dataset;l.sentientPersona?w={persona:l.sentientPersona,confidence:(y=oe[(q=l.sentientConfidence)!=null?q:"low"])!=null?y:.15}:L&&(w={persona:L.persona,confidence:(E=oe[L.band])!=null?E:.15})}if(e.initialAssignments)for(let[l,g]of Object.entries(e.initialAssignments))i.set(l,p,{variantId:g,assignedAt:Date.now(),segment:p,confidence:1});let I=Promise.resolve(),z=o.getSessionId();if(z){let l=F((x=document.referrer)!=null?x:""),g=b(b({sessionId:z,deviceClass:u,trafficSource:m,referrerDomain:l,utmParams:xt(),timeOfDay:W(new Date),dayOfWeek:["sun","mon","tue","wed","thu","fri","sat"][new Date().getDay()],ephemeral:o.isEphemeral(),automation:typeof navigator!="undefined"&&navigator.webdriver===!0||ie((_=navigator.userAgent)!=null?_:"")},e.userId?{userId:e.userId}:{}),e.country?{country:e.country}:{});try{I=fetch(`${s}/sessions`,{method:"POST",keepalive:!0,body:JSON.stringify(g),headers:r}).then(h=>{h.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")}).catch(()=>{})}catch(h){}}e.debug&&(console.log("[sentient] initialized",{context:e.context}),window.__sentient={client:null,queue:a});let M={goal(l,g={},h=1,T=0){let C=o.getSessionId();if(!C)return;let A=be();I.then(()=>{fetch(`${s}/goals`,{method:"POST",keepalive:!0,body:JSON.stringify({sessionId:C,name:l,metadata:g,weight:h,stepIndex:T,goalId:A}),headers:r}).catch(()=>{})})},componentGoal(l,g,h){var R,P,O;let T=o.getSessionId();if(!T)return;let C=i.get(l,p),A=C?null:(R=v.get(l))!=null?R:null;if(!C&&A===null){e.debug&&console.warn(`[sentient] componentGoal("${l}"): no assignment or slot decision yet \u2014 render its <Adaptive>/adaptive hook or call assign()/decide() before recording a goal.`);return}let U=C?C.variantId:ve(A),N={id:be(),sessionId:T,projectId:e.apiKey,componentId:l,variantId:U,eventType:"goal_achieved",goalType:g,payload:b({reward:(P=h==null?void 0:h.reward)!=null?P:1},(O=h==null?void 0:h.metadata)!=null?O:{}),timestamp:Date.now(),timeInSession:Date.now()-c};e.debug&&console.log("[sentient] componentGoal",N),I.then(()=>a.push(N))},identify(l){let g=o.getSessionId();g&&I.then(()=>{fetch(`${s}/sessions`,{method:"POST",keepalive:!0,body:JSON.stringify({sessionId:g,userId:l,ephemeral:o.isEphemeral()}),headers:r}).catch(()=>{})})},track(l){let g=o.getSessionId();if(!g)return;let h=K(b({},l),{id:be(),sessionId:g,timestamp:Date.now(),timeInSession:Date.now()-c});e.debug&&console.log("[sentient] track",h),I.then(()=>a.push(h))},getAssignment(l,g){return i.get(l,g)},async assign(l,g,h,T){let C=o.getSessionId();if(!C)return null;let A=i.get(l,p);if(A&&(g!=null&&g.length||A.content!==void 0))return{variantId:A.variantId,assignmentTtlMs:0,content:A.content};let U=S.get(l);if(U)return U;let N=(async()=>{await I;try{let R={sessionId:C,componentId:l,variantIds:g};T!==void 0?R.agentDataByVariant=T:h!==void 0&&(R.agentData=h);let P=await fetch(`${s}/assign`,{method:"POST",body:JSON.stringify(R),headers:r});if(!P.ok)return null;let O=await P.json();return i.set(l,p,{variantId:O.variantId,assignedAt:Date.now(),segment:p,confidence:1,content:O.content}),O}catch(R){return null}finally{S.delete(l)}})();return S.set(l,N),N},async decide(l){var T,C,A,U,N,R,P,O,_e,Te;let g=o.getSessionId();if(!g)return null;let h=(T=l.slots)!=null?T:[];await I;try{let X={sessionId:g};l.sections&&l.sections.length>0&&(X.sections=l.sections.map(D=>({id:D}))),X.components=(C=l.components)!=null?C:[],h.length>0&&(X.slots=h.map(ae));let Re=await fetch(`${s}/decide`,{method:"POST",body:JSON.stringify(X),headers:r});if(!Re.ok)return k(h),null;let G=await Re.json(),ge={};for(let D of h)ge[D.id]=(U=(A=G.slots)==null?void 0:A[D.id])!=null?U:ce(D);for(let[D,pe]of Object.entries(ge))v.set(D,pe);w={persona:(N=G.persona)!=null?N:"unknown",confidence:(R=G.confidence)!=null?R:0};for(let[D,pe]of Object.entries((P=G.assignments)!=null?P:{}))i.set(D,p,{variantId:pe,assignedAt:Date.now(),segment:p,confidence:1});return te(e.apiKey,{v:1,persona:w.persona,band:(0,Ie.confidenceBand)(w.confidence),slots:Object.fromEntries(v),layoutOrder:(O=G.layoutOrder)!=null?O:null,savedAt:Date.now()}),{layoutOrder:(_e=G.layoutOrder)!=null?_e:null,assignments:(Te=G.assignments)!=null?Te:{},slots:ge,persona:w.persona,confidence:w.confidence}}catch(X){return k(h),null}},getSlotResult(l){var g;return(g=v.get(l))!=null?g:null},getPersona(){return w?{persona:w.persona,confidence:w.confidence,band:(0,Ie.confidenceBand)(w.confidence)}:null},async fetchWeights(){var l;try{let g=await fetch(`${s}/weights`,{headers:r});return g.ok?(l=(await g.json()).components)!=null?l:[]:[]}catch(g){return[]}},getGraph(){return{pageNodes:[],capturedAt:0}},dispose(){a.destroy(),e.debug&&console.log("[sentient] disposed")},destroy(){a.destroy(),o.destroy();try{localStorage.removeItem(ee+e.apiKey),localStorage.removeItem(me(e.apiKey))}catch(l){}e.debug&&console.log("[sentient] destroyed")}};if(ue.set(e.apiKey,{config:e,upgrade:null}),e.debug){let l=window;l.__sentient&&(l.__sentient.client=M)}return M}var Tt=new Set(["SECTION","ARTICLE","MAIN","DIV"]),Rt="h1, h2, h3",Ot={scan:async()=>({nodes:[],edges:[],scannedAt:0}),observe:()=>{},getProminenceScore:()=>0,destroy:()=>{}};function Ce(e,t,n){return n<=t?0:Math.max(0,Math.min(1,(e-t)/(n-t)))}function Dt(e){var t,n,d;try{let c=e;for(let o of Object.keys(c)){if(!o.startsWith("__reactFiber")&&!o.startsWith("__reactInternalInstance"))continue;let i=c[o],a=(d=(t=i==null?void 0:i.type)==null?void 0:t.displayName)!=null?d:(n=i==null?void 0:i.type)==null?void 0:n.name;if(a&&a.length>1)return a}}catch(c){}}function kt(e){let t={};for(let n of Array.from(e.attributes))n.name.startsWith("data-")&&(t[n.name]=n.value);return t}function Nt(e){let t=e.getAttribute("data-sentient-type");if(t)return t;let n=e.getAttribute("role");return n||"generic"}function Pt(e){var t,n;return(n=(t=e.getAttribute("data-sentient-id"))!=null?t:e.getAttribute("id"))!=null?n:e.tagName.toLowerCase()}function Lt(e){let t=0,n=e.parentElement;for(;n;)t++,n=n.parentElement;return t}function xe(e,t){var d,c,o;let n=e.querySelector(Rt);return{componentId:Pt(e),semanticType:Nt(e),ariaLabel:(d=e.getAttribute("aria-label"))!=null?d:void 0,headingText:(o=(c=n==null?void 0:n.textContent)==null?void 0:c.trim())!=null?o:void 0,isAboveFold:e.getBoundingClientRect().top<window.innerHeight,prominenceScore:t(e),depth:Lt(e),reactComponentName:Dt(e),dataAttributes:kt(e)}}function Je(e){var o;let t=[],n=new Set,d="__root__",c=new Map;for(let[i,a]of e){let s=i.parentElement,r=d;for(;s;){if(e.has(s)){r=e.get(s);let f=e.get(i),m=`${r}->${f}`;!n.has(m)&&r!==f&&(n.add(m),t.push({fromComponentId:r,toComponentId:f,weight:.6}));break}s=s.parentElement}let u=(o=c.get(r))!=null?o:[];u.push(i),c.set(r,u)}for(let i of c.values())if(!(i.length<2))for(let a=0;a<i.length;a++)for(let s=a+1;s<i.length;s++){let r=e.get(i[a]),u=e.get(i[s]);if(r===u)continue;let f=`${r}->${u}::sib`,m=`${u}->${r}::sib`;n.has(f)||(n.add(f),t.push({fromComponentId:r,toComponentId:u,weight:.3})),n.has(m)||(n.add(m),t.push({fromComponentId:u,toComponentId:r,weight:.3}))}return t}function Mt(e){let t=[],n=new Set,d=new Map;return document.querySelectorAll("[data-sentient-id]").forEach(i=>{if(i instanceof Element&&!n.has(i)){n.add(i);let a=xe(i,e);t.push(a),d.set(i,a.componentId)}}),document.querySelectorAll("section, article, main, aside").forEach(i=>{if(!(i instanceof Element)||n.has(i))return;let a=i.hasAttribute("aria-label"),s=i.hasAttribute("data-sentient-id");if(!a&&!s)return;n.add(i);let r=xe(i,e);t.push(r),d.set(i,r.componentId)}),{nodes:t,edges:Je(d)}}function ze(){if(typeof window=="undefined")return Ot;let e=null,t=0,n=null,d=a=>{try{let s=window.getComputedStyle(a),r=parseFloat(s.fontSize)||12,u=parseFloat(s.zIndex)||0,f=a.getBoundingClientRect(),m=Math.max(f.top,0),p=window.innerHeight||1,S=1/(m/p+1),v=Ce(r,12,48)*.4+Ce(S,0,1)*.4+Ce(u,0,100)*.2;return Math.max(0,Math.min(1,v))}catch(s){return .5}};return{scan:()=>new Promise(a=>{let s=()=>{let{nodes:r,edges:u}=Mt(d);a({nodes:r,edges:u,scannedAt:Date.now()})};try{typeof requestIdleCallback=="function"?t=requestIdleCallback(s,{timeout:100}):s()}catch(r){s()}}),observe:a=>{n=a;try{e=new MutationObserver(s=>{let r=[],u=new Map;for(let f of s)f.type==="childList"&&f.addedNodes.forEach(m=>{if(!(m instanceof Element)||!Tt.has(m.tagName))return;let p=m.hasAttribute("data-sentient-id"),S=m.hasAttribute("aria-label");if(!p&&!S)return;let v=xe(m,d);r.push(v),u.set(m,v.componentId)});r.length>0&&n&&n({nodes:r,edges:Je(u),addedAt:Date.now()})}),e.observe(document.body,{childList:!0,subtree:!0})}catch(s){}},getProminenceScore:d,destroy:()=>{if(e&&(e.disconnect(),e=null),t&&typeof cancelIdleCallback=="function")try{cancelIdleCallback(t)}catch(a){}t=0,n=null}}}var Ae="_snt_graph_nodes",He="_snt_graph_edges",Ut={pricing:["features","faq"],features:["pricing"],faq:["pricing"],social_proof:["cta"],cta:["social_proof","hero","trust"],hero:["cta"],comparison:["pricing"],trust:["cta"]};function Gt(e){var t;return(t=Ut[e])!=null?t:[]}function Kt(e,t){try{let n=localStorage.getItem(e);return n?JSON.parse(n):t}catch(n){return t}}function $t(e,t){try{localStorage.setItem(e,JSON.stringify(t))}catch(n){}}var Bt=new Set(["pricing","hero","social_proof","cta","features","faq","comparison","trust","navigation","generic"]);function jt(e){return Bt.has(e)?e:"generic"}function Ft(e,t,n){let d=`${e}:${t}:${n.join(",")}`,c=5381;for(let o=0;o<d.length;o++)c=(c<<5)+c+d.charCodeAt(o)&4294967295;return(c>>>0).toString(16).padStart(8,"0")}function Qe(e){let t=new Map,n=new Map,d=()=>{typeof window!="undefined"&&$t(Ae,[...t.values()])},c=o=>{var i;try{let a=JSON.parse(o);t.clear();for(let s of(i=a.pageNodes)!=null?i:[])t.set(s.componentId,s)}catch(a){}};if(typeof window!="undefined"){let o=Kt(Ae,[]);for(let i of o)t.set(i.componentId,i);try{localStorage.removeItem(He)}catch(i){}}return{addPageNode(o){t.set(o.componentId,o),d()},addStructuralEdge(o){let i=`${o.fromComponentId}->${o.toComponentId}`;n.set(i,o)},syncOnce(){var i,a;if(!(e!=null&&e.syncUrl)||typeof window=="undefined")return;let o=[...t.values()];if(o.length!==0)try{let s=new Map;for(let p of o){let S=(i=s.get(p.semanticType))!=null?i:[];S.push(p),s.set(p.semanticType,S)}let r=[],u=new Set;for(let p of o)for(let S of Gt(p.semanticType)){let v=(a=s.get(S))!=null?a:[];for(let w of v){if(w.componentId===p.componentId)continue;let k=`semantic:${p.componentId}->${w.componentId}`;u.has(k)||(u.add(k),r.push({fromComponentId:p.componentId,toComponentId:w.componentId,type:"semantic",weight:.4,confidence:.9}))}}let f=new Set(o.map(p=>p.componentId));for(let p of n.values()){if(!f.has(p.fromComponentId)||!f.has(p.toComponentId))continue;let S=`structural:${p.fromComponentId}->${p.toComponentId}`;u.has(S)||(u.add(S),r.push({fromComponentId:p.fromComponentId,toComponentId:p.toComponentId,type:"structural",weight:p.weight,confidence:1}))}let m={pageUrl:window.location.href,nodes:o.map(p=>{let S=jt(p.semanticType);return{componentId:p.componentId,semanticType:S,answers:p.answers,contentHash:Ft(p.componentId,S,p.answers),prominenceScore:p.prominenceScore,depthInPage:p.depth}}),edges:r};fetch(e.syncUrl,{method:"POST",keepalive:!0,headers:b({"Content-Type":"application/json"},e.apiKey?{Authorization:`Bearer ${e.apiKey}`}:{}),body:JSON.stringify(m)}).catch(()=>{})}catch(s){}},snapshot(){return{pageNodes:[...t.values()],capturedAt:Date.now()}},serialize(){return JSON.stringify({pageNodes:[...t.values()]})},restore:c,destroy(){if(typeof window!="undefined")try{localStorage.removeItem(Ae),localStorage.removeItem(He)}catch(o){}}}}var Wt="https://api.sentient-ui.com/v1/events";function Jt(){try{let e=document.cookie.match(/(?:^|; )_snt_uid=([^;]*)/);return e?decodeURIComponent(e[1]):void 0}catch(e){return}}function zt(e){var a;let t=We(e);if(!e.graph||typeof window=="undefined")return t;let n=ze(),d=(a=e.ingestUrl)!=null?a:Wt,c=Qe({syncUrl:d.replace(/\/events\/?$/,"/graph/sync"),apiKey:e.apiKey,projectId:e.apiKey,sessionId:Jt()});try{let s=localStorage.getItem("_snt_graph_nodes");s&&c.restore(JSON.stringify({pageNodes:JSON.parse(s)}))}catch(s){}n.scan().then(s=>{for(let r of s.nodes)c.addPageNode({id:r.componentId,componentId:r.componentId,semanticType:r.semanticType,answers:r.headingText?[r.headingText]:[],prominenceScore:r.prominenceScore,depth:r.depth});for(let r of s.edges)c.addStructuralEdge(r);c.syncOnce()});let o=null,i=()=>{o!==null&&clearTimeout(o),o=setTimeout(()=>{o=null,c.syncOnce()},500)};return n.observe(s=>{for(let r of s.nodes)c.addPageNode({id:r.componentId,componentId:r.componentId,semanticType:r.semanticType,answers:r.headingText?[r.headingText]:[],prominenceScore:r.prominenceScore,depth:r.depth});for(let r of s.edges)c.addStructuralEdge(r);i()}),K(b({},t),{getGraph:()=>c.snapshot(),dispose:()=>{o!==null&&clearTimeout(o),n.destroy(),c.destroy(),t.dispose()},destroy:()=>{o!==null&&clearTimeout(o),n.destroy(),c.destroy(),t.destroy()}})}0&&(module.exports={deriveSessionSegment,detectDeviceClass,detectTimeOfDay,detectTrafficSource,init,referrerDomainFromReferer});
|
package/dist/index-graph.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{j as v}from"./chunk-
|
|
1
|
+
import{j as v}from"./chunk-G6ZN7Q63.mjs";import{d as x,e as _,f as O,g as R,h as M}from"./chunk-SVYHTU5Z.mjs";import{a as h,b}from"./chunk-HGGX55FR.mjs";var P=new Set(["SECTION","ARTICLE","MAIN","DIV"]),D="h1, h2, h3",G={scan:async()=>({nodes:[],edges:[],scannedAt:0}),observe:()=>{},getProminenceScore:()=>0,destroy:()=>{}};function S(e,t,n){return n<=t?0:Math.max(0,Math.min(1,(e-t)/(n-t)))}function k(e){var t,n,p;try{let c=e;for(let s of Object.keys(c)){if(!s.startsWith("__reactFiber")&&!s.startsWith("__reactInternalInstance"))continue;let r=c[s],a=(p=(t=r==null?void 0:r.type)==null?void 0:t.displayName)!=null?p:(n=r==null?void 0:r.type)==null?void 0:n.name;if(a&&a.length>1)return a}}catch(c){}}function $(e){let t={};for(let n of Array.from(e.attributes))n.name.startsWith("data-")&&(t[n.name]=n.value);return t}function L(e){let t=e.getAttribute("data-sentient-type");if(t)return t;let n=e.getAttribute("role");return n||"generic"}function U(e){var t,n;return(n=(t=e.getAttribute("data-sentient-id"))!=null?t:e.getAttribute("id"))!=null?n:e.tagName.toLowerCase()}function j(e){let t=0,n=e.parentElement;for(;n;)t++,n=n.parentElement;return t}function I(e,t){var p,c,s;let n=e.querySelector(D);return{componentId:U(e),semanticType:L(e),ariaLabel:(p=e.getAttribute("aria-label"))!=null?p:void 0,headingText:(s=(c=n==null?void 0:n.textContent)==null?void 0:c.trim())!=null?s:void 0,isAboveFold:e.getBoundingClientRect().top<window.innerHeight,prominenceScore:t(e),depth:j(e),reactComponentName:k(e),dataAttributes:$(e)}}function w(e){var s;let t=[],n=new Set,p="__root__",c=new Map;for(let[r,a]of e){let i=r.parentElement,o=p;for(;i;){if(e.has(i)){o=e.get(i);let m=e.get(r),g=`${o}->${m}`;!n.has(g)&&o!==m&&(n.add(g),t.push({fromComponentId:o,toComponentId:m,weight:.6}));break}i=i.parentElement}let u=(s=c.get(o))!=null?s:[];u.push(r),c.set(o,u)}for(let r of c.values())if(!(r.length<2))for(let a=0;a<r.length;a++)for(let i=a+1;i<r.length;i++){let o=e.get(r[a]),u=e.get(r[i]);if(o===u)continue;let m=`${o}->${u}::sib`,g=`${u}->${o}::sib`;n.has(m)||(n.add(m),t.push({fromComponentId:o,toComponentId:u,weight:.3})),n.has(g)||(n.add(g),t.push({fromComponentId:u,toComponentId:o,weight:.3}))}return t}function F(e){let t=[],n=new Set,p=new Map;return document.querySelectorAll("[data-sentient-id]").forEach(r=>{if(r instanceof Element&&!n.has(r)){n.add(r);let a=I(r,e);t.push(a),p.set(r,a.componentId)}}),document.querySelectorAll("section, article, main, aside").forEach(r=>{if(!(r instanceof Element)||n.has(r))return;let a=r.hasAttribute("aria-label"),i=r.hasAttribute("data-sentient-id");if(!a&&!i)return;n.add(r);let o=I(r,e);t.push(o),p.set(r,o.componentId)}),{nodes:t,edges:w(p)}}function N(){if(typeof window=="undefined")return G;let e=null,t=0,n=null,p=a=>{try{let i=window.getComputedStyle(a),o=parseFloat(i.fontSize)||12,u=parseFloat(i.zIndex)||0,m=a.getBoundingClientRect(),g=Math.max(m.top,0),d=window.innerHeight||1,l=1/(g/d+1),f=S(o,12,48)*.4+S(l,0,1)*.4+S(u,0,100)*.2;return Math.max(0,Math.min(1,f))}catch(i){return .5}};return{scan:()=>new Promise(a=>{let i=()=>{let{nodes:o,edges:u}=F(p);a({nodes:o,edges:u,scannedAt:Date.now()})};try{typeof requestIdleCallback=="function"?t=requestIdleCallback(i,{timeout:100}):i()}catch(o){i()}}),observe:a=>{n=a;try{e=new MutationObserver(i=>{let o=[],u=new Map;for(let m of i)m.type==="childList"&&m.addedNodes.forEach(g=>{if(!(g instanceof Element)||!P.has(g.tagName))return;let d=g.hasAttribute("data-sentient-id"),l=g.hasAttribute("aria-label");if(!d&&!l)return;let f=I(g,p);o.push(f),u.set(g,f.componentId)});o.length>0&&n&&n({nodes:o,edges:w(u),addedAt:Date.now()})}),e.observe(document.body,{childList:!0,subtree:!0})}catch(i){}},getProminenceScore:p,destroy:()=>{if(e&&(e.disconnect(),e=null),t&&typeof cancelIdleCallback=="function")try{cancelIdleCallback(t)}catch(a){}t=0,n=null}}}var C="_snt_graph_nodes",A="_snt_graph_edges",K={pricing:["features","faq"],features:["pricing"],faq:["pricing"],social_proof:["cta"],cta:["social_proof","hero","trust"],hero:["cta"],comparison:["pricing"],trust:["cta"]};function q(e){var t;return(t=K[e])!=null?t:[]}function z(e,t){try{let n=localStorage.getItem(e);return n?JSON.parse(n):t}catch(n){return t}}function H(e,t){try{localStorage.setItem(e,JSON.stringify(t))}catch(n){}}var J=new Set(["pricing","hero","social_proof","cta","features","faq","comparison","trust","navigation","generic"]);function B(e){return J.has(e)?e:"generic"}function V(e,t,n){let p=`${e}:${t}:${n.join(",")}`,c=5381;for(let s=0;s<p.length;s++)c=(c<<5)+c+p.charCodeAt(s)&4294967295;return(c>>>0).toString(16).padStart(8,"0")}function T(e){let t=new Map,n=new Map,p=()=>{typeof window!="undefined"&&H(C,[...t.values()])},c=s=>{var r;try{let a=JSON.parse(s);t.clear();for(let i of(r=a.pageNodes)!=null?r:[])t.set(i.componentId,i)}catch(a){}};if(typeof window!="undefined"){let s=z(C,[]);for(let r of s)t.set(r.componentId,r);try{localStorage.removeItem(A)}catch(r){}}return{addPageNode(s){t.set(s.componentId,s),p()},addStructuralEdge(s){let r=`${s.fromComponentId}->${s.toComponentId}`;n.set(r,s)},syncOnce(){var r,a;if(!(e!=null&&e.syncUrl)||typeof window=="undefined")return;let s=[...t.values()];if(s.length!==0)try{let i=new Map;for(let d of s){let l=(r=i.get(d.semanticType))!=null?r:[];l.push(d),i.set(d.semanticType,l)}let o=[],u=new Set;for(let d of s)for(let l of q(d.semanticType)){let f=(a=i.get(l))!=null?a:[];for(let y of f){if(y.componentId===d.componentId)continue;let E=`semantic:${d.componentId}->${y.componentId}`;u.has(E)||(u.add(E),o.push({fromComponentId:d.componentId,toComponentId:y.componentId,type:"semantic",weight:.4,confidence:.9}))}}let m=new Set(s.map(d=>d.componentId));for(let d of n.values()){if(!m.has(d.fromComponentId)||!m.has(d.toComponentId))continue;let l=`structural:${d.fromComponentId}->${d.toComponentId}`;u.has(l)||(u.add(l),o.push({fromComponentId:d.fromComponentId,toComponentId:d.toComponentId,type:"structural",weight:d.weight,confidence:1}))}let g={pageUrl:window.location.href,nodes:s.map(d=>{let l=B(d.semanticType);return{componentId:d.componentId,semanticType:l,answers:d.answers,contentHash:V(d.componentId,l,d.answers),prominenceScore:d.prominenceScore,depthInPage:d.depth}}),edges:o};fetch(e.syncUrl,{method:"POST",keepalive:!0,headers:h({"Content-Type":"application/json"},e.apiKey?{Authorization:`Bearer ${e.apiKey}`}:{}),body:JSON.stringify(g)}).catch(()=>{})}catch(i){}},snapshot(){return{pageNodes:[...t.values()],capturedAt:Date.now()}},serialize(){return JSON.stringify({pageNodes:[...t.values()]})},restore:c,destroy(){if(typeof window!="undefined")try{localStorage.removeItem(C),localStorage.removeItem(A)}catch(s){}}}}var W="https://api.sentient-ui.com/v1/events";function Y(){try{let e=document.cookie.match(/(?:^|; )_snt_uid=([^;]*)/);return e?decodeURIComponent(e[1]):void 0}catch(e){return}}function oe(e){var a;let t=v(e);if(!e.graph||typeof window=="undefined")return t;let n=N(),p=(a=e.ingestUrl)!=null?a:W,c=T({syncUrl:p.replace(/\/events\/?$/,"/graph/sync"),apiKey:e.apiKey,projectId:e.apiKey,sessionId:Y()});try{let i=localStorage.getItem("_snt_graph_nodes");i&&c.restore(JSON.stringify({pageNodes:JSON.parse(i)}))}catch(i){}n.scan().then(i=>{for(let o of i.nodes)c.addPageNode({id:o.componentId,componentId:o.componentId,semanticType:o.semanticType,answers:o.headingText?[o.headingText]:[],prominenceScore:o.prominenceScore,depth:o.depth});for(let o of i.edges)c.addStructuralEdge(o);c.syncOnce()});let s=null,r=()=>{s!==null&&clearTimeout(s),s=setTimeout(()=>{s=null,c.syncOnce()},500)};return n.observe(i=>{for(let o of i.nodes)c.addPageNode({id:o.componentId,componentId:o.componentId,semanticType:o.semanticType,answers:o.headingText?[o.headingText]:[],prominenceScore:o.prominenceScore,depth:o.depth});for(let o of i.edges)c.addStructuralEdge(o);r()}),b(h({},t),{getGraph:()=>c.snapshot(),dispose:()=>{s!==null&&clearTimeout(s),n.destroy(),c.destroy(),t.dispose()},destroy:()=>{s!==null&&clearTimeout(s),n.destroy(),c.destroy(),t.destroy()}})}export{M as deriveSessionSegment,x as detectDeviceClass,R as detectTimeOfDay,_ as detectTrafficSource,oe as init,O as referrerDomainFromReferer};
|
package/dist/index.d.cts
CHANGED
|
@@ -329,6 +329,18 @@ type SentientClient = {
|
|
|
329
329
|
/** Fetches current bandit weights for all components in this project. Used by the provider to keep live-weight polling fresh. */
|
|
330
330
|
fetchWeights(): Promise<ComponentWeightEntry[]>;
|
|
331
331
|
getGraph(): GraphSnapshot;
|
|
332
|
+
/**
|
|
333
|
+
* Routine teardown: stops timers/listeners and flushes pending events, but
|
|
334
|
+
* KEEPS the visitor identity, decision snapshot, and retry bucket. Use for
|
|
335
|
+
* component unmount / re-init (framework providers call this on cleanup).
|
|
336
|
+
*/
|
|
337
|
+
dispose(): void;
|
|
338
|
+
/**
|
|
339
|
+
* Consent-revocation / forget-me teardown: everything `dispose()` does,
|
|
340
|
+
* plus deletion of the visitor identity (`_snt_uid`), the decision
|
|
341
|
+
* snapshot, and the persisted retry bucket. The next visit starts as a
|
|
342
|
+
* brand-new visitor.
|
|
343
|
+
*/
|
|
332
344
|
destroy(): void;
|
|
333
345
|
/** True when this client is the keyless local-mode client (dev only). */
|
|
334
346
|
readonly isLocal?: boolean;
|
package/dist/index.d.ts
CHANGED
|
@@ -329,6 +329,18 @@ type SentientClient = {
|
|
|
329
329
|
/** Fetches current bandit weights for all components in this project. Used by the provider to keep live-weight polling fresh. */
|
|
330
330
|
fetchWeights(): Promise<ComponentWeightEntry[]>;
|
|
331
331
|
getGraph(): GraphSnapshot;
|
|
332
|
+
/**
|
|
333
|
+
* Routine teardown: stops timers/listeners and flushes pending events, but
|
|
334
|
+
* KEEPS the visitor identity, decision snapshot, and retry bucket. Use for
|
|
335
|
+
* component unmount / re-init (framework providers call this on cleanup).
|
|
336
|
+
*/
|
|
337
|
+
dispose(): void;
|
|
338
|
+
/**
|
|
339
|
+
* Consent-revocation / forget-me teardown: everything `dispose()` does,
|
|
340
|
+
* plus deletion of the visitor identity (`_snt_uid`), the decision
|
|
341
|
+
* snapshot, and the persisted retry bucket. The next visit starts as a
|
|
342
|
+
* brand-new visitor.
|
|
343
|
+
*/
|
|
332
344
|
destroy(): void;
|
|
333
345
|
/** True when this client is the keyless local-mode client (dev only). */
|
|
334
346
|
readonly isLocal?: boolean;
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var Qe=Object.create;var X=Object.defineProperty,Ye=Object.defineProperties,ze=Object.getOwnPropertyDescriptor,Ve=Object.getOwnPropertyDescriptors,He=Object.getOwnPropertyNames,Ae=Object.getOwnPropertySymbols,qe=Object.getPrototypeOf,Ce=Object.prototype.hasOwnProperty,Xe=Object.prototype.propertyIsEnumerable;var Oe=(e,t,n)=>t in e?X(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,w=(e,t)=>{for(var n in t||(t={}))Ce.call(t,n)&&Oe(e,n,t[n]);if(Ae)for(var n of Ae(t))Xe.call(t,n)&&Oe(e,n,t[n]);return e},K=(e,t)=>Ye(e,Ve(t));var Ze=(e,t)=>{for(var n in t)X(e,n,{get:t[n],enumerable:!0})},Te=(e,t,n,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let d of He(t))!Ce.call(e,d)&&d!==n&&X(e,d,{get:()=>t[d],enumerable:!(i=ze(t,d))||i.enumerable});return e};var et=(e,t,n)=>(n=e!=null?Qe(qe(e)):{},Te(t||!e||!e.__esModule?X(n,"default",{value:e,enumerable:!0}):n,e)),tt=e=>Te(X({},"__esModule",{value:!0}),e);var It={};Ze(It,{LOCAL_MODE_BANNER:()=>Ee,PROD_KEYLESS_ERROR:()=>pe,SNAPSHOT_STORAGE_KEY_PREFIX:()=>se,agentUaList:()=>we,armOfResult:()=>de,attachMicroSignalDetectors:()=>$e,baselineResultFor:()=>$,baselineSlots:()=>Ue,deriveSessionSegment:()=>Me,detectDeviceClass:()=>ee,detectTimeOfDay:()=>re,detectTrafficSource:()=>te,grantConsent:()=>Et,init:()=>Je,isDoNotTrackEnabled:()=>_e,matchedAgentToken:()=>be,readSnapshot:()=>ue,referrerDomainFromReferer:()=>ne,renderPrePaintScript:()=>Ke,toWireSlot:()=>oe,uaTokenMatch:()=>Z,writeSnapshot:()=>W});module.exports=tt(It);var nt="_snt_uid";var G="_snt_uid";function rt(){try{if(typeof crypto!="undefined"&&typeof crypto.randomUUID=="function")return crypto.randomUUID()}catch(t){}let e=()=>Math.floor(Math.random()*4294967295).toString(16).padStart(8,"0");return`${e()}-${e()}-${e()}-${e()}`}function ot(e){try{let t=document.cookie.match(new RegExp(`(?:^|; )${e}=([^;]*)`));return t?decodeURIComponent(t[1]):null}catch(t){return null}}function st(e,t,n){try{document.cookie=`${e}=${encodeURIComponent(t)}; max-age=${n}; SameSite=strict; path=/`}catch(i){}}function it(e){try{return localStorage.getItem(e)}catch(t){return null}}function at(e,t){try{return localStorage.setItem(e,t),!0}catch(n){return!1}}function lt(e){try{return sessionStorage.getItem(e)}catch(t){return null}}function ct(e,t){try{return sessionStorage.setItem(e,t),!0}catch(n){return!1}}function dt(e){try{sessionStorage.removeItem(e)}catch(t){}}function ut(e){try{return document.cookie=`${e}_probe=1; max-age=1; SameSite=strict; path=/`,/(?:^|; )_snt_uid_probe=1/.test(document.cookie)||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 pt={getSessionId:()=>null,isEphemeral:()=>!1,destroy:()=>{}};function le(e){var l,g,m,S,h,b;if(typeof window=="undefined")return pt;let t=(l=e==null?void 0:e.cookieName)!=null?l:nt,i=((g=e==null?void 0:e.cookieTTLDays)!=null?g:365)*24*60*60,d=(b=(h=(S=(m=ot(t))!=null?m:it(G))!=null?S:lt(G))!=null?h:e==null?void 0:e.ssrSessionId)!=null?b:rt();st(t,d,i);let r=at(G,d),c=ut(t),s=r?!1:ct(G,d),o=!r&&!c&&!s;return{getSessionId:()=>d,isEphemeral:()=>o,destroy:()=>{d=null,ft(t),gt(G),dt(G)}}}var mt={push:()=>{},flush:()=>{},destroy:()=>{}};function yt(e,t){try{let n=localStorage.getItem(t);if(!n)return[];let i=JSON.parse(n);return Array.isArray(i)?(localStorage.removeItem(t),i.slice(-e)):[]}catch(n){return[]}}function he(e,t,n){try{let d=[...(()=>{try{let r=localStorage.getItem(n);if(!r)return[];let c=JSON.parse(r);return Array.isArray(c)?c:[]}catch(r){return[]}})(),...e].slice(-t);localStorage.setItem(n,JSON.stringify(d))}catch(i){}}function Pe(e){var z,V,H;if(typeof window=="undefined")return mt;let t=(z=e.flushIntervalMs)!=null?z:5e3,n=(V=e.maxBatchSize)!=null?V:20,i=(H=e.maxRetrySize)!=null?H:100,d=e.ingestUrl,r=e.apiKey,c=`_snt_retry_${r.slice(0,12)}`,s=[],o=new Set,l=[],g=f=>{for(let y of f)m.delete(y),!o.has(y)&&(o.add(y),l.push(y));for(;l.length>500;){let y=l.shift();y&&o.delete(y)}},m=new Set,S=f=>{o.has(f.id)||m.has(f.id)||(m.add(f.id),s.push(f))},h=yt(i,c);for(let f of h)S(f);let b=0,v=0,E=f=>{if(f.length===0)return;let y=JSON.stringify(f),_=f.map(u=>u.id),R;try{R=fetch(d,{method:"POST",keepalive:!0,body:y,headers:{"Content-Type":"application/json",Authorization:`Bearer ${r}`}})}catch(u){he(f,i,c);for(let p of _)m.delete(p);v++,b=Date.now()+Math.min(6e4,1e3*2**Math.min(v,6));return}let a=u=>{if(u.ok||u.status>=400&&u.status<500&&u.status!==429){g(_),v=0,b=0;return}he(f,i,c);for(let p of _)m.delete(p);v++,b=Date.now()+Math.min(6e4,1e3*2**Math.min(v,6))};R instanceof Promise?R.then(a).catch(()=>{he(f,i,c);for(let u of _)m.delete(u);v++,b=Date.now()+Math.min(6e4,1e3*2**Math.min(v,6))}):a(R)},F=typeof TextEncoder!="undefined"?new TextEncoder:null,L=f=>F?F.encode(f).length:f.length,ae=f=>{let y=[],_=2;for(let R of f){let a=L(JSON.stringify(R))+1;if(y.length>0&&_+a>57344||y.length>=n)break;y.push(R),_+=a}return y},x=()=>{try{if(Date.now()<b)return;for(;s.length>0;){let f=s.filter(_=>!o.has(_.id));if(s.length=0,f.length===0)break;let y=ae(f);if(y.length===0)break;y.length<f.length&&s.push(...f.slice(y.length)),E(y)}}catch(f){}},J=!0,N=null;N=setInterval(()=>{J&&x()},t);let Q=()=>{document.visibilityState==="hidden"&&x()},Y=()=>{x()};return document.addEventListener("visibilitychange",Q),window.addEventListener("beforeunload",Y),{push(f){S(f),s.length>=n&&x()},flush:x,destroy(){J=!1,N!==null&&(clearInterval(N),N=null),document.removeEventListener("visibilitychange",Q),window.removeEventListener("beforeunload",Y),x()}}}var ve="_snt_asgn_";function ce(e,t){return`${e}:${t}`}function ht(e,t){return`${ve}${encodeURIComponent(e)}:${encodeURIComponent(t)}`}function Le(e){let t=e.slice(ve.length),n=t.indexOf(":");if(n<0)return null;try{return{componentId:decodeURIComponent(t.slice(0,n)),segment:decodeURIComponent(t.slice(n+1))}}catch(i){return null}}function Se(){try{let e=[];for(let t=0;t<localStorage.length;t++){let n=localStorage.key(t);n!=null&&n.startsWith(ve)&&e.push(n)}return e}catch(e){return[]}}function Ne(e=18e5){let t=new Map,n=d=>d.assignedAt+e<Date.now();return typeof window!="undefined"&&(()=>{for(let d of Se())try{let r=localStorage.getItem(d);if(!r)continue;let c=JSON.parse(r);if(n(c)){localStorage.removeItem(d);continue}let s=Le(d);if(!s)continue;t.set(ce(s.componentId,s.segment),c)}catch(r){}})(),{get(d,r){let c=t.get(ce(d,r));return c?n(c)?(t.delete(ce(d,r)),null):c:null},set(d,r,c){let s=ce(d,r);t.set(s,c);try{localStorage.setItem(ht(d,r),JSON.stringify(c))}catch(o){}},invalidate(d){let r=`${d}:`;for(let c of[...t.keys()])c.startsWith(r)&&t.delete(c);for(let c of Se()){let s=Le(c);if((s==null?void 0:s.componentId)===d)try{localStorage.removeItem(c)}catch(o){}}},clear(){t.clear();for(let d of Se())try{localStorage.removeItem(d)}catch(r){}}}}var we=["GPTBot","ChatGPT-User","OAI-SearchBot","ClaudeBot","Claude-User","Claude-SearchBot","PerplexityBot","Perplexity-User","Google-Extended","Applebot-Extended","Meta-ExternalAgent","Bytespider","CCBot","Amazonbot","cohere-ai","Diffbot"];function Z(e){return be(e)!==null}function be(e){var n;if(!e)return null;let t=e.toLowerCase();return(n=we.find(i=>t.includes(i.toLowerCase())))!=null?n:null}function ee(e){let t=e.toLowerCase();return/ipad|tablet|playbook|kindle|silk/.test(t)?"tablet":/mobi|iphone|ipod|android.*mobile|phone/.test(t)?"mobile":"desktop"}function te(e,t){if(!e)return"direct";try{let n=new URL(e);if(t)try{if(new URL(t).host===n.host)return"direct"}catch(d){}let i=n.hostname.toLowerCase();return/(^|\.)(google|bing|duckduckgo|yahoo)\./.test(i)?"search":/(^|\.)(twitter|x\.com|facebook|linkedin|reddit|t\.co)/.test(i)?"social":"referral"}catch(n){return"direct"}}function ne(e){if(!e)return null;try{return new URL(e).hostname}catch(t){return null}}function re(e){let t=e.getHours();return t<6?"night":t<12?"morning":t<18?"afternoon":"evening"}function Me(e){let t=St("__segment__",e);return`${t.deviceClass}:${t.trafficSource}`}function St(e,t){var r,c,s,o,l,g,m;let n=(c=(r=t==null?void 0:t.userAgent)==null?void 0:r.trim())!=null?c:"",i=(o=(s=t==null?void 0:t.referer)==null?void 0:s.trim())!=null?o:"",d=(l=t==null?void 0:t.now)!=null?l:new Date;return{sessionId:e,ephemeral:!1,utmParams:(g=t==null?void 0:t.utmParams)!=null?g:{},deviceClass:n?ee(n):"desktop",trafficSource:i?te(i,t==null?void 0:t.appOrigin):"direct",referrerDomain:ne(i),timeOfDay:re(d),dayOfWeek:(m=["sun","mon","tue","wed","thu","fri","sat"][d.getDay()])!=null?m:"sun",automation:(t==null?void 0:t.webdriver)===!0||Z(n)}}var B=require("@sentientui/policy");function oe(e){return w(w(w({id:e.id},e.arms?{arms:[...e.arms]}:{}),e.dims?{dims:Object.fromEntries(Object.entries(e.dims).map(([t,n])=>[t,[...n]]))}:{}),e.baseline!==void 0?{baseline:e.baseline}:{})}function $(e){let t=oe(e);return(0,B.slotResultFor)(t,(0,B.slotBaselineArm)(t))}function Ue(e){let t={};for(let n of e)t[n.id]=$(n);return t}function de(e){return typeof e=="string"?e:(0,B.canonicalArm)(e)}var se="_snt_snap:",vt=["low","medium","high"];function ue(e){try{let t=localStorage.getItem(se+e);if(!t)return null;let n=JSON.parse(t);return!n||typeof n!="object"||n.v!==1||typeof n.persona!="string"||typeof n.band!="string"||!vt.includes(n.band)||typeof n.slots!="object"||n.slots===null||Array.isArray(n.slots)||!(n.layoutOrder===null||Array.isArray(n.layoutOrder))||typeof n.savedAt!="number"?null:n}catch(t){return null}}function W(e,t){try{localStorage.setItem(se+e,JSON.stringify(t))}catch(n){}}function Ke(e){return"(function(){try{var r=localStorage.getItem("+JSON.stringify(se+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){}})();'}var Ie=require("@sentientui/policy");var fe=require("@sentientui/policy");var pe="[sentient] No API key configured \u2014 nothing is being learned. Set NEXT_PUBLIC_SENTIENT_API_KEY or pass localMode: true for local development.",Ee="[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.",Ge=!1,ge=!1;function wt(){var e;try{return(e=new URLSearchParams(window.location.search).get("sentient_persona"))!=null?e:void 0}catch(t){return}}function Be(e){var s;let t=le({ssrSessionId:e.ssrSessionId}),n=(s=t.getSessionId())!=null?s:"local",i=wt(),d=import("@sentientui/core/local").then(o=>{let l=o;return l.LOCAL_ENGINE_AVAILABLE?(Ge||(Ge=!0,console.info(Ee)),l):(ge||(ge=!0,console.error(pe)),null)}).catch(()=>(ge||(ge=!0,console.error(pe)),null)),r=null;function c(o){let l=document.documentElement;l.dataset.sentientPersona===void 0&&(l.dataset.sentientPersona=o.persona,l.dataset.sentientConfidence=(0,fe.confidenceBand)(o.confidence))}return{isLocal:!0,async decide(o){var m,S,h;let l=await d;if(!l)return null;let g=l.createLocalEngine({sessionId:n,forcedPersona:i}).decide(o);return r=K(w({},g),{layoutOrder:(S=(m=g.layoutOrder)!=null?m:r==null?void 0:r.layoutOrder)!=null?S:null,slots:w(w({},(h=r==null?void 0:r.slots)!=null?h:{}),g.slots)}),W(e.apiKey||"local",{v:1,persona:r.persona,band:(0,fe.confidenceBand)(r.confidence),slots:r.slots,layoutOrder:r.layoutOrder,savedAt:Date.now()}),c(g),g},getSlotResult(o){var l,g,m;return(m=(g=r==null?void 0:r.slots[o])!=null?g:(l=e.initialSlots)==null?void 0:l[o])!=null?m:null},getPersona(){return r?{persona:r.persona,confidence:r.confidence,band:(0,fe.confidenceBand)(r.confidence)}:null},async assign(o,l){var S;let g=await d;return!g||!l||l.length===0?l!=null&&l[0]?{variantId:l[0],assignmentTtlMs:0}:null:{variantId:(S=g.createLocalEngine({sessionId:n,forcedPersona:i}).decide({components:[{id:o,variantIds:l}]}).assignments[o])!=null?S:l[0],assignmentTtlMs:0}},track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},getAssignment:()=>null,fetchWeights:()=>Promise.resolve([]),getGraph:()=>({pageNodes:[],capturedAt:0}),destroy:()=>t.destroy()}}function $e(e,t,n){var d;let i=[];{let s=!1,o=[],l=()=>{if(s)return;let g=Date.now();for(o.push(g);o.length>0&&g-o[0]>500;)o.shift();o.length>=3&&(s=!0,e("rage_click"))};t.addEventListener("click",l),i.push(()=>t.removeEventListener("click",l))}{let r=!1,c=s=>{if(r||!(s.target instanceof Node)||!t.contains(s.target)&&t!==s.target)return;r=!0;let o=typeof window!="undefined"?window.getSelection():null,l=o?o.toString().length:0;e("text_copy",{selectionLength:l})};document.addEventListener("copy",c),i.push(()=>document.removeEventListener("copy",c))}{let r=!1,c=!1,s=null,o=()=>{s!==null&&(clearTimeout(s),s=null)},l=()=>{r||!c||(o(),s=setTimeout(()=>{!r&&c&&(r=!0,e("scroll_hesitation"))},3e3))},g=()=>{o(),l()},m=h=>{for(let b of h)c=b.intersectionRatio>.3,c?l():o()};typeof process!="undefined"&&((d=process.env)==null?void 0:d.NODE_ENV)!=="production"&&(window.__lastIOCallback=m);let S=new IntersectionObserver(m,{threshold:[.3]});S.observe(t),window.addEventListener("scroll",g,{passive:!0}),i.push(()=>{S.disconnect(),window.removeEventListener("scroll",g),o()})}{let r=!1,c=n!=null?n:Date.now(),s=()=>{if(r||document.visibilityState!=="hidden")return;let o=Date.now()-c;o<15e3&&(r=!0,e("tab_loss",{timeOnPage:o}))};document.addEventListener("visibilitychange",s),i.push(()=>document.removeEventListener("visibilitychange",s))}return()=>{for(let r of i)r()}}var We="https://api.sentient-ui.com/v1/events",j=new Map,je=null;function xe(){try{if(typeof crypto!="undefined"&&typeof crypto.randomUUID=="function")return crypto.randomUUID()}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 ie={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}),destroy:()=>{}};function bt(){try{let e={},t=new URLSearchParams(window.location.search);for(let[n,i]of t)n.startsWith("utm_")&&(e[n]=i);return e}catch(e){return{}}}function Fe(e){return e.replace(/\/events\/?$/,"")}function _e(){return[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 Et(e){if(typeof window=="undefined")return;let t=e!=null?e:je;if(!t){console.warn("[sentient] grantConsent() called before init()");return}let n=j.get(t);if(!n){console.warn("[sentient] grantConsent() called before init()");return}let{config:i,upgrade:d}=n;if(!d||i.respectDoNotTrack!==!1&&_e())return;let r=Je(K(w({},i),{consent:!0}));d(r),j.set(t,{config:K(w({},i),{consent:!0}),upgrade:null})}function xt(e){var c;let t=Fe((c=e.ingestUrl)!=null?c:We),n={"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`},i={track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},getAssignment:()=>null,fetchWeights:()=>Promise.resolve([]),async assign(s,o,l){try{let g=new URLSearchParams({componentId:s});for(let h of o!=null?o:[])g.append("variantIds[]",h);let m=await fetch(`${t}/winner?${g.toString()}`,{headers:n});return m.ok?{variantId:(await m.json()).variantId,assignmentTtlMs:0}:o!=null&&o[0]?{variantId:o[0],assignmentTtlMs:0}:null}catch(g){return o!=null&&o[0]?{variantId:o[0],assignmentTtlMs:0}:null}},decide:()=>Promise.resolve(null),getSlotResult:()=>null,getPersona:()=>null,getGraph:()=>({pageNodes:[],capturedAt:0}),destroy:()=>{}},d={track:s=>i.track(s),goal:(s,o,l,g)=>i.goal(s,o,l,g),componentGoal:(s,o,l)=>i.componentGoal(s,o,l),identify:s=>i.identify(s),getAssignment:(s,o)=>i.getAssignment(s,o),assign:(s,o,l,g)=>i.assign(s,o,l,g),decide:s=>i.decide(s),getSlotResult:s=>i.getSlotResult(s),getPersona:()=>i.getPersona(),fetchWeights:()=>i.fetchWeights(),getGraph:()=>i.getGraph(),destroy:()=>i.destroy()};function r(s){i=s}return{proxy:d,setInner:r}}function Je(e){var Q,Y,z,V,H,f,y,_,R;if(typeof window=="undefined")return ie;je=e.apiKey;let t=typeof e.apiKey=="string"&&e.apiKey.startsWith("pk_");if(e.localMode===!0||!t&&e.localMode!==!1)return j.set(e.apiKey||"local",{config:e,upgrade:null}),Be(e);let n=e.respectDoNotTrack!==!1&&_e();if(e.consent===!1||n){if(e.preConsentBehavior==="statistical_winner"){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."),ie;let{proxy:a,setInner:u}=xt(e);return j.set(e.apiKey,{config:e,upgrade:n?null:u}),a}return j.set(e.apiKey,{config:e,upgrade:null}),ie}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."),ie;if(e.ingestUrl==="")return console.warn("[sentient] init() called with an empty ingestUrl. SDK disabled."),ie;let i=(Q=e.ingestUrl)!=null?Q:We,d=Date.now(),r=le({ssrSessionId:e.ssrSessionId}),c=Ne(),s=Pe({ingestUrl:i,apiKey:e.apiKey}),o=Fe(i),l={"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`},g=ee((Y=navigator.userAgent)!=null?Y:""),m=typeof window!="undefined"?window.location.origin:void 0,S=te((z=document.referrer)!=null?z:"",m),h=(V=e.sessionSegment)!=null?V:`${g}:${S}`,b=new Map,v=new Map,E=null,F=a=>{for(let u of a)v.has(u.id)||v.set(u.id,$(u))};if(e.initialSlots)for(let[a,u]of Object.entries(e.initialSlots))v.set(a,u);let L=ue(e.apiKey);if(L)for(let[a,u]of Object.entries(L.slots))v.has(a)||v.set(a,u);let ae={low:.15,medium:.5,high:.85};if(e.initialPersona)E=w({},e.initialPersona);else{let a=document.documentElement.dataset;a.sentientPersona?E={persona:a.sentientPersona,confidence:(f=ae[(H=a.sentientConfidence)!=null?H:"low"])!=null?f:.15}:L&&(E={persona:L.persona,confidence:(y=ae[L.band])!=null?y:.15})}if(e.initialAssignments)for(let[a,u]of Object.entries(e.initialAssignments))c.set(a,h,{variantId:u,assignedAt:Date.now(),segment:h,confidence:1});let x=Promise.resolve(),J=r.getSessionId();if(J){let a=ne((_=document.referrer)!=null?_:""),u=w(w({sessionId:J,deviceClass:g,trafficSource:S,referrerDomain:a,utmParams:bt(),timeOfDay:re(new Date),dayOfWeek:["sun","mon","tue","wed","thu","fri","sat"][new Date().getDay()],ephemeral:r.isEphemeral(),automation:typeof navigator!="undefined"&&navigator.webdriver===!0||Z((R=navigator.userAgent)!=null?R:"")},e.userId?{userId:e.userId}:{}),e.country?{country:e.country}:{});try{x=fetch(`${o}/sessions`,{method:"POST",keepalive:!0,body:JSON.stringify(u),headers:l}).then(p=>{p.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")}).catch(()=>{})}catch(p){}}e.debug&&(console.log("[sentient] initialized",{context:e.context}),window.__sentient={client:null,queue:s});let N={goal(a,u={},p=1,D=0){let I=r.getSessionId();if(!I)return;let k=xe();x.then(()=>{fetch(`${o}/goals`,{method:"POST",keepalive:!0,body:JSON.stringify({sessionId:I,name:a,metadata:u,weight:p,stepIndex:D,goalId:k}),headers:l}).catch(()=>{})})},componentGoal(a,u,p){var A,P,O;let D=r.getSessionId();if(!D)return;let I=c.get(a,h),k=I?null:(A=v.get(a))!=null?A:null;if(!I&&k===null){e.debug&&console.warn(`[sentient] componentGoal("${a}"): no assignment or slot decision yet \u2014 render its <Adaptive>/adaptive hook or call assign()/decide() before recording a goal.`);return}let M=I?I.variantId:de(k),T={id:xe(),sessionId:D,projectId:e.apiKey,componentId:a,variantId:M,eventType:"goal_achieved",goalType:u,payload:w({reward:(P=p==null?void 0:p.reward)!=null?P:1},(O=p==null?void 0:p.metadata)!=null?O:{}),timestamp:Date.now(),timeInSession:Date.now()-d};e.debug&&console.log("[sentient] componentGoal",T),x.then(()=>s.push(T))},identify(a){let u=r.getSessionId();u&&x.then(()=>{fetch(`${o}/sessions`,{method:"POST",keepalive:!0,body:JSON.stringify({sessionId:u,userId:a,ephemeral:r.isEphemeral()}),headers:l}).catch(()=>{})})},track(a){let u=r.getSessionId();if(!u)return;let p=K(w({},a),{id:xe(),sessionId:u,timestamp:Date.now(),timeInSession:Date.now()-d});e.debug&&console.log("[sentient] track",p),x.then(()=>s.push(p))},getAssignment(a,u){return c.get(a,u)},async assign(a,u,p,D){let I=r.getSessionId();if(!I)return null;let k=c.get(a,h);if(k&&(u!=null&&u.length||k.content!==void 0))return{variantId:k.variantId,assignmentTtlMs:0,content:k.content};let M=b.get(a);if(M)return M;let T=(async()=>{await x;try{let A={sessionId:I,componentId:a,variantIds:u};D!==void 0?A.agentDataByVariant=D:p!==void 0&&(A.agentData=p);let P=await fetch(`${o}/assign`,{method:"POST",body:JSON.stringify(A),headers:l});if(!P.ok)return null;let O=await P.json();return c.set(a,h,{variantId:O.variantId,assignedAt:Date.now(),segment:h,confidence:1,content:O.content}),O}catch(A){return null}finally{b.delete(a)}})();return b.set(a,T),T},async decide(a){var D,I,k,M,T,A,P,O,ke,Re;let u=r.getSessionId();if(!u)return null;let p=(D=a.slots)!=null?D:[];await x;try{let q={sessionId:u};a.sections&&a.sections.length>0&&(q.sections=a.sections.map(C=>({id:C}))),q.components=(I=a.components)!=null?I:[],p.length>0&&(q.slots=p.map(oe));let De=await fetch(`${o}/decide`,{method:"POST",body:JSON.stringify(q),headers:l});if(!De.ok)return F(p),null;let U=await De.json(),me={};for(let C of p)me[C.id]=(M=(k=U.slots)==null?void 0:k[C.id])!=null?M:$(C);for(let[C,ye]of Object.entries(me))v.set(C,ye);E={persona:(T=U.persona)!=null?T:"unknown",confidence:(A=U.confidence)!=null?A:0};for(let[C,ye]of Object.entries((P=U.assignments)!=null?P:{}))c.set(C,h,{variantId:ye,assignedAt:Date.now(),segment:h,confidence:1});return W(e.apiKey,{v:1,persona:E.persona,band:(0,Ie.confidenceBand)(E.confidence),slots:Object.fromEntries(v),layoutOrder:(O=U.layoutOrder)!=null?O:null,savedAt:Date.now()}),{layoutOrder:(ke=U.layoutOrder)!=null?ke:null,assignments:(Re=U.assignments)!=null?Re:{},slots:me,persona:E.persona,confidence:E.confidence}}catch(q){return F(p),null}},getSlotResult(a){var u;return(u=v.get(a))!=null?u:null},getPersona(){return E?{persona:E.persona,confidence:E.confidence,band:(0,Ie.confidenceBand)(E.confidence)}:null},async fetchWeights(){var a;try{let u=await fetch(`${o}/weights`,{headers:l});return u.ok?(a=(await u.json()).components)!=null?a:[]:[]}catch(u){return[]}},getGraph(){return{pageNodes:[],capturedAt:0}},destroy(){s.destroy(),r.destroy(),e.debug&&console.log("[sentient] destroyed")}};if(j.set(e.apiKey,{config:e,upgrade:null}),e.debug){let a=window;a.__sentient&&(a.__sentient.client=N)}return N}0&&(module.exports={LOCAL_MODE_BANNER,PROD_KEYLESS_ERROR,SNAPSHOT_STORAGE_KEY_PREFIX,agentUaList,armOfResult,attachMicroSignalDetectors,baselineResultFor,baselineSlots,deriveSessionSegment,detectDeviceClass,detectTimeOfDay,detectTrafficSource,grantConsent,init,isDoNotTrackEnabled,matchedAgentToken,readSnapshot,referrerDomainFromReferer,renderPrePaintScript,toWireSlot,uaTokenMatch,writeSnapshot});
|
|
1
|
+
"use strict";var Ye=Object.create;var Z=Object.defineProperty,ze=Object.defineProperties,He=Object.getOwnPropertyDescriptor,Ve=Object.getOwnPropertyDescriptors,Xe=Object.getOwnPropertyNames,Oe=Object.getOwnPropertySymbols,qe=Object.getPrototypeOf,Te=Object.prototype.hasOwnProperty,Ze=Object.prototype.propertyIsEnumerable;var Ce=(e,t,n)=>t in e?Z(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,w=(e,t)=>{for(var n in t||(t={}))Te.call(t,n)&&Ce(e,n,t[n]);if(Oe)for(var n of Oe(t))Ze.call(t,n)&&Ce(e,n,t[n]);return e},G=(e,t)=>ze(e,Ve(t));var et=(e,t)=>{for(var n in t)Z(e,n,{get:t[n],enumerable:!0})},Pe=(e,t,n,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let d of Xe(t))!Te.call(e,d)&&d!==n&&Z(e,d,{get:()=>t[d],enumerable:!(i=He(t,d))||i.enumerable});return e};var tt=(e,t,n)=>(n=e!=null?Ye(qe(e)):{},Pe(t||!e||!e.__esModule?Z(n,"default",{value:e,enumerable:!0}):n,e)),nt=e=>Pe(Z({},"__esModule",{value:!0}),e);var _t={};et(_t,{LOCAL_MODE_BANNER:()=>xe,PROD_KEYLESS_ERROR:()=>pe,SNAPSHOT_STORAGE_KEY_PREFIX:()=>K,agentUaList:()=>be,armOfResult:()=>de,attachMicroSignalDetectors:()=>We,baselineResultFor:()=>W,baselineSlots:()=>Ke,deriveSessionSegment:()=>Ue,detectDeviceClass:()=>te,detectTimeOfDay:()=>oe,detectTrafficSource:()=>ne,grantConsent:()=>xt,init:()=>Qe,isDoNotTrackEnabled:()=>Re,matchedAgentToken:()=>Ee,readSnapshot:()=>ue,referrerDomainFromReferer:()=>re,renderPrePaintScript:()=>Ge,toWireSlot:()=>se,uaTokenMatch:()=>ee,writeSnapshot:()=>j});module.exports=nt(_t);var rt="_snt_uid";var B="_snt_uid";function ot(){try{if(typeof crypto!="undefined"&&typeof crypto.randomUUID=="function")return crypto.randomUUID()}catch(t){}let e=()=>Math.floor(Math.random()*4294967295).toString(16).padStart(8,"0");return`${e()}-${e()}-${e()}-${e()}`}function st(e){try{let t=document.cookie.match(new RegExp(`(?:^|; )${e}=([^;]*)`));return t?decodeURIComponent(t[1]):null}catch(t){return null}}function it(e,t,n){try{document.cookie=`${e}=${encodeURIComponent(t)}; max-age=${n}; SameSite=strict; path=/`}catch(i){}}function at(e){try{return localStorage.getItem(e)}catch(t){return null}}function lt(e,t){try{return localStorage.setItem(e,t),!0}catch(n){return!1}}function ct(e){try{return sessionStorage.getItem(e)}catch(t){return null}}function dt(e,t){try{return sessionStorage.setItem(e,t),!0}catch(n){return!1}}function ut(e){try{sessionStorage.removeItem(e)}catch(t){}}function gt(e){try{return document.cookie=`${e}_probe=1; max-age=1; SameSite=strict; path=/`,/(?:^|; )_snt_uid_probe=1/.test(document.cookie)||document.cookie.indexOf(`${e}_probe=1`)!==-1}catch(t){return!1}}function ft(e){try{localStorage.removeItem(e)}catch(t){}}function pt(e){try{document.cookie=`${e}=; max-age=0; SameSite=strict; path=/`}catch(t){}}var mt={getSessionId:()=>null,isEphemeral:()=>!1,destroy:()=>{}};function le(e){var l,g,m,h,S,b;if(typeof window=="undefined")return mt;let t=(l=e==null?void 0:e.cookieName)!=null?l:rt,i=((g=e==null?void 0:e.cookieTTLDays)!=null?g:365)*24*60*60,d=(b=(S=(h=(m=st(t))!=null?m:at(B))!=null?h:ct(B))!=null?S:e==null?void 0:e.ssrSessionId)!=null?b:ot();it(t,d,i);let r=lt(B,d),c=gt(t),s=r?!1:dt(B,d),o=!r&&!c&&!s;return{getSessionId:()=>d,isEphemeral:()=>o,destroy:()=>{d=null,pt(t),ft(B),ut(B)}}}function he(e){return`_snt_retry_${e.slice(0,12)}`}var yt={push:()=>{},flush:()=>{},destroy:()=>{}};function St(e,t){try{let n=localStorage.getItem(t);if(!n)return[];let i=JSON.parse(n);return Array.isArray(i)?(localStorage.removeItem(t),i.slice(-e)):[]}catch(n){return[]}}function Se(e,t,n){try{let d=[...(()=>{try{let r=localStorage.getItem(n);if(!r)return[];let c=JSON.parse(r);return Array.isArray(c)?c:[]}catch(r){return[]}})(),...e].slice(-t);localStorage.setItem(n,JSON.stringify(d))}catch(i){}}function Le(e){var H,V,X;if(typeof window=="undefined")return yt;let t=(H=e.flushIntervalMs)!=null?H:5e3,n=(V=e.maxBatchSize)!=null?V:20,i=(X=e.maxRetrySize)!=null?X:100,d=e.ingestUrl,r=e.apiKey,c=he(r),s=[],o=new Set,l=[],g=f=>{for(let y of f)m.delete(y),!o.has(y)&&(o.add(y),l.push(y));for(;l.length>500;){let y=l.shift();y&&o.delete(y)}},m=new Set,h=f=>{o.has(f.id)||m.has(f.id)||(m.add(f.id),s.push(f))},S=St(i,c);for(let f of S)h(f);let b=0,v=0,E=f=>{if(f.length===0)return;let y=JSON.stringify(f),_=f.map(u=>u.id),k;try{k=fetch(d,{method:"POST",keepalive:!0,body:y,headers:{"Content-Type":"application/json",Authorization:`Bearer ${r}`}})}catch(u){Se(f,i,c);for(let p of _)m.delete(p);v++,b=Date.now()+Math.min(6e4,1e3*2**Math.min(v,6));return}let a=u=>{if(u.ok||u.status>=400&&u.status<500&&u.status!==429){g(_),v=0,b=0;return}Se(f,i,c);for(let p of _)m.delete(p);v++,b=Date.now()+Math.min(6e4,1e3*2**Math.min(v,6))};k instanceof Promise?k.then(a).catch(()=>{Se(f,i,c);for(let u of _)m.delete(u);v++,b=Date.now()+Math.min(6e4,1e3*2**Math.min(v,6))}):a(k)},J=typeof TextEncoder!="undefined"?new TextEncoder:null,L=f=>J?J.encode(f).length:f.length,ae=f=>{let y=[],_=2;for(let k of f){let a=L(JSON.stringify(k))+1;if(y.length>0&&_+a>57344||y.length>=n)break;y.push(k),_+=a}return y},x=()=>{try{if(Date.now()<b)return;for(;s.length>0;){let f=s.filter(_=>!o.has(_.id));if(s.length=0,f.length===0)break;let y=ae(f);if(y.length===0)break;y.length<f.length&&s.push(...f.slice(y.length)),E(y)}}catch(f){}},Q=!0,N=null;N=setInterval(()=>{Q&&x()},t);let Y=()=>{document.visibilityState==="hidden"&&x()},z=()=>{x()};return document.addEventListener("visibilitychange",Y),window.addEventListener("beforeunload",z),{push(f){h(f),s.length>=n&&x()},flush:x,destroy(){Q=!1,N!==null&&(clearInterval(N),N=null),document.removeEventListener("visibilitychange",Y),window.removeEventListener("beforeunload",z),x()}}}var we="_snt_asgn_";function ce(e,t){return`${e}:${t}`}function ht(e,t){return`${we}${encodeURIComponent(e)}:${encodeURIComponent(t)}`}function Ne(e){let t=e.slice(we.length),n=t.indexOf(":");if(n<0)return null;try{return{componentId:decodeURIComponent(t.slice(0,n)),segment:decodeURIComponent(t.slice(n+1))}}catch(i){return null}}function ve(){try{let e=[];for(let t=0;t<localStorage.length;t++){let n=localStorage.key(t);n!=null&&n.startsWith(we)&&e.push(n)}return e}catch(e){return[]}}function Me(e=18e5){let t=new Map,n=d=>d.assignedAt+e<Date.now();return typeof window!="undefined"&&(()=>{for(let d of ve())try{let r=localStorage.getItem(d);if(!r)continue;let c=JSON.parse(r);if(n(c)){localStorage.removeItem(d);continue}let s=Ne(d);if(!s)continue;t.set(ce(s.componentId,s.segment),c)}catch(r){}})(),{get(d,r){let c=t.get(ce(d,r));return c?n(c)?(t.delete(ce(d,r)),null):c:null},set(d,r,c){let s=ce(d,r);t.set(s,c);try{localStorage.setItem(ht(d,r),JSON.stringify(c))}catch(o){}},invalidate(d){let r=`${d}:`;for(let c of[...t.keys()])c.startsWith(r)&&t.delete(c);for(let c of ve()){let s=Ne(c);if((s==null?void 0:s.componentId)===d)try{localStorage.removeItem(c)}catch(o){}}},clear(){t.clear();for(let d of ve())try{localStorage.removeItem(d)}catch(r){}}}}var be=["GPTBot","ChatGPT-User","OAI-SearchBot","ClaudeBot","Claude-User","Claude-SearchBot","PerplexityBot","Perplexity-User","Google-Extended","Applebot-Extended","Meta-ExternalAgent","Bytespider","CCBot","Amazonbot","cohere-ai","Diffbot"];function ee(e){return Ee(e)!==null}function Ee(e){var n;if(!e)return null;let t=e.toLowerCase();return(n=be.find(i=>t.includes(i.toLowerCase())))!=null?n:null}function te(e){let t=e.toLowerCase();return/ipad|tablet|playbook|kindle|silk/.test(t)?"tablet":/mobi|iphone|ipod|android.*mobile|phone/.test(t)?"mobile":"desktop"}function ne(e,t){if(!e)return"direct";try{let n=new URL(e);if(t)try{if(new URL(t).host===n.host)return"direct"}catch(d){}let i=n.hostname.toLowerCase();return/(^|\.)(google|bing|duckduckgo|yahoo)\./.test(i)?"search":/(^|\.)(twitter|x\.com|facebook|linkedin|reddit|t\.co)/.test(i)?"social":"referral"}catch(n){return"direct"}}function re(e){if(!e)return null;try{return new URL(e).hostname}catch(t){return null}}function oe(e){let t=e.getHours();return t<6?"night":t<12?"morning":t<18?"afternoon":"evening"}function Ue(e){let t=vt("__segment__",e);return`${t.deviceClass}:${t.trafficSource}`}function vt(e,t){var r,c,s,o,l,g,m;let n=(c=(r=t==null?void 0:t.userAgent)==null?void 0:r.trim())!=null?c:"",i=(o=(s=t==null?void 0:t.referer)==null?void 0:s.trim())!=null?o:"",d=(l=t==null?void 0:t.now)!=null?l:new Date;return{sessionId:e,ephemeral:!1,utmParams:(g=t==null?void 0:t.utmParams)!=null?g:{},deviceClass:n?te(n):"desktop",trafficSource:i?ne(i,t==null?void 0:t.appOrigin):"direct",referrerDomain:re(i),timeOfDay:oe(d),dayOfWeek:(m=["sun","mon","tue","wed","thu","fri","sat"][d.getDay()])!=null?m:"sun",automation:(t==null?void 0:t.webdriver)===!0||ee(n)}}var $=require("@sentientui/policy");function se(e){return w(w(w({id:e.id},e.arms?{arms:[...e.arms]}:{}),e.dims?{dims:Object.fromEntries(Object.entries(e.dims).map(([t,n])=>[t,[...n]]))}:{}),e.baseline!==void 0?{baseline:e.baseline}:{})}function W(e){let t=se(e);return(0,$.slotResultFor)(t,(0,$.slotBaselineArm)(t))}function Ke(e){let t={};for(let n of e)t[n.id]=W(n);return t}function de(e){return typeof e=="string"?e:(0,$.canonicalArm)(e)}var K="_snt_snap:",wt=["low","medium","high"];function ue(e){try{let t=localStorage.getItem(K+e);if(!t)return null;let n=JSON.parse(t);return!n||typeof n!="object"||n.v!==1||typeof n.persona!="string"||typeof n.band!="string"||!wt.includes(n.band)||typeof n.slots!="object"||n.slots===null||Array.isArray(n.slots)||!(n.layoutOrder===null||Array.isArray(n.layoutOrder))||typeof n.savedAt!="number"?null:n}catch(t){return null}}function j(e,t){try{localStorage.setItem(K+e,JSON.stringify(t))}catch(n){}}function Ge(e){return"(function(){try{var r=localStorage.getItem("+JSON.stringify(K+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){}})();'}var _e=require("@sentientui/policy");var fe=require("@sentientui/policy");var pe="[sentient] No API key configured \u2014 nothing is being learned. Set NEXT_PUBLIC_SENTIENT_API_KEY or pass localMode: true for local development.",xe="[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.",Be=!1,ge=!1;function bt(){var e;try{return(e=new URLSearchParams(window.location.search).get("sentient_persona"))!=null?e:void 0}catch(t){return}}function $e(e){var s;let t=le({ssrSessionId:e.ssrSessionId}),n=(s=t.getSessionId())!=null?s:"local",i=bt(),d=import("@sentientui/core/local").then(o=>{let l=o;return l.LOCAL_ENGINE_AVAILABLE?(Be||(Be=!0,console.info(xe)),l):(ge||(ge=!0,console.error(pe)),null)}).catch(()=>(ge||(ge=!0,console.error(pe)),null)),r=null;function c(o){let l=document.documentElement;l.dataset.sentientPersona===void 0&&(l.dataset.sentientPersona=o.persona,l.dataset.sentientConfidence=(0,fe.confidenceBand)(o.confidence))}return{isLocal:!0,async decide(o){var m,h,S;let l=await d;if(!l)return null;let g=l.createLocalEngine({sessionId:n,forcedPersona:i}).decide(o);return r=G(w({},g),{layoutOrder:(h=(m=g.layoutOrder)!=null?m:r==null?void 0:r.layoutOrder)!=null?h:null,slots:w(w({},(S=r==null?void 0:r.slots)!=null?S:{}),g.slots)}),j(e.apiKey||"local",{v:1,persona:r.persona,band:(0,fe.confidenceBand)(r.confidence),slots:r.slots,layoutOrder:r.layoutOrder,savedAt:Date.now()}),c(g),g},getSlotResult(o){var l,g,m;return(m=(g=r==null?void 0:r.slots[o])!=null?g:(l=e.initialSlots)==null?void 0:l[o])!=null?m:null},getPersona(){return r?{persona:r.persona,confidence:r.confidence,band:(0,fe.confidenceBand)(r.confidence)}:null},async assign(o,l){var h;let g=await d;return!g||!l||l.length===0?l!=null&&l[0]?{variantId:l[0],assignmentTtlMs:0}:null:{variantId:(h=g.createLocalEngine({sessionId:n,forcedPersona:i}).decide({components:[{id:o,variantIds:l}]}).assignments[o])!=null?h:l[0],assignmentTtlMs:0}},track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},getAssignment:()=>null,fetchWeights:()=>Promise.resolve([]),getGraph:()=>({pageNodes:[],capturedAt:0}),dispose:()=>{},destroy:()=>t.destroy()}}function We(e,t,n){var d;let i=[];{let s=!1,o=[],l=()=>{if(s)return;let g=Date.now();for(o.push(g);o.length>0&&g-o[0]>500;)o.shift();o.length>=3&&(s=!0,e("rage_click"))};t.addEventListener("click",l),i.push(()=>t.removeEventListener("click",l))}{let r=!1,c=s=>{if(r||!(s.target instanceof Node)||!t.contains(s.target)&&t!==s.target)return;r=!0;let o=typeof window!="undefined"?window.getSelection():null,l=o?o.toString().length:0;e("text_copy",{selectionLength:l})};document.addEventListener("copy",c),i.push(()=>document.removeEventListener("copy",c))}{let r=!1,c=!1,s=null,o=()=>{s!==null&&(clearTimeout(s),s=null)},l=()=>{r||!c||(o(),s=setTimeout(()=>{!r&&c&&(r=!0,e("scroll_hesitation"))},3e3))},g=()=>{o(),l()},m=S=>{for(let b of S)c=b.intersectionRatio>.3,c?l():o()};typeof process!="undefined"&&((d=process.env)==null?void 0:d.NODE_ENV)!=="production"&&(window.__lastIOCallback=m);let h=new IntersectionObserver(m,{threshold:[.3]});h.observe(t),window.addEventListener("scroll",g,{passive:!0}),i.push(()=>{h.disconnect(),window.removeEventListener("scroll",g),o()})}{let r=!1,c=n!=null?n:Date.now(),s=()=>{if(r||document.visibilityState!=="hidden")return;let o=Date.now()-c;o<15e3&&(r=!0,e("tab_loss",{timeOnPage:o}))};document.addEventListener("visibilitychange",s),i.push(()=>document.removeEventListener("visibilitychange",s))}return()=>{for(let r of i)r()}}var je="https://api.sentient-ui.com/v1/events",F=new Map,Fe=null;function Ie(){try{if(typeof crypto!="undefined"&&typeof crypto.randomUUID=="function")return crypto.randomUUID()}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 ie={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 Et(){try{let e={},t=new URLSearchParams(window.location.search);for(let[n,i]of t)n.startsWith("utm_")&&(e[n]=i);return e}catch(e){return{}}}function Je(e){return e.replace(/\/events\/?$/,"")}function Re(){return[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 xt(e){if(typeof window=="undefined")return;let t=e!=null?e:Fe;if(!t){console.warn("[sentient] grantConsent() called before init()");return}let n=F.get(t);if(!n){console.warn("[sentient] grantConsent() called before init()");return}let{config:i,upgrade:d}=n;if(!d||i.respectDoNotTrack!==!1&&Re())return;let r=Qe(G(w({},i),{consent:!0}));d(r),F.set(t,{config:G(w({},i),{consent:!0}),upgrade:null})}function It(e){var c;let t=Je((c=e.ingestUrl)!=null?c:je),n={"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`},i={track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},getAssignment:()=>null,fetchWeights:()=>Promise.resolve([]),async assign(s,o,l){try{let g=new URLSearchParams({componentId:s});for(let S of o!=null?o:[])g.append("variantIds[]",S);let m=await fetch(`${t}/winner?${g.toString()}`,{headers:n});return m.ok?{variantId:(await m.json()).variantId,assignmentTtlMs:0}:o!=null&&o[0]?{variantId:o[0],assignmentTtlMs:0}:null}catch(g){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:()=>{}},d={track:s=>i.track(s),goal:(s,o,l,g)=>i.goal(s,o,l,g),componentGoal:(s,o,l)=>i.componentGoal(s,o,l),identify:s=>i.identify(s),getAssignment:(s,o)=>i.getAssignment(s,o),assign:(s,o,l,g)=>i.assign(s,o,l,g),decide:s=>i.decide(s),getSlotResult:s=>i.getSlotResult(s),getPersona:()=>i.getPersona(),fetchWeights:()=>i.fetchWeights(),getGraph:()=>i.getGraph(),dispose:()=>i.dispose(),destroy:()=>i.destroy()};function r(s){i=s}return{proxy:d,setInner:r}}function Qe(e){var Y,z,H,V,X,f,y,_,k;if(typeof window=="undefined")return ie;Fe=e.apiKey;let t=typeof e.apiKey=="string"&&e.apiKey.startsWith("pk_");if(e.localMode===!0||!t&&e.localMode!==!1)return F.set(e.apiKey||"local",{config:e,upgrade:null}),$e(e);let n=e.respectDoNotTrack!==!1&&Re();if(e.consent===!1||n){if(e.preConsentBehavior==="statistical_winner"){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."),ie;let{proxy:a,setInner:u}=It(e);return F.set(e.apiKey,{config:e,upgrade:n?null:u}),a}return F.set(e.apiKey,{config:e,upgrade:null}),ie}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."),ie;if(e.ingestUrl==="")return console.warn("[sentient] init() called with an empty ingestUrl. SDK disabled."),ie;let i=(Y=e.ingestUrl)!=null?Y:je,d=Date.now(),r=le({ssrSessionId:e.ssrSessionId}),c=Me(),s=Le({ingestUrl:i,apiKey:e.apiKey}),o=Je(i),l={"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`},g=te((z=navigator.userAgent)!=null?z:""),m=typeof window!="undefined"?window.location.origin:void 0,h=ne((H=document.referrer)!=null?H:"",m),S=(V=e.sessionSegment)!=null?V:`${g}:${h}`,b=new Map,v=new Map,E=null,J=a=>{for(let u of a)v.has(u.id)||v.set(u.id,W(u))};if(e.initialSlots)for(let[a,u]of Object.entries(e.initialSlots))v.set(a,u);let L=ue(e.apiKey);if(L)for(let[a,u]of Object.entries(L.slots))v.has(a)||v.set(a,u);let ae={low:.15,medium:.5,high:.85};if(e.initialPersona)E=w({},e.initialPersona);else{let a=document.documentElement.dataset;a.sentientPersona?E={persona:a.sentientPersona,confidence:(f=ae[(X=a.sentientConfidence)!=null?X:"low"])!=null?f:.15}:L&&(E={persona:L.persona,confidence:(y=ae[L.band])!=null?y:.15})}if(e.initialAssignments)for(let[a,u]of Object.entries(e.initialAssignments))c.set(a,S,{variantId:u,assignedAt:Date.now(),segment:S,confidence:1});let x=Promise.resolve(),Q=r.getSessionId();if(Q){let a=re((_=document.referrer)!=null?_:""),u=w(w({sessionId:Q,deviceClass:g,trafficSource:h,referrerDomain:a,utmParams:Et(),timeOfDay:oe(new Date),dayOfWeek:["sun","mon","tue","wed","thu","fri","sat"][new Date().getDay()],ephemeral:r.isEphemeral(),automation:typeof navigator!="undefined"&&navigator.webdriver===!0||ee((k=navigator.userAgent)!=null?k:"")},e.userId?{userId:e.userId}:{}),e.country?{country:e.country}:{});try{x=fetch(`${o}/sessions`,{method:"POST",keepalive:!0,body:JSON.stringify(u),headers:l}).then(p=>{p.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")}).catch(()=>{})}catch(p){}}e.debug&&(console.log("[sentient] initialized",{context:e.context}),window.__sentient={client:null,queue:s});let N={goal(a,u={},p=1,A=0){let I=r.getSessionId();if(!I)return;let R=Ie();x.then(()=>{fetch(`${o}/goals`,{method:"POST",keepalive:!0,body:JSON.stringify({sessionId:I,name:a,metadata:u,weight:p,stepIndex:A,goalId:R}),headers:l}).catch(()=>{})})},componentGoal(a,u,p){var D,P,O;let A=r.getSessionId();if(!A)return;let I=c.get(a,S),R=I?null:(D=v.get(a))!=null?D:null;if(!I&&R===null){e.debug&&console.warn(`[sentient] componentGoal("${a}"): no assignment or slot decision yet \u2014 render its <Adaptive>/adaptive hook or call assign()/decide() before recording a goal.`);return}let M=I?I.variantId:de(R),T={id:Ie(),sessionId:A,projectId:e.apiKey,componentId:a,variantId:M,eventType:"goal_achieved",goalType:u,payload:w({reward:(P=p==null?void 0:p.reward)!=null?P:1},(O=p==null?void 0:p.metadata)!=null?O:{}),timestamp:Date.now(),timeInSession:Date.now()-d};e.debug&&console.log("[sentient] componentGoal",T),x.then(()=>s.push(T))},identify(a){let u=r.getSessionId();u&&x.then(()=>{fetch(`${o}/sessions`,{method:"POST",keepalive:!0,body:JSON.stringify({sessionId:u,userId:a,ephemeral:r.isEphemeral()}),headers:l}).catch(()=>{})})},track(a){let u=r.getSessionId();if(!u)return;let p=G(w({},a),{id:Ie(),sessionId:u,timestamp:Date.now(),timeInSession:Date.now()-d});e.debug&&console.log("[sentient] track",p),x.then(()=>s.push(p))},getAssignment(a,u){return c.get(a,u)},async assign(a,u,p,A){let I=r.getSessionId();if(!I)return null;let R=c.get(a,S);if(R&&(u!=null&&u.length||R.content!==void 0))return{variantId:R.variantId,assignmentTtlMs:0,content:R.content};let M=b.get(a);if(M)return M;let T=(async()=>{await x;try{let D={sessionId:I,componentId:a,variantIds:u};A!==void 0?D.agentDataByVariant=A:p!==void 0&&(D.agentData=p);let P=await fetch(`${o}/assign`,{method:"POST",body:JSON.stringify(D),headers:l});if(!P.ok)return null;let O=await P.json();return c.set(a,S,{variantId:O.variantId,assignedAt:Date.now(),segment:S,confidence:1,content:O.content}),O}catch(D){return null}finally{b.delete(a)}})();return b.set(a,T),T},async decide(a){var A,I,R,M,T,D,P,O,ke,Ae;let u=r.getSessionId();if(!u)return null;let p=(A=a.slots)!=null?A:[];await x;try{let q={sessionId:u};a.sections&&a.sections.length>0&&(q.sections=a.sections.map(C=>({id:C}))),q.components=(I=a.components)!=null?I:[],p.length>0&&(q.slots=p.map(se));let De=await fetch(`${o}/decide`,{method:"POST",body:JSON.stringify(q),headers:l});if(!De.ok)return J(p),null;let U=await De.json(),me={};for(let C of p)me[C.id]=(M=(R=U.slots)==null?void 0:R[C.id])!=null?M:W(C);for(let[C,ye]of Object.entries(me))v.set(C,ye);E={persona:(T=U.persona)!=null?T:"unknown",confidence:(D=U.confidence)!=null?D:0};for(let[C,ye]of Object.entries((P=U.assignments)!=null?P:{}))c.set(C,S,{variantId:ye,assignedAt:Date.now(),segment:S,confidence:1});return j(e.apiKey,{v:1,persona:E.persona,band:(0,_e.confidenceBand)(E.confidence),slots:Object.fromEntries(v),layoutOrder:(O=U.layoutOrder)!=null?O:null,savedAt:Date.now()}),{layoutOrder:(ke=U.layoutOrder)!=null?ke:null,assignments:(Ae=U.assignments)!=null?Ae:{},slots:me,persona:E.persona,confidence:E.confidence}}catch(q){return J(p),null}},getSlotResult(a){var u;return(u=v.get(a))!=null?u:null},getPersona(){return E?{persona:E.persona,confidence:E.confidence,band:(0,_e.confidenceBand)(E.confidence)}:null},async fetchWeights(){var a;try{let u=await fetch(`${o}/weights`,{headers:l});return u.ok?(a=(await u.json()).components)!=null?a:[]:[]}catch(u){return[]}},getGraph(){return{pageNodes:[],capturedAt:0}},dispose(){s.destroy(),e.debug&&console.log("[sentient] disposed")},destroy(){s.destroy(),r.destroy();try{localStorage.removeItem(K+e.apiKey),localStorage.removeItem(he(e.apiKey))}catch(a){}e.debug&&console.log("[sentient] destroyed")}};if(F.set(e.apiKey,{config:e,upgrade:null}),e.debug){let a=window;a.__sentient&&(a.__sentient.client=N)}return N}0&&(module.exports={LOCAL_MODE_BANNER,PROD_KEYLESS_ERROR,SNAPSHOT_STORAGE_KEY_PREFIX,agentUaList,armOfResult,attachMicroSignalDetectors,baselineResultFor,baselineSlots,deriveSessionSegment,detectDeviceClass,detectTimeOfDay,detectTrafficSource,grantConsent,init,isDoNotTrackEnabled,matchedAgentToken,readSnapshot,referrerDomainFromReferer,renderPrePaintScript,toWireSlot,uaTokenMatch,writeSnapshot});
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as m,b as n,c as o,d as p,e as q,f as r,g as s,h as t,i as u,j as v}from"./chunk-
|
|
1
|
+
import{a as m,b as n,c as o,d as p,e as q,f as r,g as s,h as t,i as u,j as v}from"./chunk-G6ZN7Q63.mjs";import{a,b,c,d,e,f,g,h,j as i,k as j,l as k,m as l}from"./chunk-SVYHTU5Z.mjs";import"./chunk-HGGX55FR.mjs";export{r as LOCAL_MODE_BANNER,q as PROD_KEYLESS_ERROR,m as SNAPSHOT_STORAGE_KEY_PREFIX,a as agentUaList,l as armOfResult,s as attachMicroSignalDetectors,j as baselineResultFor,k as baselineSlots,h as deriveSessionSegment,d as detectDeviceClass,g as detectTimeOfDay,e as detectTrafficSource,u as grantConsent,v as init,t as isDoNotTrackEnabled,c as matchedAgentToken,n as readSnapshot,f as referrerDomainFromReferer,p as renderPrePaintScript,i as toWireSlot,b as uaTokenMatch,o as writeSnapshot};
|
package/llms.txt
CHANGED
|
@@ -10,8 +10,10 @@
|
|
|
10
10
|
## Install (agent quickstart)
|
|
11
11
|
|
|
12
12
|
- React app: `npx @sentientui/cli init` — detects the framework (Next App/Pages, Vite, Remix, CRA),
|
|
13
|
-
installs @sentientui/react,
|
|
14
|
-
|
|
13
|
+
installs @sentientui/react, writes .env.local, scaffolds an example. It does NOT edit your
|
|
14
|
+
layout: it prints the wrap snippet — you must wrap the app with <AdaptiveRoot> (or
|
|
15
|
+
<AdaptiveProvider>) yourself, or nothing adapts and nothing is tracked. Works with NO API key
|
|
16
|
+
(keyless local mode: deterministic simulated decisions).
|
|
15
17
|
Verify by opening the app with `?sentient_persona=buyer` vs `?sentient_persona=deal_seeker`.
|
|
16
18
|
- Real learning: create a project at https://sentient-ui.com, put the pk_ key in
|
|
17
19
|
NEXT_PUBLIC_SENTIENT_API_KEY, add the domain to allowed origins.
|
package/package.json
CHANGED
package/dist/chunk-X2URHWFL.mjs
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{b as re,d as ie,e as ae,f as le,g as ce,j as de,k as X,m as ue}from"./chunk-SVYHTU5Z.mjs";import{a as k,b as K}from"./chunk-HGGX55FR.mjs";var Pe="_snt_uid";var G="_snt_uid";function Le(){try{if(typeof crypto!="undefined"&&typeof crypto.randomUUID=="function")return crypto.randomUUID()}catch(t){}let e=()=>Math.floor(Math.random()*4294967295).toString(16).padStart(8,"0");return`${e()}-${e()}-${e()}-${e()}`}function Ne(e){try{let t=document.cookie.match(new RegExp(`(?:^|; )${e}=([^;]*)`));return t?decodeURIComponent(t[1]):null}catch(t){return null}}function Me(e,t,r){try{document.cookie=`${e}=${encodeURIComponent(t)}; max-age=${r}; SameSite=strict; path=/`}catch(d){}}function Ue(e){try{return localStorage.getItem(e)}catch(t){return null}}function Ke(e,t){try{return localStorage.setItem(e,t),!0}catch(r){return!1}}function Ge(e){try{return sessionStorage.getItem(e)}catch(t){return null}}function $e(e,t){try{return sessionStorage.setItem(e,t),!0}catch(r){return!1}}function Be(e){try{sessionStorage.removeItem(e)}catch(t){}}function We(e){try{return document.cookie=`${e}_probe=1; max-age=1; SameSite=strict; path=/`,/(?:^|; )_snt_uid_probe=1/.test(document.cookie)||document.cookie.indexOf(`${e}_probe=1`)!==-1}catch(t){return!1}}function je(e){try{localStorage.removeItem(e)}catch(t){}}function Fe(e){try{document.cookie=`${e}=; max-age=0; SameSite=strict; path=/`}catch(t){}}var Je={getSessionId:()=>null,isEphemeral:()=>!1,destroy:()=>{}};function Z(e){var a,g,m,S,h,w;if(typeof window=="undefined")return Je;let t=(a=e==null?void 0:e.cookieName)!=null?a:Pe,d=((g=e==null?void 0:e.cookieTTLDays)!=null?g:365)*24*60*60,u=(w=(h=(S=(m=Ne(t))!=null?m:Ue(G))!=null?S:Ge(G))!=null?h:e==null?void 0:e.ssrSessionId)!=null?w:Le();Me(t,u,d);let n=Ke(G,u),c=We(t),o=n?!1:$e(G,u),s=!n&&!c&&!o;return{getSessionId:()=>u,isEphemeral:()=>s,destroy:()=>{u=null,Fe(t),je(G),Be(G)}}}var Qe={push:()=>{},flush:()=>{},destroy:()=>{}};function Ye(e,t){try{let r=localStorage.getItem(t);if(!r)return[];let d=JSON.parse(r);return Array.isArray(d)?(localStorage.removeItem(t),d.slice(-e)):[]}catch(r){return[]}}function ge(e,t,r){try{let u=[...(()=>{try{let n=localStorage.getItem(r);if(!n)return[];let c=JSON.parse(n);return Array.isArray(c)?c:[]}catch(n){return[]}})(),...e].slice(-t);localStorage.setItem(r,JSON.stringify(u))}catch(d){}}function be(e){var J,Q,Y;if(typeof window=="undefined")return Qe;let t=(J=e.flushIntervalMs)!=null?J:5e3,r=(Q=e.maxBatchSize)!=null?Q:20,d=(Y=e.maxRetrySize)!=null?Y:100,u=e.ingestUrl,n=e.apiKey,c=`_snt_retry_${n.slice(0,12)}`,o=[],s=new Set,a=[],g=p=>{for(let y of p)m.delete(y),!s.has(y)&&(s.add(y),a.push(y));for(;a.length>500;){let y=a.shift();y&&s.delete(y)}},m=new Set,S=p=>{s.has(p.id)||m.has(p.id)||(m.add(p.id),o.push(p))},h=Ye(d,c);for(let p of h)S(p);let w=0,v=0,E=p=>{if(p.length===0)return;let y=JSON.stringify(p),_=p.map(l=>l.id),A;try{A=fetch(u,{method:"POST",keepalive:!0,body:y,headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`}})}catch(l){ge(p,d,c);for(let f of _)m.delete(f);v++,w=Date.now()+Math.min(6e4,1e3*2**Math.min(v,6));return}let i=l=>{if(l.ok||l.status>=400&&l.status<500&&l.status!==429){g(_),v=0,w=0;return}ge(p,d,c);for(let f of _)m.delete(f);v++,w=Date.now()+Math.min(6e4,1e3*2**Math.min(v,6))};A instanceof Promise?A.then(i).catch(()=>{ge(p,d,c);for(let l of _)m.delete(l);v++,w=Date.now()+Math.min(6e4,1e3*2**Math.min(v,6))}):i(A)},B=typeof TextEncoder!="undefined"?new TextEncoder:null,L=p=>B?B.encode(p).length:p.length,q=p=>{let y=[],_=2;for(let A of p){let i=L(JSON.stringify(A))+1;if(y.length>0&&_+i>57344||y.length>=r)break;y.push(A),_+=i}return y},b=()=>{try{if(Date.now()<w)return;for(;o.length>0;){let p=o.filter(_=>!s.has(_.id));if(o.length=0,p.length===0)break;let y=q(p);if(y.length===0)break;y.length<p.length&&o.push(...p.slice(y.length)),E(y)}}catch(p){}},W=!0,N=null;N=setInterval(()=>{W&&b()},t);let j=()=>{document.visibilityState==="hidden"&&b()},F=()=>{b()};return document.addEventListener("visibilitychange",j),window.addEventListener("beforeunload",F),{push(p){S(p),o.length>=r&&b()},flush:b,destroy(){W=!1,N!==null&&(clearInterval(N),N=null),document.removeEventListener("visibilitychange",j),window.removeEventListener("beforeunload",F),b()}}}var fe="_snt_asgn_";function ee(e,t){return`${e}:${t}`}function Ve(e,t){return`${fe}${encodeURIComponent(e)}:${encodeURIComponent(t)}`}function Ie(e){let t=e.slice(fe.length),r=t.indexOf(":");if(r<0)return null;try{return{componentId:decodeURIComponent(t.slice(0,r)),segment:decodeURIComponent(t.slice(r+1))}}catch(d){return null}}function pe(){try{let e=[];for(let t=0;t<localStorage.length;t++){let r=localStorage.key(t);r!=null&&r.startsWith(fe)&&e.push(r)}return e}catch(e){return[]}}function _e(e=18e5){let t=new Map,r=u=>u.assignedAt+e<Date.now();return typeof window!="undefined"&&(()=>{for(let u of pe())try{let n=localStorage.getItem(u);if(!n)continue;let c=JSON.parse(n);if(r(c)){localStorage.removeItem(u);continue}let o=Ie(u);if(!o)continue;t.set(ee(o.componentId,o.segment),c)}catch(n){}})(),{get(u,n){let c=t.get(ee(u,n));return c?r(c)?(t.delete(ee(u,n)),null):c:null},set(u,n,c){let o=ee(u,n);t.set(o,c);try{localStorage.setItem(Ve(u,n),JSON.stringify(c))}catch(s){}},invalidate(u){let n=`${u}:`;for(let c of[...t.keys()])c.startsWith(n)&&t.delete(c);for(let c of pe()){let o=Ie(c);if((o==null?void 0:o.componentId)===u)try{localStorage.removeItem(c)}catch(s){}}},clear(){t.clear();for(let u of pe())try{localStorage.removeItem(u)}catch(n){}}}}var te="_snt_snap:",ze=["low","medium","high"];function me(e){try{let t=localStorage.getItem(te+e);if(!t)return null;let r=JSON.parse(t);return!r||typeof r!="object"||r.v!==1||typeof r.persona!="string"||typeof r.band!="string"||!ze.includes(r.band)||typeof r.slots!="object"||r.slots===null||Array.isArray(r.slots)||!(r.layoutOrder===null||Array.isArray(r.layoutOrder))||typeof r.savedAt!="number"?null:r}catch(t){return null}}function z(e,t){try{localStorage.setItem(te+e,JSON.stringify(t))}catch(r){}}function He(e){return"(function(){try{var r=localStorage.getItem("+JSON.stringify(te+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 Re}from"@sentientui/policy";import{confidenceBand as ye}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.",ke="[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.",xe=!1,ne=!1;function qe(){var e;try{return(e=new URLSearchParams(window.location.search).get("sentient_persona"))!=null?e:void 0}catch(t){return}}function Ae(e){var o;let t=Z({ssrSessionId:e.ssrSessionId}),r=(o=t.getSessionId())!=null?o:"local",d=qe(),u=import("@sentientui/core/local").then(s=>{let a=s;return a.LOCAL_ENGINE_AVAILABLE?(xe||(xe=!0,console.info(ke)),a):(ne||(ne=!0,console.error(he)),null)}).catch(()=>(ne||(ne=!0,console.error(he)),null)),n=null;function c(s){let a=document.documentElement;a.dataset.sentientPersona===void 0&&(a.dataset.sentientPersona=s.persona,a.dataset.sentientConfidence=ye(s.confidence))}return{isLocal:!0,async decide(s){var m,S,h;let a=await u;if(!a)return null;let g=a.createLocalEngine({sessionId:r,forcedPersona:d}).decide(s);return n=K(k({},g),{layoutOrder:(S=(m=g.layoutOrder)!=null?m:n==null?void 0:n.layoutOrder)!=null?S:null,slots:k(k({},(h=n==null?void 0:n.slots)!=null?h:{}),g.slots)}),z(e.apiKey||"local",{v:1,persona:n.persona,band:ye(n.confidence),slots:n.slots,layoutOrder:n.layoutOrder,savedAt:Date.now()}),c(g),g},getSlotResult(s){var a,g,m;return(m=(g=n==null?void 0:n.slots[s])!=null?g:(a=e.initialSlots)==null?void 0:a[s])!=null?m:null},getPersona(){return n?{persona:n.persona,confidence:n.confidence,band:ye(n.confidence)}:null},async assign(s,a){var S;let g=await u;return!g||!a||a.length===0?a!=null&&a[0]?{variantId:a[0],assignmentTtlMs:0}:null:{variantId:(S=g.createLocalEngine({sessionId:r,forcedPersona:d}).decide({components:[{id:s,variantIds:a}]}).assignments[s])!=null?S:a[0],assignmentTtlMs:0}},track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},getAssignment:()=>null,fetchWeights:()=>Promise.resolve([]),getGraph:()=>({pageNodes:[],capturedAt:0}),destroy:()=>t.destroy()}}function Xe(e,t,r){var u;let d=[];{let o=!1,s=[],a=()=>{if(o)return;let g=Date.now();for(s.push(g);s.length>0&&g-s[0]>500;)s.shift();s.length>=3&&(o=!0,e("rage_click"))};t.addEventListener("click",a),d.push(()=>t.removeEventListener("click",a))}{let n=!1,c=o=>{if(n||!(o.target instanceof Node)||!t.contains(o.target)&&t!==o.target)return;n=!0;let s=typeof window!="undefined"?window.getSelection():null,a=s?s.toString().length:0;e("text_copy",{selectionLength:a})};document.addEventListener("copy",c),d.push(()=>document.removeEventListener("copy",c))}{let n=!1,c=!1,o=null,s=()=>{o!==null&&(clearTimeout(o),o=null)},a=()=>{n||!c||(s(),o=setTimeout(()=>{!n&&c&&(n=!0,e("scroll_hesitation"))},3e3))},g=()=>{s(),a()},m=h=>{for(let w of h)c=w.intersectionRatio>.3,c?a():s()};typeof process!="undefined"&&((u=process.env)==null?void 0:u.NODE_ENV)!=="production"&&(window.__lastIOCallback=m);let S=new IntersectionObserver(m,{threshold:[.3]});S.observe(t),window.addEventListener("scroll",g,{passive:!0}),d.push(()=>{S.disconnect(),window.removeEventListener("scroll",g),s()})}{let n=!1,c=r!=null?r:Date.now(),o=()=>{if(n||document.visibilityState!=="hidden")return;let s=Date.now()-c;s<15e3&&(n=!0,e("tab_loss",{timeOnPage:s}))};document.addEventListener("visibilitychange",o),d.push(()=>document.removeEventListener("visibilitychange",o))}return()=>{for(let n of d)n()}}var De="https://api.sentient-ui.com/v1/events",$=new Map,Oe=null;function Se(){try{if(typeof crypto!="undefined"&&typeof crypto.randomUUID=="function")return crypto.randomUUID()}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 H={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}),destroy:()=>{}};function Ze(){try{let e={},t=new URLSearchParams(window.location.search);for(let[r,d]of t)r.startsWith("utm_")&&(e[r]=d);return e}catch(e){return{}}}function Te(e){return e.replace(/\/events\/?$/,"")}function Ce(){return[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 _t(e){if(typeof window=="undefined")return;let t=e!=null?e:Oe;if(!t){console.warn("[sentient] grantConsent() called before init()");return}let r=$.get(t);if(!r){console.warn("[sentient] grantConsent() called before init()");return}let{config:d,upgrade:u}=r;if(!u||d.respectDoNotTrack!==!1&&Ce())return;let n=tt(K(k({},d),{consent:!0}));u(n),$.set(t,{config:K(k({},d),{consent:!0}),upgrade:null})}function et(e){var c;let t=Te((c=e.ingestUrl)!=null?c:De),r={"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`},d={track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},getAssignment:()=>null,fetchWeights:()=>Promise.resolve([]),async assign(o,s,a){try{let g=new URLSearchParams({componentId:o});for(let h of s!=null?s:[])g.append("variantIds[]",h);let m=await fetch(`${t}/winner?${g.toString()}`,{headers:r});return m.ok?{variantId:(await m.json()).variantId,assignmentTtlMs:0}:s!=null&&s[0]?{variantId:s[0],assignmentTtlMs:0}:null}catch(g){return s!=null&&s[0]?{variantId:s[0],assignmentTtlMs:0}:null}},decide:()=>Promise.resolve(null),getSlotResult:()=>null,getPersona:()=>null,getGraph:()=>({pageNodes:[],capturedAt:0}),destroy:()=>{}},u={track:o=>d.track(o),goal:(o,s,a,g)=>d.goal(o,s,a,g),componentGoal:(o,s,a)=>d.componentGoal(o,s,a),identify:o=>d.identify(o),getAssignment:(o,s)=>d.getAssignment(o,s),assign:(o,s,a,g)=>d.assign(o,s,a,g),decide:o=>d.decide(o),getSlotResult:o=>d.getSlotResult(o),getPersona:()=>d.getPersona(),fetchWeights:()=>d.fetchWeights(),getGraph:()=>d.getGraph(),destroy:()=>d.destroy()};function n(o){d=o}return{proxy:u,setInner:n}}function tt(e){var j,F,J,Q,Y,p,y,_,A;if(typeof window=="undefined")return H;Oe=e.apiKey;let t=typeof e.apiKey=="string"&&e.apiKey.startsWith("pk_");if(e.localMode===!0||!t&&e.localMode!==!1)return $.set(e.apiKey||"local",{config:e,upgrade:null}),Ae(e);let r=e.respectDoNotTrack!==!1&&Ce();if(e.consent===!1||r){if(e.preConsentBehavior==="statistical_winner"){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."),H;let{proxy:i,setInner:l}=et(e);return $.set(e.apiKey,{config:e,upgrade:r?null:l}),i}return $.set(e.apiKey,{config:e,upgrade:null}),H}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."),H;if(e.ingestUrl==="")return console.warn("[sentient] init() called with an empty ingestUrl. SDK disabled."),H;let d=(j=e.ingestUrl)!=null?j:De,u=Date.now(),n=Z({ssrSessionId:e.ssrSessionId}),c=_e(),o=be({ingestUrl:d,apiKey:e.apiKey}),s=Te(d),a={"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`},g=ie((F=navigator.userAgent)!=null?F:""),m=typeof window!="undefined"?window.location.origin:void 0,S=ae((J=document.referrer)!=null?J:"",m),h=(Q=e.sessionSegment)!=null?Q:`${g}:${S}`,w=new Map,v=new Map,E=null,B=i=>{for(let l of i)v.has(l.id)||v.set(l.id,X(l))};if(e.initialSlots)for(let[i,l]of Object.entries(e.initialSlots))v.set(i,l);let L=me(e.apiKey);if(L)for(let[i,l]of Object.entries(L.slots))v.has(i)||v.set(i,l);let q={low:.15,medium:.5,high:.85};if(e.initialPersona)E=k({},e.initialPersona);else{let i=document.documentElement.dataset;i.sentientPersona?E={persona:i.sentientPersona,confidence:(p=q[(Y=i.sentientConfidence)!=null?Y:"low"])!=null?p:.15}:L&&(E={persona:L.persona,confidence:(y=q[L.band])!=null?y:.15})}if(e.initialAssignments)for(let[i,l]of Object.entries(e.initialAssignments))c.set(i,h,{variantId:l,assignedAt:Date.now(),segment:h,confidence:1});let b=Promise.resolve(),W=n.getSessionId();if(W){let i=le((_=document.referrer)!=null?_:""),l=k(k({sessionId:W,deviceClass:g,trafficSource:S,referrerDomain:i,utmParams:Ze(),timeOfDay:ce(new Date),dayOfWeek:["sun","mon","tue","wed","thu","fri","sat"][new Date().getDay()],ephemeral:n.isEphemeral(),automation:typeof navigator!="undefined"&&navigator.webdriver===!0||re((A=navigator.userAgent)!=null?A:"")},e.userId?{userId:e.userId}:{}),e.country?{country:e.country}:{});try{b=fetch(`${s}/sessions`,{method:"POST",keepalive:!0,body:JSON.stringify(l),headers:a}).then(f=>{f.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")}).catch(()=>{})}catch(f){}}e.debug&&(console.log("[sentient] initialized",{context:e.context}),window.__sentient={client:null,queue:o});let N={goal(i,l={},f=1,R=0){let I=n.getSessionId();if(!I)return;let x=Se();b.then(()=>{fetch(`${s}/goals`,{method:"POST",keepalive:!0,body:JSON.stringify({sessionId:I,name:i,metadata:l,weight:f,stepIndex:R,goalId:x}),headers:a}).catch(()=>{})})},componentGoal(i,l,f){var D,P,O;let R=n.getSessionId();if(!R)return;let I=c.get(i,h),x=I?null:(D=v.get(i))!=null?D:null;if(!I&&x===null){e.debug&&console.warn(`[sentient] componentGoal("${i}"): no assignment or slot decision yet \u2014 render its <Adaptive>/adaptive hook or call assign()/decide() before recording a goal.`);return}let M=I?I.variantId:ue(x),C={id:Se(),sessionId:R,projectId:e.apiKey,componentId:i,variantId:M,eventType:"goal_achieved",goalType:l,payload:k({reward:(P=f==null?void 0:f.reward)!=null?P:1},(O=f==null?void 0:f.metadata)!=null?O:{}),timestamp:Date.now(),timeInSession:Date.now()-u};e.debug&&console.log("[sentient] componentGoal",C),b.then(()=>o.push(C))},identify(i){let l=n.getSessionId();l&&b.then(()=>{fetch(`${s}/sessions`,{method:"POST",keepalive:!0,body:JSON.stringify({sessionId:l,userId:i,ephemeral:n.isEphemeral()}),headers:a}).catch(()=>{})})},track(i){let l=n.getSessionId();if(!l)return;let f=K(k({},i),{id:Se(),sessionId:l,timestamp:Date.now(),timeInSession:Date.now()-u});e.debug&&console.log("[sentient] track",f),b.then(()=>o.push(f))},getAssignment(i,l){return c.get(i,l)},async assign(i,l,f,R){let I=n.getSessionId();if(!I)return null;let x=c.get(i,h);if(x&&(l!=null&&l.length||x.content!==void 0))return{variantId:x.variantId,assignmentTtlMs:0,content:x.content};let M=w.get(i);if(M)return M;let C=(async()=>{await b;try{let D={sessionId:I,componentId:i,variantIds:l};R!==void 0?D.agentDataByVariant=R:f!==void 0&&(D.agentData=f);let P=await fetch(`${s}/assign`,{method:"POST",body:JSON.stringify(D),headers:a});if(!P.ok)return null;let O=await P.json();return c.set(i,h,{variantId:O.variantId,assignedAt:Date.now(),segment:h,confidence:1,content:O.content}),O}catch(D){return null}finally{w.delete(i)}})();return w.set(i,C),C},async decide(i){var R,I,x,M,C,D,P,O,ve,we;let l=n.getSessionId();if(!l)return null;let f=(R=i.slots)!=null?R:[];await b;try{let V={sessionId:l};i.sections&&i.sections.length>0&&(V.sections=i.sections.map(T=>({id:T}))),V.components=(I=i.components)!=null?I:[],f.length>0&&(V.slots=f.map(de));let Ee=await fetch(`${s}/decide`,{method:"POST",body:JSON.stringify(V),headers:a});if(!Ee.ok)return B(f),null;let U=await Ee.json(),se={};for(let T of f)se[T.id]=(M=(x=U.slots)==null?void 0:x[T.id])!=null?M:X(T);for(let[T,oe]of Object.entries(se))v.set(T,oe);E={persona:(C=U.persona)!=null?C:"unknown",confidence:(D=U.confidence)!=null?D:0};for(let[T,oe]of Object.entries((P=U.assignments)!=null?P:{}))c.set(T,h,{variantId:oe,assignedAt:Date.now(),segment:h,confidence:1});return z(e.apiKey,{v:1,persona:E.persona,band:Re(E.confidence),slots:Object.fromEntries(v),layoutOrder:(O=U.layoutOrder)!=null?O:null,savedAt:Date.now()}),{layoutOrder:(ve=U.layoutOrder)!=null?ve:null,assignments:(we=U.assignments)!=null?we:{},slots:se,persona:E.persona,confidence:E.confidence}}catch(V){return B(f),null}},getSlotResult(i){var l;return(l=v.get(i))!=null?l:null},getPersona(){return E?{persona:E.persona,confidence:E.confidence,band:Re(E.confidence)}:null},async fetchWeights(){var i;try{let l=await fetch(`${s}/weights`,{headers:a});return l.ok?(i=(await l.json()).components)!=null?i:[]:[]}catch(l){return[]}},getGraph(){return{pageNodes:[],capturedAt:0}},destroy(){o.destroy(),n.destroy(),e.debug&&console.log("[sentient] destroyed")}};if($.set(e.apiKey,{config:e,upgrade:null}),e.debug){let i=window;i.__sentient&&(i.__sentient.client=N)}return N}export{te as a,me as b,z as c,He as d,he as e,ke as f,Xe as g,Ce as h,_t as i,tt as j};
|