@sentientui/core 0.16.2 → 0.16.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunk-SHGSYP75.mjs +2 -0
- package/dist/{chunk-I2QGVQI6.mjs.map → chunk-SHGSYP75.mjs.map} +1 -1
- package/dist/{index-C247KMBw.d.ts → index-CTs3AM9E.d.ts} +3 -1
- package/dist/{index-CZLjrtM4.d.cts → index-DqbtJfra.d.cts} +3 -1
- package/dist/index-engagement.js +1 -1
- package/dist/index-engagement.js.map +1 -1
- package/dist/index-engagement.mjs +1 -1
- package/dist/index-engagement.mjs.map +1 -1
- package/dist/index-graph.d.cts +2 -2
- package/dist/index-graph.d.ts +2 -2
- package/dist/index-graph.mjs +1 -1
- package/dist/index-local.d.cts +1 -1
- package/dist/index-local.d.ts +1 -1
- package/dist/index.d.cts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1 -1
- package/package.json +1 -1
- package/dist/chunk-I2QGVQI6.mjs +0 -2
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var He=Object.create;var oe=Object.defineProperty,ze=Object.defineProperties,Ve=Object.getOwnPropertyDescriptor,qe=Object.getOwnPropertyDescriptors,Xe=Object.getOwnPropertyNames,Oe=Object.getOwnPropertySymbols,Ze=Object.getPrototypeOf,Pe=Object.prototype.hasOwnProperty,et=Object.prototype.propertyIsEnumerable;var Te=(e,t,n)=>t in e?oe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,S=(e,t)=>{for(var n in t||(t={}))Pe.call(t,n)&&Te(e,n,t[n]);if(Oe)for(var n of Oe(t))et.call(t,n)&&Te(e,n,t[n]);return e},F=(e,t)=>ze(e,qe(t));var tt=(e,t)=>{for(var n in t)oe(e,n,{get:t[n],enumerable:!0})},Le=(e,t,n,c)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Xe(t))!Pe.call(e,i)&&i!==n&&oe(e,i,{get:()=>t[i],enumerable:!(c=Ve(t,i))||c.enumerable});return e};var nt=(e,t,n)=>(n=e!=null?He(Ze(e)):{},Le(t||!e||!e.__esModule?oe(n,"default",{value:e,enumerable:!0}):n,e)),ot=e=>Le(oe({},"__esModule",{value:!0}),e);var _t={};tt(_t,{LOCAL_MODE_BANNER:()=>Ie,PROD_KEYLESS_ERROR:()=>Se,SNAPSHOT_STORAGE_KEY_PREFIX:()=>W,agentUaList:()=>Ee,armOfResult:()=>fe,attachMicroSignalDetectors:()=>je,baselineResultFor:()=>Y,baselineSlots:()=>Ge,deriveSessionSegment:()=>Ke,detectDeviceClass:()=>se,detectTimeOfDay:()=>le,detectTrafficSource:()=>ie,grantConsent:()=>It,init:()=>Ye,isDoNotTrackEnabled:()=>Re,matchedAgentToken:()=>xe,readSnapshot:()=>pe,referrerDomainFromReferer:()=>ae,renderPrePaintScript:()=>Be,toWireSlot:()=>ce,uaTokenMatch:()=>re,writeSnapshot:()=>H});module.exports=ot(_t);var rt="_snt_uid";var J="_snt_uid";function st(){try{if(typeof crypto!="undefined"&&typeof crypto.randomUUID=="function")return crypto.randomUUID()}catch(t){}let e=()=>Math.floor(Math.random()*4294967295).toString(16).padStart(8,"0");return`${e()}-${e()}-${e()}-${e()}`}function it(e){try{let t=document.cookie.match(new RegExp(`(?:^|; )${e}=([^;]*)`));return t?decodeURIComponent(t[1]):null}catch(t){return null}}function at(e,t,n){try{document.cookie=`${e}=${encodeURIComponent(t)}; max-age=${n}; SameSite=strict; path=/`}catch(c){}}function lt(e){try{return localStorage.getItem(e)}catch(t){return null}}function ct(e,t){try{return localStorage.setItem(e,t),!0}catch(n){return!1}}function dt(e){try{return sessionStorage.getItem(e)}catch(t){return null}}function ut(e,t){try{return sessionStorage.setItem(e,t),!0}catch(n){return!1}}function gt(e){try{sessionStorage.removeItem(e)}catch(t){}}function ft(e){try{return document.cookie=`${e}_probe=1; max-age=1; SameSite=strict; path=/`,/(?:^|; )_snt_uid_probe=1/.test(document.cookie)||document.cookie.indexOf(`${e}_probe=1`)!==-1}catch(t){return!1}}function pt(e){try{localStorage.removeItem(e)}catch(t){}}function mt(e){try{document.cookie=`${e}=; max-age=0; SameSite=strict; path=/`}catch(t){}}var yt={getSessionId:()=>null,isEphemeral:()=>!1,destroy:()=>{}};function ue(e){var d,g,p,v,E,h;if(typeof window=="undefined")return yt;let t=(d=e==null?void 0:e.cookieName)!=null?d:rt,c=((g=e==null?void 0:e.cookieTTLDays)!=null?g:365)*24*60*60,i=(h=(E=(v=(p=it(t))!=null?p:lt(J))!=null?v:dt(J))!=null?E:e==null?void 0:e.ssrSessionId)!=null?h:st();at(t,i,c);let s=ct(J,i),a=ft(t),o=s?!1:ut(J,i),l=!s&&!a&&!o;return{getSessionId:()=>i,isEphemeral:()=>l,destroy:()=>{i=null,mt(t),pt(J),gt(J)}}}function ve(e){return`_snt_retry_${e.slice(0,12)}`}var St={push:()=>{},flush:()=>{},destroy:()=>{}};function ht(e,t){try{let n=localStorage.getItem(t);if(!n)return[];let c=JSON.parse(n);return Array.isArray(c)?(localStorage.removeItem(t),c.slice(-e)):[]}catch(n){return[]}}function he(e,t,n){try{let i=[...(()=>{try{let s=localStorage.getItem(n);if(!s)return[];let a=JSON.parse(s);return Array.isArray(a)?a:[]}catch(s){return[]}})(),...e].slice(-t);localStorage.setItem(n,JSON.stringify(i))}catch(c){}}function Me(e){var X,Z,ee;if(typeof window=="undefined")return St;let t=(X=e.flushIntervalMs)!=null?X:5e3,n=(Z=e.maxBatchSize)!=null?Z:20,c=(ee=e.maxRetrySize)!=null?ee:100,i=e.ingestUrl,s=e.apiKey,a=ve(s),o=[],l=new Set,d=[],g=f=>{for(let y of f)p.delete(y),!l.has(y)&&(l.add(y),d.push(y));for(;d.length>500;){let y=d.shift();y&&l.delete(y)}},p=new Set,v=f=>{l.has(f.id)||p.has(f.id)||(p.add(f.id),o.push(f))},E=ht(c,a);for(let f of E)v(f);let h=0,R=0,k=f=>{if(f.length===0)return;let y=JSON.stringify(f),I=f.map(r=>r.id),D;try{D=fetch(i,{method:"POST",keepalive:!0,body:y,headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`}})}catch(r){he(f,c,a);for(let u of I)p.delete(u);R++,h=Date.now()+Math.min(6e4,1e3*2**Math.min(R,6));return}let M=r=>{if(r.ok||r.status>=400&&r.status<500&&r.status!==429){g(I),R=0,h=0;return}he(f,c,a);for(let u of I)p.delete(u);R++,h=Date.now()+Math.min(6e4,1e3*2**Math.min(R,6))};D instanceof Promise?D.then(M).catch(()=>{he(f,c,a);for(let r of I)p.delete(r);R++,h=Date.now()+Math.min(6e4,1e3*2**Math.min(R,6))}):M(D)},b=typeof TextEncoder!="undefined"?new TextEncoder:null,de=f=>b?b.encode(f).length:f.length,K=f=>{let y=[],I=2;for(let D of f){let M=de(JSON.stringify(D))+1;if(y.length>0&&I+M>57344||y.length>=n)break;y.push(D),I+=M}return y},P=()=>{try{if(Date.now()<h)return;for(;o.length>0;){let f=o.filter(I=>!l.has(I.id));if(o.length=0,f.length===0)break;let y=K(f);if(y.length===0)break;y.length<f.length&&o.push(...f.slice(y.length)),k(y)}}catch(f){}},A=!0,G=null;G=setInterval(()=>{A&&P()},t);let V=()=>{document.visibilityState==="hidden"&&P()},q=()=>{P()};return document.addEventListener("visibilitychange",V),window.addEventListener("pagehide",q),{push(f){v(f),o.length>=n&&P()},flush:P,destroy(){A=!1,G!==null&&(clearInterval(G),G=null),document.removeEventListener("visibilitychange",V),window.removeEventListener("pagehide",q),P()}}}var we="_snt_asgn_";function ge(e,t){return`${e}:${t}`}function vt(e,t){return`${we}${encodeURIComponent(e)}:${encodeURIComponent(t)}`}function Ne(e){let t=e.slice(we.length),n=t.indexOf(":");if(n<0)return null;try{return{componentId:decodeURIComponent(t.slice(0,n)),segment:decodeURIComponent(t.slice(n+1))}}catch(c){return null}}function be(){try{let e=[];for(let t=0;t<localStorage.length;t++){let n=localStorage.key(t);n!=null&&n.startsWith(we)&&e.push(n)}return e}catch(e){return[]}}function Ue(e=18e5){let t=new Map,n=i=>i.assignedAt+e<Date.now();return typeof window!="undefined"&&(()=>{for(let i of be())try{let s=localStorage.getItem(i);if(!s)continue;let a=JSON.parse(s);if(n(a)){localStorage.removeItem(i);continue}let o=Ne(i);if(!o)continue;t.set(ge(o.componentId,o.segment),a)}catch(s){}})(),{get(i,s){let a=t.get(ge(i,s));return a?n(a)?(t.delete(ge(i,s)),null):a:null},set(i,s,a){let o=ge(i,s);t.set(o,a);try{localStorage.setItem(vt(i,s),JSON.stringify(a))}catch(l){}},invalidate(i){let s=`${i}:`;for(let a of[...t.keys()])a.startsWith(s)&&t.delete(a);for(let a of be()){let o=Ne(a);if((o==null?void 0:o.componentId)===i)try{localStorage.removeItem(a)}catch(l){}}},clear(){t.clear();for(let i of be())try{localStorage.removeItem(i)}catch(s){}}}}var Ee=["GPTBot","ChatGPT-User","OAI-SearchBot","ClaudeBot","Claude-User","Claude-SearchBot","PerplexityBot","Perplexity-User","Google-Extended","Applebot-Extended","Meta-ExternalAgent","Bytespider","CCBot","Amazonbot","cohere-ai","Diffbot"];function re(e){return xe(e)!==null}function xe(e){var n;if(!e)return null;let t=e.toLowerCase();return(n=Ee.find(c=>t.includes(c.toLowerCase())))!=null?n:null}function se(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 ie(e,t){if(!e)return"direct";try{let n=new URL(e);if(t)try{if(new URL(t).host===n.host)return"direct"}catch(i){}let c=n.hostname.toLowerCase();return/(^|\.)(google|bing|duckduckgo|yahoo)\./.test(c)?"search":/(^|\.)(twitter\.com|x\.com|facebook\.com|linkedin\.com|reddit\.com|t\.co)$/.test(c)?"social":"referral"}catch(n){return"direct"}}function ae(e){if(!e)return null;try{return new URL(e).hostname}catch(t){return null}}function le(e){let t=e.getHours();return t<6?"night":t<12?"morning":t<18?"afternoon":"evening"}function Ke(e){let t=bt("__segment__",e);return`${t.deviceClass}:${t.trafficSource}`}function bt(e,t){var s,a,o,l,d,g,p;let n=(a=(s=t==null?void 0:t.userAgent)==null?void 0:s.trim())!=null?a:"",c=(l=(o=t==null?void 0:t.referer)==null?void 0:o.trim())!=null?l:"",i=(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?se(n):"desktop",trafficSource:c?ie(c,t==null?void 0:t.appOrigin):"direct",referrerDomain:ae(c),timeOfDay:le(i),dayOfWeek:(p=["sun","mon","tue","wed","thu","fri","sat"][i.getDay()])!=null?p:"sun",automation:(t==null?void 0:t.webdriver)===!0||re(n)}}var Q=require("@sentientui/policy");function ce(e){return S(S(S({id:e.id},e.arms?{arms:[...e.arms]}:{}),e.dims?{dims:Object.fromEntries(Object.entries(e.dims).map(([t,n])=>[t,[...n]]))}:{}),e.baseline!==void 0?{baseline:e.baseline}:{})}function Y(e){let t=ce(e);return(0,Q.slotResultFor)(t,(0,Q.slotBaselineArm)(t))}function Ge(e){let t={};for(let n of e)t[n.id]=Y(n);return t}function fe(e){return typeof e=="string"?e:(0,Q.canonicalArm)(e)}var W="_snt_snap:",wt=["low","medium","high"];function pe(e){try{let t=localStorage.getItem(W+e);if(!t)return null;let n=JSON.parse(t);return!n||typeof n!="object"||n.v!==1||typeof n.persona!="string"||typeof n.band!="string"||!wt.includes(n.band)||typeof n.slots!="object"||n.slots===null||Array.isArray(n.slots)||!(n.layoutOrder===null||Array.isArray(n.layoutOrder))||typeof n.savedAt!="number"||!(n.slotConfig===void 0||typeof n.slotConfig=="object"&&n.slotConfig!==null&&!Array.isArray(n.slotConfig))?null:n}catch(t){return null}}function H(e,t){try{localStorage.setItem(W+e,JSON.stringify(t))}catch(n){}}function Be(e){return"(function(){try{var r=localStorage.getItem("+JSON.stringify(W+e).replace(/</g,"\\u003c")+');if(!r)return;var s=JSON.parse(r);if(!s||s.v!==1||typeof s.persona!=="string"||typeof s.band!=="string")return;var d=document.documentElement;if(d.hasAttribute("data-sentient-persona"))return;d.setAttribute("data-sentient-persona",s.persona);d.setAttribute("data-sentient-confidence",s.band);}catch(e){}})();'}var _e=require("@sentientui/policy");var ye=require("@sentientui/policy");var Se="[sentient] No API key configured \u2014 nothing is being learned. Set NEXT_PUBLIC_SENTIENT_API_KEY or pass localMode: true for local development.",Ie="[sentient] Local mode \u2014 decisions are simulated on-device and nothing is sent over the network. Add an API key to learn from real traffic.",$e=!1,me=!1;function Et(){var e;try{return(e=new URLSearchParams(window.location.search).get("sentient_persona"))!=null?e:void 0}catch(t){return}}function We(e){var o;let t=ue({ssrSessionId:e.ssrSessionId}),n=(o=t.getSessionId())!=null?o:"local",c=Et(),i=import("@sentientui/core/local").then(l=>{let d=l;return d.LOCAL_ENGINE_AVAILABLE?($e||($e=!0,console.info(Ie)),d):(me||(me=!0,console.error(Se)),null)}).catch(()=>(me||(me=!0,console.error(Se)),null)),s=null;function a(l){let d=document.documentElement;d.dataset.sentientPersona===void 0&&(d.dataset.sentientPersona=l.persona,d.dataset.sentientConfidence=(0,ye.confidenceBand)(l.confidence))}return{isLocal:!0,async decide(l){var p,v,E;let d=await i;if(!d)return null;let g=d.createLocalEngine({sessionId:n,forcedPersona:c}).decide(l);return s=F(S({},g),{layoutOrder:(v=(p=g.layoutOrder)!=null?p:s==null?void 0:s.layoutOrder)!=null?v:null,slots:S(S({},(E=s==null?void 0:s.slots)!=null?E:{}),g.slots)}),H(e.apiKey||"local",{v:1,persona:s.persona,band:(0,ye.confidenceBand)(s.confidence),slots:s.slots,layoutOrder:s.layoutOrder,savedAt:Date.now()}),a(g),g},getSlotResult(l){var d,g,p;return(p=(g=s==null?void 0:s.slots[l])!=null?g:(d=e.initialSlots)==null?void 0:d[l])!=null?p:null},getPersona(){return s?{persona:s.persona,confidence:s.confidence,band:(0,ye.confidenceBand)(s.confidence)}:null},async assign(l,d){var v;let g=await i;return!g||!d||d.length===0?d!=null&&d[0]?{variantId:d[0],assignmentTtlMs:0}:null:{variantId:(v=g.createLocalEngine({sessionId:n,forcedPersona:c}).decide({components:[{id:l,variantIds:d}]}).assignments[l])!=null?v:d[0],assignmentTtlMs:0}},track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},getAssignment:()=>null,fetchWeights:()=>Promise.resolve([]),getGraph:()=>({pageNodes:[],capturedAt:0}),dispose:()=>{},destroy:()=>t.destroy()}}function je(e,t,n){let c=[];{let a=!1,o=[],l=()=>{if(a)return;let d=Date.now();for(o.push(d);o.length>0&&d-o[0]>500;)o.shift();o.length>=3&&(a=!0,e("rage_click"))};t.addEventListener("click",l),c.push(()=>t.removeEventListener("click",l))}{let i=!1,s=a=>{if(i||!(a.target instanceof Node)||!t.contains(a.target)&&t!==a.target)return;i=!0;let o=typeof window!="undefined"?window.getSelection():null,l=o?o.toString().length:0;e("text_copy",{selectionLength:l})};document.addEventListener("copy",s),c.push(()=>document.removeEventListener("copy",s))}{let i=!1,s=!1,a=null,o=()=>{a!==null&&(clearTimeout(a),a=null)},l=()=>{i||!s||(o(),a=setTimeout(()=>{!i&&s&&(i=!0,e("scroll_hesitation"))},3e3))},d=()=>{o(),l()},g=v=>{for(let E of v)s=E.intersectionRatio>.3,s?l():o()},p=new IntersectionObserver(g,{threshold:[.3]});p.observe(t),window.addEventListener("scroll",d,{passive:!0}),c.push(()=>{p.disconnect(),window.removeEventListener("scroll",d),o()})}{let i=!1,s=n!=null?n:Date.now(),a=()=>{if(i||document.visibilityState!=="hidden")return;let o=Date.now()-s;o<15e3&&(i=!0,e("tab_loss",{timeOnPage:o}))};document.addEventListener("visibilitychange",a),c.push(()=>document.removeEventListener("visibilitychange",a))}return()=>{for(let i of c)i()}}var Fe="https://api.sentient-ui.com/v1/events",j=new Map,Je=null;function Ce(){try{if(typeof crypto!="undefined"&&typeof crypto.randomUUID=="function")return crypto.randomUUID()}catch(e){}return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})}var z={track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},getAssignment:()=>null,assign:()=>Promise.resolve(null),decide:()=>Promise.resolve(null),getSlotResult:()=>null,getPersona:()=>null,fetchWeights:()=>Promise.resolve([]),getGraph:()=>({pageNodes:[],capturedAt:0}),dispose:()=>{},destroy:()=>{}};function xt(){try{let e={},t=new URLSearchParams(window.location.search);for(let[n,c]of t)n.startsWith("utm_")&&(e[n]=c);return e}catch(e){return{}}}function Qe(e){return e.replace(/\/events\/?$/,"")}function Re(){return typeof navigator!="undefined"&&navigator.globalPrivacyControl===!0?!0:[typeof navigator!="undefined"?navigator.doNotTrack:void 0,typeof window!="undefined"?window.doNotTrack:void 0,typeof navigator!="undefined"?navigator.msDoNotTrack:void 0].some(t=>t==="1"||t==="yes")}function It(e){if(typeof window=="undefined")return;let t=e!=null?e:Je;if(!t){console.warn("[sentient] grantConsent() called before init()");return}let n=j.get(t);if(!n){console.warn("[sentient] grantConsent() called before init()");return}let{config:c,upgrade:i}=n;if(!i||c.respectDoNotTrack!==!1&&Re())return;let s=Ye(F(S({},c),{consent:!0}));i(s),j.set(t,{config:F(S({},c),{consent:!0}),upgrade:null})}function Ct(e){var a;let t=Qe((a=e.ingestUrl)!=null?a:Fe),n={"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`},c={track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},getAssignment:()=>null,fetchWeights:()=>Promise.resolve([]),async assign(o,l,d){try{let g=new URLSearchParams({componentId:o});for(let E of l!=null?l:[])g.append("variantIds[]",E);let p=await fetch(`${t}/winner?${g.toString()}`,{headers:n});return p.ok?{variantId:(await p.json()).variantId,assignmentTtlMs:0}:l!=null&&l[0]?{variantId:l[0],assignmentTtlMs:0}:null}catch(g){return l!=null&&l[0]?{variantId:l[0],assignmentTtlMs:0}:null}},decide:()=>Promise.resolve(null),getSlotResult:()=>null,getPersona:()=>null,getGraph:()=>({pageNodes:[],capturedAt:0}),dispose:()=>{},destroy:()=>{}},i={track:o=>c.track(o),goal:(o,l,d,g)=>c.goal(o,l,d,g),componentGoal:(o,l,d)=>c.componentGoal(o,l,d),identify:o=>c.identify(o),getAssignment:(o,l)=>c.getAssignment(o,l),assign:(o,l,d,g)=>c.assign(o,l,d,g),decide:o=>c.decide(o),getSlotResult:o=>c.getSlotResult(o),getPersona:()=>c.getPersona(),fetchWeights:()=>c.fetchWeights(),getGraph:()=>c.getGraph(),dispose:()=>c.dispose(),destroy:()=>c.destroy()};function s(o){c=o}return{proxy:i,setInner:s}}function Ye(e){var q,X,Z,ee,f,y,I,D,M;if(typeof window=="undefined")return z;Je=e.apiKey;let t=e.respectDoNotTrack!==!1&&Re(),n=e.consent===!1||t,c=typeof e.apiKey=="string"&&e.apiKey.startsWith("pk_");if(e.localMode===!0||!c&&e.localMode!==!1)return n?(j.set(e.apiKey||"local",{config:e,upgrade:null}),z):(j.set(e.apiKey||"local",{config:e,upgrade:null}),We(e));if(n){if(e.preConsentBehavior==="statistical_winner"){if(!e.apiKey||!e.apiKey.startsWith("pk_"))return console.warn("[sentient] init() called with an invalid apiKey \u2014 expected a pk_ public key. SDK disabled."),z;let{proxy:r,setInner:u}=Ct(e);return j.set(e.apiKey,{config:e,upgrade:t?null:u}),r}return j.set(e.apiKey,{config:e,upgrade:null}),z}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."),z;if(e.ingestUrl==="")return console.warn("[sentient] init() called with an empty ingestUrl. SDK disabled."),z;let i=(q=e.ingestUrl)!=null?q:Fe,s=Date.now(),a=ue({ssrSessionId:e.ssrSessionId}),o=Ue(),l=Me({ingestUrl:i,apiKey:e.apiKey}),d=Qe(i),g={"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`},p=se((X=navigator.userAgent)!=null?X:""),v=typeof window!="undefined"?window.location.origin:void 0,E=ie((Z=document.referrer)!=null?Z:"",v),h=(ee=e.sessionSegment)!=null?ee:`${p}:${E}`,R=new Map,k=new Map,b=null,de=r=>{for(let u of r)k.has(u.id)||k.set(u.id,Y(u))};if(e.initialSlots)for(let[r,u]of Object.entries(e.initialSlots))k.set(r,u);let K=pe(e.apiKey);if(K)for(let[r,u]of Object.entries(K.slots))k.has(r)||k.set(r,u);let P={low:.15,medium:.5,high:.85};if(e.initialPersona)b=S({},e.initialPersona);else{let r=document.documentElement.dataset;r.sentientPersona?b={persona:r.sentientPersona,confidence:(y=P[(f=r.sentientConfidence)!=null?f:"low"])!=null?y:.15}:K&&(b={persona:K.persona,confidence:(I=P[K.band])!=null?I:.15})}if(e.initialAssignments)for(let[r,u]of Object.entries(e.initialAssignments))o.set(r,h,{variantId:u,assignedAt:Date.now(),segment:h,confidence:1});let A=Promise.resolve(),G=a.getSessionId();if(G){let r=ae((D=document.referrer)!=null?D:""),u=S(S({sessionId:G,deviceClass:p,trafficSource:E,referrerDomain:r,utmParams:xt(),timeOfDay:le(new Date),dayOfWeek:["sun","mon","tue","wed","thu","fri","sat"][new Date().getDay()],ephemeral:a.isEphemeral(),automation:typeof navigator!="undefined"&&navigator.webdriver===!0||re((M=navigator.userAgent)!=null?M:"")},e.userId?{userId:e.userId}:{}),e.country?{country:e.country}:{});try{A=fetch(`${d}/sessions`,{method:"POST",keepalive:!0,body:JSON.stringify(u),headers:g}).then(m=>{m.status===402&&console.warn("[SentientUI] Session limit exceeded for this project. The bandit will stop learning until the limit resets. Upgrade at sentient-ui.com/pricing")}).catch(()=>{})}catch(m){}}e.debug&&(console.log("[sentient] initialized",{context:e.context}),window.__sentient={client:null,queue:l});let V={goal(r,u={},m=1,O=0){let x=a.getSessionId();if(!x)return;let C=Ce();A.then(()=>{fetch(`${d}/goals`,{method:"POST",keepalive:!0,body:JSON.stringify({sessionId:x,name:r,metadata:u,weight:m,stepIndex:O,goalId:C}),headers:g}).catch(()=>{})})},componentGoal(r,u,m){var T,U,L;let O=a.getSessionId();if(!O)return;let x=o.get(r,h),C=x?null:(T=k.get(r))!=null?T:null;if(!x&&C===null){e.debug&&console.warn(`[sentient] componentGoal("${r}"): no assignment or slot decision yet \u2014 render its <Adaptive>/adaptive hook or call assign()/decide() before recording a goal.`);return}let B=x?x.variantId:fe(C),N={id:Ce(),sessionId:O,projectId:e.apiKey,componentId:r,variantId:B,eventType:"goal_achieved",goalType:u,payload:S({reward:(U=m==null?void 0:m.reward)!=null?U:1},(L=m==null?void 0:m.metadata)!=null?L:{}),timestamp:Date.now(),timeInSession:Date.now()-s};e.debug&&console.log("[sentient] componentGoal",N),A.then(()=>l.push(N))},identify(r){let u=a.getSessionId();u&&A.then(()=>{fetch(`${d}/sessions`,{method:"POST",keepalive:!0,body:JSON.stringify({sessionId:u,userId:r,ephemeral:a.isEphemeral()}),headers:g}).catch(()=>{})})},track(r){let u=a.getSessionId();if(!u)return;let m=F(S({},r),{id:Ce(),sessionId:u,timestamp:Date.now(),timeInSession:Date.now()-s});e.debug&&console.log("[sentient] track",m),A.then(()=>l.push(m))},getAssignment(r,u){return o.get(r,u)},async assign(r,u,m,O){let x=a.getSessionId();if(!x)return null;let C=o.get(r,h);if(C&&(u!=null&&u.length||C.content!==void 0))return{variantId:C.variantId,assignmentTtlMs:0,content:C.content};let B=R.get(r);if(B)return B;let N=(async()=>{await A;try{let T={sessionId:x,componentId:r,variantIds:u};O!==void 0?T.agentDataByVariant=O:m!==void 0&&(T.agentData=m);let U=await fetch(`${d}/assign`,{method:"POST",body:JSON.stringify(T),headers:g});if(!U.ok)return null;let L=await U.json();return o.set(r,h,{variantId:L.variantId,assignedAt:Date.now(),segment:h,confidence:1,content:L.content}),L}catch(T){return null}finally{R.delete(r)}})();return R.set(r,N),N},async decide(r){var O,x,C,B,N,T,U,L,ke,Ae;let u=a.getSessionId();if(!u)return null;let m=(O=r.slots)!=null?O:[];await A;try{let $={sessionId:u};r.sections&&r.sections.length>0&&($.sections=r.sections.map(_=>({id:_}))),$.components=(x=r.components)!=null?x:[],m.length>0&&($.slots=m.map(ce)),r.slotsFrom==="registry"&&($.slotsFrom="registry"),r.v&&($.v=r.v);let De=await fetch(`${d}/decide`,{method:"POST",body:JSON.stringify($),headers:g});if(!De.ok)return de(m),null;let w=await De.json(),te={};for(let _ of m)te[_.id]=(B=(C=w.slots)==null?void 0:C[_.id])!=null?B:Y(_);if(w.slots)for(let[_,ne]of Object.entries(w.slots))_ in te||(te[_]=ne);for(let[_,ne]of Object.entries(te))k.set(_,ne);b={persona:(N=w.persona)!=null?N:"unknown",confidence:(T=w.confidence)!=null?T:0};for(let[_,ne]of Object.entries((U=w.assignments)!=null?U:{}))o.set(_,h,{variantId:ne,assignedAt:Date.now(),segment:h,confidence:1});return H(e.apiKey,S({v:1,persona:b.persona,band:(0,_e.confidenceBand)(b.confidence),slots:Object.fromEntries(k),layoutOrder:(L=w.layoutOrder)!=null?L:null,savedAt:Date.now()},w.slotConfig?{slotConfig:w.slotConfig}:{})),S(S({layoutOrder:(ke=w.layoutOrder)!=null?ke:null,assignments:(Ae=w.assignments)!=null?Ae:{},slots:te,persona:b.persona,confidence:b.confidence},w.slotConfig?{slotConfig:w.slotConfig}:{}),w.goals?{goals:w.goals}:{})}catch($){return de(m),null}},getSlotResult(r){var u;return(u=k.get(r))!=null?u:null},getPersona(){return b?{persona:b.persona,confidence:b.confidence,band:(0,_e.confidenceBand)(b.confidence)}:null},async fetchWeights(){var r;try{let u=await fetch(`${d}/weights`,{headers:g});return u.ok?(r=(await u.json()).components)!=null?r:[]:[]}catch(u){return[]}},getGraph(){return{pageNodes:[],capturedAt:0}},dispose(){l.destroy(),e.debug&&console.log("[sentient] disposed")},destroy(){l.destroy(),a.destroy();try{localStorage.removeItem(W+e.apiKey),localStorage.removeItem(ve(e.apiKey))}catch(r){}e.debug&&console.log("[sentient] destroyed")}};if(j.set(e.apiKey,{config:e,upgrade:null}),e.debug){let r=window;r.__sentient&&(r.__sentient.client=V)}return V}0&&(module.exports={LOCAL_MODE_BANNER,PROD_KEYLESS_ERROR,SNAPSHOT_STORAGE_KEY_PREFIX,agentUaList,armOfResult,attachMicroSignalDetectors,baselineResultFor,baselineSlots,deriveSessionSegment,detectDeviceClass,detectTimeOfDay,detectTrafficSource,grantConsent,init,isDoNotTrackEnabled,matchedAgentToken,readSnapshot,referrerDomainFromReferer,renderPrePaintScript,toWireSlot,uaTokenMatch,writeSnapshot});
|
|
1
|
+
"use strict";var He=Object.create;var oe=Object.defineProperty,ze=Object.defineProperties,Ve=Object.getOwnPropertyDescriptor,qe=Object.getOwnPropertyDescriptors,Xe=Object.getOwnPropertyNames,Oe=Object.getOwnPropertySymbols,Ze=Object.getPrototypeOf,Le=Object.prototype.hasOwnProperty,et=Object.prototype.propertyIsEnumerable;var Te=(e,t,n)=>t in e?oe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,h=(e,t)=>{for(var n in t||(t={}))Le.call(t,n)&&Te(e,n,t[n]);if(Oe)for(var n of Oe(t))et.call(t,n)&&Te(e,n,t[n]);return e},F=(e,t)=>ze(e,qe(t));var tt=(e,t)=>{for(var n in t)oe(e,n,{get:t[n],enumerable:!0})},Pe=(e,t,n,a)=>{if(t&&typeof t=="object"||typeof t=="function")for(let c of Xe(t))!Le.call(e,c)&&c!==n&&oe(e,c,{get:()=>t[c],enumerable:!(a=Ve(t,c))||a.enumerable});return e};var nt=(e,t,n)=>(n=e!=null?He(Ze(e)):{},Pe(t||!e||!e.__esModule?oe(n,"default",{value:e,enumerable:!0}):n,e)),ot=e=>Pe(oe({},"__esModule",{value:!0}),e);var _t={};tt(_t,{LOCAL_MODE_BANNER:()=>Ie,PROD_KEYLESS_ERROR:()=>Se,SNAPSHOT_STORAGE_KEY_PREFIX:()=>W,agentUaList:()=>Ee,armOfResult:()=>fe,attachMicroSignalDetectors:()=>je,baselineResultFor:()=>Y,baselineSlots:()=>Ge,deriveSessionSegment:()=>Ke,detectDeviceClass:()=>se,detectTimeOfDay:()=>le,detectTrafficSource:()=>ie,grantConsent:()=>It,init:()=>Ye,isDoNotTrackEnabled:()=>Re,matchedAgentToken:()=>xe,readSnapshot:()=>pe,referrerDomainFromReferer:()=>ae,renderPrePaintScript:()=>Be,toWireSlot:()=>ce,uaTokenMatch:()=>re,writeSnapshot:()=>H});module.exports=ot(_t);var rt="_snt_uid";var J="_snt_uid";function st(){try{if(typeof crypto!="undefined"&&typeof crypto.randomUUID=="function")return crypto.randomUUID()}catch(t){}let e=()=>Math.floor(Math.random()*4294967295).toString(16).padStart(8,"0");return`${e()}-${e()}-${e()}-${e()}`}function it(e){try{let t=document.cookie.match(new RegExp(`(?:^|; )${e}=([^;]*)`));return t?decodeURIComponent(t[1]):null}catch(t){return null}}function at(e,t,n){try{document.cookie=`${e}=${encodeURIComponent(t)}; max-age=${n}; SameSite=strict; path=/`}catch(a){}}function lt(e){try{return localStorage.getItem(e)}catch(t){return null}}function ct(e,t){try{return localStorage.setItem(e,t),!0}catch(n){return!1}}function dt(e){try{return sessionStorage.getItem(e)}catch(t){return null}}function ut(e,t){try{return sessionStorage.setItem(e,t),!0}catch(n){return!1}}function gt(e){try{sessionStorage.removeItem(e)}catch(t){}}function ft(e){try{return document.cookie=`${e}_probe=1; max-age=1; SameSite=strict; path=/`,/(?:^|; )_snt_uid_probe=1/.test(document.cookie)||document.cookie.indexOf(`${e}_probe=1`)!==-1}catch(t){return!1}}function pt(e){try{localStorage.removeItem(e)}catch(t){}}function mt(e){try{document.cookie=`${e}=; max-age=0; SameSite=strict; path=/`}catch(t){}}var yt={getSessionId:()=>null,isEphemeral:()=>!1,destroy:()=>{}};function ue(e){var d,g,p,v,E,S;if(typeof window=="undefined")return yt;let t=(d=e==null?void 0:e.cookieName)!=null?d:rt,a=((g=e==null?void 0:e.cookieTTLDays)!=null?g:365)*24*60*60,c=(S=(E=(v=(p=it(t))!=null?p:lt(J))!=null?v:dt(J))!=null?E:e==null?void 0:e.ssrSessionId)!=null?S:st();at(t,c,a);let s=ct(J,c),l=ft(t),r=s?!1:ut(J,c),o=!s&&!l&&!r;return{getSessionId:()=>c,isEphemeral:()=>o,destroy:()=>{c=null,mt(t),pt(J),gt(J)}}}function ve(e){return`_snt_retry_${e.slice(0,12)}`}var St={push:()=>{},flush:()=>{},destroy:()=>{}};function ht(e,t){try{let n=localStorage.getItem(t);if(!n)return[];let a=JSON.parse(n);return Array.isArray(a)?(localStorage.removeItem(t),a.slice(-e)):[]}catch(n){return[]}}function he(e,t,n){try{let c=[...(()=>{try{let s=localStorage.getItem(n);if(!s)return[];let l=JSON.parse(s);return Array.isArray(l)?l:[]}catch(s){return[]}})(),...e].slice(-t);localStorage.setItem(n,JSON.stringify(c))}catch(a){}}function Me(e){var X,Z,ee;if(typeof window=="undefined")return St;let t=(X=e.flushIntervalMs)!=null?X:5e3,n=(Z=e.maxBatchSize)!=null?Z:20,a=(ee=e.maxRetrySize)!=null?ee:100,c=e.ingestUrl,s=e.apiKey,l=ve(s),r=[],o=new Set,d=[],g=f=>{for(let y of f)p.delete(y),!o.has(y)&&(o.add(y),d.push(y));for(;d.length>500;){let y=d.shift();y&&o.delete(y)}},p=new Set,v=f=>{o.has(f.id)||p.has(f.id)||(p.add(f.id),r.push(f))},E=ht(a,l);for(let f of E)v(f);let S=0,R=0,k=f=>{if(f.length===0)return;let y=JSON.stringify(f),I=f.map(i=>i.id),D;try{D=fetch(c,{method:"POST",keepalive:!0,body:y,headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`}})}catch(i){he(f,a,l);for(let u of I)p.delete(u);R++,S=Date.now()+Math.min(6e4,1e3*2**Math.min(R,6));return}let M=i=>{if(i.ok||i.status>=400&&i.status<500&&i.status!==429){g(I),R=0,S=0;return}he(f,a,l);for(let u of I)p.delete(u);R++,S=Date.now()+Math.min(6e4,1e3*2**Math.min(R,6))};D instanceof Promise?D.then(M).catch(()=>{he(f,a,l);for(let i of I)p.delete(i);R++,S=Date.now()+Math.min(6e4,1e3*2**Math.min(R,6))}):M(D)},b=typeof TextEncoder!="undefined"?new TextEncoder:null,de=f=>b?b.encode(f).length:f.length,K=f=>{let y=[],I=2;for(let D of f){let M=de(JSON.stringify(D))+1;if(y.length>0&&I+M>57344||y.length>=n)break;y.push(D),I+=M}return y},L=()=>{try{if(Date.now()<S)return;for(;r.length>0;){let f=r.filter(I=>!o.has(I.id));if(r.length=0,f.length===0)break;let y=K(f);if(y.length===0)break;y.length<f.length&&r.push(...f.slice(y.length)),k(y)}}catch(f){}},A=!0,G=null;G=setInterval(()=>{A&&L()},t);let V=()=>{document.visibilityState==="hidden"&&L()},q=()=>{L()};return document.addEventListener("visibilitychange",V),window.addEventListener("pagehide",q),{push(f){v(f),r.length>=n&&L()},flush:L,destroy(){A=!1,G!==null&&(clearInterval(G),G=null),document.removeEventListener("visibilitychange",V),window.removeEventListener("pagehide",q),L()}}}var we="_snt_asgn_";function ge(e,t){return`${e}:${t}`}function vt(e,t){return`${we}${encodeURIComponent(e)}:${encodeURIComponent(t)}`}function Ne(e){let t=e.slice(we.length),n=t.indexOf(":");if(n<0)return null;try{return{componentId:decodeURIComponent(t.slice(0,n)),segment:decodeURIComponent(t.slice(n+1))}}catch(a){return null}}function be(){try{let e=[];for(let t=0;t<localStorage.length;t++){let n=localStorage.key(t);n!=null&&n.startsWith(we)&&e.push(n)}return e}catch(e){return[]}}function Ue(e=18e5){let t=new Map,n=c=>c.assignedAt+e<Date.now();return typeof window!="undefined"&&(()=>{for(let c of be())try{let s=localStorage.getItem(c);if(!s)continue;let l=JSON.parse(s);if(n(l)){localStorage.removeItem(c);continue}let r=Ne(c);if(!r)continue;t.set(ge(r.componentId,r.segment),l)}catch(s){}})(),{get(c,s){let l=t.get(ge(c,s));return l?n(l)?(t.delete(ge(c,s)),null):l:null},set(c,s,l){let r=ge(c,s);t.set(r,l);try{localStorage.setItem(vt(c,s),JSON.stringify(l))}catch(o){}},invalidate(c){let s=`${c}:`;for(let l of[...t.keys()])l.startsWith(s)&&t.delete(l);for(let l of be()){let r=Ne(l);if((r==null?void 0:r.componentId)===c)try{localStorage.removeItem(l)}catch(o){}}},clear(){t.clear();for(let c of be())try{localStorage.removeItem(c)}catch(s){}}}}var Ee=["GPTBot","ChatGPT-User","OAI-SearchBot","ClaudeBot","Claude-User","Claude-SearchBot","PerplexityBot","Perplexity-User","Google-Extended","Applebot-Extended","Meta-ExternalAgent","Bytespider","CCBot","Amazonbot","cohere-ai","Diffbot"];function re(e){return xe(e)!==null}function xe(e){var n;if(!e)return null;let t=e.toLowerCase();return(n=Ee.find(a=>t.includes(a.toLowerCase())))!=null?n:null}function se(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 ie(e,t){if(!e)return"direct";try{let n=new URL(e);if(t)try{if(new URL(t).host===n.host)return"direct"}catch(c){}let a=n.hostname.toLowerCase();return/(^|\.)(google|bing|duckduckgo|yahoo)\./.test(a)?"search":/(^|\.)(twitter\.com|x\.com|facebook\.com|linkedin\.com|reddit\.com|t\.co)$/.test(a)?"social":"referral"}catch(n){return"direct"}}function ae(e){if(!e)return null;try{return new URL(e).hostname}catch(t){return null}}function le(e){let t=e.getHours();return t<6?"night":t<12?"morning":t<18?"afternoon":"evening"}function Ke(e){let t=bt("__segment__",e);return`${t.deviceClass}:${t.trafficSource}`}function bt(e,t){var s,l,r,o,d,g,p;let n=(l=(s=t==null?void 0:t.userAgent)==null?void 0:s.trim())!=null?l:"",a=(o=(r=t==null?void 0:t.referer)==null?void 0:r.trim())!=null?o:"",c=(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?se(n):"desktop",trafficSource:a?ie(a,t==null?void 0:t.appOrigin):"direct",referrerDomain:ae(a),timeOfDay:le(c),dayOfWeek:(p=["sun","mon","tue","wed","thu","fri","sat"][c.getDay()])!=null?p:"sun",automation:(t==null?void 0:t.webdriver)===!0||re(n)}}var Q=require("@sentientui/policy");function ce(e){return h(h(h({id:e.id},e.arms?{arms:[...e.arms]}:{}),e.dims?{dims:Object.fromEntries(Object.entries(e.dims).map(([t,n])=>[t,[...n]]))}:{}),e.baseline!==void 0?{baseline:e.baseline}:{})}function Y(e){let t=ce(e);return(0,Q.slotResultFor)(t,(0,Q.slotBaselineArm)(t))}function Ge(e){let t={};for(let n of e)t[n.id]=Y(n);return t}function fe(e){return typeof e=="string"?e:(0,Q.canonicalArm)(e)}var W="_snt_snap:",wt=["low","medium","high"];function pe(e){try{let t=localStorage.getItem(W+e);if(!t)return null;let n=JSON.parse(t);return!n||typeof n!="object"||n.v!==1||typeof n.persona!="string"||typeof n.band!="string"||!wt.includes(n.band)||typeof n.slots!="object"||n.slots===null||Array.isArray(n.slots)||!(n.layoutOrder===null||Array.isArray(n.layoutOrder))||typeof n.savedAt!="number"||!(n.slotConfig===void 0||typeof n.slotConfig=="object"&&n.slotConfig!==null&&!Array.isArray(n.slotConfig))?null:n}catch(t){return null}}function H(e,t){try{localStorage.setItem(W+e,JSON.stringify(t))}catch(n){}}function Be(e){return"(function(){try{var r=localStorage.getItem("+JSON.stringify(W+e).replace(/</g,"\\u003c")+');if(!r)return;var s=JSON.parse(r);if(!s||s.v!==1||typeof s.persona!=="string"||typeof s.band!=="string")return;var d=document.documentElement;if(d.hasAttribute("data-sentient-persona"))return;d.setAttribute("data-sentient-persona",s.persona);d.setAttribute("data-sentient-confidence",s.band);}catch(e){}})();'}var _e=require("@sentientui/policy");var ye=require("@sentientui/policy");var Se="[sentient] No API key configured \u2014 nothing is being learned. Set NEXT_PUBLIC_SENTIENT_API_KEY or pass localMode: true for local development.",Ie="[sentient] Local mode \u2014 decisions are simulated on-device and nothing is sent over the network. Add an API key to learn from real traffic.",$e=!1,me=!1;function Et(){var e;try{return(e=new URLSearchParams(window.location.search).get("sentient_persona"))!=null?e:void 0}catch(t){return}}function We(e){var r;let t=ue({ssrSessionId:e.ssrSessionId}),n=(r=t.getSessionId())!=null?r:"local",a=Et(),c=import("@sentientui/core/local").then(o=>{let d=o;return d.LOCAL_ENGINE_AVAILABLE?($e||($e=!0,console.info(Ie)),d):(me||(me=!0,console.error(Se)),null)}).catch(()=>(me||(me=!0,console.error(Se)),null)),s=null;function l(o){let d=document.documentElement;d.dataset.sentientPersona===void 0&&(d.dataset.sentientPersona=o.persona,d.dataset.sentientConfidence=(0,ye.confidenceBand)(o.confidence))}return{isLocal:!0,async decide(o){var p,v,E;let d=await c;if(!d)return null;let g=d.createLocalEngine({sessionId:n,forcedPersona:a}).decide(o);return s=F(h({},g),{layoutOrder:(v=(p=g.layoutOrder)!=null?p:s==null?void 0:s.layoutOrder)!=null?v:null,slots:h(h({},(E=s==null?void 0:s.slots)!=null?E:{}),g.slots)}),H(e.apiKey||"local",{v:1,persona:s.persona,band:(0,ye.confidenceBand)(s.confidence),slots:s.slots,layoutOrder:s.layoutOrder,savedAt:Date.now()}),l(g),g},getSlotResult(o){var d,g,p;return(p=(g=s==null?void 0:s.slots[o])!=null?g:(d=e.initialSlots)==null?void 0:d[o])!=null?p:null},getPersona(){return s?{persona:s.persona,confidence:s.confidence,band:(0,ye.confidenceBand)(s.confidence)}:null},async assign(o,d){var v;let g=await c;return!g||!d||d.length===0?d!=null&&d[0]?{variantId:d[0],assignmentTtlMs:0}:null:{variantId:(v=g.createLocalEngine({sessionId:n,forcedPersona:a}).decide({components:[{id:o,variantIds:d}]}).assignments[o])!=null?v:d[0],assignmentTtlMs:0}},track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},getAssignment:()=>null,fetchWeights:()=>Promise.resolve([]),getGraph:()=>({pageNodes:[],capturedAt:0}),dispose:()=>{},destroy:()=>t.destroy()}}function je(e,t,n,a){let c=[];{let r=!1,o=[],d=()=>{if(r)return;let g=Date.now();for(o.push(g);o.length>0&&g-o[0]>500;)o.shift();o.length>=3&&(r=!0,e("rage_click"))};t.addEventListener("click",d),c.push(()=>t.removeEventListener("click",d))}{let s=!1,l=r=>{if(s||!(r.target instanceof Node)||!t.contains(r.target)&&t!==r.target)return;s=!0;let o=typeof window!="undefined"?window.getSelection():null,d=o?o.toString().length:0;e("text_copy",{selectionLength:d})};document.addEventListener("copy",l),c.push(()=>document.removeEventListener("copy",l))}{let s=!1,l=!1,r=null,o=()=>{r!==null&&(clearTimeout(r),r=null)},d=()=>{s||!l||(o(),r=setTimeout(()=>{!s&&l&&(s=!0,e("scroll_hesitation"))},3e3))},g=()=>{o(),d()},p=E=>{for(let S of E)l=S.intersectionRatio>.3,l?d():o()},v=new IntersectionObserver(p,{threshold:[.3]});v.observe(t),window.addEventListener("scroll",g,{passive:!0}),c.push(()=>{v.disconnect(),window.removeEventListener("scroll",g),o()})}if((a==null?void 0:a.tabLoss)!==!1){let s=!1,l=n!=null?n:Date.now(),r=()=>{if(s||document.visibilityState!=="hidden")return;let o=Date.now()-l;o<15e3&&(s=!0,e("tab_loss",{timeOnPage:o}))};document.addEventListener("visibilitychange",r),c.push(()=>document.removeEventListener("visibilitychange",r))}return()=>{for(let s of c)s()}}var Fe="https://api.sentient-ui.com/v1/events",j=new Map,Je=null;function Ce(){try{if(typeof crypto!="undefined"&&typeof crypto.randomUUID=="function")return crypto.randomUUID()}catch(e){}return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})}var z={track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},getAssignment:()=>null,assign:()=>Promise.resolve(null),decide:()=>Promise.resolve(null),getSlotResult:()=>null,getPersona:()=>null,fetchWeights:()=>Promise.resolve([]),getGraph:()=>({pageNodes:[],capturedAt:0}),dispose:()=>{},destroy:()=>{}};function xt(){try{let e={},t=new URLSearchParams(window.location.search);for(let[n,a]of t)n.startsWith("utm_")&&(e[n]=a);return e}catch(e){return{}}}function Qe(e){return e.replace(/\/events\/?$/,"")}function Re(){return typeof navigator!="undefined"&&navigator.globalPrivacyControl===!0?!0:[typeof navigator!="undefined"?navigator.doNotTrack:void 0,typeof window!="undefined"?window.doNotTrack:void 0,typeof navigator!="undefined"?navigator.msDoNotTrack:void 0].some(t=>t==="1"||t==="yes")}function It(e){if(typeof window=="undefined")return;let t=e!=null?e:Je;if(!t){console.warn("[sentient] grantConsent() called before init()");return}let n=j.get(t);if(!n){console.warn("[sentient] grantConsent() called before init()");return}let{config:a,upgrade:c}=n;if(!c||a.respectDoNotTrack!==!1&&Re())return;let s=Ye(F(h({},a),{consent:!0}));c(s),j.set(t,{config:F(h({},a),{consent:!0}),upgrade:null})}function Ct(e){var l;let t=Qe((l=e.ingestUrl)!=null?l:Fe),n={"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`},a={track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},getAssignment:()=>null,fetchWeights:()=>Promise.resolve([]),async assign(r,o,d){try{let g=new URLSearchParams({componentId:r});for(let E of o!=null?o:[])g.append("variantIds[]",E);let p=await fetch(`${t}/winner?${g.toString()}`,{headers:n});return p.ok?{variantId:(await p.json()).variantId,assignmentTtlMs:0}:o!=null&&o[0]?{variantId:o[0],assignmentTtlMs:0}:null}catch(g){return o!=null&&o[0]?{variantId:o[0],assignmentTtlMs:0}:null}},decide:()=>Promise.resolve(null),getSlotResult:()=>null,getPersona:()=>null,getGraph:()=>({pageNodes:[],capturedAt:0}),dispose:()=>{},destroy:()=>{}},c={track:r=>a.track(r),goal:(r,o,d,g)=>a.goal(r,o,d,g),componentGoal:(r,o,d)=>a.componentGoal(r,o,d),identify:r=>a.identify(r),getAssignment:(r,o)=>a.getAssignment(r,o),assign:(r,o,d,g)=>a.assign(r,o,d,g),decide:r=>a.decide(r),getSlotResult:r=>a.getSlotResult(r),getPersona:()=>a.getPersona(),fetchWeights:()=>a.fetchWeights(),getGraph:()=>a.getGraph(),dispose:()=>a.dispose(),destroy:()=>a.destroy()};function s(r){a=r}return{proxy:c,setInner:s}}function Ye(e){var q,X,Z,ee,f,y,I,D,M;if(typeof window=="undefined")return z;Je=e.apiKey;let t=e.respectDoNotTrack!==!1&&Re(),n=e.consent===!1||t,a=typeof e.apiKey=="string"&&e.apiKey.startsWith("pk_");if(e.localMode===!0||!a&&e.localMode!==!1)return n?(j.set(e.apiKey||"local",{config:e,upgrade:null}),z):(j.set(e.apiKey||"local",{config:e,upgrade:null}),We(e));if(n){if(e.preConsentBehavior==="statistical_winner"){if(!e.apiKey||!e.apiKey.startsWith("pk_"))return console.warn("[sentient] init() called with an invalid apiKey \u2014 expected a pk_ public key. SDK disabled."),z;let{proxy:i,setInner:u}=Ct(e);return j.set(e.apiKey,{config:e,upgrade:t?null:u}),i}return j.set(e.apiKey,{config:e,upgrade:null}),z}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."),z;if(e.ingestUrl==="")return console.warn("[sentient] init() called with an empty ingestUrl. SDK disabled."),z;let c=(q=e.ingestUrl)!=null?q:Fe,s=Date.now(),l=ue({ssrSessionId:e.ssrSessionId}),r=Ue(),o=Me({ingestUrl:c,apiKey:e.apiKey}),d=Qe(c),g={"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`},p=se((X=navigator.userAgent)!=null?X:""),v=typeof window!="undefined"?window.location.origin:void 0,E=ie((Z=document.referrer)!=null?Z:"",v),S=(ee=e.sessionSegment)!=null?ee:`${p}:${E}`,R=new Map,k=new Map,b=null,de=i=>{for(let u of i)k.has(u.id)||k.set(u.id,Y(u))};if(e.initialSlots)for(let[i,u]of Object.entries(e.initialSlots))k.set(i,u);let K=pe(e.apiKey);if(K)for(let[i,u]of Object.entries(K.slots))k.has(i)||k.set(i,u);let L={low:.15,medium:.5,high:.85};if(e.initialPersona)b=h({},e.initialPersona);else{let i=document.documentElement.dataset;i.sentientPersona?b={persona:i.sentientPersona,confidence:(y=L[(f=i.sentientConfidence)!=null?f:"low"])!=null?y:.15}:K&&(b={persona:K.persona,confidence:(I=L[K.band])!=null?I:.15})}if(e.initialAssignments)for(let[i,u]of Object.entries(e.initialAssignments))r.set(i,S,{variantId:u,assignedAt:Date.now(),segment:S,confidence:1});let A=Promise.resolve(),G=l.getSessionId();if(G){let i=ae((D=document.referrer)!=null?D:""),u=h(h({sessionId:G,deviceClass:p,trafficSource:E,referrerDomain:i,utmParams:xt(),timeOfDay:le(new Date),dayOfWeek:["sun","mon","tue","wed","thu","fri","sat"][new Date().getDay()],ephemeral:l.isEphemeral(),automation:typeof navigator!="undefined"&&navigator.webdriver===!0||re((M=navigator.userAgent)!=null?M:"")},e.userId?{userId:e.userId}:{}),e.country?{country:e.country}:{});try{A=fetch(`${d}/sessions`,{method:"POST",keepalive:!0,body:JSON.stringify(u),headers:g}).then(m=>{m.status===402&&console.warn("[SentientUI] Session limit exceeded for this project. The bandit will stop learning until the limit resets. Upgrade at sentient-ui.com/pricing")}).catch(()=>{})}catch(m){}}e.debug&&(console.log("[sentient] initialized",{context:e.context}),window.__sentient={client:null,queue:o});let V={goal(i,u={},m=1,O=0){let x=l.getSessionId();if(!x)return;let C=Ce();A.then(()=>{fetch(`${d}/goals`,{method:"POST",keepalive:!0,body:JSON.stringify({sessionId:x,name:i,metadata:u,weight:m,stepIndex:O,goalId:C}),headers:g}).catch(()=>{})})},componentGoal(i,u,m){var T,U,P;let O=l.getSessionId();if(!O)return;let x=r.get(i,S),C=x?null:(T=k.get(i))!=null?T:null;if(!x&&C===null){e.debug&&console.warn(`[sentient] componentGoal("${i}"): no assignment or slot decision yet \u2014 render its <Adaptive>/adaptive hook or call assign()/decide() before recording a goal.`);return}let B=x?x.variantId:fe(C),N={id:Ce(),sessionId:O,projectId:e.apiKey,componentId:i,variantId:B,eventType:"goal_achieved",goalType:u,payload:h({reward:(U=m==null?void 0:m.reward)!=null?U:1},(P=m==null?void 0:m.metadata)!=null?P:{}),timestamp:Date.now(),timeInSession:Date.now()-s};e.debug&&console.log("[sentient] componentGoal",N),A.then(()=>o.push(N))},identify(i){let u=l.getSessionId();u&&A.then(()=>{fetch(`${d}/sessions`,{method:"POST",keepalive:!0,body:JSON.stringify({sessionId:u,userId:i,ephemeral:l.isEphemeral()}),headers:g}).catch(()=>{})})},track(i){let u=l.getSessionId();if(!u)return;let m=F(h({},i),{id:Ce(),sessionId:u,timestamp:Date.now(),timeInSession:Date.now()-s});e.debug&&console.log("[sentient] track",m),A.then(()=>o.push(m))},getAssignment(i,u){return r.get(i,u)},async assign(i,u,m,O){let x=l.getSessionId();if(!x)return null;let C=r.get(i,S);if(C&&(u!=null&&u.length||C.content!==void 0))return{variantId:C.variantId,assignmentTtlMs:0,content:C.content};let B=R.get(i);if(B)return B;let N=(async()=>{await A;try{let T={sessionId:x,componentId:i,variantIds:u};O!==void 0?T.agentDataByVariant=O:m!==void 0&&(T.agentData=m);let U=await fetch(`${d}/assign`,{method:"POST",body:JSON.stringify(T),headers:g});if(!U.ok)return null;let P=await U.json();return r.set(i,S,{variantId:P.variantId,assignedAt:Date.now(),segment:S,confidence:1,content:P.content}),P}catch(T){return null}finally{R.delete(i)}})();return R.set(i,N),N},async decide(i){var O,x,C,B,N,T,U,P,ke,Ae;let u=l.getSessionId();if(!u)return null;let m=(O=i.slots)!=null?O:[];await A;try{let $={sessionId:u};i.sections&&i.sections.length>0&&($.sections=i.sections.map(_=>({id:_}))),$.components=(x=i.components)!=null?x:[],m.length>0&&($.slots=m.map(ce)),i.slotsFrom==="registry"&&($.slotsFrom="registry"),i.v&&($.v=i.v);let De=await fetch(`${d}/decide`,{method:"POST",body:JSON.stringify($),headers:g});if(!De.ok)return de(m),null;let w=await De.json(),te={};for(let _ of m)te[_.id]=(B=(C=w.slots)==null?void 0:C[_.id])!=null?B:Y(_);if(w.slots)for(let[_,ne]of Object.entries(w.slots))_ in te||(te[_]=ne);for(let[_,ne]of Object.entries(te))k.set(_,ne);b={persona:(N=w.persona)!=null?N:"unknown",confidence:(T=w.confidence)!=null?T:0};for(let[_,ne]of Object.entries((U=w.assignments)!=null?U:{}))r.set(_,S,{variantId:ne,assignedAt:Date.now(),segment:S,confidence:1});return H(e.apiKey,h({v:1,persona:b.persona,band:(0,_e.confidenceBand)(b.confidence),slots:Object.fromEntries(k),layoutOrder:(P=w.layoutOrder)!=null?P:null,savedAt:Date.now()},w.slotConfig?{slotConfig:w.slotConfig}:{})),h(h({layoutOrder:(ke=w.layoutOrder)!=null?ke:null,assignments:(Ae=w.assignments)!=null?Ae:{},slots:te,persona:b.persona,confidence:b.confidence},w.slotConfig?{slotConfig:w.slotConfig}:{}),w.goals?{goals:w.goals}:{})}catch($){return de(m),null}},getSlotResult(i){var u;return(u=k.get(i))!=null?u:null},getPersona(){return b?{persona:b.persona,confidence:b.confidence,band:(0,_e.confidenceBand)(b.confidence)}:null},async fetchWeights(){var i;try{let u=await fetch(`${d}/weights`,{headers:g});return u.ok?(i=(await u.json()).components)!=null?i:[]:[]}catch(u){return[]}},getGraph(){return{pageNodes:[],capturedAt:0}},dispose(){o.destroy(),e.debug&&console.log("[sentient] disposed")},destroy(){o.destroy(),l.destroy();try{localStorage.removeItem(W+e.apiKey),localStorage.removeItem(ve(e.apiKey))}catch(i){}e.debug&&console.log("[sentient] destroyed")}};if(j.set(e.apiKey,{config:e,upgrade:null}),e.debug){let i=window;i.__sentient&&(i.__sentient.client=V)}return V}0&&(module.exports={LOCAL_MODE_BANNER,PROD_KEYLESS_ERROR,SNAPSHOT_STORAGE_KEY_PREFIX,agentUaList,armOfResult,attachMicroSignalDetectors,baselineResultFor,baselineSlots,deriveSessionSegment,detectDeviceClass,detectTimeOfDay,detectTrafficSource,grantConsent,init,isDoNotTrackEnabled,matchedAgentToken,readSnapshot,referrerDomainFromReferer,renderPrePaintScript,toWireSlot,uaTokenMatch,writeSnapshot});
|
|
2
2
|
//# sourceMappingURL=index.js.map
|