@sentientui/core 0.2.0 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +83 -0
- package/dist/chunk-HWKW5O3R.mjs +1 -0
- package/dist/index-graph.d.cts +1 -1
- package/dist/index-graph.d.ts +1 -1
- package/dist/index-graph.js +1 -1
- package/dist/index-graph.mjs +1 -1
- package/dist/index.d.cts +40 -12
- package/dist/index.d.ts +40 -12
- package/dist/index.js +1 -1
- package/dist/index.mjs +1 -1
- package/package.json +39 -37
- package/dist/chunk-2K7NAMTI.mjs +0 -1
package/README.md
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
# @sentientui/core
|
|
2
|
+
|
|
3
|
+
Framework-agnostic JavaScript SDK for [SentientUI](https://sentientui.dev) — an adaptive UI platform that uses a contextual bandit to automatically surface the best-performing variant for each visitor.
|
|
4
|
+
|
|
5
|
+
## Installation
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
npm install @sentientui/core
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
## Quick start
|
|
12
|
+
|
|
13
|
+
```ts
|
|
14
|
+
import { init } from '@sentientui/core';
|
|
15
|
+
|
|
16
|
+
const client = init({
|
|
17
|
+
apiKey: 'pk_your_key',
|
|
18
|
+
context: 'saas', // 'landing' | 'ecommerce' | 'saas' | 'marketplace'
|
|
19
|
+
});
|
|
20
|
+
|
|
21
|
+
// Get a variant assignment for a component
|
|
22
|
+
const result = await client.assign('hero-headline');
|
|
23
|
+
console.log(result?.variantId); // e.g. 'variant-b'
|
|
24
|
+
|
|
25
|
+
// Track a conversion event
|
|
26
|
+
client.track({
|
|
27
|
+
projectId: 'your-project-id',
|
|
28
|
+
componentId: 'hero-headline',
|
|
29
|
+
variantId: result?.variantId ?? 'control',
|
|
30
|
+
eventType: 'click',
|
|
31
|
+
});
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
## API
|
|
35
|
+
|
|
36
|
+
### `init(config)`
|
|
37
|
+
|
|
38
|
+
Initializes the client. Returns a no-op client during SSR and when `consent` is `false`.
|
|
39
|
+
|
|
40
|
+
| Option | Type | Description |
|
|
41
|
+
|--------|------|-------------|
|
|
42
|
+
| `apiKey` | `string` | Your public API key (`pk_…`) |
|
|
43
|
+
| `context` | `string` | Site context — `'landing'`, `'ecommerce'`, `'saas'`, or `'marketplace'` |
|
|
44
|
+
| `initialAssignments` | `Record<string, string>` | SSR-preloaded assignments to seed the cache (prevents variant flash on hydration) |
|
|
45
|
+
| `sessionSegment` | `string` | Segment from SSR (`device:source`) — must match the value used in `preloadAssignments` |
|
|
46
|
+
| `consent` | `boolean` | Set to `false` to disable tracking (e.g. before cookie consent). Defaults to `true` |
|
|
47
|
+
| `debug` | `boolean` | Logs events to the console and exposes `window.__sentient` |
|
|
48
|
+
|
|
49
|
+
### `client.assign(componentId, variantIds?)`
|
|
50
|
+
|
|
51
|
+
Fetches a variant assignment from the bandit. Returns a cached result immediately if one exists. Returns `null` during SSR.
|
|
52
|
+
|
|
53
|
+
### `client.track(event)`
|
|
54
|
+
|
|
55
|
+
Queues an event for ingest. Batched and sent automatically.
|
|
56
|
+
|
|
57
|
+
### `client.getAssignment(componentId, segment)`
|
|
58
|
+
|
|
59
|
+
Synchronously returns the cached assignment for a component/segment pair, or `null` if not yet assigned.
|
|
60
|
+
|
|
61
|
+
### `client.destroy()`
|
|
62
|
+
|
|
63
|
+
Flushes the event queue and clears the session. Call on page unload if needed.
|
|
64
|
+
|
|
65
|
+
## SSR helpers
|
|
66
|
+
|
|
67
|
+
```ts
|
|
68
|
+
import { preloadAssignments, readSessionCookie } from '@sentientui/core';
|
|
69
|
+
|
|
70
|
+
// In your server loader / getServerSideProps / Server Component:
|
|
71
|
+
const sessionSegment = readSessionCookie(request.headers.get('cookie'));
|
|
72
|
+
const initialAssignments = await preloadAssignments({
|
|
73
|
+
apiKey: 'pk_your_key',
|
|
74
|
+
componentIds: ['hero-headline', 'pricing-cta'],
|
|
75
|
+
sessionSegment,
|
|
76
|
+
});
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
Pass `initialAssignments` and `sessionSegment` to `init()` on the client to prevent hydration mismatches.
|
|
80
|
+
|
|
81
|
+
## License
|
|
82
|
+
|
|
83
|
+
MIT
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var V=Object.defineProperty,X=Object.defineProperties;var H=Object.getOwnPropertyDescriptors;var F=Object.getOwnPropertySymbols;var Z=Object.prototype.hasOwnProperty,ee=Object.prototype.propertyIsEnumerable;var j=(e,t,n)=>t in e?V(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Q=(e,t)=>{for(var n in t||(t={}))Z.call(t,n)&&j(e,n,t[n]);if(F)for(var n of F(t))ee.call(t,n)&&j(e,n,t[n]);return e},z=(e,t)=>X(e,H(t));var te="_snt_uid";var k="_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 re(e){try{let t=document.cookie.match(new RegExp(`(?:^|; )${e}=([^;]*)`));return t?decodeURIComponent(t[1]):null}catch(t){return null}}function se(e,t,n){try{document.cookie=`${e}=${encodeURIComponent(t)}; max-age=${n}; SameSite=strict; path=/`}catch(o){}}function ie(e){try{return localStorage.getItem(e)}catch(t){return null}}function oe(e,t){try{return localStorage.setItem(e,t),!0}catch(n){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(n){return!1}}function de(e){try{sessionStorage.removeItem(e)}catch(t){}}function ue(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 le(e){try{localStorage.removeItem(e)}catch(t){}}function ge(e){try{document.cookie=`${e}=; max-age=0; SameSite=strict; path=/`}catch(t){}}var me={getSessionId:()=>null,isEphemeral:()=>!1,destroy:()=>{}};function W(e){var f,m,p,v,h;if(typeof window=="undefined")return me;let t=(f=e==null?void 0:e.cookieName)!=null?f:te,o=((m=e==null?void 0:e.cookieTTLDays)!=null?m:365)*24*60*60,r=(h=(v=(p=re(t))!=null?p:ie(k))!=null?v:ae(k))!=null?h:ne();se(t,r,o);let a=oe(k,r),s=ue(t),i=a?!1:ce(k,r),d=!a&&!s&&!i;return{getSessionId:()=>r,isEphemeral:()=>d,destroy:()=>{r=null,ge(t),le(k),de(k)}}}var U="_snt_retry";var fe={push:()=>{},flush:()=>{},destroy:()=>{}};function pe(e){try{let t=localStorage.getItem(U);if(!t)return[];let n=JSON.parse(t);return Array.isArray(n)?(localStorage.removeItem(U),n.slice(-e)):[]}catch(t){return[]}}function G(e,t){try{let o=[...(()=>{try{let r=localStorage.getItem(U);if(!r)return[];let a=JSON.parse(r);return Array.isArray(a)?a:[]}catch(r){return[]}})(),...e].slice(-t);localStorage.setItem(U,JSON.stringify(o))}catch(n){}}function Y(e){var y,T,b;if(typeof window=="undefined")return fe;let t=(y=e.flushIntervalMs)!=null?y:5e3,n=(T=e.maxBatchSize)!=null?T:20,o=(b=e.maxRetrySize)!=null?b:100,r=e.ingestUrl,a=e.apiKey,s=[],i=new Set,d=[],f=c=>{for(let g of c)i.has(g)||(i.add(g),d.push(g));for(;d.length>500;){let g=d.shift();g&&i.delete(g)}},m=new Set,p=c=>{i.has(c.id)||m.has(c.id)||(m.add(c.id),s.push(c))},v=pe(o);for(let c of v)p(c);let h=0,S=0,C=c=>{if(c.length===0)return;let g=JSON.stringify(c),_=c.map(E=>E.id),A;try{A=fetch(r,{method:"POST",keepalive:!0,body:g,headers:{"Content-Type":"application/json",Authorization:`Bearer ${a}`}})}catch(E){G(c,o),S++,h=Date.now()+Math.min(6e4,1e3*2**Math.min(S,6));return}let x=E=>{if(E.ok||E.status>=400&&E.status<500&&E.status!==429){f(_),S=0,h=0;return}G(c,o),S++,h=Date.now()+Math.min(6e4,1e3*2**Math.min(S,6))};A instanceof Promise?A.then(x).catch(()=>{G(c,o),S++,h=Date.now()+Math.min(6e4,1e3*2**Math.min(S,6))}):x(A)},O=c=>{let g=[],_=2;for(let A of c){let x=JSON.stringify(A).length+1;if(g.length>0&&_+x>57344||g.length>=n)break;g.push(A),_+=x}return g},I=()=>{try{if(Date.now()<h)return;for(;s.length>0;){let c=s.filter(_=>!i.has(_.id));if(s.length=0,c.length===0)break;let g=O(c);if(g.length===0)break;g.length<c.length&&s.push(...c.slice(g.length)),C(g)}}catch(c){}},D=!0,w=null;w=setInterval(()=>{D&&I()},t);let u=()=>{document.visibilityState==="hidden"&&I()},l=()=>{I()};return document.addEventListener("visibilitychange",u),window.addEventListener("beforeunload",l),{push(c){p(c),s.length>=n&&I()},flush:I,destroy(){D=!1,w!==null&&(clearInterval(w),w=null),document.removeEventListener("visibilitychange",u),window.removeEventListener("beforeunload",l),I()}}}var P="_snt_asgn_";function R(e,t){return`${e}:${t}`}function ye(e,t){return`${P}${e}_${t}`}function J(){try{let e=[];for(let t=0;t<localStorage.length;t++){let n=localStorage.key(t);n!=null&&n.startsWith(P)&&e.push(n)}return e}catch(e){return[]}}function q(e=18e5){let t=new Map,n=r=>r.assignedAt+e<Date.now();return typeof window!="undefined"&&(()=>{for(let r of J())try{let a=localStorage.getItem(r);if(!a)continue;let s=JSON.parse(a);if(n(s)){localStorage.removeItem(r);continue}let i=r.slice(P.length),d=i.lastIndexOf("_");if(d<0)continue;let f=i.slice(0,d),m=i.slice(d+1);t.set(R(f,m),s)}catch(a){}})(),{get(r,a){let s=t.get(R(r,a));return s?n(s)?(t.delete(R(r,a)),null):s:null},set(r,a,s){let i=R(r,a);t.set(i,s);try{localStorage.setItem(ye(r,a),JSON.stringify(s))}catch(d){}},invalidate(r){let a=`${r}:`;for(let s of[...t.keys()])s.startsWith(a)&&t.delete(s);for(let s of J()){let i=s.slice(P.length),d=i.lastIndexOf("_");if(d<0)continue;if(i.slice(0,d)===r)try{localStorage.removeItem(s)}catch(m){}}},clear(){t.clear();for(let r of J())try{localStorage.removeItem(r)}catch(a){}}}}function $(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(r){}let o=n.hostname.toLowerCase();return/(^|\.)(google|bing|duckduckgo|yahoo)\./.test(o)?"search":/(^|\.)(twitter|x\.com|facebook|linkedin|reddit|t\.co)/.test(o)?"social":"referral"}catch(n){return"direct"}}function N(e){if(!e)return null;try{return new URL(e).hostname}catch(t){return null}}function M(e){let t=e.getHours();return t<6?"night":t<12?"morning":t<18?"afternoon":"evening"}function he(e){let t=K("__segment__",e);return`${t.deviceClass}:${t.trafficSource}`}function K(e,t){var a,s,i,d,f,m,p;let n=(s=(a=t==null?void 0:t.userAgent)==null?void 0:a.trim())!=null?s:"",o=(d=(i=t==null?void 0:t.referer)==null?void 0:i.trim())!=null?d:"",r=(f=t==null?void 0:t.now)!=null?f:new Date;return{sessionId:e,ephemeral:!1,utmParams:(m=t==null?void 0:t.utmParams)!=null?m:{},deviceClass:n?$(n):"desktop",trafficSource:o?L(o,t==null?void 0:t.appOrigin):"direct",referrerDomain:N(o),timeOfDay:M(r),dayOfWeek:(p=["sun","mon","tue","wed","thu","fri","sat"][r.getDay()])!=null?p:"sun"}}async function Se(e,t,n){let o={"Content-Type":"application/json",Authorization:`Bearer ${n.apiKey}`};n.origin&&(o.Origin=n.origin);let r=K(t,{userAgent:n.userAgent,referer:n.referer,utmParams:n.utmParams,appOrigin:n.origin});try{(await fetch(`${n.baseUrl}/sessions`,{method:"POST",headers:o,body:JSON.stringify(r)})).status===402&&console.warn("[SentientUI] Session limit exceeded for this project. The bandit will stop learning until the limit resets. Upgrade at sentientui.dev/pricing")}catch(i){}let a=await Promise.allSettled(e.map(async({id:i,variantIds:d})=>{let f=await fetch(`${n.baseUrl}/assign`,{method:"POST",headers:o,body:JSON.stringify({sessionId:t,componentId:i,variantIds:d})});if(!f.ok)return null;let m=await f.json();return{id:i,variantId:m.variantId}})),s={};for(let i of a)i.status==="fulfilled"&&i.value&&(s[i.value.id]=i.value.variantId);return s}function ve(e){var t,n;return(n=(t=e.get("_snt_uid"))==null?void 0:t.value)!=null?n:null}async function Ie(e,t,n){let o={layoutOrder:e.sections,assignments:{},persona:"unknown",confidence:0},r={"Content-Type":"application/json",Authorization:`Bearer ${n.apiKey}`};n.origin&&(r.Origin=n.origin);let a=K(t,{userAgent:n.userAgent,referer:n.referer,utmParams:n.utmParams,appOrigin:n.origin});try{await fetch(`${n.baseUrl}/sessions`,{method:"POST",headers:r,body:JSON.stringify(a)})}catch(s){}try{let s=await fetch(`${n.baseUrl}/decide`,{method:"POST",headers:r,body:JSON.stringify({sessionId:t,sections:e.sections.map(i=>({id:i})),components:e.components})});return s.ok?await s.json():o}catch(s){return o}}var we="https://sentient-api.fly.dev/v1/events";function Ae(){try{if(typeof crypto!="undefined"&&typeof crypto.randomUUID=="function")return crypto.randomUUID()}catch(e){}return`evt-${Date.now()}-${Math.random().toString(16).slice(2)}`}var B={track:()=>{},goal:()=>{},identify:()=>{},getAssignment:()=>null,assign:()=>Promise.resolve(null),getGraph:()=>({pageNodes:[],capturedAt:0}),destroy:()=>{}};function Ee(){try{let e={},t=new URLSearchParams(window.location.search);for(let[n,o]of t)n.startsWith("utm_")&&(e[n]=o);return e}catch(e){return{}}}function be(e){return e.replace(/\/events\/?$/,"")}function Le(e){var C,O,I,D,w;if(typeof window=="undefined"||e.consent===!1)return B;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."),B;if(e.ingestUrl==="")return console.warn("[sentient] init() called with an empty ingestUrl. SDK disabled."),B;let t=(C=e.ingestUrl)!=null?C:we,n=Date.now(),o=W(),r=q(),a=Y({ingestUrl:t,apiKey:e.apiKey}),s=be(t),i={"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`},d=$((O=navigator.userAgent)!=null?O:""),f=typeof window!="undefined"?window.location.origin:void 0,m=L((I=document.referrer)!=null?I:"",f),p=(D=e.sessionSegment)!=null?D:`${d}:${m}`;if(e.initialAssignments)for(let[u,l]of Object.entries(e.initialAssignments))r.set(u,p,{variantId:l,assignedAt:Date.now(),segment:p,confidence:1});let v=Promise.resolve(),h=o.getSessionId();if(h){let u=N((w=document.referrer)!=null?w:""),l=Q({sessionId:h,deviceClass:d,trafficSource:m,referrerDomain:u,utmParams:Ee(),timeOfDay:M(new Date),dayOfWeek:["sun","mon","tue","wed","thu","fri","sat"][new Date().getDay()],ephemeral:o.isEphemeral()},e.userId?{userId:e.userId}:{});try{v=fetch(`${s}/sessions`,{method:"POST",keepalive:!0,body:JSON.stringify(l),headers:i}).then(y=>{y.status===402&&console.warn("[SentientUI] Session limit exceeded for this project. The bandit will stop learning until the limit resets. Upgrade at sentientui.dev/pricing")}).catch(()=>{})}catch(y){}}e.debug&&(console.log("[sentient] initialized",{context:e.context}),window.__sentient={client:null,queue:a});let S={goal(u,l={}){let y=o.getSessionId();y&&v.then(()=>{fetch(`${s}/goals`,{method:"POST",keepalive:!0,body:JSON.stringify({sessionId:y,name:u,metadata:l}),headers:i}).catch(()=>{})})},identify(u){let l=o.getSessionId();l&&v.then(()=>{fetch(`${s}/sessions`,{method:"POST",keepalive:!0,body:JSON.stringify({sessionId:l,userId:u,ephemeral:o.isEphemeral()}),headers:i}).catch(()=>{})})},track(u){let l=o.getSessionId();if(!l)return;let y=z(Q({},u),{id:Ae(),sessionId:l,timestamp:Date.now(),timeInSession:Date.now()-n});a.push(y),e.debug&&console.log("[sentient] track",y)},getAssignment(u,l){return r.get(u,l)},async assign(u,l){let y=o.getSessionId();if(!y)return null;let T=r.get(u,p);if(T)return{variantId:T.variantId,assignmentTtlMs:0};await v;try{let b=await fetch(`${s}/assign`,{method:"POST",body:JSON.stringify({sessionId:y,componentId:u,variantIds:l}),headers:i});if(!b.ok)return null;let c=await b.json();return r.set(u,p,{variantId:c.variantId,assignedAt:Date.now(),segment:p,confidence:1}),c}catch(b){return null}},getGraph(){return{pageNodes:[],capturedAt:0}},destroy(){a.destroy(),o.destroy(),e.debug&&console.log("[sentient] destroyed")}};if(e.debug){let u=window;u.__sentient&&(u.__sentient.client=S)}return S}export{Q as a,z as b,$ as c,L as d,N as e,M as f,he as g,Se as h,ve as i,Ie as j,Le as k};
|
package/dist/index-graph.d.cts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { SentientConfig, SentientClient } from './index.cjs';
|
|
2
|
-
export { AssignResult, Assignment, AssignmentCache, ContentAddedEvent, DOMScanner, EventQueue, EventType, GraphClient, GraphConfig, GraphSnapshot, PageNode, QueueConfig, ScanResult, ScannedNode, SentientEvent, ServerAssignConfig, ServerAssignments, SessionConfig, SessionManager,
|
|
2
|
+
export { AssignResult, Assignment, AssignmentCache, ContentAddedEvent, DOMScanner, EventQueue, EventType, GraphClient, GraphConfig, GraphSnapshot, PageNode, QueueConfig, ScanResult, ScannedNode, SentientEvent, ServerAssignConfig, ServerAssignments, SessionConfig, SessionManager, deriveSessionSegment, detectDeviceClass, detectTimeOfDay, detectTrafficSource, preloadAssignments, readSessionCookie, referrerDomainFromReferer } from './index.cjs';
|
|
3
3
|
|
|
4
4
|
/**
|
|
5
5
|
* Graph-capable entry point for @sentientui/core.
|
package/dist/index-graph.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { SentientConfig, SentientClient } from './index.js';
|
|
2
|
-
export { AssignResult, Assignment, AssignmentCache, ContentAddedEvent, DOMScanner, EventQueue, EventType, GraphClient, GraphConfig, GraphSnapshot, PageNode, QueueConfig, ScanResult, ScannedNode, SentientEvent, ServerAssignConfig, ServerAssignments, SessionConfig, SessionManager,
|
|
2
|
+
export { AssignResult, Assignment, AssignmentCache, ContentAddedEvent, DOMScanner, EventQueue, EventType, GraphClient, GraphConfig, GraphSnapshot, PageNode, QueueConfig, ScanResult, ScannedNode, SentientEvent, ServerAssignConfig, ServerAssignments, SessionConfig, SessionManager, deriveSessionSegment, detectDeviceClass, detectTimeOfDay, detectTrafficSource, preloadAssignments, readSessionCookie, referrerDomainFromReferer } from './index.js';
|
|
3
3
|
|
|
4
4
|
/**
|
|
5
5
|
* Graph-capable entry point for @sentientui/core.
|
package/dist/index-graph.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var M=Object.defineProperty,ge=Object.defineProperties,le=Object.getOwnPropertyDescriptor,pe=Object.getOwnPropertyDescriptors,me=Object.getOwnPropertyNames,ee=Object.getOwnPropertySymbols;var ne=Object.prototype.hasOwnProperty,fe=Object.prototype.propertyIsEnumerable;var te=(e,t,n)=>t in e?M(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,_=(e,t)=>{for(var n in t||(t={}))ne.call(t,n)&&te(e,n,t[n]);if(ee)for(var n of ee(t))fe.call(t,n)&&te(e,n,t[n]);return e},L=(e,t)=>ge(e,pe(t));var he=(e,t)=>{for(var n in t)M(e,n,{get:t[n],enumerable:!0})},ye=(e,t,n,c)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of me(t))!ne.call(e,s)&&s!==n&&M(e,s,{get:()=>t[s],enumerable:!(c=le(t,s))||c.enumerable});return e};var Se=e=>ye(M({},"__esModule",{value:!0}),e);var et={};he(et,{deriveSessionSegment:()=>J,detectDeviceClass:()=>T,detectTimeOfDay:()=>k,detectTrafficSource:()=>N,init:()=>Ze,preloadAssignments:()=>Q,readSessionCookie:()=>W,referrerDomainFromReferer:()=>D});module.exports=Se(et);var ve="_snt_uid";var x="_snt_uid";function Ee(){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 we(e,t,n){try{document.cookie=`${e}=${encodeURIComponent(t)}; max-age=${n}; SameSite=strict; path=/`}catch(c){}}function Ie(e){try{return localStorage.getItem(e)}catch(t){return null}}function Ae(e,t){try{return localStorage.setItem(e,t),!0}catch(n){return!1}}function Ce(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 xe(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 Ne(e){try{localStorage.removeItem(e)}catch(t){}}function De(e){try{document.cookie=`${e}=; max-age=0; SameSite=strict; path=/`}catch(t){}}var ke={getSessionId:()=>null,isEphemeral:()=>!1,destroy:()=>{}};function re(e){var d,u,l,S,f;if(typeof window=="undefined")return ke;let t=(d=e==null?void 0:e.cookieName)!=null?d:ve,c=((u=e==null?void 0:e.cookieTTLDays)!=null?u:365)*24*60*60,s=(f=(S=(l=be(t))!=null?l:Ie(x))!=null?S:Ce(x))!=null?f:Ee();we(t,s,c);let r=Ae(x,s),o=Te(t),i=r?!1:_e(x,s),a=!r&&!o&&!i;return{getSessionId:()=>s,isEphemeral:()=>a,destroy:()=>{s=null,De(t),Ne(x),xe(x)}}}var $="_snt_retry";var Oe={push:()=>{},flush:()=>{},destroy:()=>{}};function Ue(e){try{let t=localStorage.getItem($);if(!t)return[];let n=JSON.parse(t);return Array.isArray(n)?(localStorage.removeItem($),n.slice(-e)):[]}catch(t){return[]}}function F(e,t){try{let c=[...(()=>{try{let s=localStorage.getItem($);if(!s)return[];let r=JSON.parse(s);return Array.isArray(r)?r:[]}catch(s){return[]}})(),...e].slice(-t);localStorage.setItem($,JSON.stringify(c))}catch(n){}}function se(e){var A,U,Z;if(typeof window=="undefined")return Oe;let t=(A=e.flushIntervalMs)!=null?A:5e3,n=(U=e.maxBatchSize)!=null?U:20,c=(Z=e.maxRetrySize)!=null?Z:100,s=e.ingestUrl,r=e.apiKey,o=[],i=new Set,a=[],d=g=>{for(let p of g)i.has(p)||(i.add(p),a.push(p));for(;a.length>500;){let p=a.shift();p&&i.delete(p)}},u=new Set,l=g=>{i.has(g.id)||u.has(g.id)||(u.add(g.id),o.push(g))},S=Ue(c);for(let g of S)l(g);let f=0,y=0,I=g=>{if(g.length===0)return;let p=JSON.stringify(g),C=g.map(w=>w.id),b;try{b=fetch(s,{method:"POST",keepalive:!0,body:p,headers:{"Content-Type":"application/json",Authorization:`Bearer ${r}`}})}catch(w){F(g,c),y++,f=Date.now()+Math.min(6e4,1e3*2**Math.min(y,6));return}let R=w=>{if(w.ok||w.status>=400&&w.status<500&&w.status!==429){d(C),y=0,f=0;return}F(g,c),y++,f=Date.now()+Math.min(6e4,1e3*2**Math.min(y,6))};b instanceof Promise?b.then(R).catch(()=>{F(g,c),y++,f=Date.now()+Math.min(6e4,1e3*2**Math.min(y,6))}):R(b)},P=g=>{let p=[],C=2;for(let b of g){let R=JSON.stringify(b).length+1;if(p.length>0&&C+R>57344||p.length>=n)break;p.push(b),C+=R}return p},v=()=>{try{if(Date.now()<f)return;for(;o.length>0;){let g=o.filter(C=>!i.has(C.id));if(o.length=0,g.length===0)break;let p=P(g);if(p.length===0)break;p.length<g.length&&o.push(...g.slice(p.length)),I(p)}}catch(g){}},m=!0,h=null;h=setInterval(()=>{m&&v()},t);let E=()=>{document.visibilityState==="hidden"&&v()},O=()=>{v()};return document.addEventListener("visibilitychange",E),window.addEventListener("beforeunload",O),{push(g){l(g),o.length>=n&&v()},flush:v,destroy(){m=!1,h!==null&&(clearInterval(h),h=null),document.removeEventListener("visibilitychange",E),window.removeEventListener("beforeunload",O),v()}}}var G="_snt_asgn_";function K(e,t){return`${e}:${t}`}function Re(e,t){return`${G}${e}_${t}`}function z(){try{let e=[];for(let t=0;t<localStorage.length;t++){let n=localStorage.key(t);n!=null&&n.startsWith(G)&&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 z())try{let r=localStorage.getItem(s);if(!r)continue;let o=JSON.parse(r);if(n(o)){localStorage.removeItem(s);continue}let i=s.slice(G.length),a=i.lastIndexOf("_");if(a<0)continue;let d=i.slice(0,a),u=i.slice(a+1);t.set(K(d,u),o)}catch(r){}})(),{get(s,r){let o=t.get(K(s,r));return o?n(o)?(t.delete(K(s,r)),null):o:null},set(s,r,o){let i=K(s,r);t.set(i,o);try{localStorage.setItem(Re(s,r),JSON.stringify(o))}catch(a){}},invalidate(s){let r=`${s}:`;for(let o of[...t.keys()])o.startsWith(r)&&t.delete(o);for(let o of z()){let i=o.slice(G.length),a=i.lastIndexOf("_");if(a<0)continue;if(i.slice(0,a)===s)try{localStorage.removeItem(o)}catch(u){}}},clear(){t.clear();for(let s of z())try{localStorage.removeItem(s)}catch(r){}}}}function T(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 N(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 c=n.hostname.toLowerCase();return/(^|\.)(google|bing|duckduckgo|yahoo)\./.test(c)?"search":/(^|\.)(twitter|x\.com|facebook|linkedin|reddit|t\.co)/.test(c)?"social":"referral"}catch(n){return"direct"}}function D(e){if(!e)return null;try{return new URL(e).hostname}catch(t){return null}}function k(e){let t=e.getHours();return t<6?"night":t<12?"morning":t<18?"afternoon":"evening"}function J(e){let t=j("__segment__",e);return`${t.deviceClass}:${t.trafficSource}`}function j(e,t){var r,o,i,a,d,u,l;let n=(o=(r=t==null?void 0:t.userAgent)==null?void 0:r.trim())!=null?o:"",c=(a=(i=t==null?void 0:t.referer)==null?void 0:i.trim())!=null?a:"",s=(d=t==null?void 0:t.now)!=null?d:new Date;return{sessionId:e,ephemeral:!1,utmParams:(u=t==null?void 0:t.utmParams)!=null?u:{},deviceClass:n?T(n):"desktop",trafficSource:c?N(c,t==null?void 0:t.appOrigin):"direct",referrerDomain:D(c),timeOfDay:k(s),dayOfWeek:(l=["sun","mon","tue","wed","thu","fri","sat"][s.getDay()])!=null?l:"sun"}}async function Q(e,t,n){let c={"Content-Type":"application/json",Authorization:`Bearer ${n.apiKey}`};n.origin&&(c.Origin=n.origin);let s=j(t,{userAgent:n.userAgent,referer:n.referer,utmParams:n.utmParams,appOrigin:n.origin});try{await fetch(`${n.baseUrl}/sessions`,{method:"POST",headers:c,body:JSON.stringify(s)})}catch(i){}let r=await Promise.allSettled(e.map(async({id:i,variantIds:a})=>{let d=await fetch(`${n.baseUrl}/assign`,{method:"POST",headers:c,body:JSON.stringify({sessionId:t,componentId:i,variantIds:a})});if(!d.ok)return null;let u=await d.json();return{id:i,variantId:u.variantId}})),o={};for(let i of r)i.status==="fulfilled"&&i.value&&(o[i.value.id]=i.value.variantId);return o}function W(e){var t,n;return(n=(t=e.get("_snt_uid"))==null?void 0:t.value)!=null?n:null}function Pe(){try{if(typeof crypto!="undefined"&&typeof crypto.randomUUID=="function")return crypto.randomUUID()}catch(e){}return`evt-${Date.now()}-${Math.random().toString(16).slice(2)}`}var B={track:()=>{},getAssignment:()=>null,assign:()=>Promise.resolve(null),getGraph:()=>({pageNodes:[],userEdges:[],capturedAt:0}),destroy:()=>{}};function Me(){try{let e={},t=new URLSearchParams(window.location.search);for(let[n,c]of t)n.startsWith("utm_")&&(e[n]=c);return e}catch(e){return{}}}function Le(e){return e.replace(/\/events\/?$/,"")}function ie(e){var y,I,P,v;if(typeof window=="undefined"||e.consent===!1)return B;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."),B;if(!e.ingestUrl)return console.warn("[sentient] init() called without ingestUrl. SDK disabled."),B;let t=Date.now(),n=re(),c=oe(),s=se({ingestUrl:e.ingestUrl,apiKey:e.apiKey}),r=Le(e.ingestUrl),o={"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`},i=T((y=navigator.userAgent)!=null?y:""),a=typeof window!="undefined"?window.location.origin:void 0,d=N((I=document.referrer)!=null?I:"",a),u=(P=e.sessionSegment)!=null?P:`${i}:${d}`;if(e.initialAssignments)for(let[m,h]of Object.entries(e.initialAssignments))c.set(m,u,{variantId:h,assignedAt:Date.now(),segment:u,confidence:1});let l=Promise.resolve(),S=n.getSessionId();if(S){let m=D((v=document.referrer)!=null?v:""),h={sessionId:S,deviceClass:i,trafficSource:d,referrerDomain:m,utmParams:Me(),timeOfDay:k(new Date),dayOfWeek:["sun","mon","tue","wed","thu","fri","sat"][new Date().getDay()],ephemeral:n.isEphemeral()};try{l=fetch(`${r}/sessions`,{method:"POST",keepalive:!0,body:JSON.stringify(h),headers:o}).then(()=>{}).catch(()=>{})}catch(E){}}e.debug&&(console.log("[sentient] initialized",{context:e.context}),window.__sentient={client:null,queue:s});let f={track(m){let h=n.getSessionId();if(!h)return;let E=L(_({},m),{id:Pe(),sessionId:h,timestamp:Date.now(),timeInSession:Date.now()-t});s.push(E),e.debug&&console.log("[sentient] track",E)},getAssignment(m,h){return c.get(m,h)},async assign(m,h){let E=n.getSessionId();if(!E)return null;let O=c.get(m,u);if(O)return{variantId:O.variantId,assignmentTtlMs:0};await l;try{let A=await fetch(`${r}/assign`,{method:"POST",body:JSON.stringify({sessionId:E,componentId:m,variantIds:h}),headers:o});if(!A.ok)return null;let U=await A.json();return c.set(m,u,{variantId:U.variantId,assignedAt:Date.now(),segment:u,confidence:1}),U}catch(A){return null}},getGraph(){return{pageNodes:[],userEdges:[],capturedAt:0}},destroy(){s.destroy(),n.destroy(),e.debug&&console.log("[sentient] destroyed")}};if(e.debug){let m=window;m.__sentient&&(m.__sentient.client=f)}return f}var $e=new Set(["SECTION","ARTICLE","MAIN","DIV"]),Ke="h1, h2, h3",Ge={scan:async()=>({nodes:[],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 Be(e){var t,n,c;try{let s=e;for(let r of Object.keys(s)){if(!r.startsWith("__reactFiber")&&!r.startsWith("__reactInternalInstance"))continue;let o=s[r],i=(c=(t=o==null?void 0:o.type)==null?void 0:t.displayName)!=null?c:(n=o==null?void 0:o.type)==null?void 0:n.name;if(i&&i.length>1)return i}}catch(s){}}function Fe(e){let t={};for(let n of Array.from(e.attributes))n.name.startsWith("data-")&&(t[n.name]=n.value);return t}function ze(e){let t=e.getAttribute("data-sentient-type");if(t)return t;let n=e.getAttribute("role");return n||"generic"}function Je(e){var t,n;return(n=(t=e.getAttribute("data-sentient-id"))!=null?t:e.getAttribute("id"))!=null?n:e.tagName.toLowerCase()}function je(e){let t=0,n=e.parentElement;for(;n;)t++,n=n.parentElement;return t}function Y(e,t){var c,s,r;let n=e.querySelector(Ke);return{componentId:Je(e),semanticType:ze(e),ariaLabel:(c=e.getAttribute("aria-label"))!=null?c:void 0,headingText:(r=(s=n==null?void 0:n.textContent)==null?void 0:s.trim())!=null?r:void 0,isAboveFold:e.getBoundingClientRect().top<window.innerHeight,prominenceScore:t(e),depth:je(e),reactComponentName:Be(e),dataAttributes:Fe(e)}}function Qe(e){let t=[],n=new Set;return document.querySelectorAll("[data-sentient-id]").forEach(r=>{r instanceof Element&&!n.has(r)&&(n.add(r),t.push(Y(r,e)))}),document.querySelectorAll("section, article, main, aside").forEach(r=>{if(!(r instanceof Element)||n.has(r))return;let o=r.hasAttribute("aria-label"),i=r.hasAttribute("data-sentient-id");!o&&!i||(n.add(r),t.push(Y(r,e)))}),t}function ae(){if(typeof window=="undefined")return Ge;let e=null,t=0,n=null,c=i=>{try{let a=window.getComputedStyle(i),d=parseFloat(a.fontSize)||12,u=parseFloat(a.zIndex)||0,l=i.getBoundingClientRect(),S=Math.max(l.top,0),f=window.innerHeight||1,y=1/(S/f+1),I=q(d,12,48)*.4+q(y,0,1)*.4+q(u,0,100)*.2;return Math.max(0,Math.min(1,I))}catch(a){return .5}};return{scan:()=>new Promise(i=>{let a=()=>{i({nodes:Qe(c),scannedAt:Date.now()})};try{typeof requestIdleCallback=="function"?t=requestIdleCallback(a,{timeout:100}):a()}catch(d){a()}}),observe:i=>{n=i;try{e=new MutationObserver(a=>{let d=[];for(let u of a)u.type==="childList"&&u.addedNodes.forEach(l=>{if(!(l instanceof Element)||!$e.has(l.tagName))return;let S=l.hasAttribute("data-sentient-id"),f=l.hasAttribute("aria-label");!S&&!f||d.push(Y(l,c))});d.length>0&&n&&n({nodes:d,addedAt:Date.now()})}),e.observe(document.body,{childList:!0,subtree:!0})}catch(a){}},getProminenceScore:c,destroy:()=>{if(e&&(e.disconnect(),e=null),t&&typeof cancelIdleCallback=="function")try{cancelIdleCallback(t)}catch(i){}t=0,n=null}}}var H="_snt_graph_nodes",V="_snt_graph_edges",We={pricing:["features","faq"],features:["pricing"],faq:["pricing"],social_proof:["cta"],cta:["social_proof","hero","trust"],hero:["cta"],comparison:["pricing"],trust:["cta"]};function X(e){return Math.max(0,Math.min(1,e))}function qe(e){var t;return(t=We[e])!=null?t:[]}function ce(e,t){try{let n=localStorage.getItem(e);return n?JSON.parse(n):t}catch(n){return t}}function de(e,t){try{localStorage.setItem(e,JSON.stringify(t))}catch(n){}}var Ye=new Set(["pricing","hero","social_proof","cta","features","faq","comparison","trust","navigation","generic"]);function He(e){return Ye.has(e)?e:"generic"}function Ve(e,t,n){let c=`${e}:${t}:${n.join(",")}`,s=5381;for(let r=0;r<c.length;r++)s=(s<<5)+s+c.charCodeAt(r)&4294967295;return(s>>>0).toString(16).padStart(8,"0")}function ue(e){let t=new Map,n=new Map,c=()=>{typeof window!="undefined"&&(de(H,[...t.values()]),de(V,[...n.values()]))},s=o=>{var i,a;try{let d=JSON.parse(o);t.clear(),n.clear();for(let u of(i=d.pageNodes)!=null?i:[])t.set(u.componentId,u);for(let u of(a=d.userEdges)!=null?a:[])n.set(u.componentId,u)}catch(d){}};if(typeof window!="undefined"){let o=ce(H,[]),i=ce(V,[]);for(let a of o)t.set(a.componentId,a);for(let a of i)n.set(a.componentId,a)}let r=(o,i)=>{let a=n.get(o);a?(a.attentionWeight=X(a.attentionWeight+i),a.lastUpdated=Date.now()):n.set(o,{componentId:o,attentionWeight:X(i),interactionCount:0,dwellTime:0,lastUpdated:Date.now()})};return{addPageNode(o){t.set(o.componentId,o),c()},syncOnce(){if(!(e!=null&&e.syncUrl)||typeof window=="undefined")return;let o=[...t.values()];if(o.length!==0)try{let i={pageUrl:window.location.href,nodes:o.map(a=>{let d=He(a.semanticType);return{componentId:a.componentId,semanticType:d,answers:a.answers,contentHash:Ve(a.componentId,d,a.answers),prominenceScore:a.prominenceScore,depthInPage:a.depth}}),edges:[]};fetch(e.syncUrl,{method:"POST",keepalive:!0,headers:_({"Content-Type":"application/json"},e.apiKey?{Authorization:`Bearer ${e.apiKey}`}:{}),body:JSON.stringify(i)}).catch(()=>{})}catch(i){}},updateUserEdge(o,i){var d;let a=(d=n.get(o))!=null?d:{componentId:o,attentionWeight:0,interactionCount:0,dwellTime:0,lastUpdated:Date.now()};a.attentionWeight=X(a.attentionWeight+i),a.interactionCount+=1,a.lastUpdated=Date.now(),n.set(o,a),c()},propagate(o,i){let a=t.get(o);if(!a){r(o,i),c();return}r(o,i);for(let d of qe(a.semanticType))for(let u of t.values())u.semanticType===d&&u.componentId!==o&&r(u.componentId,i*.4);for(let d of t.values())d.depth===a.depth+1&&r(d.componentId,i*.6);for(let d of t.values())d.semanticType===a.semanticType&&d.componentId!==o&&r(d.componentId,i*-.2);c()},snapshot(){return{pageNodes:[...t.values()],userEdges:[...n.values()],capturedAt:Date.now()}},serialize(){return JSON.stringify({pageNodes:[...t.values()],userEdges:[...n.values()]})},restore:s,destroy(){if(typeof window!="undefined")try{localStorage.removeItem(H),localStorage.removeItem(V)}catch(o){}}}}function Xe(){try{let e=document.cookie.match(/(?:^|; )_snt_uid=([^;]*)/);return e?decodeURIComponent(e[1]):void 0}catch(e){return}}function Ze(e){let t=ie(e);if(!e.graph||typeof window=="undefined")return t;let n=ae(),c=ue({syncUrl:e.ingestUrl.replace(/\/events\/?$/,"/graph/sync"),apiKey:e.apiKey,projectId:e.apiKey,sessionId:Xe()});try{let s=localStorage.getItem("_snt_graph_nodes"),r=localStorage.getItem("_snt_graph_edges");(s||r)&&c.restore(JSON.stringify({pageNodes:s?JSON.parse(s):[],userEdges:r?JSON.parse(r):[]}))}catch(s){}return n.scan().then(s=>{for(let r of s.nodes)c.addPageNode({id:r.componentId,componentId:r.componentId,semanticType:r.semanticType,answers:r.headingText?[r.headingText]:[],prominenceScore:r.prominenceScore,depth:r.depth});c.syncOnce()}),n.observe(s=>{for(let r of s.nodes)c.addPageNode({id:r.componentId,componentId:r.componentId,semanticType:r.semanticType,answers:r.headingText?[r.headingText]:[],prominenceScore:r.prominenceScore,depth:r.depth})}),L(_({},t),{getGraph:()=>c.snapshot(),destroy:()=>{n.destroy(),c.destroy(),t.destroy()}})}0&&(module.exports={deriveSessionSegment,detectDeviceClass,detectTimeOfDay,detectTrafficSource,init,preloadAssignments,readSessionCookie,referrerDomainFromReferer});
|
|
1
|
+
"use strict";var $=Object.defineProperty,de=Object.defineProperties,ue=Object.getOwnPropertyDescriptor,ge=Object.getOwnPropertyDescriptors,le=Object.getOwnPropertyNames,X=Object.getOwnPropertySymbols;var ee=Object.prototype.hasOwnProperty,pe=Object.prototype.propertyIsEnumerable;var Z=(e,t,n)=>t in e?$(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,_=(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))pe.call(t,n)&&Z(e,n,t[n]);return e},L=(e,t)=>de(e,ge(t));var me=(e,t)=>{for(var n in t)$(e,n,{get:t[n],enumerable:!0})},fe=(e,t,n,a)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of le(t))!ee.call(e,o)&&o!==n&&$(e,o,{get:()=>t[o],enumerable:!(a=ue(t,o))||a.enumerable});return e};var he=e=>fe($({},"__esModule",{value:!0}),e);var nt={};me(nt,{deriveSessionSegment:()=>z,detectDeviceClass:()=>k,detectTimeOfDay:()=>R,detectTrafficSource:()=>N,init:()=>tt,preloadAssignments:()=>q,readSessionCookie:()=>W,referrerDomainFromReferer:()=>D});module.exports=he(nt);var ye="_snt_uid";var O="_snt_uid";function Se(){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 ve(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 Ee(e){try{return localStorage.getItem(e)}catch(t){return null}}function we(e,t){try{return localStorage.setItem(e,t),!0}catch(n){return!1}}function be(e){try{return sessionStorage.getItem(e)}catch(t){return null}}function Ce(e,t){try{return sessionStorage.setItem(e,t),!0}catch(n){return!1}}function Ae(e){try{sessionStorage.removeItem(e)}catch(t){}}function _e(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 Te(e){try{localStorage.removeItem(e)}catch(t){}}function xe(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,g,l,m,u;if(typeof window=="undefined")return Oe;let t=(d=e==null?void 0:e.cookieName)!=null?d:ye,a=((g=e==null?void 0:e.cookieTTLDays)!=null?g:365)*24*60*60,o=(u=(m=(l=ve(t))!=null?l:Ee(O))!=null?m:be(O))!=null?u:Se();Ie(t,o,a);let i=we(O,o),r=_e(t),s=i?!1:Ce(O,o),c=!i&&!r&&!s;return{getSessionId:()=>o,isEphemeral:()=>c,destroy:()=>{o=null,xe(t),Te(O),Ae(O)}}}var K="_snt_retry";var ke={push:()=>{},flush:()=>{},destroy:()=>{}};function Ne(e){try{let t=localStorage.getItem(K);if(!t)return[];let n=JSON.parse(t);return Array.isArray(n)?(localStorage.removeItem(K),n.slice(-e)):[]}catch(t){return[]}}function F(e,t){try{let a=[...(()=>{try{let o=localStorage.getItem(K);if(!o)return[];let i=JSON.parse(o);return Array.isArray(i)?i:[]}catch(o){return[]}})(),...e].slice(-t);localStorage.setItem(K,JSON.stringify(a))}catch(n){}}function ne(e){var v,P,T;if(typeof window=="undefined")return ke;let t=(v=e.flushIntervalMs)!=null?v:5e3,n=(P=e.maxBatchSize)!=null?P:20,a=(T=e.maxRetrySize)!=null?T:100,o=e.ingestUrl,i=e.apiKey,r=[],s=new Set,c=[],d=p=>{for(let S of p)s.has(S)||(s.add(S),c.push(S));for(;c.length>500;){let S=c.shift();S&&s.delete(S)}},g=new Set,l=p=>{s.has(p.id)||g.has(p.id)||(g.add(p.id),r.push(p))},m=Ne(a);for(let p of m)l(p);let u=0,f=0,E=p=>{if(p.length===0)return;let S=JSON.stringify(p),x=p.map(A=>A.id),C;try{C=fetch(o,{method:"POST",keepalive:!0,body:S,headers:{"Content-Type":"application/json",Authorization:`Bearer ${i}`}})}catch(A){F(p,a),f++,u=Date.now()+Math.min(6e4,1e3*2**Math.min(f,6));return}let M=A=>{if(A.ok||A.status>=400&&A.status<500&&A.status!==429){d(x),f=0,u=0;return}F(p,a),f++,u=Date.now()+Math.min(6e4,1e3*2**Math.min(f,6))};C instanceof Promise?C.then(M).catch(()=>{F(p,a),f++,u=Date.now()+Math.min(6e4,1e3*2**Math.min(f,6))}):M(C)},w=p=>{let S=[],x=2;for(let C of p){let M=JSON.stringify(C).length+1;if(S.length>0&&x+M>57344||S.length>=n)break;S.push(C),x+=M}return S},I=()=>{try{if(Date.now()<u)return;for(;r.length>0;){let p=r.filter(x=>!s.has(x.id));if(r.length=0,p.length===0)break;let S=w(p);if(S.length===0)break;S.length<p.length&&r.push(...p.slice(S.length)),E(S)}}catch(p){}},U=!0,b=null;b=setInterval(()=>{U&&I()},t);let h=()=>{document.visibilityState==="hidden"&&I()},y=()=>{I()};return document.addEventListener("visibilitychange",h),window.addEventListener("beforeunload",y),{push(p){l(p),r.length>=n&&I()},flush:I,destroy(){U=!1,b!==null&&(clearInterval(b),b=null),document.removeEventListener("visibilitychange",h),window.removeEventListener("beforeunload",y),I()}}}var B="_snt_asgn_";function G(e,t){return`${e}:${t}`}function De(e,t){return`${B}${e}_${t}`}function J(){try{let e=[];for(let t=0;t<localStorage.length;t++){let n=localStorage.key(t);n!=null&&n.startsWith(B)&&e.push(n)}return e}catch(e){return[]}}function re(e=18e5){let t=new Map,n=o=>o.assignedAt+e<Date.now();return typeof window!="undefined"&&(()=>{for(let o of J())try{let i=localStorage.getItem(o);if(!i)continue;let r=JSON.parse(i);if(n(r)){localStorage.removeItem(o);continue}let s=o.slice(B.length),c=s.lastIndexOf("_");if(c<0)continue;let d=s.slice(0,c),g=s.slice(c+1);t.set(G(d,g),r)}catch(i){}})(),{get(o,i){let r=t.get(G(o,i));return r?n(r)?(t.delete(G(o,i)),null):r:null},set(o,i,r){let s=G(o,i);t.set(s,r);try{localStorage.setItem(De(o,i),JSON.stringify(r))}catch(c){}},invalidate(o){let i=`${o}:`;for(let r of[...t.keys()])r.startsWith(i)&&t.delete(r);for(let r of J()){let s=r.slice(B.length),c=s.lastIndexOf("_");if(c<0)continue;if(s.slice(0,c)===o)try{localStorage.removeItem(r)}catch(g){}}},clear(){t.clear();for(let o of J())try{localStorage.removeItem(o)}catch(i){}}}}function k(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 N(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 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 D(e){if(!e)return null;try{return new URL(e).hostname}catch(t){return null}}function R(e){let t=e.getHours();return t<6?"night":t<12?"morning":t<18?"afternoon":"evening"}function z(e){let t=Q("__segment__",e);return`${t.deviceClass}:${t.trafficSource}`}function Q(e,t){var i,r,s,c,d,g,l;let n=(r=(i=t==null?void 0:t.userAgent)==null?void 0:i.trim())!=null?r:"",a=(c=(s=t==null?void 0:t.referer)==null?void 0:s.trim())!=null?c:"",o=(d=t==null?void 0:t.now)!=null?d:new Date;return{sessionId:e,ephemeral:!1,utmParams:(g=t==null?void 0:t.utmParams)!=null?g:{},deviceClass:n?k(n):"desktop",trafficSource:a?N(a,t==null?void 0:t.appOrigin):"direct",referrerDomain:D(a),timeOfDay:R(o),dayOfWeek:(l=["sun","mon","tue","wed","thu","fri","sat"][o.getDay()])!=null?l:"sun"}}async function q(e,t,n){let a={"Content-Type":"application/json",Authorization:`Bearer ${n.apiKey}`};n.origin&&(a.Origin=n.origin);let o=Q(t,{userAgent:n.userAgent,referer:n.referer,utmParams:n.utmParams,appOrigin:n.origin});try{(await fetch(`${n.baseUrl}/sessions`,{method:"POST",headers:a,body:JSON.stringify(o)})).status===402&&console.warn("[SentientUI] Session limit exceeded for this project. The bandit will stop learning until the limit resets. Upgrade at sentientui.dev/pricing")}catch(s){}let i=await Promise.allSettled(e.map(async({id:s,variantIds:c})=>{let d=await fetch(`${n.baseUrl}/assign`,{method:"POST",headers:a,body:JSON.stringify({sessionId:t,componentId:s,variantIds:c})});if(!d.ok)return null;let g=await d.json();return{id:s,variantId:g.variantId}})),r={};for(let s of i)s.status==="fulfilled"&&s.value&&(r[s.value.id]=s.value.variantId);return r}function W(e){var t,n;return(n=(t=e.get("_snt_uid"))==null?void 0:t.value)!=null?n:null}var Re="https://sentient-api.fly.dev/v1/events";function Ue(){try{if(typeof crypto!="undefined"&&typeof crypto.randomUUID=="function")return crypto.randomUUID()}catch(e){}return`evt-${Date.now()}-${Math.random().toString(16).slice(2)}`}var j={track:()=>{},goal:()=>{},identify:()=>{},getAssignment:()=>null,assign:()=>Promise.resolve(null),getGraph:()=>({pageNodes:[],capturedAt:0}),destroy:()=>{}};function Pe(){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 Me(e){return e.replace(/\/events\/?$/,"")}function se(e){var E,w,I,U,b;if(typeof window=="undefined"||e.consent===!1)return j;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."),j;if(e.ingestUrl==="")return console.warn("[sentient] init() called with an empty ingestUrl. SDK disabled."),j;let t=(E=e.ingestUrl)!=null?E:Re,n=Date.now(),a=te(),o=re(),i=ne({ingestUrl:t,apiKey:e.apiKey}),r=Me(t),s={"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`},c=k((w=navigator.userAgent)!=null?w:""),d=typeof window!="undefined"?window.location.origin:void 0,g=N((I=document.referrer)!=null?I:"",d),l=(U=e.sessionSegment)!=null?U:`${c}:${g}`;if(e.initialAssignments)for(let[h,y]of Object.entries(e.initialAssignments))o.set(h,l,{variantId:y,assignedAt:Date.now(),segment:l,confidence:1});let m=Promise.resolve(),u=a.getSessionId();if(u){let h=D((b=document.referrer)!=null?b:""),y=_({sessionId:u,deviceClass:c,trafficSource:g,referrerDomain:h,utmParams:Pe(),timeOfDay:R(new Date),dayOfWeek:["sun","mon","tue","wed","thu","fri","sat"][new Date().getDay()],ephemeral:a.isEphemeral()},e.userId?{userId:e.userId}:{});try{m=fetch(`${r}/sessions`,{method:"POST",keepalive:!0,body:JSON.stringify(y),headers:s}).then(v=>{v.status===402&&console.warn("[SentientUI] Session limit exceeded for this project. The bandit will stop learning until the limit resets. Upgrade at sentientui.dev/pricing")}).catch(()=>{})}catch(v){}}e.debug&&(console.log("[sentient] initialized",{context:e.context}),window.__sentient={client:null,queue:i});let f={goal(h,y={}){let v=a.getSessionId();v&&m.then(()=>{fetch(`${r}/goals`,{method:"POST",keepalive:!0,body:JSON.stringify({sessionId:v,name:h,metadata:y}),headers:s}).catch(()=>{})})},identify(h){let y=a.getSessionId();y&&m.then(()=>{fetch(`${r}/sessions`,{method:"POST",keepalive:!0,body:JSON.stringify({sessionId:y,userId:h,ephemeral:a.isEphemeral()}),headers:s}).catch(()=>{})})},track(h){let y=a.getSessionId();if(!y)return;let v=L(_({},h),{id:Ue(),sessionId:y,timestamp:Date.now(),timeInSession:Date.now()-n});i.push(v),e.debug&&console.log("[sentient] track",v)},getAssignment(h,y){return o.get(h,y)},async assign(h,y){let v=a.getSessionId();if(!v)return null;let P=o.get(h,l);if(P)return{variantId:P.variantId,assignmentTtlMs:0};await m;try{let T=await fetch(`${r}/assign`,{method:"POST",body:JSON.stringify({sessionId:v,componentId:h,variantIds:y}),headers:s});if(!T.ok)return null;let p=await T.json();return o.set(h,l,{variantId:p.variantId,assignedAt:Date.now(),segment:l,confidence:1}),p}catch(T){return null}},getGraph(){return{pageNodes:[],capturedAt:0}},destroy(){i.destroy(),a.destroy(),e.debug&&console.log("[sentient] destroyed")}};if(e.debug){let h=window;h.__sentient&&(h.__sentient.client=f)}return f}var $e=new Set(["SECTION","ARTICLE","MAIN","DIV"]),Le="h1, h2, h3",Ke={scan:async()=>({nodes:[],edges:[],scannedAt:0}),observe:()=>{},getProminenceScore:()=>0,destroy:()=>{}};function Y(e,t,n){return n<=t?0:Math.max(0,Math.min(1,(e-t)/(n-t)))}function Ge(e){var t,n,a;try{let o=e;for(let i of Object.keys(o)){if(!i.startsWith("__reactFiber")&&!i.startsWith("__reactInternalInstance"))continue;let r=o[i],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(o){}}function Be(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 Fe(e){var t,n;return(n=(t=e.getAttribute("data-sentient-id"))!=null?t:e.getAttribute("id"))!=null?n:e.tagName.toLowerCase()}function Je(e){let t=0,n=e.parentElement;for(;n;)t++,n=n.parentElement;return t}function H(e,t){var a,o,i;let n=e.querySelector(Le);return{componentId:Fe(e),semanticType:je(e),ariaLabel:(a=e.getAttribute("aria-label"))!=null?a:void 0,headingText:(i=(o=n==null?void 0:n.textContent)==null?void 0:o.trim())!=null?i:void 0,isAboveFold:e.getBoundingClientRect().top<window.innerHeight,prominenceScore:t(e),depth:Je(e),reactComponentName:Ge(e),dataAttributes:Be(e)}}function oe(e){var i;let t=[],n=new Set,a="__root__",o=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 l=e.get(r),m=`${d}->${l}`;!n.has(m)&&d!==l&&(n.add(m),t.push({fromComponentId:d,toComponentId:l,weight:.6}));break}c=c.parentElement}let g=(i=o.get(d))!=null?i:[];g.push(r),o.set(d,g)}for(let r of o.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]),g=e.get(r[c]);if(d===g)continue;let l=`${d}->${g}::sib`,m=`${g}->${d}::sib`;n.has(l)||(n.add(l),t.push({fromComponentId:d,toComponentId:g,weight:.3})),n.has(m)||(n.add(m),t.push({fromComponentId:g,toComponentId:d,weight:.3}))}return t}function ze(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=H(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=H(r,e);t.push(d),a.set(r,d.componentId)}),{nodes:t,edges:oe(a)}}function ie(){if(typeof window=="undefined")return Ke;let e=null,t=0,n=null,a=s=>{try{let c=window.getComputedStyle(s),d=parseFloat(c.fontSize)||12,g=parseFloat(c.zIndex)||0,l=s.getBoundingClientRect(),m=Math.max(l.top,0),u=window.innerHeight||1,f=1/(m/u+1),E=Y(d,12,48)*.4+Y(f,0,1)*.4+Y(g,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:g}=ze(a);s({nodes:d,edges:g,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=[],g=new Map;for(let l of c)l.type==="childList"&&l.addedNodes.forEach(m=>{if(!(m instanceof Element)||!$e.has(m.tagName))return;let u=m.hasAttribute("data-sentient-id"),f=m.hasAttribute("aria-label");if(!u&&!f)return;let E=H(m,a);d.push(E),g.set(m,E.componentId)});d.length>0&&n&&n({nodes:d,edges:oe(g),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",ae="_snt_graph_edges",Qe={pricing:["features","faq"],features:["pricing"],faq:["pricing"],social_proof:["cta"],cta:["social_proof","hero","trust"],hero:["cta"],comparison:["pricing"],trust:["cta"]};function qe(e){var t;return(t=Qe[e])!=null?t:[]}function We(e,t){try{let n=localStorage.getItem(e);return n?JSON.parse(n):t}catch(n){return t}}function Ye(e,t){try{localStorage.setItem(e,JSON.stringify(t))}catch(n){}}var He=new Set(["pricing","hero","social_proof","cta","features","faq","comparison","trust","navigation","generic"]);function Ve(e){return He.has(e)?e:"generic"}function Xe(e,t,n){let a=`${e}:${t}:${n.join(",")}`,o=5381;for(let i=0;i<a.length;i++)o=(o<<5)+o+a.charCodeAt(i)&4294967295;return(o>>>0).toString(16).padStart(8,"0")}function ce(e){let t=new Map,n=new Map,a=()=>{typeof window!="undefined"&&Ye(V,[...t.values()])},o=i=>{var r;try{let s=JSON.parse(i);t.clear();for(let c of(r=s.pageNodes)!=null?r:[])t.set(c.componentId,c)}catch(s){}};if(typeof window!="undefined"){let i=We(V,[]);for(let r of i)t.set(r.componentId,r);try{localStorage.removeItem(ae)}catch(r){}}return{addPageNode(i){t.set(i.componentId,i),a()},addStructuralEdge(i){let r=`${i.fromComponentId}->${i.toComponentId}`;n.set(r,i)},syncOnce(){var r,s;if(!(e!=null&&e.syncUrl)||typeof window=="undefined")return;let i=[...t.values()];if(i.length!==0)try{let c=new Map;for(let u of i){let f=(r=c.get(u.semanticType))!=null?r:[];f.push(u),c.set(u.semanticType,f)}let d=[],g=new Set;for(let u of i)for(let f of qe(u.semanticType)){let E=(s=c.get(f))!=null?s:[];for(let w of E){if(w.componentId===u.componentId)continue;let I=`semantic:${u.componentId}->${w.componentId}`;g.has(I)||(g.add(I),d.push({fromComponentId:u.componentId,toComponentId:w.componentId,type:"semantic",weight:.4,confidence:.9}))}}let l=new Set(i.map(u=>u.componentId));for(let u of n.values()){if(!l.has(u.fromComponentId)||!l.has(u.toComponentId))continue;let f=`structural:${u.fromComponentId}->${u.toComponentId}`;g.has(f)||(g.add(f),d.push({fromComponentId:u.fromComponentId,toComponentId:u.toComponentId,type:"structural",weight:u.weight,confidence:1}))}let m={pageUrl:window.location.href,nodes:i.map(u=>{let f=Ve(u.semanticType);return{componentId:u.componentId,semanticType:f,answers:u.answers,contentHash:Xe(u.componentId,f,u.answers),prominenceScore:u.prominenceScore,depthInPage:u.depth}}),edges:d};fetch(e.syncUrl,{method:"POST",keepalive:!0,headers:_({"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:o,destroy(){if(typeof window!="undefined")try{localStorage.removeItem(V),localStorage.removeItem(ae)}catch(i){}}}}var Ze="https://sentient-api.fly.dev/v1/events";function et(){try{let e=document.cookie.match(/(?:^|; )_snt_uid=([^;]*)/);return e?decodeURIComponent(e[1]):void 0}catch(e){return}}function tt(e){var i;let t=se(e);if(!e.graph||typeof window=="undefined")return t;let n=ie(),a=(i=e.ingestUrl)!=null?i:Ze,o=ce({syncUrl:a.replace(/\/events\/?$/,"/graph/sync"),apiKey:e.apiKey,projectId:e.apiKey,sessionId:et()});try{let r=localStorage.getItem("_snt_graph_nodes");r&&o.restore(JSON.stringify({pageNodes:JSON.parse(r)}))}catch(r){}return n.scan().then(r=>{for(let s of r.nodes)o.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)o.addStructuralEdge(s);o.syncOnce()}),n.observe(r=>{for(let s of r.nodes)o.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)o.addStructuralEdge(s)}),L(_({},t),{getGraph:()=>o.snapshot(),destroy:()=>{n.destroy(),o.destroy(),t.destroy()}})}0&&(module.exports={deriveSessionSegment,detectDeviceClass,detectTimeOfDay,detectTrafficSource,init,preloadAssignments,readSessionCookie,referrerDomainFromReferer});
|
package/dist/index-graph.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as
|
|
1
|
+
import{a as h,b,c as x,d as _,e as O,f as M,g as R,h as P,i as D,k as v}from"./chunk-HWKW5O3R.mjs";var G=new Set(["SECTION","ARTICLE","MAIN","DIV"]),k="h1, h2, h3",$={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 L(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 o=d[s],r=(p=(t=o==null?void 0:o.type)==null?void 0:t.displayName)!=null?p:(n=o==null?void 0:o.type)==null?void 0:n.name;if(r&&r.length>1)return r}}catch(d){}}function U(e){let t={};for(let n of Array.from(e.attributes))n.name.startsWith("data-")&&(t[n.name]=n.value);return t}function j(e){let t=e.getAttribute("data-sentient-type");if(t)return t;let n=e.getAttribute("role");return n||"generic"}function F(e){var t,n;return(n=(t=e.getAttribute("data-sentient-id"))!=null?t:e.getAttribute("id"))!=null?n:e.tagName.toLowerCase()}function K(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(k);return{componentId:F(e),semanticType:j(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:K(e),reactComponentName:L(e),dataAttributes:U(e)}}function w(e){var s;let t=[],n=new Set,p="__root__",d=new Map;for(let[o,r]of e){let a=o.parentElement,c=p;for(;a;){if(e.has(a)){c=e.get(a);let m=e.get(o),g=`${c}->${m}`;!n.has(g)&&c!==m&&(n.add(g),t.push({fromComponentId:c,toComponentId:m,weight:.6}));break}a=a.parentElement}let u=(s=d.get(c))!=null?s:[];u.push(o),d.set(c,u)}for(let o of d.values())if(!(o.length<2))for(let r=0;r<o.length;r++)for(let a=r+1;a<o.length;a++){let c=e.get(o[r]),u=e.get(o[a]);if(c===u)continue;let m=`${c}->${u}::sib`,g=`${u}->${c}::sib`;n.has(m)||(n.add(m),t.push({fromComponentId:c,toComponentId:u,weight:.3})),n.has(g)||(n.add(g),t.push({fromComponentId:u,toComponentId:c,weight:.3}))}return t}function q(e){let t=[],n=new Set,p=new Map;return document.querySelectorAll("[data-sentient-id]").forEach(o=>{if(o instanceof Element&&!n.has(o)){n.add(o);let r=I(o,e);t.push(r),p.set(o,r.componentId)}}),document.querySelectorAll("section, article, main, aside").forEach(o=>{if(!(o instanceof Element)||n.has(o))return;let r=o.hasAttribute("aria-label"),a=o.hasAttribute("data-sentient-id");if(!r&&!a)return;n.add(o);let c=I(o,e);t.push(c),p.set(o,c.componentId)}),{nodes:t,edges:w(p)}}function N(){if(typeof window=="undefined")return $;let e=null,t=0,n=null,p=r=>{try{let a=window.getComputedStyle(r),c=parseFloat(a.fontSize)||12,u=parseFloat(a.zIndex)||0,m=r.getBoundingClientRect(),g=Math.max(m.top,0),i=window.innerHeight||1,f=1/(g/i+1),l=S(c,12,48)*.4+S(f,0,1)*.4+S(u,0,100)*.2;return Math.max(0,Math.min(1,l))}catch(a){return .5}};return{scan:()=>new Promise(r=>{let a=()=>{let{nodes:c,edges:u}=q(p);r({nodes:c,edges:u,scannedAt:Date.now()})};try{typeof requestIdleCallback=="function"?t=requestIdleCallback(a,{timeout:100}):a()}catch(c){a()}}),observe:r=>{n=r;try{e=new MutationObserver(a=>{let c=[],u=new Map;for(let m of a)m.type==="childList"&&m.addedNodes.forEach(g=>{if(!(g instanceof Element)||!G.has(g.tagName))return;let i=g.hasAttribute("data-sentient-id"),f=g.hasAttribute("aria-label");if(!i&&!f)return;let l=I(g,p);c.push(l),u.set(g,l.componentId)});c.length>0&&n&&n({nodes:c,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(r){}t=0,n=null}}}var C="_snt_graph_nodes",A="_snt_graph_edges",z={pricing:["features","faq"],features:["pricing"],faq:["pricing"],social_proof:["cta"],cta:["social_proof","hero","trust"],hero:["cta"],comparison:["pricing"],trust:["cta"]};function H(e){var t;return(t=z[e])!=null?t:[]}function J(e,t){try{let n=localStorage.getItem(e);return n?JSON.parse(n):t}catch(n){return t}}function B(e,t){try{localStorage.setItem(e,JSON.stringify(t))}catch(n){}}var V=new Set(["pricing","hero","social_proof","cta","features","faq","comparison","trust","navigation","generic"]);function W(e){return V.has(e)?e:"generic"}function Y(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"&&B(C,[...t.values()])},d=s=>{var o;try{let r=JSON.parse(s);t.clear();for(let a of(o=r.pageNodes)!=null?o:[])t.set(a.componentId,a)}catch(r){}};if(typeof window!="undefined"){let s=J(C,[]);for(let o of s)t.set(o.componentId,o);try{localStorage.removeItem(A)}catch(o){}}return{addPageNode(s){t.set(s.componentId,s),p()},addStructuralEdge(s){let o=`${s.fromComponentId}->${s.toComponentId}`;n.set(o,s)},syncOnce(){var o,r;if(!(e!=null&&e.syncUrl)||typeof window=="undefined")return;let s=[...t.values()];if(s.length!==0)try{let a=new Map;for(let i of s){let f=(o=a.get(i.semanticType))!=null?o:[];f.push(i),a.set(i.semanticType,f)}let c=[],u=new Set;for(let i of s)for(let f of H(i.semanticType)){let l=(r=a.get(f))!=null?r:[];for(let y of l){if(y.componentId===i.componentId)continue;let E=`semantic:${i.componentId}->${y.componentId}`;u.has(E)||(u.add(E),c.push({fromComponentId:i.componentId,toComponentId:y.componentId,type:"semantic",weight:.4,confidence:.9}))}}let m=new Set(s.map(i=>i.componentId));for(let i of n.values()){if(!m.has(i.fromComponentId)||!m.has(i.toComponentId))continue;let f=`structural:${i.fromComponentId}->${i.toComponentId}`;u.has(f)||(u.add(f),c.push({fromComponentId:i.fromComponentId,toComponentId:i.toComponentId,type:"structural",weight:i.weight,confidence:1}))}let g={pageUrl:window.location.href,nodes:s.map(i=>{let f=W(i.semanticType);return{componentId:i.componentId,semanticType:f,answers:i.answers,contentHash:Y(i.componentId,f,i.answers),prominenceScore:i.prominenceScore,depthInPage:i.depth}}),edges:c};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 Q="https://sentient-api.fly.dev/v1/events";function X(){try{let e=document.cookie.match(/(?:^|; )_snt_uid=([^;]*)/);return e?decodeURIComponent(e[1]):void 0}catch(e){return}}function se(e){var s;let t=v(e);if(!e.graph||typeof window=="undefined")return t;let n=N(),p=(s=e.ingestUrl)!=null?s:Q,d=T({syncUrl:p.replace(/\/events\/?$/,"/graph/sync"),apiKey:e.apiKey,projectId:e.apiKey,sessionId:X()});try{let o=localStorage.getItem("_snt_graph_nodes");o&&d.restore(JSON.stringify({pageNodes:JSON.parse(o)}))}catch(o){}return n.scan().then(o=>{for(let r of o.nodes)d.addPageNode({id:r.componentId,componentId:r.componentId,semanticType:r.semanticType,answers:r.headingText?[r.headingText]:[],prominenceScore:r.prominenceScore,depth:r.depth});for(let r of o.edges)d.addStructuralEdge(r);d.syncOnce()}),n.observe(o=>{for(let r of o.nodes)d.addPageNode({id:r.componentId,componentId:r.componentId,semanticType:r.semanticType,answers:r.headingText?[r.headingText]:[],prominenceScore:r.prominenceScore,depth:r.depth});for(let r of o.edges)d.addStructuralEdge(r)}),b(h({},t),{getGraph:()=>d.snapshot(),destroy:()=>{n.destroy(),d.destroy(),t.destroy()}})}export{R as deriveSessionSegment,x as detectDeviceClass,M as detectTimeOfDay,_ as detectTrafficSource,se as init,P as preloadAssignments,D as readSessionCookie,O as referrerDomainFromReferer};
|
package/dist/index.d.cts
CHANGED
|
@@ -63,12 +63,20 @@ type ScannedNode = {
|
|
|
63
63
|
reactComponentName?: string;
|
|
64
64
|
dataAttributes: Record<string, string>;
|
|
65
65
|
};
|
|
66
|
+
type StructuralEdge$1 = {
|
|
67
|
+
fromComponentId: string;
|
|
68
|
+
toComponentId: string;
|
|
69
|
+
/** 0.6 for direct parent → child, 0.3 for sibling (both directions emitted). */
|
|
70
|
+
weight: number;
|
|
71
|
+
};
|
|
66
72
|
type ScanResult = {
|
|
67
73
|
nodes: ScannedNode[];
|
|
74
|
+
edges: StructuralEdge$1[];
|
|
68
75
|
scannedAt: number;
|
|
69
76
|
};
|
|
70
77
|
type ContentAddedEvent = {
|
|
71
78
|
nodes: ScannedNode[];
|
|
79
|
+
edges: StructuralEdge$1[];
|
|
72
80
|
addedAt: number;
|
|
73
81
|
};
|
|
74
82
|
type DOMScanner = {
|
|
@@ -87,16 +95,8 @@ type PageNode = {
|
|
|
87
95
|
prominenceScore: number;
|
|
88
96
|
depth: number;
|
|
89
97
|
};
|
|
90
|
-
type UserEdge = {
|
|
91
|
-
componentId: string;
|
|
92
|
-
attentionWeight: number;
|
|
93
|
-
interactionCount: number;
|
|
94
|
-
dwellTime: number;
|
|
95
|
-
lastUpdated: number;
|
|
96
|
-
};
|
|
97
98
|
type GraphSnapshot = {
|
|
98
99
|
pageNodes: PageNode[];
|
|
99
|
-
userEdges: UserEdge[];
|
|
100
100
|
capturedAt: number;
|
|
101
101
|
};
|
|
102
102
|
type GraphConfig = {
|
|
@@ -105,10 +105,15 @@ type GraphConfig = {
|
|
|
105
105
|
projectId?: string;
|
|
106
106
|
sessionId?: string;
|
|
107
107
|
};
|
|
108
|
+
type StructuralEdge = {
|
|
109
|
+
fromComponentId: string;
|
|
110
|
+
toComponentId: string;
|
|
111
|
+
weight: number;
|
|
112
|
+
};
|
|
108
113
|
type GraphClient = {
|
|
109
114
|
addPageNode(node: PageNode): void;
|
|
110
|
-
|
|
111
|
-
|
|
115
|
+
/** Record a DOM-derived parent/child or sibling relationship between two components. */
|
|
116
|
+
addStructuralEdge(edge: StructuralEdge): void;
|
|
112
117
|
/** One-shot batch sync of all current page nodes to the backend. */
|
|
113
118
|
syncOnce(): void;
|
|
114
119
|
snapshot(): GraphSnapshot;
|
|
@@ -183,11 +188,30 @@ declare function readSessionCookie(cookies: {
|
|
|
183
188
|
value: string;
|
|
184
189
|
} | undefined;
|
|
185
190
|
}): string | null;
|
|
191
|
+
type DecideResult = {
|
|
192
|
+
layoutOrder: string[];
|
|
193
|
+
assignments: Record<string, string>;
|
|
194
|
+
persona: string;
|
|
195
|
+
confidence: number;
|
|
196
|
+
};
|
|
197
|
+
/**
|
|
198
|
+
* Single-roundtrip SSR call returning layout order + all component assignments.
|
|
199
|
+
* Falls back to default section order + empty assignments if the API is unavailable.
|
|
200
|
+
* Use instead of `preloadAssignments` when the page declares a `sections` array.
|
|
201
|
+
*/
|
|
202
|
+
declare function preloadDecisions(params: {
|
|
203
|
+
sections: string[];
|
|
204
|
+
components: Array<{
|
|
205
|
+
id: string;
|
|
206
|
+
variantIds?: string[];
|
|
207
|
+
}>;
|
|
208
|
+
}, sessionId: string, config: ServerAssignConfig): Promise<DecideResult>;
|
|
186
209
|
|
|
187
210
|
type SentientConfig = {
|
|
188
211
|
apiKey: string;
|
|
189
212
|
context: 'landing' | 'ecommerce' | 'saas' | 'marketplace';
|
|
190
|
-
|
|
213
|
+
/** @internal — not exposed to users; defaults to the hosted SentientUI API. */
|
|
214
|
+
ingestUrl?: string;
|
|
191
215
|
debug?: boolean;
|
|
192
216
|
/**
|
|
193
217
|
* Pre-seeded assignments from `preloadAssignments()` (SSR).
|
|
@@ -206,13 +230,17 @@ type SentientConfig = {
|
|
|
206
230
|
* the user grants or revokes consent mid-session.
|
|
207
231
|
*/
|
|
208
232
|
consent?: boolean;
|
|
233
|
+
userId?: string;
|
|
209
234
|
};
|
|
210
235
|
type AssignResult = {
|
|
211
236
|
variantId: string;
|
|
212
237
|
assignmentTtlMs: number;
|
|
238
|
+
content?: string;
|
|
213
239
|
};
|
|
214
240
|
type SentientClient = {
|
|
215
241
|
track(event: Omit<SentientEvent, 'id' | 'sessionId' | 'timestamp' | 'timeInSession'>): void;
|
|
242
|
+
goal(name: string, metadata?: Record<string, unknown>): void;
|
|
243
|
+
identify(userId: string): void;
|
|
216
244
|
getAssignment(componentId: string, segment: string): Assignment | null;
|
|
217
245
|
/** Server-side variant assignment. Caches the result locally per (component, segment). */
|
|
218
246
|
assign(componentId: string, variantIds?: string[]): Promise<AssignResult | null>;
|
|
@@ -225,4 +253,4 @@ type SentientClient = {
|
|
|
225
253
|
*/
|
|
226
254
|
declare function init(config: SentientConfig): SentientClient;
|
|
227
255
|
|
|
228
|
-
export { type AssignResult, type Assignment, type AssignmentCache, type ContentAddedEvent, type DOMScanner, type EventQueue, type EventType, type GraphClient, type GraphConfig, type GraphSnapshot, type PageNode, type QueueConfig, type ScanResult, type ScannedNode, type SentientClient, type SentientConfig, type SentientEvent, type ServerAssignConfig, type ServerAssignments, type SessionConfig, type SessionManager,
|
|
256
|
+
export { type AssignResult, type Assignment, type AssignmentCache, type ContentAddedEvent, type DOMScanner, type DecideResult, type EventQueue, type EventType, type GraphClient, type GraphConfig, type GraphSnapshot, type PageNode, type QueueConfig, type ScanResult, type ScannedNode, type SentientClient, type SentientConfig, type SentientEvent, type ServerAssignConfig, type ServerAssignments, type SessionConfig, type SessionManager, deriveSessionSegment, detectDeviceClass, detectTimeOfDay, detectTrafficSource, init, preloadAssignments, preloadDecisions, readSessionCookie, referrerDomainFromReferer };
|
package/dist/index.d.ts
CHANGED
|
@@ -63,12 +63,20 @@ type ScannedNode = {
|
|
|
63
63
|
reactComponentName?: string;
|
|
64
64
|
dataAttributes: Record<string, string>;
|
|
65
65
|
};
|
|
66
|
+
type StructuralEdge$1 = {
|
|
67
|
+
fromComponentId: string;
|
|
68
|
+
toComponentId: string;
|
|
69
|
+
/** 0.6 for direct parent → child, 0.3 for sibling (both directions emitted). */
|
|
70
|
+
weight: number;
|
|
71
|
+
};
|
|
66
72
|
type ScanResult = {
|
|
67
73
|
nodes: ScannedNode[];
|
|
74
|
+
edges: StructuralEdge$1[];
|
|
68
75
|
scannedAt: number;
|
|
69
76
|
};
|
|
70
77
|
type ContentAddedEvent = {
|
|
71
78
|
nodes: ScannedNode[];
|
|
79
|
+
edges: StructuralEdge$1[];
|
|
72
80
|
addedAt: number;
|
|
73
81
|
};
|
|
74
82
|
type DOMScanner = {
|
|
@@ -87,16 +95,8 @@ type PageNode = {
|
|
|
87
95
|
prominenceScore: number;
|
|
88
96
|
depth: number;
|
|
89
97
|
};
|
|
90
|
-
type UserEdge = {
|
|
91
|
-
componentId: string;
|
|
92
|
-
attentionWeight: number;
|
|
93
|
-
interactionCount: number;
|
|
94
|
-
dwellTime: number;
|
|
95
|
-
lastUpdated: number;
|
|
96
|
-
};
|
|
97
98
|
type GraphSnapshot = {
|
|
98
99
|
pageNodes: PageNode[];
|
|
99
|
-
userEdges: UserEdge[];
|
|
100
100
|
capturedAt: number;
|
|
101
101
|
};
|
|
102
102
|
type GraphConfig = {
|
|
@@ -105,10 +105,15 @@ type GraphConfig = {
|
|
|
105
105
|
projectId?: string;
|
|
106
106
|
sessionId?: string;
|
|
107
107
|
};
|
|
108
|
+
type StructuralEdge = {
|
|
109
|
+
fromComponentId: string;
|
|
110
|
+
toComponentId: string;
|
|
111
|
+
weight: number;
|
|
112
|
+
};
|
|
108
113
|
type GraphClient = {
|
|
109
114
|
addPageNode(node: PageNode): void;
|
|
110
|
-
|
|
111
|
-
|
|
115
|
+
/** Record a DOM-derived parent/child or sibling relationship between two components. */
|
|
116
|
+
addStructuralEdge(edge: StructuralEdge): void;
|
|
112
117
|
/** One-shot batch sync of all current page nodes to the backend. */
|
|
113
118
|
syncOnce(): void;
|
|
114
119
|
snapshot(): GraphSnapshot;
|
|
@@ -183,11 +188,30 @@ declare function readSessionCookie(cookies: {
|
|
|
183
188
|
value: string;
|
|
184
189
|
} | undefined;
|
|
185
190
|
}): string | null;
|
|
191
|
+
type DecideResult = {
|
|
192
|
+
layoutOrder: string[];
|
|
193
|
+
assignments: Record<string, string>;
|
|
194
|
+
persona: string;
|
|
195
|
+
confidence: number;
|
|
196
|
+
};
|
|
197
|
+
/**
|
|
198
|
+
* Single-roundtrip SSR call returning layout order + all component assignments.
|
|
199
|
+
* Falls back to default section order + empty assignments if the API is unavailable.
|
|
200
|
+
* Use instead of `preloadAssignments` when the page declares a `sections` array.
|
|
201
|
+
*/
|
|
202
|
+
declare function preloadDecisions(params: {
|
|
203
|
+
sections: string[];
|
|
204
|
+
components: Array<{
|
|
205
|
+
id: string;
|
|
206
|
+
variantIds?: string[];
|
|
207
|
+
}>;
|
|
208
|
+
}, sessionId: string, config: ServerAssignConfig): Promise<DecideResult>;
|
|
186
209
|
|
|
187
210
|
type SentientConfig = {
|
|
188
211
|
apiKey: string;
|
|
189
212
|
context: 'landing' | 'ecommerce' | 'saas' | 'marketplace';
|
|
190
|
-
|
|
213
|
+
/** @internal — not exposed to users; defaults to the hosted SentientUI API. */
|
|
214
|
+
ingestUrl?: string;
|
|
191
215
|
debug?: boolean;
|
|
192
216
|
/**
|
|
193
217
|
* Pre-seeded assignments from `preloadAssignments()` (SSR).
|
|
@@ -206,13 +230,17 @@ type SentientConfig = {
|
|
|
206
230
|
* the user grants or revokes consent mid-session.
|
|
207
231
|
*/
|
|
208
232
|
consent?: boolean;
|
|
233
|
+
userId?: string;
|
|
209
234
|
};
|
|
210
235
|
type AssignResult = {
|
|
211
236
|
variantId: string;
|
|
212
237
|
assignmentTtlMs: number;
|
|
238
|
+
content?: string;
|
|
213
239
|
};
|
|
214
240
|
type SentientClient = {
|
|
215
241
|
track(event: Omit<SentientEvent, 'id' | 'sessionId' | 'timestamp' | 'timeInSession'>): void;
|
|
242
|
+
goal(name: string, metadata?: Record<string, unknown>): void;
|
|
243
|
+
identify(userId: string): void;
|
|
216
244
|
getAssignment(componentId: string, segment: string): Assignment | null;
|
|
217
245
|
/** Server-side variant assignment. Caches the result locally per (component, segment). */
|
|
218
246
|
assign(componentId: string, variantIds?: string[]): Promise<AssignResult | null>;
|
|
@@ -225,4 +253,4 @@ type SentientClient = {
|
|
|
225
253
|
*/
|
|
226
254
|
declare function init(config: SentientConfig): SentientClient;
|
|
227
255
|
|
|
228
|
-
export { type AssignResult, type Assignment, type AssignmentCache, type ContentAddedEvent, type DOMScanner, type EventQueue, type EventType, type GraphClient, type GraphConfig, type GraphSnapshot, type PageNode, type QueueConfig, type ScanResult, type ScannedNode, type SentientClient, type SentientConfig, type SentientEvent, type ServerAssignConfig, type ServerAssignments, type SessionConfig, type SessionManager,
|
|
256
|
+
export { type AssignResult, type Assignment, type AssignmentCache, type ContentAddedEvent, type DOMScanner, type DecideResult, type EventQueue, type EventType, type GraphClient, type GraphConfig, type GraphSnapshot, type PageNode, type QueueConfig, type ScanResult, type ScannedNode, type SentientClient, type SentientConfig, type SentientEvent, type ServerAssignConfig, type ServerAssignments, type SessionConfig, type SessionManager, deriveSessionSegment, detectDeviceClass, detectTimeOfDay, detectTrafficSource, init, preloadAssignments, preloadDecisions, readSessionCookie, referrerDomainFromReferer };
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var $=Object.defineProperty,te=Object.defineProperties,ne=Object.getOwnPropertyDescriptor,re=Object.getOwnPropertyDescriptors,se=Object.getOwnPropertyNames,z=Object.getOwnPropertySymbols;var j=Object.prototype.hasOwnProperty,ie=Object.prototype.propertyIsEnumerable;var J=(e,t,n)=>t in e?$(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,W=(e,t)=>{for(var n in t||(t={}))j.call(t,n)&&J(e,n,t[n]);if(z)for(var n of z(t))ie.call(t,n)&&J(e,n,t[n]);return e},Y=(e,t)=>te(e,re(t));var oe=(e,t)=>{for(var n in t)$(e,n,{get:t[n],enumerable:!0})},ae=(e,t,n,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of se(t))!j.call(e,r)&&r!==n&&$(e,r,{get:()=>t[r],enumerable:!(i=ne(t,r))||i.enumerable});return e};var ce=e=>ae($({},"__esModule",{value:!0}),e);var De={};oe(De,{deriveSessionSegment:()=>H,detectDeviceClass:()=>D,detectTimeOfDay:()=>O,detectTrafficSource:()=>T,init:()=>Ce,preloadAssignments:()=>Z,readSessionCookie:()=>ee,referrerDomainFromReferer:()=>U});module.exports=ce(De);var ue="_snt_uid";var b="_snt_uid";function de(){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 le(e){try{let t=document.cookie.match(new RegExp(`(?:^|; )${e}=([^;]*)`));return t?decodeURIComponent(t[1]):null}catch(t){return null}}function ge(e,t,n){try{document.cookie=`${e}=${encodeURIComponent(t)}; max-age=${n}; SameSite=strict; path=/`}catch(i){}}function me(e){try{return localStorage.getItem(e)}catch(t){return null}}function fe(e,t){try{return localStorage.setItem(e,t),!0}catch(n){return!1}}function pe(e){try{return sessionStorage.getItem(e)}catch(t){return null}}function ye(e,t){try{return sessionStorage.setItem(e,t),!0}catch(n){return!1}}function Se(e){try{sessionStorage.removeItem(e)}catch(t){}}function he(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 ve(e){try{localStorage.removeItem(e)}catch(t){}}function Ie(e){try{document.cookie=`${e}=; max-age=0; SameSite=strict; path=/`}catch(t){}}var Ee={getSessionId:()=>null,isEphemeral:()=>!1,destroy:()=>{}};function q(e){var m,d,p,I,y;if(typeof window=="undefined")return Ee;let t=(m=e==null?void 0:e.cookieName)!=null?m:ue,i=((d=e==null?void 0:e.cookieTTLDays)!=null?d:365)*24*60*60,r=(y=(I=(p=le(t))!=null?p:me(b))!=null?I:pe(b))!=null?y:de();ge(t,r,i);let a=fe(b,r),s=he(t),o=a?!1:ye(b,r),u=!a&&!s&&!o;return{getSessionId:()=>r,isEphemeral:()=>u,destroy:()=>{r=null,Ie(t),ve(b),Se(b)}}}var L="_snt_retry";var we={push:()=>{},flush:()=>{},destroy:()=>{}};function Ae(e){try{let t=localStorage.getItem(L);if(!t)return[];let n=JSON.parse(t);return Array.isArray(n)?(localStorage.removeItem(L),n.slice(-e)):[]}catch(t){return[]}}function B(e,t){try{let i=[...(()=>{try{let r=localStorage.getItem(L);if(!r)return[];let a=JSON.parse(r);return Array.isArray(a)?a:[]}catch(r){return[]}})(),...e].slice(-t);localStorage.setItem(L,JSON.stringify(i))}catch(n){}}function V(e){var A,x,F;if(typeof window=="undefined")return we;let t=(A=e.flushIntervalMs)!=null?A:5e3,n=(x=e.maxBatchSize)!=null?x:20,i=(F=e.maxRetrySize)!=null?F:100,r=e.ingestUrl,a=e.apiKey,s=[],o=new Set,u=[],m=c=>{for(let l of c)o.has(l)||(o.add(l),u.push(l));for(;u.length>500;){let l=u.shift();l&&o.delete(l)}},d=new Set,p=c=>{o.has(c.id)||d.has(c.id)||(d.add(c.id),s.push(c))},I=Ae(i);for(let c of I)p(c);let y=0,S=0,R=c=>{if(c.length===0)return;let l=JSON.stringify(c),_=c.map(w=>w.id),E;try{E=fetch(r,{method:"POST",keepalive:!0,body:l,headers:{"Content-Type":"application/json",Authorization:`Bearer ${a}`}})}catch(w){B(c,i),S++,y=Date.now()+Math.min(6e4,1e3*2**Math.min(S,6));return}let C=w=>{if(w.ok||w.status>=400&&w.status<500&&w.status!==429){m(_),S=0,y=0;return}B(c,i),S++,y=Date.now()+Math.min(6e4,1e3*2**Math.min(S,6))};E instanceof Promise?E.then(C).catch(()=>{B(c,i),S++,y=Date.now()+Math.min(6e4,1e3*2**Math.min(S,6))}):C(E)},P=c=>{let l=[],_=2;for(let E of c){let C=JSON.stringify(E).length+1;if(l.length>0&&_+C>57344||l.length>=n)break;l.push(E),_+=C}return l},h=()=>{try{if(Date.now()<y)return;for(;s.length>0;){let c=s.filter(_=>!o.has(_.id));if(s.length=0,c.length===0)break;let l=P(c);if(l.length===0)break;l.length<c.length&&s.push(...c.slice(l.length)),R(l)}}catch(c){}},g=!0,f=null;f=setInterval(()=>{g&&h()},t);let v=()=>{document.visibilityState==="hidden"&&h()},k=()=>{h()};return document.addEventListener("visibilitychange",v),window.addEventListener("beforeunload",k),{push(c){p(c),s.length>=n&&h()},flush:h,destroy(){g=!1,f!==null&&(clearInterval(f),f=null),document.removeEventListener("visibilitychange",v),window.removeEventListener("beforeunload",k),h()}}}var K="_snt_asgn_";function M(e,t){return`${e}:${t}`}function _e(e,t){return`${K}${e}_${t}`}function Q(){try{let e=[];for(let t=0;t<localStorage.length;t++){let n=localStorage.key(t);n!=null&&n.startsWith(K)&&e.push(n)}return e}catch(e){return[]}}function X(e=18e5){let t=new Map,n=r=>r.assignedAt+e<Date.now();return typeof window!="undefined"&&(()=>{for(let r of Q())try{let a=localStorage.getItem(r);if(!a)continue;let s=JSON.parse(a);if(n(s)){localStorage.removeItem(r);continue}let o=r.slice(K.length),u=o.lastIndexOf("_");if(u<0)continue;let m=o.slice(0,u),d=o.slice(u+1);t.set(M(m,d),s)}catch(a){}})(),{get(r,a){let s=t.get(M(r,a));return s?n(s)?(t.delete(M(r,a)),null):s:null},set(r,a,s){let o=M(r,a);t.set(o,s);try{localStorage.setItem(_e(r,a),JSON.stringify(s))}catch(u){}},invalidate(r){let a=`${r}:`;for(let s of[...t.keys()])s.startsWith(a)&&t.delete(s);for(let s of Q()){let o=s.slice(K.length),u=o.lastIndexOf("_");if(u<0)continue;if(o.slice(0,u)===r)try{localStorage.removeItem(s)}catch(d){}}},clear(){t.clear();for(let r of Q())try{localStorage.removeItem(r)}catch(a){}}}}function D(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 T(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(r){}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 U(e){if(!e)return null;try{return new URL(e).hostname}catch(t){return null}}function O(e){let t=e.getHours();return t<6?"night":t<12?"morning":t<18?"afternoon":"evening"}function H(e){let t=G("__segment__",e);return`${t.deviceClass}:${t.trafficSource}`}function G(e,t){var a,s,o,u,m,d,p;let n=(s=(a=t==null?void 0:t.userAgent)==null?void 0:a.trim())!=null?s:"",i=(u=(o=t==null?void 0:t.referer)==null?void 0:o.trim())!=null?u:"",r=(m=t==null?void 0:t.now)!=null?m:new Date;return{sessionId:e,ephemeral:!1,utmParams:(d=t==null?void 0:t.utmParams)!=null?d:{},deviceClass:n?D(n):"desktop",trafficSource:i?T(i,t==null?void 0:t.appOrigin):"direct",referrerDomain:U(i),timeOfDay:O(r),dayOfWeek:(p=["sun","mon","tue","wed","thu","fri","sat"][r.getDay()])!=null?p:"sun"}}async function Z(e,t,n){let i={"Content-Type":"application/json",Authorization:`Bearer ${n.apiKey}`};n.origin&&(i.Origin=n.origin);let r=G(t,{userAgent:n.userAgent,referer:n.referer,utmParams:n.utmParams,appOrigin:n.origin});try{await fetch(`${n.baseUrl}/sessions`,{method:"POST",headers:i,body:JSON.stringify(r)})}catch(o){}let a=await Promise.allSettled(e.map(async({id:o,variantIds:u})=>{let m=await fetch(`${n.baseUrl}/assign`,{method:"POST",headers:i,body:JSON.stringify({sessionId:t,componentId:o,variantIds:u})});if(!m.ok)return null;let d=await m.json();return{id:o,variantId:d.variantId}})),s={};for(let o of a)o.status==="fulfilled"&&o.value&&(s[o.value.id]=o.value.variantId);return s}function ee(e){var t,n;return(n=(t=e.get("_snt_uid"))==null?void 0:t.value)!=null?n:null}function be(){try{if(typeof crypto!="undefined"&&typeof crypto.randomUUID=="function")return crypto.randomUUID()}catch(e){}return`evt-${Date.now()}-${Math.random().toString(16).slice(2)}`}var N={track:()=>{},getAssignment:()=>null,assign:()=>Promise.resolve(null),getGraph:()=>({pageNodes:[],userEdges:[],capturedAt:0}),destroy:()=>{}};function ke(){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 xe(e){return e.replace(/\/events\/?$/,"")}function Ce(e){var S,R,P,h;if(typeof window=="undefined"||e.consent===!1)return 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 without ingestUrl. SDK disabled."),N;let t=Date.now(),n=q(),i=X(),r=V({ingestUrl:e.ingestUrl,apiKey:e.apiKey}),a=xe(e.ingestUrl),s={"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`},o=D((S=navigator.userAgent)!=null?S:""),u=typeof window!="undefined"?window.location.origin:void 0,m=T((R=document.referrer)!=null?R:"",u),d=(P=e.sessionSegment)!=null?P:`${o}:${m}`;if(e.initialAssignments)for(let[g,f]of Object.entries(e.initialAssignments))i.set(g,d,{variantId:f,assignedAt:Date.now(),segment:d,confidence:1});let p=Promise.resolve(),I=n.getSessionId();if(I){let g=U((h=document.referrer)!=null?h:""),f={sessionId:I,deviceClass:o,trafficSource:m,referrerDomain:g,utmParams:ke(),timeOfDay:O(new Date),dayOfWeek:["sun","mon","tue","wed","thu","fri","sat"][new Date().getDay()],ephemeral:n.isEphemeral()};try{p=fetch(`${a}/sessions`,{method:"POST",keepalive:!0,body:JSON.stringify(f),headers:s}).then(()=>{}).catch(()=>{})}catch(v){}}e.debug&&(console.log("[sentient] initialized",{context:e.context}),window.__sentient={client:null,queue:r});let y={track(g){let f=n.getSessionId();if(!f)return;let v=Y(W({},g),{id:be(),sessionId:f,timestamp:Date.now(),timeInSession:Date.now()-t});r.push(v),e.debug&&console.log("[sentient] track",v)},getAssignment(g,f){return i.get(g,f)},async assign(g,f){let v=n.getSessionId();if(!v)return null;let k=i.get(g,d);if(k)return{variantId:k.variantId,assignmentTtlMs:0};await p;try{let A=await fetch(`${a}/assign`,{method:"POST",body:JSON.stringify({sessionId:v,componentId:g,variantIds:f}),headers:s});if(!A.ok)return null;let x=await A.json();return i.set(g,d,{variantId:x.variantId,assignedAt:Date.now(),segment:d,confidence:1}),x}catch(A){return null}},getGraph(){return{pageNodes:[],userEdges:[],capturedAt:0}},destroy(){r.destroy(),n.destroy(),e.debug&&console.log("[sentient] destroyed")}};if(e.debug){let g=window;g.__sentient&&(g.__sentient.client=y)}return y}0&&(module.exports={deriveSessionSegment,detectDeviceClass,detectTimeOfDay,detectTrafficSource,init,preloadAssignments,readSessionCookie,referrerDomainFromReferer});
|
|
1
|
+
"use strict";var L=Object.defineProperty,ne=Object.defineProperties,re=Object.getOwnPropertyDescriptor,se=Object.getOwnPropertyDescriptors,ie=Object.getOwnPropertyNames,j=Object.getOwnPropertySymbols;var W=Object.prototype.hasOwnProperty,oe=Object.prototype.propertyIsEnumerable;var z=(e,t,n)=>t in e?L(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,G=(e,t)=>{for(var n in t||(t={}))W.call(t,n)&&z(e,n,t[n]);if(j)for(var n of j(t))oe.call(t,n)&&z(e,n,t[n]);return e},Y=(e,t)=>ne(e,se(t));var ae=(e,t)=>{for(var n in t)L(e,n,{get:t[n],enumerable:!0})},ce=(e,t,n,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of ie(t))!W.call(e,r)&&r!==n&&L(e,r,{get:()=>t[r],enumerable:!(i=re(t,r))||i.enumerable});return e};var de=e=>ce(L({},"__esModule",{value:!0}),e);var Oe={};ae(Oe,{deriveSessionSegment:()=>H,detectDeviceClass:()=>C,detectTimeOfDay:()=>R,detectTrafficSource:()=>O,init:()=>Ce,preloadAssignments:()=>Z,preloadDecisions:()=>te,readSessionCookie:()=>ee,referrerDomainFromReferer:()=>U});module.exports=de(Oe);var ue="_snt_uid";var k="_snt_uid";function le(){try{if(typeof crypto!="undefined"&&typeof crypto.randomUUID=="function")return crypto.randomUUID()}catch(t){}let e=()=>Math.floor(Math.random()*4294967295).toString(16).padStart(8,"0");return`${e()}-${e()}-${e()}-${e()}`}function ge(e){try{let t=document.cookie.match(new RegExp(`(?:^|; )${e}=([^;]*)`));return t?decodeURIComponent(t[1]):null}catch(t){return null}}function me(e,t,n){try{document.cookie=`${e}=${encodeURIComponent(t)}; max-age=${n}; SameSite=strict; path=/`}catch(i){}}function fe(e){try{return localStorage.getItem(e)}catch(t){return null}}function pe(e,t){try{return localStorage.setItem(e,t),!0}catch(n){return!1}}function ye(e){try{return sessionStorage.getItem(e)}catch(t){return null}}function he(e,t){try{return sessionStorage.setItem(e,t),!0}catch(n){return!1}}function Se(e){try{sessionStorage.removeItem(e)}catch(t){}}function ve(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 we(e){try{document.cookie=`${e}=; max-age=0; SameSite=strict; path=/`}catch(t){}}var Ae={getSessionId:()=>null,isEphemeral:()=>!1,destroy:()=>{}};function q(e){var f,m,p,v,h;if(typeof window=="undefined")return Ae;let t=(f=e==null?void 0:e.cookieName)!=null?f:ue,i=((m=e==null?void 0:e.cookieTTLDays)!=null?m:365)*24*60*60,r=(h=(v=(p=ge(t))!=null?p:fe(k))!=null?v:ye(k))!=null?h:le();me(t,r,i);let a=pe(k,r),s=ve(t),o=a?!1:he(k,r),d=!a&&!s&&!o;return{getSessionId:()=>r,isEphemeral:()=>d,destroy:()=>{r=null,we(t),Ie(k),Se(k)}}}var N="_snt_retry";var Ee={push:()=>{},flush:()=>{},destroy:()=>{}};function be(e){try{let t=localStorage.getItem(N);if(!t)return[];let n=JSON.parse(t);return Array.isArray(n)?(localStorage.removeItem(N),n.slice(-e)):[]}catch(t){return[]}}function J(e,t){try{let i=[...(()=>{try{let r=localStorage.getItem(N);if(!r)return[];let a=JSON.parse(r);return Array.isArray(a)?a:[]}catch(r){return[]}})(),...e].slice(-t);localStorage.setItem(N,JSON.stringify(i))}catch(n){}}function V(e){var y,T,b;if(typeof window=="undefined")return Ee;let t=(y=e.flushIntervalMs)!=null?y:5e3,n=(T=e.maxBatchSize)!=null?T:20,i=(b=e.maxRetrySize)!=null?b:100,r=e.ingestUrl,a=e.apiKey,s=[],o=new Set,d=[],f=c=>{for(let g of c)o.has(g)||(o.add(g),d.push(g));for(;d.length>500;){let g=d.shift();g&&o.delete(g)}},m=new Set,p=c=>{o.has(c.id)||m.has(c.id)||(m.add(c.id),s.push(c))},v=be(i);for(let c of v)p(c);let h=0,S=0,P=c=>{if(c.length===0)return;let g=JSON.stringify(c),_=c.map(E=>E.id),A;try{A=fetch(r,{method:"POST",keepalive:!0,body:g,headers:{"Content-Type":"application/json",Authorization:`Bearer ${a}`}})}catch(E){J(c,i),S++,h=Date.now()+Math.min(6e4,1e3*2**Math.min(S,6));return}let x=E=>{if(E.ok||E.status>=400&&E.status<500&&E.status!==429){f(_),S=0,h=0;return}J(c,i),S++,h=Date.now()+Math.min(6e4,1e3*2**Math.min(S,6))};A instanceof Promise?A.then(x).catch(()=>{J(c,i),S++,h=Date.now()+Math.min(6e4,1e3*2**Math.min(S,6))}):x(A)},$=c=>{let g=[],_=2;for(let A of c){let x=JSON.stringify(A).length+1;if(g.length>0&&_+x>57344||g.length>=n)break;g.push(A),_+=x}return g},I=()=>{try{if(Date.now()<h)return;for(;s.length>0;){let c=s.filter(_=>!o.has(_.id));if(s.length=0,c.length===0)break;let g=$(c);if(g.length===0)break;g.length<c.length&&s.push(...c.slice(g.length)),P(g)}}catch(c){}},D=!0,w=null;w=setInterval(()=>{D&&I()},t);let u=()=>{document.visibilityState==="hidden"&&I()},l=()=>{I()};return document.addEventListener("visibilitychange",u),window.addEventListener("beforeunload",l),{push(c){p(c),s.length>=n&&I()},flush:I,destroy(){D=!1,w!==null&&(clearInterval(w),w=null),document.removeEventListener("visibilitychange",u),window.removeEventListener("beforeunload",l),I()}}}var K="_snt_asgn_";function M(e,t){return`${e}:${t}`}function _e(e,t){return`${K}${e}_${t}`}function F(){try{let e=[];for(let t=0;t<localStorage.length;t++){let n=localStorage.key(t);n!=null&&n.startsWith(K)&&e.push(n)}return e}catch(e){return[]}}function X(e=18e5){let t=new Map,n=r=>r.assignedAt+e<Date.now();return typeof window!="undefined"&&(()=>{for(let r of F())try{let a=localStorage.getItem(r);if(!a)continue;let s=JSON.parse(a);if(n(s)){localStorage.removeItem(r);continue}let o=r.slice(K.length),d=o.lastIndexOf("_");if(d<0)continue;let f=o.slice(0,d),m=o.slice(d+1);t.set(M(f,m),s)}catch(a){}})(),{get(r,a){let s=t.get(M(r,a));return s?n(s)?(t.delete(M(r,a)),null):s:null},set(r,a,s){let o=M(r,a);t.set(o,s);try{localStorage.setItem(_e(r,a),JSON.stringify(s))}catch(d){}},invalidate(r){let a=`${r}:`;for(let s of[...t.keys()])s.startsWith(a)&&t.delete(s);for(let s of F()){let o=s.slice(K.length),d=o.lastIndexOf("_");if(d<0)continue;if(o.slice(0,d)===r)try{localStorage.removeItem(s)}catch(m){}}},clear(){t.clear();for(let r of F())try{localStorage.removeItem(r)}catch(a){}}}}function C(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 O(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(r){}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 U(e){if(!e)return null;try{return new URL(e).hostname}catch(t){return null}}function R(e){let t=e.getHours();return t<6?"night":t<12?"morning":t<18?"afternoon":"evening"}function H(e){let t=B("__segment__",e);return`${t.deviceClass}:${t.trafficSource}`}function B(e,t){var a,s,o,d,f,m,p;let n=(s=(a=t==null?void 0:t.userAgent)==null?void 0:a.trim())!=null?s:"",i=(d=(o=t==null?void 0:t.referer)==null?void 0:o.trim())!=null?d:"",r=(f=t==null?void 0:t.now)!=null?f:new Date;return{sessionId:e,ephemeral:!1,utmParams:(m=t==null?void 0:t.utmParams)!=null?m:{},deviceClass:n?C(n):"desktop",trafficSource:i?O(i,t==null?void 0:t.appOrigin):"direct",referrerDomain:U(i),timeOfDay:R(r),dayOfWeek:(p=["sun","mon","tue","wed","thu","fri","sat"][r.getDay()])!=null?p:"sun"}}async function Z(e,t,n){let i={"Content-Type":"application/json",Authorization:`Bearer ${n.apiKey}`};n.origin&&(i.Origin=n.origin);let r=B(t,{userAgent:n.userAgent,referer:n.referer,utmParams:n.utmParams,appOrigin:n.origin});try{(await fetch(`${n.baseUrl}/sessions`,{method:"POST",headers:i,body:JSON.stringify(r)})).status===402&&console.warn("[SentientUI] Session limit exceeded for this project. The bandit will stop learning until the limit resets. Upgrade at sentientui.dev/pricing")}catch(o){}let a=await Promise.allSettled(e.map(async({id:o,variantIds:d})=>{let f=await fetch(`${n.baseUrl}/assign`,{method:"POST",headers:i,body:JSON.stringify({sessionId:t,componentId:o,variantIds:d})});if(!f.ok)return null;let m=await f.json();return{id:o,variantId:m.variantId}})),s={};for(let o of a)o.status==="fulfilled"&&o.value&&(s[o.value.id]=o.value.variantId);return s}function ee(e){var t,n;return(n=(t=e.get("_snt_uid"))==null?void 0:t.value)!=null?n:null}async function te(e,t,n){let i={layoutOrder:e.sections,assignments:{},persona:"unknown",confidence:0},r={"Content-Type":"application/json",Authorization:`Bearer ${n.apiKey}`};n.origin&&(r.Origin=n.origin);let a=B(t,{userAgent:n.userAgent,referer:n.referer,utmParams:n.utmParams,appOrigin:n.origin});try{await fetch(`${n.baseUrl}/sessions`,{method:"POST",headers:r,body:JSON.stringify(a)})}catch(s){}try{let s=await fetch(`${n.baseUrl}/decide`,{method:"POST",headers:r,body:JSON.stringify({sessionId:t,sections:e.sections.map(o=>({id:o})),components:e.components})});return s.ok?await s.json():i}catch(s){return i}}var ke="https://sentient-api.fly.dev/v1/events";function De(){try{if(typeof crypto!="undefined"&&typeof crypto.randomUUID=="function")return crypto.randomUUID()}catch(e){}return`evt-${Date.now()}-${Math.random().toString(16).slice(2)}`}var Q={track:()=>{},goal:()=>{},identify:()=>{},getAssignment:()=>null,assign:()=>Promise.resolve(null),getGraph:()=>({pageNodes:[],capturedAt:0}),destroy:()=>{}};function Te(){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 xe(e){return e.replace(/\/events\/?$/,"")}function Ce(e){var P,$,I,D,w;if(typeof window=="undefined"||e.consent===!1)return Q;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."),Q;if(e.ingestUrl==="")return console.warn("[sentient] init() called with an empty ingestUrl. SDK disabled."),Q;let t=(P=e.ingestUrl)!=null?P:ke,n=Date.now(),i=q(),r=X(),a=V({ingestUrl:t,apiKey:e.apiKey}),s=xe(t),o={"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`},d=C(($=navigator.userAgent)!=null?$:""),f=typeof window!="undefined"?window.location.origin:void 0,m=O((I=document.referrer)!=null?I:"",f),p=(D=e.sessionSegment)!=null?D:`${d}:${m}`;if(e.initialAssignments)for(let[u,l]of Object.entries(e.initialAssignments))r.set(u,p,{variantId:l,assignedAt:Date.now(),segment:p,confidence:1});let v=Promise.resolve(),h=i.getSessionId();if(h){let u=U((w=document.referrer)!=null?w:""),l=G({sessionId:h,deviceClass:d,trafficSource:m,referrerDomain:u,utmParams:Te(),timeOfDay:R(new Date),dayOfWeek:["sun","mon","tue","wed","thu","fri","sat"][new Date().getDay()],ephemeral:i.isEphemeral()},e.userId?{userId:e.userId}:{});try{v=fetch(`${s}/sessions`,{method:"POST",keepalive:!0,body:JSON.stringify(l),headers:o}).then(y=>{y.status===402&&console.warn("[SentientUI] Session limit exceeded for this project. The bandit will stop learning until the limit resets. Upgrade at sentientui.dev/pricing")}).catch(()=>{})}catch(y){}}e.debug&&(console.log("[sentient] initialized",{context:e.context}),window.__sentient={client:null,queue:a});let S={goal(u,l={}){let y=i.getSessionId();y&&v.then(()=>{fetch(`${s}/goals`,{method:"POST",keepalive:!0,body:JSON.stringify({sessionId:y,name:u,metadata:l}),headers:o}).catch(()=>{})})},identify(u){let l=i.getSessionId();l&&v.then(()=>{fetch(`${s}/sessions`,{method:"POST",keepalive:!0,body:JSON.stringify({sessionId:l,userId:u,ephemeral:i.isEphemeral()}),headers:o}).catch(()=>{})})},track(u){let l=i.getSessionId();if(!l)return;let y=Y(G({},u),{id:De(),sessionId:l,timestamp:Date.now(),timeInSession:Date.now()-n});a.push(y),e.debug&&console.log("[sentient] track",y)},getAssignment(u,l){return r.get(u,l)},async assign(u,l){let y=i.getSessionId();if(!y)return null;let T=r.get(u,p);if(T)return{variantId:T.variantId,assignmentTtlMs:0};await v;try{let b=await fetch(`${s}/assign`,{method:"POST",body:JSON.stringify({sessionId:y,componentId:u,variantIds:l}),headers:o});if(!b.ok)return null;let c=await b.json();return r.set(u,p,{variantId:c.variantId,assignedAt:Date.now(),segment:p,confidence:1}),c}catch(b){return null}},getGraph(){return{pageNodes:[],capturedAt:0}},destroy(){a.destroy(),i.destroy(),e.debug&&console.log("[sentient] destroyed")}};if(e.debug){let u=window;u.__sentient&&(u.__sentient.client=S)}return S}0&&(module.exports={deriveSessionSegment,detectDeviceClass,detectTimeOfDay,detectTrafficSource,init,preloadAssignments,preloadDecisions,readSessionCookie,referrerDomainFromReferer});
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{c as a,d as b,e as c,f as d,g as e,h as f,i as g,j as h}from"./chunk-
|
|
1
|
+
import{c as a,d as b,e as c,f as d,g as e,h as f,i as g,j as h,k as i}from"./chunk-HWKW5O3R.mjs";export{e as deriveSessionSegment,a as detectDeviceClass,d as detectTimeOfDay,b as detectTrafficSource,i as init,f as preloadAssignments,h as preloadDecisions,g as readSessionCookie,c as referrerDomainFromReferer};
|
package/package.json
CHANGED
|
@@ -1,37 +1,39 @@
|
|
|
1
|
-
{
|
|
2
|
-
"name": "@sentientui/core",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"private": false,
|
|
5
|
-
"type": "module",
|
|
6
|
-
"main": "./dist/index.js",
|
|
7
|
-
"module": "./dist/index.mjs",
|
|
8
|
-
"types": "./dist/index.d.ts",
|
|
9
|
-
"exports": {
|
|
10
|
-
".": {
|
|
11
|
-
"types": "./dist/index.d.ts",
|
|
12
|
-
"import": "./dist/index.mjs",
|
|
13
|
-
"require": "./dist/index.js"
|
|
14
|
-
},
|
|
15
|
-
"./graph": {
|
|
16
|
-
"types": "./dist/index-graph.d.ts",
|
|
17
|
-
"import": "./dist/index-graph.mjs",
|
|
18
|
-
"require": "./dist/index-graph.js"
|
|
19
|
-
}
|
|
20
|
-
},
|
|
21
|
-
"files": [
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
"
|
|
26
|
-
"
|
|
27
|
-
"
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
"
|
|
33
|
-
"
|
|
34
|
-
"
|
|
35
|
-
"
|
|
36
|
-
|
|
37
|
-
|
|
1
|
+
{
|
|
2
|
+
"name": "@sentientui/core",
|
|
3
|
+
"version": "0.3.0",
|
|
4
|
+
"private": false,
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "./dist/index.js",
|
|
7
|
+
"module": "./dist/index.mjs",
|
|
8
|
+
"types": "./dist/index.d.ts",
|
|
9
|
+
"exports": {
|
|
10
|
+
".": {
|
|
11
|
+
"types": "./dist/index.d.ts",
|
|
12
|
+
"import": "./dist/index.mjs",
|
|
13
|
+
"require": "./dist/index.js"
|
|
14
|
+
},
|
|
15
|
+
"./graph": {
|
|
16
|
+
"types": "./dist/index-graph.d.ts",
|
|
17
|
+
"import": "./dist/index-graph.mjs",
|
|
18
|
+
"require": "./dist/index-graph.js"
|
|
19
|
+
}
|
|
20
|
+
},
|
|
21
|
+
"files": [
|
|
22
|
+
"dist"
|
|
23
|
+
],
|
|
24
|
+
"scripts": {
|
|
25
|
+
"build": "tsup",
|
|
26
|
+
"test": "vitest run",
|
|
27
|
+
"typecheck": "tsc --noEmit",
|
|
28
|
+
"size-check": "tsx scripts/size-check.ts",
|
|
29
|
+
"lint": "eslint src"
|
|
30
|
+
},
|
|
31
|
+
"devDependencies": {
|
|
32
|
+
"@types/node": "^22.10.2",
|
|
33
|
+
"jsdom": "^25.0.1",
|
|
34
|
+
"tsup": "^8.3.5",
|
|
35
|
+
"tsx": "^4.19.2",
|
|
36
|
+
"typescript": "^5.7.2",
|
|
37
|
+
"vitest": "^2.1.8"
|
|
38
|
+
}
|
|
39
|
+
}
|
package/dist/chunk-2K7NAMTI.mjs
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
var V=Object.defineProperty,X=Object.defineProperties;var H=Object.getOwnPropertyDescriptors;var F=Object.getOwnPropertySymbols;var Z=Object.prototype.hasOwnProperty,ee=Object.prototype.propertyIsEnumerable;var z=(e,t,n)=>t in e?V(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,J=(e,t)=>{for(var n in t||(t={}))Z.call(t,n)&&z(e,n,t[n]);if(F)for(var n of F(t))ee.call(t,n)&&z(e,n,t[n]);return e},j=(e,t)=>X(e,H(t));var te="_snt_uid";var b="_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 re(e){try{let t=document.cookie.match(new RegExp(`(?:^|; )${e}=([^;]*)`));return t?decodeURIComponent(t[1]):null}catch(t){return null}}function se(e,t,n){try{document.cookie=`${e}=${encodeURIComponent(t)}; max-age=${n}; SameSite=strict; path=/`}catch(o){}}function ie(e){try{return localStorage.getItem(e)}catch(t){return null}}function oe(e,t){try{return localStorage.setItem(e,t),!0}catch(n){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(n){return!1}}function ue(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 le(e){try{localStorage.removeItem(e)}catch(t){}}function ge(e){try{document.cookie=`${e}=; max-age=0; SameSite=strict; path=/`}catch(t){}}var me={getSessionId:()=>null,isEphemeral:()=>!1,destroy:()=>{}};function W(e){var m,d,p,I,y;if(typeof window=="undefined")return me;let t=(m=e==null?void 0:e.cookieName)!=null?m:te,o=((d=e==null?void 0:e.cookieTTLDays)!=null?d:365)*24*60*60,r=(y=(I=(p=re(t))!=null?p:ie(b))!=null?I:ae(b))!=null?y:ne();se(t,r,o);let a=oe(b,r),s=de(t),i=a?!1:ce(b,r),u=!a&&!s&&!i;return{getSessionId:()=>r,isEphemeral:()=>u,destroy:()=>{r=null,ge(t),le(b),ue(b)}}}var U="_snt_retry";var fe={push:()=>{},flush:()=>{},destroy:()=>{}};function pe(e){try{let t=localStorage.getItem(U);if(!t)return[];let n=JSON.parse(t);return Array.isArray(n)?(localStorage.removeItem(U),n.slice(-e)):[]}catch(t){return[]}}function N(e,t){try{let o=[...(()=>{try{let r=localStorage.getItem(U);if(!r)return[];let a=JSON.parse(r);return Array.isArray(a)?a:[]}catch(r){return[]}})(),...e].slice(-t);localStorage.setItem(U,JSON.stringify(o))}catch(n){}}function Y(e){var A,x,G;if(typeof window=="undefined")return fe;let t=(A=e.flushIntervalMs)!=null?A:5e3,n=(x=e.maxBatchSize)!=null?x:20,o=(G=e.maxRetrySize)!=null?G:100,r=e.ingestUrl,a=e.apiKey,s=[],i=new Set,u=[],m=c=>{for(let l of c)i.has(l)||(i.add(l),u.push(l));for(;u.length>500;){let l=u.shift();l&&i.delete(l)}},d=new Set,p=c=>{i.has(c.id)||d.has(c.id)||(d.add(c.id),s.push(c))},I=pe(o);for(let c of I)p(c);let y=0,S=0,D=c=>{if(c.length===0)return;let l=JSON.stringify(c),_=c.map(w=>w.id),E;try{E=fetch(r,{method:"POST",keepalive:!0,body:l,headers:{"Content-Type":"application/json",Authorization:`Bearer ${a}`}})}catch(w){N(c,o),S++,y=Date.now()+Math.min(6e4,1e3*2**Math.min(S,6));return}let C=w=>{if(w.ok||w.status>=400&&w.status<500&&w.status!==429){m(_),S=0,y=0;return}N(c,o),S++,y=Date.now()+Math.min(6e4,1e3*2**Math.min(S,6))};E instanceof Promise?E.then(C).catch(()=>{N(c,o),S++,y=Date.now()+Math.min(6e4,1e3*2**Math.min(S,6))}):C(E)},T=c=>{let l=[],_=2;for(let E of c){let C=JSON.stringify(E).length+1;if(l.length>0&&_+C>57344||l.length>=n)break;l.push(E),_+=C}return l},h=()=>{try{if(Date.now()<y)return;for(;s.length>0;){let c=s.filter(_=>!i.has(_.id));if(s.length=0,c.length===0)break;let l=T(c);if(l.length===0)break;l.length<c.length&&s.push(...c.slice(l.length)),D(l)}}catch(c){}},g=!0,f=null;f=setInterval(()=>{g&&h()},t);let v=()=>{document.visibilityState==="hidden"&&h()},k=()=>{h()};return document.addEventListener("visibilitychange",v),window.addEventListener("beforeunload",k),{push(c){p(c),s.length>=n&&h()},flush:h,destroy(){g=!1,f!==null&&(clearInterval(f),f=null),document.removeEventListener("visibilitychange",v),window.removeEventListener("beforeunload",k),h()}}}var R="_snt_asgn_";function O(e,t){return`${e}:${t}`}function ye(e,t){return`${R}${e}_${t}`}function B(){try{let e=[];for(let t=0;t<localStorage.length;t++){let n=localStorage.key(t);n!=null&&n.startsWith(R)&&e.push(n)}return e}catch(e){return[]}}function q(e=18e5){let t=new Map,n=r=>r.assignedAt+e<Date.now();return typeof window!="undefined"&&(()=>{for(let r of B())try{let a=localStorage.getItem(r);if(!a)continue;let s=JSON.parse(a);if(n(s)){localStorage.removeItem(r);continue}let i=r.slice(R.length),u=i.lastIndexOf("_");if(u<0)continue;let m=i.slice(0,u),d=i.slice(u+1);t.set(O(m,d),s)}catch(a){}})(),{get(r,a){let s=t.get(O(r,a));return s?n(s)?(t.delete(O(r,a)),null):s:null},set(r,a,s){let i=O(r,a);t.set(i,s);try{localStorage.setItem(ye(r,a),JSON.stringify(s))}catch(u){}},invalidate(r){let a=`${r}:`;for(let s of[...t.keys()])s.startsWith(a)&&t.delete(s);for(let s of B()){let i=s.slice(R.length),u=i.lastIndexOf("_");if(u<0)continue;if(i.slice(0,u)===r)try{localStorage.removeItem(s)}catch(d){}}},clear(){t.clear();for(let r of B())try{localStorage.removeItem(r)}catch(a){}}}}function P(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 $(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(r){}let o=n.hostname.toLowerCase();return/(^|\.)(google|bing|duckduckgo|yahoo)\./.test(o)?"search":/(^|\.)(twitter|x\.com|facebook|linkedin|reddit|t\.co)/.test(o)?"social":"referral"}catch(n){return"direct"}}function L(e){if(!e)return null;try{return new URL(e).hostname}catch(t){return null}}function M(e){let t=e.getHours();return t<6?"night":t<12?"morning":t<18?"afternoon":"evening"}function Se(e){let t=Q("__segment__",e);return`${t.deviceClass}:${t.trafficSource}`}function Q(e,t){var a,s,i,u,m,d,p;let n=(s=(a=t==null?void 0:t.userAgent)==null?void 0:a.trim())!=null?s:"",o=(u=(i=t==null?void 0:t.referer)==null?void 0:i.trim())!=null?u:"",r=(m=t==null?void 0:t.now)!=null?m:new Date;return{sessionId:e,ephemeral:!1,utmParams:(d=t==null?void 0:t.utmParams)!=null?d:{},deviceClass:n?P(n):"desktop",trafficSource:o?$(o,t==null?void 0:t.appOrigin):"direct",referrerDomain:L(o),timeOfDay:M(r),dayOfWeek:(p=["sun","mon","tue","wed","thu","fri","sat"][r.getDay()])!=null?p:"sun"}}async function he(e,t,n){let o={"Content-Type":"application/json",Authorization:`Bearer ${n.apiKey}`};n.origin&&(o.Origin=n.origin);let r=Q(t,{userAgent:n.userAgent,referer:n.referer,utmParams:n.utmParams,appOrigin:n.origin});try{await fetch(`${n.baseUrl}/sessions`,{method:"POST",headers:o,body:JSON.stringify(r)})}catch(i){}let a=await Promise.allSettled(e.map(async({id:i,variantIds:u})=>{let m=await fetch(`${n.baseUrl}/assign`,{method:"POST",headers:o,body:JSON.stringify({sessionId:t,componentId:i,variantIds:u})});if(!m.ok)return null;let d=await m.json();return{id:i,variantId:d.variantId}})),s={};for(let i of a)i.status==="fulfilled"&&i.value&&(s[i.value.id]=i.value.variantId);return s}function ve(e){var t,n;return(n=(t=e.get("_snt_uid"))==null?void 0:t.value)!=null?n:null}function Ie(){try{if(typeof crypto!="undefined"&&typeof crypto.randomUUID=="function")return crypto.randomUUID()}catch(e){}return`evt-${Date.now()}-${Math.random().toString(16).slice(2)}`}var K={track:()=>{},getAssignment:()=>null,assign:()=>Promise.resolve(null),getGraph:()=>({pageNodes:[],userEdges:[],capturedAt:0}),destroy:()=>{}};function Ee(){try{let e={},t=new URLSearchParams(window.location.search);for(let[n,o]of t)n.startsWith("utm_")&&(e[n]=o);return e}catch(e){return{}}}function we(e){return e.replace(/\/events\/?$/,"")}function Pe(e){var S,D,T,h;if(typeof window=="undefined"||e.consent===!1)return K;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."),K;if(!e.ingestUrl)return console.warn("[sentient] init() called without ingestUrl. SDK disabled."),K;let t=Date.now(),n=W(),o=q(),r=Y({ingestUrl:e.ingestUrl,apiKey:e.apiKey}),a=we(e.ingestUrl),s={"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`},i=P((S=navigator.userAgent)!=null?S:""),u=typeof window!="undefined"?window.location.origin:void 0,m=$((D=document.referrer)!=null?D:"",u),d=(T=e.sessionSegment)!=null?T:`${i}:${m}`;if(e.initialAssignments)for(let[g,f]of Object.entries(e.initialAssignments))o.set(g,d,{variantId:f,assignedAt:Date.now(),segment:d,confidence:1});let p=Promise.resolve(),I=n.getSessionId();if(I){let g=L((h=document.referrer)!=null?h:""),f={sessionId:I,deviceClass:i,trafficSource:m,referrerDomain:g,utmParams:Ee(),timeOfDay:M(new Date),dayOfWeek:["sun","mon","tue","wed","thu","fri","sat"][new Date().getDay()],ephemeral:n.isEphemeral()};try{p=fetch(`${a}/sessions`,{method:"POST",keepalive:!0,body:JSON.stringify(f),headers:s}).then(()=>{}).catch(()=>{})}catch(v){}}e.debug&&(console.log("[sentient] initialized",{context:e.context}),window.__sentient={client:null,queue:r});let y={track(g){let f=n.getSessionId();if(!f)return;let v=j(J({},g),{id:Ie(),sessionId:f,timestamp:Date.now(),timeInSession:Date.now()-t});r.push(v),e.debug&&console.log("[sentient] track",v)},getAssignment(g,f){return o.get(g,f)},async assign(g,f){let v=n.getSessionId();if(!v)return null;let k=o.get(g,d);if(k)return{variantId:k.variantId,assignmentTtlMs:0};await p;try{let A=await fetch(`${a}/assign`,{method:"POST",body:JSON.stringify({sessionId:v,componentId:g,variantIds:f}),headers:s});if(!A.ok)return null;let x=await A.json();return o.set(g,d,{variantId:x.variantId,assignedAt:Date.now(),segment:d,confidence:1}),x}catch(A){return null}},getGraph(){return{pageNodes:[],userEdges:[],capturedAt:0}},destroy(){r.destroy(),n.destroy(),e.debug&&console.log("[sentient] destroyed")}};if(e.debug){let g=window;g.__sentient&&(g.__sentient.client=y)}return y}export{J as a,j as b,P as c,$ as d,L as e,M as f,Se as g,he as h,ve as i,Pe as j};
|