@sentientui/core 0.7.1 → 0.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunk-PXHVZ2OY.mjs +1 -0
- package/dist/index-graph.js +1 -1
- package/dist/index-graph.mjs +1 -1
- package/dist/index.d.cts +28 -2
- package/dist/index.d.ts +28 -2
- package/dist/index.js +1 -1
- package/dist/index.mjs +1 -1
- package/package.json +1 -1
- package/dist/chunk-PXHX4K5R.mjs +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a as R,b as K,c as G,d as Q,e as F,f as z}from"./chunk-QCYVBCUV.mjs";var te="_snt_uid";var C="_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 se(e){try{let t=document.cookie.match(new RegExp(`(?:^|; )${e}=([^;]*)`));return t?decodeURIComponent(t[1]):null}catch(t){return null}}function ie(e,t,c){try{document.cookie=`${e}=${encodeURIComponent(t)}; max-age=${c}; SameSite=strict; path=/`}catch(r){}}function re(e){try{return localStorage.getItem(e)}catch(t){return null}}function oe(e,t){try{return localStorage.setItem(e,t),!0}catch(c){return!1}}function ae(e){try{return sessionStorage.getItem(e)}catch(t){return null}}function ce(e,t){try{return sessionStorage.setItem(e,t),!0}catch(c){return!1}}function le(e){try{sessionStorage.removeItem(e)}catch(t){}}function de(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 ue(e){try{localStorage.removeItem(e)}catch(t){}}function ge(e){try{document.cookie=`${e}=; max-age=0; SameSite=strict; path=/`}catch(t){}}var fe={getSessionId:()=>null,isEphemeral:()=>!1,destroy:()=>{}};function H(e){var g,f,m,y,S,v;if(typeof window=="undefined")return fe;let t=(g=e==null?void 0:e.cookieName)!=null?g:te,r=((f=e==null?void 0:e.cookieTTLDays)!=null?f:365)*24*60*60,a=(v=(S=(y=(m=se(t))!=null?m:re(C))!=null?y:ae(C))!=null?S:e==null?void 0:e.ssrSessionId)!=null?v:ne();ie(t,a,r);let o=oe(C,a),i=de(t),s=o?!1:ce(C,a),n=!o&&!i&&!s;return{getSessionId:()=>a,isEphemeral:()=>n,destroy:()=>{a=null,ge(t),ue(C),le(C)}}}var pe={push:()=>{},flush:()=>{},destroy:()=>{}};function me(e,t){try{let c=localStorage.getItem(t);if(!c)return[];let r=JSON.parse(c);return Array.isArray(r)?(localStorage.removeItem(t),r.slice(-e)):[]}catch(c){return[]}}function J(e,t,c){try{let a=[...(()=>{try{let o=localStorage.getItem(c);if(!o)return[];let i=JSON.parse(o);return Array.isArray(i)?i:[]}catch(o){return[]}})(),...e].slice(-t);localStorage.setItem(c,JSON.stringify(a))}catch(r){}}function V(e){var k,I,D;if(typeof window=="undefined")return pe;let t=(k=e.flushIntervalMs)!=null?k:5e3,c=(I=e.maxBatchSize)!=null?I:20,r=(D=e.maxRetrySize)!=null?D:100,a=e.ingestUrl,o=e.apiKey,i=`_snt_retry_${o.slice(0,12)}`,s=[],n=new Set,g=[],f=l=>{for(let p of l)m.delete(p),!n.has(p)&&(n.add(p),g.push(p));for(;g.length>500;){let p=g.shift();p&&n.delete(p)}},m=new Set,y=l=>{n.has(l.id)||m.has(l.id)||(m.add(l.id),s.push(l))},S=me(r,i);for(let l of S)y(l);let v=0,x=0,L=l=>{if(l.length===0)return;let p=JSON.stringify(l),w=l.map(b=>b.id),E;try{E=fetch(a,{method:"POST",keepalive:!0,body:p,headers:{"Content-Type":"application/json",Authorization:`Bearer ${o}`}})}catch(b){J(l,r,i);for(let B of w)m.delete(B);x++,v=Date.now()+Math.min(6e4,1e3*2**Math.min(x,6));return}let O=b=>{if(b.ok||b.status>=400&&b.status<500&&b.status!==429){f(w),x=0,v=0;return}J(l,r,i);for(let B of w)m.delete(B);x++,v=Date.now()+Math.min(6e4,1e3*2**Math.min(x,6))};E instanceof Promise?E.then(O).catch(()=>{J(l,r,i);for(let b of w)m.delete(b);x++,v=Date.now()+Math.min(6e4,1e3*2**Math.min(x,6))}):O(E)},A=typeof TextEncoder!="undefined"?new TextEncoder:null,N=l=>A?A.encode(l).length:l.length,$=l=>{let p=[],w=2;for(let E of l){let O=N(JSON.stringify(E))+1;if(p.length>0&&w+O>57344||p.length>=c)break;p.push(E),w+=O}return p},_=()=>{try{if(Date.now()<v)return;for(;s.length>0;){let l=s.filter(w=>!n.has(w.id));if(s.length=0,l.length===0)break;let p=$(l);if(p.length===0)break;p.length<l.length&&s.push(...l.slice(p.length)),L(p)}}catch(l){}},d=!0,u=null;u=setInterval(()=>{d&&_()},t);let h=()=>{document.visibilityState==="hidden"&&_()},T=()=>{_()};return document.addEventListener("visibilitychange",h),window.addEventListener("beforeunload",T),{push(l){y(l),s.length>=c&&_()},flush:_,destroy(){d=!1,u!==null&&(clearInterval(u),u=null),document.removeEventListener("visibilitychange",h),window.removeEventListener("beforeunload",T),_()}}}var W="_snt_asgn_";function P(e,t){return`${e}:${t}`}function he(e,t){return`${W}${e}_${t}`}function j(){try{let e=[];for(let t=0;t<localStorage.length;t++){let c=localStorage.key(t);c!=null&&c.startsWith(W)&&e.push(c)}return e}catch(e){return[]}}function Y(e=18e5){let t=new Map,c=a=>a.assignedAt+e<Date.now();return typeof window!="undefined"&&(()=>{for(let a of j())try{let o=localStorage.getItem(a);if(!o)continue;let i=JSON.parse(o);if(c(i)){localStorage.removeItem(a);continue}let s=a.slice(W.length),n=s.lastIndexOf("_");if(n<0)continue;let g=s.slice(0,n),f=s.slice(n+1);t.set(P(g,f),i)}catch(o){}})(),{get(a,o){let i=t.get(P(a,o));return i?c(i)?(t.delete(P(a,o)),null):i:null},set(a,o,i){let s=P(a,o);t.set(s,i);try{localStorage.setItem(he(a,o),JSON.stringify(i))}catch(n){}},invalidate(a){let o=`${a}:`;for(let i of[...t.keys()])i.startsWith(o)&&t.delete(i);for(let i of j()){let s=i.slice(W.length),n=s.lastIndexOf("_");if(n<0)continue;if(s.slice(0,n)===a)try{localStorage.removeItem(i)}catch(f){}}},clear(){t.clear();for(let a of j())try{localStorage.removeItem(a)}catch(o){}}}}function ye(e,t,c){var a;let r=[];{let s=!1,n=[],g=()=>{if(s)return;let f=Date.now();for(n.push(f);n.length>0&&f-n[0]>500;)n.shift();n.length>=3&&(s=!0,e("rage_click"))};t.addEventListener("click",g),r.push(()=>t.removeEventListener("click",g))}{let o=!1,i=s=>{if(o||!(s.target instanceof Node)||!t.contains(s.target)&&t!==s.target)return;o=!0;let n=typeof window!="undefined"?window.getSelection():null,g=n?n.toString().length:0;e("text_copy",{selectionLength:g})};document.addEventListener("copy",i),r.push(()=>document.removeEventListener("copy",i))}{let o=!1,i=!1,s=null,n=()=>{s!==null&&(clearTimeout(s),s=null)},g=()=>{o||!i||(n(),s=setTimeout(()=>{!o&&i&&(o=!0,e("scroll_hesitation"))},3e3))},f=()=>{n(),g()},m=S=>{for(let v of S)i=v.intersectionRatio>.3,i?g():n()};typeof process!="undefined"&&((a=process.env)==null?void 0:a.NODE_ENV)!=="production"&&(window.__lastIOCallback=m);let y=new IntersectionObserver(m,{threshold:[.3]});y.observe(t),window.addEventListener("scroll",f,{passive:!0}),r.push(()=>{y.disconnect(),window.removeEventListener("scroll",f),n()})}{let o=!1,i=c!=null?c:Date.now(),s=()=>{if(o||document.visibilityState!=="hidden")return;let n=Date.now()-i;n<15e3&&(o=!0,e("tab_loss",{timeOnPage:n}))};document.addEventListener("visibilitychange",s),r.push(()=>document.removeEventListener("visibilitychange",s))}return()=>{for(let o of r)o()}}var X="https://api.sentient-ui.com/v1/events",U=new Map,Z=null;function q(){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 M={track:()=>{},goal:()=>{},identify:()=>{},getAssignment:()=>null,assign:()=>Promise.resolve(null),fetchWeights:()=>Promise.resolve([]),getGraph:()=>({pageNodes:[],capturedAt:0}),destroy:()=>{}};function Se(){try{let e={},t=new URLSearchParams(window.location.search);for(let[c,r]of t)c.startsWith("utm_")&&(e[c]=r);return e}catch(e){return{}}}function ee(e){return e.replace(/\/events\/?$/,"")}function De(e){if(typeof window=="undefined")return;let t=e!=null?e:Z;if(!t){console.warn("[sentient] grantConsent() called before init()");return}let c=U.get(t);if(!c){console.warn("[sentient] grantConsent() called before init()");return}let{config:r,upgrade:a}=c;if(!a)return;let o=we(K(R({},r),{consent:!0}));a(o),U.set(t,{config:K(R({},r),{consent:!0}),upgrade:null})}function ve(e){var i;let t=ee((i=e.ingestUrl)!=null?i:X),c={"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`},r={track:()=>{},goal:()=>{},identify:()=>{},getAssignment:()=>null,fetchWeights:()=>Promise.resolve([]),async assign(s,n,g){try{let f=new URLSearchParams({componentId:s});for(let S of n!=null?n:[])f.append("variantIds[]",S);let m=await fetch(`${t}/winner?${f.toString()}`,{headers:c});return m.ok?{variantId:(await m.json()).variantId,assignmentTtlMs:0}:n!=null&&n[0]?{variantId:n[0],assignmentTtlMs:0}:null}catch(f){return n!=null&&n[0]?{variantId:n[0],assignmentTtlMs:0}:null}},getGraph:()=>({pageNodes:[],capturedAt:0}),destroy:()=>{}},a={track:s=>r.track(s),goal:(s,n,g,f)=>r.goal(s,n,g,f),identify:s=>r.identify(s),getAssignment:(s,n)=>r.getAssignment(s,n),assign:(s,n,g,f)=>r.assign(s,n,g,f),fetchWeights:()=>r.fetchWeights(),getGraph:()=>r.getGraph(),destroy:()=>r.destroy()};function o(s){r=s}return{proxy:a,setInner:o}}function we(e){var L,A,N,$,_;if(typeof window=="undefined")return M;if(Z=e.apiKey,e.consent===!1){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."),M;let{proxy:d,setInner:u}=ve(e);return U.set(e.apiKey,{config:e,upgrade:u}),d}return U.set(e.apiKey,{config:e,upgrade:null}),M}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."),M;if(e.ingestUrl==="")return console.warn("[sentient] init() called with an empty ingestUrl. SDK disabled."),M;let t=(L=e.ingestUrl)!=null?L:X,c=Date.now(),r=H({ssrSessionId:e.ssrSessionId}),a=Y(),o=V({ingestUrl:t,apiKey:e.apiKey}),i=ee(t),s={"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`},n=G((A=navigator.userAgent)!=null?A:""),g=typeof window!="undefined"?window.location.origin:void 0,f=Q((N=document.referrer)!=null?N:"",g),m=($=e.sessionSegment)!=null?$:`${n}:${f}`,y=new Map;if(e.initialAssignments)for(let[d,u]of Object.entries(e.initialAssignments))a.set(d,m,{variantId:u,assignedAt:Date.now(),segment:m,confidence:1});let S=Promise.resolve(),v=r.getSessionId();if(v){let d=F((_=document.referrer)!=null?_:""),u=R({sessionId:v,deviceClass:n,trafficSource:f,referrerDomain:d,utmParams:Se(),timeOfDay:z(new Date),dayOfWeek:["sun","mon","tue","wed","thu","fri","sat"][new Date().getDay()],ephemeral:r.isEphemeral()},e.userId?{userId:e.userId}:{});try{S=fetch(`${i}/sessions`,{method:"POST",keepalive:!0,body:JSON.stringify(u),headers:s}).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:o});let x={goal(d,u={},h=1,T=0){let k=r.getSessionId();if(!k)return;let I=q();S.then(()=>{fetch(`${i}/goals`,{method:"POST",keepalive:!0,body:JSON.stringify({sessionId:k,name:d,metadata:u,weight:h,stepIndex:T,goalId:I}),headers:s}).catch(()=>{})})},identify(d){let u=r.getSessionId();u&&S.then(()=>{fetch(`${i}/sessions`,{method:"POST",keepalive:!0,body:JSON.stringify({sessionId:u,userId:d,ephemeral:r.isEphemeral()}),headers:s}).catch(()=>{})})},track(d){let u=r.getSessionId();if(!u)return;let h=K(R({},d),{id:q(),sessionId:u,timestamp:Date.now(),timeInSession:Date.now()-c});o.push(h),e.debug&&console.log("[sentient] track",h)},getAssignment(d,u){return a.get(d,u)},async assign(d,u,h,T){let k=r.getSessionId();if(!k)return null;let I=a.get(d,m);if(I&&(u!=null&&u.length||I.content!==void 0))return{variantId:I.variantId,assignmentTtlMs:0,content:I.content};let D=y.get(d);if(D)return D;let l=(async()=>{await S;try{let p={sessionId:k,componentId:d,variantIds:u};T!==void 0?p.agentDataByVariant=T:h!==void 0&&(p.agentData=h);let w=await fetch(`${i}/assign`,{method:"POST",body:JSON.stringify(p),headers:s});if(!w.ok)return null;let E=await w.json();return a.set(d,m,{variantId:E.variantId,assignedAt:Date.now(),segment:m,confidence:1,content:E.content}),E}catch(p){return null}finally{y.delete(d)}})();return y.set(d,l),l},async fetchWeights(){var d;try{let u=await fetch(`${i}/weights`,{headers:s});return u.ok?(d=(await u.json()).components)!=null?d:[]:[]}catch(u){return[]}},getGraph(){return{pageNodes:[],capturedAt:0}},destroy(){o.destroy(),r.destroy(),e.debug&&console.log("[sentient] destroyed")}};if(U.set(e.apiKey,{config:e,upgrade:null}),e.debug){let d=window;d.__sentient&&(d.__sentient.client=x)}return x}export{ye as a,De as b,we as c};
|
package/dist/index-graph.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var G=Object.defineProperty,le=Object.defineProperties,ge=Object.getOwnPropertyDescriptor,pe=Object.getOwnPropertyDescriptors,fe=Object.getOwnPropertyNames,X=Object.getOwnPropertySymbols;var ee=Object.prototype.hasOwnProperty,me=Object.prototype.propertyIsEnumerable;var Z=(e,t,n)=>t in e?G(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,D=(e,t)=>{for(var n in t||(t={}))ee.call(t,n)&&Z(e,n,t[n]);if(X)for(var n of X(t))me.call(t,n)&&Z(e,n,t[n]);return e},B=(e,t)=>le(e,pe(t));var he=(e,t)=>{for(var n in t)G(e,n,{get:t[n],enumerable:!0})},ye=(e,t,n,a)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of fe(t))!ee.call(e,i)&&i!==n&&G(e,i,{get:()=>t[i],enumerable:!(a=ge(t,i))||a.enumerable});return e};var Se=e=>ye(G({},"__esModule",{value:!0}),e);var it={};he(it,{deriveSessionSegment:()=>W,detectDeviceClass:()=>R,detectTimeOfDay:()=>P,detectTrafficSource:()=>M,init:()=>st,referrerDomainFromReferer:()=>U});module.exports=Se(it);var ve="_snt_uid";var N="_snt_uid";function we(){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 Ee(e){try{let t=document.cookie.match(new RegExp(`(?:^|; )${e}=([^;]*)`));return t?decodeURIComponent(t[1]):null}catch(t){return null}}function Ie(e,t,n){try{document.cookie=`${e}=${encodeURIComponent(t)}; max-age=${n}; SameSite=strict; path=/`}catch(a){}}function be(e){try{return localStorage.getItem(e)}catch(t){return null}}function Ce(e,t){try{return localStorage.setItem(e,t),!0}catch(n){return!1}}function xe(e){try{return sessionStorage.getItem(e)}catch(t){return null}}function _e(e,t){try{return sessionStorage.setItem(e,t),!0}catch(n){return!1}}function Ae(e){try{sessionStorage.removeItem(e)}catch(t){}}function Te(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 ke(e){try{localStorage.removeItem(e)}catch(t){}}function De(e){try{document.cookie=`${e}=; max-age=0; SameSite=strict; path=/`}catch(t){}}var Oe={getSessionId:()=>null,isEphemeral:()=>!1,destroy:()=>{}};function te(e){var d,l,g,m,u;if(typeof window=="undefined")return Oe;let t=(d=e==null?void 0:e.cookieName)!=null?d:ve,a=((l=e==null?void 0:e.cookieTTLDays)!=null?l:365)*24*60*60,i=(u=(m=(g=Ee(t))!=null?g:be(N))!=null?m:xe(N))!=null?u:we();Ie(t,i,a);let o=Ce(N,i),r=Te(t),s=o?!1:_e(N,i),c=!o&&!r&&!s;return{getSessionId:()=>i,isEphemeral:()=>c,destroy:()=>{i=null,De(t),ke(N),Ae(N)}}}var F="_snt_retry";var Ne={push:()=>{},flush:()=>{},destroy:()=>{}};function Re(e){try{let t=localStorage.getItem(F);if(!t)return[];let n=JSON.parse(t);return Array.isArray(n)?(localStorage.removeItem(F),n.slice(-e)):[]}catch(t){return[]}}function Q(e,t){try{let a=[...(()=>{try{let i=localStorage.getItem(F);if(!i)return[];let o=JSON.parse(i);return Array.isArray(o)?o:[]}catch(i){return[]}})(),...e].slice(-t);localStorage.setItem(F,JSON.stringify(a))}catch(n){}}function ne(e){var k,A,O;if(typeof window=="undefined")return Ne;let t=(k=e.flushIntervalMs)!=null?k:5e3,n=(A=e.maxBatchSize)!=null?A:20,a=(O=e.maxRetrySize)!=null?O:100,i=e.ingestUrl,o=e.apiKey,r=[],s=new Set,c=[],d=p=>{for(let y of p)l.delete(y),!s.has(y)&&(s.add(y),c.push(y));for(;c.length>500;){let y=c.shift();y&&s.delete(y)}},l=new Set,g=p=>{s.has(p.id)||l.has(p.id)||(l.add(p.id),r.push(p))},m=Re(a);for(let p of m)g(p);let u=0,h=0,E=p=>{if(p.length===0)return;let y=JSON.stringify(p),v=p.map(_=>_.id),I;try{I=fetch(i,{method:"POST",keepalive:!0,body:y,headers:{"Content-Type":"application/json",Authorization:`Bearer ${o}`}})}catch(_){Q(p,a);for(let J of v)l.delete(J);h++,u=Date.now()+Math.min(6e4,1e3*2**Math.min(h,6));return}let x=_=>{if(_.ok||_.status>=400&&_.status<500&&_.status!==429){d(v),h=0,u=0;return}Q(p,a);for(let J of v)l.delete(J);h++,u=Date.now()+Math.min(6e4,1e3*2**Math.min(h,6))};I instanceof Promise?I.then(x).catch(()=>{Q(p,a);for(let _ of v)l.delete(_);h++,u=Date.now()+Math.min(6e4,1e3*2**Math.min(h,6))}):x(I)},b=typeof TextEncoder!="undefined"?new TextEncoder:null,T=p=>b?b.encode(p).length:p.length,K=p=>{let y=[],v=2;for(let I of p){let x=T(JSON.stringify(I))+1;if(y.length>0&&v+x>57344||y.length>=n)break;y.push(I),v+=x}return y},C=()=>{try{if(Date.now()<u)return;for(;r.length>0;){let p=r.filter(v=>!s.has(v.id));if(r.length=0,p.length===0)break;let y=K(p);if(y.length===0)break;y.length<p.length&&r.push(...p.slice(y.length)),E(y)}}catch(p){}},L=!0,f=null;f=setInterval(()=>{L&&C()},t);let S=()=>{document.visibilityState==="hidden"&&C()},w=()=>{C()};return document.addEventListener("visibilitychange",S),window.addEventListener("beforeunload",w),{push(p){g(p),r.length>=n&&C()},flush:C,destroy(){L=!1,f!==null&&(clearInterval(f),f=null),document.removeEventListener("visibilitychange",S),window.removeEventListener("beforeunload",w),C()}}}var z="_snt_asgn_";function j(e,t){return`${e}:${t}`}function Me(e,t){return`${z}${e}_${t}`}function H(){try{let e=[];for(let t=0;t<localStorage.length;t++){let n=localStorage.key(t);n!=null&&n.startsWith(z)&&e.push(n)}return e}catch(e){return[]}}function re(e=18e5){let t=new Map,n=i=>i.assignedAt+e<Date.now();return typeof window!="undefined"&&(()=>{for(let i of H())try{let o=localStorage.getItem(i);if(!o)continue;let r=JSON.parse(o);if(n(r)){localStorage.removeItem(i);continue}let s=i.slice(z.length),c=s.lastIndexOf("_");if(c<0)continue;let d=s.slice(0,c),l=s.slice(c+1);t.set(j(d,l),r)}catch(o){}})(),{get(i,o){let r=t.get(j(i,o));return r?n(r)?(t.delete(j(i,o)),null):r:null},set(i,o,r){let s=j(i,o);t.set(s,r);try{localStorage.setItem(Me(i,o),JSON.stringify(r))}catch(c){}},invalidate(i){let o=`${i}:`;for(let r of[...t.keys()])r.startsWith(o)&&t.delete(r);for(let r of H()){let s=r.slice(z.length),c=s.lastIndexOf("_");if(c<0)continue;if(s.slice(0,c)===i)try{localStorage.removeItem(r)}catch(l){}}},clear(){t.clear();for(let i of H())try{localStorage.removeItem(i)}catch(o){}}}}function R(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 M(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(i){}let a=n.hostname.toLowerCase();return/(^|\.)(google|bing|duckduckgo|yahoo)\./.test(a)?"search":/(^|\.)(twitter|x\.com|facebook|linkedin|reddit|t\.co)/.test(a)?"social":"referral"}catch(n){return"direct"}}function U(e){if(!e)return null;try{return new URL(e).hostname}catch(t){return null}}function P(e){let t=e.getHours();return t<6?"night":t<12?"morning":t<18?"afternoon":"evening"}function W(e){let t=Ue("__segment__",e);return`${t.deviceClass}:${t.trafficSource}`}function Ue(e,t){var o,r,s,c,d,l,g;let n=(r=(o=t==null?void 0:t.userAgent)==null?void 0:o.trim())!=null?r:"",a=(c=(s=t==null?void 0:t.referer)==null?void 0:s.trim())!=null?c:"",i=(d=t==null?void 0:t.now)!=null?d:new Date;return{sessionId:e,ephemeral:!1,utmParams:(l=t==null?void 0:t.utmParams)!=null?l:{},deviceClass:n?R(n):"desktop",trafficSource:a?M(a,t==null?void 0:t.appOrigin):"direct",referrerDomain:U(a),timeOfDay:P(i),dayOfWeek:(g=["sun","mon","tue","wed","thu","fri","sat"][i.getDay()])!=null?g:"sun"}}var oe="https://api.sentient-ui.com/v1/events",Pe=null,Le=null;function $e(){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 $={track:()=>{},goal:()=>{},identify:()=>{},getAssignment:()=>null,assign:()=>Promise.resolve(null),getGraph:()=>({pageNodes:[],capturedAt:0}),destroy:()=>{}};function Ke(){try{let e={},t=new URLSearchParams(window.location.search);for(let[n,a]of t)n.startsWith("utm_")&&(e[n]=a);return e}catch(e){return{}}}function se(e){return e.replace(/\/events\/?$/,"")}function Ge(e){var i;let t=se((i=e.ingestUrl)!=null?i:oe),n={"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`},a={track:()=>{},goal:()=>{},identify:()=>{},getAssignment:()=>null,async assign(o,r,s){try{let c=new URLSearchParams({componentId:o});for(let g of r!=null?r:[])c.append("variantIds[]",g);let d=await fetch(`${t}/winner?${c.toString()}`,{headers:n});return d.ok?{variantId:(await d.json()).variantId,assignmentTtlMs:0}:r!=null&&r[0]?{variantId:r[0],assignmentTtlMs:0}:null}catch(c){return r!=null&&r[0]?{variantId:r[0],assignmentTtlMs:0}:null}},getGraph:()=>({pageNodes:[],capturedAt:0}),destroy:()=>{}};return Le=o=>{a=o},{track:o=>a.track(o),goal:(o,r)=>a.goal(o,r),identify:o=>a.identify(o),getAssignment:(o,r)=>a.getAssignment(o,r),assign:(o,r,s,c)=>a.assign(o,r,s,c),getGraph:()=>a.getGraph(),destroy:()=>a.destroy()}}function ie(e){var b,T,K,C,L;if(typeof window=="undefined")return $;if(Pe=e,e.consent===!1)return e.preConsentBehavior==="statistical_winner"?!e.apiKey||!e.apiKey.startsWith("pk_")?(console.warn("[sentient] init() called with an invalid apiKey \u2014 expected a pk_ public key. SDK disabled."),$):Ge(e):$;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."),$;if(e.ingestUrl==="")return console.warn("[sentient] init() called with an empty ingestUrl. SDK disabled."),$;let t=(b=e.ingestUrl)!=null?b:oe,n=Date.now(),a=te(),i=re(),o=ne({ingestUrl:t,apiKey:e.apiKey}),r=se(t),s={"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`},c=R((T=navigator.userAgent)!=null?T:""),d=typeof window!="undefined"?window.location.origin:void 0,l=M((K=document.referrer)!=null?K:"",d),g=(C=e.sessionSegment)!=null?C:`${c}:${l}`,m=new Map;if(e.initialAssignments)for(let[f,S]of Object.entries(e.initialAssignments))i.set(f,g,{variantId:S,assignedAt:Date.now(),segment:g,confidence:1});let u=Promise.resolve(),h=a.getSessionId();if(h){let f=U((L=document.referrer)!=null?L:""),S=D({sessionId:h,deviceClass:c,trafficSource:l,referrerDomain:f,utmParams:Ke(),timeOfDay:P(new Date),dayOfWeek:["sun","mon","tue","wed","thu","fri","sat"][new Date().getDay()],ephemeral:a.isEphemeral()},e.userId?{userId:e.userId}:{});try{u=fetch(`${r}/sessions`,{method:"POST",keepalive:!0,body:JSON.stringify(S),headers:s}).then(w=>{w.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(w){}}e.debug&&(console.log("[sentient] initialized",{context:e.context}),window.__sentient={client:null,queue:o});let E={goal(f,S={},w=1,k=0){let A=a.getSessionId();A&&u.then(()=>{fetch(`${r}/goals`,{method:"POST",keepalive:!0,body:JSON.stringify({sessionId:A,name:f,metadata:S,weight:w,stepIndex:k}),headers:s}).catch(()=>{})})},identify(f){let S=a.getSessionId();S&&u.then(()=>{fetch(`${r}/sessions`,{method:"POST",keepalive:!0,body:JSON.stringify({sessionId:S,userId:f,ephemeral:a.isEphemeral()}),headers:s}).catch(()=>{})})},track(f){let S=a.getSessionId();if(!S)return;let w=B(D({},f),{id:$e(),sessionId:S,timestamp:Date.now(),timeInSession:Date.now()-n});o.push(w),e.debug&&console.log("[sentient] track",w)},getAssignment(f,S){return i.get(f,S)},async assign(f,S,w,k){let A=a.getSessionId();if(!A)return null;let O=i.get(f,g);if(O)return{variantId:O.variantId,assignmentTtlMs:0,content:O.content};let p=m.get(f);if(p)return p;let y=(async()=>{await u;try{let v={sessionId:A,componentId:f,variantIds:S};k!==void 0?v.agentDataByVariant=k:w!==void 0&&(v.agentData=w);let I=await fetch(`${r}/assign`,{method:"POST",body:JSON.stringify(v),headers:s});if(!I.ok)return null;let x=await I.json();return i.set(f,g,{variantId:x.variantId,assignedAt:Date.now(),segment:g,confidence:1,content:x.content}),x}catch(v){return null}finally{m.delete(f)}})();return m.set(f,y),y},getGraph(){return{pageNodes:[],capturedAt:0}},destroy(){o.destroy(),a.destroy(),e.debug&&console.log("[sentient] destroyed")}};if(e.debug){let f=window;f.__sentient&&(f.__sentient.client=E)}return E}var Be=new Set(["SECTION","ARTICLE","MAIN","DIV"]),Fe="h1, h2, h3",je={scan:async()=>({nodes:[],edges:[],scannedAt:0}),observe:()=>{},getProminenceScore:()=>0,destroy:()=>{}};function q(e,t,n){return n<=t?0:Math.max(0,Math.min(1,(e-t)/(n-t)))}function ze(e){var t,n,a;try{let i=e;for(let o of Object.keys(i)){if(!o.startsWith("__reactFiber")&&!o.startsWith("__reactInternalInstance"))continue;let r=i[o],s=(a=(t=r==null?void 0:r.type)==null?void 0:t.displayName)!=null?a:(n=r==null?void 0:r.type)==null?void 0:n.name;if(s&&s.length>1)return s}}catch(i){}}function Je(e){let t={};for(let n of Array.from(e.attributes))n.name.startsWith("data-")&&(t[n.name]=n.value);return t}function Qe(e){let t=e.getAttribute("data-sentient-type");if(t)return t;let n=e.getAttribute("role");return n||"generic"}function He(e){var t,n;return(n=(t=e.getAttribute("data-sentient-id"))!=null?t:e.getAttribute("id"))!=null?n:e.tagName.toLowerCase()}function We(e){let t=0,n=e.parentElement;for(;n;)t++,n=n.parentElement;return t}function Y(e,t){var a,i,o;let n=e.querySelector(Fe);return{componentId:He(e),semanticType:Qe(e),ariaLabel:(a=e.getAttribute("aria-label"))!=null?a:void 0,headingText:(o=(i=n==null?void 0:n.textContent)==null?void 0:i.trim())!=null?o:void 0,isAboveFold:e.getBoundingClientRect().top<window.innerHeight,prominenceScore:t(e),depth:We(e),reactComponentName:ze(e),dataAttributes:Je(e)}}function ae(e){var o;let t=[],n=new Set,a="__root__",i=new Map;for(let[r,s]of e){let c=r.parentElement,d=a;for(;c;){if(e.has(c)){d=e.get(c);let g=e.get(r),m=`${d}->${g}`;!n.has(m)&&d!==g&&(n.add(m),t.push({fromComponentId:d,toComponentId:g,weight:.6}));break}c=c.parentElement}let l=(o=i.get(d))!=null?o:[];l.push(r),i.set(d,l)}for(let r of i.values())if(!(r.length<2))for(let s=0;s<r.length;s++)for(let c=s+1;c<r.length;c++){let d=e.get(r[s]),l=e.get(r[c]);if(d===l)continue;let g=`${d}->${l}::sib`,m=`${l}->${d}::sib`;n.has(g)||(n.add(g),t.push({fromComponentId:d,toComponentId:l,weight:.3})),n.has(m)||(n.add(m),t.push({fromComponentId:l,toComponentId:d,weight:.3}))}return t}function qe(e){let t=[],n=new Set,a=new Map;return document.querySelectorAll("[data-sentient-id]").forEach(r=>{if(r instanceof Element&&!n.has(r)){n.add(r);let s=Y(r,e);t.push(s),a.set(r,s.componentId)}}),document.querySelectorAll("section, article, main, aside").forEach(r=>{if(!(r instanceof Element)||n.has(r))return;let s=r.hasAttribute("aria-label"),c=r.hasAttribute("data-sentient-id");if(!s&&!c)return;n.add(r);let d=Y(r,e);t.push(d),a.set(r,d.componentId)}),{nodes:t,edges:ae(a)}}function ce(){if(typeof window=="undefined")return je;let e=null,t=0,n=null,a=s=>{try{let c=window.getComputedStyle(s),d=parseFloat(c.fontSize)||12,l=parseFloat(c.zIndex)||0,g=s.getBoundingClientRect(),m=Math.max(g.top,0),u=window.innerHeight||1,h=1/(m/u+1),E=q(d,12,48)*.4+q(h,0,1)*.4+q(l,0,100)*.2;return Math.max(0,Math.min(1,E))}catch(c){return .5}};return{scan:()=>new Promise(s=>{let c=()=>{let{nodes:d,edges:l}=qe(a);s({nodes:d,edges:l,scannedAt:Date.now()})};try{typeof requestIdleCallback=="function"?t=requestIdleCallback(c,{timeout:100}):c()}catch(d){c()}}),observe:s=>{n=s;try{e=new MutationObserver(c=>{let d=[],l=new Map;for(let g of c)g.type==="childList"&&g.addedNodes.forEach(m=>{if(!(m instanceof Element)||!Be.has(m.tagName))return;let u=m.hasAttribute("data-sentient-id"),h=m.hasAttribute("aria-label");if(!u&&!h)return;let E=Y(m,a);d.push(E),l.set(m,E.componentId)});d.length>0&&n&&n({nodes:d,edges:ae(l),addedAt:Date.now()})}),e.observe(document.body,{childList:!0,subtree:!0})}catch(c){}},getProminenceScore:a,destroy:()=>{if(e&&(e.disconnect(),e=null),t&&typeof cancelIdleCallback=="function")try{cancelIdleCallback(t)}catch(s){}t=0,n=null}}}var V="_snt_graph_nodes",de="_snt_graph_edges",Ye={pricing:["features","faq"],features:["pricing"],faq:["pricing"],social_proof:["cta"],cta:["social_proof","hero","trust"],hero:["cta"],comparison:["pricing"],trust:["cta"]};function Ve(e){var t;return(t=Ye[e])!=null?t:[]}function Xe(e,t){try{let n=localStorage.getItem(e);return n?JSON.parse(n):t}catch(n){return t}}function Ze(e,t){try{localStorage.setItem(e,JSON.stringify(t))}catch(n){}}var et=new Set(["pricing","hero","social_proof","cta","features","faq","comparison","trust","navigation","generic"]);function tt(e){return et.has(e)?e:"generic"}function nt(e,t,n){let a=`${e}:${t}:${n.join(",")}`,i=5381;for(let o=0;o<a.length;o++)i=(i<<5)+i+a.charCodeAt(o)&4294967295;return(i>>>0).toString(16).padStart(8,"0")}function ue(e){let t=new Map,n=new Map,a=()=>{typeof window!="undefined"&&Ze(V,[...t.values()])},i=o=>{var r;try{let s=JSON.parse(o);t.clear();for(let c of(r=s.pageNodes)!=null?r:[])t.set(c.componentId,c)}catch(s){}};if(typeof window!="undefined"){let o=Xe(V,[]);for(let r of o)t.set(r.componentId,r);try{localStorage.removeItem(de)}catch(r){}}return{addPageNode(o){t.set(o.componentId,o),a()},addStructuralEdge(o){let r=`${o.fromComponentId}->${o.toComponentId}`;n.set(r,o)},syncOnce(){var r,s;if(!(e!=null&&e.syncUrl)||typeof window=="undefined")return;let o=[...t.values()];if(o.length!==0)try{let c=new Map;for(let u of o){let h=(r=c.get(u.semanticType))!=null?r:[];h.push(u),c.set(u.semanticType,h)}let d=[],l=new Set;for(let u of o)for(let h of Ve(u.semanticType)){let E=(s=c.get(h))!=null?s:[];for(let b of E){if(b.componentId===u.componentId)continue;let T=`semantic:${u.componentId}->${b.componentId}`;l.has(T)||(l.add(T),d.push({fromComponentId:u.componentId,toComponentId:b.componentId,type:"semantic",weight:.4,confidence:.9}))}}let g=new Set(o.map(u=>u.componentId));for(let u of n.values()){if(!g.has(u.fromComponentId)||!g.has(u.toComponentId))continue;let h=`structural:${u.fromComponentId}->${u.toComponentId}`;l.has(h)||(l.add(h),d.push({fromComponentId:u.fromComponentId,toComponentId:u.toComponentId,type:"structural",weight:u.weight,confidence:1}))}let m={pageUrl:window.location.href,nodes:o.map(u=>{let h=tt(u.semanticType);return{componentId:u.componentId,semanticType:h,answers:u.answers,contentHash:nt(u.componentId,h,u.answers),prominenceScore:u.prominenceScore,depthInPage:u.depth}}),edges:d};fetch(e.syncUrl,{method:"POST",keepalive:!0,headers:D({"Content-Type":"application/json"},e.apiKey?{Authorization:`Bearer ${e.apiKey}`}:{}),body:JSON.stringify(m)}).catch(()=>{})}catch(c){}},snapshot(){return{pageNodes:[...t.values()],capturedAt:Date.now()}},serialize(){return JSON.stringify({pageNodes:[...t.values()]})},restore:i,destroy(){if(typeof window!="undefined")try{localStorage.removeItem(V),localStorage.removeItem(de)}catch(o){}}}}var rt="https://api.sentient-ui.com/v1/events";function ot(){try{let e=document.cookie.match(/(?:^|; )_snt_uid=([^;]*)/);return e?decodeURIComponent(e[1]):void 0}catch(e){return}}function st(e){var o;let t=ie(e);if(!e.graph||typeof window=="undefined")return t;let n=ce(),a=(o=e.ingestUrl)!=null?o:rt,i=ue({syncUrl:a.replace(/\/events\/?$/,"/graph/sync"),apiKey:e.apiKey,projectId:e.apiKey,sessionId:ot()});try{let r=localStorage.getItem("_snt_graph_nodes");r&&i.restore(JSON.stringify({pageNodes:JSON.parse(r)}))}catch(r){}return n.scan().then(r=>{for(let s of r.nodes)i.addPageNode({id:s.componentId,componentId:s.componentId,semanticType:s.semanticType,answers:s.headingText?[s.headingText]:[],prominenceScore:s.prominenceScore,depth:s.depth});for(let s of r.edges)i.addStructuralEdge(s);i.syncOnce()}),n.observe(r=>{for(let s of r.nodes)i.addPageNode({id:s.componentId,componentId:s.componentId,semanticType:s.semanticType,answers:s.headingText?[s.headingText]:[],prominenceScore:s.prominenceScore,depth:s.depth});for(let s of r.edges)i.addStructuralEdge(s)}),B(D({},t),{getGraph:()=>i.snapshot(),destroy:()=>{n.destroy(),i.destroy(),t.destroy()}})}0&&(module.exports={deriveSessionSegment,detectDeviceClass,detectTimeOfDay,detectTrafficSource,init,referrerDomainFromReferer});
|
|
1
|
+
"use strict";var W=Object.defineProperty,pe=Object.defineProperties,fe=Object.getOwnPropertyDescriptor,me=Object.getOwnPropertyDescriptors,he=Object.getOwnPropertyNames,Z=Object.getOwnPropertySymbols;var te=Object.prototype.hasOwnProperty,ye=Object.prototype.propertyIsEnumerable;var ee=(e,t,n)=>t in e?W(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,D=(e,t)=>{for(var n in t||(t={}))te.call(t,n)&&ee(e,n,t[n]);if(Z)for(var n of Z(t))ye.call(t,n)&&ee(e,n,t[n]);return e},B=(e,t)=>pe(e,me(t));var Se=(e,t)=>{for(var n in t)W(e,n,{get:t[n],enumerable:!0})},ve=(e,t,n,d)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of he(t))!te.call(e,s)&&s!==n&&W(e,s,{get:()=>t[s],enumerable:!(d=fe(t,s))||d.enumerable});return e};var we=e=>ve(W({},"__esModule",{value:!0}),e);var it={};Se(it,{deriveSessionSegment:()=>H,detectDeviceClass:()=>O,detectTimeOfDay:()=>U,detectTrafficSource:()=>R,init:()=>st,referrerDomainFromReferer:()=>M});module.exports=we(it);var Ee="_snt_uid";var N="_snt_uid";function Ie(){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 be(e){try{let t=document.cookie.match(new RegExp(`(?:^|; )${e}=([^;]*)`));return t?decodeURIComponent(t[1]):null}catch(t){return null}}function Ce(e,t,n){try{document.cookie=`${e}=${encodeURIComponent(t)}; max-age=${n}; SameSite=strict; path=/`}catch(d){}}function xe(e){try{return localStorage.getItem(e)}catch(t){return null}}function _e(e,t){try{return localStorage.setItem(e,t),!0}catch(n){return!1}}function Te(e){try{return sessionStorage.getItem(e)}catch(t){return null}}function Ae(e,t){try{return sessionStorage.setItem(e,t),!0}catch(n){return!1}}function ke(e){try{sessionStorage.removeItem(e)}catch(t){}}function De(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 Ne(e){try{localStorage.removeItem(e)}catch(t){}}function Oe(e){try{document.cookie=`${e}=; max-age=0; SameSite=strict; path=/`}catch(t){}}var Re={getSessionId:()=>null,isEphemeral:()=>!1,destroy:()=>{}};function ne(e){var c,u,g,h,l,y;if(typeof window=="undefined")return Re;let t=(c=e==null?void 0:e.cookieName)!=null?c:Ee,d=((u=e==null?void 0:e.cookieTTLDays)!=null?u:365)*24*60*60,s=(y=(l=(h=(g=be(t))!=null?g:xe(N))!=null?h:Te(N))!=null?l:e==null?void 0:e.ssrSessionId)!=null?y:Ie();Ce(t,s,d);let i=_e(N,s),r=De(t),a=i?!1:Ae(N,s),o=!i&&!r&&!a;return{getSessionId:()=>s,isEphemeral:()=>o,destroy:()=>{s=null,Oe(t),Ne(N),ke(N)}}}var Me={push:()=>{},flush:()=>{},destroy:()=>{}};function Ue(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 J(e,t,n){try{let s=[...(()=>{try{let i=localStorage.getItem(n);if(!i)return[];let r=JSON.parse(i);return Array.isArray(r)?r:[]}catch(i){return[]}})(),...e].slice(-t);localStorage.setItem(n,JSON.stringify(s))}catch(d){}}function re(e){var A,C,P;if(typeof window=="undefined")return Me;let t=(A=e.flushIntervalMs)!=null?A:5e3,n=(C=e.maxBatchSize)!=null?C:20,d=(P=e.maxRetrySize)!=null?P:100,s=e.ingestUrl,i=e.apiKey,r=`_snt_retry_${i.slice(0,12)}`,a=[],o=new Set,c=[],u=p=>{for(let S of p)g.delete(S),!o.has(S)&&(o.add(S),c.push(S));for(;c.length>500;){let S=c.shift();S&&o.delete(S)}},g=new Set,h=p=>{o.has(p.id)||g.has(p.id)||(g.add(p.id),a.push(p))},l=Ue(d,r);for(let p of l)h(p);let y=0,v=0,_=p=>{if(p.length===0)return;let S=JSON.stringify(p),E=p.map(x=>x.id),I;try{I=fetch(s,{method:"POST",keepalive:!0,body:S,headers:{"Content-Type":"application/json",Authorization:`Bearer ${i}`}})}catch(x){J(p,d,r);for(let z of E)g.delete(z);v++,y=Date.now()+Math.min(6e4,1e3*2**Math.min(v,6));return}let L=x=>{if(x.ok||x.status>=400&&x.status<500&&x.status!==429){u(E),v=0,y=0;return}J(p,d,r);for(let z of E)g.delete(z);v++,y=Date.now()+Math.min(6e4,1e3*2**Math.min(v,6))};I instanceof Promise?I.then(L).catch(()=>{J(p,d,r);for(let x of E)g.delete(x);v++,y=Date.now()+Math.min(6e4,1e3*2**Math.min(v,6))}):L(I)},T=typeof TextEncoder!="undefined"?new TextEncoder:null,G=p=>T?T.encode(p).length:p.length,K=p=>{let S=[],E=2;for(let I of p){let L=G(JSON.stringify(I))+1;if(S.length>0&&E+L>57344||S.length>=n)break;S.push(I),E+=L}return S},b=()=>{try{if(Date.now()<y)return;for(;a.length>0;){let p=a.filter(E=>!o.has(E.id));if(a.length=0,p.length===0)break;let S=K(p);if(S.length===0)break;S.length<p.length&&a.push(...p.slice(S.length)),_(S)}}catch(p){}},f=!0,m=null;m=setInterval(()=>{f&&b()},t);let w=()=>{document.visibilityState==="hidden"&&b()},k=()=>{b()};return document.addEventListener("visibilitychange",w),window.addEventListener("beforeunload",k),{push(p){h(p),a.length>=n&&b()},flush:b,destroy(){f=!1,m!==null&&(clearInterval(m),m=null),document.removeEventListener("visibilitychange",w),window.removeEventListener("beforeunload",k),b()}}}var j="_snt_asgn_";function F(e,t){return`${e}:${t}`}function Pe(e,t){return`${j}${e}_${t}`}function Q(){try{let e=[];for(let t=0;t<localStorage.length;t++){let n=localStorage.key(t);n!=null&&n.startsWith(j)&&e.push(n)}return e}catch(e){return[]}}function oe(e=18e5){let t=new Map,n=s=>s.assignedAt+e<Date.now();return typeof window!="undefined"&&(()=>{for(let s of Q())try{let i=localStorage.getItem(s);if(!i)continue;let r=JSON.parse(i);if(n(r)){localStorage.removeItem(s);continue}let a=s.slice(j.length),o=a.lastIndexOf("_");if(o<0)continue;let c=a.slice(0,o),u=a.slice(o+1);t.set(F(c,u),r)}catch(i){}})(),{get(s,i){let r=t.get(F(s,i));return r?n(r)?(t.delete(F(s,i)),null):r:null},set(s,i,r){let a=F(s,i);t.set(a,r);try{localStorage.setItem(Pe(s,i),JSON.stringify(r))}catch(o){}},invalidate(s){let i=`${s}:`;for(let r of[...t.keys()])r.startsWith(i)&&t.delete(r);for(let r of Q()){let a=r.slice(j.length),o=a.lastIndexOf("_");if(o<0)continue;if(a.slice(0,o)===s)try{localStorage.removeItem(r)}catch(u){}}},clear(){t.clear();for(let s of Q())try{localStorage.removeItem(s)}catch(i){}}}}function O(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 R(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(s){}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 M(e){if(!e)return null;try{return new URL(e).hostname}catch(t){return null}}function U(e){let t=e.getHours();return t<6?"night":t<12?"morning":t<18?"afternoon":"evening"}function H(e){let t=Le("__segment__",e);return`${t.deviceClass}:${t.trafficSource}`}function Le(e,t){var i,r,a,o,c,u,g;let n=(r=(i=t==null?void 0:t.userAgent)==null?void 0:i.trim())!=null?r:"",d=(o=(a=t==null?void 0:t.referer)==null?void 0:a.trim())!=null?o:"",s=(c=t==null?void 0:t.now)!=null?c:new Date;return{sessionId:e,ephemeral:!1,utmParams:(u=t==null?void 0:t.utmParams)!=null?u:{},deviceClass:n?O(n):"desktop",trafficSource:d?R(d,t==null?void 0:t.appOrigin):"direct",referrerDomain:M(d),timeOfDay:U(s),dayOfWeek:(g=["sun","mon","tue","wed","thu","fri","sat"][s.getDay()])!=null?g:"sun"}}var ie="https://api.sentient-ui.com/v1/events",q=new Map,$e=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 $={track:()=>{},goal:()=>{},identify:()=>{},getAssignment:()=>null,assign:()=>Promise.resolve(null),fetchWeights:()=>Promise.resolve([]),getGraph:()=>({pageNodes:[],capturedAt:0}),destroy:()=>{}};function Ge(){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 ae(e){return e.replace(/\/events\/?$/,"")}function Ke(e){var r;let t=ae((r=e.ingestUrl)!=null?r:ie),n={"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`},d={track:()=>{},goal:()=>{},identify:()=>{},getAssignment:()=>null,fetchWeights:()=>Promise.resolve([]),async assign(a,o,c){try{let u=new URLSearchParams({componentId:a});for(let l of o!=null?o:[])u.append("variantIds[]",l);let g=await fetch(`${t}/winner?${u.toString()}`,{headers:n});return g.ok?{variantId:(await g.json()).variantId,assignmentTtlMs:0}:o!=null&&o[0]?{variantId:o[0],assignmentTtlMs:0}:null}catch(u){return o!=null&&o[0]?{variantId:o[0],assignmentTtlMs:0}:null}},getGraph:()=>({pageNodes:[],capturedAt:0}),destroy:()=>{}},s={track:a=>d.track(a),goal:(a,o,c,u)=>d.goal(a,o,c,u),identify:a=>d.identify(a),getAssignment:(a,o)=>d.getAssignment(a,o),assign:(a,o,c,u)=>d.assign(a,o,c,u),fetchWeights:()=>d.fetchWeights(),getGraph:()=>d.getGraph(),destroy:()=>d.destroy()};function i(a){d=a}return{proxy:s,setInner:i}}function ce(e){var _,T,G,K,b;if(typeof window=="undefined")return $;if($e=e.apiKey,e.consent===!1){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."),$;let{proxy:f,setInner:m}=Ke(e);return q.set(e.apiKey,{config:e,upgrade:m}),f}return q.set(e.apiKey,{config:e,upgrade:null}),$}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."),$;if(e.ingestUrl==="")return console.warn("[sentient] init() called with an empty ingestUrl. SDK disabled."),$;let t=(_=e.ingestUrl)!=null?_:ie,n=Date.now(),d=ne({ssrSessionId:e.ssrSessionId}),s=oe(),i=re({ingestUrl:t,apiKey:e.apiKey}),r=ae(t),a={"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`},o=O((T=navigator.userAgent)!=null?T:""),c=typeof window!="undefined"?window.location.origin:void 0,u=R((G=document.referrer)!=null?G:"",c),g=(K=e.sessionSegment)!=null?K:`${o}:${u}`,h=new Map;if(e.initialAssignments)for(let[f,m]of Object.entries(e.initialAssignments))s.set(f,g,{variantId:m,assignedAt:Date.now(),segment:g,confidence:1});let l=Promise.resolve(),y=d.getSessionId();if(y){let f=M((b=document.referrer)!=null?b:""),m=D({sessionId:y,deviceClass:o,trafficSource:u,referrerDomain:f,utmParams:Ge(),timeOfDay:U(new Date),dayOfWeek:["sun","mon","tue","wed","thu","fri","sat"][new Date().getDay()],ephemeral:d.isEphemeral()},e.userId?{userId:e.userId}:{});try{l=fetch(`${r}/sessions`,{method:"POST",keepalive:!0,body:JSON.stringify(m),headers:a}).then(w=>{w.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(w){}}e.debug&&(console.log("[sentient] initialized",{context:e.context}),window.__sentient={client:null,queue:i});let v={goal(f,m={},w=1,k=0){let A=d.getSessionId();if(!A)return;let C=se();l.then(()=>{fetch(`${r}/goals`,{method:"POST",keepalive:!0,body:JSON.stringify({sessionId:A,name:f,metadata:m,weight:w,stepIndex:k,goalId:C}),headers:a}).catch(()=>{})})},identify(f){let m=d.getSessionId();m&&l.then(()=>{fetch(`${r}/sessions`,{method:"POST",keepalive:!0,body:JSON.stringify({sessionId:m,userId:f,ephemeral:d.isEphemeral()}),headers:a}).catch(()=>{})})},track(f){let m=d.getSessionId();if(!m)return;let w=B(D({},f),{id:se(),sessionId:m,timestamp:Date.now(),timeInSession:Date.now()-n});i.push(w),e.debug&&console.log("[sentient] track",w)},getAssignment(f,m){return s.get(f,m)},async assign(f,m,w,k){let A=d.getSessionId();if(!A)return null;let C=s.get(f,g);if(C&&(m!=null&&m.length||C.content!==void 0))return{variantId:C.variantId,assignmentTtlMs:0,content:C.content};let P=h.get(f);if(P)return P;let p=(async()=>{await l;try{let S={sessionId:A,componentId:f,variantIds:m};k!==void 0?S.agentDataByVariant=k:w!==void 0&&(S.agentData=w);let E=await fetch(`${r}/assign`,{method:"POST",body:JSON.stringify(S),headers:a});if(!E.ok)return null;let I=await E.json();return s.set(f,g,{variantId:I.variantId,assignedAt:Date.now(),segment:g,confidence:1,content:I.content}),I}catch(S){return null}finally{h.delete(f)}})();return h.set(f,p),p},async fetchWeights(){var f;try{let m=await fetch(`${r}/weights`,{headers:a});return m.ok?(f=(await m.json()).components)!=null?f:[]:[]}catch(m){return[]}},getGraph(){return{pageNodes:[],capturedAt:0}},destroy(){i.destroy(),d.destroy(),e.debug&&console.log("[sentient] destroyed")}};if(q.set(e.apiKey,{config:e,upgrade:null}),e.debug){let f=window;f.__sentient&&(f.__sentient.client=v)}return v}var We=new Set(["SECTION","ARTICLE","MAIN","DIV"]),Be="h1, h2, h3",Fe={scan:async()=>({nodes:[],edges:[],scannedAt:0}),observe:()=>{},getProminenceScore:()=>0,destroy:()=>{}};function V(e,t,n){return n<=t?0:Math.max(0,Math.min(1,(e-t)/(n-t)))}function je(e){var t,n,d;try{let s=e;for(let i of Object.keys(s)){if(!i.startsWith("__reactFiber")&&!i.startsWith("__reactInternalInstance"))continue;let r=s[i],a=(d=(t=r==null?void 0:r.type)==null?void 0:t.displayName)!=null?d:(n=r==null?void 0:r.type)==null?void 0:n.name;if(a&&a.length>1)return a}}catch(s){}}function ze(e){let t={};for(let n of Array.from(e.attributes))n.name.startsWith("data-")&&(t[n.name]=n.value);return t}function Je(e){let t=e.getAttribute("data-sentient-type");if(t)return t;let n=e.getAttribute("role");return n||"generic"}function Qe(e){var t,n;return(n=(t=e.getAttribute("data-sentient-id"))!=null?t:e.getAttribute("id"))!=null?n:e.tagName.toLowerCase()}function He(e){let t=0,n=e.parentElement;for(;n;)t++,n=n.parentElement;return t}function Y(e,t){var d,s,i;let n=e.querySelector(Be);return{componentId:Qe(e),semanticType:Je(e),ariaLabel:(d=e.getAttribute("aria-label"))!=null?d:void 0,headingText:(i=(s=n==null?void 0:n.textContent)==null?void 0:s.trim())!=null?i:void 0,isAboveFold:e.getBoundingClientRect().top<window.innerHeight,prominenceScore:t(e),depth:He(e),reactComponentName:je(e),dataAttributes:ze(e)}}function de(e){var i;let t=[],n=new Set,d="__root__",s=new Map;for(let[r,a]of e){let o=r.parentElement,c=d;for(;o;){if(e.has(o)){c=e.get(o);let g=e.get(r),h=`${c}->${g}`;!n.has(h)&&c!==g&&(n.add(h),t.push({fromComponentId:c,toComponentId:g,weight:.6}));break}o=o.parentElement}let u=(i=s.get(c))!=null?i:[];u.push(r),s.set(c,u)}for(let r of s.values())if(!(r.length<2))for(let a=0;a<r.length;a++)for(let o=a+1;o<r.length;o++){let c=e.get(r[a]),u=e.get(r[o]);if(c===u)continue;let g=`${c}->${u}::sib`,h=`${u}->${c}::sib`;n.has(g)||(n.add(g),t.push({fromComponentId:c,toComponentId:u,weight:.3})),n.has(h)||(n.add(h),t.push({fromComponentId:u,toComponentId:c,weight:.3}))}return t}function qe(e){let t=[],n=new Set,d=new Map;return document.querySelectorAll("[data-sentient-id]").forEach(r=>{if(r instanceof Element&&!n.has(r)){n.add(r);let a=Y(r,e);t.push(a),d.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"),o=r.hasAttribute("data-sentient-id");if(!a&&!o)return;n.add(r);let c=Y(r,e);t.push(c),d.set(r,c.componentId)}),{nodes:t,edges:de(d)}}function ue(){if(typeof window=="undefined")return Fe;let e=null,t=0,n=null,d=a=>{try{let o=window.getComputedStyle(a),c=parseFloat(o.fontSize)||12,u=parseFloat(o.zIndex)||0,g=a.getBoundingClientRect(),h=Math.max(g.top,0),l=window.innerHeight||1,y=1/(h/l+1),v=V(c,12,48)*.4+V(y,0,1)*.4+V(u,0,100)*.2;return Math.max(0,Math.min(1,v))}catch(o){return .5}};return{scan:()=>new Promise(a=>{let o=()=>{let{nodes:c,edges:u}=qe(d);a({nodes:c,edges:u,scannedAt:Date.now()})};try{typeof requestIdleCallback=="function"?t=requestIdleCallback(o,{timeout:100}):o()}catch(c){o()}}),observe:a=>{n=a;try{e=new MutationObserver(o=>{let c=[],u=new Map;for(let g of o)g.type==="childList"&&g.addedNodes.forEach(h=>{if(!(h instanceof Element)||!We.has(h.tagName))return;let l=h.hasAttribute("data-sentient-id"),y=h.hasAttribute("aria-label");if(!l&&!y)return;let v=Y(h,d);c.push(v),u.set(h,v.componentId)});c.length>0&&n&&n({nodes:c,edges:de(u),addedAt:Date.now()})}),e.observe(document.body,{childList:!0,subtree:!0})}catch(o){}},getProminenceScore:d,destroy:()=>{if(e&&(e.disconnect(),e=null),t&&typeof cancelIdleCallback=="function")try{cancelIdleCallback(t)}catch(a){}t=0,n=null}}}var X="_snt_graph_nodes",le="_snt_graph_edges",Ve={pricing:["features","faq"],features:["pricing"],faq:["pricing"],social_proof:["cta"],cta:["social_proof","hero","trust"],hero:["cta"],comparison:["pricing"],trust:["cta"]};function Ye(e){var t;return(t=Ve[e])!=null?t:[]}function Xe(e,t){try{let n=localStorage.getItem(e);return n?JSON.parse(n):t}catch(n){return t}}function Ze(e,t){try{localStorage.setItem(e,JSON.stringify(t))}catch(n){}}var et=new Set(["pricing","hero","social_proof","cta","features","faq","comparison","trust","navigation","generic"]);function tt(e){return et.has(e)?e:"generic"}function nt(e,t,n){let d=`${e}:${t}:${n.join(",")}`,s=5381;for(let i=0;i<d.length;i++)s=(s<<5)+s+d.charCodeAt(i)&4294967295;return(s>>>0).toString(16).padStart(8,"0")}function ge(e){let t=new Map,n=new Map,d=()=>{typeof window!="undefined"&&Ze(X,[...t.values()])},s=i=>{var r;try{let a=JSON.parse(i);t.clear();for(let o of(r=a.pageNodes)!=null?r:[])t.set(o.componentId,o)}catch(a){}};if(typeof window!="undefined"){let i=Xe(X,[]);for(let r of i)t.set(r.componentId,r);try{localStorage.removeItem(le)}catch(r){}}return{addPageNode(i){t.set(i.componentId,i),d()},addStructuralEdge(i){let r=`${i.fromComponentId}->${i.toComponentId}`;n.set(r,i)},syncOnce(){var r,a;if(!(e!=null&&e.syncUrl)||typeof window=="undefined")return;let i=[...t.values()];if(i.length!==0)try{let o=new Map;for(let l of i){let y=(r=o.get(l.semanticType))!=null?r:[];y.push(l),o.set(l.semanticType,y)}let c=[],u=new Set;for(let l of i)for(let y of Ye(l.semanticType)){let v=(a=o.get(y))!=null?a:[];for(let _ of v){if(_.componentId===l.componentId)continue;let T=`semantic:${l.componentId}->${_.componentId}`;u.has(T)||(u.add(T),c.push({fromComponentId:l.componentId,toComponentId:_.componentId,type:"semantic",weight:.4,confidence:.9}))}}let g=new Set(i.map(l=>l.componentId));for(let l of n.values()){if(!g.has(l.fromComponentId)||!g.has(l.toComponentId))continue;let y=`structural:${l.fromComponentId}->${l.toComponentId}`;u.has(y)||(u.add(y),c.push({fromComponentId:l.fromComponentId,toComponentId:l.toComponentId,type:"structural",weight:l.weight,confidence:1}))}let h={pageUrl:window.location.href,nodes:i.map(l=>{let y=tt(l.semanticType);return{componentId:l.componentId,semanticType:y,answers:l.answers,contentHash:nt(l.componentId,y,l.answers),prominenceScore:l.prominenceScore,depthInPage:l.depth}}),edges:c};fetch(e.syncUrl,{method:"POST",keepalive:!0,headers:D({"Content-Type":"application/json"},e.apiKey?{Authorization:`Bearer ${e.apiKey}`}:{}),body:JSON.stringify(h)}).catch(()=>{})}catch(o){}},snapshot(){return{pageNodes:[...t.values()],capturedAt:Date.now()}},serialize(){return JSON.stringify({pageNodes:[...t.values()]})},restore:s,destroy(){if(typeof window!="undefined")try{localStorage.removeItem(X),localStorage.removeItem(le)}catch(i){}}}}var rt="https://api.sentient-ui.com/v1/events";function ot(){try{let e=document.cookie.match(/(?:^|; )_snt_uid=([^;]*)/);return e?decodeURIComponent(e[1]):void 0}catch(e){return}}function st(e){var a;let t=ce(e);if(!e.graph||typeof window=="undefined")return t;let n=ue(),d=(a=e.ingestUrl)!=null?a:rt,s=ge({syncUrl:d.replace(/\/events\/?$/,"/graph/sync"),apiKey:e.apiKey,projectId:e.apiKey,sessionId:ot()});try{let o=localStorage.getItem("_snt_graph_nodes");o&&s.restore(JSON.stringify({pageNodes:JSON.parse(o)}))}catch(o){}n.scan().then(o=>{for(let c of o.nodes)s.addPageNode({id:c.componentId,componentId:c.componentId,semanticType:c.semanticType,answers:c.headingText?[c.headingText]:[],prominenceScore:c.prominenceScore,depth:c.depth});for(let c of o.edges)s.addStructuralEdge(c);s.syncOnce()});let i=null,r=()=>{i!==null&&clearTimeout(i),i=setTimeout(()=>{i=null,s.syncOnce()},500)};return n.observe(o=>{for(let c of o.nodes)s.addPageNode({id:c.componentId,componentId:c.componentId,semanticType:c.semanticType,answers:c.headingText?[c.headingText]:[],prominenceScore:c.prominenceScore,depth:c.depth});for(let c of o.edges)s.addStructuralEdge(c);r()}),B(D({},t),{getGraph:()=>s.snapshot(),destroy:()=>{i!==null&&clearTimeout(i),n.destroy(),s.destroy(),t.destroy()}})}0&&(module.exports={deriveSessionSegment,detectDeviceClass,detectTimeOfDay,detectTrafficSource,init,referrerDomainFromReferer});
|
package/dist/index-graph.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{c as v}from"./chunk-
|
|
1
|
+
import{c as v}from"./chunk-PXHVZ2OY.mjs";import{a as h,b,c as x,d as _,e as O,f as R,g as M}from"./chunk-QCYVBCUV.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 d=e;for(let s of Object.keys(d)){if(!s.startsWith("__reactFiber")&&!s.startsWith("__reactInternalInstance"))continue;let r=d[s],i=(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(i&&i.length>1)return i}}catch(d){}}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,d,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=(d=n==null?void 0:n.textContent)==null?void 0:d.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__",d=new Map;for(let[r,i]of e){let a=r.parentElement,o=p;for(;a;){if(e.has(a)){o=e.get(a);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}a=a.parentElement}let u=(s=d.get(o))!=null?s:[];u.push(r),d.set(o,u)}for(let r of d.values())if(!(r.length<2))for(let i=0;i<r.length;i++)for(let a=i+1;a<r.length;a++){let o=e.get(r[i]),u=e.get(r[a]);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 i=I(r,e);t.push(i),p.set(r,i.componentId)}}),document.querySelectorAll("section, article, main, aside").forEach(r=>{if(!(r instanceof Element)||n.has(r))return;let i=r.hasAttribute("aria-label"),a=r.hasAttribute("data-sentient-id");if(!i&&!a)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=i=>{try{let a=window.getComputedStyle(i),o=parseFloat(a.fontSize)||12,u=parseFloat(a.zIndex)||0,m=i.getBoundingClientRect(),g=Math.max(m.top,0),c=window.innerHeight||1,l=1/(g/c+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(a){return .5}};return{scan:()=>new Promise(i=>{let a=()=>{let{nodes:o,edges:u}=F(p);i({nodes:o,edges:u,scannedAt:Date.now()})};try{typeof requestIdleCallback=="function"?t=requestIdleCallback(a,{timeout:100}):a()}catch(o){a()}}),observe:i=>{n=i;try{e=new MutationObserver(a=>{let o=[],u=new Map;for(let m of a)m.type==="childList"&&m.addedNodes.forEach(g=>{if(!(g instanceof Element)||!P.has(g.tagName))return;let c=g.hasAttribute("data-sentient-id"),l=g.hasAttribute("aria-label");if(!c&&!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(a){}},getProminenceScore:p,destroy:()=>{if(e&&(e.disconnect(),e=null),t&&typeof cancelIdleCallback=="function")try{cancelIdleCallback(t)}catch(i){}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(",")}`,d=5381;for(let s=0;s<p.length;s++)d=(d<<5)+d+p.charCodeAt(s)&4294967295;return(d>>>0).toString(16).padStart(8,"0")}function T(e){let t=new Map,n=new Map,p=()=>{typeof window!="undefined"&&H(C,[...t.values()])},d=s=>{var r;try{let i=JSON.parse(s);t.clear();for(let a of(r=i.pageNodes)!=null?r:[])t.set(a.componentId,a)}catch(i){}};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,i;if(!(e!=null&&e.syncUrl)||typeof window=="undefined")return;let s=[...t.values()];if(s.length!==0)try{let a=new Map;for(let c of s){let l=(r=a.get(c.semanticType))!=null?r:[];l.push(c),a.set(c.semanticType,l)}let o=[],u=new Set;for(let c of s)for(let l of q(c.semanticType)){let f=(i=a.get(l))!=null?i:[];for(let y of f){if(y.componentId===c.componentId)continue;let E=`semantic:${c.componentId}->${y.componentId}`;u.has(E)||(u.add(E),o.push({fromComponentId:c.componentId,toComponentId:y.componentId,type:"semantic",weight:.4,confidence:.9}))}}let m=new Set(s.map(c=>c.componentId));for(let c of n.values()){if(!m.has(c.fromComponentId)||!m.has(c.toComponentId))continue;let l=`structural:${c.fromComponentId}->${c.toComponentId}`;u.has(l)||(u.add(l),o.push({fromComponentId:c.fromComponentId,toComponentId:c.toComponentId,type:"structural",weight:c.weight,confidence:1}))}let g={pageUrl:window.location.href,nodes:s.map(c=>{let l=B(c.semanticType);return{componentId:c.componentId,semanticType:l,answers:c.answers,contentHash:V(c.componentId,l,c.answers),prominenceScore:c.prominenceScore,depthInPage:c.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(a){}},snapshot(){return{pageNodes:[...t.values()],capturedAt:Date.now()}},serialize(){return JSON.stringify({pageNodes:[...t.values()]})},restore:d,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 i;let t=v(e);if(!e.graph||typeof window=="undefined")return t;let n=N(),p=(i=e.ingestUrl)!=null?i:W,d=T({syncUrl:p.replace(/\/events\/?$/,"/graph/sync"),apiKey:e.apiKey,projectId:e.apiKey,sessionId:Y()});try{let a=localStorage.getItem("_snt_graph_nodes");a&&d.restore(JSON.stringify({pageNodes:JSON.parse(a)}))}catch(a){}n.scan().then(a=>{for(let o of a.nodes)d.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 a.edges)d.addStructuralEdge(o);d.syncOnce()});let s=null,r=()=>{s!==null&&clearTimeout(s),s=setTimeout(()=>{s=null,d.syncOnce()},500)};return n.observe(a=>{for(let o of a.nodes)d.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 a.edges)d.addStructuralEdge(o);r()}),b(h({},t),{getGraph:()=>d.snapshot(),destroy:()=>{s!==null&&clearTimeout(s),n.destroy(),d.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
|
@@ -4,6 +4,13 @@ export { d as deriveSessionSegment, a as detectDeviceClass, c as detectTimeOfDay
|
|
|
4
4
|
type SessionConfig = {
|
|
5
5
|
cookieName?: string;
|
|
6
6
|
cookieTTLDays?: number;
|
|
7
|
+
/**
|
|
8
|
+
* Session ID generated during SSR (e.g. from `loadAdaptiveAssignments`).
|
|
9
|
+
* Used as the fallback when no existing cookie or localStorage entry is found,
|
|
10
|
+
* so the client adopts the same session the server used for variant assignment
|
|
11
|
+
* on first visit rather than generating a new, orphaned ID.
|
|
12
|
+
*/
|
|
13
|
+
ssrSessionId?: string;
|
|
7
14
|
};
|
|
8
15
|
type SessionManager = {
|
|
9
16
|
getSessionId(): string | null;
|
|
@@ -165,12 +172,28 @@ type SentientConfig = {
|
|
|
165
172
|
*/
|
|
166
173
|
preConsentBehavior?: 'statistical_winner' | 'control';
|
|
167
174
|
userId?: string;
|
|
175
|
+
/**
|
|
176
|
+
* Session ID generated server-side (from `loadAdaptiveAssignments` / `loadAdaptiveDecision`).
|
|
177
|
+
* When provided, the client adopts this ID on first visit instead of generating a new one,
|
|
178
|
+
* ensuring events and goals are attributed to the same session the server used for assignment.
|
|
179
|
+
*/
|
|
180
|
+
ssrSessionId?: string;
|
|
168
181
|
};
|
|
169
182
|
type AssignResult = {
|
|
170
183
|
variantId: string;
|
|
171
184
|
assignmentTtlMs: number;
|
|
172
185
|
content?: string;
|
|
173
186
|
};
|
|
187
|
+
type WeightEntry = {
|
|
188
|
+
variantId: string;
|
|
189
|
+
pulls: number;
|
|
190
|
+
avgReward: number | null;
|
|
191
|
+
};
|
|
192
|
+
type ComponentWeightEntry = {
|
|
193
|
+
componentId: string;
|
|
194
|
+
updatedAt: number;
|
|
195
|
+
variants: WeightEntry[];
|
|
196
|
+
};
|
|
174
197
|
type SentientClient = {
|
|
175
198
|
track(event: Omit<SentientEvent, 'id' | 'sessionId' | 'timestamp' | 'timeInSession'>): void;
|
|
176
199
|
goal(name: string, metadata?: Record<string, unknown>, weight?: number, stepIndex?: number): void;
|
|
@@ -178,6 +201,8 @@ type SentientClient = {
|
|
|
178
201
|
getAssignment(componentId: string, segment: string): Assignment | null;
|
|
179
202
|
/** Server-side variant assignment. Caches the result locally per (component, segment). */
|
|
180
203
|
assign(componentId: string, variantIds?: string[], agentData?: unknown, agentDataByVariant?: Record<string, unknown>): Promise<AssignResult | null>;
|
|
204
|
+
/** Fetches current bandit weights for all components in this project. Used by the provider to keep live-weight polling fresh. */
|
|
205
|
+
fetchWeights(): Promise<ComponentWeightEntry[]>;
|
|
181
206
|
getGraph(): GraphSnapshot;
|
|
182
207
|
destroy(): void;
|
|
183
208
|
};
|
|
@@ -186,11 +211,12 @@ type SentientClient = {
|
|
|
186
211
|
* Upgrades a pre-consent client (created with `consent: false, preConsentBehavior: 'statistical_winner'`)
|
|
187
212
|
* to a fully-tracking client. Call this from your consent management platform callback.
|
|
188
213
|
* For React apps, prefer updating the `consent` prop on `<AdaptiveProvider>`.
|
|
214
|
+
* Pass `apiKey` to target a specific project; omit to upgrade the most-recently-initialized client.
|
|
189
215
|
*/
|
|
190
|
-
declare function grantConsent(): void;
|
|
216
|
+
declare function grantConsent(apiKey?: string): void;
|
|
191
217
|
/**
|
|
192
218
|
* Initializes the Sentient client. Returns a no-op client during SSR.
|
|
193
219
|
*/
|
|
194
220
|
declare function init(config: SentientConfig): SentientClient;
|
|
195
221
|
|
|
196
|
-
export { type AssignResult, type Assignment, type AssignmentCache, type ContentAddedEvent, type DOMScanner, type EventQueue, type EventType, type GraphClient, type GraphConfig, type GraphSnapshot, type MicroSignalEmitter, type MicroSignalType, type PageNode, type QueueConfig, type ScanResult, type ScannedNode, type SentientClient, type SentientConfig, type SentientEvent, type SessionConfig, type SessionManager, attachMicroSignalDetectors, grantConsent, init };
|
|
222
|
+
export { type AssignResult, type Assignment, type AssignmentCache, type ComponentWeightEntry, type ContentAddedEvent, type DOMScanner, type EventQueue, type EventType, type GraphClient, type GraphConfig, type GraphSnapshot, type MicroSignalEmitter, type MicroSignalType, type PageNode, type QueueConfig, type ScanResult, type ScannedNode, type SentientClient, type SentientConfig, type SentientEvent, type SessionConfig, type SessionManager, type WeightEntry, attachMicroSignalDetectors, grantConsent, init };
|
package/dist/index.d.ts
CHANGED
|
@@ -4,6 +4,13 @@ export { d as deriveSessionSegment, a as detectDeviceClass, c as detectTimeOfDay
|
|
|
4
4
|
type SessionConfig = {
|
|
5
5
|
cookieName?: string;
|
|
6
6
|
cookieTTLDays?: number;
|
|
7
|
+
/**
|
|
8
|
+
* Session ID generated during SSR (e.g. from `loadAdaptiveAssignments`).
|
|
9
|
+
* Used as the fallback when no existing cookie or localStorage entry is found,
|
|
10
|
+
* so the client adopts the same session the server used for variant assignment
|
|
11
|
+
* on first visit rather than generating a new, orphaned ID.
|
|
12
|
+
*/
|
|
13
|
+
ssrSessionId?: string;
|
|
7
14
|
};
|
|
8
15
|
type SessionManager = {
|
|
9
16
|
getSessionId(): string | null;
|
|
@@ -165,12 +172,28 @@ type SentientConfig = {
|
|
|
165
172
|
*/
|
|
166
173
|
preConsentBehavior?: 'statistical_winner' | 'control';
|
|
167
174
|
userId?: string;
|
|
175
|
+
/**
|
|
176
|
+
* Session ID generated server-side (from `loadAdaptiveAssignments` / `loadAdaptiveDecision`).
|
|
177
|
+
* When provided, the client adopts this ID on first visit instead of generating a new one,
|
|
178
|
+
* ensuring events and goals are attributed to the same session the server used for assignment.
|
|
179
|
+
*/
|
|
180
|
+
ssrSessionId?: string;
|
|
168
181
|
};
|
|
169
182
|
type AssignResult = {
|
|
170
183
|
variantId: string;
|
|
171
184
|
assignmentTtlMs: number;
|
|
172
185
|
content?: string;
|
|
173
186
|
};
|
|
187
|
+
type WeightEntry = {
|
|
188
|
+
variantId: string;
|
|
189
|
+
pulls: number;
|
|
190
|
+
avgReward: number | null;
|
|
191
|
+
};
|
|
192
|
+
type ComponentWeightEntry = {
|
|
193
|
+
componentId: string;
|
|
194
|
+
updatedAt: number;
|
|
195
|
+
variants: WeightEntry[];
|
|
196
|
+
};
|
|
174
197
|
type SentientClient = {
|
|
175
198
|
track(event: Omit<SentientEvent, 'id' | 'sessionId' | 'timestamp' | 'timeInSession'>): void;
|
|
176
199
|
goal(name: string, metadata?: Record<string, unknown>, weight?: number, stepIndex?: number): void;
|
|
@@ -178,6 +201,8 @@ type SentientClient = {
|
|
|
178
201
|
getAssignment(componentId: string, segment: string): Assignment | null;
|
|
179
202
|
/** Server-side variant assignment. Caches the result locally per (component, segment). */
|
|
180
203
|
assign(componentId: string, variantIds?: string[], agentData?: unknown, agentDataByVariant?: Record<string, unknown>): Promise<AssignResult | null>;
|
|
204
|
+
/** Fetches current bandit weights for all components in this project. Used by the provider to keep live-weight polling fresh. */
|
|
205
|
+
fetchWeights(): Promise<ComponentWeightEntry[]>;
|
|
181
206
|
getGraph(): GraphSnapshot;
|
|
182
207
|
destroy(): void;
|
|
183
208
|
};
|
|
@@ -186,11 +211,12 @@ type SentientClient = {
|
|
|
186
211
|
* Upgrades a pre-consent client (created with `consent: false, preConsentBehavior: 'statistical_winner'`)
|
|
187
212
|
* to a fully-tracking client. Call this from your consent management platform callback.
|
|
188
213
|
* For React apps, prefer updating the `consent` prop on `<AdaptiveProvider>`.
|
|
214
|
+
* Pass `apiKey` to target a specific project; omit to upgrade the most-recently-initialized client.
|
|
189
215
|
*/
|
|
190
|
-
declare function grantConsent(): void;
|
|
216
|
+
declare function grantConsent(apiKey?: string): void;
|
|
191
217
|
/**
|
|
192
218
|
* Initializes the Sentient client. Returns a no-op client during SSR.
|
|
193
219
|
*/
|
|
194
220
|
declare function init(config: SentientConfig): SentientClient;
|
|
195
221
|
|
|
196
|
-
export { type AssignResult, type Assignment, type AssignmentCache, type ContentAddedEvent, type DOMScanner, type EventQueue, type EventType, type GraphClient, type GraphConfig, type GraphSnapshot, type MicroSignalEmitter, type MicroSignalType, type PageNode, type QueueConfig, type ScanResult, type ScannedNode, type SentientClient, type SentientConfig, type SentientEvent, type SessionConfig, type SessionManager, attachMicroSignalDetectors, grantConsent, init };
|
|
222
|
+
export { type AssignResult, type Assignment, type AssignmentCache, type ComponentWeightEntry, type ContentAddedEvent, type DOMScanner, type EventQueue, type EventType, type GraphClient, type GraphConfig, type GraphSnapshot, type MicroSignalEmitter, type MicroSignalType, type PageNode, type QueueConfig, type ScanResult, type ScannedNode, type SentientClient, type SentientConfig, type SentientEvent, type SessionConfig, type SessionManager, type WeightEntry, attachMicroSignalDetectors, grantConsent, init };
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var N=Object.defineProperty,ae=Object.defineProperties,ce=Object.getOwnPropertyDescriptor,le=Object.getOwnPropertyDescriptors,ue=Object.getOwnPropertyNames,q=Object.getOwnPropertySymbols;var X=Object.prototype.hasOwnProperty,de=Object.prototype.propertyIsEnumerable;var V=(e,t,r)=>t in e?N(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,B=(e,t)=>{for(var r in t||(t={}))X.call(t,r)&&V(e,r,t[r]);if(q)for(var r of q(t))de.call(t,r)&&V(e,r,t[r]);return e},z=(e,t)=>ae(e,le(t));var ge=(e,t)=>{for(var r in t)N(e,r,{get:t[r],enumerable:!0})},fe=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of ue(t))!X.call(e,i)&&i!==r&&N(e,i,{get:()=>t[i],enumerable:!(o=ce(t,i))||o.enumerable});return e};var me=e=>fe(N({},"__esModule",{value:!0}),e);var Pe={};ge(Pe,{attachMicroSignalDetectors:()=>ie,deriveSessionSegment:()=>ne,detectDeviceClass:()=>O,detectTimeOfDay:()=>L,detectTrafficSource:()=>R,grantConsent:()=>Le,init:()=>oe,referrerDomainFromReferer:()=>U});module.exports=me(Pe);var pe="_snt_uid";var C="_snt_uid";function ye(){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 he(e){try{let t=document.cookie.match(new RegExp(`(?:^|; )${e}=([^;]*)`));return t?decodeURIComponent(t[1]):null}catch(t){return null}}function Se(e,t,r){try{document.cookie=`${e}=${encodeURIComponent(t)}; max-age=${r}; SameSite=strict; path=/`}catch(o){}}function ve(e){try{return localStorage.getItem(e)}catch(t){return null}}function we(e,t){try{return localStorage.setItem(e,t),!0}catch(r){return!1}}function xe(e){try{return sessionStorage.getItem(e)}catch(t){return null}}function Ee(e,t){try{return sessionStorage.setItem(e,t),!0}catch(r){return!1}}function _e(e){try{sessionStorage.removeItem(e)}catch(t){}}function be(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 ke(e){try{localStorage.removeItem(e)}catch(t){}}function Ie(e){try{document.cookie=`${e}=; max-age=0; SameSite=strict; path=/`}catch(t){}}var Te={getSessionId:()=>null,isEphemeral:()=>!1,destroy:()=>{}};function Z(e){var f,d,m,v,y;if(typeof window=="undefined")return Te;let t=(f=e==null?void 0:e.cookieName)!=null?f:pe,o=((d=e==null?void 0:e.cookieTTLDays)!=null?d:365)*24*60*60,i=(y=(v=(m=he(t))!=null?m:ve(C))!=null?v:xe(C))!=null?y:ye();Se(t,i,o);let s=we(C,i),n=be(t),a=s?!1:Ee(C,i),c=!s&&!n&&!a;return{getSessionId:()=>i,isEphemeral:()=>c,destroy:()=>{i=null,Ie(t),ke(C),_e(C)}}}var G="_snt_retry";var Ce={push:()=>{},flush:()=>{},destroy:()=>{}};function De(e){try{let t=localStorage.getItem(G);if(!t)return[];let r=JSON.parse(t);return Array.isArray(r)?(localStorage.removeItem(G),r.slice(-e)):[]}catch(t){return[]}}function J(e,t){try{let o=[...(()=>{try{let i=localStorage.getItem(G);if(!i)return[];let s=JSON.parse(i);return Array.isArray(s)?s:[]}catch(i){return[]}})(),...e].slice(-t);localStorage.setItem(G,JSON.stringify(o))}catch(r){}}function ee(e){var I,k,T;if(typeof window=="undefined")return Ce;let t=(I=e.flushIntervalMs)!=null?I:5e3,r=(k=e.maxBatchSize)!=null?k:20,o=(T=e.maxRetrySize)!=null?T:100,i=e.ingestUrl,s=e.apiKey,n=[],a=new Set,c=[],f=l=>{for(let g of l)d.delete(g),!a.has(g)&&(a.add(g),c.push(g));for(;c.length>500;){let g=c.shift();g&&a.delete(g)}},d=new Set,m=l=>{a.has(l.id)||d.has(l.id)||(d.add(l.id),n.push(l))},v=De(o);for(let l of v)m(l);let y=0,w=0,P=l=>{if(l.length===0)return;let g=JSON.stringify(l),h=l.map(b=>b.id),x;try{x=fetch(i,{method:"POST",keepalive:!0,body:g,headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`}})}catch(b){J(l,o);for(let W of h)d.delete(W);w++,y=Date.now()+Math.min(6e4,1e3*2**Math.min(w,6));return}let _=b=>{if(b.ok||b.status>=400&&b.status<500&&b.status!==429){f(h),w=0,y=0;return}J(l,o);for(let W of h)d.delete(W);w++,y=Date.now()+Math.min(6e4,1e3*2**Math.min(w,6))};x instanceof Promise?x.then(_).catch(()=>{J(l,o);for(let b of h)d.delete(b);w++,y=Date.now()+Math.min(6e4,1e3*2**Math.min(w,6))}):_(x)},D=typeof TextEncoder!="undefined"?new TextEncoder:null,$=l=>D?D.encode(l).length:l.length,K=l=>{let g=[],h=2;for(let x of l){let _=$(JSON.stringify(x))+1;if(g.length>0&&h+_>57344||g.length>=r)break;g.push(x),h+=_}return g},E=()=>{try{if(Date.now()<y)return;for(;n.length>0;){let l=n.filter(h=>!a.has(h.id));if(n.length=0,l.length===0)break;let g=K(l);if(g.length===0)break;g.length<l.length&&n.push(...l.slice(g.length)),P(g)}}catch(l){}},A=!0,u=null;u=setInterval(()=>{A&&E()},t);let p=()=>{document.visibilityState==="hidden"&&E()},S=()=>{E()};return document.addEventListener("visibilitychange",p),window.addEventListener("beforeunload",S),{push(l){m(l),n.length>=r&&E()},flush:E,destroy(){A=!1,u!==null&&(clearInterval(u),u=null),document.removeEventListener("visibilitychange",p),window.removeEventListener("beforeunload",S),E()}}}var F="_snt_asgn_";function Q(e,t){return`${e}:${t}`}function Ae(e,t){return`${F}${e}_${t}`}function j(){try{let e=[];for(let t=0;t<localStorage.length;t++){let r=localStorage.key(t);r!=null&&r.startsWith(F)&&e.push(r)}return e}catch(e){return[]}}function te(e=18e5){let t=new Map,r=i=>i.assignedAt+e<Date.now();return typeof window!="undefined"&&(()=>{for(let i of j())try{let s=localStorage.getItem(i);if(!s)continue;let n=JSON.parse(s);if(r(n)){localStorage.removeItem(i);continue}let a=i.slice(F.length),c=a.lastIndexOf("_");if(c<0)continue;let f=a.slice(0,c),d=a.slice(c+1);t.set(Q(f,d),n)}catch(s){}})(),{get(i,s){let n=t.get(Q(i,s));return n?r(n)?(t.delete(Q(i,s)),null):n:null},set(i,s,n){let a=Q(i,s);t.set(a,n);try{localStorage.setItem(Ae(i,s),JSON.stringify(n))}catch(c){}},invalidate(i){let s=`${i}:`;for(let n of[...t.keys()])n.startsWith(s)&&t.delete(n);for(let n of j()){let a=n.slice(F.length),c=a.lastIndexOf("_");if(c<0)continue;if(a.slice(0,c)===i)try{localStorage.removeItem(n)}catch(d){}}},clear(){t.clear();for(let i of j())try{localStorage.removeItem(i)}catch(s){}}}}function O(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 R(e,t){if(!e)return"direct";try{let r=new URL(e);if(t)try{if(new URL(t).host===r.host)return"direct"}catch(i){}let o=r.hostname.toLowerCase();return/(^|\.)(google|bing|duckduckgo|yahoo)\./.test(o)?"search":/(^|\.)(twitter|x\.com|facebook|linkedin|reddit|t\.co)/.test(o)?"social":"referral"}catch(r){return"direct"}}function U(e){if(!e)return null;try{return new URL(e).hostname}catch(t){return null}}function L(e){let t=e.getHours();return t<6?"night":t<12?"morning":t<18?"afternoon":"evening"}function ne(e){let t=Oe("__segment__",e);return`${t.deviceClass}:${t.trafficSource}`}function Oe(e,t){var s,n,a,c,f,d,m;let r=(n=(s=t==null?void 0:t.userAgent)==null?void 0:s.trim())!=null?n:"",o=(c=(a=t==null?void 0:t.referer)==null?void 0:a.trim())!=null?c:"",i=(f=t==null?void 0:t.now)!=null?f:new Date;return{sessionId:e,ephemeral:!1,utmParams:(d=t==null?void 0:t.utmParams)!=null?d:{},deviceClass:r?O(r):"desktop",trafficSource:o?R(o,t==null?void 0:t.appOrigin):"direct",referrerDomain:U(o),timeOfDay:L(i),dayOfWeek:(m=["sun","mon","tue","wed","thu","fri","sat"][i.getDay()])!=null?m:"sun"}}function ie(e,t,r){let o=[];{let n=!1,a=[],c=()=>{if(n)return;let f=Date.now();for(a.push(f);a.length>0&&f-a[0]>500;)a.shift();a.length>=3&&(n=!0,e("rage_click"))};t.addEventListener("click",c),o.push(()=>t.removeEventListener("click",c))}{let i=!1,s=n=>{if(i||!(n.target instanceof Node)||!t.contains(n.target)&&t!==n.target)return;i=!0;let a=typeof window!="undefined"?window.getSelection():null,c=a?a.toString().length:0;e("text_copy",{selectionLength:c})};document.addEventListener("copy",s),o.push(()=>document.removeEventListener("copy",s))}{let i=!1,s=!1,n=null,a=()=>{n!==null&&(clearTimeout(n),n=null)},c=()=>{i||!s||(a(),n=setTimeout(()=>{!i&&s&&(i=!0,e("scroll_hesitation"))},3e3))},f=()=>{a(),c()},d=v=>{for(let y of v)s=y.intersectionRatio>.3,s?c():a()};window.__lastIOCallback=d;let m=new IntersectionObserver(d,{threshold:[.3]});m.observe(t),window.addEventListener("scroll",f,{passive:!0}),o.push(()=>{m.disconnect(),window.removeEventListener("scroll",f),a()})}{let i=!1,s=r!=null?r:Date.now(),n=()=>{if(i||document.visibilityState!=="hidden")return;let a=Date.now()-s;a<15e3&&(i=!0,e("tab_loss",{timeOnPage:a}))};document.addEventListener("visibilitychange",n),o.push(()=>document.removeEventListener("visibilitychange",n))}return()=>{for(let i of o)i()}}var re="https://api.sentient-ui.com/v1/events",H=null,Y=null;function Re(){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 M={track:()=>{},goal:()=>{},identify:()=>{},getAssignment:()=>null,assign:()=>Promise.resolve(null),getGraph:()=>({pageNodes:[],capturedAt:0}),destroy:()=>{}};function Ue(){try{let e={},t=new URLSearchParams(window.location.search);for(let[r,o]of t)r.startsWith("utm_")&&(e[r]=o);return e}catch(e){return{}}}function se(e){return e.replace(/\/events\/?$/,"")}function Le(){if(typeof window=="undefined")return;if(!H){console.warn("[sentient] grantConsent() called before init()");return}let e=Y;Y=null;let t=oe(z(B({},H),{consent:!0}));e==null||e(t)}function Me(e){var i;let t=se((i=e.ingestUrl)!=null?i:re),r={"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`},o={track:()=>{},goal:()=>{},identify:()=>{},getAssignment:()=>null,async assign(s,n,a){try{let c=new URLSearchParams({componentId:s});for(let m of n!=null?n:[])c.append("variantIds[]",m);let f=await fetch(`${t}/winner?${c.toString()}`,{headers:r});return f.ok?{variantId:(await f.json()).variantId,assignmentTtlMs:0}:n!=null&&n[0]?{variantId:n[0],assignmentTtlMs:0}:null}catch(c){return n!=null&&n[0]?{variantId:n[0],assignmentTtlMs:0}:null}},getGraph:()=>({pageNodes:[],capturedAt:0}),destroy:()=>{}};return Y=s=>{o=s},{track:s=>o.track(s),goal:(s,n)=>o.goal(s,n),identify:s=>o.identify(s),getAssignment:(s,n)=>o.getAssignment(s,n),assign:(s,n,a,c)=>o.assign(s,n,a,c),getGraph:()=>o.getGraph(),destroy:()=>o.destroy()}}function oe(e){var D,$,K,E,A;if(typeof window=="undefined")return M;if(H=e,e.consent===!1)return e.preConsentBehavior==="statistical_winner"?!e.apiKey||!e.apiKey.startsWith("pk_")?(console.warn("[sentient] init() called with an invalid apiKey \u2014 expected a pk_ public key. SDK disabled."),M):Me(e):M;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."),M;if(e.ingestUrl==="")return console.warn("[sentient] init() called with an empty ingestUrl. SDK disabled."),M;let t=(D=e.ingestUrl)!=null?D:re,r=Date.now(),o=Z(),i=te(),s=ee({ingestUrl:t,apiKey:e.apiKey}),n=se(t),a={"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`},c=O(($=navigator.userAgent)!=null?$:""),f=typeof window!="undefined"?window.location.origin:void 0,d=R((K=document.referrer)!=null?K:"",f),m=(E=e.sessionSegment)!=null?E:`${c}:${d}`,v=new Map;if(e.initialAssignments)for(let[u,p]of Object.entries(e.initialAssignments))i.set(u,m,{variantId:p,assignedAt:Date.now(),segment:m,confidence:1});let y=Promise.resolve(),w=o.getSessionId();if(w){let u=U((A=document.referrer)!=null?A:""),p=B({sessionId:w,deviceClass:c,trafficSource:d,referrerDomain:u,utmParams:Ue(),timeOfDay:L(new Date),dayOfWeek:["sun","mon","tue","wed","thu","fri","sat"][new Date().getDay()],ephemeral:o.isEphemeral()},e.userId?{userId:e.userId}:{});try{y=fetch(`${n}/sessions`,{method:"POST",keepalive:!0,body:JSON.stringify(p),headers:a}).then(S=>{S.status===402&&console.warn("[SentientUI] Session limit exceeded for this project. The bandit will stop learning until the limit resets. Upgrade at sentient-ui.com/pricing")}).catch(()=>{})}catch(S){}}e.debug&&(console.log("[sentient] initialized",{context:e.context}),window.__sentient={client:null,queue:s});let P={goal(u,p={},S=1,I=0){let k=o.getSessionId();k&&y.then(()=>{fetch(`${n}/goals`,{method:"POST",keepalive:!0,body:JSON.stringify({sessionId:k,name:u,metadata:p,weight:S,stepIndex:I}),headers:a}).catch(()=>{})})},identify(u){let p=o.getSessionId();p&&y.then(()=>{fetch(`${n}/sessions`,{method:"POST",keepalive:!0,body:JSON.stringify({sessionId:p,userId:u,ephemeral:o.isEphemeral()}),headers:a}).catch(()=>{})})},track(u){let p=o.getSessionId();if(!p)return;let S=z(B({},u),{id:Re(),sessionId:p,timestamp:Date.now(),timeInSession:Date.now()-r});s.push(S),e.debug&&console.log("[sentient] track",S)},getAssignment(u,p){return i.get(u,p)},async assign(u,p,S,I){let k=o.getSessionId();if(!k)return null;let T=i.get(u,m);if(T)return{variantId:T.variantId,assignmentTtlMs:0,content:T.content};let l=v.get(u);if(l)return l;let g=(async()=>{await y;try{let h={sessionId:k,componentId:u,variantIds:p};I!==void 0?h.agentDataByVariant=I:S!==void 0&&(h.agentData=S);let x=await fetch(`${n}/assign`,{method:"POST",body:JSON.stringify(h),headers:a});if(!x.ok)return null;let _=await x.json();return i.set(u,m,{variantId:_.variantId,assignedAt:Date.now(),segment:m,confidence:1,content:_.content}),_}catch(h){return null}finally{v.delete(u)}})();return v.set(u,g),g},getGraph(){return{pageNodes:[],capturedAt:0}},destroy(){s.destroy(),o.destroy(),e.debug&&console.log("[sentient] destroyed")}};if(e.debug){let u=window;u.__sentient&&(u.__sentient.client=P)}return P}0&&(module.exports={attachMicroSignalDetectors,deriveSessionSegment,detectDeviceClass,detectTimeOfDay,detectTrafficSource,grantConsent,init,referrerDomainFromReferer});
|
|
1
|
+
"use strict";var G=Object.defineProperty,ce=Object.defineProperties,le=Object.getOwnPropertyDescriptor,ue=Object.getOwnPropertyDescriptors,de=Object.getOwnPropertyNames,V=Object.getOwnPropertySymbols;var q=Object.prototype.hasOwnProperty,ge=Object.prototype.propertyIsEnumerable;var Y=(e,t,n)=>t in e?G(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,R=(e,t)=>{for(var n in t||(t={}))q.call(t,n)&&Y(e,n,t[n]);if(V)for(var n of V(t))ge.call(t,n)&&Y(e,n,t[n]);return e},Q=(e,t)=>ce(e,ue(t));var fe=(e,t)=>{for(var n in t)G(e,n,{get:t[n],enumerable:!0})},me=(e,t,n,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of de(t))!q.call(e,o)&&o!==n&&G(e,o,{get:()=>t[o],enumerable:!(i=le(t,o))||i.enumerable});return e};var pe=e=>me(G({},"__esModule",{value:!0}),e);var Pe={};fe(Pe,{attachMicroSignalDetectors:()=>ne,deriveSessionSegment:()=>te,detectDeviceClass:()=>U,detectTimeOfDay:()=>P,detectTrafficSource:()=>L,grantConsent:()=>Le,init:()=>ae,referrerDomainFromReferer:()=>M});module.exports=pe(Pe);var he="_snt_uid";var T="_snt_uid";function ye(){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 Se(e){try{let t=document.cookie.match(new RegExp(`(?:^|; )${e}=([^;]*)`));return t?decodeURIComponent(t[1]):null}catch(t){return null}}function ve(e,t,n){try{document.cookie=`${e}=${encodeURIComponent(t)}; max-age=${n}; SameSite=strict; path=/`}catch(i){}}function we(e){try{return localStorage.getItem(e)}catch(t){return null}}function xe(e,t){try{return localStorage.setItem(e,t),!0}catch(n){return!1}}function Ee(e){try{return sessionStorage.getItem(e)}catch(t){return null}}function _e(e,t){try{return sessionStorage.setItem(e,t),!0}catch(n){return!1}}function be(e){try{sessionStorage.removeItem(e)}catch(t){}}function ke(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 Ie(e){try{localStorage.removeItem(e)}catch(t){}}function Ce(e){try{document.cookie=`${e}=; max-age=0; SameSite=strict; path=/`}catch(t){}}var Te={getSessionId:()=>null,isEphemeral:()=>!1,destroy:()=>{}};function X(e){var g,f,m,y,S,v;if(typeof window=="undefined")return Te;let t=(g=e==null?void 0:e.cookieName)!=null?g:he,i=((f=e==null?void 0:e.cookieTTLDays)!=null?f:365)*24*60*60,o=(v=(S=(y=(m=Se(t))!=null?m:we(T))!=null?y:Ee(T))!=null?S:e==null?void 0:e.ssrSessionId)!=null?v:ye();ve(t,o,i);let c=xe(T,o),a=ke(t),s=c?!1:_e(T,o),r=!c&&!a&&!s;return{getSessionId:()=>o,isEphemeral:()=>r,destroy:()=>{o=null,Ce(t),Ie(T),be(T)}}}var De={push:()=>{},flush:()=>{},destroy:()=>{}};function Ae(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 j(e,t,n){try{let o=[...(()=>{try{let c=localStorage.getItem(n);if(!c)return[];let a=JSON.parse(c);return Array.isArray(a)?a:[]}catch(c){return[]}})(),...e].slice(-t);localStorage.setItem(n,JSON.stringify(o))}catch(i){}}function Z(e){var I,b,A;if(typeof window=="undefined")return De;let t=(I=e.flushIntervalMs)!=null?I:5e3,n=(b=e.maxBatchSize)!=null?b:20,i=(A=e.maxRetrySize)!=null?A:100,o=e.ingestUrl,c=e.apiKey,a=`_snt_retry_${c.slice(0,12)}`,s=[],r=new Set,g=[],f=l=>{for(let p of l)m.delete(p),!r.has(p)&&(r.add(p),g.push(p));for(;g.length>500;){let p=g.shift();p&&r.delete(p)}},m=new Set,y=l=>{r.has(l.id)||m.has(l.id)||(m.add(l.id),s.push(l))},S=Ae(i,a);for(let l of S)y(l);let v=0,E=0,K=l=>{if(l.length===0)return;let p=JSON.stringify(l),w=l.map(k=>k.id),x;try{x=fetch(o,{method:"POST",keepalive:!0,body:p,headers:{"Content-Type":"application/json",Authorization:`Bearer ${c}`}})}catch(k){j(l,i,a);for(let J of w)m.delete(J);E++,v=Date.now()+Math.min(6e4,1e3*2**Math.min(E,6));return}let O=k=>{if(k.ok||k.status>=400&&k.status<500&&k.status!==429){f(w),E=0,v=0;return}j(l,i,a);for(let J of w)m.delete(J);E++,v=Date.now()+Math.min(6e4,1e3*2**Math.min(E,6))};x instanceof Promise?x.then(O).catch(()=>{j(l,i,a);for(let k of w)m.delete(k);E++,v=Date.now()+Math.min(6e4,1e3*2**Math.min(E,6))}):O(x)},D=typeof TextEncoder!="undefined"?new TextEncoder:null,W=l=>D?D.encode(l).length:l.length,B=l=>{let p=[],w=2;for(let x of l){let O=W(JSON.stringify(x))+1;if(p.length>0&&w+O>57344||p.length>=n)break;p.push(x),w+=O}return p},_=()=>{try{if(Date.now()<v)return;for(;s.length>0;){let l=s.filter(w=>!r.has(w.id));if(s.length=0,l.length===0)break;let p=B(l);if(p.length===0)break;p.length<l.length&&s.push(...l.slice(p.length)),K(p)}}catch(l){}},u=!0,d=null;d=setInterval(()=>{u&&_()},t);let h=()=>{document.visibilityState==="hidden"&&_()},C=()=>{_()};return document.addEventListener("visibilitychange",h),window.addEventListener("beforeunload",C),{push(l){y(l),s.length>=n&&_()},flush:_,destroy(){u=!1,d!==null&&(clearInterval(d),d=null),document.removeEventListener("visibilitychange",h),window.removeEventListener("beforeunload",C),_()}}}var z="_snt_asgn_";function F(e,t){return`${e}:${t}`}function Oe(e,t){return`${z}${e}_${t}`}function H(){try{let e=[];for(let t=0;t<localStorage.length;t++){let n=localStorage.key(t);n!=null&&n.startsWith(z)&&e.push(n)}return e}catch(e){return[]}}function ee(e=18e5){let t=new Map,n=o=>o.assignedAt+e<Date.now();return typeof window!="undefined"&&(()=>{for(let o of H())try{let c=localStorage.getItem(o);if(!c)continue;let a=JSON.parse(c);if(n(a)){localStorage.removeItem(o);continue}let s=o.slice(z.length),r=s.lastIndexOf("_");if(r<0)continue;let g=s.slice(0,r),f=s.slice(r+1);t.set(F(g,f),a)}catch(c){}})(),{get(o,c){let a=t.get(F(o,c));return a?n(a)?(t.delete(F(o,c)),null):a:null},set(o,c,a){let s=F(o,c);t.set(s,a);try{localStorage.setItem(Oe(o,c),JSON.stringify(a))}catch(r){}},invalidate(o){let c=`${o}:`;for(let a of[...t.keys()])a.startsWith(c)&&t.delete(a);for(let a of H()){let s=a.slice(z.length),r=s.lastIndexOf("_");if(r<0)continue;if(s.slice(0,r)===o)try{localStorage.removeItem(a)}catch(f){}}},clear(){t.clear();for(let o of H())try{localStorage.removeItem(o)}catch(c){}}}}function U(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 L(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(o){}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 M(e){if(!e)return null;try{return new URL(e).hostname}catch(t){return null}}function P(e){let t=e.getHours();return t<6?"night":t<12?"morning":t<18?"afternoon":"evening"}function te(e){let t=Re("__segment__",e);return`${t.deviceClass}:${t.trafficSource}`}function Re(e,t){var c,a,s,r,g,f,m;let n=(a=(c=t==null?void 0:t.userAgent)==null?void 0:c.trim())!=null?a:"",i=(r=(s=t==null?void 0:t.referer)==null?void 0:s.trim())!=null?r:"",o=(g=t==null?void 0:t.now)!=null?g:new Date;return{sessionId:e,ephemeral:!1,utmParams:(f=t==null?void 0:t.utmParams)!=null?f:{},deviceClass:n?U(n):"desktop",trafficSource:i?L(i,t==null?void 0:t.appOrigin):"direct",referrerDomain:M(i),timeOfDay:P(o),dayOfWeek:(m=["sun","mon","tue","wed","thu","fri","sat"][o.getDay()])!=null?m:"sun"}}function ne(e,t,n){var o;let i=[];{let s=!1,r=[],g=()=>{if(s)return;let f=Date.now();for(r.push(f);r.length>0&&f-r[0]>500;)r.shift();r.length>=3&&(s=!0,e("rage_click"))};t.addEventListener("click",g),i.push(()=>t.removeEventListener("click",g))}{let c=!1,a=s=>{if(c||!(s.target instanceof Node)||!t.contains(s.target)&&t!==s.target)return;c=!0;let r=typeof window!="undefined"?window.getSelection():null,g=r?r.toString().length:0;e("text_copy",{selectionLength:g})};document.addEventListener("copy",a),i.push(()=>document.removeEventListener("copy",a))}{let c=!1,a=!1,s=null,r=()=>{s!==null&&(clearTimeout(s),s=null)},g=()=>{c||!a||(r(),s=setTimeout(()=>{!c&&a&&(c=!0,e("scroll_hesitation"))},3e3))},f=()=>{r(),g()},m=S=>{for(let v of S)a=v.intersectionRatio>.3,a?g():r()};typeof process!="undefined"&&((o=process.env)==null?void 0:o.NODE_ENV)!=="production"&&(window.__lastIOCallback=m);let y=new IntersectionObserver(m,{threshold:[.3]});y.observe(t),window.addEventListener("scroll",f,{passive:!0}),i.push(()=>{y.disconnect(),window.removeEventListener("scroll",f),r()})}{let c=!1,a=n!=null?n:Date.now(),s=()=>{if(c||document.visibilityState!=="hidden")return;let r=Date.now()-a;r<15e3&&(c=!0,e("tab_loss",{timeOnPage:r}))};document.addEventListener("visibilitychange",s),i.push(()=>document.removeEventListener("visibilitychange",s))}return()=>{for(let c of i)c()}}var se="https://api.sentient-ui.com/v1/events",$=new Map,ie=null;function re(){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 N={track:()=>{},goal:()=>{},identify:()=>{},getAssignment:()=>null,assign:()=>Promise.resolve(null),fetchWeights:()=>Promise.resolve([]),getGraph:()=>({pageNodes:[],capturedAt:0}),destroy:()=>{}};function Ue(){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 oe(e){return e.replace(/\/events\/?$/,"")}function Le(e){if(typeof window=="undefined")return;let t=e!=null?e:ie;if(!t){console.warn("[sentient] grantConsent() called before init()");return}let n=$.get(t);if(!n){console.warn("[sentient] grantConsent() called before init()");return}let{config:i,upgrade:o}=n;if(!o)return;let c=ae(Q(R({},i),{consent:!0}));o(c),$.set(t,{config:Q(R({},i),{consent:!0}),upgrade:null})}function Me(e){var a;let t=oe((a=e.ingestUrl)!=null?a:se),n={"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`},i={track:()=>{},goal:()=>{},identify:()=>{},getAssignment:()=>null,fetchWeights:()=>Promise.resolve([]),async assign(s,r,g){try{let f=new URLSearchParams({componentId:s});for(let S of r!=null?r:[])f.append("variantIds[]",S);let m=await fetch(`${t}/winner?${f.toString()}`,{headers:n});return m.ok?{variantId:(await m.json()).variantId,assignmentTtlMs:0}:r!=null&&r[0]?{variantId:r[0],assignmentTtlMs:0}:null}catch(f){return r!=null&&r[0]?{variantId:r[0],assignmentTtlMs:0}:null}},getGraph:()=>({pageNodes:[],capturedAt:0}),destroy:()=>{}},o={track:s=>i.track(s),goal:(s,r,g,f)=>i.goal(s,r,g,f),identify:s=>i.identify(s),getAssignment:(s,r)=>i.getAssignment(s,r),assign:(s,r,g,f)=>i.assign(s,r,g,f),fetchWeights:()=>i.fetchWeights(),getGraph:()=>i.getGraph(),destroy:()=>i.destroy()};function c(s){i=s}return{proxy:o,setInner:c}}function ae(e){var K,D,W,B,_;if(typeof window=="undefined")return N;if(ie=e.apiKey,e.consent===!1){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."),N;let{proxy:u,setInner:d}=Me(e);return $.set(e.apiKey,{config:e,upgrade:d}),u}return $.set(e.apiKey,{config:e,upgrade:null}),N}if(!e.apiKey||!e.apiKey.startsWith("pk_"))return console.warn("[sentient] init() called with an invalid apiKey \u2014 expected a pk_ public key. SDK disabled."),N;if(e.ingestUrl==="")return console.warn("[sentient] init() called with an empty ingestUrl. SDK disabled."),N;let t=(K=e.ingestUrl)!=null?K:se,n=Date.now(),i=X({ssrSessionId:e.ssrSessionId}),o=ee(),c=Z({ingestUrl:t,apiKey:e.apiKey}),a=oe(t),s={"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`},r=U((D=navigator.userAgent)!=null?D:""),g=typeof window!="undefined"?window.location.origin:void 0,f=L((W=document.referrer)!=null?W:"",g),m=(B=e.sessionSegment)!=null?B:`${r}:${f}`,y=new Map;if(e.initialAssignments)for(let[u,d]of Object.entries(e.initialAssignments))o.set(u,m,{variantId:d,assignedAt:Date.now(),segment:m,confidence:1});let S=Promise.resolve(),v=i.getSessionId();if(v){let u=M((_=document.referrer)!=null?_:""),d=R({sessionId:v,deviceClass:r,trafficSource:f,referrerDomain:u,utmParams:Ue(),timeOfDay:P(new Date),dayOfWeek:["sun","mon","tue","wed","thu","fri","sat"][new Date().getDay()],ephemeral:i.isEphemeral()},e.userId?{userId:e.userId}:{});try{S=fetch(`${a}/sessions`,{method:"POST",keepalive:!0,body:JSON.stringify(d),headers:s}).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:c});let E={goal(u,d={},h=1,C=0){let I=i.getSessionId();if(!I)return;let b=re();S.then(()=>{fetch(`${a}/goals`,{method:"POST",keepalive:!0,body:JSON.stringify({sessionId:I,name:u,metadata:d,weight:h,stepIndex:C,goalId:b}),headers:s}).catch(()=>{})})},identify(u){let d=i.getSessionId();d&&S.then(()=>{fetch(`${a}/sessions`,{method:"POST",keepalive:!0,body:JSON.stringify({sessionId:d,userId:u,ephemeral:i.isEphemeral()}),headers:s}).catch(()=>{})})},track(u){let d=i.getSessionId();if(!d)return;let h=Q(R({},u),{id:re(),sessionId:d,timestamp:Date.now(),timeInSession:Date.now()-n});c.push(h),e.debug&&console.log("[sentient] track",h)},getAssignment(u,d){return o.get(u,d)},async assign(u,d,h,C){let I=i.getSessionId();if(!I)return null;let b=o.get(u,m);if(b&&(d!=null&&d.length||b.content!==void 0))return{variantId:b.variantId,assignmentTtlMs:0,content:b.content};let A=y.get(u);if(A)return A;let l=(async()=>{await S;try{let p={sessionId:I,componentId:u,variantIds:d};C!==void 0?p.agentDataByVariant=C:h!==void 0&&(p.agentData=h);let w=await fetch(`${a}/assign`,{method:"POST",body:JSON.stringify(p),headers:s});if(!w.ok)return null;let x=await w.json();return o.set(u,m,{variantId:x.variantId,assignedAt:Date.now(),segment:m,confidence:1,content:x.content}),x}catch(p){return null}finally{y.delete(u)}})();return y.set(u,l),l},async fetchWeights(){var u;try{let d=await fetch(`${a}/weights`,{headers:s});return d.ok?(u=(await d.json()).components)!=null?u:[]:[]}catch(d){return[]}},getGraph(){return{pageNodes:[],capturedAt:0}},destroy(){c.destroy(),i.destroy(),e.debug&&console.log("[sentient] destroyed")}};if($.set(e.apiKey,{config:e,upgrade:null}),e.debug){let u=window;u.__sentient&&(u.__sentient.client=E)}return E}0&&(module.exports={attachMicroSignalDetectors,deriveSessionSegment,detectDeviceClass,detectTimeOfDay,detectTrafficSource,grantConsent,init,referrerDomainFromReferer});
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as f,b as g,c as h}from"./chunk-
|
|
1
|
+
import{a as f,b as g,c as h}from"./chunk-PXHVZ2OY.mjs";import{c as a,d as b,e as c,f as d,g as e}from"./chunk-QCYVBCUV.mjs";export{f as attachMicroSignalDetectors,e as deriveSessionSegment,a as detectDeviceClass,d as detectTimeOfDay,b as detectTrafficSource,g as grantConsent,h as init,c as referrerDomainFromReferer};
|
package/package.json
CHANGED
package/dist/chunk-PXHX4K5R.mjs
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{a as L,b as B,c as G,d as Q,e as F,f as z}from"./chunk-QCYVBCUV.mjs";var ee="_snt_uid";var C="_snt_uid";function te(){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 ie(e,t,a){try{document.cookie=`${e}=${encodeURIComponent(t)}; max-age=${a}; SameSite=strict; path=/`}catch(o){}}function se(e){try{return localStorage.getItem(e)}catch(t){return null}}function re(e,t){try{return localStorage.setItem(e,t),!0}catch(a){return!1}}function oe(e){try{return sessionStorage.getItem(e)}catch(t){return null}}function ae(e,t){try{return sessionStorage.setItem(e,t),!0}catch(a){return!1}}function ce(e){try{sessionStorage.removeItem(e)}catch(t){}}function le(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 de(e){try{localStorage.removeItem(e)}catch(t){}}function ue(e){try{document.cookie=`${e}=; max-age=0; SameSite=strict; path=/`}catch(t){}}var ge={getSessionId:()=>null,isEphemeral:()=>!1,destroy:()=>{}};function Y(e){var f,g,p,v,y;if(typeof window=="undefined")return ge;let t=(f=e==null?void 0:e.cookieName)!=null?f:ee,o=((g=e==null?void 0:e.cookieTTLDays)!=null?g:365)*24*60*60,i=(y=(v=(p=ne(t))!=null?p:se(C))!=null?v:oe(C))!=null?y:te();ie(t,i,o);let s=re(C,i),n=le(t),r=s?!1:ae(C,i),l=!s&&!n&&!r;return{getSessionId:()=>i,isEphemeral:()=>l,destroy:()=>{i=null,ue(t),de(C),ce(C)}}}var K="_snt_retry";var fe={push:()=>{},flush:()=>{},destroy:()=>{}};function me(e){try{let t=localStorage.getItem(K);if(!t)return[];let a=JSON.parse(t);return Array.isArray(a)?(localStorage.removeItem(K),a.slice(-e)):[]}catch(t){return[]}}function J(e,t){try{let o=[...(()=>{try{let i=localStorage.getItem(K);if(!i)return[];let s=JSON.parse(i);return Array.isArray(s)?s:[]}catch(i){return[]}})(),...e].slice(-t);localStorage.setItem(K,JSON.stringify(o))}catch(a){}}function q(e){var k,b,T;if(typeof window=="undefined")return fe;let t=(k=e.flushIntervalMs)!=null?k:5e3,a=(b=e.maxBatchSize)!=null?b:20,o=(T=e.maxRetrySize)!=null?T:100,i=e.ingestUrl,s=e.apiKey,n=[],r=new Set,l=[],f=c=>{for(let u of c)g.delete(u),!r.has(u)&&(r.add(u),l.push(u));for(;l.length>500;){let u=l.shift();u&&r.delete(u)}},g=new Set,p=c=>{r.has(c.id)||g.has(c.id)||(g.add(c.id),n.push(c))},v=me(o);for(let c of v)p(c);let y=0,w=0,R=c=>{if(c.length===0)return;let u=JSON.stringify(c),h=c.map(I=>I.id),E;try{E=fetch(i,{method:"POST",keepalive:!0,body:u,headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`}})}catch(I){J(c,o);for(let P of h)g.delete(P);w++,y=Date.now()+Math.min(6e4,1e3*2**Math.min(w,6));return}let _=I=>{if(I.ok||I.status>=400&&I.status<500&&I.status!==429){f(h),w=0,y=0;return}J(c,o);for(let P of h)g.delete(P);w++,y=Date.now()+Math.min(6e4,1e3*2**Math.min(w,6))};E instanceof Promise?E.then(_).catch(()=>{J(c,o);for(let I of h)g.delete(I);w++,y=Date.now()+Math.min(6e4,1e3*2**Math.min(w,6))}):_(E)},A=typeof TextEncoder!="undefined"?new TextEncoder:null,U=c=>A?A.encode(c).length:c.length,M=c=>{let u=[],h=2;for(let E of c){let _=U(JSON.stringify(E))+1;if(u.length>0&&h+_>57344||u.length>=a)break;u.push(E),h+=_}return u},x=()=>{try{if(Date.now()<y)return;for(;n.length>0;){let c=n.filter(h=>!r.has(h.id));if(n.length=0,c.length===0)break;let u=M(c);if(u.length===0)break;u.length<c.length&&n.push(...c.slice(u.length)),R(u)}}catch(c){}},D=!0,d=null;d=setInterval(()=>{D&&x()},t);let m=()=>{document.visibilityState==="hidden"&&x()},S=()=>{x()};return document.addEventListener("visibilitychange",m),window.addEventListener("beforeunload",S),{push(c){p(c),n.length>=a&&x()},flush:x,destroy(){D=!1,d!==null&&(clearInterval(d),d=null),document.removeEventListener("visibilitychange",m),window.removeEventListener("beforeunload",S),x()}}}var $="_snt_asgn_";function N(e,t){return`${e}:${t}`}function pe(e,t){return`${$}${e}_${t}`}function W(){try{let e=[];for(let t=0;t<localStorage.length;t++){let a=localStorage.key(t);a!=null&&a.startsWith($)&&e.push(a)}return e}catch(e){return[]}}function V(e=18e5){let t=new Map,a=i=>i.assignedAt+e<Date.now();return typeof window!="undefined"&&(()=>{for(let i of W())try{let s=localStorage.getItem(i);if(!s)continue;let n=JSON.parse(s);if(a(n)){localStorage.removeItem(i);continue}let r=i.slice($.length),l=r.lastIndexOf("_");if(l<0)continue;let f=r.slice(0,l),g=r.slice(l+1);t.set(N(f,g),n)}catch(s){}})(),{get(i,s){let n=t.get(N(i,s));return n?a(n)?(t.delete(N(i,s)),null):n:null},set(i,s,n){let r=N(i,s);t.set(r,n);try{localStorage.setItem(pe(i,s),JSON.stringify(n))}catch(l){}},invalidate(i){let s=`${i}:`;for(let n of[...t.keys()])n.startsWith(s)&&t.delete(n);for(let n of W()){let r=n.slice($.length),l=r.lastIndexOf("_");if(l<0)continue;if(r.slice(0,l)===i)try{localStorage.removeItem(n)}catch(g){}}},clear(){t.clear();for(let i of W())try{localStorage.removeItem(i)}catch(s){}}}}function ye(e,t,a){let o=[];{let n=!1,r=[],l=()=>{if(n)return;let f=Date.now();for(r.push(f);r.length>0&&f-r[0]>500;)r.shift();r.length>=3&&(n=!0,e("rage_click"))};t.addEventListener("click",l),o.push(()=>t.removeEventListener("click",l))}{let i=!1,s=n=>{if(i||!(n.target instanceof Node)||!t.contains(n.target)&&t!==n.target)return;i=!0;let r=typeof window!="undefined"?window.getSelection():null,l=r?r.toString().length:0;e("text_copy",{selectionLength:l})};document.addEventListener("copy",s),o.push(()=>document.removeEventListener("copy",s))}{let i=!1,s=!1,n=null,r=()=>{n!==null&&(clearTimeout(n),n=null)},l=()=>{i||!s||(r(),n=setTimeout(()=>{!i&&s&&(i=!0,e("scroll_hesitation"))},3e3))},f=()=>{r(),l()},g=v=>{for(let y of v)s=y.intersectionRatio>.3,s?l():r()};window.__lastIOCallback=g;let p=new IntersectionObserver(g,{threshold:[.3]});p.observe(t),window.addEventListener("scroll",f,{passive:!0}),o.push(()=>{p.disconnect(),window.removeEventListener("scroll",f),r()})}{let i=!1,s=a!=null?a:Date.now(),n=()=>{if(i||document.visibilityState!=="hidden")return;let r=Date.now()-s;r<15e3&&(i=!0,e("tab_loss",{timeOnPage:r}))};document.addEventListener("visibilitychange",n),o.push(()=>document.removeEventListener("visibilitychange",n))}return()=>{for(let i of o)i()}}var X="https://api.sentient-ui.com/v1/events",j=null,H=null;function he(){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 O={track:()=>{},goal:()=>{},identify:()=>{},getAssignment:()=>null,assign:()=>Promise.resolve(null),getGraph:()=>({pageNodes:[],capturedAt:0}),destroy:()=>{}};function Se(){try{let e={},t=new URLSearchParams(window.location.search);for(let[a,o]of t)a.startsWith("utm_")&&(e[a]=o);return e}catch(e){return{}}}function Z(e){return e.replace(/\/events\/?$/,"")}function De(){if(typeof window=="undefined")return;if(!j){console.warn("[sentient] grantConsent() called before init()");return}let e=H;H=null;let t=we(B(L({},j),{consent:!0}));e==null||e(t)}function ve(e){var i;let t=Z((i=e.ingestUrl)!=null?i:X),a={"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`},o={track:()=>{},goal:()=>{},identify:()=>{},getAssignment:()=>null,async assign(s,n,r){try{let l=new URLSearchParams({componentId:s});for(let p of n!=null?n:[])l.append("variantIds[]",p);let f=await fetch(`${t}/winner?${l.toString()}`,{headers:a});return f.ok?{variantId:(await f.json()).variantId,assignmentTtlMs:0}:n!=null&&n[0]?{variantId:n[0],assignmentTtlMs:0}:null}catch(l){return n!=null&&n[0]?{variantId:n[0],assignmentTtlMs:0}:null}},getGraph:()=>({pageNodes:[],capturedAt:0}),destroy:()=>{}};return H=s=>{o=s},{track:s=>o.track(s),goal:(s,n)=>o.goal(s,n),identify:s=>o.identify(s),getAssignment:(s,n)=>o.getAssignment(s,n),assign:(s,n,r,l)=>o.assign(s,n,r,l),getGraph:()=>o.getGraph(),destroy:()=>o.destroy()}}function we(e){var A,U,M,x,D;if(typeof window=="undefined")return O;if(j=e,e.consent===!1)return e.preConsentBehavior==="statistical_winner"?!e.apiKey||!e.apiKey.startsWith("pk_")?(console.warn("[sentient] init() called with an invalid apiKey \u2014 expected a pk_ public key. SDK disabled."),O):ve(e):O;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."),O;if(e.ingestUrl==="")return console.warn("[sentient] init() called with an empty ingestUrl. SDK disabled."),O;let t=(A=e.ingestUrl)!=null?A:X,a=Date.now(),o=Y(),i=V(),s=q({ingestUrl:t,apiKey:e.apiKey}),n=Z(t),r={"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`},l=G((U=navigator.userAgent)!=null?U:""),f=typeof window!="undefined"?window.location.origin:void 0,g=Q((M=document.referrer)!=null?M:"",f),p=(x=e.sessionSegment)!=null?x:`${l}:${g}`,v=new Map;if(e.initialAssignments)for(let[d,m]of Object.entries(e.initialAssignments))i.set(d,p,{variantId:m,assignedAt:Date.now(),segment:p,confidence:1});let y=Promise.resolve(),w=o.getSessionId();if(w){let d=F((D=document.referrer)!=null?D:""),m=L({sessionId:w,deviceClass:l,trafficSource:g,referrerDomain:d,utmParams:Se(),timeOfDay:z(new Date),dayOfWeek:["sun","mon","tue","wed","thu","fri","sat"][new Date().getDay()],ephemeral:o.isEphemeral()},e.userId?{userId:e.userId}:{});try{y=fetch(`${n}/sessions`,{method:"POST",keepalive:!0,body:JSON.stringify(m),headers:r}).then(S=>{S.status===402&&console.warn("[SentientUI] Session limit exceeded for this project. The bandit will stop learning until the limit resets. Upgrade at sentient-ui.com/pricing")}).catch(()=>{})}catch(S){}}e.debug&&(console.log("[sentient] initialized",{context:e.context}),window.__sentient={client:null,queue:s});let R={goal(d,m={},S=1,k=0){let b=o.getSessionId();b&&y.then(()=>{fetch(`${n}/goals`,{method:"POST",keepalive:!0,body:JSON.stringify({sessionId:b,name:d,metadata:m,weight:S,stepIndex:k}),headers:r}).catch(()=>{})})},identify(d){let m=o.getSessionId();m&&y.then(()=>{fetch(`${n}/sessions`,{method:"POST",keepalive:!0,body:JSON.stringify({sessionId:m,userId:d,ephemeral:o.isEphemeral()}),headers:r}).catch(()=>{})})},track(d){let m=o.getSessionId();if(!m)return;let S=B(L({},d),{id:he(),sessionId:m,timestamp:Date.now(),timeInSession:Date.now()-a});s.push(S),e.debug&&console.log("[sentient] track",S)},getAssignment(d,m){return i.get(d,m)},async assign(d,m,S,k){let b=o.getSessionId();if(!b)return null;let T=i.get(d,p);if(T)return{variantId:T.variantId,assignmentTtlMs:0,content:T.content};let c=v.get(d);if(c)return c;let u=(async()=>{await y;try{let h={sessionId:b,componentId:d,variantIds:m};k!==void 0?h.agentDataByVariant=k:S!==void 0&&(h.agentData=S);let E=await fetch(`${n}/assign`,{method:"POST",body:JSON.stringify(h),headers:r});if(!E.ok)return null;let _=await E.json();return i.set(d,p,{variantId:_.variantId,assignedAt:Date.now(),segment:p,confidence:1,content:_.content}),_}catch(h){return null}finally{v.delete(d)}})();return v.set(d,u),u},getGraph(){return{pageNodes:[],capturedAt:0}},destroy(){s.destroy(),o.destroy(),e.debug&&console.log("[sentient] destroyed")}};if(e.debug){let d=window;d.__sentient&&(d.__sentient.client=R)}return R}export{ye as a,De as b,we as c};
|