@sentientui/core 0.38.0 → 0.39.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +43 -1
- package/dist/{chunk-NCLBL5V3.mjs → chunk-EVF5PQ4U.mjs} +1 -1
- package/dist/{chunk-NCLBL5V3.mjs.map → chunk-EVF5PQ4U.mjs.map} +1 -1
- package/dist/chunk-QEIHHO3T.mjs +2 -0
- package/dist/chunk-QEIHHO3T.mjs.map +1 -0
- package/dist/{index-BdpO3Qlm.d.cts → index-BAfi7_FG.d.cts} +60 -5
- package/dist/{index-DzGhQhSK.d.ts → index-DyKtujwf.d.ts} +60 -5
- 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-graph.d.cts +5 -5
- package/dist/index-graph.d.ts +5 -5
- 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 +3 -3
- package/dist/index-local.d.ts +3 -3
- package/dist/index-region.d.cts +1 -1
- package/dist/index-region.d.ts +1 -1
- package/dist/index-region.mjs +1 -1
- package/dist/index-server.d.cts +73 -5
- package/dist/index-server.d.ts +73 -5
- 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 +3 -3
- package/dist/index.d.ts +3 -3
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1 -1
- package/dist/{region-skeleton-D2ahkcbe.d.cts → region-skeleton-BRIVB-qf.d.cts} +1 -0
- package/dist/{region-skeleton-D2ahkcbe.d.ts → region-skeleton-BRIVB-qf.d.ts} +1 -0
- package/dist/{session-meta-CvEwPQCX.d.ts → session-meta-BtRtwsHI.d.ts} +1 -1
- package/dist/{session-meta-USVMwvsR.d.cts → session-meta-qx4kIL5y.d.cts} +1 -1
- package/package.json +1 -1
- package/dist/chunk-VLFWHJNJ.mjs +0 -2
- package/dist/chunk-VLFWHJNJ.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 Ve,B as Ye,C as We,D as Je,E as Xe,F as Qe,G as Ze,H as et,I as tt,M as se,N as M,O as P,P as ae,R as D,d as ne,e as oe,f as re,k as Oe,l as Me,m as Pe,n as De,o as Ge,p as ke,q as $e,r as Le,s as je,t as Ue,u as Ke,v as Fe,w as Be,x as qe,y as ze,z as He}from"./chunk-VLFWHJNJ.mjs";import{a as B,b as q,c as z,d as H}from"./chunk-XZRKD2GS.mjs";import"./chunk-NCLBL5V3.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-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};
|
|
2
2
|
//# sourceMappingURL=index-graph.mjs.map
|
package/dist/index-local.d.cts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { e as SlotDeclInput } from './session-meta-
|
|
1
|
+
import { f as DecideOutcome } from './index-BAfi7_FG.cjs';
|
|
2
|
+
import { e as SlotDeclInput } from './session-meta-qx4kIL5y.cjs';
|
|
3
3
|
import './style-vocabulary-Ba_g6_DD.cjs';
|
|
4
|
-
import './region-skeleton-
|
|
4
|
+
import './region-skeleton-BRIVB-qf.cjs';
|
|
5
5
|
import './index-consent.cjs';
|
|
6
6
|
import '@sentientui/policy';
|
|
7
7
|
|
package/dist/index-local.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { e as SlotDeclInput } from './session-meta-
|
|
1
|
+
import { f as DecideOutcome } from './index-DyKtujwf.js';
|
|
2
|
+
import { e as SlotDeclInput } from './session-meta-BtRtwsHI.js';
|
|
3
3
|
import './style-vocabulary-Ba_g6_DD.js';
|
|
4
|
-
import './region-skeleton-
|
|
4
|
+
import './region-skeleton-BRIVB-qf.js';
|
|
5
5
|
import './index-consent.js';
|
|
6
6
|
import '@sentientui/policy';
|
|
7
7
|
|
package/dist/index-region.d.cts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { R as RegionSkeleton } from './region-skeleton-
|
|
1
|
+
import { R as RegionSkeleton } from './region-skeleton-BRIVB-qf.cjs';
|
|
2
2
|
|
|
3
3
|
declare function normalizeLeafText(s: string): string;
|
|
4
4
|
/** 16 hex chars over the normalized leaf texts. Text-only on purpose: React
|
package/dist/index-region.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { R as RegionSkeleton } from './region-skeleton-
|
|
1
|
+
import { R as RegionSkeleton } from './region-skeleton-BRIVB-qf.js';
|
|
2
2
|
|
|
3
3
|
declare function normalizeLeafText(s: string): string;
|
|
4
4
|
/** 16 hex chars over the normalized leaf texts. Text-only on purpose: React
|
package/dist/index-region.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{a as R,b as M,c as V}from"./chunk-
|
|
1
|
+
import{a as R,b as M,c as V}from"./chunk-EVF5PQ4U.mjs";import{a as E,b as y}from"./chunk-G6VP7HGJ.mjs";import{a as p,b}from"./chunk-TMCGHANO.mjs";function k(e){return e.replace(/\s+/g," ").trim().slice(0,300)}function D(e,o){let n=o>>>0;for(let t=0;t<e.length;t++)n^=e.charCodeAt(t),n=Math.imul(n,16777619)>>>0;return n.toString(16).padStart(8,"0")}function S(e){let o=e.join("");return D(o,2166136261)+D(o,1523705862)}var $=new Set(["A","BUTTON"]),O=/^H([1-6])$/,F=new Set(["P","LI","LABEL","BLOCKQUOTE","FIGCAPTION","DT","DD","TD","TH"]),H=new Set(["LABEL","FIGCAPTION","DT"]),U=new Set(["SCRIPT","STYLE","TEMPLATE","NOSCRIPT"]);function C(e){return $.has(e.tagName)||e.getAttribute("role")==="button"?!0:e.tagName==="INPUT"&&/^(submit|button)$/i.test(e.type)}function X(e){if(O.test(e.tagName)||F.has(e.tagName))return!0;let o=e.ownerDocument.defaultView,n=o?o.getComputedStyle(e).display:"";return n!==""&&n!=="inline"&&n!=="contents"}function j(e,o){let n=null;for(let t=e.parentElement;t&&t!==o.parentElement;t=t.parentElement){if(C(t)){n=t;break}if(t===o)break}if(n)return n;for(let t=e.parentElement;t;t=t.parentElement)if(t===o||X(t))return t;return o}function _(e,o){var n,t;if(e)try{let r=new URL(e,(t=(n=o.location)==null?void 0:n.href)!=null?t:"https://relative.invalid/");return r.protocol!=="https:"&&r.protocol!=="http:"?void 0:o.location&&r.origin===o.location.origin?r.pathname:`${r.origin}${r.pathname}`}catch(r){return}}function I(e){return e===""||e==="transparent"||/rgba\([^)]*,\s*0\)$/.test(e)}function z(e){let o=e.ownerDocument,n=o.defaultView;if(!n)return{bg:null};for(let t=e;t;t=t.parentElement){let r=n.getComputedStyle(t),l=y(r.backgroundImage,o);if(l.length>0)return p({bg:l[0]},l.length>1?{alt:l[l.length-1]}:{});let s=E(r.backgroundColor,o);if(!I(s))return{bg:s}}return{bg:null}}function B(e,o=40){var f,i,d;let n=e.ownerDocument.createTreeWalker(e,4),t=[];for(let a=n.nextNode();a;a=n.nextNode())if(((f=a.nodeValue)!=null?f:"").trim()!==""&&!U.has((d=(i=a.parentElement)==null?void 0:i.tagName)!=null?d:"")&&(t.push(a),t.length>120))return{reason:"too_large"};if(t.length===0)return{reason:"empty"};let r=[],l=[];for(let a of t){let u=j(a,e),g=r.indexOf(u);g===-1&&(r.push(u),g=r.length-1),l.push(g)}if(r.length>o)return{reason:"too_large"};let s=t.map(a=>{var u;return k((u=a.nodeValue)!=null?u:"")});return{textNodes:t,ownerEls:r,leafToNode:l,leaves:s,fp:S(s)}}function P(e,o=40){var h;let n=B(e,o);if(!("fp"in n))return{skeleton:null,reason:n.reason};let{textNodes:t,ownerEls:r,leafToNode:l,leaves:s}=n,f=e.ownerDocument,i=f.defaultView,d=[],a=r.map((c,v)=>{var w,L;let m=i==null?void 0:i.getComputedStyle(c),x=(w=c.parentElement)!=null?w:e,T=d.indexOf(x);T===-1&&(d.push(x),T=d.length-1);let N=O.exec(c.tagName),A=C(c)?"action":N?"heading":H.has(c.tagName)?"label":"text",G=k(s.filter((Y,K)=>l[K]===v).join(" "));return b(p(b(p({tag:c.tagName.toLowerCase(),role:A},N?{level:Number(N[1])}:{}),{text:G,classes:((L=c.getAttribute("class"))!=null?L:"").replace(/\s+/g," ").trim()}),A==="action"?p({filled:!!m&&(!I(E(m.backgroundColor,e.ownerDocument))||m.backgroundImage!==""&&m.backgroundImage!=="none")},_(c.getAttribute("href"),f)!==void 0?{href:_(c.getAttribute("href"),f)}:{}):{}),{color:E(m==null?void 0:m.color,e.ownerDocument),group:T,restylable:!0})}),u=z(e),g=i==null?void 0:i.getComputedStyle(e);return{skeleton:{v:1,root:b(p({tag:e.tagName.toLowerCase(),classes:((h=e.getAttribute("class"))!=null?h:"").replace(/\s+/g," ").trim(),ambientBg:u.bg},u.alt?{ambientBgAlt:u.alt}:{}),{ambientText:E(g==null?void 0:g.color,e.ownerDocument)}),nodes:a,leaves:s,leafToNode:l,fp:S(s)},textNodes:t,ownerEls:r}}function Q(e,o){try{let n=P(e,o==null?void 0:o.maxNodes);return n.skeleton?{skeleton:n.skeleton}:n}catch(n){return{skeleton:null,reason:"unaddressable"}}}export{P as captureRegionDom,Q as captureRegionSkeleton,k as normalizeLeafText,B as regionAddress,S as skeletonFingerprint};
|
|
2
2
|
//# sourceMappingURL=index-region.mjs.map
|
package/dist/index-server.d.cts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
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-
|
|
4
|
-
import { c as RenderCaps } from './region-skeleton-
|
|
2
|
+
import { d as SlotConfigEntry, e as SlotDeclInput } from './session-meta-qx4kIL5y.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-qx4kIL5y.cjs';
|
|
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';
|
|
7
7
|
|
|
@@ -75,6 +75,12 @@ type ServerAssignConfig = {
|
|
|
75
75
|
};
|
|
76
76
|
/** componentId → assigned variantId */
|
|
77
77
|
type ServerAssignments = Record<string, string>;
|
|
78
|
+
/** `preloadAssignmentsDetailed`'s answer: the assignments, plus the ids the
|
|
79
|
+
* server handed back as moved to the shared track (only when asked). */
|
|
80
|
+
type ServerAssignmentsDetailed = {
|
|
81
|
+
assignments: ServerAssignments;
|
|
82
|
+
unified: string[];
|
|
83
|
+
};
|
|
78
84
|
/**
|
|
79
85
|
* Fetches variant assignments server-side for all listed components.
|
|
80
86
|
* Returns a map suitable for passing as `initialAssignments` to `<AdaptiveProvider>`.
|
|
@@ -98,6 +104,20 @@ declare function preloadAssignments(components: Array<{
|
|
|
98
104
|
id: string;
|
|
99
105
|
variantIds: string[];
|
|
100
106
|
}>, sessionId: string, config: ServerAssignConfig): Promise<ServerAssignments>;
|
|
107
|
+
/**
|
|
108
|
+
* `preloadAssignments`, and also which components were moved onto the shared
|
|
109
|
+
* track. With `opts.unified` each assign says the page can follow such a move:
|
|
110
|
+
* a moved id is then not assigned (nothing is recorded for it) and comes back
|
|
111
|
+
* in `unified`, for the page to render as a slot. Pass those ids to
|
|
112
|
+
* `<AdaptiveProvider initialUnified>`. Without it a moved id is served its
|
|
113
|
+
* frozen result read-only, as for any older SDK.
|
|
114
|
+
*/
|
|
115
|
+
declare function preloadAssignmentsDetailed(components: Array<{
|
|
116
|
+
id: string;
|
|
117
|
+
variantIds: string[];
|
|
118
|
+
}>, sessionId: string, config: ServerAssignConfig, opts?: {
|
|
119
|
+
unified?: boolean;
|
|
120
|
+
}): Promise<ServerAssignmentsDetailed>;
|
|
101
121
|
/**
|
|
102
122
|
* Reads the Sentient session cookie from a Next.js `ReadonlyRequestCookies` object
|
|
103
123
|
* (the return value of `cookies()` from `next/headers`), or any object with a
|
|
@@ -133,6 +153,9 @@ type DecideResult = {
|
|
|
133
153
|
stage?: string;
|
|
134
154
|
/** The visit's serving context. Never for the page. */
|
|
135
155
|
context?: string;
|
|
156
|
+
/** Requested components moved onto the shared track (only with
|
|
157
|
+
* `unifiedCaps`): not in `assignments`; render each as a slot. */
|
|
158
|
+
unified?: string[];
|
|
136
159
|
};
|
|
137
160
|
/**
|
|
138
161
|
* Single-roundtrip SSR call returning layout order, component assignments,
|
|
@@ -168,10 +191,55 @@ declare function preloadDecisions(params: {
|
|
|
168
191
|
* is assumed to match; a real mismatch is reported from the browser as
|
|
169
192
|
* drift. Declare `forms: false` for slots without an `onFormSubmit`, or a
|
|
170
193
|
* form arm can be drawn that this page will refuse. Default per slot:
|
|
171
|
-
* `{ forms: true, compose: true }`.
|
|
194
|
+
* `{ forms: true, compose: true, ops: false }`.
|
|
172
195
|
*/
|
|
173
196
|
renderCaps?: Record<string, Omit<RenderCaps, 'fp'>>;
|
|
197
|
+
/** The page renders a moved (unified) component on the shared track: such
|
|
198
|
+
* ids in `components` come back in `unified` instead of `assignments`,
|
|
199
|
+
* with nothing recorded. Without it they are served the frozen result. */
|
|
200
|
+
unifiedCaps?: boolean;
|
|
174
201
|
}, sessionId: string, config: ServerAssignConfig): Promise<DecideResult>;
|
|
202
|
+
/**
|
|
203
|
+
* Fixed namespace for server-goal ids. It is public (it ships in this file), so
|
|
204
|
+
* it adds no secrecy: the id's uniqueness comes from the session id it hashes
|
|
205
|
+
* (see trackServerGoal). Never change it: a retried delivery must map to the
|
|
206
|
+
* same goal id.
|
|
207
|
+
*/
|
|
208
|
+
declare const SERVER_GOAL_NAMESPACE = "3d8f5a21-7c64-4b19-8e0a-5f2c91d7b6e3";
|
|
209
|
+
type TrackServerGoalOptions = {
|
|
210
|
+
/** Project SECRET key (sk_...), from a server-only env var. */
|
|
211
|
+
serverKey: string;
|
|
212
|
+
/** The visitor's session id: `readSessionCookie(cookies, apiKey)` in the same
|
|
213
|
+
* request, or the id you stored from `client.getVisitorId()`. Null/empty
|
|
214
|
+
* means nobody to credit: nothing is sent. */
|
|
215
|
+
sessionId: string | null | undefined;
|
|
216
|
+
/** Goal name, as defined in your project (e.g. 'purchase'). */
|
|
217
|
+
name: string;
|
|
218
|
+
/** Your own id for this conversion (order id, Stripe event id, user id).
|
|
219
|
+
* Calling again with the same session + name + dedupeKey counts once. */
|
|
220
|
+
dedupeKey: string;
|
|
221
|
+
value?: number;
|
|
222
|
+
currency?: string;
|
|
223
|
+
metadata?: Record<string, unknown>;
|
|
224
|
+
/** API base including `/v1`. Defaults to the hosted API. */
|
|
225
|
+
apiBaseUrl?: string;
|
|
226
|
+
fetch?: typeof fetch;
|
|
227
|
+
/** Give up after this many ms. Default 5000. */
|
|
228
|
+
timeoutMs?: number;
|
|
229
|
+
};
|
|
230
|
+
/**
|
|
231
|
+
* Records a conversion from your server (route handler, server action,
|
|
232
|
+
* webhook). Never throws; resolves 'recorded', 'skipped_no_visitor' (no
|
|
233
|
+
* session to credit, nothing sent) or 'failed'.
|
|
234
|
+
*
|
|
235
|
+
* Hand-rolling this (cookie, deterministic id, sk_ call) was the only way to
|
|
236
|
+
* count a webhook-confirmed conversion, and few customers would get the dedupe
|
|
237
|
+
* right: a random goal id per attempt counts a retried webhook twice. The id
|
|
238
|
+
* here is derived from session + name + dedupeKey, so replays collapse
|
|
239
|
+
* server-side; dedupeKey is also sent as externalId, which the API dedupes per
|
|
240
|
+
* (project, goal name) on its own.
|
|
241
|
+
*/
|
|
242
|
+
declare function trackServerGoal(opts: TrackServerGoalOptions): Promise<'recorded' | 'skipped_no_visitor' | 'failed'>;
|
|
175
243
|
|
|
176
244
|
type AgentCaptureOptions = {
|
|
177
245
|
/** Your public `pk_` key — the same one the snippet uses. */
|
|
@@ -231,4 +299,4 @@ type ConnectRequest = {
|
|
|
231
299
|
*/
|
|
232
300
|
declare function sentientAgentMiddleware(opts: Omit<AgentCaptureOptions, 'waitUntil' | 'source'>): (req: ConnectRequest, res: unknown, next: (err?: unknown) => void) => void;
|
|
233
301
|
|
|
234
|
-
export { type AgentCaptureOptions, type CapturableRequest, type DecideResult, type ServerAssignConfig, type ServerAssignments, SlotDeclInput, captureAgentRequest, postAgentFetch, preloadAssignments, preloadDecisions, readSessionCookie, sentientAgentMiddleware };
|
|
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 };
|
package/dist/index-server.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
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-
|
|
4
|
-
import { c as RenderCaps } from './region-skeleton-
|
|
2
|
+
import { d as SlotConfigEntry, e as SlotDeclInput } from './session-meta-BtRtwsHI.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-BtRtwsHI.js';
|
|
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';
|
|
7
7
|
|
|
@@ -75,6 +75,12 @@ type ServerAssignConfig = {
|
|
|
75
75
|
};
|
|
76
76
|
/** componentId → assigned variantId */
|
|
77
77
|
type ServerAssignments = Record<string, string>;
|
|
78
|
+
/** `preloadAssignmentsDetailed`'s answer: the assignments, plus the ids the
|
|
79
|
+
* server handed back as moved to the shared track (only when asked). */
|
|
80
|
+
type ServerAssignmentsDetailed = {
|
|
81
|
+
assignments: ServerAssignments;
|
|
82
|
+
unified: string[];
|
|
83
|
+
};
|
|
78
84
|
/**
|
|
79
85
|
* Fetches variant assignments server-side for all listed components.
|
|
80
86
|
* Returns a map suitable for passing as `initialAssignments` to `<AdaptiveProvider>`.
|
|
@@ -98,6 +104,20 @@ declare function preloadAssignments(components: Array<{
|
|
|
98
104
|
id: string;
|
|
99
105
|
variantIds: string[];
|
|
100
106
|
}>, sessionId: string, config: ServerAssignConfig): Promise<ServerAssignments>;
|
|
107
|
+
/**
|
|
108
|
+
* `preloadAssignments`, and also which components were moved onto the shared
|
|
109
|
+
* track. With `opts.unified` each assign says the page can follow such a move:
|
|
110
|
+
* a moved id is then not assigned (nothing is recorded for it) and comes back
|
|
111
|
+
* in `unified`, for the page to render as a slot. Pass those ids to
|
|
112
|
+
* `<AdaptiveProvider initialUnified>`. Without it a moved id is served its
|
|
113
|
+
* frozen result read-only, as for any older SDK.
|
|
114
|
+
*/
|
|
115
|
+
declare function preloadAssignmentsDetailed(components: Array<{
|
|
116
|
+
id: string;
|
|
117
|
+
variantIds: string[];
|
|
118
|
+
}>, sessionId: string, config: ServerAssignConfig, opts?: {
|
|
119
|
+
unified?: boolean;
|
|
120
|
+
}): Promise<ServerAssignmentsDetailed>;
|
|
101
121
|
/**
|
|
102
122
|
* Reads the Sentient session cookie from a Next.js `ReadonlyRequestCookies` object
|
|
103
123
|
* (the return value of `cookies()` from `next/headers`), or any object with a
|
|
@@ -133,6 +153,9 @@ type DecideResult = {
|
|
|
133
153
|
stage?: string;
|
|
134
154
|
/** The visit's serving context. Never for the page. */
|
|
135
155
|
context?: string;
|
|
156
|
+
/** Requested components moved onto the shared track (only with
|
|
157
|
+
* `unifiedCaps`): not in `assignments`; render each as a slot. */
|
|
158
|
+
unified?: string[];
|
|
136
159
|
};
|
|
137
160
|
/**
|
|
138
161
|
* Single-roundtrip SSR call returning layout order, component assignments,
|
|
@@ -168,10 +191,55 @@ declare function preloadDecisions(params: {
|
|
|
168
191
|
* is assumed to match; a real mismatch is reported from the browser as
|
|
169
192
|
* drift. Declare `forms: false` for slots without an `onFormSubmit`, or a
|
|
170
193
|
* form arm can be drawn that this page will refuse. Default per slot:
|
|
171
|
-
* `{ forms: true, compose: true }`.
|
|
194
|
+
* `{ forms: true, compose: true, ops: false }`.
|
|
172
195
|
*/
|
|
173
196
|
renderCaps?: Record<string, Omit<RenderCaps, 'fp'>>;
|
|
197
|
+
/** The page renders a moved (unified) component on the shared track: such
|
|
198
|
+
* ids in `components` come back in `unified` instead of `assignments`,
|
|
199
|
+
* with nothing recorded. Without it they are served the frozen result. */
|
|
200
|
+
unifiedCaps?: boolean;
|
|
174
201
|
}, sessionId: string, config: ServerAssignConfig): Promise<DecideResult>;
|
|
202
|
+
/**
|
|
203
|
+
* Fixed namespace for server-goal ids. It is public (it ships in this file), so
|
|
204
|
+
* it adds no secrecy: the id's uniqueness comes from the session id it hashes
|
|
205
|
+
* (see trackServerGoal). Never change it: a retried delivery must map to the
|
|
206
|
+
* same goal id.
|
|
207
|
+
*/
|
|
208
|
+
declare const SERVER_GOAL_NAMESPACE = "3d8f5a21-7c64-4b19-8e0a-5f2c91d7b6e3";
|
|
209
|
+
type TrackServerGoalOptions = {
|
|
210
|
+
/** Project SECRET key (sk_...), from a server-only env var. */
|
|
211
|
+
serverKey: string;
|
|
212
|
+
/** The visitor's session id: `readSessionCookie(cookies, apiKey)` in the same
|
|
213
|
+
* request, or the id you stored from `client.getVisitorId()`. Null/empty
|
|
214
|
+
* means nobody to credit: nothing is sent. */
|
|
215
|
+
sessionId: string | null | undefined;
|
|
216
|
+
/** Goal name, as defined in your project (e.g. 'purchase'). */
|
|
217
|
+
name: string;
|
|
218
|
+
/** Your own id for this conversion (order id, Stripe event id, user id).
|
|
219
|
+
* Calling again with the same session + name + dedupeKey counts once. */
|
|
220
|
+
dedupeKey: string;
|
|
221
|
+
value?: number;
|
|
222
|
+
currency?: string;
|
|
223
|
+
metadata?: Record<string, unknown>;
|
|
224
|
+
/** API base including `/v1`. Defaults to the hosted API. */
|
|
225
|
+
apiBaseUrl?: string;
|
|
226
|
+
fetch?: typeof fetch;
|
|
227
|
+
/** Give up after this many ms. Default 5000. */
|
|
228
|
+
timeoutMs?: number;
|
|
229
|
+
};
|
|
230
|
+
/**
|
|
231
|
+
* Records a conversion from your server (route handler, server action,
|
|
232
|
+
* webhook). Never throws; resolves 'recorded', 'skipped_no_visitor' (no
|
|
233
|
+
* session to credit, nothing sent) or 'failed'.
|
|
234
|
+
*
|
|
235
|
+
* Hand-rolling this (cookie, deterministic id, sk_ call) was the only way to
|
|
236
|
+
* count a webhook-confirmed conversion, and few customers would get the dedupe
|
|
237
|
+
* right: a random goal id per attempt counts a retried webhook twice. The id
|
|
238
|
+
* here is derived from session + name + dedupeKey, so replays collapse
|
|
239
|
+
* server-side; dedupeKey is also sent as externalId, which the API dedupes per
|
|
240
|
+
* (project, goal name) on its own.
|
|
241
|
+
*/
|
|
242
|
+
declare function trackServerGoal(opts: TrackServerGoalOptions): Promise<'recorded' | 'skipped_no_visitor' | 'failed'>;
|
|
175
243
|
|
|
176
244
|
type AgentCaptureOptions = {
|
|
177
245
|
/** Your public `pk_` key — the same one the snippet uses. */
|
|
@@ -231,4 +299,4 @@ type ConnectRequest = {
|
|
|
231
299
|
*/
|
|
232
300
|
declare function sentientAgentMiddleware(opts: Omit<AgentCaptureOptions, 'waitUntil' | 'source'>): (req: ConnectRequest, res: unknown, next: (err?: unknown) => void) => void;
|
|
233
301
|
|
|
234
|
-
export { type AgentCaptureOptions, type CapturableRequest, type DecideResult, type ServerAssignConfig, type ServerAssignments, SlotDeclInput, captureAgentRequest, postAgentFetch, preloadAssignments, preloadDecisions, readSessionCookie, sentientAgentMiddleware };
|
|
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 };
|
package/dist/index-server.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var C=Object.defineProperty,se=Object.defineProperties,ie=Object.getOwnPropertyDescriptor,oe=Object.getOwnPropertyDescriptors,ae=Object.getOwnPropertyNames,q=Object.getOwnPropertySymbols;var J=Object.prototype.hasOwnProperty,le=Object.prototype.propertyIsEnumerable;var W=(t,e,r)=>e in t?C(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,a=(t,e)=>{for(var r in e||(e={}))J.call(e,r)&&W(t,r,e[r]);if(q)for(var r of q(e))le.call(e,r)&&W(t,r,e[r]);return t},x=(t,e)=>se(t,oe(e));var ce=(t,e)=>{for(var r in e)C(t,r,{get:e[r],enumerable:!0})},ue=(t,e,r,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of ae(e))!J.call(t,n)&&n!==r&&C(t,n,{get:()=>e[n],enumerable:!(s=ie(e,n))||s.enumerable});return t};var de=t=>ue(C({},"__esModule",{value:!0}),t);var Se={};ce(Se,{CLICK_ID_KEYS:()=>O,buildSessionUpsertPayload:()=>h,captureAgentRequest:()=>j,deriveSessionSegment:()=>z,detectDeviceClass:()=>P,detectTimeOfDay:()=>U,detectTrafficSource:()=>k,extractTrackedParams:()=>Y,postAgentFetch:()=>_,preloadAssignments:()=>Z,preloadDecisions:()=>te,readSessionCookie:()=>ee,referrerDomainFromReferer:()=>v,sentientAgentMiddleware:()=>re});module.exports=de(Se);var ge=["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 fe(t){return w(t)!==null}function w(t){var r;if(!t)return null;let e=t.toLowerCase();return(r=ge.find(s=>e.includes(s.toLowerCase())))!=null?r:null}function P(t){let e=t.toLowerCase();return/ipad|tablet|playbook|kindle|silk/.test(e)?"tablet":/mobi|iphone|ipod|android.*mobile|phone/.test(e)?"mobile":"desktop"}function k(t,e){if(!t)return"direct";try{let r=new URL(t);if(e)try{if(new URL(e).host===r.host)return"direct"}catch(n){}let s=r.hostname.toLowerCase();return/(^|\.)(google|bing|duckduckgo|yahoo)\./.test(s)?"search":/(^|\.)(twitter\.com|x\.com|facebook\.com|linkedin\.com|reddit\.com|t\.co)$/.test(s)?"social":"referral"}catch(r){return"direct"}}function v(t){if(!t)return null;try{return new URL(t).hostname}catch(e){return null}}var O=["gclid","gbraid","wbraid","fbclid","ttclid","msclkid","twclid","li_fat_id"];function Y(t){let e={},r={};try{let s=typeof t=="string"||t instanceof URLSearchParams?new URLSearchParams(t):Object.entries(t).flatMap(([n,i])=>{let u=Array.isArray(i)?i[0]:i;return u===void 0?[]:[[n,u]]});for(let[n,i]of s)n.startsWith("utm_")?n in e||(e[n]=i):O.includes(n)&&(n in r||(r[n]=i))}catch(s){}return{utmParams:e,clickIds:r}}function U(t){let e=t.getHours();return e<6?"night":e<12?"morning":e<18?"afternoon":"evening"}function z(t){let e=h("__segment__",t);return`${e.deviceClass}:${e.trafficSource}`}function h(t,e){var i,u,c,p,o,m,f,y;let r=(u=(i=e==null?void 0:e.userAgent)==null?void 0:i.trim())!=null?u:"",s=(p=(c=e==null?void 0:e.referer)==null?void 0:c.trim())!=null?p:"",n=(o=e==null?void 0:e.now)!=null?o:new Date;return a({sessionId:t,ephemeral:!1,utmParams:(m=e==null?void 0:e.utmParams)!=null?m:{},clickIds:(f=e==null?void 0:e.clickIds)!=null?f:{},deviceClass:r?P(r):"desktop",trafficSource:s?k(s,e==null?void 0:e.appOrigin):"direct",referrerDomain:v(s),timeOfDay:U(n),dayOfWeek:(y=["sun","mon","tue","wed","thu","fri","sat"][n.getDay()])!=null?y:"sun",automation:(e==null?void 0:e.webdriver)===!0||fe(r)},e!=null&&e.landingPath?{landingPath:e.landingPath.split(/[?#]/)[0]}:{})}function pe(t){return t?`_${t.slice(0,12)}`:""}var D="_snt_uid";function H(t){return`${D}${pe(t)}`}var S=require("@sentientui/policy");function T(t){return a(a(a({id:t.id},t.arms?{arms:[...t.arms]}:{}),t.dims?{dims:Object.fromEntries(Object.entries(t.dims).map(([e,r])=>[e,[...r]]))}:{}),t.baseline!==void 0?{baseline:t.baseline}:{})}function E(t){let e=T(t);return(0,S.slotResultFor)(e,(0,S.slotBaselineArm)(e))}function V(t){let e={};for(let r of t)e[r.id]=E(r);return e}var me="X-Sentient-Server-Key";function X(t){let e={"Content-Type":"application/json",Authorization:`Bearer ${t.apiKey}`};return t.origin&&(e.Origin=t.origin),t.serverKey&&typeof window=="undefined"&&(e[me]=t.serverKey),e}var Q=1e3;function I(t,e,r){let s=new AbortController,n=setTimeout(()=>s.abort(),r);return fetch(t,x(a({},e),{signal:s.signal})).finally(()=>clearTimeout(n))}async function Z(t,e,r){var p;if(r.doNotTrack)return{};let s=(p=r.timeoutMs)!=null?p:Q,n=X(r),i=a(a({},h(e,{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 o=await I(`${r.baseUrl}/sessions`,{method:"POST",headers:n,body:JSON.stringify(i)},s);if(o.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(!o.ok){let m=await o.json().catch(()=>({}));console.error(`[SentientUI] preloadAssignments: session upsert failed (${o.status})`,m)}}catch(o){console.error("[SentientUI] preloadAssignments: session upsert threw",o)}let u=await Promise.allSettled(t.map(async({id:o,variantIds:m})=>{let f=await I(`${r.baseUrl}/assign`,{method:"POST",headers:n,body:JSON.stringify({sessionId:e,componentId:o,variantIds:m})},s);if(!f.ok){let b=await f.json().catch(()=>({}));return console.error(`[SentientUI] preloadAssignments: assign failed for "${o}" (${f.status})`,b),null}let y=await f.json();return{id:o,variantId:y.variantId}})),c={};for(let o of u)o.status==="fulfilled"&&o.value&&(c[o.value.id]=o.value.variantId);return c}function ee(t,e){var r,s,n,i;return(i=(n=e?(r=t.get(H(e)))==null?void 0:r.value:void 0)!=null?n:(s=t.get(D))==null?void 0:s.value)!=null?i:null}async function te(t,e,r){var o,m,f,y,b,L,M,B,N,$,F,G;let s=(o=r.timeoutMs)!=null?o:Q,n=(m=t.slots)!=null?m:[],i=null;t.slotsFrom==="registry"&&(Array.isArray(t.registrySlotIds)?i=t.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 u={layoutOrder:(f=t.sections)!=null?f:[],assignments:{},slots:V(n),persona:"unknown",confidence:0};if(r.doNotTrack)return u;let c=X(r),p=a(a({},h(e,{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 g=await I(`${r.baseUrl}/sessions`,{method:"POST",headers:c,body:JSON.stringify(p)},s);if(!g.ok){let l=await g.json().catch(()=>({}));console.error(`[SentientUI] preloadDecisions: session upsert failed (${g.status})`,l)}}catch(g){console.error("[SentientUI] preloadDecisions: session upsert threw",g)}try{let g=await I(`${r.baseUrl}/decide`,{method:"POST",headers:c,body:JSON.stringify(a(a(a({sessionId:e,sections:((y=t.sections)!=null?y:[]).map(d=>({id:d})),components:t.components},n.length>0?{slots:n.map(T)}:{}),i!==null?{slotsFrom:"registry",registrySlotIds:i,bootstrap:!1,render:Object.fromEntries(i.map(d=>{var R,K;return[d,(K=(R=t.renderCaps)==null?void 0:R[d])!=null?K:{forms:!0,compose:!0}]}))}:{}),r.persona?{persona:r.persona}:{}))},s);if(!g.ok){let d=await g.json().catch(()=>({}));return console.error(`[SentientUI] preloadDecisions: decide failed (${g.status})`,d),u}let l=await g.json(),A={};for(let d of n)A[d.id]=(L=(b=l.slots)==null?void 0:b[d.id])!=null?L:E(d);for(let[d,R]of Object.entries((M=l.slots)!=null?M:{}))d in A||(A[d]=R);let ne=l.slotConfig!==void 0&&typeof l.slotConfig=="object"&&l.slotConfig!==null&&!Array.isArray(l.slotConfig);return a(a(a(a(a({layoutOrder:(N=(B=l.layoutOrder)!=null?B:t.sections)!=null?N:[],assignments:($=l.assignments)!=null?$:{},slots:A,persona:(F=l.persona)!=null?F:"unknown",confidence:(G=l.confidence)!=null?G:0},ne?{slotConfig:l.slotConfig}:{}),l.palette?{palette:l.palette}:{}),l.vocabulary?{vocabulary:l.vocabulary}:{}),typeof l.stage=="string"?{stage:l.stage}:{}),typeof l.context=="string"?{context:l.context}:{})}catch(g){return console.error("[SentientUI] preloadDecisions: decide threw",g),u}}var ye="https://api.sentient-ui.com/v1";function he(t){try{return new URL(t,"http://localhost").pathname||"/"}catch(e){return t.split(/[?#]/,1)[0]||"/"}}function _(t,e){var s,n,i,u;let r=(s=e.fetchImpl)!=null?s:typeof fetch=="function"?fetch:void 0;if(!(!r||!e.apiKey))try{let c=r(`${(n=e.baseUrl)!=null?n:ye}/crawler-events`,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e.apiKey}`},body:JSON.stringify({path:t.path,botName:t.botName,userAgent:t.userAgent,source:(i=e.source)!=null?i:"middleware"})}).catch(()=>{});(u=e.waitUntil)==null||u.call(e,c)}catch(c){}}function j(t,e){var n;let r="";try{r=(n=t.headers.get("user-agent"))!=null?n:""}catch(i){return!1}let s=w(r);return s?(_({path:he(t.url),userAgent:r,botName:s},e),!0):!1}function re(t){return(e,r,s)=>{var n,i,u;try{let c=e.headers["user-agent"],p=Array.isArray(c)?(n=c[0])!=null?n:"":c!=null?c:"";j({url:(u=(i=e.originalUrl)!=null?i:e.url)!=null?u:"/",headers:{get:o=>o.toLowerCase()==="user-agent"?p:null}},x(a({},t),{source:"middleware"}))}catch(c){}s()}}0&&(module.exports={CLICK_ID_KEYS,buildSessionUpsertPayload,captureAgentRequest,deriveSessionSegment,detectDeviceClass,detectTimeOfDay,detectTrafficSource,extractTrackedParams,postAgentFetch,preloadAssignments,preloadDecisions,readSessionCookie,referrerDomainFromReferer,sentientAgentMiddleware});
|
|
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});
|
|
2
2
|
//# sourceMappingURL=index-server.js.map
|