@sentientui/core 0.39.1 → 0.40.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunk-7RF3JRZO.mjs +2 -0
- package/dist/chunk-7RF3JRZO.mjs.map +1 -0
- package/dist/chunk-B4A22OMG.mjs +2 -0
- package/dist/chunk-B4A22OMG.mjs.map +1 -0
- package/dist/chunk-IUT3UXTD.mjs +2 -0
- package/dist/chunk-IUT3UXTD.mjs.map +1 -0
- package/dist/{index-BAfi7_FG.d.cts → index-CN9VJxiW.d.cts} +45 -2
- package/dist/{index-DyKtujwf.d.ts → index-CROWjwsJ.d.ts} +45 -2
- package/dist/index-consent.js +1 -1
- package/dist/index-consent.js.map +1 -1
- package/dist/index-consent.mjs +1 -1
- package/dist/index-engagement.js.map +1 -1
- package/dist/index-engagement.mjs +1 -1
- package/dist/index-graph.d.cts +4 -4
- package/dist/index-graph.d.ts +4 -4
- package/dist/index-graph.js +1 -1
- package/dist/index-graph.js.map +1 -1
- package/dist/index-graph.mjs +1 -1
- package/dist/index-local.d.cts +2 -2
- package/dist/index-local.d.ts +2 -2
- package/dist/index-server.d.cts +27 -4
- package/dist/index-server.d.ts +27 -4
- package/dist/index-server.js +1 -1
- package/dist/index-server.js.map +1 -1
- package/dist/index-server.mjs +1 -1
- package/dist/index-server.mjs.map +1 -1
- package/dist/index.d.cts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1 -1
- package/dist/{session-meta-qx4kIL5y.d.cts → session-meta-BG8w53d7.d.cts} +1 -1
- package/dist/{session-meta-BtRtwsHI.d.ts → session-meta-D9Wx2PtC.d.ts} +1 -1
- package/package.json +1 -1
- package/dist/chunk-MKM7TD3L.mjs +0 -2
- package/dist/chunk-MKM7TD3L.mjs.map +0 -1
- package/dist/chunk-QEIHHO3T.mjs +0 -2
- package/dist/chunk-QEIHHO3T.mjs.map +0 -1
- package/dist/chunk-XZRKD2GS.mjs +0 -2
- package/dist/chunk-XZRKD2GS.mjs.map +0 -1
package/dist/index-graph.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{a as v}from"./chunk-WKXD7KI3.mjs";import{a as _,g as O}from"./chunk-Z6ILOYBD.mjs";import{A as ze,B as He,C as Ve,D as Ye,E as We,F as Je,G as Xe,H as Qe,I as Ze,J as et,K as tt,O as se,P as M,Q as P,R as ae,T as D,d as ne,e as oe,f as re,m as Oe,n as Me,o as Pe,p as De,q as Ge,r as ke,s as $e,t as Le,u as je,v as Ue,w as Ke,x as Fe,y as Be,z as qe}from"./chunk-QEIHHO3T.mjs";import{a as B,b as q,c as z,d as H}from"./chunk-XZRKD2GS.mjs";import"./chunk-EVF5PQ4U.mjs";import{g as V,h as Y,i as W,l as J,m as X,o as Q,p as Z,q as ee,r as te}from"./chunk-MKM7TD3L.mjs";import{a as R,b as w,c as A}from"./chunk-J5EL7HKC.mjs";import{a as I,b}from"./chunk-TMCGHANO.mjs";var G="_snt_graph_edges",ie={pricing:["features","faq"],features:["pricing"],faq:["pricing"],social_proof:["cta"],cta:["social_proof","hero","trust"],hero:["cta"],comparison:["pricing"],trust:["cta"]};function ce(e){var t;return(t=ie[e])!=null?t:[]}function de(e,t){try{let n=localStorage.getItem(e);return n?JSON.parse(n):t}catch(n){return t}}function pe(e,t){try{localStorage.setItem(e,JSON.stringify(t))}catch(n){}}var ue=new Set(["pricing","hero","social_proof","cta","features","faq","comparison","trust","navigation","generic"]);function le(e){return ue.has(e)?e:"generic"}function k(e){try{let t=new URL(e);return`${t.origin}${t.pathname}`}catch(t){return"/"}}function me(e,t,n){let a=`${e}:${t}:${n.join(",")}`,s=5381;for(let o=0;o<a.length;o++)s=(s<<5)+s+a.charCodeAt(o)&4294967295;return(s>>>0).toString(16).padStart(8,"0")}function $(e){let t=new Map,n=new Map,a=`_snt_graph_nodes${R(e==null?void 0:e.apiKey)}`,s=()=>{typeof window!="undefined"&&pe(a,[...t.values()])};if(typeof window!="undefined"){let o=de(a,[]);for(let i of o)t.set(i.componentId,i);try{localStorage.removeItem(G)}catch(i){}}return{addPageNode(o){t.set(o.componentId,o),s()},addStructuralEdge(o){let i=`${o.fromComponentId}->${o.toComponentId}`;n.set(i,o)},syncOnce(){var i,c;if(!(e!=null&&e.syncUrl)||typeof window=="undefined")return;let o=[...t.values()];if(o.length!==0)try{let l=new Map;for(let r of o){let d=(i=l.get(r.semanticType))!=null?i:[];d.push(r),l.set(r.semanticType,d)}let u=[],m=new Set;for(let r of o)for(let d of ce(r.semanticType)){let p=(c=l.get(d))!=null?c:[];for(let S of p){if(S.componentId===r.componentId)continue;let f=`semantic:${r.componentId}->${S.componentId}`;m.has(f)||(m.add(f),u.push({fromComponentId:r.componentId,toComponentId:S.componentId,type:"semantic",weight:.4,confidence:.9}))}}let g=new Set(o.map(r=>r.componentId));for(let r of n.values()){if(!g.has(r.fromComponentId)||!g.has(r.toComponentId))continue;let d=`structural:${r.fromComponentId}->${r.toComponentId}`;m.has(d)||(m.add(d),u.push({fromComponentId:r.fromComponentId,toComponentId:r.toComponentId,type:"structural",weight:r.weight,confidence:1}))}let h=b(I(I({pageUrl:k(window.location.href)},e.sessionId?{sessionId:e.sessionId}:{}),e.projectId?{projectId:e.projectId}:{}),{nodes:o.map(r=>{let d=le(r.semanticType);return{componentId:r.componentId,semanticType:d,answers:r.answers,contentHash:me(r.componentId,d,r.answers),prominenceScore:r.prominenceScore,depthInPage:r.depth}}),edges:u});fetch(e.syncUrl,{method:"POST",keepalive:!0,headers:I({"Content-Type":"application/json"},e.apiKey?{Authorization:`Bearer ${e.apiKey}`}:{}),body:JSON.stringify(h)}).catch(()=>{})}catch(l){}},snapshot(){return{pageNodes:[...t.values()],capturedAt:Date.now()}},destroy(){if(typeof window!="undefined")try{localStorage.removeItem(a),localStorage.removeItem(G)}catch(o){}}}}var fe=new Set(["SECTION","ARTICLE","MAIN","DIV","ASIDE"]),ge=200,he="h1, h2, h3",Se="[data-sentient-id], section[aria-label], article[aria-label], main[aria-label], aside[aria-label]",L=30,ye=1500,Ee={scan:async()=>({nodes:[],edges:[],scannedAt:0}),observe:()=>{},getProminenceScore:()=>0,destroy:()=>{}};function j(e,t,n){return n<=t?0:Math.max(0,Math.min(1,(e-t)/(n-t)))}function Ie(e){var t,n,a;try{let s=e;for(let o of Object.keys(s)){if(!o.startsWith("__reactFiber")&&!o.startsWith("__reactInternalInstance"))continue;let i=s[o],c=(a=(t=i==null?void 0:i.type)==null?void 0:t.displayName)!=null?a:(n=i==null?void 0:i.type)==null?void 0:n.name;if(c&&c.length>1)return c}}catch(s){}}function Ce(e){let t={};for(let n of Array.from(e.attributes))n.name.startsWith("data-")&&(t[n.name]=n.value);return t}var x=new Set(_);function be(e,t){let n=e.getAttribute("data-sentient-id"),a=n?t==null?void 0:t[n]:void 0;if(a&&x.has(a))return a;let s=e.getAttribute("data-sentient-type");if(s&&x.has(s))return s;let o=e.getAttribute("role");return o&&x.has(o)?o:O(e)}function Te(e){let t=5381;for(let n=0;n<e.length;n++)t=(t<<5)+t+e.charCodeAt(n)&4294967295;return(t>>>0).toString(16).padStart(8,"0")}function we(e){let t=[],n=e;for(;n;){let a=n.parentElement;if(!a){t.push(n.tagName.toLowerCase());break}let s=Array.prototype.indexOf.call(a.children,n);t.push(`${n.tagName.toLowerCase()}[${s}]`),n=a}return t.reverse().join("/")}function Ae(e){var n;let t=(n=e.getAttribute("data-sentient-id"))!=null?n:e.getAttribute("id");return t||`${e.tagName.toLowerCase()}-${Te(we(e))}`}function ve(e){let t=0,n=e.parentElement;for(;n;)t++,n=n.parentElement;return t}function N(e,t,n){var s,o,i,c;let a=e.querySelector(he);return{componentId:Ae(e),semanticType:be(e,n),ariaLabel:(s=e.getAttribute("aria-label"))!=null?s:void 0,headingText:(i=(o=a==null?void 0:a.textContent)==null?void 0:o.trim())!=null?i:void 0,isAboveFold:e.getBoundingClientRect().top<window.innerHeight,prominenceScore:t(e),depth:ve(e),reactComponentName:Ie(e),dataAttributes:Ce(e),locator:(c=v(e,e.ownerDocument))!=null?c:void 0}}function U(e){var o;let t=[],n=new Set,a="__root__",s=new Map;for(let[i,c]of e){let l=i.parentElement,u=a;for(;l;){if(e.has(l)){u=e.get(l);let g=e.get(i),h=`${u}->${g}`;!n.has(h)&&u!==g&&(n.add(h),t.push({fromComponentId:u,toComponentId:g,weight:.6}));break}l=l.parentElement}let m=(o=s.get(u))!=null?o:[];m.push(i),s.set(u,m)}for(let i of s.values()){if(i.length<2)continue;let c=i.length>L?i.slice(0,L):i;for(let l=0;l<c.length;l++)for(let u=l+1;u<c.length;u++){if(t.length>=ye)return t;let m=e.get(c[l]),g=e.get(c[u]);if(m===g)continue;let h=`${m}->${g}::sib`,r=`${g}->${m}::sib`;n.has(h)||(n.add(h),t.push({fromComponentId:m,toComponentId:g,weight:.3})),n.has(r)||(n.add(r),t.push({fromComponentId:g,toComponentId:m,weight:.3}))}}return t}function xe(e,t){let n=[],a=new Set,s=new Map;return document.querySelectorAll("[data-sentient-id]").forEach(c=>{if(c instanceof Element&&!a.has(c)){a.add(c);let l=N(c,e,t);n.push(l),s.set(c,l.componentId)}}),document.querySelectorAll("section, article, main, aside").forEach(c=>{if(!(c instanceof Element)||a.has(c))return;let l=c.hasAttribute("aria-label"),u=c.hasAttribute("data-sentient-id");if(!l&&!u)return;a.add(c);let m=N(c,e,t);n.push(m),s.set(c,m.componentId)}),{nodes:n,edges:U(s),elementToId:s}}function K(e={}){let{sectionTypes:t}=e;if(typeof window=="undefined")return Ee;let n=null,a=0,s=null,o=new Map,i=r=>{try{let d=window.getComputedStyle(r),p=parseFloat(d.fontSize)||12,S=parseFloat(d.zIndex)||0,f=r.getBoundingClientRect(),E=Math.max(f.top,0),y=window.innerHeight||1,C=1/(E/y+1),F=j(p,12,48)*.4+C*.4+j(S,0,100)*.2;return Math.max(0,Math.min(1,F))}catch(d){return .5}},c=()=>new Promise(r=>{let d=()=>{let{nodes:p,edges:S,elementToId:f}=xe(i,t);o.clear();for(let[E,y]of f)o.set(E,y);r({nodes:p,edges:S,scannedAt:Date.now()})};try{typeof requestIdleCallback=="function"?a=requestIdleCallback(d,{timeout:100}):d()}catch(p){d()}}),l=new Set,u=null,m=()=>{u=null;let r=[...l];l.clear();let d=[],p=new Set;for(let f of r){if(!f.isConnected)continue;let E=[];fe.has(f.tagName)&&(f.hasAttribute("data-sentient-id")||f.hasAttribute("aria-label"))&&E.push(f);try{f.querySelectorAll(Se).forEach(y=>E.push(y))}catch(y){}for(let y of E){if(o.has(y))continue;let C=N(y,i,t);d.push(C),p.add(C.componentId),o.set(y,C.componentId)}}if(d.length===0||!s)return;for(let f of[...o.keys()])f.isConnected||o.delete(f);let S=U(o).filter(f=>p.has(f.fromComponentId)||p.has(f.toComponentId));s({nodes:d,edges:S,addedAt:Date.now()})};return{scan:c,observe:r=>{s=r;try{n=new MutationObserver(d=>{for(let p of d)p.type==="childList"&&p.addedNodes.forEach(S=>{S instanceof Element&&l.add(S)});l.size>0&&u===null&&(u=setTimeout(m,ge))}),n.observe(document.body,{childList:!0,subtree:!0})}catch(d){}},getProminenceScore:i,destroy:()=>{if(n&&(n.disconnect(),n=null),u!==null&&clearTimeout(u),u=null,l.clear(),a&&typeof cancelIdleCallback=="function")try{cancelIdleCallback(a)}catch(r){}a=0,s=null,o.clear()}}}var Ne="https://api.sentient-ui.com/v1/events";function Re(e){var n;let t=a=>{try{let s=document.cookie.match(new RegExp(`(?:^|; )${a}=([^;]*)`));return s?decodeURIComponent(s[1]):void 0}catch(s){return}};return(n=e?t(A(e)):void 0)!=null?n:t(w)}var T=new Map;function _e(e){var r;let t=D(e),n=e.respectDoNotTrack!==!1&&P(),a=e.consent===!1||n,s=typeof e.apiKey=="string"&&e.apiKey.startsWith("pk_"),o=e.localMode===!0||!s;if(!e.graph||o||typeof window=="undefined")return t;if(a)return n||M(e.apiKey,d=>_e(d)),t;let i=T.get(e.apiKey);if(i)try{i()}catch(d){}let c=K({sectionTypes:e.sectionTypes}),l=(r=e.ingestUrl)!=null?r:Ne,u=$({syncUrl:l.replace(/\/events\/?$/,"/graph/sync"),apiKey:e.apiKey,projectId:e.apiKey,sessionId:Re(e.apiKey)});c.scan().then(d=>{for(let p of d.nodes)u.addPageNode({id:p.componentId,componentId:p.componentId,semanticType:p.semanticType,answers:e.captureDomText&&p.headingText?[p.headingText]:[],prominenceScore:p.prominenceScore,depth:p.depth});for(let p of d.edges)u.addStructuralEdge(p);u.syncOnce()});let m=null,g=()=>{m!==null&&clearTimeout(m),m=setTimeout(()=>{m=null,u.syncOnce()},500)};c.observe(d=>{for(let p of d.nodes)u.addPageNode({id:p.componentId,componentId:p.componentId,semanticType:p.semanticType,answers:e.captureDomText&&p.headingText?[p.headingText]:[],prominenceScore:p.prominenceScore,depth:p.depth});for(let p of d.edges)u.addStructuralEdge(p);g()});let h=()=>{m!==null&&(clearTimeout(m),m=null),c.destroy(),u.destroy(),T.get(e.apiKey)===h&&T.delete(e.apiKey)};return T.set(e.apiKey,h),b(I({},t),{getGraph:()=>u.snapshot(),dispose:()=>{h(),t.dispose()},destroy:()=>{h(),t.destroy()}})}export{Me as BLOCK_ALIGNS,$e as BLOCK_EMPHASES,Ue as BLOCK_FITS,Oe as BLOCK_GAPS,Ke as BLOCK_GRID_COLUMNS,Fe as BLOCK_HEADING_LEVELS,Pe as BLOCK_JUSTIFIES,ze as BLOCK_MAX_WIDTHS,qe as BLOCK_PADS,je as BLOCK_RATIOS,De as BLOCK_SIZES,Be as BLOCK_SURFACES,Le as BLOCK_TEXT_ALIGNS,ke as BLOCK_TONES,Ge as BLOCK_WEIGHTS,He as FORM_FIELD_KINDS,Ve as FORM_INPUT_TYPES,w as LEGACY_SESSION_COOKIE_NAME,Ze as MAX_BLOCK_ARMS,Qe as MAX_BLOCK_CHILDREN,Xe as MAX_BLOCK_DEPTH,Je as MAX_BLOCK_NODES,et as MAX_BLOCK_TEXT_LEN,Ye as MAX_FORM_FIELDS,We as MAX_FORM_SELECT_OPTIONS,B as SNAPSHOT_STORAGE_KEY_PREFIX,ne as STAGE_ATTRIBUTE,te as armOfResult,se as attachMicroSignalDetectors,Z as baselineResultFor,ee as baselineSlots,tt as containsFormBlock,X as deriveSessionSegment,V as detectDeviceClass,J as detectTimeOfDay,Y as detectTrafficSource,oe as exposedStage,ae as grantConsent,_e as init,P as isDoNotTrackEnabled,v as locatorFromElement,q as readSnapshot,W as referrerDomainFromReferer,H as renderPrePaintScript,k as sanitizePageUrl,A as sessionCookieName,re as setStageAttribute,Q as toWireSlot,z as writeSnapshot};
|
|
1
|
+
import{a as v}from"./chunk-WKXD7KI3.mjs";import{a as _,g as O}from"./chunk-Z6ILOYBD.mjs";import{A as ze,B as He,C as Ve,D as Ye,E as We,F as Je,G as Xe,H as Qe,I as Ze,J as et,K as tt,O as se,P as M,Q as P,R as ae,T as D,d as ne,e as oe,f as re,m as Oe,n as Me,o as Pe,p as De,q as Ge,r as ke,s as $e,t as Le,u as je,v as Ue,w as Ke,x as Fe,y as Be,z as qe}from"./chunk-IUT3UXTD.mjs";import{a as B,b as q,c as z,d as H}from"./chunk-B4A22OMG.mjs";import"./chunk-EVF5PQ4U.mjs";import{g as V,h as Y,i as W,l as J,m as X,o as Q,p as Z,q as ee,r as te}from"./chunk-7RF3JRZO.mjs";import{a as R,b as w,c as A}from"./chunk-J5EL7HKC.mjs";import{a as I,b}from"./chunk-TMCGHANO.mjs";var G="_snt_graph_edges",ie={pricing:["features","faq"],features:["pricing"],faq:["pricing"],social_proof:["cta"],cta:["social_proof","hero","trust"],hero:["cta"],comparison:["pricing"],trust:["cta"]};function ce(e){var t;return(t=ie[e])!=null?t:[]}function de(e,t){try{let n=localStorage.getItem(e);return n?JSON.parse(n):t}catch(n){return t}}function pe(e,t){try{localStorage.setItem(e,JSON.stringify(t))}catch(n){}}var ue=new Set(["pricing","hero","social_proof","cta","features","faq","comparison","trust","navigation","generic"]);function le(e){return ue.has(e)?e:"generic"}function k(e){try{let t=new URL(e);return`${t.origin}${t.pathname}`}catch(t){return"/"}}function me(e,t,n){let a=`${e}:${t}:${n.join(",")}`,s=5381;for(let o=0;o<a.length;o++)s=(s<<5)+s+a.charCodeAt(o)&4294967295;return(s>>>0).toString(16).padStart(8,"0")}function $(e){let t=new Map,n=new Map,a=`_snt_graph_nodes${R(e==null?void 0:e.apiKey)}`,s=()=>{typeof window!="undefined"&&pe(a,[...t.values()])};if(typeof window!="undefined"){let o=de(a,[]);for(let i of o)t.set(i.componentId,i);try{localStorage.removeItem(G)}catch(i){}}return{addPageNode(o){t.set(o.componentId,o),s()},addStructuralEdge(o){let i=`${o.fromComponentId}->${o.toComponentId}`;n.set(i,o)},syncOnce(){var i,c;if(!(e!=null&&e.syncUrl)||typeof window=="undefined")return;let o=[...t.values()];if(o.length!==0)try{let l=new Map;for(let r of o){let d=(i=l.get(r.semanticType))!=null?i:[];d.push(r),l.set(r.semanticType,d)}let u=[],m=new Set;for(let r of o)for(let d of ce(r.semanticType)){let p=(c=l.get(d))!=null?c:[];for(let S of p){if(S.componentId===r.componentId)continue;let f=`semantic:${r.componentId}->${S.componentId}`;m.has(f)||(m.add(f),u.push({fromComponentId:r.componentId,toComponentId:S.componentId,type:"semantic",weight:.4,confidence:.9}))}}let g=new Set(o.map(r=>r.componentId));for(let r of n.values()){if(!g.has(r.fromComponentId)||!g.has(r.toComponentId))continue;let d=`structural:${r.fromComponentId}->${r.toComponentId}`;m.has(d)||(m.add(d),u.push({fromComponentId:r.fromComponentId,toComponentId:r.toComponentId,type:"structural",weight:r.weight,confidence:1}))}let h=b(I(I({pageUrl:k(window.location.href)},e.sessionId?{sessionId:e.sessionId}:{}),e.projectId?{projectId:e.projectId}:{}),{nodes:o.map(r=>{let d=le(r.semanticType);return{componentId:r.componentId,semanticType:d,answers:r.answers,contentHash:me(r.componentId,d,r.answers),prominenceScore:r.prominenceScore,depthInPage:r.depth}}),edges:u});fetch(e.syncUrl,{method:"POST",keepalive:!0,headers:I({"Content-Type":"application/json"},e.apiKey?{Authorization:`Bearer ${e.apiKey}`}:{}),body:JSON.stringify(h)}).catch(()=>{})}catch(l){}},snapshot(){return{pageNodes:[...t.values()],capturedAt:Date.now()}},destroy(){if(typeof window!="undefined")try{localStorage.removeItem(a),localStorage.removeItem(G)}catch(o){}}}}var fe=new Set(["SECTION","ARTICLE","MAIN","DIV","ASIDE"]),ge=200,he="h1, h2, h3",Se="[data-sentient-id], section[aria-label], article[aria-label], main[aria-label], aside[aria-label]",L=30,ye=1500,Ee={scan:async()=>({nodes:[],edges:[],scannedAt:0}),observe:()=>{},getProminenceScore:()=>0,destroy:()=>{}};function j(e,t,n){return n<=t?0:Math.max(0,Math.min(1,(e-t)/(n-t)))}function Ie(e){var t,n,a;try{let s=e;for(let o of Object.keys(s)){if(!o.startsWith("__reactFiber")&&!o.startsWith("__reactInternalInstance"))continue;let i=s[o],c=(a=(t=i==null?void 0:i.type)==null?void 0:t.displayName)!=null?a:(n=i==null?void 0:i.type)==null?void 0:n.name;if(c&&c.length>1)return c}}catch(s){}}function Ce(e){let t={};for(let n of Array.from(e.attributes))n.name.startsWith("data-")&&(t[n.name]=n.value);return t}var x=new Set(_);function be(e,t){let n=e.getAttribute("data-sentient-id"),a=n?t==null?void 0:t[n]:void 0;if(a&&x.has(a))return a;let s=e.getAttribute("data-sentient-type");if(s&&x.has(s))return s;let o=e.getAttribute("role");return o&&x.has(o)?o:O(e)}function Te(e){let t=5381;for(let n=0;n<e.length;n++)t=(t<<5)+t+e.charCodeAt(n)&4294967295;return(t>>>0).toString(16).padStart(8,"0")}function we(e){let t=[],n=e;for(;n;){let a=n.parentElement;if(!a){t.push(n.tagName.toLowerCase());break}let s=Array.prototype.indexOf.call(a.children,n);t.push(`${n.tagName.toLowerCase()}[${s}]`),n=a}return t.reverse().join("/")}function Ae(e){var n;let t=(n=e.getAttribute("data-sentient-id"))!=null?n:e.getAttribute("id");return t||`${e.tagName.toLowerCase()}-${Te(we(e))}`}function ve(e){let t=0,n=e.parentElement;for(;n;)t++,n=n.parentElement;return t}function N(e,t,n){var s,o,i,c;let a=e.querySelector(he);return{componentId:Ae(e),semanticType:be(e,n),ariaLabel:(s=e.getAttribute("aria-label"))!=null?s:void 0,headingText:(i=(o=a==null?void 0:a.textContent)==null?void 0:o.trim())!=null?i:void 0,isAboveFold:e.getBoundingClientRect().top<window.innerHeight,prominenceScore:t(e),depth:ve(e),reactComponentName:Ie(e),dataAttributes:Ce(e),locator:(c=v(e,e.ownerDocument))!=null?c:void 0}}function U(e){var o;let t=[],n=new Set,a="__root__",s=new Map;for(let[i,c]of e){let l=i.parentElement,u=a;for(;l;){if(e.has(l)){u=e.get(l);let g=e.get(i),h=`${u}->${g}`;!n.has(h)&&u!==g&&(n.add(h),t.push({fromComponentId:u,toComponentId:g,weight:.6}));break}l=l.parentElement}let m=(o=s.get(u))!=null?o:[];m.push(i),s.set(u,m)}for(let i of s.values()){if(i.length<2)continue;let c=i.length>L?i.slice(0,L):i;for(let l=0;l<c.length;l++)for(let u=l+1;u<c.length;u++){if(t.length>=ye)return t;let m=e.get(c[l]),g=e.get(c[u]);if(m===g)continue;let h=`${m}->${g}::sib`,r=`${g}->${m}::sib`;n.has(h)||(n.add(h),t.push({fromComponentId:m,toComponentId:g,weight:.3})),n.has(r)||(n.add(r),t.push({fromComponentId:g,toComponentId:m,weight:.3}))}}return t}function xe(e,t){let n=[],a=new Set,s=new Map;return document.querySelectorAll("[data-sentient-id]").forEach(c=>{if(c instanceof Element&&!a.has(c)){a.add(c);let l=N(c,e,t);n.push(l),s.set(c,l.componentId)}}),document.querySelectorAll("section, article, main, aside").forEach(c=>{if(!(c instanceof Element)||a.has(c))return;let l=c.hasAttribute("aria-label"),u=c.hasAttribute("data-sentient-id");if(!l&&!u)return;a.add(c);let m=N(c,e,t);n.push(m),s.set(c,m.componentId)}),{nodes:n,edges:U(s),elementToId:s}}function K(e={}){let{sectionTypes:t}=e;if(typeof window=="undefined")return Ee;let n=null,a=0,s=null,o=new Map,i=r=>{try{let d=window.getComputedStyle(r),p=parseFloat(d.fontSize)||12,S=parseFloat(d.zIndex)||0,f=r.getBoundingClientRect(),E=Math.max(f.top,0),y=window.innerHeight||1,C=1/(E/y+1),F=j(p,12,48)*.4+C*.4+j(S,0,100)*.2;return Math.max(0,Math.min(1,F))}catch(d){return .5}},c=()=>new Promise(r=>{let d=()=>{let{nodes:p,edges:S,elementToId:f}=xe(i,t);o.clear();for(let[E,y]of f)o.set(E,y);r({nodes:p,edges:S,scannedAt:Date.now()})};try{typeof requestIdleCallback=="function"?a=requestIdleCallback(d,{timeout:100}):d()}catch(p){d()}}),l=new Set,u=null,m=()=>{u=null;let r=[...l];l.clear();let d=[],p=new Set;for(let f of r){if(!f.isConnected)continue;let E=[];fe.has(f.tagName)&&(f.hasAttribute("data-sentient-id")||f.hasAttribute("aria-label"))&&E.push(f);try{f.querySelectorAll(Se).forEach(y=>E.push(y))}catch(y){}for(let y of E){if(o.has(y))continue;let C=N(y,i,t);d.push(C),p.add(C.componentId),o.set(y,C.componentId)}}if(d.length===0||!s)return;for(let f of[...o.keys()])f.isConnected||o.delete(f);let S=U(o).filter(f=>p.has(f.fromComponentId)||p.has(f.toComponentId));s({nodes:d,edges:S,addedAt:Date.now()})};return{scan:c,observe:r=>{s=r;try{n=new MutationObserver(d=>{for(let p of d)p.type==="childList"&&p.addedNodes.forEach(S=>{S instanceof Element&&l.add(S)});l.size>0&&u===null&&(u=setTimeout(m,ge))}),n.observe(document.body,{childList:!0,subtree:!0})}catch(d){}},getProminenceScore:i,destroy:()=>{if(n&&(n.disconnect(),n=null),u!==null&&clearTimeout(u),u=null,l.clear(),a&&typeof cancelIdleCallback=="function")try{cancelIdleCallback(a)}catch(r){}a=0,s=null,o.clear()}}}var Ne="https://api.sentient-ui.com/v1/events";function Re(e){var n;let t=a=>{try{let s=document.cookie.match(new RegExp(`(?:^|; )${a}=([^;]*)`));return s?decodeURIComponent(s[1]):void 0}catch(s){return}};return(n=e?t(A(e)):void 0)!=null?n:t(w)}var T=new Map;function _e(e){var r;let t=D(e),n=e.respectDoNotTrack!==!1&&P(),a=e.consent===!1||n,s=typeof e.apiKey=="string"&&e.apiKey.startsWith("pk_"),o=e.localMode===!0||!s;if(!e.graph||o||typeof window=="undefined")return t;if(a)return n||M(e.apiKey,d=>_e(d)),t;let i=T.get(e.apiKey);if(i)try{i()}catch(d){}let c=K({sectionTypes:e.sectionTypes}),l=(r=e.ingestUrl)!=null?r:Ne,u=$({syncUrl:l.replace(/\/events\/?$/,"/graph/sync"),apiKey:e.apiKey,projectId:e.apiKey,sessionId:Re(e.apiKey)});c.scan().then(d=>{for(let p of d.nodes)u.addPageNode({id:p.componentId,componentId:p.componentId,semanticType:p.semanticType,answers:e.captureDomText&&p.headingText?[p.headingText]:[],prominenceScore:p.prominenceScore,depth:p.depth});for(let p of d.edges)u.addStructuralEdge(p);u.syncOnce()});let m=null,g=()=>{m!==null&&clearTimeout(m),m=setTimeout(()=>{m=null,u.syncOnce()},500)};c.observe(d=>{for(let p of d.nodes)u.addPageNode({id:p.componentId,componentId:p.componentId,semanticType:p.semanticType,answers:e.captureDomText&&p.headingText?[p.headingText]:[],prominenceScore:p.prominenceScore,depth:p.depth});for(let p of d.edges)u.addStructuralEdge(p);g()});let h=()=>{m!==null&&(clearTimeout(m),m=null),c.destroy(),u.destroy(),T.get(e.apiKey)===h&&T.delete(e.apiKey)};return T.set(e.apiKey,h),b(I({},t),{getGraph:()=>u.snapshot(),dispose:()=>{h(),t.dispose()},destroy:()=>{h(),t.destroy()}})}export{Me as BLOCK_ALIGNS,$e as BLOCK_EMPHASES,Ue as BLOCK_FITS,Oe as BLOCK_GAPS,Ke as BLOCK_GRID_COLUMNS,Fe as BLOCK_HEADING_LEVELS,Pe as BLOCK_JUSTIFIES,ze as BLOCK_MAX_WIDTHS,qe as BLOCK_PADS,je as BLOCK_RATIOS,De as BLOCK_SIZES,Be as BLOCK_SURFACES,Le as BLOCK_TEXT_ALIGNS,ke as BLOCK_TONES,Ge as BLOCK_WEIGHTS,He as FORM_FIELD_KINDS,Ve as FORM_INPUT_TYPES,w as LEGACY_SESSION_COOKIE_NAME,Ze as MAX_BLOCK_ARMS,Qe as MAX_BLOCK_CHILDREN,Xe as MAX_BLOCK_DEPTH,Je as MAX_BLOCK_NODES,et as MAX_BLOCK_TEXT_LEN,Ye as MAX_FORM_FIELDS,We as MAX_FORM_SELECT_OPTIONS,B as SNAPSHOT_STORAGE_KEY_PREFIX,ne as STAGE_ATTRIBUTE,te as armOfResult,se as attachMicroSignalDetectors,Z as baselineResultFor,ee as baselineSlots,tt as containsFormBlock,X as deriveSessionSegment,V as detectDeviceClass,J as detectTimeOfDay,Y as detectTrafficSource,oe as exposedStage,ae as grantConsent,_e as init,P as isDoNotTrackEnabled,v as locatorFromElement,q as readSnapshot,W as referrerDomainFromReferer,H as renderPrePaintScript,k as sanitizePageUrl,A as sessionCookieName,re as setStageAttribute,Q as toWireSlot,z as writeSnapshot};
|
|
2
2
|
//# sourceMappingURL=index-graph.mjs.map
|
package/dist/index-local.d.cts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { f as DecideOutcome } from './index-
|
|
2
|
-
import { e as SlotDeclInput } from './session-meta-
|
|
1
|
+
import { f as DecideOutcome } from './index-CN9VJxiW.cjs';
|
|
2
|
+
import { e as SlotDeclInput } from './session-meta-BG8w53d7.cjs';
|
|
3
3
|
import './style-vocabulary-Ba_g6_DD.cjs';
|
|
4
4
|
import './region-skeleton-BRIVB-qf.cjs';
|
|
5
5
|
import './index-consent.cjs';
|
package/dist/index-local.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { f as DecideOutcome } from './index-
|
|
2
|
-
import { e as SlotDeclInput } from './session-meta-
|
|
1
|
+
import { f as DecideOutcome } from './index-CROWjwsJ.js';
|
|
2
|
+
import { e as SlotDeclInput } from './session-meta-D9Wx2PtC.js';
|
|
3
3
|
import './style-vocabulary-Ba_g6_DD.js';
|
|
4
4
|
import './region-skeleton-BRIVB-qf.js';
|
|
5
5
|
import './index-consent.js';
|
package/dist/index-server.d.cts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { $ as SitePalette, a4 as StyleVocabulary } from './style-vocabulary-Ba_g6_DD.cjs';
|
|
2
|
-
import { d as SlotConfigEntry, e as SlotDeclInput } from './session-meta-
|
|
3
|
-
export { C as CLICK_ID_KEYS, c as SessionUpsertPayload, l as buildSessionUpsertPayload, n as deriveSessionSegment, o as detectDeviceClass, p as detectTimeOfDay, q as detectTrafficSource, r as extractTrackedParams, u as referrerDomainFromReferer } from './session-meta-
|
|
2
|
+
import { d as SlotConfigEntry, e as SlotDeclInput } from './session-meta-BG8w53d7.cjs';
|
|
3
|
+
export { C as CLICK_ID_KEYS, c as SessionUpsertPayload, l as buildSessionUpsertPayload, n as deriveSessionSegment, o as detectDeviceClass, p as detectTimeOfDay, q as detectTrafficSource, r as extractTrackedParams, u as referrerDomainFromReferer } from './session-meta-BG8w53d7.cjs';
|
|
4
4
|
import { c as RenderCaps } from './region-skeleton-BRIVB-qf.cjs';
|
|
5
5
|
import { SlotResult } from '@sentientui/policy';
|
|
6
6
|
export { SlotResult } from '@sentientui/policy';
|
|
@@ -206,13 +206,36 @@ declare function preloadDecisions(params: {
|
|
|
206
206
|
* same goal id.
|
|
207
207
|
*/
|
|
208
208
|
declare const SERVER_GOAL_NAMESPACE = "3d8f5a21-7c64-4b19-8e0a-5f2c91d7b6e3";
|
|
209
|
+
/**
|
|
210
|
+
* Verified identify: the `userHash` for `identify(userId, { userHash })`.
|
|
211
|
+
* Compute it on YOUR server (it needs the secret key) and hand it to the page
|
|
212
|
+
* with the user id — `<AdaptiveRoot userId>` from `@sentientui/react/next`
|
|
213
|
+
* does both for you. Once a project sends verified identifies, only verified
|
|
214
|
+
* bindings receive server goals by `userId` and carry a user's portrait
|
|
215
|
+
* across devices: an unsigned identify is any browser's claim.
|
|
216
|
+
*
|
|
217
|
+
* The secret is derived from the secret key, so there is nothing new to
|
|
218
|
+
* configure: `HMAC(sk, 'sentient-identity-v1')`, then `v1.<exp>.` + HMAC(that,
|
|
219
|
+
* `${userId}.${exp}`) — the API stores the same derivation per server key.
|
|
220
|
+
* Valid for `ttlSeconds` (default 24 h, at most 7 days).
|
|
221
|
+
*/
|
|
222
|
+
declare function signUserId(userId: string, serverKey: string, opts?: {
|
|
223
|
+
ttlSeconds?: number;
|
|
224
|
+
now?: number;
|
|
225
|
+
}): Promise<string>;
|
|
209
226
|
type TrackServerGoalOptions = {
|
|
210
227
|
/** Project SECRET key (sk_...), from a server-only env var. */
|
|
211
228
|
serverKey: string;
|
|
212
229
|
/** The visitor's session id: `readSessionCookie(cookies, apiKey)` in the same
|
|
213
230
|
* request, or the id you stored from `client.getVisitorId()`. Null/empty
|
|
214
231
|
* means nobody to credit: nothing is sent. */
|
|
215
|
-
sessionId
|
|
232
|
+
sessionId?: string | null;
|
|
233
|
+
/** Your own user id, as passed to `client.identify()` in the browser — use it
|
|
234
|
+
* when the backend never sees our visitor id (a webhook, a job, a signup
|
|
235
|
+
* handled on another host). The API credits that user's most recently seen
|
|
236
|
+
* visit in the project; with no such visit nothing is recorded and this
|
|
237
|
+
* resolves 'skipped_no_visitor'. Ignored when `sessionId` is given. */
|
|
238
|
+
userId?: string | null;
|
|
216
239
|
/** Goal name, as defined in your project (e.g. 'purchase'). */
|
|
217
240
|
name: string;
|
|
218
241
|
/** Your own id for this conversion (order id, Stripe event id, user id).
|
|
@@ -299,4 +322,4 @@ type ConnectRequest = {
|
|
|
299
322
|
*/
|
|
300
323
|
declare function sentientAgentMiddleware(opts: Omit<AgentCaptureOptions, 'waitUntil' | 'source'>): (req: ConnectRequest, res: unknown, next: (err?: unknown) => void) => void;
|
|
301
324
|
|
|
302
|
-
export { type AgentCaptureOptions, type CapturableRequest, type DecideResult, SERVER_GOAL_NAMESPACE, type ServerAssignConfig, type ServerAssignments, type ServerAssignmentsDetailed, SlotDeclInput, type TrackServerGoalOptions, captureAgentRequest, postAgentFetch, preloadAssignments, preloadAssignmentsDetailed, preloadDecisions, readSessionCookie, sentientAgentMiddleware, trackServerGoal };
|
|
325
|
+
export { type AgentCaptureOptions, type CapturableRequest, type DecideResult, SERVER_GOAL_NAMESPACE, type ServerAssignConfig, type ServerAssignments, type ServerAssignmentsDetailed, SlotDeclInput, type TrackServerGoalOptions, captureAgentRequest, postAgentFetch, preloadAssignments, preloadAssignmentsDetailed, preloadDecisions, readSessionCookie, sentientAgentMiddleware, signUserId, trackServerGoal };
|
package/dist/index-server.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { $ as SitePalette, a4 as StyleVocabulary } from './style-vocabulary-Ba_g6_DD.js';
|
|
2
|
-
import { d as SlotConfigEntry, e as SlotDeclInput } from './session-meta-
|
|
3
|
-
export { C as CLICK_ID_KEYS, c as SessionUpsertPayload, l as buildSessionUpsertPayload, n as deriveSessionSegment, o as detectDeviceClass, p as detectTimeOfDay, q as detectTrafficSource, r as extractTrackedParams, u as referrerDomainFromReferer } from './session-meta-
|
|
2
|
+
import { d as SlotConfigEntry, e as SlotDeclInput } from './session-meta-D9Wx2PtC.js';
|
|
3
|
+
export { C as CLICK_ID_KEYS, c as SessionUpsertPayload, l as buildSessionUpsertPayload, n as deriveSessionSegment, o as detectDeviceClass, p as detectTimeOfDay, q as detectTrafficSource, r as extractTrackedParams, u as referrerDomainFromReferer } from './session-meta-D9Wx2PtC.js';
|
|
4
4
|
import { c as RenderCaps } from './region-skeleton-BRIVB-qf.js';
|
|
5
5
|
import { SlotResult } from '@sentientui/policy';
|
|
6
6
|
export { SlotResult } from '@sentientui/policy';
|
|
@@ -206,13 +206,36 @@ declare function preloadDecisions(params: {
|
|
|
206
206
|
* same goal id.
|
|
207
207
|
*/
|
|
208
208
|
declare const SERVER_GOAL_NAMESPACE = "3d8f5a21-7c64-4b19-8e0a-5f2c91d7b6e3";
|
|
209
|
+
/**
|
|
210
|
+
* Verified identify: the `userHash` for `identify(userId, { userHash })`.
|
|
211
|
+
* Compute it on YOUR server (it needs the secret key) and hand it to the page
|
|
212
|
+
* with the user id — `<AdaptiveRoot userId>` from `@sentientui/react/next`
|
|
213
|
+
* does both for you. Once a project sends verified identifies, only verified
|
|
214
|
+
* bindings receive server goals by `userId` and carry a user's portrait
|
|
215
|
+
* across devices: an unsigned identify is any browser's claim.
|
|
216
|
+
*
|
|
217
|
+
* The secret is derived from the secret key, so there is nothing new to
|
|
218
|
+
* configure: `HMAC(sk, 'sentient-identity-v1')`, then `v1.<exp>.` + HMAC(that,
|
|
219
|
+
* `${userId}.${exp}`) — the API stores the same derivation per server key.
|
|
220
|
+
* Valid for `ttlSeconds` (default 24 h, at most 7 days).
|
|
221
|
+
*/
|
|
222
|
+
declare function signUserId(userId: string, serverKey: string, opts?: {
|
|
223
|
+
ttlSeconds?: number;
|
|
224
|
+
now?: number;
|
|
225
|
+
}): Promise<string>;
|
|
209
226
|
type TrackServerGoalOptions = {
|
|
210
227
|
/** Project SECRET key (sk_...), from a server-only env var. */
|
|
211
228
|
serverKey: string;
|
|
212
229
|
/** The visitor's session id: `readSessionCookie(cookies, apiKey)` in the same
|
|
213
230
|
* request, or the id you stored from `client.getVisitorId()`. Null/empty
|
|
214
231
|
* means nobody to credit: nothing is sent. */
|
|
215
|
-
sessionId
|
|
232
|
+
sessionId?: string | null;
|
|
233
|
+
/** Your own user id, as passed to `client.identify()` in the browser — use it
|
|
234
|
+
* when the backend never sees our visitor id (a webhook, a job, a signup
|
|
235
|
+
* handled on another host). The API credits that user's most recently seen
|
|
236
|
+
* visit in the project; with no such visit nothing is recorded and this
|
|
237
|
+
* resolves 'skipped_no_visitor'. Ignored when `sessionId` is given. */
|
|
238
|
+
userId?: string | null;
|
|
216
239
|
/** Goal name, as defined in your project (e.g. 'purchase'). */
|
|
217
240
|
name: string;
|
|
218
241
|
/** Your own id for this conversion (order id, Stripe event id, user id).
|
|
@@ -299,4 +322,4 @@ type ConnectRequest = {
|
|
|
299
322
|
*/
|
|
300
323
|
declare function sentientAgentMiddleware(opts: Omit<AgentCaptureOptions, 'waitUntil' | 'source'>): (req: ConnectRequest, res: unknown, next: (err?: unknown) => void) => void;
|
|
301
324
|
|
|
302
|
-
export { type AgentCaptureOptions, type CapturableRequest, type DecideResult, SERVER_GOAL_NAMESPACE, type ServerAssignConfig, type ServerAssignments, type ServerAssignmentsDetailed, SlotDeclInput, type TrackServerGoalOptions, captureAgentRequest, postAgentFetch, preloadAssignments, preloadAssignmentsDetailed, preloadDecisions, readSessionCookie, sentientAgentMiddleware, trackServerGoal };
|
|
325
|
+
export { type AgentCaptureOptions, type CapturableRequest, type DecideResult, SERVER_GOAL_NAMESPACE, type ServerAssignConfig, type ServerAssignments, type ServerAssignmentsDetailed, SlotDeclInput, type TrackServerGoalOptions, captureAgentRequest, postAgentFetch, preloadAssignments, preloadAssignmentsDetailed, preloadDecisions, readSessionCookie, sentientAgentMiddleware, signUserId, trackServerGoal };
|
package/dist/index-server.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var P=Object.defineProperty,ae=Object.defineProperties,le=Object.getOwnPropertyDescriptor,ce=Object.getOwnPropertyDescriptors,ue=Object.getOwnPropertyNames,J=Object.getOwnPropertySymbols;var z=Object.prototype.hasOwnProperty,de=Object.prototype.propertyIsEnumerable;var W=(e,t,r)=>t in e?P(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,c=(e,t)=>{for(var r in t||(t={}))z.call(t,r)&&W(e,r,t[r]);if(J)for(var r of J(t))de.call(t,r)&&W(e,r,t[r]);return e},O=(e,t)=>ae(e,ce(t));var ge=(e,t)=>{for(var r in t)P(e,r,{get:t[r],enumerable:!0})},fe=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of ue(t))!z.call(e,s)&&s!==r&&P(e,s,{get:()=>t[s],enumerable:!(n=le(t,s))||n.enumerable});return e};var me=e=>fe(P({},"__esModule",{value:!0}),e);var Ce={};ge(Ce,{CLICK_ID_KEYS:()=>L,SERVER_GOAL_NAMESPACE:()=>F,buildSessionUpsertPayload:()=>v,captureAgentRequest:()=>q,deriveSessionSegment:()=>H,detectDeviceClass:()=>E,detectTimeOfDay:()=>M,detectTrafficSource:()=>_,extractTrackedParams:()=>Y,postAgentFetch:()=>K,preloadAssignments:()=>te,preloadAssignmentsDetailed:()=>N,preloadDecisions:()=>ne,readSessionCookie:()=>re,referrerDomainFromReferer:()=>$,sentientAgentMiddleware:()=>ie,trackServerGoal:()=>se});module.exports=me(Ce);var pe=["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 ye(e){return T(e)!==null}function T(e){var r;if(!e)return null;let t=e.toLowerCase();return(r=pe.find(n=>t.includes(n.toLowerCase())))!=null?r:null}function E(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 r=new URL(e);if(t)try{if(new URL(t).host===r.host)return"direct"}catch(s){}let n=r.hostname.toLowerCase();return/(^|\.)(google|bing|duckduckgo|yahoo)\./.test(n)?"search":/(^|\.)(twitter\.com|x\.com|facebook\.com|linkedin\.com|reddit\.com|t\.co)$/.test(n)?"social":"referral"}catch(r){return"direct"}}function $(e){if(!e)return null;try{return new URL(e).hostname}catch(t){return null}}var L=["gclid","gbraid","wbraid","fbclid","ttclid","msclkid","twclid","li_fat_id"];function Y(e){let t={},r={};try{let n=typeof e=="string"||e instanceof URLSearchParams?new URLSearchParams(e):Object.entries(e).flatMap(([s,i])=>{let a=Array.isArray(i)?i[0]:i;return a===void 0?[]:[[s,a]]});for(let[s,i]of n)s.startsWith("utm_")?s in t||(t[s]=i):L.includes(s)&&(s in r||(r[s]=i))}catch(n){}return{utmParams:t,clickIds:r}}function M(e){let t=e.getHours();return t<6?"night":t<12?"morning":t<18?"afternoon":"evening"}function H(e){let t=v("__segment__",e);return`${t.deviceClass}:${t.trafficSource}`}function v(e,t){var i,a,o,f,m,u,l,A;let r=(a=(i=t==null?void 0:t.userAgent)==null?void 0:i.trim())!=null?a:"",n=(f=(o=t==null?void 0:t.referer)==null?void 0:o.trim())!=null?f:"",s=(m=t==null?void 0:t.now)!=null?m:new Date;return c({sessionId:e,ephemeral:!1,utmParams:(u=t==null?void 0:t.utmParams)!=null?u:{},clickIds:(l=t==null?void 0:t.clickIds)!=null?l:{},deviceClass:r?E(r):"desktop",trafficSource:n?_(n,t==null?void 0:t.appOrigin):"direct",referrerDomain:$(n),timeOfDay:M(s),dayOfWeek:(A=["sun","mon","tue","wed","thu","fri","sat"][s.getDay()])!=null?A:"sun",automation:(t==null?void 0:t.webdriver)===!0||ye(r)},t!=null&&t.landingPath?{landingPath:t.landingPath.split(/[?#]/)[0]}:{})}function he(e){return e?`_${e.slice(0,12)}`:""}var B="_snt_uid";function X(e){return`${B}${he(e)}`}var C=require("@sentientui/policy");function j(e){return c(c(c({id:e.id},e.arms?{arms:[...e.arms]}:{}),e.dims?{dims:Object.fromEntries(Object.entries(e.dims).map(([t,r])=>[t,[...r]]))}:{}),e.baseline!==void 0?{baseline:e.baseline}:{})}function G(e){let t=j(e);return(0,C.slotResultFor)(t,(0,C.slotBaselineArm)(t))}function Q(e){let t={};for(let r of e)t[r.id]=G(r);return t}var Se="X-Sentient-Server-Key";function Z(e){let t={"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`};return e.origin&&(t.Origin=e.origin),e.serverKey&&typeof window=="undefined"&&(t[Se]=e.serverKey),t}var ee=1e3;function D(e,t,r){let n=new AbortController,s=setTimeout(()=>n.abort(),r);return fetch(e,O(c({},t),{signal:n.signal})).finally(()=>clearTimeout(s))}async function te(e,t,r){return(await N(e,t,r)).assignments}async function N(e,t,r,n){var u;if(r.doNotTrack)return{assignments:{},unified:[]};let s=(u=r.timeoutMs)!=null?u:ee,i=Z(r),a=c(c({},v(t,{userAgent:r.userAgent,referer:r.referer,utmParams:r.utmParams,clickIds:r.clickIds,appOrigin:r.origin,landingPath:r.landingPath})),r.persona?{persona:r.persona}:{});try{let l=await D(`${r.baseUrl}/sessions`,{method:"POST",headers:i,body:JSON.stringify(a)},s);if(l.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");else if(!l.ok){let A=await l.json().catch(()=>({}));console.error(`[SentientUI] preloadAssignments: session upsert failed (${l.status})`,A)}}catch(l){console.error("[SentientUI] preloadAssignments: session upsert threw",l)}let o=await Promise.allSettled(e.map(async({id:l,variantIds:A})=>{let p=await D(`${r.baseUrl}/assign`,{method:"POST",headers:i,body:JSON.stringify(c({sessionId:t,componentId:l,variantIds:A},n!=null&&n.unified?{caps:{unified:!0}}:{}))},s);if(!p.ok){let S=await p.json().catch(()=>({}));return console.error(`[SentientUI] preloadAssignments: assign failed for "${l}" (${p.status})`,S),null}let y=await p.json();return{id:l,variantId:y.variantId,unified:(n==null?void 0:n.unified)===!0&&y.unified===!0}})),f={},m=[];for(let l of o)l.status==="fulfilled"&&l.value&&(l.value.unified?m.push(l.value.id):f[l.value.id]=l.value.variantId);return{assignments:f,unified:m}}function re(e,t){var r,n,s,i;return(i=(s=t?(r=e.get(X(t)))==null?void 0:r.value:void 0)!=null?s:(n=e.get(B))==null?void 0:n.value)!=null?i:null}async function ne(e,t,r){var m,u,l,A,p,y,S,x,w,R,g,I;let n=(m=r.timeoutMs)!=null?m:ee,s=(u=e.slots)!=null?u:[],i=null;e.slotsFrom==="registry"&&(Array.isArray(e.registrySlotIds)?i=e.registrySlotIds:console.error("[SentientUI] preloadDecisions: slotsFrom: 'registry' needs registrySlotIds (the <Adaptive id>s this page renders). An unscoped registry decide records a trial for every published slot on every page; falling back to request mode."));let a={layoutOrder:(l=e.sections)!=null?l:[],assignments:{},slots:Q(s),persona:"unknown",confidence:0};if(r.doNotTrack)return a;let o=Z(r),f=c(c({},v(t,{userAgent:r.userAgent,referer:r.referer,utmParams:r.utmParams,clickIds:r.clickIds,appOrigin:r.origin,landingPath:r.landingPath})),r.persona?{persona:r.persona}:{});try{let b=await D(`${r.baseUrl}/sessions`,{method:"POST",headers:o,body:JSON.stringify(f)},n);if(!b.ok){let d=await b.json().catch(()=>({}));console.error(`[SentientUI] preloadDecisions: session upsert failed (${b.status})`,d)}}catch(b){console.error("[SentientUI] preloadDecisions: session upsert threw",b)}try{let b=await D(`${r.baseUrl}/decide`,{method:"POST",headers:o,body:JSON.stringify(c(c(c(c({sessionId:t,sections:((A=e.sections)!=null?A:[]).map(h=>({id:h})),components:e.components},s.length>0?{slots:s.map(j)}:{}),i!==null?{slotsFrom:"registry",registrySlotIds:i,bootstrap:!1,render:Object.fromEntries(i.map(h=>{var U,V;return[h,(V=(U=e.renderCaps)==null?void 0:U[h])!=null?V:{forms:!0,compose:!0,ops:!1}]}))}:{}),r.persona?{persona:r.persona}:{}),e.unifiedCaps?{caps:{unified:!0}}:{}))},n);if(!b.ok){let h=await b.json().catch(()=>({}));return console.error(`[SentientUI] preloadDecisions: decide failed (${b.status})`,h),a}let d=await b.json(),k={};for(let h of s)k[h.id]=(y=(p=d.slots)==null?void 0:p[h.id])!=null?y:G(h);for(let[h,U]of Object.entries((S=d.slots)!=null?S:{}))h in k||(k[h]=U);let oe=d.slotConfig!==void 0&&typeof d.slotConfig=="object"&&d.slotConfig!==null&&!Array.isArray(d.slotConfig);return c(c(c(c(c(c({layoutOrder:(w=(x=d.layoutOrder)!=null?x:e.sections)!=null?w:[],assignments:(R=d.assignments)!=null?R:{},slots:k,persona:(g=d.persona)!=null?g:"unknown",confidence:(I=d.confidence)!=null?I:0},oe?{slotConfig:d.slotConfig}:{}),d.palette?{palette:d.palette}:{}),d.vocabulary?{vocabulary:d.vocabulary}:{}),typeof d.stage=="string"?{stage:d.stage}:{}),typeof d.context=="string"?{context:d.context}:{}),e.unifiedCaps&&Array.isArray(d.unified)?{unified:d.unified.filter(h=>typeof h=="string")}:{})}catch(b){return console.error("[SentientUI] preloadDecisions: decide threw",b),a}}var F="3d8f5a21-7c64-4b19-8e0a-5f2c91d7b6e3";function be(e){let t=(p,y)=>p<<y|p>>>32-y,r=e.length,n=new Uint8Array((r+8>>6)*64+64);n.set(e),n[r]=128;let s=new DataView(n.buffer);s.setUint32(n.length-8,Math.floor(r*8/4294967296)),s.setUint32(n.length-4,r*8>>>0);let i=1732584193,a=4023233417,o=2562383102,f=271733878,m=3285377520,u=new Array(80);for(let p=0;p<n.length;p+=64){for(let g=0;g<16;g++)u[g]=s.getUint32(p+g*4);for(let g=16;g<80;g++)u[g]=t(u[g-3]^u[g-8]^u[g-14]^u[g-16],1);let y=i,S=a,x=o,w=f,R=m;for(let g=0;g<80;g++){let[I,b]=g<20?[S&x|~S&w,1518500249]:g<40?[S^x^w,1859775393]:g<60?[S&x|S&w|x&w,2400959708]:[S^x^w,3395469782],d=t(y,5)+I+R+b+u[g]|0;R=w,w=x,x=t(S,30),S=y,y=d}i=i+y|0,a=a+S|0,o=o+x|0,f=f+w|0,m=m+R|0}let l=new Uint8Array(20),A=new DataView(l.buffer);return[i,a,o,f,m].forEach((p,y)=>A.setUint32(y*4,p>>>0)),l}async function Ae(e,t){var m;let r=t.replace(/-/g,""),n=new Uint8Array(16);for(let u=0;u<16;u++)n[u]=parseInt(r.slice(u*2,u*2+2),16);let s=new TextEncoder().encode(e),i=new Uint8Array(16+s.length);i.set(n,0),i.set(s,16);let a=(m=globalThis.crypto)==null?void 0:m.subtle,o=(a?new Uint8Array(await a.digest("SHA-1",i)):be(i)).slice(0,16);o[6]=o[6]&15|80,o[8]=o[8]&63|128;let f=Array.from(o,u=>u.toString(16).padStart(2,"0")).join("");return`${f.slice(0,8)}-${f.slice(8,12)}-${f.slice(12,16)}-${f.slice(16,20)}-${f.slice(20,32)}`}var xe="https://api.sentient-ui.com/v1",we=5e3;async function se(e){var s,i;if(typeof window!="undefined")return console.error("[SentientUI] trackServerGoal is server-only: the secret key was not sent. Call it from a route handler, server action or webhook."),"failed";if(!e.sessionId)return"skipped_no_visitor";if(e.name.includes(":"))return console.error('[SentientUI] trackServerGoal: goal names cannot contain ":" (nothing was sent).'),"failed";let t=(s=e.fetch)!=null?s:fetch,r=new AbortController,n;try{let a=new Promise((m,u)=>{var l;n=setTimeout(()=>{r.abort(),u(new Error("timeout"))},(l=e.timeoutMs)!=null?l:we)});a.catch(()=>{});let o=await Ae(`${e.sessionId}:${e.name}:${e.dedupeKey}`,F);return(await Promise.race([t(`${((i=e.apiBaseUrl)!=null?i:xe).replace(/\/+$/,"")}/goals`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e.serverKey}`},body:JSON.stringify(c(c(c({sessionId:e.sessionId,name:e.name,goalId:o,externalId:e.dedupeKey},e.value!==void 0?{value:e.value}:{}),e.currency!==void 0?{currency:e.currency}:{}),e.metadata!==void 0?{metadata:e.metadata}:{})),signal:r.signal}),a])).ok?"recorded":"failed"}catch(a){return"failed"}finally{n&&clearTimeout(n)}}var Re="https://api.sentient-ui.com/v1";function ve(e){try{return new URL(e,"http://localhost").pathname||"/"}catch(t){return e.split(/[?#]/,1)[0]||"/"}}function K(e,t){var n,s,i,a;let r=(n=t.fetchImpl)!=null?n:typeof fetch=="function"?fetch:void 0;if(!(!r||!t.apiKey))try{let o=r(`${(s=t.baseUrl)!=null?s:Re}/crawler-events`,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${t.apiKey}`},body:JSON.stringify({path:e.path,botName:e.botName,userAgent:e.userAgent,source:(i=t.source)!=null?i:"middleware"})}).catch(()=>{});(a=t.waitUntil)==null||a.call(t,o)}catch(o){}}function q(e,t){var s;let r="";try{r=(s=e.headers.get("user-agent"))!=null?s:""}catch(i){return!1}let n=T(r);return n?(K({path:ve(e.url),userAgent:r,botName:n},t),!0):!1}function ie(e){return(t,r,n)=>{var s,i,a;try{let o=t.headers["user-agent"],f=Array.isArray(o)?(s=o[0])!=null?s:"":o!=null?o:"";q({url:(a=(i=t.originalUrl)!=null?i:t.url)!=null?a:"/",headers:{get:m=>m.toLowerCase()==="user-agent"?f:null}},O(c({},e),{source:"middleware"}))}catch(o){}n()}}0&&(module.exports={CLICK_ID_KEYS,SERVER_GOAL_NAMESPACE,buildSessionUpsertPayload,captureAgentRequest,deriveSessionSegment,detectDeviceClass,detectTimeOfDay,detectTrafficSource,extractTrackedParams,postAgentFetch,preloadAssignments,preloadAssignmentsDetailed,preloadDecisions,readSessionCookie,referrerDomainFromReferer,sentientAgentMiddleware,trackServerGoal});
|
|
1
|
+
"use strict";var O=Object.defineProperty,de=Object.defineProperties,ue=Object.getOwnPropertyDescriptor,ge=Object.getOwnPropertyDescriptors,fe=Object.getOwnPropertyNames,W=Object.getOwnPropertySymbols;var z=Object.prototype.hasOwnProperty,me=Object.prototype.propertyIsEnumerable;var J=(e,t,n)=>t in e?O(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,u=(e,t)=>{for(var n in t||(t={}))z.call(t,n)&&J(e,n,t[n]);if(W)for(var n of W(t))me.call(t,n)&&J(e,n,t[n]);return e},R=(e,t)=>de(e,ge(t));var ye=(e,t)=>{for(var n in t)O(e,n,{get:t[n],enumerable:!0})},pe=(e,t,n,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of fe(t))!z.call(e,r)&&r!==n&&O(e,r,{get:()=>t[r],enumerable:!(i=ue(t,r))||i.enumerable});return e};var he=e=>pe(O({},"__esModule",{value:!0}),e);var Oe={};ye(Oe,{CLICK_ID_KEYS:()=>M,SERVER_GOAL_NAMESPACE:()=>K,buildSessionUpsertPayload:()=>U,captureAgentRequest:()=>H,deriveSessionSegment:()=>X,detectDeviceClass:()=>T,detectTimeOfDay:()=>L,detectTrafficSource:()=>_,extractTrackedParams:()=>Y,postAgentFetch:()=>V,preloadAssignments:()=>re,preloadAssignmentsDetailed:()=>F,preloadDecisions:()=>ie,readSessionCookie:()=>se,referrerDomainFromReferer:()=>$,sentientAgentMiddleware:()=>ce,signUserId:()=>oe,trackServerGoal:()=>ae});module.exports=he(Oe);var xe=["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 be(e){return E(e)!==null}function E(e){var n;if(!e)return null;let t=e.toLowerCase();return(n=xe.find(i=>t.includes(i.toLowerCase())))!=null?n:null}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 _(e,t,n){if(!e)return"direct";try{let i=new URL(e);if(t)try{if(new URL(t).host===i.host)return"direct"}catch(s){}let r=i.hostname.toLowerCase();return n&&`.${r}`.endsWith(`.${n}`)?"direct":/(^|\.)(google|bing|duckduckgo|yahoo)\./.test(r)?"search":/(^|\.)(twitter\.com|x\.com|facebook\.com|linkedin\.com|reddit\.com|t\.co)$/.test(r)?"social":"referral"}catch(i){return"direct"}}function $(e){if(!e)return null;try{return new URL(e).hostname}catch(t){return null}}var M=["gclid","gbraid","wbraid","fbclid","ttclid","msclkid","twclid","li_fat_id"];function Y(e){let t={},n={};try{let i=typeof e=="string"||e instanceof URLSearchParams?new URLSearchParams(e):Object.entries(e).flatMap(([r,s])=>{let o=Array.isArray(s)?s[0]:s;return o===void 0?[]:[[r,o]]});for(let[r,s]of i)r.startsWith("utm_")?r in t||(t[r]=s):M.includes(r)&&(r in n||(n[r]=s))}catch(i){}return{utmParams:t,clickIds:n}}function L(e){let t=e.getHours();return t<6?"night":t<12?"morning":t<18?"afternoon":"evening"}function X(e){let t=U("__segment__",e);return`${t.deviceClass}:${t.trafficSource}`}function U(e,t){var s,o,c,m,d,a,l,h;let n=(o=(s=t==null?void 0:t.userAgent)==null?void 0:s.trim())!=null?o:"",i=(m=(c=t==null?void 0:t.referer)==null?void 0:c.trim())!=null?m:"",r=(d=t==null?void 0:t.now)!=null?d:new Date;return u({sessionId:e,ephemeral:!1,utmParams:(a=t==null?void 0:t.utmParams)!=null?a:{},clickIds:(l=t==null?void 0:t.clickIds)!=null?l:{},deviceClass:n?T(n):"desktop",trafficSource:i?_(i,t==null?void 0:t.appOrigin):"direct",referrerDomain:$(i),timeOfDay:L(r),dayOfWeek:(h=["sun","mon","tue","wed","thu","fri","sat"][r.getDay()])!=null?h:"sun",automation:(t==null?void 0:t.webdriver)===!0||be(n)},t!=null&&t.landingPath?{landingPath:t.landingPath.split(/[?#]/)[0]}:{})}function Se(e){return e?`_${e.slice(0,12)}`:""}var j="_snt_uid";function Q(e){return`${j}${Se(e)}`}var C=require("@sentientui/policy");function B(e){return u(u(u({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 G(e){let t=B(e);return(0,C.slotResultFor)(t,(0,C.slotBaselineArm)(t))}function Z(e){let t={};for(let n of e)t[n.id]=G(n);return t}var Ae="X-Sentient-Server-Key";function te(e){let t={"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`};return e.origin&&(t.Origin=e.origin),e.serverKey&&typeof window=="undefined"&&(t[Ae]=e.serverKey),t}var ne=1e3;function D(e,t,n){let i=new AbortController,r=setTimeout(()=>i.abort(),n);return fetch(e,R(u({},t),{signal:i.signal})).finally(()=>clearTimeout(r))}async function re(e,t,n){return(await F(e,t,n)).assignments}async function F(e,t,n,i){var a;if(n.doNotTrack)return{assignments:{},unified:[]};let r=(a=n.timeoutMs)!=null?a:ne,s=te(n),o=u(u({},U(t,{userAgent:n.userAgent,referer:n.referer,utmParams:n.utmParams,clickIds:n.clickIds,appOrigin:n.origin,landingPath:n.landingPath})),n.persona?{persona:n.persona}:{});try{let l=await D(`${n.baseUrl}/sessions`,{method:"POST",headers:s,body:JSON.stringify(o)},r);if(l.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");else if(!l.ok){let h=await l.json().catch(()=>({}));console.error(`[SentientUI] preloadAssignments: session upsert failed (${l.status})`,h)}}catch(l){console.error("[SentientUI] preloadAssignments: session upsert threw",l)}let c=await Promise.allSettled(e.map(async({id:l,variantIds:h})=>{let x=await D(`${n.baseUrl}/assign`,{method:"POST",headers:s,body:JSON.stringify(u({sessionId:t,componentId:l,variantIds:h},i!=null&&i.unified?{caps:{unified:!0}}:{}))},r);if(!x.ok){let b=await x.json().catch(()=>({}));return console.error(`[SentientUI] preloadAssignments: assign failed for "${l}" (${x.status})`,b),null}let p=await x.json();return{id:l,variantId:p.variantId,unified:(i==null?void 0:i.unified)===!0&&p.unified===!0}})),m={},d=[];for(let l of c)l.status==="fulfilled"&&l.value&&(l.value.unified?d.push(l.value.id):m[l.value.id]=l.value.variantId);return{assignments:m,unified:d}}function se(e,t){var n,i,r,s;return(s=(r=t?(n=e.get(Q(t)))==null?void 0:n.value:void 0)!=null?r:(i=e.get(j))==null?void 0:i.value)!=null?s:null}async function ie(e,t,n){var d,a,l,h,x,p,b,S,A,g,f,I;let i=(d=n.timeoutMs)!=null?d:ne,r=(a=e.slots)!=null?a:[],s=null;e.slotsFrom==="registry"&&(Array.isArray(e.registrySlotIds)?s=e.registrySlotIds:console.error("[SentientUI] preloadDecisions: slotsFrom: 'registry' needs registrySlotIds (the <Adaptive id>s this page renders). An unscoped registry decide records a trial for every published slot on every page; falling back to request mode."));let o={layoutOrder:(l=e.sections)!=null?l:[],assignments:{},slots:Z(r),persona:"unknown",confidence:0};if(n.doNotTrack)return o;let c=te(n),m=u(u({},U(t,{userAgent:n.userAgent,referer:n.referer,utmParams:n.utmParams,clickIds:n.clickIds,appOrigin:n.origin,landingPath:n.landingPath})),n.persona?{persona:n.persona}:{});try{let v=await D(`${n.baseUrl}/sessions`,{method:"POST",headers:c,body:JSON.stringify(m)},i);if(!v.ok){let y=await v.json().catch(()=>({}));console.error(`[SentientUI] preloadDecisions: session upsert failed (${v.status})`,y)}}catch(v){console.error("[SentientUI] preloadDecisions: session upsert threw",v)}try{let v=await D(`${n.baseUrl}/decide`,{method:"POST",headers:c,body:JSON.stringify(u(u(u(u({sessionId:t,sections:((h=e.sections)!=null?h:[]).map(w=>({id:w})),components:e.components},r.length>0?{slots:r.map(B)}:{}),s!==null?{slotsFrom:"registry",registrySlotIds:s,bootstrap:!1,render:Object.fromEntries(s.map(w=>{var P,q;return[w,(q=(P=e.renderCaps)==null?void 0:P[w])!=null?q:{forms:!0,compose:!0,ops:!1}]}))}:{}),n.persona?{persona:n.persona}:{}),e.unifiedCaps?{caps:{unified:!0}}:{}))},i);if(!v.ok){let w=await v.json().catch(()=>({}));return console.error(`[SentientUI] preloadDecisions: decide failed (${v.status})`,w),o}let y=await v.json(),k={};for(let w of r)k[w.id]=(p=(x=y.slots)==null?void 0:x[w.id])!=null?p:G(w);for(let[w,P]of Object.entries((b=y.slots)!=null?b:{}))w in k||(k[w]=P);let le=y.slotConfig!==void 0&&typeof y.slotConfig=="object"&&y.slotConfig!==null&&!Array.isArray(y.slotConfig);return u(u(u(u(u(u({layoutOrder:(A=(S=y.layoutOrder)!=null?S:e.sections)!=null?A:[],assignments:(g=y.assignments)!=null?g:{},slots:k,persona:(f=y.persona)!=null?f:"unknown",confidence:(I=y.confidence)!=null?I:0},le?{slotConfig:y.slotConfig}:{}),y.palette?{palette:y.palette}:{}),y.vocabulary?{vocabulary:y.vocabulary}:{}),typeof y.stage=="string"?{stage:y.stage}:{}),typeof y.context=="string"?{context:y.context}:{}),e.unifiedCaps&&Array.isArray(y.unified)?{unified:y.unified.filter(w=>typeof w=="string")}:{})}catch(v){return console.error("[SentientUI] preloadDecisions: decide threw",v),o}}var K="3d8f5a21-7c64-4b19-8e0a-5f2c91d7b6e3";function we(e){let t=(x,p)=>x<<p|x>>>32-p,n=e.length,i=new Uint8Array((n+8>>6)*64+64);i.set(e),i[n]=128;let r=new DataView(i.buffer);r.setUint32(i.length-8,Math.floor(n*8/4294967296)),r.setUint32(i.length-4,n*8>>>0);let s=1732584193,o=4023233417,c=2562383102,m=271733878,d=3285377520,a=new Array(80);for(let x=0;x<i.length;x+=64){for(let f=0;f<16;f++)a[f]=r.getUint32(x+f*4);for(let f=16;f<80;f++)a[f]=t(a[f-3]^a[f-8]^a[f-14]^a[f-16],1);let p=s,b=o,S=c,A=m,g=d;for(let f=0;f<80;f++){let[I,v]=f<20?[b&S|~b&A,1518500249]:f<40?[b^S^A,1859775393]:f<60?[b&S|b&A|S&A,2400959708]:[b^S^A,3395469782],y=t(p,5)+I+g+v+a[f]|0;g=A,A=S,S=t(b,30),b=p,p=y}s=s+p|0,o=o+b|0,c=c+S|0,m=m+A|0,d=d+g|0}let l=new Uint8Array(20),h=new DataView(l.buffer);return[s,o,c,m,d].forEach((x,p)=>h.setUint32(p*4,x>>>0)),l}async function ve(e,t){var d;let n=t.replace(/-/g,""),i=new Uint8Array(16);for(let a=0;a<16;a++)i[a]=parseInt(n.slice(a*2,a*2+2),16);let r=new TextEncoder().encode(e),s=new Uint8Array(16+r.length);s.set(i,0),s.set(r,16);let o=(d=globalThis.crypto)==null?void 0:d.subtle,c=(o?new Uint8Array(await o.digest("SHA-1",s)):we(s)).slice(0,16);c[6]=c[6]&15|80,c[8]=c[8]&63|128;let m=Array.from(c,a=>a.toString(16).padStart(2,"0")).join("");return`${m.slice(0,8)}-${m.slice(8,12)}-${m.slice(12,16)}-${m.slice(16,20)}-${m.slice(20,32)}`}var Ie=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]);function N(e){let t=e.length*8,n=new Uint8Array(Math.ceil((e.length+9)/64)*64);n.set(e),n[e.length]=128;let i=new DataView(n.buffer);i.setUint32(n.length-8,Math.floor(t/4294967296)),i.setUint32(n.length-4,t>>>0);let r=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),s=new Uint32Array(64),o=(d,a)=>d>>>a|d<<32-a;for(let d=0;d<n.length;d+=64){for(let g=0;g<16;g++)s[g]=i.getUint32(d+g*4);for(let g=16;g<64;g++){let f=o(s[g-15],7)^o(s[g-15],18)^s[g-15]>>>3,I=o(s[g-2],17)^o(s[g-2],19)^s[g-2]>>>10;s[g]=s[g-16]+f+s[g-7]+I|0}let[a,l,h,x,p,b,S,A]=[r[0],r[1],r[2],r[3],r[4],r[5],r[6],r[7]];for(let g=0;g<64;g++){let f=A+(o(p,6)^o(p,11)^o(p,25))+(p&b^~p&S)+Ie[g]+s[g]|0,I=(o(a,2)^o(a,13)^o(a,22))+(a&l^a&h^l&h)|0;A=S,S=b,b=p,p=x+f|0,x=h,h=l,l=a,a=f+I|0}r[0]=r[0]+a|0,r[1]=r[1]+l|0,r[2]=r[2]+h|0,r[3]=r[3]+x|0,r[4]=r[4]+p|0,r[5]=r[5]+b|0,r[6]=r[6]+S|0,r[7]=r[7]+A|0}let c=new Uint8Array(32),m=new DataView(c.buffer);return r.forEach((d,a)=>m.setUint32(a*4,d)),c}function Ue(e,t){let n=new Uint8Array(64);n.set(e.length>64?N(e):e);let i=new Uint8Array(64+t.length),r=new Uint8Array(96);for(let s=0;s<64;s++)i[s]=n[s]^54,r[s]=n[s]^92;return i.set(t,64),r.set(N(i),64),N(r)}async function ee(e,t){var c;let n=new TextEncoder,i=n.encode(e),r=n.encode(t),s=(c=globalThis.crypto)==null?void 0:c.subtle,o=s?new Uint8Array(await s.sign("HMAC",await s.importKey("raw",i,{name:"HMAC",hash:"SHA-256"},!1,["sign"]),r)):Ue(i,r);return Array.from(o,m=>m.toString(16).padStart(2,"0")).join("")}async function oe(e,t,n){var s,o;if(typeof window!="undefined")return console.error("[SentientUI] signUserId is server-only: it needs the secret key. Compute the hash on your server and pass it to identify()."),"";let i=Math.floor(((s=n==null?void 0:n.now)!=null?s:Date.now())/1e3)+Math.min((o=n==null?void 0:n.ttlSeconds)!=null?o:86400,7*86400),r=await ee(t,"sentient-identity-v1");return`v1.${i}.${await ee(r,`${e}.${i}`)}`}var Re="https://api.sentient-ui.com/v1",Ce=5e3;async function ae(e){var s,o;if(typeof window!="undefined")return console.error("[SentientUI] trackServerGoal is server-only: the secret key was not sent. Call it from a route handler, server action or webhook."),"failed";let t=e.sessionId?null:e.userId||null;if(!e.sessionId&&!t)return"skipped_no_visitor";if(e.name.includes(":"))return console.error('[SentientUI] trackServerGoal: goal names cannot contain ":" (nothing was sent).'),"failed";let n=(s=e.fetch)!=null?s:fetch,i=new AbortController,r;try{let c=new Promise((a,l)=>{var h;r=setTimeout(()=>{i.abort(),l(new Error("timeout"))},(h=e.timeoutMs)!=null?h:Ce)});c.catch(()=>{});let m=await ve(t===null?`${e.sessionId}:${e.name}:${e.dedupeKey}`:`user:${e.serverKey}:${t}:${e.name}:${e.dedupeKey}`,K),d=await Promise.race([n(`${((o=e.apiBaseUrl)!=null?o:Re).replace(/\/+$/,"")}/goals`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e.serverKey}`},body:JSON.stringify(u(u(u(R(u({},t===null?{sessionId:e.sessionId}:{userId:t}),{name:e.name,goalId:m,externalId:e.dedupeKey}),e.value!==void 0?{value:e.value}:{}),e.currency!==void 0?{currency:e.currency}:{}),e.metadata!==void 0?{metadata:e.metadata}:{})),signal:i.signal}),c]);return d.ok?"recorded":t!==null&&d.status===404?(process.env.NODE_ENV!=="production"&&console.warn(`[SentientUI] trackServerGoal: no visit is linked to userId "${t}" yet, so "${e.name}" was not recorded. Identify the visitor in the browser first (<AdaptiveRoot userId>, or identify(userId, { userHash })) \u2014 once a project signs its identifies, only signed visits count.`),"skipped_no_visitor"):"failed"}catch(c){return"failed"}finally{r&&clearTimeout(r)}}var ke="https://api.sentient-ui.com/v1";function Pe(e){try{return new URL(e,"http://localhost").pathname||"/"}catch(t){return e.split(/[?#]/,1)[0]||"/"}}function V(e,t){var i,r,s,o;let n=(i=t.fetchImpl)!=null?i:typeof fetch=="function"?fetch:void 0;if(!(!n||!t.apiKey))try{let c=n(`${(r=t.baseUrl)!=null?r:ke}/crawler-events`,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${t.apiKey}`},body:JSON.stringify({path:e.path,botName:e.botName,userAgent:e.userAgent,source:(s=t.source)!=null?s:"middleware"})}).catch(()=>{});(o=t.waitUntil)==null||o.call(t,c)}catch(c){}}function H(e,t){var r;let n="";try{n=(r=e.headers.get("user-agent"))!=null?r:""}catch(s){return!1}let i=E(n);return i?(V({path:Pe(e.url),userAgent:n,botName:i},t),!0):!1}function ce(e){return(t,n,i)=>{var r,s,o;try{let c=t.headers["user-agent"],m=Array.isArray(c)?(r=c[0])!=null?r:"":c!=null?c:"";H({url:(o=(s=t.originalUrl)!=null?s:t.url)!=null?o:"/",headers:{get:d=>d.toLowerCase()==="user-agent"?m:null}},R(u({},e),{source:"middleware"}))}catch(c){}i()}}0&&(module.exports={CLICK_ID_KEYS,SERVER_GOAL_NAMESPACE,buildSessionUpsertPayload,captureAgentRequest,deriveSessionSegment,detectDeviceClass,detectTimeOfDay,detectTrafficSource,extractTrackedParams,postAgentFetch,preloadAssignments,preloadAssignmentsDetailed,preloadDecisions,readSessionCookie,referrerDomainFromReferer,sentientAgentMiddleware,signUserId,trackServerGoal});
|
|
2
2
|
//# sourceMappingURL=index-server.js.map
|