@sentientui/core 0.26.0 → 0.28.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-APVHRDKP.mjs +2 -0
- package/dist/chunk-APVHRDKP.mjs.map +1 -0
- package/dist/{index-Ce3IPLrF.d.cts → index-C6tOKQ_H.d.ts} +30 -215
- 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 +4 -3
- package/dist/index-graph.d.ts +4 -3
- 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-graph.mjs.map +1 -1
- package/dist/index-local.d.cts +2 -2
- package/dist/index-local.d.ts +2 -2
- package/dist/{index-DubrRV6l.d.ts → index-qAywhZRg.d.cts} +30 -215
- package/dist/index-server.d.cts +9 -2
- package/dist/index-server.d.ts +9 -2
- 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-CY_Luh5i.d.cts +414 -0
- package/dist/session-meta-CY_Luh5i.d.ts +414 -0
- package/llms.txt +4 -0
- package/package.json +1 -1
- package/dist/chunk-RCN2SIB6.mjs +0 -2
- package/dist/chunk-RCN2SIB6.mjs.map +0 -1
- package/dist/session-meta-C-bMqVeq.d.cts +0 -130
- package/dist/session-meta-C-bMqVeq.d.ts +0 -130
package/dist/index-graph.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{a as w}from"./chunk-WKXD7KI3.mjs";import{a as v,g as A}from"./chunk-Z6ILOYBD.mjs";import{A as Z,B as O,a as V,b as W,c as J,d as X,g as we,h as Te,i as ve,j as Ae,k as Ne,l as xe,m as _e,n as Oe,o as Re,p as Me,q as De,r as Pe,s as ke,t as Ge,u as $e,v as Le,w as je,x as Q,y as x,z as _}from"./chunk-RCN2SIB6.mjs";import{a as N,b as C,c as b,j,k as K,l as U,o as F,p as q,r as z,s as B,t as H,u as Y}from"./chunk-2NVSFI4V.mjs";import{a as y,b as E}from"./chunk-TMCGHANO.mjs";var R="_snt_graph_edges",ee={pricing:["features","faq"],features:["pricing"],faq:["pricing"],social_proof:["cta"],cta:["social_proof","hero","trust"],hero:["cta"],comparison:["pricing"],trust:["cta"]};function te(e){var t;return(t=ee[e])!=null?t:[]}function ne(e,t){try{let n=localStorage.getItem(e);return n?JSON.parse(n):t}catch(n){return t}}function oe(e,t){try{localStorage.setItem(e,JSON.stringify(t))}catch(n){}}var re=new Set(["pricing","hero","social_proof","cta","features","faq","comparison","trust","navigation","generic"]);function se(e){return re.has(e)?e:"generic"}function M(e){try{let t=new URL(e);return`${t.origin}${t.pathname}`}catch(t){return"/"}}function ae(e,t,n){let a=`${e}:${t}:${n.join(",")}`,c=5381;for(let i=0;i<a.length;i++)c=(c<<5)+c+a.charCodeAt(i)&4294967295;return(c>>>0).toString(16).padStart(8,"0")}function D(e){let t=new Map,n=new Map,a=`_snt_graph_nodes${N(e==null?void 0:e.apiKey)}`,c=()=>{typeof window!="undefined"&&oe(a,[...t.values()])};if(typeof window!="undefined"){let i=ne(a,[]);for(let o of i)t.set(o.componentId,o);try{localStorage.removeItem(R)}catch(o){}}return{addPageNode(i){t.set(i.componentId,i),c()},addStructuralEdge(i){let o=`${i.fromComponentId}->${i.toComponentId}`;n.set(o,i)},syncOnce(){var o,m;if(!(e!=null&&e.syncUrl)||typeof window=="undefined")return;let i=[...t.values()];if(i.length!==0)try{let u=new Map;for(let r of i){let p=(o=u.get(r.semanticType))!=null?o:[];p.push(r),u.set(r.semanticType,p)}let s=[],d=new Set;for(let r of i)for(let p of te(r.semanticType)){let l=(m=u.get(p))!=null?m:[];for(let h of l){if(h.componentId===r.componentId)continue;let S=`semantic:${r.componentId}->${h.componentId}`;d.has(S)||(d.add(S),s.push({fromComponentId:r.componentId,toComponentId:h.componentId,type:"semantic",weight:.4,confidence:.9}))}}let f=new Set(i.map(r=>r.componentId));for(let r of n.values()){if(!f.has(r.fromComponentId)||!f.has(r.toComponentId))continue;let p=`structural:${r.fromComponentId}->${r.toComponentId}`;d.has(p)||(d.add(p),s.push({fromComponentId:r.fromComponentId,toComponentId:r.toComponentId,type:"structural",weight:r.weight,confidence:1}))}let g=E(y(y({pageUrl:M(window.location.href)},e.sessionId?{sessionId:e.sessionId}:{}),e.projectId?{projectId:e.projectId}:{}),{nodes:i.map(r=>{let p=se(r.semanticType);return{componentId:r.componentId,semanticType:p,answers:r.answers,contentHash:ae(r.componentId,p,r.answers),prominenceScore:r.prominenceScore,depthInPage:r.depth}}),edges:s});fetch(e.syncUrl,{method:"POST",keepalive:!0,headers:y({"Content-Type":"application/json"},e.apiKey?{Authorization:`Bearer ${e.apiKey}`}:{}),body:JSON.stringify(g)}).catch(()=>{})}catch(u){}},snapshot(){return{pageNodes:[...t.values()],capturedAt:Date.now()}},destroy(){if(typeof window!="undefined")try{localStorage.removeItem(a),localStorage.removeItem(R)}catch(i){}}}}var ie=new Set(["SECTION","ARTICLE","MAIN","DIV","ASIDE"]),ce="h1, h2, h3",de="[data-sentient-id], section[aria-label], article[aria-label], main[aria-label], aside[aria-label]",P=30,pe=1500,ue={scan:async()=>({nodes:[],edges:[],scannedAt:0}),observe:()=>{},getProminenceScore:()=>0,destroy:()=>{}};function k(e,t,n){return n<=t?0:Math.max(0,Math.min(1,(e-t)/(n-t)))}function le(e){var t,n,a;try{let c=e;for(let i of Object.keys(c)){if(!i.startsWith("__reactFiber")&&!i.startsWith("__reactInternalInstance"))continue;let o=c[i],m=(a=(t=o==null?void 0:o.type)==null?void 0:t.displayName)!=null?a:(n=o==null?void 0:o.type)==null?void 0:n.name;if(m&&m.length>1)return m}}catch(c){}}function me(e){let t={};for(let n of Array.from(e.attributes))n.name.startsWith("data-")&&(t[n.name]=n.value);return t}var G=new Set(v);function fe(e){let t=e.getAttribute("data-sentient-type");if(t&&G.has(t))return t;let n=e.getAttribute("role");return n&&G.has(n)?n:A(e)}function ge(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 he(e){let t=[],n=e;for(;n;){let a=n.parentElement;if(!a){t.push(n.tagName.toLowerCase());break}let c=Array.prototype.indexOf.call(a.children,n);t.push(`${n.tagName.toLowerCase()}[${c}]`),n=a}return t.reverse().join("/")}function Se(e){var n;let t=(n=e.getAttribute("data-sentient-id"))!=null?n:e.getAttribute("id");return t||`${e.tagName.toLowerCase()}-${ge(he(e))}`}function ye(e){let t=0,n=e.parentElement;for(;n;)t++,n=n.parentElement;return t}function T(e,t){var a,c,i,o;let n=e.querySelector(ce);return{componentId:Se(e),semanticType:fe(e),ariaLabel:(a=e.getAttribute("aria-label"))!=null?a:void 0,headingText:(i=(c=n==null?void 0:n.textContent)==null?void 0:c.trim())!=null?i:void 0,isAboveFold:e.getBoundingClientRect().top<window.innerHeight,prominenceScore:t(e),depth:ye(e),reactComponentName:le(e),dataAttributes:me(e),locator:(o=w(e,e.ownerDocument))!=null?o:void 0}}function $(e){var i;let t=[],n=new Set,a="__root__",c=new Map;for(let[o,m]of e){let u=o.parentElement,s=a;for(;u;){if(e.has(u)){s=e.get(u);let f=e.get(o),g=`${s}->${f}`;!n.has(g)&&s!==f&&(n.add(g),t.push({fromComponentId:s,toComponentId:f,weight:.6}));break}u=u.parentElement}let d=(i=c.get(s))!=null?i:[];d.push(o),c.set(s,d)}for(let o of c.values()){if(o.length<2)continue;let m=o.length>P?o.slice(0,P):o;for(let u=0;u<m.length;u++)for(let s=u+1;s<m.length;s++){if(t.length>=pe)return t;let d=e.get(m[u]),f=e.get(m[s]);if(d===f)continue;let g=`${d}->${f}::sib`,r=`${f}->${d}::sib`;n.has(g)||(n.add(g),t.push({fromComponentId:d,toComponentId:f,weight:.3})),n.has(r)||(n.add(r),t.push({fromComponentId:f,toComponentId:d,weight:.3}))}}return t}function Ee(e){let t=[],n=new Set,a=new Map;return document.querySelectorAll("[data-sentient-id]").forEach(o=>{if(o instanceof Element&&!n.has(o)){n.add(o);let m=T(o,e);t.push(m),a.set(o,m.componentId)}}),document.querySelectorAll("section, article, main, aside").forEach(o=>{if(!(o instanceof Element)||n.has(o))return;let m=o.hasAttribute("aria-label"),u=o.hasAttribute("data-sentient-id");if(!m&&!u)return;n.add(o);let s=T(o,e);t.push(s),a.set(o,s.componentId)}),{nodes:t,edges:$(a),elementToId:a}}function L(){if(typeof window=="undefined")return ue;let e=null,t=0,n=null,a=new Map,c=u=>{try{let s=window.getComputedStyle(u),d=parseFloat(s.fontSize)||12,f=parseFloat(s.zIndex)||0,g=u.getBoundingClientRect(),r=Math.max(g.top,0),p=window.innerHeight||1,l=1/(r/p+1),h=k(d,12,48)*.4+l*.4+k(f,0,100)*.2;return Math.max(0,Math.min(1,h))}catch(s){return .5}};return{scan:()=>new Promise(u=>{let s=()=>{let{nodes:d,edges:f,elementToId:g}=Ee(c);a.clear();for(let[r,p]of g)a.set(r,p);u({nodes:d,edges:f,scannedAt:Date.now()})};try{typeof requestIdleCallback=="function"?t=requestIdleCallback(s,{timeout:100}):s()}catch(d){s()}}),observe:u=>{n=u;try{e=new MutationObserver(s=>{let d=[],f=new Set;for(let r of s)r.type==="childList"&&r.addedNodes.forEach(p=>{if(!(p instanceof Element))return;let l=[];ie.has(p.tagName)&&(p.hasAttribute("data-sentient-id")||p.hasAttribute("aria-label"))&&l.push(p);try{p.querySelectorAll(de).forEach(h=>l.push(h))}catch(h){}for(let h of l){if(a.has(h))continue;let S=T(h,c);d.push(S),f.add(S.componentId),a.set(h,S.componentId)}});if(d.length===0||!n)return;for(let r of[...a.keys()])r.isConnected||a.delete(r);let g=$(a).filter(r=>f.has(r.fromComponentId)||f.has(r.toComponentId));n({nodes:d,edges:g,addedAt:Date.now()})}),e.observe(document.body,{childList:!0,subtree:!0})}catch(s){}},getProminenceScore:c,destroy:()=>{if(e&&(e.disconnect(),e=null),t&&typeof cancelIdleCallback=="function")try{cancelIdleCallback(t)}catch(u){}t=0,n=null,a.clear()}}}var Ie="https://api.sentient-ui.com/v1/events";function Ce(e){var n;let t=a=>{try{let c=document.cookie.match(new RegExp(`(?:^|; )${a}=([^;]*)`));return c?decodeURIComponent(c[1]):void 0}catch(c){return}};return(n=e?t(b(e)):void 0)!=null?n:t(C)}var I=new Map;function be(e){var r;let t=O(e),n=e.respectDoNotTrack!==!1&&_(),a=e.consent===!1||n,c=typeof e.apiKey=="string"&&e.apiKey.startsWith("pk_"),i=e.localMode===!0||!c;if(!e.graph||i||typeof window=="undefined")return t;if(a)return n||x(e.apiKey,p=>be(p)),t;let o=I.get(e.apiKey);if(o)try{o()}catch(p){}let m=L(),u=(r=e.ingestUrl)!=null?r:Ie,s=D({syncUrl:u.replace(/\/events\/?$/,"/graph/sync"),apiKey:e.apiKey,projectId:e.apiKey,sessionId:Ce(e.apiKey)});m.scan().then(p=>{for(let l of p.nodes)s.addPageNode({id:l.componentId,componentId:l.componentId,semanticType:l.semanticType,answers:e.captureDomText&&l.headingText?[l.headingText]:[],prominenceScore:l.prominenceScore,depth:l.depth});for(let l of p.edges)s.addStructuralEdge(l);s.syncOnce()});let d=null,f=()=>{d!==null&&clearTimeout(d),d=setTimeout(()=>{d=null,s.syncOnce()},500)};m.observe(p=>{for(let l of p.nodes)s.addPageNode({id:l.componentId,componentId:l.componentId,semanticType:l.semanticType,answers:e.captureDomText&&l.headingText?[l.headingText]:[],prominenceScore:l.prominenceScore,depth:l.depth});for(let l of p.edges)s.addStructuralEdge(l);f()});let g=()=>{d!==null&&(clearTimeout(d),d=null),m.destroy(),s.destroy(),I.get(e.apiKey)===g&&I.delete(e.apiKey)};return I.set(e.apiKey,g),E(y({},t),{getGraph:()=>s.snapshot(),dispose:()=>{g(),t.dispose()},destroy:()=>{g(),t.destroy()}})}export{Te as BLOCK_ALIGNS,_e as BLOCK_EMPHASES,Me as BLOCK_FITS,we as BLOCK_GAPS,De as BLOCK_GRID_COLUMNS,Pe as BLOCK_HEADING_LEVELS,ve as BLOCK_JUSTIFIES,Re as BLOCK_RATIOS,Ae as BLOCK_SIZES,Oe as BLOCK_TEXT_ALIGNS,xe as BLOCK_TONES,Ne as BLOCK_WEIGHTS,C as LEGACY_SESSION_COOKIE_NAME,Le as MAX_BLOCK_ARMS,$e as MAX_BLOCK_CHILDREN,Ge as MAX_BLOCK_DEPTH,ke as MAX_BLOCK_NODES,je as MAX_BLOCK_TEXT_LEN,V as SNAPSHOT_STORAGE_KEY_PREFIX,Y as armOfResult,Q as attachMicroSignalDetectors,B as baselineResultFor,H as baselineSlots,q as deriveSessionSegment,j as detectDeviceClass,F as detectTimeOfDay,K as detectTrafficSource,Z as grantConsent,be as init,_ as isDoNotTrackEnabled,w as locatorFromElement,W as readSnapshot,U as referrerDomainFromReferer,X as renderPrePaintScript,M as sanitizePageUrl,b as sessionCookieName,z as toWireSlot,J as writeSnapshot};
|
|
1
|
+
import{a as w}from"./chunk-WKXD7KI3.mjs";import{a as v,g as A}from"./chunk-Z6ILOYBD.mjs";import{A as qe,B as ze,C as Be,D as He,E as Ye,F as Q,G as x,H as _,I as Z,J as O,a as V,b as W,c as J,d as X,g as we,h as Te,i as ve,j as Ae,k as Ne,l as xe,m as _e,n as Oe,o as Re,p as Me,q as De,r as Pe,s as ke,t as Ge,u as $e,v as Le,w as je,x as Ke,y as Ue,z as Fe}from"./chunk-APVHRDKP.mjs";import{a as N,b as C,c as b,j,k as K,l as U,o as F,p as q,r as z,s as B,t as H,u as Y}from"./chunk-2NVSFI4V.mjs";import{a as y,b as E}from"./chunk-TMCGHANO.mjs";var R="_snt_graph_edges",ee={pricing:["features","faq"],features:["pricing"],faq:["pricing"],social_proof:["cta"],cta:["social_proof","hero","trust"],hero:["cta"],comparison:["pricing"],trust:["cta"]};function te(e){var t;return(t=ee[e])!=null?t:[]}function ne(e,t){try{let n=localStorage.getItem(e);return n?JSON.parse(n):t}catch(n){return t}}function oe(e,t){try{localStorage.setItem(e,JSON.stringify(t))}catch(n){}}var re=new Set(["pricing","hero","social_proof","cta","features","faq","comparison","trust","navigation","generic"]);function se(e){return re.has(e)?e:"generic"}function M(e){try{let t=new URL(e);return`${t.origin}${t.pathname}`}catch(t){return"/"}}function ae(e,t,n){let a=`${e}:${t}:${n.join(",")}`,c=5381;for(let i=0;i<a.length;i++)c=(c<<5)+c+a.charCodeAt(i)&4294967295;return(c>>>0).toString(16).padStart(8,"0")}function D(e){let t=new Map,n=new Map,a=`_snt_graph_nodes${N(e==null?void 0:e.apiKey)}`,c=()=>{typeof window!="undefined"&&oe(a,[...t.values()])};if(typeof window!="undefined"){let i=ne(a,[]);for(let o of i)t.set(o.componentId,o);try{localStorage.removeItem(R)}catch(o){}}return{addPageNode(i){t.set(i.componentId,i),c()},addStructuralEdge(i){let o=`${i.fromComponentId}->${i.toComponentId}`;n.set(o,i)},syncOnce(){var o,m;if(!(e!=null&&e.syncUrl)||typeof window=="undefined")return;let i=[...t.values()];if(i.length!==0)try{let u=new Map;for(let r of i){let p=(o=u.get(r.semanticType))!=null?o:[];p.push(r),u.set(r.semanticType,p)}let s=[],d=new Set;for(let r of i)for(let p of te(r.semanticType)){let l=(m=u.get(p))!=null?m:[];for(let h of l){if(h.componentId===r.componentId)continue;let S=`semantic:${r.componentId}->${h.componentId}`;d.has(S)||(d.add(S),s.push({fromComponentId:r.componentId,toComponentId:h.componentId,type:"semantic",weight:.4,confidence:.9}))}}let f=new Set(i.map(r=>r.componentId));for(let r of n.values()){if(!f.has(r.fromComponentId)||!f.has(r.toComponentId))continue;let p=`structural:${r.fromComponentId}->${r.toComponentId}`;d.has(p)||(d.add(p),s.push({fromComponentId:r.fromComponentId,toComponentId:r.toComponentId,type:"structural",weight:r.weight,confidence:1}))}let g=E(y(y({pageUrl:M(window.location.href)},e.sessionId?{sessionId:e.sessionId}:{}),e.projectId?{projectId:e.projectId}:{}),{nodes:i.map(r=>{let p=se(r.semanticType);return{componentId:r.componentId,semanticType:p,answers:r.answers,contentHash:ae(r.componentId,p,r.answers),prominenceScore:r.prominenceScore,depthInPage:r.depth}}),edges:s});fetch(e.syncUrl,{method:"POST",keepalive:!0,headers:y({"Content-Type":"application/json"},e.apiKey?{Authorization:`Bearer ${e.apiKey}`}:{}),body:JSON.stringify(g)}).catch(()=>{})}catch(u){}},snapshot(){return{pageNodes:[...t.values()],capturedAt:Date.now()}},destroy(){if(typeof window!="undefined")try{localStorage.removeItem(a),localStorage.removeItem(R)}catch(i){}}}}var ie=new Set(["SECTION","ARTICLE","MAIN","DIV","ASIDE"]),ce="h1, h2, h3",de="[data-sentient-id], section[aria-label], article[aria-label], main[aria-label], aside[aria-label]",P=30,pe=1500,ue={scan:async()=>({nodes:[],edges:[],scannedAt:0}),observe:()=>{},getProminenceScore:()=>0,destroy:()=>{}};function k(e,t,n){return n<=t?0:Math.max(0,Math.min(1,(e-t)/(n-t)))}function le(e){var t,n,a;try{let c=e;for(let i of Object.keys(c)){if(!i.startsWith("__reactFiber")&&!i.startsWith("__reactInternalInstance"))continue;let o=c[i],m=(a=(t=o==null?void 0:o.type)==null?void 0:t.displayName)!=null?a:(n=o==null?void 0:o.type)==null?void 0:n.name;if(m&&m.length>1)return m}}catch(c){}}function me(e){let t={};for(let n of Array.from(e.attributes))n.name.startsWith("data-")&&(t[n.name]=n.value);return t}var G=new Set(v);function fe(e){let t=e.getAttribute("data-sentient-type");if(t&&G.has(t))return t;let n=e.getAttribute("role");return n&&G.has(n)?n:A(e)}function ge(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 he(e){let t=[],n=e;for(;n;){let a=n.parentElement;if(!a){t.push(n.tagName.toLowerCase());break}let c=Array.prototype.indexOf.call(a.children,n);t.push(`${n.tagName.toLowerCase()}[${c}]`),n=a}return t.reverse().join("/")}function Se(e){var n;let t=(n=e.getAttribute("data-sentient-id"))!=null?n:e.getAttribute("id");return t||`${e.tagName.toLowerCase()}-${ge(he(e))}`}function ye(e){let t=0,n=e.parentElement;for(;n;)t++,n=n.parentElement;return t}function T(e,t){var a,c,i,o;let n=e.querySelector(ce);return{componentId:Se(e),semanticType:fe(e),ariaLabel:(a=e.getAttribute("aria-label"))!=null?a:void 0,headingText:(i=(c=n==null?void 0:n.textContent)==null?void 0:c.trim())!=null?i:void 0,isAboveFold:e.getBoundingClientRect().top<window.innerHeight,prominenceScore:t(e),depth:ye(e),reactComponentName:le(e),dataAttributes:me(e),locator:(o=w(e,e.ownerDocument))!=null?o:void 0}}function $(e){var i;let t=[],n=new Set,a="__root__",c=new Map;for(let[o,m]of e){let u=o.parentElement,s=a;for(;u;){if(e.has(u)){s=e.get(u);let f=e.get(o),g=`${s}->${f}`;!n.has(g)&&s!==f&&(n.add(g),t.push({fromComponentId:s,toComponentId:f,weight:.6}));break}u=u.parentElement}let d=(i=c.get(s))!=null?i:[];d.push(o),c.set(s,d)}for(let o of c.values()){if(o.length<2)continue;let m=o.length>P?o.slice(0,P):o;for(let u=0;u<m.length;u++)for(let s=u+1;s<m.length;s++){if(t.length>=pe)return t;let d=e.get(m[u]),f=e.get(m[s]);if(d===f)continue;let g=`${d}->${f}::sib`,r=`${f}->${d}::sib`;n.has(g)||(n.add(g),t.push({fromComponentId:d,toComponentId:f,weight:.3})),n.has(r)||(n.add(r),t.push({fromComponentId:f,toComponentId:d,weight:.3}))}}return t}function Ee(e){let t=[],n=new Set,a=new Map;return document.querySelectorAll("[data-sentient-id]").forEach(o=>{if(o instanceof Element&&!n.has(o)){n.add(o);let m=T(o,e);t.push(m),a.set(o,m.componentId)}}),document.querySelectorAll("section, article, main, aside").forEach(o=>{if(!(o instanceof Element)||n.has(o))return;let m=o.hasAttribute("aria-label"),u=o.hasAttribute("data-sentient-id");if(!m&&!u)return;n.add(o);let s=T(o,e);t.push(s),a.set(o,s.componentId)}),{nodes:t,edges:$(a),elementToId:a}}function L(){if(typeof window=="undefined")return ue;let e=null,t=0,n=null,a=new Map,c=u=>{try{let s=window.getComputedStyle(u),d=parseFloat(s.fontSize)||12,f=parseFloat(s.zIndex)||0,g=u.getBoundingClientRect(),r=Math.max(g.top,0),p=window.innerHeight||1,l=1/(r/p+1),h=k(d,12,48)*.4+l*.4+k(f,0,100)*.2;return Math.max(0,Math.min(1,h))}catch(s){return .5}};return{scan:()=>new Promise(u=>{let s=()=>{let{nodes:d,edges:f,elementToId:g}=Ee(c);a.clear();for(let[r,p]of g)a.set(r,p);u({nodes:d,edges:f,scannedAt:Date.now()})};try{typeof requestIdleCallback=="function"?t=requestIdleCallback(s,{timeout:100}):s()}catch(d){s()}}),observe:u=>{n=u;try{e=new MutationObserver(s=>{let d=[],f=new Set;for(let r of s)r.type==="childList"&&r.addedNodes.forEach(p=>{if(!(p instanceof Element))return;let l=[];ie.has(p.tagName)&&(p.hasAttribute("data-sentient-id")||p.hasAttribute("aria-label"))&&l.push(p);try{p.querySelectorAll(de).forEach(h=>l.push(h))}catch(h){}for(let h of l){if(a.has(h))continue;let S=T(h,c);d.push(S),f.add(S.componentId),a.set(h,S.componentId)}});if(d.length===0||!n)return;for(let r of[...a.keys()])r.isConnected||a.delete(r);let g=$(a).filter(r=>f.has(r.fromComponentId)||f.has(r.toComponentId));n({nodes:d,edges:g,addedAt:Date.now()})}),e.observe(document.body,{childList:!0,subtree:!0})}catch(s){}},getProminenceScore:c,destroy:()=>{if(e&&(e.disconnect(),e=null),t&&typeof cancelIdleCallback=="function")try{cancelIdleCallback(t)}catch(u){}t=0,n=null,a.clear()}}}var Ie="https://api.sentient-ui.com/v1/events";function Ce(e){var n;let t=a=>{try{let c=document.cookie.match(new RegExp(`(?:^|; )${a}=([^;]*)`));return c?decodeURIComponent(c[1]):void 0}catch(c){return}};return(n=e?t(b(e)):void 0)!=null?n:t(C)}var I=new Map;function be(e){var r;let t=O(e),n=e.respectDoNotTrack!==!1&&_(),a=e.consent===!1||n,c=typeof e.apiKey=="string"&&e.apiKey.startsWith("pk_"),i=e.localMode===!0||!c;if(!e.graph||i||typeof window=="undefined")return t;if(a)return n||x(e.apiKey,p=>be(p)),t;let o=I.get(e.apiKey);if(o)try{o()}catch(p){}let m=L(),u=(r=e.ingestUrl)!=null?r:Ie,s=D({syncUrl:u.replace(/\/events\/?$/,"/graph/sync"),apiKey:e.apiKey,projectId:e.apiKey,sessionId:Ce(e.apiKey)});m.scan().then(p=>{for(let l of p.nodes)s.addPageNode({id:l.componentId,componentId:l.componentId,semanticType:l.semanticType,answers:e.captureDomText&&l.headingText?[l.headingText]:[],prominenceScore:l.prominenceScore,depth:l.depth});for(let l of p.edges)s.addStructuralEdge(l);s.syncOnce()});let d=null,f=()=>{d!==null&&clearTimeout(d),d=setTimeout(()=>{d=null,s.syncOnce()},500)};m.observe(p=>{for(let l of p.nodes)s.addPageNode({id:l.componentId,componentId:l.componentId,semanticType:l.semanticType,answers:e.captureDomText&&l.headingText?[l.headingText]:[],prominenceScore:l.prominenceScore,depth:l.depth});for(let l of p.edges)s.addStructuralEdge(l);f()});let g=()=>{d!==null&&(clearTimeout(d),d=null),m.destroy(),s.destroy(),I.get(e.apiKey)===g&&I.delete(e.apiKey)};return I.set(e.apiKey,g),E(y({},t),{getGraph:()=>s.snapshot(),dispose:()=>{g(),t.dispose()},destroy:()=>{g(),t.destroy()}})}export{Te as BLOCK_ALIGNS,_e as BLOCK_EMPHASES,Me as BLOCK_FITS,we as BLOCK_GAPS,De as BLOCK_GRID_COLUMNS,Pe as BLOCK_HEADING_LEVELS,ve as BLOCK_JUSTIFIES,$e as BLOCK_MAX_WIDTHS,Ge as BLOCK_PADS,Re as BLOCK_RATIOS,Ae as BLOCK_SIZES,ke as BLOCK_SURFACES,Oe as BLOCK_TEXT_ALIGNS,xe as BLOCK_TONES,Ne as BLOCK_WEIGHTS,Le as FORM_FIELD_KINDS,je as FORM_INPUT_TYPES,C as LEGACY_SESSION_COOKIE_NAME,Be as MAX_BLOCK_ARMS,ze as MAX_BLOCK_CHILDREN,qe as MAX_BLOCK_DEPTH,Fe as MAX_BLOCK_NODES,He as MAX_BLOCK_TEXT_LEN,Ke as MAX_FORM_FIELDS,Ue as MAX_FORM_SELECT_OPTIONS,V as SNAPSHOT_STORAGE_KEY_PREFIX,Y as armOfResult,Q as attachMicroSignalDetectors,B as baselineResultFor,H as baselineSlots,Ye as containsFormBlock,q as deriveSessionSegment,j as detectDeviceClass,F as detectTimeOfDay,K as detectTrafficSource,Z as grantConsent,be as init,_ as isDoNotTrackEnabled,w as locatorFromElement,W as readSnapshot,U as referrerDomainFromReferer,X as renderPrePaintScript,M as sanitizePageUrl,b as sessionCookieName,z as toWireSlot,J as writeSnapshot};
|
|
2
2
|
//# sourceMappingURL=index-graph.mjs.map
|
package/dist/index-graph.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/graph.ts","../src/scanner.ts","../src/index-graph.ts"],"sourcesContent":["/** In-memory context graph with persistence and backend sync. */\n\nimport { storageSuffix } from './storage-key.js';\n\nexport type PageNode = {\n id: string;\n componentId: string;\n semanticType: string;\n answers: string[];\n prominenceScore: number;\n depth: number;\n};\n\nexport type GraphSnapshot = {\n pageNodes: PageNode[];\n capturedAt: number;\n};\n\nexport type GraphConfig = {\n syncUrl?: string;\n apiKey?: string;\n projectId?: string;\n sessionId?: string;\n};\n\nexport type StructuralEdge = {\n fromComponentId: string;\n toComponentId: string;\n weight: number;\n};\n\nexport type GraphClient = {\n addPageNode(node: PageNode): void;\n /** Record a DOM-derived parent/child or sibling relationship between two components. */\n addStructuralEdge(edge: StructuralEdge): void;\n /** One-shot batch sync of all current page nodes to the backend. */\n syncOnce(): void;\n snapshot(): GraphSnapshot;\n destroy(): void;\n};\n\n// _snt_graph_edges was written by earlier builds but never synced to the backend.\n// We still read and clear any leftover key on init/destroy so old clients don't\n// accumulate stale data, but we no longer write it.\nconst STALE_EDGES_KEY = '_snt_graph_edges';\n\nconst SEMANTIC_NEIGHBOURS: Record<string, string[]> = {\n pricing: ['features', 'faq'],\n features: ['pricing'],\n faq: ['pricing'],\n social_proof: ['cta'],\n cta: ['social_proof', 'hero', 'trust'],\n hero: ['cta'],\n comparison: ['pricing'],\n trust: ['cta'],\n};\n\nfunction neighboursFor(semanticType: string): string[] {\n return SEMANTIC_NEIGHBOURS[semanticType] ?? [];\n}\n\nfunction readStorage<T>(key: string, fallback: T): T {\n try {\n const raw = localStorage.getItem(key);\n if (!raw) return fallback;\n return JSON.parse(raw) as T;\n } catch {\n return fallback;\n }\n}\n\nfunction writeStorage(key: string, value: unknown): void {\n try {\n localStorage.setItem(key, JSON.stringify(value));\n } catch {\n /* ignore */\n }\n}\n\nconst VALID_SEMANTIC_TYPES = new Set([\n 'pricing', 'hero', 'social_proof', 'cta', 'features',\n 'faq', 'comparison', 'trust', 'navigation', 'generic',\n]);\n\nfunction toValidSemanticType(type: string): string {\n return VALID_SEMANTIC_TYPES.has(type) ? type : 'generic';\n}\n\n/**\n * Path-only page URL for graph sync — strips query + fragment so tokens,\n * emails, and other sensitive URL params never leave the browser by default.\n */\nexport function sanitizePageUrl(href: string): string {\n try {\n const u = new URL(href);\n return `${u.origin}${u.pathname}`;\n } catch {\n return '/';\n }\n}\n\nfunction contentHashOf(componentId: string, semanticType: string, answers: string[]): string {\n const input = `${componentId}:${semanticType}:${answers.join(',')}`;\n let h = 5381;\n for (let i = 0; i < input.length; i++) {\n h = ((h << 5) + h + input.charCodeAt(i)) & 0xffffffff;\n }\n return (h >>> 0).toString(16).padStart(8, '0');\n}\n\n/**\n * Creates an in-memory graph client with optional persistence and sync.\n */\nexport function createGraphClient(config?: GraphConfig): GraphClient {\n const pageNodes = new Map<string, PageNode>();\n const structuralEdges = new Map<string, StructuralEdge>();\n\n // Per-project localStorage key so two projects on one origin don't share a\n // graph-node cache (see storage-key.ts). Legacy `_snt_graph_nodes` with no key.\n const nodesKey = `_snt_graph_nodes${storageSuffix(config?.apiKey)}`;\n\n const persist = (): void => {\n if (typeof window === 'undefined') return;\n writeStorage(nodesKey, [...pageNodes.values()]);\n };\n\n // serialize()/restore() were removed here: persisted-node restoration moved\n // into this constructor (below), leaving both dead — yet still shipping in\n // the graph bundle.\n if (typeof window !== 'undefined') {\n const storedNodes = readStorage<PageNode[]>(nodesKey, []);\n for (const node of storedNodes) {\n pageNodes.set(node.componentId, node);\n }\n // Clear any stale edge data written by older SDK versions.\n try { localStorage.removeItem(STALE_EDGES_KEY); } catch { /* ignore */ }\n }\n\n return {\n addPageNode(node: PageNode): void {\n pageNodes.set(node.componentId, node);\n persist();\n },\n\n addStructuralEdge(edge: StructuralEdge): void {\n const key = `${edge.fromComponentId}->${edge.toComponentId}`;\n structuralEdges.set(key, edge);\n },\n\n syncOnce(): void {\n if (!config?.syncUrl || typeof window === 'undefined') return;\n const nodes = [...pageNodes.values()];\n if (nodes.length === 0) return;\n try {\n // Build semantic edges from the SEMANTIC_NEIGHBOURS map. Each node emits\n // an edge to every present sibling that matches one of its neighbour types.\n // Weight matches propagate()'s 0.4 attention factor; confidence is high\n // because the mapping is curated, not inferred.\n const nodesByType = new Map<string, PageNode[]>();\n for (const n of nodes) {\n const list = nodesByType.get(n.semanticType) ?? [];\n list.push(n);\n nodesByType.set(n.semanticType, list);\n }\n const edges: Array<{\n fromComponentId: string;\n toComponentId: string;\n type: 'semantic' | 'structural';\n weight: number;\n confidence: number;\n }> = [];\n const seen = new Set<string>();\n for (const source of nodes) {\n for (const neighbourType of neighboursFor(source.semanticType)) {\n const targets = nodesByType.get(neighbourType) ?? [];\n for (const target of targets) {\n if (target.componentId === source.componentId) continue;\n const key = `semantic:${source.componentId}->${target.componentId}`;\n if (seen.has(key)) continue;\n seen.add(key);\n edges.push({\n fromComponentId: source.componentId,\n toComponentId: target.componentId,\n type: 'semantic',\n weight: 0.4,\n confidence: 0.9,\n });\n }\n }\n }\n\n // Structural edges from DOM relationships, recorded during scan.\n // Only emit when both endpoints are present in this page's node set —\n // a structural edge to/from a node that no longer exists would dangle.\n const componentIds = new Set(nodes.map((n) => n.componentId));\n for (const edge of structuralEdges.values()) {\n if (!componentIds.has(edge.fromComponentId) || !componentIds.has(edge.toComponentId)) continue;\n const key = `structural:${edge.fromComponentId}->${edge.toComponentId}`;\n if (seen.has(key)) continue;\n seen.add(key);\n edges.push({\n fromComponentId: edge.fromComponentId,\n toComponentId: edge.toComponentId,\n type: 'structural',\n weight: edge.weight,\n confidence: 1.0,\n });\n }\n\n const payload = {\n pageUrl: sanitizePageUrl(window.location.href),\n // Visitor/project attribution. The /graph/sync handler ignores unknown\n // top-level fields (Fastify additionalProperties + Zod strips extras),\n // so these ride along harmlessly and let beacons carry attribution.\n ...(config.sessionId ? { sessionId: config.sessionId } : {}),\n ...(config.projectId ? { projectId: config.projectId } : {}),\n nodes: nodes.map((n) => {\n const semanticType = toValidSemanticType(n.semanticType);\n return {\n componentId: n.componentId,\n semanticType,\n answers: n.answers,\n contentHash: contentHashOf(n.componentId, semanticType, n.answers),\n prominenceScore: n.prominenceScore,\n depthInPage: n.depth,\n };\n }),\n edges,\n };\n fetch(config.syncUrl, {\n method: 'POST',\n keepalive: true,\n headers: {\n 'Content-Type': 'application/json',\n ...(config.apiKey ? { Authorization: `Bearer ${config.apiKey}` } : {}),\n },\n body: JSON.stringify(payload),\n }).catch(() => undefined);\n } catch {\n /* ignore */\n }\n },\n\n snapshot(): GraphSnapshot {\n return {\n pageNodes: [...pageNodes.values()],\n capturedAt: Date.now(),\n };\n },\n\n destroy(): void {\n if (typeof window === 'undefined') return;\n try {\n localStorage.removeItem(nodesKey);\n localStorage.removeItem(STALE_EDGES_KEY);\n } catch {\n /* ignore */\n }\n },\n };\n}\n","/** Reads the rendered DOM to build the page-side context graph. */\n\nimport { classifySection, SEMANTIC_TYPES, type SemanticType } from './engagement/classify';\nimport { locatorFromElement } from './locator-from-dom.js';\nimport type { CompoundLocator } from './snapshot.js';\n\nexport type ScannedNode = {\n componentId: string;\n semanticType: string;\n ariaLabel?: string;\n headingText?: string;\n isAboveFold: boolean;\n prominenceScore: number;\n depth: number;\n reactComponentName?: string;\n dataAttributes: Record<string, string>;\n /** Compound locator for this element. The server hashes it into section_key —\n * the identity the crawler and the snippet resolve to for the same physical\n * section. Undefined when nothing resolves uniquely: the runtime never\n * guesses an identity it could not verify later. */\n locator?: CompoundLocator;\n};\n\nexport type StructuralEdge = {\n fromComponentId: string;\n toComponentId: string;\n /** 0.6 for direct parent → child, 0.3 for sibling (both directions emitted). */\n weight: number;\n};\n\nexport type ScanResult = {\n nodes: ScannedNode[];\n edges: StructuralEdge[];\n scannedAt: number;\n};\n\nexport type ContentAddedEvent = {\n nodes: ScannedNode[];\n edges: StructuralEdge[];\n addedAt: number;\n};\n\nexport type DOMScanner = {\n scan(): Promise<ScanResult>;\n observe(onContentAdded: (event: ContentAddedEvent) => void): void;\n getProminenceScore(element: Element): number;\n destroy(): void;\n};\n\n// ASIDE included to match the initial scan (which queries `section, article,\n// main, aside`) — this set omitted it, so a server-rendered aside was captured\n// while an identical dynamically-inserted one was silently ignored.\nconst OBSERVE_TAGS = new Set(['SECTION', 'ARTICLE', 'MAIN', 'DIV', 'ASIDE']);\nconst HEADING_SELECTOR = 'h1, h2, h3';\n// Selector mirror of the initial scan's criteria (collectNodesAndEdges): any\n// element carrying a declared id, plus structural tags with an aria-label.\n// Used to walk INTO inserted subtrees — a SPA mounts ONE root node whose\n// interesting sections are all descendants, and inspecting only the root made\n// every framework-mounted component permanently invisible to graph capture.\nconst SUBTREE_SELECTOR =\n '[data-sentient-id], section[aria-label], article[aria-label], main[aria-label], aside[aria-label]';\n\n// Sibling detection is O(n²) per group and emits two edges per pair, so a page\n// with hundreds of co-located components (e.g. a 200-cell product grid) would\n// otherwise emit tens of thousands of low-signal sibling edges. We cap the\n// sibling fan-out per group and the total structural edges per detection pass.\n// The total stays well under the server's 2000-edge-per-sync limit, leaving room\n// for semantic edges. Parent→child edges (higher signal) are emitted first, so\n// the cap sheds sibling edges before it ever touches them.\nconst MAX_SIBLINGS_PER_GROUP = 30;\nconst MAX_STRUCTURAL_EDGES = 1500;\n\nconst SSR_SCANNER: DOMScanner = {\n scan: async () => ({ nodes: [], edges: [], scannedAt: 0 }),\n observe: () => undefined,\n getProminenceScore: () => 0,\n destroy: () => undefined,\n};\n\nfunction normalize(value: number, min: number, max: number): number {\n if (max <= min) return 0;\n return Math.max(0, Math.min(1, (value - min) / (max - min)));\n}\n\nfunction readReactComponentName(element: Element): string | undefined {\n try {\n const record = element as unknown as Record<string, unknown>;\n for (const key of Object.keys(record)) {\n if (!key.startsWith('__reactFiber') && !key.startsWith('__reactInternalInstance')) {\n continue;\n }\n const fiber = record[key] as { type?: { name?: string; displayName?: string } };\n const name = fiber?.type?.displayName ?? fiber?.type?.name;\n if (name && name.length > 1) {\n return name;\n }\n }\n } catch {\n /* ignore */\n }\n return undefined;\n}\n\nfunction extractDataAttributes(element: Element): Record<string, string> {\n const attrs: Record<string, string> = {};\n for (const attr of Array.from(element.attributes)) {\n if (attr.name.startsWith('data-')) {\n attrs[attr.name] = attr.value;\n }\n }\n return attrs;\n}\n\nconst SEMANTIC_SET: ReadonlySet<string> = new Set(SEMANTIC_TYPES);\n\n// Explicit tag wins → role → heuristic → generic. Every output is normalized to\n// the graph_nodes enum: an out-of-vocabulary data-sentient-type/role falls\n// through to the heuristic instead of being emitted raw (raw values violated\n// the graph_nodes CHECK constraint on insert).\nfunction inferSemanticType(element: Element): SemanticType {\n const explicit = element.getAttribute('data-sentient-type');\n if (explicit && SEMANTIC_SET.has(explicit)) return explicit as SemanticType;\n const role = element.getAttribute('role');\n if (role && SEMANTIC_SET.has(role)) return role as SemanticType;\n return classifySection(element);\n}\n\n// djb2 over a string → 8-hex-char digest. Stable and collision-resistant enough\n// to disambiguate co-located components that declare no id of their own.\nfunction shortHash(input: string): string {\n let h = 5381;\n for (let i = 0; i < input.length; i++) {\n h = ((h << 5) + h + input.charCodeAt(i)) & 0xffffffff;\n }\n return (h >>> 0).toString(16).padStart(8, '0');\n}\n\n// A structural path (tag + sibling index at each level up to the root) uniquely\n// and stably identifies an element's DOM position, so two id-less sections don't\n// hash to the same value the way a bare tagName would.\nfunction domPathSignature(element: Element): string {\n const parts: string[] = [];\n let current: Element | null = element;\n while (current) {\n const parent: Element | null = current.parentElement;\n if (!parent) {\n parts.push(current.tagName.toLowerCase());\n break;\n }\n const index = Array.prototype.indexOf.call(parent.children, current);\n parts.push(`${current.tagName.toLowerCase()}[${index}]`);\n current = parent;\n }\n return parts.reverse().join('/');\n}\n\n// Prefer an author-declared id. When none exists, synthesize a stable, unique id\n// from the element's DOM path — the old `tagName.toLowerCase()` fallback gave\n// every id-less <section> the same \"section\" id, so a second such node silently\n// overwrote the first in the componentId-keyed graph Map (node loss).\nfunction componentIdFor(element: Element): string {\n const declared =\n element.getAttribute('data-sentient-id') ?? element.getAttribute('id');\n if (declared) return declared;\n return `${element.tagName.toLowerCase()}-${shortHash(domPathSignature(element))}`;\n}\n\nfunction depthOf(element: Element): number {\n let depth = 0;\n let current: Element | null = element.parentElement;\n while (current) {\n depth++;\n current = current.parentElement;\n }\n return depth;\n}\n\nfunction scanElement(\n element: Element,\n getProminenceScore: (el: Element) => number,\n): ScannedNode {\n const heading = element.querySelector(HEADING_SELECTOR);\n return {\n componentId: componentIdFor(element),\n semanticType: inferSemanticType(element),\n ariaLabel: element.getAttribute('aria-label') ?? undefined,\n headingText: heading?.textContent?.trim() ?? undefined,\n isAboveFold: element.getBoundingClientRect().top < window.innerHeight,\n prominenceScore: getProminenceScore(element),\n depth: depthOf(element),\n reactComponentName: readReactComponentName(element),\n dataAttributes: extractDataAttributes(element),\n locator: locatorFromElement(element, element.ownerDocument) ?? undefined,\n };\n}\n\n/**\n * Detects structural relationships between scanned component elements:\n * - parent → child (direct ancestor link, weight 0.6)\n * - sibling ↔ sibling (share nearest component ancestor, weight 0.3, bidirectional)\n * A pair appears at most once per direction.\n */\nfunction detectStructuralEdges(elementToId: Map<Element, string>): StructuralEdge[] {\n const edges: StructuralEdge[] = [];\n const seen = new Set<string>();\n const ROOT = '__root__';\n\n // Parent → child: nearest component ancestor only.\n const groups = new Map<string, Element[]>();\n for (const [el, _id] of elementToId) {\n let ancestor: Element | null = el.parentElement;\n let groupKey = ROOT;\n while (ancestor) {\n if (elementToId.has(ancestor)) {\n groupKey = elementToId.get(ancestor)!;\n const childId = elementToId.get(el)!;\n const key = `${groupKey}->${childId}`;\n if (!seen.has(key) && groupKey !== childId) {\n seen.add(key);\n edges.push({ fromComponentId: groupKey, toComponentId: childId, weight: 0.6 });\n }\n break;\n }\n ancestor = ancestor.parentElement;\n }\n const siblings = groups.get(groupKey) ?? [];\n siblings.push(el);\n groups.set(groupKey, siblings);\n }\n\n // Sibling ↔ sibling: same ancestor group.\n for (const sibs of groups.values()) {\n if (sibs.length < 2) continue;\n // Cap the fan-out of any single group before the O(n²) pairing.\n const capped = sibs.length > MAX_SIBLINGS_PER_GROUP ? sibs.slice(0, MAX_SIBLINGS_PER_GROUP) : sibs;\n for (let i = 0; i < capped.length; i++) {\n for (let j = i + 1; j < capped.length; j++) {\n if (edges.length >= MAX_STRUCTURAL_EDGES) return edges;\n const aId = elementToId.get(capped[i]!)!;\n const bId = elementToId.get(capped[j]!)!;\n if (aId === bId) continue;\n const fwd = `${aId}->${bId}::sib`;\n const rev = `${bId}->${aId}::sib`;\n if (!seen.has(fwd)) {\n seen.add(fwd);\n edges.push({ fromComponentId: aId, toComponentId: bId, weight: 0.3 });\n }\n if (!seen.has(rev)) {\n seen.add(rev);\n edges.push({ fromComponentId: bId, toComponentId: aId, weight: 0.3 });\n }\n }\n }\n }\n\n return edges;\n}\n\nfunction collectNodesAndEdges(\n getProminenceScore: (el: Element) => number,\n): { nodes: ScannedNode[]; edges: StructuralEdge[]; elementToId: Map<Element, string> } {\n const nodes: ScannedNode[] = [];\n const seen = new Set<Element>();\n const elementToId = new Map<Element, string>();\n\n const registered = document.querySelectorAll('[data-sentient-id]');\n registered.forEach((el) => {\n if (el instanceof Element && !seen.has(el)) {\n seen.add(el);\n const node = scanElement(el, getProminenceScore);\n nodes.push(node);\n elementToId.set(el, node.componentId);\n }\n });\n\n const structural = document.querySelectorAll('section, article, main, aside');\n structural.forEach((el) => {\n if (!(el instanceof Element) || seen.has(el)) return;\n const hasAria = el.hasAttribute('aria-label');\n const hasSentientId = el.hasAttribute('data-sentient-id');\n if (!hasAria && !hasSentientId) return;\n seen.add(el);\n const node = scanElement(el, getProminenceScore);\n nodes.push(node);\n elementToId.set(el, node.componentId);\n });\n\n return { nodes, edges: detectStructuralEdges(elementToId), elementToId };\n}\n\n/**\n * Creates a DOM scanner that uses idle callbacks and mutation observation.\n */\nexport function createDOMScanner(): DOMScanner {\n if (typeof window === 'undefined') {\n return SSR_SCANNER;\n }\n\n let observer: MutationObserver | null = null;\n let idleCallbackId = 0;\n let contentCallback: ((event: ContentAddedEvent) => void) | null = null;\n // Element→componentId for every node registered so far (initial scan + prior\n // mutations). The MutationObserver detects edges against this whole set — not\n // just the nodes in the current mutation — so a child inserted under an\n // already-scanned parent still gets its parent→child edge.\n const knownElementToId = new Map<Element, string>();\n\n const getProminenceScore = (element: Element): number => {\n try {\n const styles = window.getComputedStyle(element);\n const fontSize = parseFloat(styles.fontSize) || 12;\n const zIndex = parseFloat(styles.zIndex) || 0;\n const rect = element.getBoundingClientRect();\n const distanceFromTop = Math.max(rect.top, 0);\n const viewportHeight = window.innerHeight || 1;\n const inverseDistance = 1 / (distanceFromTop / viewportHeight + 1);\n\n // inverseDistance is already in (0, 1] by construction, so it needs no\n // further normalization — only fontSize and zIndex are rescaled.\n const score =\n normalize(fontSize, 12, 48) * 0.4 +\n inverseDistance * 0.4 +\n normalize(zIndex, 0, 100) * 0.2;\n\n return Math.max(0, Math.min(1, score));\n } catch {\n return 0.5;\n }\n };\n\n const scan = (): Promise<ScanResult> =>\n new Promise((resolve) => {\n const run = (): void => {\n const { nodes, edges, elementToId } = collectNodesAndEdges(getProminenceScore);\n // Seed the known-element registry so the observer can resolve parents that\n // were registered in this scan when later children are inserted.\n knownElementToId.clear();\n for (const [el, id] of elementToId) knownElementToId.set(el, id);\n resolve({ nodes, edges, scannedAt: Date.now() });\n };\n\n try {\n if (typeof requestIdleCallback === 'function') {\n idleCallbackId = requestIdleCallback(run, { timeout: 100 });\n } else {\n run();\n }\n } catch {\n run();\n }\n });\n\n const observe = (onContentAdded: (event: ContentAddedEvent) => void): void => {\n contentCallback = onContentAdded;\n try {\n observer = new MutationObserver((mutations) => {\n const added: ScannedNode[] = [];\n const addedIds = new Set<string>();\n for (const mutation of mutations) {\n if (mutation.type !== 'childList') continue;\n mutation.addedNodes.forEach((node) => {\n if (!(node instanceof Element)) return;\n const candidates: Element[] = [];\n if (\n OBSERVE_TAGS.has(node.tagName) &&\n (node.hasAttribute('data-sentient-id') || node.hasAttribute('aria-label'))\n ) {\n candidates.push(node);\n }\n // Also scan the inserted SUBTREE with the initial scan's criteria\n // (see SUBTREE_SELECTOR): the root of a SPA/framework mount is\n // usually a plain wrapper, and its sections arrive as descendants\n // of ONE childList mutation — inspecting only the root meant they\n // were never captured at all.\n try {\n node.querySelectorAll(SUBTREE_SELECTOR).forEach((el) => candidates.push(el));\n } catch {\n /* exotic host without querySelectorAll — root-only scan stands */\n }\n for (const el of candidates) {\n // Skip elements already registered: a parent and its child can\n // both appear in addedNodes (the child once via the parent's\n // subtree, once directly), which would emit duplicate nodes.\n if (knownElementToId.has(el)) continue;\n const scanned = scanElement(el, getProminenceScore);\n added.push(scanned);\n addedIds.add(scanned.componentId);\n knownElementToId.set(el, scanned.componentId);\n }\n });\n }\n if (added.length === 0 || !contentCallback) return;\n // Drop elements no longer in the document so removed nodes don't dangle\n // and the map stays bounded.\n for (const el of [...knownElementToId.keys()]) {\n if (!el.isConnected) knownElementToId.delete(el);\n }\n // Detect over the FULL known set so a child inserted under an already-\n // scanned parent still gets its parent→child edge, then surface only the\n // edges that touch a newly-added node (existing edges were already emitted).\n const edges = detectStructuralEdges(knownElementToId).filter(\n (e) => addedIds.has(e.fromComponentId) || addedIds.has(e.toComponentId),\n );\n contentCallback({ nodes: added, edges, addedAt: Date.now() });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n } catch {\n /* ignore */\n }\n };\n\n const destroy = (): void => {\n if (observer) {\n observer.disconnect();\n observer = null;\n }\n if (idleCallbackId && typeof cancelIdleCallback === 'function') {\n try {\n cancelIdleCallback(idleCallbackId);\n } catch {\n /* ignore */\n }\n }\n idleCallbackId = 0;\n contentCallback = null;\n knownElementToId.clear();\n };\n\n return {\n scan,\n observe,\n getProminenceScore,\n destroy,\n };\n}\n","/**\n * Graph-capable entry point for @sentientui/core.\n *\n * Import from `@sentientui/core/graph` when you need DOM graph scanning and\n * page-structure sync. This entry pulls in `scanner.ts` and `graph.ts` at\n * build time, giving bundlers a real tree-shaking boundary. Standard A/B tests\n * should use `@sentientui/core` (the lean entry) instead.\n */\n\n// Re-export everything from the lean entry except `init`, which we override\n// below — so a graph consumer never needs dual-entry imports (importing the\n// lean entry alongside this one risks initialising two clients).\nexport {\n detectDeviceClass,\n detectTrafficSource,\n detectTimeOfDay,\n deriveSessionSegment,\n referrerDomainFromReferer,\n grantConsent,\n} from './index.js';\n// Sourced from their own modules (identical bindings to the lean barrel's):\n// snapshot/pre-paint helpers, slot helpers, blocks, micro-signals, and the\n// session cookie name — all were missing here, which made the comment above\n// a lie and forced consumers into dual-entry imports.\nexport {\n SNAPSHOT_STORAGE_KEY_PREFIX,\n readSnapshot,\n writeSnapshot,\n renderPrePaintScript,\n} from './snapshot.js';\nexport type { DecisionSnapshot, SlotConfigEntry, SlotOps, CompoundLocator } from './snapshot.js';\nexport { armOfResult, baselineResultFor, baselineSlots, toWireSlot } from './slots.js';\nexport type { SlotDeclInput, SlotResult } from './slots.js';\nexport * from './blocks.js';\nexport { attachMicroSignalDetectors } from './micro-signals.js';\nexport type { MicroSignalEmitter, MicroSignalType } from './micro-signals.js';\nexport { sessionCookieName, LEGACY_SESSION_COOKIE_NAME } from './storage-key.js';\n// SSR preload helpers moved to `@sentientui/core/server` in 0.6.0.\nexport type {\n SentientConfig,\n AssignResult,\n SentientClient,\n} from './index.js';\nexport type {\n SessionConfig,\n SessionManager,\n EventType,\n SentientEvent,\n QueueConfig,\n Assignment,\n} from './index.js';\n// EventQueue/AssignmentCache are no longer on the lean barrel — source them from\n// their own modules so the `/graph` subpath keeps exposing them unchanged.\nexport type { EventQueue } from './queue.js';\nexport type { AssignmentCache } from './cache.js';\n// Scanner + graph types (live in this entry only).\nexport type {\n ScannedNode,\n ScanResult,\n ContentAddedEvent,\n DOMScanner,\n} from './scanner.js';\nexport type {\n PageNode,\n GraphSnapshot,\n GraphConfig,\n GraphClient,\n} from './graph.js';\nexport { sanitizePageUrl } from './graph.js';\nexport { locatorFromElement } from './locator-from-dom.js';\n\nimport {\n init as initLean,\n isDoNotTrackEnabled,\n _registerConsentUpgradeInit,\n type SentientConfig,\n type SentientClient,\n} from './index.js';\nexport { isDoNotTrackEnabled };\nimport { LEGACY_SESSION_COOKIE_NAME, sessionCookieName } from './storage-key.js';\n\nconst DEFAULT_INGEST_URL = 'https://api.sentient-ui.com/v1/events';\nimport { createDOMScanner } from './scanner.js';\nimport { createGraphClient } from './graph.js';\n\nexport type GraphSentientConfig = SentientConfig & {\n /**\n * Enable DOM graph scanning and page-structure sync. Wires a MutationObserver\n * and a localStorage-backed graph. When `false` (default) this entry behaves\n * identically to `@sentientui/core`.\n */\n graph?: boolean;\n /**\n * Include captured heading / DOM text in graph sync payloads. OFF by default —\n * headings can contain account names or user-generated content. Structure\n * (component ids, semantic types, prominence) still syncs when `graph: true`.\n */\n captureDomText?: boolean;\n};\n\n// The client writes the per-project SUFFIXED cookie (sessionCookieName in\n// storage-key.ts). This reader kept the bare `_snt_uid` after namespacing\n// landed, so graph sync sent `sessionId: undefined` for every keyed project.\n// The bare name stays as a fallback for pre-namespacing identities.\nfunction readSntUid(apiKey?: string): string | undefined {\n const read = (name: string): string | undefined => {\n try {\n // Cookie names are `_snt_uid` + `_` + a pk_ key prefix — no regex\n // metacharacters, so interpolation is safe (same pattern as session.ts).\n const m = document.cookie.match(new RegExp(`(?:^|; )${name}=([^;]*)`));\n return m ? decodeURIComponent(m[1]!) : undefined;\n } catch {\n return undefined;\n }\n };\n return (apiKey ? read(sessionCookieName(apiKey)) : undefined) ?? read(LEGACY_SESSION_COOKIE_NAME);\n}\n\n/**\n * Graph-capable variant of `init()`. Identical to the lean `init` when\n * `config.graph` is `false` (or omitted). When `config.graph: true`, mounts\n * a DOM scanner + graph client and enables `client.getGraph()`.\n *\n * Import from `@sentientui/core/graph` — do not call the lean `init` alongside\n * this function as that would initialise two clients.\n */\n// Teardown for the graph resources (scanner + MutationObserver + debounce\n// timer + graph client) bound to each apiKey. initLean already disposes the\n// lean client's own timers/listeners on re-init, but it knows nothing about\n// these graph resources, so this entry tracks and tears them down itself —\n// otherwise an HMR / consent-toggle / provider-remount re-init would leak a\n// live MutationObserver and a pending sync timer per mount.\nconst _graphTeardowns = new Map<string, () => void>();\n\nexport function init(config: GraphSentientConfig): SentientClient {\n const client = initLean(config);\n\n // Mirror initLean's opt-out gate: a DNT/GPC visitor (or consent:false) must\n // not get the DOM scanner + graph sync, which POST page-structure beacons and\n // read `_snt_uid` — tracking that bypasses the lean client's own gating, even\n // under `preConsentBehavior: 'statistical_winner'` (audit P1).\n const dntBlocked = config.respectDoNotTrack !== false && isDoNotTrackEnabled();\n const gated = config.consent === false || dntBlocked;\n\n // Zero-network contract, mirroring the lean init's own gate: `localMode:\n // true` forces the on-device engine, and a missing OR INVALID (non-`pk_`)\n // key means the lean client is keyless-local or disabled. This used to check\n // only `!apiKey`, so a typo'd key — which the React provider's default\n // `graph: true` reaches — still mounted the scanner and POSTed\n // /v1/graph/sync into a client that discards everything.\n const keyValid = typeof config.apiKey === 'string' && config.apiKey.startsWith('pk_');\n const zeroNetwork = config.localMode === true || !keyValid;\n if (!config.graph || zeroNetwork || typeof window === 'undefined') return client;\n\n if (gated) {\n // Consent may still be granted later: grantConsent() must re-init through\n // THIS entry so the post-consent client mounts the scanner — the lean init\n // it upgraded through before knows nothing about graph resources, so a\n // consent grant used to lose graph capture for the session. DNT-blocked\n // clients register nothing: consent cannot override a global opt-out.\n if (!dntBlocked) {\n _registerConsentUpgradeInit(config.apiKey, (c) => init(c as GraphSentientConfig));\n }\n return client;\n }\n\n // A prior graph mount for this key is now superseded — tear it down first so\n // its observer/timer don't leak alongside the new mount's.\n const prevTeardown = _graphTeardowns.get(config.apiKey);\n if (prevTeardown) {\n try {\n prevTeardown();\n } catch {\n /* teardown must never throw on re-init */\n }\n }\n\n const domScanner = createDOMScanner();\n const resolvedIngestUrl = config.ingestUrl ?? DEFAULT_INGEST_URL;\n const graphClient = createGraphClient({\n syncUrl: resolvedIngestUrl.replace(/\\/events\\/?$/, '/graph/sync'),\n apiKey: config.apiKey,\n projectId: config.apiKey,\n sessionId: readSntUid(config.apiKey),\n });\n\n // Persisted page-node state from a previous page load is restored by the graph\n // client's own constructor (it reads `_snt_graph_nodes` on creation). We no\n // longer re-read the key and call restore() here — that was a redundant second\n // load path that cleared and reloaded identical data.\n\n void domScanner.scan().then((result) => {\n for (const node of result.nodes) {\n graphClient.addPageNode({\n id: node.componentId,\n componentId: node.componentId,\n semanticType: node.semanticType,\n answers: config.captureDomText && node.headingText ? [node.headingText] : [],\n prominenceScore: node.prominenceScore,\n depth: node.depth,\n });\n }\n for (const edge of result.edges) {\n graphClient.addStructuralEdge(edge);\n }\n graphClient.syncOnce();\n });\n\n let syncDebounceTimer: ReturnType<typeof setTimeout> | null = null;\n const debouncedSync = (): void => {\n if (syncDebounceTimer !== null) clearTimeout(syncDebounceTimer);\n syncDebounceTimer = setTimeout(() => {\n syncDebounceTimer = null;\n graphClient.syncOnce();\n }, 500);\n };\n\n domScanner.observe((event) => {\n for (const node of event.nodes) {\n graphClient.addPageNode({\n id: node.componentId,\n componentId: node.componentId,\n semanticType: node.semanticType,\n answers: config.captureDomText && node.headingText ? [node.headingText] : [],\n prominenceScore: node.prominenceScore,\n depth: node.depth,\n });\n }\n for (const edge of event.edges) {\n graphClient.addStructuralEdge(edge);\n }\n debouncedSync();\n });\n\n // Tears down only the graph resources; the caller pairs it with the lean\n // client's own dispose/destroy. Idempotent, and de-registers itself so a\n // later re-init or teardown can't run it twice on already-freed resources.\n const teardownGraph = (): void => {\n if (syncDebounceTimer !== null) {\n clearTimeout(syncDebounceTimer);\n syncDebounceTimer = null;\n }\n domScanner.destroy();\n graphClient.destroy();\n if (_graphTeardowns.get(config.apiKey) === teardownGraph) {\n _graphTeardowns.delete(config.apiKey);\n }\n };\n _graphTeardowns.set(config.apiKey, teardownGraph);\n\n return {\n ...client,\n getGraph: () => graphClient.snapshot(),\n dispose: () => {\n teardownGraph();\n client.dispose();\n },\n destroy: () => {\n teardownGraph();\n client.destroy();\n },\n };\n}\n"],"mappings":"meA4CA,IAAMA,EAAkB,mBAElBC,GAAgD,CACpD,QAAS,CAAC,WAAY,KAAK,EAC3B,SAAU,CAAC,SAAS,EACpB,IAAK,CAAC,SAAS,EACf,aAAc,CAAC,KAAK,EACpB,IAAK,CAAC,eAAgB,OAAQ,OAAO,EACrC,KAAM,CAAC,KAAK,EACZ,WAAY,CAAC,SAAS,EACtB,MAAO,CAAC,KAAK,CACf,EAEA,SAASC,GAAcC,EAAgC,CAzDvD,IAAAC,EA0DE,OAAOA,EAAAH,GAAoBE,CAAY,IAAhC,KAAAC,EAAqC,CAAC,CAC/C,CAEA,SAASC,GAAeC,EAAaC,EAAgB,CACnD,GAAI,CACF,IAAMC,EAAM,aAAa,QAAQF,CAAG,EACpC,OAAKE,EACE,KAAK,MAAMA,CAAG,EADJD,CAEnB,OAAQE,EAAA,CACN,OAAOF,CACT,CACF,CAEA,SAASG,GAAaJ,EAAaK,EAAsB,CACvD,GAAI,CACF,aAAa,QAAQL,EAAK,KAAK,UAAUK,CAAK,CAAC,CACjD,OAAQF,EAA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ACxB,aAAaA,CAAiB,EAC9BA,EAAoB,MAEtBR,EAAW,QAAQ,EACnBG,EAAY,QAAQ,EAChBf,EAAgB,IAAIE,EAAO,MAAM,IAAMqB,GACzCvB,EAAgB,OAAOE,EAAO,MAAM,CAExC,EACA,OAAAF,EAAgB,IAAIE,EAAO,OAAQqB,CAAa,EAEzCC,EAAAC,EAAA,GACFtB,GADE,CAEL,SAAU,IAAMY,EAAY,SAAS,EACrC,QAAS,IAAM,CACbQ,EAAc,EACdpB,EAAO,QAAQ,CACjB,EACA,QAAS,IAAM,CACboB,EAAc,EACdpB,EAAO,QAAQ,CACjB,CACF,EACF","names":["STALE_EDGES_KEY","SEMANTIC_NEIGHBOURS","neighboursFor","semanticType","_a","readStorage","key","fallback","raw","e","writeStorage","value","VALID_SEMANTIC_TYPES","toValidSemanticType","type","sanitizePageUrl","href","u","contentHashOf","componentId","answers","input","h","createGraphClient","config","pageNodes","structuralEdges","nodesKey","storageSuffix","persist","storedNodes","node","edge","_b","nodes","nodesByType","n","list","edges","seen","source","neighbourType","targets","target","componentIds","payload","__spreadProps","__spreadValues","OBSERVE_TAGS","HEADING_SELECTOR","SUBTREE_SELECTOR","MAX_SIBLINGS_PER_GROUP","MAX_STRUCTURAL_EDGES","SSR_SCANNER","normalize","value","min","max","readReactComponentName","element","_a","_b","_c","record","key","fiber","name","e","extractDataAttributes","attrs","attr","SEMANTIC_SET","SEMANTIC_TYPES","inferSemanticType","explicit","role","classifySection","shortHash","input","h","i","domPathSignature","parts","current","parent","index","componentIdFor","declared","depthOf","depth","scanElement","getProminenceScore","_d","heading","locatorFromElement","detectStructuralEdges","elementToId","edges","seen","ROOT","groups","el","_id","ancestor","groupKey","childId","siblings","sibs","capped","j","aId","bId","fwd","rev","collectNodesAndEdges","nodes","node","hasAria","hasSentientId","createDOMScanner","observer","idleCallbackId","contentCallback","knownElementToId","styles","fontSize","zIndex","rect","distanceFromTop","viewportHeight","inverseDistance","score","resolve","run","id","onContentAdded","mutations","added","addedIds","mutation","candidates","scanned","DEFAULT_INGEST_URL","readSntUid","apiKey","_a","read","name","m","e","sessionCookieName","LEGACY_SESSION_COOKIE_NAME","_graphTeardowns","init","config","client","dntBlocked","isDoNotTrackEnabled","gated","keyValid","zeroNetwork","_registerConsentUpgradeInit","c","prevTeardown","domScanner","createDOMScanner","resolvedIngestUrl","graphClient","createGraphClient","result","node","edge","syncDebounceTimer","debouncedSync","event","teardownGraph","__spreadProps","__spreadValues"]}
|
|
1
|
+
{"version":3,"sources":["../src/graph.ts","../src/scanner.ts","../src/index-graph.ts"],"sourcesContent":["/** In-memory context graph with persistence and backend sync. */\n\nimport { storageSuffix } from './storage-key.js';\n\nexport type PageNode = {\n id: string;\n componentId: string;\n semanticType: string;\n answers: string[];\n prominenceScore: number;\n depth: number;\n};\n\nexport type GraphSnapshot = {\n pageNodes: PageNode[];\n capturedAt: number;\n};\n\nexport type GraphConfig = {\n syncUrl?: string;\n apiKey?: string;\n projectId?: string;\n sessionId?: string;\n};\n\nexport type StructuralEdge = {\n fromComponentId: string;\n toComponentId: string;\n weight: number;\n};\n\nexport type GraphClient = {\n addPageNode(node: PageNode): void;\n /** Record a DOM-derived parent/child or sibling relationship between two components. */\n addStructuralEdge(edge: StructuralEdge): void;\n /** One-shot batch sync of all current page nodes to the backend. */\n syncOnce(): void;\n snapshot(): GraphSnapshot;\n destroy(): void;\n};\n\n// _snt_graph_edges was written by earlier builds but never synced to the backend.\n// We still read and clear any leftover key on init/destroy so old clients don't\n// accumulate stale data, but we no longer write it.\nconst STALE_EDGES_KEY = '_snt_graph_edges';\n\nconst SEMANTIC_NEIGHBOURS: Record<string, string[]> = {\n pricing: ['features', 'faq'],\n features: ['pricing'],\n faq: ['pricing'],\n social_proof: ['cta'],\n cta: ['social_proof', 'hero', 'trust'],\n hero: ['cta'],\n comparison: ['pricing'],\n trust: ['cta'],\n};\n\nfunction neighboursFor(semanticType: string): string[] {\n return SEMANTIC_NEIGHBOURS[semanticType] ?? [];\n}\n\nfunction readStorage<T>(key: string, fallback: T): T {\n try {\n const raw = localStorage.getItem(key);\n if (!raw) return fallback;\n return JSON.parse(raw) as T;\n } catch {\n return fallback;\n }\n}\n\nfunction writeStorage(key: string, value: unknown): void {\n try {\n localStorage.setItem(key, JSON.stringify(value));\n } catch {\n /* ignore */\n }\n}\n\nconst VALID_SEMANTIC_TYPES = new Set([\n 'pricing', 'hero', 'social_proof', 'cta', 'features',\n 'faq', 'comparison', 'trust', 'navigation', 'generic',\n]);\n\nfunction toValidSemanticType(type: string): string {\n return VALID_SEMANTIC_TYPES.has(type) ? type : 'generic';\n}\n\n/**\n * Path-only page URL for graph sync — strips query + fragment so tokens,\n * emails, and other sensitive URL params never leave the browser by default.\n */\nexport function sanitizePageUrl(href: string): string {\n try {\n const u = new URL(href);\n return `${u.origin}${u.pathname}`;\n } catch {\n return '/';\n }\n}\n\nfunction contentHashOf(componentId: string, semanticType: string, answers: string[]): string {\n const input = `${componentId}:${semanticType}:${answers.join(',')}`;\n let h = 5381;\n for (let i = 0; i < input.length; i++) {\n h = ((h << 5) + h + input.charCodeAt(i)) & 0xffffffff;\n }\n return (h >>> 0).toString(16).padStart(8, '0');\n}\n\n/**\n * Creates an in-memory graph client with optional persistence and sync.\n */\nexport function createGraphClient(config?: GraphConfig): GraphClient {\n const pageNodes = new Map<string, PageNode>();\n const structuralEdges = new Map<string, StructuralEdge>();\n\n // Per-project localStorage key so two projects on one origin don't share a\n // graph-node cache (see storage-key.ts). Legacy `_snt_graph_nodes` with no key.\n const nodesKey = `_snt_graph_nodes${storageSuffix(config?.apiKey)}`;\n\n const persist = (): void => {\n if (typeof window === 'undefined') return;\n writeStorage(nodesKey, [...pageNodes.values()]);\n };\n\n // serialize()/restore() were removed here: persisted-node restoration moved\n // into this constructor (below), leaving both dead — yet still shipping in\n // the graph bundle.\n if (typeof window !== 'undefined') {\n const storedNodes = readStorage<PageNode[]>(nodesKey, []);\n for (const node of storedNodes) {\n pageNodes.set(node.componentId, node);\n }\n // Clear any stale edge data written by older SDK versions.\n try { localStorage.removeItem(STALE_EDGES_KEY); } catch { /* ignore */ }\n }\n\n return {\n addPageNode(node: PageNode): void {\n pageNodes.set(node.componentId, node);\n persist();\n },\n\n addStructuralEdge(edge: StructuralEdge): void {\n const key = `${edge.fromComponentId}->${edge.toComponentId}`;\n structuralEdges.set(key, edge);\n },\n\n syncOnce(): void {\n if (!config?.syncUrl || typeof window === 'undefined') return;\n const nodes = [...pageNodes.values()];\n if (nodes.length === 0) return;\n try {\n // Build semantic edges from the SEMANTIC_NEIGHBOURS map. Each node emits\n // an edge to every present sibling that matches one of its neighbour types.\n // Weight matches propagate()'s 0.4 attention factor; confidence is high\n // because the mapping is curated, not inferred.\n const nodesByType = new Map<string, PageNode[]>();\n for (const n of nodes) {\n const list = nodesByType.get(n.semanticType) ?? [];\n list.push(n);\n nodesByType.set(n.semanticType, list);\n }\n const edges: Array<{\n fromComponentId: string;\n toComponentId: string;\n type: 'semantic' | 'structural';\n weight: number;\n confidence: number;\n }> = [];\n const seen = new Set<string>();\n for (const source of nodes) {\n for (const neighbourType of neighboursFor(source.semanticType)) {\n const targets = nodesByType.get(neighbourType) ?? [];\n for (const target of targets) {\n if (target.componentId === source.componentId) continue;\n const key = `semantic:${source.componentId}->${target.componentId}`;\n if (seen.has(key)) continue;\n seen.add(key);\n edges.push({\n fromComponentId: source.componentId,\n toComponentId: target.componentId,\n type: 'semantic',\n weight: 0.4,\n confidence: 0.9,\n });\n }\n }\n }\n\n // Structural edges from DOM relationships, recorded during scan.\n // Only emit when both endpoints are present in this page's node set —\n // a structural edge to/from a node that no longer exists would dangle.\n const componentIds = new Set(nodes.map((n) => n.componentId));\n for (const edge of structuralEdges.values()) {\n if (!componentIds.has(edge.fromComponentId) || !componentIds.has(edge.toComponentId)) continue;\n const key = `structural:${edge.fromComponentId}->${edge.toComponentId}`;\n if (seen.has(key)) continue;\n seen.add(key);\n edges.push({\n fromComponentId: edge.fromComponentId,\n toComponentId: edge.toComponentId,\n type: 'structural',\n weight: edge.weight,\n confidence: 1.0,\n });\n }\n\n const payload = {\n pageUrl: sanitizePageUrl(window.location.href),\n // Visitor/project attribution. The /graph/sync handler ignores unknown\n // top-level fields (Fastify additionalProperties + Zod strips extras),\n // so these ride along harmlessly and let beacons carry attribution.\n ...(config.sessionId ? { sessionId: config.sessionId } : {}),\n ...(config.projectId ? { projectId: config.projectId } : {}),\n nodes: nodes.map((n) => {\n const semanticType = toValidSemanticType(n.semanticType);\n return {\n componentId: n.componentId,\n semanticType,\n answers: n.answers,\n contentHash: contentHashOf(n.componentId, semanticType, n.answers),\n prominenceScore: n.prominenceScore,\n depthInPage: n.depth,\n };\n }),\n edges,\n };\n fetch(config.syncUrl, {\n method: 'POST',\n keepalive: true,\n headers: {\n 'Content-Type': 'application/json',\n ...(config.apiKey ? { Authorization: `Bearer ${config.apiKey}` } : {}),\n },\n body: JSON.stringify(payload),\n }).catch(() => undefined);\n } catch {\n /* ignore */\n }\n },\n\n snapshot(): GraphSnapshot {\n return {\n pageNodes: [...pageNodes.values()],\n capturedAt: Date.now(),\n };\n },\n\n destroy(): void {\n if (typeof window === 'undefined') return;\n try {\n localStorage.removeItem(nodesKey);\n localStorage.removeItem(STALE_EDGES_KEY);\n } catch {\n /* ignore */\n }\n },\n };\n}\n","/** Reads the rendered DOM to build the page-side context graph. */\n\nimport { classifySection, SEMANTIC_TYPES, type SemanticType } from './engagement/classify';\nimport { locatorFromElement } from './locator-from-dom.js';\nimport type { CompoundLocator } from './snapshot.js';\n\nexport type ScannedNode = {\n componentId: string;\n semanticType: string;\n ariaLabel?: string;\n headingText?: string;\n isAboveFold: boolean;\n prominenceScore: number;\n depth: number;\n reactComponentName?: string;\n dataAttributes: Record<string, string>;\n /** Compound locator for this element. The server hashes it into section_key —\n * the identity the crawler and the snippet resolve to for the same physical\n * section. Undefined when nothing resolves uniquely: the runtime never\n * guesses an identity it could not verify later. */\n locator?: CompoundLocator;\n};\n\nexport type StructuralEdge = {\n fromComponentId: string;\n toComponentId: string;\n /** 0.6 for direct parent → child, 0.3 for sibling (both directions emitted). */\n weight: number;\n};\n\nexport type ScanResult = {\n nodes: ScannedNode[];\n edges: StructuralEdge[];\n scannedAt: number;\n};\n\nexport type ContentAddedEvent = {\n nodes: ScannedNode[];\n edges: StructuralEdge[];\n addedAt: number;\n};\n\nexport type DOMScanner = {\n scan(): Promise<ScanResult>;\n observe(onContentAdded: (event: ContentAddedEvent) => void): void;\n getProminenceScore(element: Element): number;\n destroy(): void;\n};\n\n// ASIDE included to match the initial scan (which queries `section, article,\n// main, aside`) — this set omitted it, so a server-rendered aside was captured\n// while an identical dynamically-inserted one was silently ignored.\nconst OBSERVE_TAGS = new Set(['SECTION', 'ARTICLE', 'MAIN', 'DIV', 'ASIDE']);\nconst HEADING_SELECTOR = 'h1, h2, h3';\n// Selector mirror of the initial scan's criteria (collectNodesAndEdges): any\n// element carrying a declared id, plus structural tags with an aria-label.\n// Used to walk INTO inserted subtrees — a SPA mounts ONE root node whose\n// interesting sections are all descendants, and inspecting only the root made\n// every framework-mounted component permanently invisible to graph capture.\nconst SUBTREE_SELECTOR =\n '[data-sentient-id], section[aria-label], article[aria-label], main[aria-label], aside[aria-label]';\n\n// Sibling detection is O(n²) per group and emits two edges per pair, so a page\n// with hundreds of co-located components (e.g. a 200-cell product grid) would\n// otherwise emit tens of thousands of low-signal sibling edges. We cap the\n// sibling fan-out per group and the total structural edges per detection pass.\n// The total stays well under the server's 2000-edge-per-sync limit, leaving room\n// for semantic edges. Parent→child edges (higher signal) are emitted first, so\n// the cap sheds sibling edges before it ever touches them.\nconst MAX_SIBLINGS_PER_GROUP = 30;\nconst MAX_STRUCTURAL_EDGES = 1500;\n\nconst SSR_SCANNER: DOMScanner = {\n scan: async () => ({ nodes: [], edges: [], scannedAt: 0 }),\n observe: () => undefined,\n getProminenceScore: () => 0,\n destroy: () => undefined,\n};\n\nfunction normalize(value: number, min: number, max: number): number {\n if (max <= min) return 0;\n return Math.max(0, Math.min(1, (value - min) / (max - min)));\n}\n\nfunction readReactComponentName(element: Element): string | undefined {\n try {\n const record = element as unknown as Record<string, unknown>;\n for (const key of Object.keys(record)) {\n if (!key.startsWith('__reactFiber') && !key.startsWith('__reactInternalInstance')) {\n continue;\n }\n const fiber = record[key] as { type?: { name?: string; displayName?: string } };\n const name = fiber?.type?.displayName ?? fiber?.type?.name;\n if (name && name.length > 1) {\n return name;\n }\n }\n } catch {\n /* ignore */\n }\n return undefined;\n}\n\nfunction extractDataAttributes(element: Element): Record<string, string> {\n const attrs: Record<string, string> = {};\n for (const attr of Array.from(element.attributes)) {\n if (attr.name.startsWith('data-')) {\n attrs[attr.name] = attr.value;\n }\n }\n return attrs;\n}\n\nconst SEMANTIC_SET: ReadonlySet<string> = new Set(SEMANTIC_TYPES);\n\n// Explicit tag wins → role → heuristic → generic. Every output is normalized to\n// the graph_nodes enum: an out-of-vocabulary data-sentient-type/role falls\n// through to the heuristic instead of being emitted raw (raw values violated\n// the graph_nodes CHECK constraint on insert).\nfunction inferSemanticType(element: Element): SemanticType {\n const explicit = element.getAttribute('data-sentient-type');\n if (explicit && SEMANTIC_SET.has(explicit)) return explicit as SemanticType;\n const role = element.getAttribute('role');\n if (role && SEMANTIC_SET.has(role)) return role as SemanticType;\n return classifySection(element);\n}\n\n// djb2 over a string → 8-hex-char digest. Stable and collision-resistant enough\n// to disambiguate co-located components that declare no id of their own.\nfunction shortHash(input: string): string {\n let h = 5381;\n for (let i = 0; i < input.length; i++) {\n h = ((h << 5) + h + input.charCodeAt(i)) & 0xffffffff;\n }\n return (h >>> 0).toString(16).padStart(8, '0');\n}\n\n// A structural path (tag + sibling index at each level up to the root) uniquely\n// and stably identifies an element's DOM position, so two id-less sections don't\n// hash to the same value the way a bare tagName would.\nfunction domPathSignature(element: Element): string {\n const parts: string[] = [];\n let current: Element | null = element;\n while (current) {\n const parent: Element | null = current.parentElement;\n if (!parent) {\n parts.push(current.tagName.toLowerCase());\n break;\n }\n const index = Array.prototype.indexOf.call(parent.children, current);\n parts.push(`${current.tagName.toLowerCase()}[${index}]`);\n current = parent;\n }\n return parts.reverse().join('/');\n}\n\n// Prefer an author-declared id. When none exists, synthesize a stable, unique id\n// from the element's DOM path — the old `tagName.toLowerCase()` fallback gave\n// every id-less <section> the same \"section\" id, so a second such node silently\n// overwrote the first in the componentId-keyed graph Map (node loss).\nfunction componentIdFor(element: Element): string {\n const declared =\n element.getAttribute('data-sentient-id') ?? element.getAttribute('id');\n if (declared) return declared;\n return `${element.tagName.toLowerCase()}-${shortHash(domPathSignature(element))}`;\n}\n\nfunction depthOf(element: Element): number {\n let depth = 0;\n let current: Element | null = element.parentElement;\n while (current) {\n depth++;\n current = current.parentElement;\n }\n return depth;\n}\n\nfunction scanElement(\n element: Element,\n getProminenceScore: (el: Element) => number,\n): ScannedNode {\n const heading = element.querySelector(HEADING_SELECTOR);\n return {\n componentId: componentIdFor(element),\n semanticType: inferSemanticType(element),\n ariaLabel: element.getAttribute('aria-label') ?? undefined,\n headingText: heading?.textContent?.trim() ?? undefined,\n isAboveFold: element.getBoundingClientRect().top < window.innerHeight,\n prominenceScore: getProminenceScore(element),\n depth: depthOf(element),\n reactComponentName: readReactComponentName(element),\n dataAttributes: extractDataAttributes(element),\n locator: locatorFromElement(element, element.ownerDocument) ?? undefined,\n };\n}\n\n/**\n * Detects structural relationships between scanned component elements:\n * - parent → child (direct ancestor link, weight 0.6)\n * - sibling ↔ sibling (share nearest component ancestor, weight 0.3, bidirectional)\n * A pair appears at most once per direction.\n */\nfunction detectStructuralEdges(elementToId: Map<Element, string>): StructuralEdge[] {\n const edges: StructuralEdge[] = [];\n const seen = new Set<string>();\n const ROOT = '__root__';\n\n // Parent → child: nearest component ancestor only.\n const groups = new Map<string, Element[]>();\n for (const [el, _id] of elementToId) {\n let ancestor: Element | null = el.parentElement;\n let groupKey = ROOT;\n while (ancestor) {\n if (elementToId.has(ancestor)) {\n groupKey = elementToId.get(ancestor)!;\n const childId = elementToId.get(el)!;\n const key = `${groupKey}->${childId}`;\n if (!seen.has(key) && groupKey !== childId) {\n seen.add(key);\n edges.push({ fromComponentId: groupKey, toComponentId: childId, weight: 0.6 });\n }\n break;\n }\n ancestor = ancestor.parentElement;\n }\n const siblings = groups.get(groupKey) ?? [];\n siblings.push(el);\n groups.set(groupKey, siblings);\n }\n\n // Sibling ↔ sibling: same ancestor group.\n for (const sibs of groups.values()) {\n if (sibs.length < 2) continue;\n // Cap the fan-out of any single group before the O(n²) pairing.\n const capped = sibs.length > MAX_SIBLINGS_PER_GROUP ? sibs.slice(0, MAX_SIBLINGS_PER_GROUP) : sibs;\n for (let i = 0; i < capped.length; i++) {\n for (let j = i + 1; j < capped.length; j++) {\n if (edges.length >= MAX_STRUCTURAL_EDGES) return edges;\n const aId = elementToId.get(capped[i]!)!;\n const bId = elementToId.get(capped[j]!)!;\n if (aId === bId) continue;\n const fwd = `${aId}->${bId}::sib`;\n const rev = `${bId}->${aId}::sib`;\n if (!seen.has(fwd)) {\n seen.add(fwd);\n edges.push({ fromComponentId: aId, toComponentId: bId, weight: 0.3 });\n }\n if (!seen.has(rev)) {\n seen.add(rev);\n edges.push({ fromComponentId: bId, toComponentId: aId, weight: 0.3 });\n }\n }\n }\n }\n\n return edges;\n}\n\nfunction collectNodesAndEdges(\n getProminenceScore: (el: Element) => number,\n): { nodes: ScannedNode[]; edges: StructuralEdge[]; elementToId: Map<Element, string> } {\n const nodes: ScannedNode[] = [];\n const seen = new Set<Element>();\n const elementToId = new Map<Element, string>();\n\n const registered = document.querySelectorAll('[data-sentient-id]');\n registered.forEach((el) => {\n if (el instanceof Element && !seen.has(el)) {\n seen.add(el);\n const node = scanElement(el, getProminenceScore);\n nodes.push(node);\n elementToId.set(el, node.componentId);\n }\n });\n\n const structural = document.querySelectorAll('section, article, main, aside');\n structural.forEach((el) => {\n if (!(el instanceof Element) || seen.has(el)) return;\n const hasAria = el.hasAttribute('aria-label');\n const hasSentientId = el.hasAttribute('data-sentient-id');\n if (!hasAria && !hasSentientId) return;\n seen.add(el);\n const node = scanElement(el, getProminenceScore);\n nodes.push(node);\n elementToId.set(el, node.componentId);\n });\n\n return { nodes, edges: detectStructuralEdges(elementToId), elementToId };\n}\n\n/**\n * Creates a DOM scanner that uses idle callbacks and mutation observation.\n */\nexport function createDOMScanner(): DOMScanner {\n if (typeof window === 'undefined') {\n return SSR_SCANNER;\n }\n\n let observer: MutationObserver | null = null;\n let idleCallbackId = 0;\n let contentCallback: ((event: ContentAddedEvent) => void) | null = null;\n // Element→componentId for every node registered so far (initial scan + prior\n // mutations). The MutationObserver detects edges against this whole set — not\n // just the nodes in the current mutation — so a child inserted under an\n // already-scanned parent still gets its parent→child edge.\n const knownElementToId = new Map<Element, string>();\n\n const getProminenceScore = (element: Element): number => {\n try {\n const styles = window.getComputedStyle(element);\n const fontSize = parseFloat(styles.fontSize) || 12;\n const zIndex = parseFloat(styles.zIndex) || 0;\n const rect = element.getBoundingClientRect();\n const distanceFromTop = Math.max(rect.top, 0);\n const viewportHeight = window.innerHeight || 1;\n const inverseDistance = 1 / (distanceFromTop / viewportHeight + 1);\n\n // inverseDistance is already in (0, 1] by construction, so it needs no\n // further normalization — only fontSize and zIndex are rescaled.\n const score =\n normalize(fontSize, 12, 48) * 0.4 +\n inverseDistance * 0.4 +\n normalize(zIndex, 0, 100) * 0.2;\n\n return Math.max(0, Math.min(1, score));\n } catch {\n return 0.5;\n }\n };\n\n const scan = (): Promise<ScanResult> =>\n new Promise((resolve) => {\n const run = (): void => {\n const { nodes, edges, elementToId } = collectNodesAndEdges(getProminenceScore);\n // Seed the known-element registry so the observer can resolve parents that\n // were registered in this scan when later children are inserted.\n knownElementToId.clear();\n for (const [el, id] of elementToId) knownElementToId.set(el, id);\n resolve({ nodes, edges, scannedAt: Date.now() });\n };\n\n try {\n if (typeof requestIdleCallback === 'function') {\n idleCallbackId = requestIdleCallback(run, { timeout: 100 });\n } else {\n run();\n }\n } catch {\n run();\n }\n });\n\n const observe = (onContentAdded: (event: ContentAddedEvent) => void): void => {\n contentCallback = onContentAdded;\n try {\n observer = new MutationObserver((mutations) => {\n const added: ScannedNode[] = [];\n const addedIds = new Set<string>();\n for (const mutation of mutations) {\n if (mutation.type !== 'childList') continue;\n mutation.addedNodes.forEach((node) => {\n if (!(node instanceof Element)) return;\n const candidates: Element[] = [];\n if (\n OBSERVE_TAGS.has(node.tagName) &&\n (node.hasAttribute('data-sentient-id') || node.hasAttribute('aria-label'))\n ) {\n candidates.push(node);\n }\n // Also scan the inserted SUBTREE with the initial scan's criteria\n // (see SUBTREE_SELECTOR): the root of a SPA/framework mount is\n // usually a plain wrapper, and its sections arrive as descendants\n // of ONE childList mutation — inspecting only the root meant they\n // were never captured at all.\n try {\n node.querySelectorAll(SUBTREE_SELECTOR).forEach((el) => candidates.push(el));\n } catch {\n /* exotic host without querySelectorAll — root-only scan stands */\n }\n for (const el of candidates) {\n // Skip elements already registered: a parent and its child can\n // both appear in addedNodes (the child once via the parent's\n // subtree, once directly), which would emit duplicate nodes.\n if (knownElementToId.has(el)) continue;\n const scanned = scanElement(el, getProminenceScore);\n added.push(scanned);\n addedIds.add(scanned.componentId);\n knownElementToId.set(el, scanned.componentId);\n }\n });\n }\n if (added.length === 0 || !contentCallback) return;\n // Drop elements no longer in the document so removed nodes don't dangle\n // and the map stays bounded.\n for (const el of [...knownElementToId.keys()]) {\n if (!el.isConnected) knownElementToId.delete(el);\n }\n // Detect over the FULL known set so a child inserted under an already-\n // scanned parent still gets its parent→child edge, then surface only the\n // edges that touch a newly-added node (existing edges were already emitted).\n const edges = detectStructuralEdges(knownElementToId).filter(\n (e) => addedIds.has(e.fromComponentId) || addedIds.has(e.toComponentId),\n );\n contentCallback({ nodes: added, edges, addedAt: Date.now() });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n } catch {\n /* ignore */\n }\n };\n\n const destroy = (): void => {\n if (observer) {\n observer.disconnect();\n observer = null;\n }\n if (idleCallbackId && typeof cancelIdleCallback === 'function') {\n try {\n cancelIdleCallback(idleCallbackId);\n } catch {\n /* ignore */\n }\n }\n idleCallbackId = 0;\n contentCallback = null;\n knownElementToId.clear();\n };\n\n return {\n scan,\n observe,\n getProminenceScore,\n destroy,\n };\n}\n","/**\n * Graph-capable entry point for @sentientui/core.\n *\n * Import from `@sentientui/core/graph` when you need DOM graph scanning and\n * page-structure sync. This entry pulls in `scanner.ts` and `graph.ts` at\n * build time, giving bundlers a real tree-shaking boundary. Standard A/B tests\n * should use `@sentientui/core` (the lean entry) instead.\n */\n\n// Re-export everything from the lean entry except `init`, which we override\n// below — so a graph consumer never needs dual-entry imports (importing the\n// lean entry alongside this one risks initialising two clients).\nexport {\n detectDeviceClass,\n detectTrafficSource,\n detectTimeOfDay,\n deriveSessionSegment,\n referrerDomainFromReferer,\n grantConsent,\n} from './index.js';\n// Sourced from their own modules (identical bindings to the lean barrel's):\n// snapshot/pre-paint helpers, slot helpers, blocks, micro-signals, and the\n// session cookie name — all were missing here, which made the comment above\n// a lie and forced consumers into dual-entry imports.\nexport {\n SNAPSHOT_STORAGE_KEY_PREFIX,\n readSnapshot,\n writeSnapshot,\n renderPrePaintScript,\n} from './snapshot.js';\nexport type { DecisionSnapshot, SlotConfigEntry, SlotOps, CompoundLocator } from './snapshot.js';\nexport { armOfResult, baselineResultFor, baselineSlots, toWireSlot } from './slots.js';\nexport type { SlotDeclInput, SlotResult } from './slots.js';\nexport * from './blocks.js';\nexport { attachMicroSignalDetectors } from './micro-signals.js';\nexport type { MicroSignalEmitter, MicroSignalType } from './micro-signals.js';\nexport { sessionCookieName, LEGACY_SESSION_COOKIE_NAME } from './storage-key.js';\n// SSR preload helpers moved to `@sentientui/core/server` in 0.6.0.\nexport type {\n SentientConfig,\n AssignResult,\n SentientClient,\n} from './index.js';\nexport type {\n SessionConfig,\n SessionManager,\n EventType,\n SentientEvent,\n QueueConfig,\n Assignment,\n} from './index.js';\n// EventQueue/AssignmentCache are no longer on the lean barrel — source them from\n// their own modules so the `/graph` subpath keeps exposing them unchanged.\nexport type { EventQueue } from './queue.js';\nexport type { AssignmentCache } from './cache.js';\n// Scanner + graph types (live in this entry only).\nexport type {\n ScannedNode,\n ScanResult,\n ContentAddedEvent,\n DOMScanner,\n} from './scanner.js';\nexport type {\n PageNode,\n GraphSnapshot,\n GraphConfig,\n GraphClient,\n} from './graph.js';\nexport { sanitizePageUrl } from './graph.js';\nexport { locatorFromElement } from './locator-from-dom.js';\n\nimport {\n init as initLean,\n isDoNotTrackEnabled,\n _registerConsentUpgradeInit,\n type SentientConfig,\n type SentientClient,\n} from './index.js';\nexport { isDoNotTrackEnabled };\nimport { LEGACY_SESSION_COOKIE_NAME, sessionCookieName } from './storage-key.js';\n\nconst DEFAULT_INGEST_URL = 'https://api.sentient-ui.com/v1/events';\nimport { createDOMScanner } from './scanner.js';\nimport { createGraphClient } from './graph.js';\n\nexport type GraphSentientConfig = SentientConfig & {\n /**\n * Enable DOM graph scanning and page-structure sync. Wires a MutationObserver\n * and a localStorage-backed graph. When `false` (default) this entry behaves\n * identically to `@sentientui/core`.\n */\n graph?: boolean;\n /**\n * Include captured heading / DOM text in graph sync payloads. OFF by default —\n * headings can contain account names or user-generated content. Structure\n * (component ids, semantic types, prominence) still syncs when `graph: true`.\n */\n captureDomText?: boolean;\n};\n\n// The client writes the per-project SUFFIXED cookie (sessionCookieName in\n// storage-key.ts). This reader kept the bare `_snt_uid` after namespacing\n// landed, so graph sync sent `sessionId: undefined` for every keyed project.\n// The bare name stays as a fallback for pre-namespacing identities.\nfunction readSntUid(apiKey?: string): string | undefined {\n const read = (name: string): string | undefined => {\n try {\n // Cookie names are `_snt_uid` + `_` + a pk_ key prefix — no regex\n // metacharacters, so interpolation is safe (same pattern as session.ts).\n const m = document.cookie.match(new RegExp(`(?:^|; )${name}=([^;]*)`));\n return m ? decodeURIComponent(m[1]!) : undefined;\n } catch {\n return undefined;\n }\n };\n return (apiKey ? read(sessionCookieName(apiKey)) : undefined) ?? read(LEGACY_SESSION_COOKIE_NAME);\n}\n\n/**\n * Graph-capable variant of `init()`. Identical to the lean `init` when\n * `config.graph` is `false` (or omitted). When `config.graph: true`, mounts\n * a DOM scanner + graph client and enables `client.getGraph()`.\n *\n * Import from `@sentientui/core/graph` — do not call the lean `init` alongside\n * this function as that would initialise two clients.\n */\n// Teardown for the graph resources (scanner + MutationObserver + debounce\n// timer + graph client) bound to each apiKey. initLean already disposes the\n// lean client's own timers/listeners on re-init, but it knows nothing about\n// these graph resources, so this entry tracks and tears them down itself —\n// otherwise an HMR / consent-toggle / provider-remount re-init would leak a\n// live MutationObserver and a pending sync timer per mount.\nconst _graphTeardowns = new Map<string, () => void>();\n\nexport function init(config: GraphSentientConfig): SentientClient {\n const client = initLean(config);\n\n // Mirror initLean's opt-out gate: a DNT/GPC visitor (or consent:false) must\n // not get the DOM scanner + graph sync, which POST page-structure beacons and\n // read `_snt_uid` — tracking that bypasses the lean client's own gating, even\n // under `preConsentBehavior: 'statistical_winner'` (audit P1).\n const dntBlocked = config.respectDoNotTrack !== false && isDoNotTrackEnabled();\n const gated = config.consent === false || dntBlocked;\n\n // Zero-network contract, mirroring the lean init's own gate: `localMode:\n // true` forces the on-device engine, and a missing OR INVALID (non-`pk_`)\n // key means the lean client is keyless-local or disabled. This used to check\n // only `!apiKey`, so a typo'd key — which the React provider's default\n // `graph: true` reaches — still mounted the scanner and POSTed\n // /v1/graph/sync into a client that discards everything.\n const keyValid = typeof config.apiKey === 'string' && config.apiKey.startsWith('pk_');\n const zeroNetwork = config.localMode === true || !keyValid;\n if (!config.graph || zeroNetwork || typeof window === 'undefined') return client;\n\n if (gated) {\n // Consent may still be granted later: grantConsent() must re-init through\n // THIS entry so the post-consent client mounts the scanner — the lean init\n // it upgraded through before knows nothing about graph resources, so a\n // consent grant used to lose graph capture for the session. DNT-blocked\n // clients register nothing: consent cannot override a global opt-out.\n if (!dntBlocked) {\n _registerConsentUpgradeInit(config.apiKey, (c) => init(c as GraphSentientConfig));\n }\n return client;\n }\n\n // A prior graph mount for this key is now superseded — tear it down first so\n // its observer/timer don't leak alongside the new mount's.\n const prevTeardown = _graphTeardowns.get(config.apiKey);\n if (prevTeardown) {\n try {\n prevTeardown();\n } catch {\n /* teardown must never throw on re-init */\n }\n }\n\n const domScanner = createDOMScanner();\n const resolvedIngestUrl = config.ingestUrl ?? DEFAULT_INGEST_URL;\n const graphClient = createGraphClient({\n syncUrl: resolvedIngestUrl.replace(/\\/events\\/?$/, '/graph/sync'),\n apiKey: config.apiKey,\n projectId: config.apiKey,\n sessionId: readSntUid(config.apiKey),\n });\n\n // Persisted page-node state from a previous page load is restored by the graph\n // client's own constructor (it reads `_snt_graph_nodes` on creation). We no\n // longer re-read the key and call restore() here — that was a redundant second\n // load path that cleared and reloaded identical data.\n\n void domScanner.scan().then((result) => {\n for (const node of result.nodes) {\n graphClient.addPageNode({\n id: node.componentId,\n componentId: node.componentId,\n semanticType: node.semanticType,\n answers: config.captureDomText && node.headingText ? [node.headingText] : [],\n prominenceScore: node.prominenceScore,\n depth: node.depth,\n });\n }\n for (const edge of result.edges) {\n graphClient.addStructuralEdge(edge);\n }\n graphClient.syncOnce();\n });\n\n let syncDebounceTimer: ReturnType<typeof setTimeout> | null = null;\n const debouncedSync = (): void => {\n if (syncDebounceTimer !== null) clearTimeout(syncDebounceTimer);\n syncDebounceTimer = setTimeout(() => {\n syncDebounceTimer = null;\n graphClient.syncOnce();\n }, 500);\n };\n\n domScanner.observe((event) => {\n for (const node of event.nodes) {\n graphClient.addPageNode({\n id: node.componentId,\n componentId: node.componentId,\n semanticType: node.semanticType,\n answers: config.captureDomText && node.headingText ? [node.headingText] : [],\n prominenceScore: node.prominenceScore,\n depth: node.depth,\n });\n }\n for (const edge of event.edges) {\n graphClient.addStructuralEdge(edge);\n }\n debouncedSync();\n });\n\n // Tears down only the graph resources; the caller pairs it with the lean\n // client's own dispose/destroy. Idempotent, and de-registers itself so a\n // later re-init or teardown can't run it twice on already-freed resources.\n const teardownGraph = (): void => {\n if (syncDebounceTimer !== null) {\n clearTimeout(syncDebounceTimer);\n syncDebounceTimer = null;\n }\n domScanner.destroy();\n graphClient.destroy();\n if (_graphTeardowns.get(config.apiKey) === teardownGraph) {\n _graphTeardowns.delete(config.apiKey);\n }\n };\n _graphTeardowns.set(config.apiKey, teardownGraph);\n\n return {\n ...client,\n getGraph: () => graphClient.snapshot(),\n dispose: () => {\n teardownGraph();\n client.dispose();\n },\n destroy: () => {\n teardownGraph();\n client.destroy();\n },\n };\n}\n"],"mappings":"miBA4CA,IAAMA,EAAkB,mBAElBC,GAAgD,CACpD,QAAS,CAAC,WAAY,KAAK,EAC3B,SAAU,CAAC,SAAS,EACpB,IAAK,CAAC,SAAS,EACf,aAAc,CAAC,KAAK,EACpB,IAAK,CAAC,eAAgB,OAAQ,OAAO,EACrC,KAAM,CAAC,KAAK,EACZ,WAAY,CAAC,SAAS,EACtB,MAAO,CAAC,KAAK,CACf,EAEA,SAASC,GAAcC,EAAgC,CAzDvD,IAAAC,EA0DE,OAAOA,EAAAH,GAAoBE,CAAY,IAAhC,KAAAC,EAAqC,CAAC,CAC/C,CAEA,SAASC,GAAeC,EAAaC,EAAgB,CACnD,GAAI,CACF,IAAMC,EAAM,aAAa,QAAQF,CAAG,EACpC,OAAKE,EACE,KAAK,MAAMA,CAAG,EADJD,CAEnB,OAAQE,EAAA,CACN,OAAOF,CACT,CACF,CAEA,SAASG,GAAaJ,EAAaK,EAAsB,CACvD,GAAI,CACF,aAAa,QAAQL,EAAK,KAAK,UAAUK,CAAK,CAAC,CACjD,OAAQF,EAAA,CAER,CACF,CAEA,IAAMG,GAAuB,IAAI,IAAI,CACnC,UAAW,OAAQ,eAAgB,MAAO,WAC1C,MAAO,aAAc,QAAS,aAAc,SAC9C,CAAC,EAED,SAASC,GAAoBC,EAAsB,CACjD,OAAOF,GAAqB,IAAIE,CAAI,EAAIA,EAAO,SACjD,CAMO,SAASC,EAAgBC,EAAsB,CACpD,GAAI,CACF,IAAMC,EAAI,IAAI,IAAID,CAAI,EACtB,MAAO,GAA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bQ,EAAc,EACdpB,EAAO,QAAQ,CACjB,EACA,QAAS,IAAM,CACboB,EAAc,EACdpB,EAAO,QAAQ,CACjB,CACF,EACF","names":["STALE_EDGES_KEY","SEMANTIC_NEIGHBOURS","neighboursFor","semanticType","_a","readStorage","key","fallback","raw","e","writeStorage","value","VALID_SEMANTIC_TYPES","toValidSemanticType","type","sanitizePageUrl","href","u","contentHashOf","componentId","answers","input","h","createGraphClient","config","pageNodes","structuralEdges","nodesKey","storageSuffix","persist","storedNodes","node","edge","_b","nodes","nodesByType","n","list","edges","seen","source","neighbourType","targets","target","componentIds","payload","__spreadProps","__spreadValues","OBSERVE_TAGS","HEADING_SELECTOR","SUBTREE_SELECTOR","MAX_SIBLINGS_PER_GROUP","MAX_STRUCTURAL_EDGES","SSR_SCANNER","normalize","value","min","max","readReactComponentName","element","_a","_b","_c","record","key","fiber","name","e","extractDataAttributes","attrs","attr","SEMANTIC_SET","SEMANTIC_TYPES","inferSemanticType","explicit","role","classifySection","shortHash","input","h","i","domPathSignature","parts","current","parent","index","componentIdFor","declared","depthOf","depth","scanElement","getProminenceScore","_d","heading","locatorFromElement","detectStructuralEdges","elementToId","edges","seen","ROOT","groups","el","_id","ancestor","groupKey","childId","siblings","sibs","capped","j","aId","bId","fwd","rev","collectNodesAndEdges","nodes","node","hasAria","hasSentientId","createDOMScanner","observer","idleCallbackId","contentCallback","knownElementToId","styles","fontSize","zIndex","rect","distanceFromTop","viewportHeight","inverseDistance","score","resolve","run","id","onContentAdded","mutations","added","addedIds","mutation","candidates","scanned","DEFAULT_INGEST_URL","readSntUid","apiKey","_a","read","name","m","e","sessionCookieName","LEGACY_SESSION_COOKIE_NAME","_graphTeardowns","init","config","client","dntBlocked","isDoNotTrackEnabled","gated","keyValid","zeroNetwork","_registerConsentUpgradeInit","c","prevTeardown","domScanner","createDOMScanner","resolvedIngestUrl","graphClient","createGraphClient","result","node","edge","syncDebounceTimer","debouncedSync","event","teardownGraph","__spreadProps","__spreadValues"]}
|
package/dist/index-local.d.cts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
1
|
+
import { d as DecideOutcome } from './index-qAywhZRg.cjs';
|
|
2
|
+
import { a2 as SlotDeclInput } from './session-meta-CY_Luh5i.cjs';
|
|
3
3
|
import '@sentientui/policy';
|
|
4
4
|
|
|
5
5
|
/**
|
package/dist/index-local.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
1
|
+
import { d as DecideOutcome } from './index-C6tOKQ_H.js';
|
|
2
|
+
import { a2 as SlotDeclInput } from './session-meta-CY_Luh5i.js';
|
|
3
3
|
import '@sentientui/policy';
|
|
4
4
|
|
|
5
5
|
/**
|
|
@@ -1,135 +1,6 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { a1 as SlotConfigEntry, a0 as SitePalette, a2 as SlotDeclInput, I as CompoundLocator } from './session-meta-CY_Luh5i.cjs';
|
|
2
2
|
import { SlotResult } from '@sentientui/policy';
|
|
3
3
|
|
|
4
|
-
/**
|
|
5
|
-
* Composition Blocks (spec: 2026-08-20-nocode-composition-variants-design.md §4).
|
|
6
|
-
*
|
|
7
|
-
* A bounded, TYPED component tree — never HTML — that a registry arm may carry
|
|
8
|
-
* (`published_config.arms[].blocks`). The vocabulary is the whitelist: every
|
|
9
|
-
* prop value is an enumerated token, validated server-side before publish
|
|
10
|
-
* (apps/api/src/domain/composition-blocks.ts) and rendered client-side through
|
|
11
|
-
* document.createElement + property assignment only. No innerHTML/outerHTML/
|
|
12
|
-
* insertAdjacentHTML exists anywhere on this path — the security property is
|
|
13
|
-
* preserved by never accepting HTML, not by sanitizing it, which is why there
|
|
14
|
-
* is no sanitizer to keep honest.
|
|
15
|
-
*
|
|
16
|
-
* Token lists live here (not in the API domain like SlotOps' mirrors) because
|
|
17
|
-
* three parties must agree byte-for-byte: the server validator, the snippet
|
|
18
|
-
* renderer, and eventually the React renderer (§11) — a drifted copy would let
|
|
19
|
-
* a published arm fail to render, which the fail-safe turns into an invisibly
|
|
20
|
-
* missing section, not an error.
|
|
21
|
-
*/
|
|
22
|
-
declare const BLOCK_GAPS: readonly ["none", "sm", "md", "lg"];
|
|
23
|
-
declare const BLOCK_ALIGNS: readonly ["start", "center", "end", "stretch"];
|
|
24
|
-
declare const BLOCK_JUSTIFIES: readonly ["start", "center", "end", "between"];
|
|
25
|
-
declare const BLOCK_SIZES: readonly ["sm", "md", "lg"];
|
|
26
|
-
declare const BLOCK_WEIGHTS: readonly ["normal", "medium", "bold"];
|
|
27
|
-
declare const BLOCK_TONES: readonly ["default", "muted", "accent"];
|
|
28
|
-
declare const BLOCK_EMPHASES: readonly ["primary", "secondary", "ghost"];
|
|
29
|
-
declare const BLOCK_TEXT_ALIGNS: readonly ["left", "center", "right"];
|
|
30
|
-
declare const BLOCK_RATIOS: readonly ["auto", "square", "landscape", "wide"];
|
|
31
|
-
declare const BLOCK_FITS: readonly ["cover", "contain"];
|
|
32
|
-
declare const BLOCK_GRID_COLUMNS: readonly [2, 3, 4];
|
|
33
|
-
declare const BLOCK_HEADING_LEVELS: readonly [2, 3, 4];
|
|
34
|
-
type BlockGap = (typeof BLOCK_GAPS)[number];
|
|
35
|
-
type BlockAlign = (typeof BLOCK_ALIGNS)[number];
|
|
36
|
-
type BlockJustify = (typeof BLOCK_JUSTIFIES)[number];
|
|
37
|
-
type BlockSize = (typeof BLOCK_SIZES)[number];
|
|
38
|
-
type BlockWeight = (typeof BLOCK_WEIGHTS)[number];
|
|
39
|
-
type BlockTone = (typeof BLOCK_TONES)[number];
|
|
40
|
-
type BlockEmphasis = (typeof BLOCK_EMPHASES)[number];
|
|
41
|
-
type BlockTextAlign = (typeof BLOCK_TEXT_ALIGNS)[number];
|
|
42
|
-
type BlockRatio = (typeof BLOCK_RATIOS)[number];
|
|
43
|
-
type BlockFit = (typeof BLOCK_FITS)[number];
|
|
44
|
-
/** Flex row/column container. */
|
|
45
|
-
type StackBlock = {
|
|
46
|
-
type: 'stack';
|
|
47
|
-
direction: 'row' | 'column';
|
|
48
|
-
children: BlockNode[];
|
|
49
|
-
gap?: BlockGap;
|
|
50
|
-
align?: BlockAlign;
|
|
51
|
-
justify?: BlockJustify;
|
|
52
|
-
wrap?: boolean;
|
|
53
|
-
};
|
|
54
|
-
/** 2–4 equal-column grid container. */
|
|
55
|
-
type GridBlock = {
|
|
56
|
-
type: 'grid';
|
|
57
|
-
columns: (typeof BLOCK_GRID_COLUMNS)[number];
|
|
58
|
-
children: BlockNode[];
|
|
59
|
-
gap?: BlockGap;
|
|
60
|
-
align?: BlockAlign;
|
|
61
|
-
};
|
|
62
|
-
/** Paragraph / label. */
|
|
63
|
-
type TextBlock = {
|
|
64
|
-
type: 'text';
|
|
65
|
-
value: string;
|
|
66
|
-
size?: BlockSize;
|
|
67
|
-
weight?: BlockWeight;
|
|
68
|
-
tone?: BlockTone;
|
|
69
|
-
align?: BlockTextAlign;
|
|
70
|
-
};
|
|
71
|
-
/** h2–h4 — never h1 (the page owns its h1). */
|
|
72
|
-
type HeadingBlock = {
|
|
73
|
-
type: 'heading';
|
|
74
|
-
value: string;
|
|
75
|
-
level: (typeof BLOCK_HEADING_LEVELS)[number];
|
|
76
|
-
size?: BlockSize;
|
|
77
|
-
align?: BlockTextAlign;
|
|
78
|
-
};
|
|
79
|
-
/** Link styled as a button. `tag` feeds agent legibility (agentDataByVariant). */
|
|
80
|
-
type ButtonBlock = {
|
|
81
|
-
type: 'button';
|
|
82
|
-
label: string;
|
|
83
|
-
href: string;
|
|
84
|
-
emphasis?: BlockEmphasis;
|
|
85
|
-
size?: BlockSize;
|
|
86
|
-
tag?: string;
|
|
87
|
-
};
|
|
88
|
-
/** Inline text link. */
|
|
89
|
-
type LinkBlock = {
|
|
90
|
-
type: 'link';
|
|
91
|
-
label: string;
|
|
92
|
-
href: string;
|
|
93
|
-
tag?: string;
|
|
94
|
-
};
|
|
95
|
-
/** Image. `alt` is required; empty only with an explicit `decorative: true`. */
|
|
96
|
-
type ImageBlock = {
|
|
97
|
-
type: 'image';
|
|
98
|
-
src: string;
|
|
99
|
-
alt: string;
|
|
100
|
-
decorative?: boolean;
|
|
101
|
-
ratio?: BlockRatio;
|
|
102
|
-
fit?: BlockFit;
|
|
103
|
-
};
|
|
104
|
-
/** Eyebrow / pill. */
|
|
105
|
-
type BadgeBlock = {
|
|
106
|
-
type: 'badge';
|
|
107
|
-
value: string;
|
|
108
|
-
tone?: BlockTone;
|
|
109
|
-
};
|
|
110
|
-
/** Vertical rhythm. */
|
|
111
|
-
type SpacerBlock = {
|
|
112
|
-
type: 'spacer';
|
|
113
|
-
size: BlockSize;
|
|
114
|
-
};
|
|
115
|
-
type BlockNode = StackBlock | GridBlock | TextBlock | HeadingBlock | ButtonBlock | LinkBlock | ImageBlock | BadgeBlock | SpacerBlock;
|
|
116
|
-
/** The derived site palette (spec §4 "Colour and type: derived, not chosen").
|
|
117
|
-
* Sampled by the on-site editor from the live page's own buttons — computed
|
|
118
|
-
* styles, so values are plain colors (rgb/hex), never var()/url() — validated
|
|
119
|
-
* server-side, stored per project, and served with the decision so injected
|
|
120
|
-
* blocks render in the merchant's own primary color and corner radius.
|
|
121
|
-
* Absent → the renderer's neutral inherit-first defaults. */
|
|
122
|
-
type SitePalette = {
|
|
123
|
-
primaryBg: string;
|
|
124
|
-
primaryText: string;
|
|
125
|
-
radius: string;
|
|
126
|
-
};
|
|
127
|
-
declare const MAX_BLOCK_NODES = 64;
|
|
128
|
-
declare const MAX_BLOCK_DEPTH = 5;
|
|
129
|
-
declare const MAX_BLOCK_CHILDREN = 12;
|
|
130
|
-
declare const MAX_BLOCK_ARMS = 4;
|
|
131
|
-
declare const MAX_BLOCK_TEXT_LEN = 500;
|
|
132
|
-
|
|
133
4
|
/** Manages anonymous session identity with cookie + localStorage layers. */
|
|
134
5
|
type SessionConfig = {
|
|
135
6
|
cookieName?: string;
|
|
@@ -250,90 +121,6 @@ type GraphClient = {
|
|
|
250
121
|
*/
|
|
251
122
|
declare function sanitizePageUrl(href: string): string;
|
|
252
123
|
|
|
253
|
-
/**
|
|
254
|
-
* Decision snapshot: the SPA / return-visit pre-paint source. Written after
|
|
255
|
-
* every successful decide; read by the inline pre-paint script (before any
|
|
256
|
-
* framework code runs) and by init() to seed slot/persona state.
|
|
257
|
-
*/
|
|
258
|
-
|
|
259
|
-
declare const SNAPSHOT_STORAGE_KEY_PREFIX = "_snt_snap:";
|
|
260
|
-
/** Versioned compound locator: resolve id → dataAttr → selector, then verify
|
|
261
|
-
* against fingerprint. Lets a slot survive DOM/markup drift. */
|
|
262
|
-
type CompoundLocator = {
|
|
263
|
-
v?: number;
|
|
264
|
-
id?: string;
|
|
265
|
-
dataAttr?: {
|
|
266
|
-
name: string;
|
|
267
|
-
value: string;
|
|
268
|
-
};
|
|
269
|
-
selector?: string;
|
|
270
|
-
urlMatch?: string;
|
|
271
|
-
fingerprint?: {
|
|
272
|
-
tag?: string;
|
|
273
|
-
text?: string;
|
|
274
|
-
};
|
|
275
|
-
semanticId?: string;
|
|
276
|
-
};
|
|
277
|
-
/** Bounded, declarative operations a registry arm may apply to its element.
|
|
278
|
-
* The style set is a fixed whitelist (validated server-side); no arbitrary CSS,
|
|
279
|
-
* HTML, or JS ever. `text` is applied via textContent; https-only URLs.
|
|
280
|
-
* moveBefore/moveAfter (exactly one) reposition the element relative to a
|
|
281
|
-
* uniquely-resolving sibling anchor — post-decide only, never pre-paint. */
|
|
282
|
-
type SlotOps = {
|
|
283
|
-
text?: string;
|
|
284
|
-
style?: Record<string, string>;
|
|
285
|
-
hidden?: boolean;
|
|
286
|
-
href?: string;
|
|
287
|
-
imageSrc?: string;
|
|
288
|
-
imageAlt?: string;
|
|
289
|
-
moveBefore?: CompoundLocator;
|
|
290
|
-
moveAfter?: CompoundLocator;
|
|
291
|
-
};
|
|
292
|
-
/** Registry-mode apply info per slot: where to apply and what to set. Stored so
|
|
293
|
-
* a returning visitor's pre-paint can reapply it. `target` is the Phase-2 bare
|
|
294
|
-
* selector; `locator` (Phase 3) is the compound locator, preferred when present. */
|
|
295
|
-
type SlotConfigEntry = {
|
|
296
|
-
kind: 'tokens' | 'arms';
|
|
297
|
-
target?: string;
|
|
298
|
-
locator?: CompoundLocator;
|
|
299
|
-
content?: string;
|
|
300
|
-
ops?: SlotOps;
|
|
301
|
-
/** Composition Blocks per arm — ALL arms, not just the served one, because
|
|
302
|
-
* Option-B rendering pre-paints every arm hidden and reveals the served one
|
|
303
|
-
* (spec §6). Holdout sessions receive the baseline arm's tree only, so the
|
|
304
|
-
* control group's DOM stays meaningful. Absent for non-composition slots. */
|
|
305
|
-
blocks?: Record<string, BlockNode>;
|
|
306
|
-
};
|
|
307
|
-
type DecisionSnapshot = {
|
|
308
|
-
v: 1;
|
|
309
|
-
persona: string;
|
|
310
|
-
band: 'low' | 'medium' | 'high';
|
|
311
|
-
slots: Record<string, SlotResult>;
|
|
312
|
-
layoutOrder: string[] | null;
|
|
313
|
-
savedAt: number;
|
|
314
|
-
slotConfig?: Record<string, SlotConfigEntry>;
|
|
315
|
-
/** Derived site palette for Composition Block rendering — cached so the
|
|
316
|
-
* pre-paint render already looks native (a palette that pops in post-decide
|
|
317
|
-
* would be its own flash). */
|
|
318
|
-
palette?: SitePalette;
|
|
319
|
-
};
|
|
320
|
-
/** Returns null on missing, corrupt, or wrong-version data — never throws. */
|
|
321
|
-
declare function readSnapshot(apiKey: string): DecisionSnapshot | null;
|
|
322
|
-
/** Best-effort persist — storage failures are swallowed. */
|
|
323
|
-
declare function writeSnapshot(apiKey: string, snap: DecisionSnapshot): void;
|
|
324
|
-
/**
|
|
325
|
-
* Inline pre-paint script (Rung 1a): reads the snapshot and sets
|
|
326
|
-
* `data-sentient-persona` / `data-sentient-confidence` on <html> before
|
|
327
|
-
* first paint. Single-writer: it never overwrites attributes already set.
|
|
328
|
-
*
|
|
329
|
-
* Safety properties (pinned by tests):
|
|
330
|
-
* - apiKey goes through JSON.stringify, then '<' is escaped to <, so a
|
|
331
|
-
* hostile key can neither break the JS string nor terminate the <script>.
|
|
332
|
-
* - Built by string concatenation and contains no backticks, so the output
|
|
333
|
-
* survives being embedded in template-literal-based renderers.
|
|
334
|
-
*/
|
|
335
|
-
declare function renderPrePaintScript(apiKey: string): string;
|
|
336
|
-
|
|
337
124
|
declare const PROD_KEYLESS_ERROR = "[sentient] No API key configured \u2014 nothing is being learned. Set NEXT_PUBLIC_SENTIENT_API_KEY or pass localMode: true for local development.";
|
|
338
125
|
declare const LOCAL_MODE_BANNER = "[sentient] Local mode \u2014 decisions are simulated on-device and nothing is sent over the network. Add an API key to learn from real traffic.";
|
|
339
126
|
|
|
@@ -445,6 +232,13 @@ type SentientConfig = {
|
|
|
445
232
|
* server-rendered markup on first paint.
|
|
446
233
|
*/
|
|
447
234
|
initialSlots?: Record<string, SlotResult>;
|
|
235
|
+
/**
|
|
236
|
+
* Registry slot config decided outside the browser (SSR). Seeds
|
|
237
|
+
* `getSlotConfig()` so server-rendered block/content arms survive hydration.
|
|
238
|
+
*/
|
|
239
|
+
initialSlotConfig?: Record<string, SlotConfigEntry>;
|
|
240
|
+
/** Site palette decided outside the browser (SSR). Seeds `getSitePalette()`. */
|
|
241
|
+
initialPalette?: SitePalette;
|
|
448
242
|
/**
|
|
449
243
|
* Persona decided during SSR. Takes priority over the html-attribute
|
|
450
244
|
* adoption and the local snapshot.
|
|
@@ -529,6 +323,14 @@ type DecideInput = {
|
|
|
529
323
|
* entirely on older deployments. Omit if the caller has no version to report.
|
|
530
324
|
*/
|
|
531
325
|
v?: string;
|
|
326
|
+
/**
|
|
327
|
+
* Snippet only: which inline pre-paint contract the install carries
|
|
328
|
+
* (`window.__sntPP.v`), or 0 for the two-tag install with no inline script.
|
|
329
|
+
* Sent as `pp` alongside `v`; the server persists it for the dashboard's
|
|
330
|
+
* install-health nudge and no serving behaviour depends on it. Additive —
|
|
331
|
+
* older deployments ignore it entirely.
|
|
332
|
+
*/
|
|
333
|
+
pp?: number;
|
|
532
334
|
};
|
|
533
335
|
type WeightEntry = {
|
|
534
336
|
variantId: string;
|
|
@@ -588,6 +390,19 @@ type SentientClient = {
|
|
|
588
390
|
decide(input: DecideInput): Promise<DecideOutcome | null>;
|
|
589
391
|
/** Slot result served this session (decide result, SSR seed, snapshot, or failure baseline). Null when unknown. */
|
|
590
392
|
getSlotResult(slotId: string): SlotResult | null;
|
|
393
|
+
/** Registry slot config served this session (content/ops/blocks for the slot).
|
|
394
|
+
* Null until a registry-mode decide, SSR seed, or snapshot provides it. */
|
|
395
|
+
getSlotConfig(slotId: string): SlotConfigEntry | null;
|
|
396
|
+
/** Report mounted AdaptiveSlot ids the server has no config for, so they
|
|
397
|
+
* auto-register as draft slots. Fire-and-forget, batched, deduped per
|
|
398
|
+
* client — never blocks rendering and never throws. `baselineTexts` maps a
|
|
399
|
+
* slot id to its rendered baseline text (what the region says today), so
|
|
400
|
+
* generation can ground its versions in what they replace — sent only on
|
|
401
|
+
* the first report of an id, capped, and the server keeps it only at
|
|
402
|
+
* first registration. */
|
|
403
|
+
reportSlots(slotIds: string[], baselineTexts?: Record<string, string>): void;
|
|
404
|
+
/** Site palette served with registry block decisions. Null when absent. */
|
|
405
|
+
getSitePalette(): SitePalette | null;
|
|
591
406
|
/** Current persona estimate. Band is always `confidenceBand(confidence)`. Null when nothing is known yet. */
|
|
592
407
|
getPersona(): {
|
|
593
408
|
persona: string;
|
|
@@ -635,4 +450,4 @@ declare function grantConsent(apiKey?: string): void;
|
|
|
635
450
|
*/
|
|
636
451
|
declare function init(config: SentientConfig): SentientClient;
|
|
637
452
|
|
|
638
|
-
export { type
|
|
453
|
+
export { type AssignResult as A, type ComponentGoalOptions as C, type DecideInput as D, type EventQueue as E, type GoalDefinition as G, LEGACY_SESSION_COOKIE_NAME as L, type MicroSignalEmitter as M, PROD_KEYLESS_ERROR as P, type QueueConfig as Q, type SectionMapEntry as S, type WeightEntry as W, _registerConsentUpgradeInit as _, type Assignment as a, type AssignmentCache as b, type ComponentWeightEntry as c, type DecideOutcome as d, type EventType as e, type GoalOptions as f, type GraphClient as g, type GraphConfig as h, type GraphSnapshot as i, LOCAL_MODE_BANNER as j, type MicroSignalType as k, type PageNode as l, type SentientClient as m, type SentientConfig as n, type SentientEvent as o, type SessionConfig as p, type SessionManager as q, attachMicroSignalDetectors as r, grantConsent as s, init as t, isDoNotTrackEnabled as u, sanitizePageUrl as v, sessionCookieName as w };
|