@sentientui/core 0.41.1 → 0.42.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.
Files changed (54) hide show
  1. package/README.md +31 -2
  2. package/dist/chunk-BGZLWZUG.mjs +2 -0
  3. package/dist/chunk-BGZLWZUG.mjs.map +1 -0
  4. package/dist/chunk-JNQY3XNF.mjs +2 -0
  5. package/dist/chunk-JNQY3XNF.mjs.map +1 -0
  6. package/dist/chunk-LCYGZNFI.mjs +2 -0
  7. package/dist/chunk-LCYGZNFI.mjs.map +1 -0
  8. package/dist/chunk-QPJ6TL6L.mjs +2 -0
  9. package/dist/chunk-QPJ6TL6L.mjs.map +1 -0
  10. package/dist/chunk-WUFFNQHQ.mjs +2 -0
  11. package/dist/{chunk-J5EL7HKC.mjs.map → chunk-WUFFNQHQ.mjs.map} +1 -1
  12. package/dist/{index-DlJDNOWu.d.cts → index-Bz4QCRmF.d.cts} +26 -5
  13. package/dist/{index-C--aVpoo.d.ts → index-C36TXfry.d.ts} +26 -5
  14. package/dist/index-consent.js +1 -1
  15. package/dist/index-consent.js.map +1 -1
  16. package/dist/index-consent.mjs +1 -1
  17. package/dist/index-consent.mjs.map +1 -1
  18. package/dist/index-engagement.js +1 -1
  19. package/dist/index-engagement.js.map +1 -1
  20. package/dist/index-engagement.mjs +1 -1
  21. package/dist/index-engagement.mjs.map +1 -1
  22. package/dist/index-graph.d.cts +2 -2
  23. package/dist/index-graph.d.ts +2 -2
  24. package/dist/index-graph.js +1 -1
  25. package/dist/index-graph.js.map +1 -1
  26. package/dist/index-graph.mjs +1 -1
  27. package/dist/index-graph.mjs.map +1 -1
  28. package/dist/index-internal-traffic.d.cts +37 -0
  29. package/dist/index-internal-traffic.d.ts +37 -0
  30. package/dist/index-internal-traffic.js +2 -0
  31. package/dist/index-internal-traffic.js.map +1 -0
  32. package/dist/index-internal-traffic.mjs +2 -0
  33. package/dist/index-internal-traffic.mjs.map +1 -0
  34. package/dist/index-local.d.cts +1 -1
  35. package/dist/index-local.d.ts +1 -1
  36. package/dist/index-region.mjs +1 -1
  37. package/dist/index-server.d.cts +25 -1
  38. package/dist/index-server.d.ts +25 -1
  39. package/dist/index-server.js +1 -1
  40. package/dist/index-server.js.map +1 -1
  41. package/dist/index-server.mjs +1 -1
  42. package/dist/index-server.mjs.map +1 -1
  43. package/dist/index.d.cts +1 -1
  44. package/dist/index.d.ts +1 -1
  45. package/dist/index.js +1 -1
  46. package/dist/index.js.map +1 -1
  47. package/dist/index.mjs +1 -1
  48. package/llms.txt +2 -1
  49. package/package.json +7 -2
  50. package/dist/chunk-FPOHOWJP.mjs +0 -2
  51. package/dist/chunk-FPOHOWJP.mjs.map +0 -1
  52. package/dist/chunk-J5EL7HKC.mjs +0 -2
  53. package/dist/chunk-KXA3X6T3.mjs +0 -2
  54. package/dist/chunk-KXA3X6T3.mjs.map +0 -1
@@ -1,2 +1,2 @@
1
- import{a as v}from"./chunk-WKXD7KI3.mjs";import{a as _,g as O}from"./chunk-Z6ILOYBD.mjs";import{A as ze,B as He,C as Ve,D as Ye,E as We,F as Je,G as Xe,H as Qe,I as Ze,J as et,K as tt,O as se,P as M,Q as P,R as ae,T as D,d as ne,e as oe,f as re,m as Oe,n as Me,o as Pe,p as De,q as Ge,r as ke,s as $e,t as Le,u as je,v as Ue,w as Ke,x as Fe,y as Be,z as qe}from"./chunk-KXA3X6T3.mjs";import{a as B,b as q,c as z,d as H}from"./chunk-FPOHOWJP.mjs";import"./chunk-EVF5PQ4U.mjs";import{i as V,j as Y,k as W,n as J,o as X,q as Q,r as Z,s as ee,t as te}from"./chunk-3HMJERH4.mjs";import{a as R,b as w,c as A}from"./chunk-J5EL7HKC.mjs";import{a as I,b}from"./chunk-TMCGHANO.mjs";var G="_snt_graph_edges",ie={pricing:["features","faq"],features:["pricing"],faq:["pricing"],social_proof:["cta"],cta:["social_proof","hero","trust"],hero:["cta"],comparison:["pricing"],trust:["cta"]};function ce(e){var t;return(t=ie[e])!=null?t:[]}function de(e,t){try{let n=localStorage.getItem(e);return n?JSON.parse(n):t}catch(n){return t}}function pe(e,t){try{localStorage.setItem(e,JSON.stringify(t))}catch(n){}}var ue=new Set(["pricing","hero","social_proof","cta","features","faq","comparison","trust","navigation","generic"]);function le(e){return ue.has(e)?e:"generic"}function k(e){try{let t=new URL(e);return`${t.origin}${t.pathname}`}catch(t){return"/"}}function me(e,t,n){let a=`${e}:${t}:${n.join(",")}`,s=5381;for(let o=0;o<a.length;o++)s=(s<<5)+s+a.charCodeAt(o)&4294967295;return(s>>>0).toString(16).padStart(8,"0")}function $(e){let t=new Map,n=new Map,a=`_snt_graph_nodes${R(e==null?void 0:e.apiKey)}`,s=()=>{typeof window!="undefined"&&pe(a,[...t.values()])};if(typeof window!="undefined"){let o=de(a,[]);for(let i of o)t.set(i.componentId,i);try{localStorage.removeItem(G)}catch(i){}}return{addPageNode(o){t.set(o.componentId,o),s()},addStructuralEdge(o){let i=`${o.fromComponentId}->${o.toComponentId}`;n.set(i,o)},syncOnce(){var i,c;if(!(e!=null&&e.syncUrl)||typeof window=="undefined")return;let o=[...t.values()];if(o.length!==0)try{let l=new Map;for(let r of o){let d=(i=l.get(r.semanticType))!=null?i:[];d.push(r),l.set(r.semanticType,d)}let u=[],m=new Set;for(let r of o)for(let d of ce(r.semanticType)){let p=(c=l.get(d))!=null?c:[];for(let S of p){if(S.componentId===r.componentId)continue;let f=`semantic:${r.componentId}->${S.componentId}`;m.has(f)||(m.add(f),u.push({fromComponentId:r.componentId,toComponentId:S.componentId,type:"semantic",weight:.4,confidence:.9}))}}let g=new Set(o.map(r=>r.componentId));for(let r of n.values()){if(!g.has(r.fromComponentId)||!g.has(r.toComponentId))continue;let d=`structural:${r.fromComponentId}->${r.toComponentId}`;m.has(d)||(m.add(d),u.push({fromComponentId:r.fromComponentId,toComponentId:r.toComponentId,type:"structural",weight:r.weight,confidence:1}))}let h=b(I(I({pageUrl:k(window.location.href)},e.sessionId?{sessionId:e.sessionId}:{}),e.projectId?{projectId:e.projectId}:{}),{nodes:o.map(r=>{let d=le(r.semanticType);return{componentId:r.componentId,semanticType:d,answers:r.answers,contentHash:me(r.componentId,d,r.answers),prominenceScore:r.prominenceScore,depthInPage:r.depth}}),edges:u});fetch(e.syncUrl,{method:"POST",keepalive:!0,headers:I({"Content-Type":"application/json"},e.apiKey?{Authorization:`Bearer ${e.apiKey}`}:{}),body:JSON.stringify(h)}).catch(()=>{})}catch(l){}},snapshot(){return{pageNodes:[...t.values()],capturedAt:Date.now()}},destroy(){if(typeof window!="undefined")try{localStorage.removeItem(a),localStorage.removeItem(G)}catch(o){}}}}var fe=new Set(["SECTION","ARTICLE","MAIN","DIV","ASIDE"]),ge=200,he="h1, h2, h3",Se="[data-sentient-id], section[aria-label], article[aria-label], main[aria-label], aside[aria-label]",L=30,ye=1500,Ee={scan:async()=>({nodes:[],edges:[],scannedAt:0}),observe:()=>{},getProminenceScore:()=>0,destroy:()=>{}};function j(e,t,n){return n<=t?0:Math.max(0,Math.min(1,(e-t)/(n-t)))}function Ie(e){var t,n,a;try{let s=e;for(let o of Object.keys(s)){if(!o.startsWith("__reactFiber")&&!o.startsWith("__reactInternalInstance"))continue;let i=s[o],c=(a=(t=i==null?void 0:i.type)==null?void 0:t.displayName)!=null?a:(n=i==null?void 0:i.type)==null?void 0:n.name;if(c&&c.length>1)return c}}catch(s){}}function Ce(e){let t={};for(let n of Array.from(e.attributes))n.name.startsWith("data-")&&(t[n.name]=n.value);return t}var x=new Set(_);function be(e,t){let n=e.getAttribute("data-sentient-id"),a=n?t==null?void 0:t[n]:void 0;if(a&&x.has(a))return a;let s=e.getAttribute("data-sentient-type");if(s&&x.has(s))return s;let o=e.getAttribute("role");return o&&x.has(o)?o:O(e)}function Te(e){let t=5381;for(let n=0;n<e.length;n++)t=(t<<5)+t+e.charCodeAt(n)&4294967295;return(t>>>0).toString(16).padStart(8,"0")}function we(e){let t=[],n=e;for(;n;){let a=n.parentElement;if(!a){t.push(n.tagName.toLowerCase());break}let s=Array.prototype.indexOf.call(a.children,n);t.push(`${n.tagName.toLowerCase()}[${s}]`),n=a}return t.reverse().join("/")}function Ae(e){var n;let t=(n=e.getAttribute("data-sentient-id"))!=null?n:e.getAttribute("id");return t||`${e.tagName.toLowerCase()}-${Te(we(e))}`}function ve(e){let t=0,n=e.parentElement;for(;n;)t++,n=n.parentElement;return t}function N(e,t,n){var s,o,i,c;let a=e.querySelector(he);return{componentId:Ae(e),semanticType:be(e,n),ariaLabel:(s=e.getAttribute("aria-label"))!=null?s:void 0,headingText:(i=(o=a==null?void 0:a.textContent)==null?void 0:o.trim())!=null?i:void 0,isAboveFold:e.getBoundingClientRect().top<window.innerHeight,prominenceScore:t(e),depth:ve(e),reactComponentName:Ie(e),dataAttributes:Ce(e),locator:(c=v(e,e.ownerDocument))!=null?c:void 0}}function U(e){var o;let t=[],n=new Set,a="__root__",s=new Map;for(let[i,c]of e){let l=i.parentElement,u=a;for(;l;){if(e.has(l)){u=e.get(l);let g=e.get(i),h=`${u}->${g}`;!n.has(h)&&u!==g&&(n.add(h),t.push({fromComponentId:u,toComponentId:g,weight:.6}));break}l=l.parentElement}let m=(o=s.get(u))!=null?o:[];m.push(i),s.set(u,m)}for(let i of s.values()){if(i.length<2)continue;let c=i.length>L?i.slice(0,L):i;for(let l=0;l<c.length;l++)for(let u=l+1;u<c.length;u++){if(t.length>=ye)return t;let m=e.get(c[l]),g=e.get(c[u]);if(m===g)continue;let h=`${m}->${g}::sib`,r=`${g}->${m}::sib`;n.has(h)||(n.add(h),t.push({fromComponentId:m,toComponentId:g,weight:.3})),n.has(r)||(n.add(r),t.push({fromComponentId:g,toComponentId:m,weight:.3}))}}return t}function xe(e,t){let n=[],a=new Set,s=new Map;return document.querySelectorAll("[data-sentient-id]").forEach(c=>{if(c instanceof Element&&!a.has(c)){a.add(c);let l=N(c,e,t);n.push(l),s.set(c,l.componentId)}}),document.querySelectorAll("section, article, main, aside").forEach(c=>{if(!(c instanceof Element)||a.has(c))return;let l=c.hasAttribute("aria-label"),u=c.hasAttribute("data-sentient-id");if(!l&&!u)return;a.add(c);let m=N(c,e,t);n.push(m),s.set(c,m.componentId)}),{nodes:n,edges:U(s),elementToId:s}}function K(e={}){let{sectionTypes:t}=e;if(typeof window=="undefined")return Ee;let n=null,a=0,s=null,o=new Map,i=r=>{try{let d=window.getComputedStyle(r),p=parseFloat(d.fontSize)||12,S=parseFloat(d.zIndex)||0,f=r.getBoundingClientRect(),E=Math.max(f.top,0),y=window.innerHeight||1,C=1/(E/y+1),F=j(p,12,48)*.4+C*.4+j(S,0,100)*.2;return Math.max(0,Math.min(1,F))}catch(d){return .5}},c=()=>new Promise(r=>{let d=()=>{let{nodes:p,edges:S,elementToId:f}=xe(i,t);o.clear();for(let[E,y]of f)o.set(E,y);r({nodes:p,edges:S,scannedAt:Date.now()})};try{typeof requestIdleCallback=="function"?a=requestIdleCallback(d,{timeout:100}):d()}catch(p){d()}}),l=new Set,u=null,m=()=>{u=null;let r=[...l];l.clear();let d=[],p=new Set;for(let f of r){if(!f.isConnected)continue;let E=[];fe.has(f.tagName)&&(f.hasAttribute("data-sentient-id")||f.hasAttribute("aria-label"))&&E.push(f);try{f.querySelectorAll(Se).forEach(y=>E.push(y))}catch(y){}for(let y of E){if(o.has(y))continue;let C=N(y,i,t);d.push(C),p.add(C.componentId),o.set(y,C.componentId)}}if(d.length===0||!s)return;for(let f of[...o.keys()])f.isConnected||o.delete(f);let S=U(o).filter(f=>p.has(f.fromComponentId)||p.has(f.toComponentId));s({nodes:d,edges:S,addedAt:Date.now()})};return{scan:c,observe:r=>{s=r;try{n=new MutationObserver(d=>{for(let p of d)p.type==="childList"&&p.addedNodes.forEach(S=>{S instanceof Element&&l.add(S)});l.size>0&&u===null&&(u=setTimeout(m,ge))}),n.observe(document.body,{childList:!0,subtree:!0})}catch(d){}},getProminenceScore:i,destroy:()=>{if(n&&(n.disconnect(),n=null),u!==null&&clearTimeout(u),u=null,l.clear(),a&&typeof cancelIdleCallback=="function")try{cancelIdleCallback(a)}catch(r){}a=0,s=null,o.clear()}}}var Ne="https://api.sentient-ui.com/v1/events";function Re(e){var n;let t=a=>{try{let s=document.cookie.match(new RegExp(`(?:^|; )${a}=([^;]*)`));return s?decodeURIComponent(s[1]):void 0}catch(s){return}};return(n=e?t(A(e)):void 0)!=null?n:t(w)}var T=new Map;function _e(e){var r;let t=D(e),n=e.respectDoNotTrack!==!1&&P(),a=e.consent===!1||n,s=typeof e.apiKey=="string"&&e.apiKey.startsWith("pk_"),o=e.localMode===!0||!s;if(!e.graph||o||typeof window=="undefined")return t;if(a)return n||M(e.apiKey,d=>_e(d)),t;let i=T.get(e.apiKey);if(i)try{i()}catch(d){}let c=K({sectionTypes:e.sectionTypes}),l=(r=e.ingestUrl)!=null?r:Ne,u=$({syncUrl:l.replace(/\/events\/?$/,"/graph/sync"),apiKey:e.apiKey,projectId:e.apiKey,sessionId:Re(e.apiKey)});c.scan().then(d=>{for(let p of d.nodes)u.addPageNode({id:p.componentId,componentId:p.componentId,semanticType:p.semanticType,answers:e.captureDomText&&p.headingText?[p.headingText]:[],prominenceScore:p.prominenceScore,depth:p.depth});for(let p of d.edges)u.addStructuralEdge(p);u.syncOnce()});let m=null,g=()=>{m!==null&&clearTimeout(m),m=setTimeout(()=>{m=null,u.syncOnce()},500)};c.observe(d=>{for(let p of d.nodes)u.addPageNode({id:p.componentId,componentId:p.componentId,semanticType:p.semanticType,answers:e.captureDomText&&p.headingText?[p.headingText]:[],prominenceScore:p.prominenceScore,depth:p.depth});for(let p of d.edges)u.addStructuralEdge(p);g()});let h=()=>{m!==null&&(clearTimeout(m),m=null),c.destroy(),u.destroy(),T.get(e.apiKey)===h&&T.delete(e.apiKey)};return T.set(e.apiKey,h),b(I({},t),{getGraph:()=>u.snapshot(),dispose:()=>{h(),t.dispose()},destroy:()=>{h(),t.destroy()}})}export{Me as BLOCK_ALIGNS,$e as BLOCK_EMPHASES,Ue as BLOCK_FITS,Oe as BLOCK_GAPS,Ke as BLOCK_GRID_COLUMNS,Fe as BLOCK_HEADING_LEVELS,Pe as BLOCK_JUSTIFIES,ze as BLOCK_MAX_WIDTHS,qe as BLOCK_PADS,je as BLOCK_RATIOS,De as BLOCK_SIZES,Be as BLOCK_SURFACES,Le as BLOCK_TEXT_ALIGNS,ke as BLOCK_TONES,Ge as BLOCK_WEIGHTS,He as FORM_FIELD_KINDS,Ve as FORM_INPUT_TYPES,w as LEGACY_SESSION_COOKIE_NAME,Ze as MAX_BLOCK_ARMS,Qe as MAX_BLOCK_CHILDREN,Xe as MAX_BLOCK_DEPTH,Je as MAX_BLOCK_NODES,et as MAX_BLOCK_TEXT_LEN,Ye as MAX_FORM_FIELDS,We as MAX_FORM_SELECT_OPTIONS,B as SNAPSHOT_STORAGE_KEY_PREFIX,ne as STAGE_ATTRIBUTE,te as armOfResult,se as attachMicroSignalDetectors,Z as baselineResultFor,ee as baselineSlots,tt as containsFormBlock,X as deriveSessionSegment,V as detectDeviceClass,J as detectTimeOfDay,Y as detectTrafficSource,oe as exposedStage,ae as grantConsent,_e as init,P as isDoNotTrackEnabled,v as locatorFromElement,q as readSnapshot,W as referrerDomainFromReferer,H as renderPrePaintScript,k as sanitizePageUrl,A as sessionCookieName,re as setStageAttribute,Q as toWireSlot,z as writeSnapshot};
1
+ import{a as v}from"./chunk-WKXD7KI3.mjs";import{a as _,g as O}from"./chunk-Z6ILOYBD.mjs";import{A as ze,B as He,C as Ve,D as Ye,E as We,F as Je,G as Xe,H as Qe,I as Ze,J as et,K as tt,O as se,P as M,Q as P,R as ae,T as D,d as ne,e as oe,f as re,m as Oe,n as Me,o as Pe,p as De,q as Ge,r as ke,s as $e,t as Le,u as je,v as Ue,w as Ke,x as Fe,y as Be,z as qe}from"./chunk-QPJ6TL6L.mjs";import{a as B,b as q,c as z,d as H}from"./chunk-JNQY3XNF.mjs";import"./chunk-LCYGZNFI.mjs";import"./chunk-BGZLWZUG.mjs";import"./chunk-EVF5PQ4U.mjs";import{i as V,j as Y,k as W,n as J,o as X,q as Q,r as Z,s as ee,t as te}from"./chunk-3HMJERH4.mjs";import{a as R,b as w,c as A}from"./chunk-WUFFNQHQ.mjs";import{a as I,b}from"./chunk-TMCGHANO.mjs";var G="_snt_graph_edges",ie={pricing:["features","faq"],features:["pricing"],faq:["pricing"],social_proof:["cta"],cta:["social_proof","hero","trust"],hero:["cta"],comparison:["pricing"],trust:["cta"]};function ce(e){var t;return(t=ie[e])!=null?t:[]}function de(e,t){try{let n=localStorage.getItem(e);return n?JSON.parse(n):t}catch(n){return t}}function pe(e,t){try{localStorage.setItem(e,JSON.stringify(t))}catch(n){}}var ue=new Set(["pricing","hero","social_proof","cta","features","faq","comparison","trust","navigation","generic"]);function le(e){return ue.has(e)?e:"generic"}function k(e){try{let t=new URL(e);return`${t.origin}${t.pathname}`}catch(t){return"/"}}function me(e,t,n){let a=`${e}:${t}:${n.join(",")}`,s=5381;for(let o=0;o<a.length;o++)s=(s<<5)+s+a.charCodeAt(o)&4294967295;return(s>>>0).toString(16).padStart(8,"0")}function $(e){let t=new Map,n=new Map,a=`_snt_graph_nodes${R(e==null?void 0:e.apiKey)}`,s=()=>{typeof window!="undefined"&&pe(a,[...t.values()])};if(typeof window!="undefined"){let o=de(a,[]);for(let i of o)t.set(i.componentId,i);try{localStorage.removeItem(G)}catch(i){}}return{addPageNode(o){t.set(o.componentId,o),s()},addStructuralEdge(o){let i=`${o.fromComponentId}->${o.toComponentId}`;n.set(i,o)},syncOnce(){var i,c;if(!(e!=null&&e.syncUrl)||typeof window=="undefined")return;let o=[...t.values()];if(o.length!==0)try{let l=new Map;for(let r of o){let d=(i=l.get(r.semanticType))!=null?i:[];d.push(r),l.set(r.semanticType,d)}let u=[],m=new Set;for(let r of o)for(let d of ce(r.semanticType)){let p=(c=l.get(d))!=null?c:[];for(let S of p){if(S.componentId===r.componentId)continue;let f=`semantic:${r.componentId}->${S.componentId}`;m.has(f)||(m.add(f),u.push({fromComponentId:r.componentId,toComponentId:S.componentId,type:"semantic",weight:.4,confidence:.9}))}}let g=new Set(o.map(r=>r.componentId));for(let r of n.values()){if(!g.has(r.fromComponentId)||!g.has(r.toComponentId))continue;let d=`structural:${r.fromComponentId}->${r.toComponentId}`;m.has(d)||(m.add(d),u.push({fromComponentId:r.fromComponentId,toComponentId:r.toComponentId,type:"structural",weight:r.weight,confidence:1}))}let h=b(I(I({pageUrl:k(window.location.href)},e.sessionId?{sessionId:e.sessionId}:{}),e.projectId?{projectId:e.projectId}:{}),{nodes:o.map(r=>{let d=le(r.semanticType);return{componentId:r.componentId,semanticType:d,answers:r.answers,contentHash:me(r.componentId,d,r.answers),prominenceScore:r.prominenceScore,depthInPage:r.depth}}),edges:u});fetch(e.syncUrl,{method:"POST",keepalive:!0,headers:I({"Content-Type":"application/json"},e.apiKey?{Authorization:`Bearer ${e.apiKey}`}:{}),body:JSON.stringify(h)}).catch(()=>{})}catch(l){}},snapshot(){return{pageNodes:[...t.values()],capturedAt:Date.now()}},destroy(){if(typeof window!="undefined")try{localStorage.removeItem(a),localStorage.removeItem(G)}catch(o){}}}}var fe=new Set(["SECTION","ARTICLE","MAIN","DIV","ASIDE"]),ge=200,he="h1, h2, h3",Se="[data-sentient-id], section[aria-label], article[aria-label], main[aria-label], aside[aria-label]",L=30,ye=1500,Ee={scan:async()=>({nodes:[],edges:[],scannedAt:0}),observe:()=>{},getProminenceScore:()=>0,destroy:()=>{}};function j(e,t,n){return n<=t?0:Math.max(0,Math.min(1,(e-t)/(n-t)))}function Ie(e){var t,n,a;try{let s=e;for(let o of Object.keys(s)){if(!o.startsWith("__reactFiber")&&!o.startsWith("__reactInternalInstance"))continue;let i=s[o],c=(a=(t=i==null?void 0:i.type)==null?void 0:t.displayName)!=null?a:(n=i==null?void 0:i.type)==null?void 0:n.name;if(c&&c.length>1)return c}}catch(s){}}function Ce(e){let t={};for(let n of Array.from(e.attributes))n.name.startsWith("data-")&&(t[n.name]=n.value);return t}var x=new Set(_);function be(e,t){let n=e.getAttribute("data-sentient-id"),a=n?t==null?void 0:t[n]:void 0;if(a&&x.has(a))return a;let s=e.getAttribute("data-sentient-type");if(s&&x.has(s))return s;let o=e.getAttribute("role");return o&&x.has(o)?o:O(e)}function Te(e){let t=5381;for(let n=0;n<e.length;n++)t=(t<<5)+t+e.charCodeAt(n)&4294967295;return(t>>>0).toString(16).padStart(8,"0")}function we(e){let t=[],n=e;for(;n;){let a=n.parentElement;if(!a){t.push(n.tagName.toLowerCase());break}let s=Array.prototype.indexOf.call(a.children,n);t.push(`${n.tagName.toLowerCase()}[${s}]`),n=a}return t.reverse().join("/")}function Ae(e){var n;let t=(n=e.getAttribute("data-sentient-id"))!=null?n:e.getAttribute("id");return t||`${e.tagName.toLowerCase()}-${Te(we(e))}`}function ve(e){let t=0,n=e.parentElement;for(;n;)t++,n=n.parentElement;return t}function N(e,t,n){var s,o,i,c;let a=e.querySelector(he);return{componentId:Ae(e),semanticType:be(e,n),ariaLabel:(s=e.getAttribute("aria-label"))!=null?s:void 0,headingText:(i=(o=a==null?void 0:a.textContent)==null?void 0:o.trim())!=null?i:void 0,isAboveFold:e.getBoundingClientRect().top<window.innerHeight,prominenceScore:t(e),depth:ve(e),reactComponentName:Ie(e),dataAttributes:Ce(e),locator:(c=v(e,e.ownerDocument))!=null?c:void 0}}function U(e){var o;let t=[],n=new Set,a="__root__",s=new Map;for(let[i,c]of e){let l=i.parentElement,u=a;for(;l;){if(e.has(l)){u=e.get(l);let g=e.get(i),h=`${u}->${g}`;!n.has(h)&&u!==g&&(n.add(h),t.push({fromComponentId:u,toComponentId:g,weight:.6}));break}l=l.parentElement}let m=(o=s.get(u))!=null?o:[];m.push(i),s.set(u,m)}for(let i of s.values()){if(i.length<2)continue;let c=i.length>L?i.slice(0,L):i;for(let l=0;l<c.length;l++)for(let u=l+1;u<c.length;u++){if(t.length>=ye)return t;let m=e.get(c[l]),g=e.get(c[u]);if(m===g)continue;let h=`${m}->${g}::sib`,r=`${g}->${m}::sib`;n.has(h)||(n.add(h),t.push({fromComponentId:m,toComponentId:g,weight:.3})),n.has(r)||(n.add(r),t.push({fromComponentId:g,toComponentId:m,weight:.3}))}}return t}function xe(e,t){let n=[],a=new Set,s=new Map;return document.querySelectorAll("[data-sentient-id]").forEach(c=>{if(c instanceof Element&&!a.has(c)){a.add(c);let l=N(c,e,t);n.push(l),s.set(c,l.componentId)}}),document.querySelectorAll("section, article, main, aside").forEach(c=>{if(!(c instanceof Element)||a.has(c))return;let l=c.hasAttribute("aria-label"),u=c.hasAttribute("data-sentient-id");if(!l&&!u)return;a.add(c);let m=N(c,e,t);n.push(m),s.set(c,m.componentId)}),{nodes:n,edges:U(s),elementToId:s}}function K(e={}){let{sectionTypes:t}=e;if(typeof window=="undefined")return Ee;let n=null,a=0,s=null,o=new Map,i=r=>{try{let d=window.getComputedStyle(r),p=parseFloat(d.fontSize)||12,S=parseFloat(d.zIndex)||0,f=r.getBoundingClientRect(),E=Math.max(f.top,0),y=window.innerHeight||1,C=1/(E/y+1),F=j(p,12,48)*.4+C*.4+j(S,0,100)*.2;return Math.max(0,Math.min(1,F))}catch(d){return .5}},c=()=>new Promise(r=>{let d=()=>{let{nodes:p,edges:S,elementToId:f}=xe(i,t);o.clear();for(let[E,y]of f)o.set(E,y);r({nodes:p,edges:S,scannedAt:Date.now()})};try{typeof requestIdleCallback=="function"?a=requestIdleCallback(d,{timeout:100}):d()}catch(p){d()}}),l=new Set,u=null,m=()=>{u=null;let r=[...l];l.clear();let d=[],p=new Set;for(let f of r){if(!f.isConnected)continue;let E=[];fe.has(f.tagName)&&(f.hasAttribute("data-sentient-id")||f.hasAttribute("aria-label"))&&E.push(f);try{f.querySelectorAll(Se).forEach(y=>E.push(y))}catch(y){}for(let y of E){if(o.has(y))continue;let C=N(y,i,t);d.push(C),p.add(C.componentId),o.set(y,C.componentId)}}if(d.length===0||!s)return;for(let f of[...o.keys()])f.isConnected||o.delete(f);let S=U(o).filter(f=>p.has(f.fromComponentId)||p.has(f.toComponentId));s({nodes:d,edges:S,addedAt:Date.now()})};return{scan:c,observe:r=>{s=r;try{n=new MutationObserver(d=>{for(let p of d)p.type==="childList"&&p.addedNodes.forEach(S=>{S instanceof Element&&l.add(S)});l.size>0&&u===null&&(u=setTimeout(m,ge))}),n.observe(document.body,{childList:!0,subtree:!0})}catch(d){}},getProminenceScore:i,destroy:()=>{if(n&&(n.disconnect(),n=null),u!==null&&clearTimeout(u),u=null,l.clear(),a&&typeof cancelIdleCallback=="function")try{cancelIdleCallback(a)}catch(r){}a=0,s=null,o.clear()}}}var Ne="https://api.sentient-ui.com/v1/events";function Re(e){var n;let t=a=>{try{let s=document.cookie.match(new RegExp(`(?:^|; )${a}=([^;]*)`));return s?decodeURIComponent(s[1]):void 0}catch(s){return}};return(n=e?t(A(e)):void 0)!=null?n:t(w)}var T=new Map;function _e(e){var r;let t=D(e),n=e.respectDoNotTrack!==!1&&P(),a=e.consent===!1||n,s=typeof e.apiKey=="string"&&e.apiKey.startsWith("pk_"),o=e.localMode===!0||!s;if(!e.graph||o||typeof window=="undefined")return t;if(a)return n||M(e.apiKey,d=>_e(d)),t;let i=T.get(e.apiKey);if(i)try{i()}catch(d){}let c=K({sectionTypes:e.sectionTypes}),l=(r=e.ingestUrl)!=null?r:Ne,u=$({syncUrl:l.replace(/\/events\/?$/,"/graph/sync"),apiKey:e.apiKey,projectId:e.apiKey,sessionId:Re(e.apiKey)});c.scan().then(d=>{for(let p of d.nodes)u.addPageNode({id:p.componentId,componentId:p.componentId,semanticType:p.semanticType,answers:e.captureDomText&&p.headingText?[p.headingText]:[],prominenceScore:p.prominenceScore,depth:p.depth});for(let p of d.edges)u.addStructuralEdge(p);u.syncOnce()});let m=null,g=()=>{m!==null&&clearTimeout(m),m=setTimeout(()=>{m=null,u.syncOnce()},500)};c.observe(d=>{for(let p of d.nodes)u.addPageNode({id:p.componentId,componentId:p.componentId,semanticType:p.semanticType,answers:e.captureDomText&&p.headingText?[p.headingText]:[],prominenceScore:p.prominenceScore,depth:p.depth});for(let p of d.edges)u.addStructuralEdge(p);g()});let h=()=>{m!==null&&(clearTimeout(m),m=null),c.destroy(),u.destroy(),T.get(e.apiKey)===h&&T.delete(e.apiKey)};return T.set(e.apiKey,h),b(I({},t),{getGraph:()=>u.snapshot(),dispose:()=>{h(),t.dispose()},destroy:()=>{h(),t.destroy()}})}export{Me as BLOCK_ALIGNS,$e as BLOCK_EMPHASES,Ue as BLOCK_FITS,Oe as BLOCK_GAPS,Ke as BLOCK_GRID_COLUMNS,Fe as BLOCK_HEADING_LEVELS,Pe as BLOCK_JUSTIFIES,ze as BLOCK_MAX_WIDTHS,qe as BLOCK_PADS,je as BLOCK_RATIOS,De as BLOCK_SIZES,Be as BLOCK_SURFACES,Le as BLOCK_TEXT_ALIGNS,ke as BLOCK_TONES,Ge as BLOCK_WEIGHTS,He as FORM_FIELD_KINDS,Ve as FORM_INPUT_TYPES,w as LEGACY_SESSION_COOKIE_NAME,Ze as MAX_BLOCK_ARMS,Qe as MAX_BLOCK_CHILDREN,Xe as MAX_BLOCK_DEPTH,Je as MAX_BLOCK_NODES,et as MAX_BLOCK_TEXT_LEN,Ye as MAX_FORM_FIELDS,We as MAX_FORM_SELECT_OPTIONS,B as SNAPSHOT_STORAGE_KEY_PREFIX,ne as STAGE_ATTRIBUTE,te as armOfResult,se as attachMicroSignalDetectors,Z as baselineResultFor,ee as baselineSlots,tt as containsFormBlock,X as deriveSessionSegment,V as detectDeviceClass,J as detectTimeOfDay,Y as detectTrafficSource,oe as exposedStage,ae as grantConsent,_e as init,P as isDoNotTrackEnabled,v as locatorFromElement,q as readSnapshot,W as referrerDomainFromReferer,H as renderPrePaintScript,k as sanitizePageUrl,A as sessionCookieName,re as setStageAttribute,Q as toWireSlot,z as writeSnapshot};
2
2
  //# sourceMappingURL=index-graph.mjs.map
@@ -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']);\n/** Mutation bursts are scanned once, this long after they start. */\nexport const OBSERVE_BATCH_MS = 200;\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\nexport type DOMScannerOptions = {\n /**\n * Section types declared in code, keyed by `data-sentient-id`. Replaces the\n * per-element `data-sentient-type` attribute so a section needs one attribute\n * of markup. The content classifier misses sections whose copy carries no\n * strong signal (an \"About us\" band reads `generic`, not `trust`), and a\n * wrong type here reorders that section for the wrong personas.\n */\n sectionTypes?: Readonly<Partial<Record<string, string>>>;\n};\n\n// Declared type (sectionTypes) → legacy data-sentient-type markup → role →\n// heuristic → generic. Every output is normalized to the graph_nodes enum: an\n// out-of-vocabulary declared/markup/role value falls through to the next stage\n// instead of being emitted raw (raw values violated the graph_nodes CHECK\n// constraint on insert).\nfunction inferSemanticType(\n element: Element,\n sectionTypes: Readonly<Partial<Record<string, string>>> | undefined,\n): SemanticType {\n const id = element.getAttribute('data-sentient-id');\n // The SEMANTIC_SET check also rejects inherited keys (an id of \"constructor\").\n const declared = id ? sectionTypes?.[id] : undefined;\n if (declared && SEMANTIC_SET.has(declared)) return declared as 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 sectionTypes: Readonly<Partial<Record<string, string>>> | undefined,\n): ScannedNode {\n const heading = element.querySelector(HEADING_SELECTOR);\n return {\n componentId: componentIdFor(element),\n semanticType: inferSemanticType(element, sectionTypes),\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 sectionTypes: Readonly<Partial<Record<string, string>>> | undefined,\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, sectionTypes);\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, sectionTypes);\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(options: DOMScannerOptions = {}): DOMScanner {\n const { sectionTypes } = options;\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, sectionTypes);\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 // Added roots waiting for the batched pass below, and its pending timer.\n const pendingRoots = new Set<Element>();\n let flushTimer: ReturnType<typeof setTimeout> | null = null;\n\n const processPending = (): void => {\n flushTimer = null;\n const roots = [...pendingRoots];\n pendingRoots.clear();\n const added: ScannedNode[] = [];\n const addedIds = new Set<string>();\n for (const node of roots) {\n // Gone before we got to it (a transient spinner, a replaced route), or\n // already covered by a queued ancestor's subtree scan.\n if (!node.isConnected) continue;\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 be queued (the child once via the parent's subtree, once\n // directly), which would emit duplicate nodes.\n if (knownElementToId.has(el)) continue;\n const scanned = scanElement(el, getProminenceScore, sectionTypes);\n added.push(scanned);\n addedIds.add(scanned.componentId);\n knownElementToId.set(el, scanned.componentId);\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\n const observe = (onContentAdded: (event: ContentAddedEvent) => void): void => {\n contentCallback = onContentAdded;\n try {\n // The callback only QUEUES added roots; the subtree scan runs once per\n // burst, OBSERVE_BATCH_MS after it starts (audit S11). It used to run a\n // querySelectorAll per added element inside every mutation callback — on\n // a page with constant DOM churn (a chat, a virtualised list, a ticker)\n // that was main-thread work on every frame, for sections that mostly\n // arrive once, at mount or route change.\n observer = new MutationObserver((mutations) => {\n for (const mutation of mutations) {\n if (mutation.type !== 'childList') continue;\n mutation.addedNodes.forEach((node) => {\n if (node instanceof Element) pendingRoots.add(node);\n });\n }\n if (pendingRoots.size > 0 && flushTimer === null) flushTimer = setTimeout(processPending, OBSERVE_BATCH_MS);\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 (flushTimer !== null) clearTimeout(flushTimer);\n flushTimer = null;\n pendingRoots.clear();\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 { exposedStage, setStageAttribute, STAGE_ATTRIBUTE } from './stage-attribute.js';\nexport type { StageAttributes } from './stage-attribute.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 DOMScannerOptions,\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 * Section types declared in code, keyed by `data-sentient-id`\n * (e.g. `{ about: 'trust' }`). Wins over the content classifier and over\n * legacy `data-sentient-type` markup. See `DOMScannerOptions.sectionTypes`.\n */\n sectionTypes?: Readonly<Partial<Record<string, string>>>;\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({ sectionTypes: config.sectionTypes });\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":"gqBA4CA,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,GAAGC,EAAE,MAAM,GAAGA,EAAE,QAAQ,EACjC,OAAQR,EAAA,CACN,MAAO,GACT,CACF,CAEA,SAASS,GAAcC,EAAqBhB,EAAsBiB,EAA2B,CAC3F,IAAMC,EAAQ,GAAGF,CAAW,IAAIhB,CAAY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kBgB,EAAK,YAAc,CAACA,EAAK,WAAW,EAAI,CAAC,EAC3E,gBAAiBA,EAAK,gBACtB,MAAOA,EAAK,KACd,CAAC,EAEH,QAAWC,KAAQG,EAAM,MACvBP,EAAY,kBAAkBI,CAAI,EAEpCE,EAAc,CAChB,CAAC,EAKD,IAAME,EAAgB,IAAY,CAC5BH,IAAsB,OACxB,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","i","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","OBSERVE_BATCH_MS","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","sectionTypes","id","declared","explicit","role","classifySection","shortHash","input","h","i","domPathSignature","parts","current","parent","index","componentIdFor","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","options","observer","idleCallbackId","contentCallback","knownElementToId","styles","fontSize","zIndex","rect","distanceFromTop","viewportHeight","inverseDistance","score","scan","resolve","run","pendingRoots","flushTimer","processPending","roots","added","addedIds","candidates","scanned","onContentAdded","mutations","mutation","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']);\n/** Mutation bursts are scanned once, this long after they start. */\nexport const OBSERVE_BATCH_MS = 200;\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\nexport type DOMScannerOptions = {\n /**\n * Section types declared in code, keyed by `data-sentient-id`. Replaces the\n * per-element `data-sentient-type` attribute so a section needs one attribute\n * of markup. The content classifier misses sections whose copy carries no\n * strong signal (an \"About us\" band reads `generic`, not `trust`), and a\n * wrong type here reorders that section for the wrong personas.\n */\n sectionTypes?: Readonly<Partial<Record<string, string>>>;\n};\n\n// Declared type (sectionTypes) → legacy data-sentient-type markup → role →\n// heuristic → generic. Every output is normalized to the graph_nodes enum: an\n// out-of-vocabulary declared/markup/role value falls through to the next stage\n// instead of being emitted raw (raw values violated the graph_nodes CHECK\n// constraint on insert).\nfunction inferSemanticType(\n element: Element,\n sectionTypes: Readonly<Partial<Record<string, string>>> | undefined,\n): SemanticType {\n const id = element.getAttribute('data-sentient-id');\n // The SEMANTIC_SET check also rejects inherited keys (an id of \"constructor\").\n const declared = id ? sectionTypes?.[id] : undefined;\n if (declared && SEMANTIC_SET.has(declared)) return declared as 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 sectionTypes: Readonly<Partial<Record<string, string>>> | undefined,\n): ScannedNode {\n const heading = element.querySelector(HEADING_SELECTOR);\n return {\n componentId: componentIdFor(element),\n semanticType: inferSemanticType(element, sectionTypes),\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 sectionTypes: Readonly<Partial<Record<string, string>>> | undefined,\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, sectionTypes);\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, sectionTypes);\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(options: DOMScannerOptions = {}): DOMScanner {\n const { sectionTypes } = options;\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, sectionTypes);\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 // Added roots waiting for the batched pass below, and its pending timer.\n const pendingRoots = new Set<Element>();\n let flushTimer: ReturnType<typeof setTimeout> | null = null;\n\n const processPending = (): void => {\n flushTimer = null;\n const roots = [...pendingRoots];\n pendingRoots.clear();\n const added: ScannedNode[] = [];\n const addedIds = new Set<string>();\n for (const node of roots) {\n // Gone before we got to it (a transient spinner, a replaced route), or\n // already covered by a queued ancestor's subtree scan.\n if (!node.isConnected) continue;\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 be queued (the child once via the parent's subtree, once\n // directly), which would emit duplicate nodes.\n if (knownElementToId.has(el)) continue;\n const scanned = scanElement(el, getProminenceScore, sectionTypes);\n added.push(scanned);\n addedIds.add(scanned.componentId);\n knownElementToId.set(el, scanned.componentId);\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\n const observe = (onContentAdded: (event: ContentAddedEvent) => void): void => {\n contentCallback = onContentAdded;\n try {\n // The callback only QUEUES added roots; the subtree scan runs once per\n // burst, OBSERVE_BATCH_MS after it starts (audit S11). It used to run a\n // querySelectorAll per added element inside every mutation callback — on\n // a page with constant DOM churn (a chat, a virtualised list, a ticker)\n // that was main-thread work on every frame, for sections that mostly\n // arrive once, at mount or route change.\n observer = new MutationObserver((mutations) => {\n for (const mutation of mutations) {\n if (mutation.type !== 'childList') continue;\n mutation.addedNodes.forEach((node) => {\n if (node instanceof Element) pendingRoots.add(node);\n });\n }\n if (pendingRoots.size > 0 && flushTimer === null) flushTimer = setTimeout(processPending, OBSERVE_BATCH_MS);\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 (flushTimer !== null) clearTimeout(flushTimer);\n flushTimer = null;\n pendingRoots.clear();\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 { exposedStage, setStageAttribute, STAGE_ATTRIBUTE } from './stage-attribute.js';\nexport type { StageAttributes } from './stage-attribute.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 DOMScannerOptions,\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 * Section types declared in code, keyed by `data-sentient-id`\n * (e.g. `{ about: 'trust' }`). Wins over the content classifier and over\n * legacy `data-sentient-type` markup. See `DOMScannerOptions.sectionTypes`.\n */\n sectionTypes?: Readonly<Partial<Record<string, string>>>;\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({ sectionTypes: config.sectionTypes });\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":"0tBA4CA,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,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Q,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","i","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","OBSERVE_BATCH_MS","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","sectionTypes","id","declared","explicit","role","classifySection","shortHash","input","h","i","domPathSignature","parts","current","parent","index","componentIdFor","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","options","observer","idleCallbackId","contentCallback","knownElementToId","styles","fontSize","zIndex","rect","distanceFromTop","viewportHeight","inverseDistance","score","scan","resolve","run","pendingRoots","flushTimer","processPending","roots","added","addedIds","candidates","scanned","onContentAdded","mutations","mutation","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"]}
@@ -0,0 +1,37 @@
1
+ /** What identify() may send about an email: never the address itself. */
2
+ type EmailFields = {
3
+ emailHash?: string;
4
+ emailDomain?: string;
5
+ };
6
+ /**
7
+ * `email.trim().toLowerCase()`, or null unless it has exactly one `@` with
8
+ * something on both sides. Must stay byte-identical to the API's and the
9
+ * dashboard's normalization: the server matches the hash against rules hashed
10
+ * from what the operator typed, so `Name@Example.com ` hashed un-normalized
11
+ * would never match `name@example.com` and the teammate would keep counting.
12
+ */
13
+ declare function normalizeEmail(email: unknown): string | null;
14
+ /**
15
+ * `{ emailHash: sha256_hex(norm), emailDomain }` for a valid email, `{}` for
16
+ * anything else. Without SubtleCrypto (a non-secure http: page, where
17
+ * `crypto.subtle` is undefined) the hash cannot be computed, so only the
18
+ * domain is sent — never a fallback that would put the raw address on the
19
+ * wire. A domain over 253 chars is not a hostname; the API would ignore it.
20
+ */
21
+ declare function emailFields(email: unknown): Promise<EmailFields>;
22
+ /**
23
+ * Handles `?sentient_internal=<token>` / `?sentient_internal=off` on this page
24
+ * load, then returns the browser's current token (or null).
25
+ *
26
+ * The cookie goes on the same domain as the visitor cookie (`domain`, which
27
+ * initSession detected) so a team browser marked on `example.com` is also
28
+ * internal on `app.example.com` — a host-only cookie would mark one host and
29
+ * let the other keep counting the same person. The param is stripped with
30
+ * replaceState so the token is not left in the address bar to be bookmarked,
31
+ * shared in a screenshot, or sent onward as a Referer. Only base64url tokens
32
+ * are stored: the server's token is 32 base64url chars, and anything else in
33
+ * a cookie is just junk riding every request.
34
+ */
35
+ declare function takeInternalToken(domain: string | null): string | null;
36
+
37
+ export { type EmailFields, emailFields, normalizeEmail, takeInternalToken };
@@ -0,0 +1,37 @@
1
+ /** What identify() may send about an email: never the address itself. */
2
+ type EmailFields = {
3
+ emailHash?: string;
4
+ emailDomain?: string;
5
+ };
6
+ /**
7
+ * `email.trim().toLowerCase()`, or null unless it has exactly one `@` with
8
+ * something on both sides. Must stay byte-identical to the API's and the
9
+ * dashboard's normalization: the server matches the hash against rules hashed
10
+ * from what the operator typed, so `Name@Example.com ` hashed un-normalized
11
+ * would never match `name@example.com` and the teammate would keep counting.
12
+ */
13
+ declare function normalizeEmail(email: unknown): string | null;
14
+ /**
15
+ * `{ emailHash: sha256_hex(norm), emailDomain }` for a valid email, `{}` for
16
+ * anything else. Without SubtleCrypto (a non-secure http: page, where
17
+ * `crypto.subtle` is undefined) the hash cannot be computed, so only the
18
+ * domain is sent — never a fallback that would put the raw address on the
19
+ * wire. A domain over 253 chars is not a hostname; the API would ignore it.
20
+ */
21
+ declare function emailFields(email: unknown): Promise<EmailFields>;
22
+ /**
23
+ * Handles `?sentient_internal=<token>` / `?sentient_internal=off` on this page
24
+ * load, then returns the browser's current token (or null).
25
+ *
26
+ * The cookie goes on the same domain as the visitor cookie (`domain`, which
27
+ * initSession detected) so a team browser marked on `example.com` is also
28
+ * internal on `app.example.com` — a host-only cookie would mark one host and
29
+ * let the other keep counting the same person. The param is stripped with
30
+ * replaceState so the token is not left in the address bar to be bookmarked,
31
+ * shared in a screenshot, or sent onward as a Referer. Only base64url tokens
32
+ * are stored: the server's token is 32 base64url chars, and anything else in
33
+ * a cookie is just junk riding every request.
34
+ */
35
+ declare function takeInternalToken(domain: string | null): string | null;
36
+
37
+ export { type EmailFields, emailFields, normalizeEmail, takeInternalToken };
@@ -0,0 +1,2 @@
1
+ "use strict";var a=Object.defineProperty;var S=Object.getOwnPropertyDescriptor;var y=Object.getOwnPropertyNames;var k=Object.prototype.hasOwnProperty;var h=(t,e)=>{for(var n in e)a(t,n,{get:e[n],enumerable:!0})},f=(t,e,n,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of y(e))!k.call(t,r)&&r!==n&&a(t,r,{get:()=>e[r],enumerable:!(o=S(e,r))||o.enumerable});return t};var x=t=>f(a({},"__esModule",{value:!0}),t);var _={};h(_,{emailFields:()=>d,normalizeEmail:()=>c,takeInternalToken:()=>p});module.exports=x(_);var s="sentient_internal";function l(t){try{let e=document.cookie.match(new RegExp(`(?:^|; )${t}=([^;]*)`));return e?decodeURIComponent(e[1]):null}catch(e){return null}}function E(){try{return location.protocol==="https:"?"; Secure":""}catch(t){return""}}function i(t,e,n,o){try{document.cookie=`${t}=${encodeURIComponent(e)}; max-age=${n}; SameSite=lax; path=/${o?`; domain=${o}`:""}${E()}`}catch(r){}}function u(t,e){i(t,"",0,e)}function c(t){if(typeof t!="string")return null;let e=t.trim().toLowerCase(),[n,o,r]=e.split("@");return n&&o&&r===void 0?e:null}async function d(t){let e=c(t),n=e==null?void 0:e.split("@")[1];if(!n||n.length>253)return{};try{let o=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(e)),r="";for(let g of new Uint8Array(o))r+=g.toString(16).padStart(2,"0");return{emailHash:r,emailDomain:n}}catch(o){return{emailDomain:n}}}var m=365*24*60*60;function p(t){try{let e=new URL(location.href),n=e.searchParams.get(s);n!==null&&(u(s),t&&u(s,t),n!=="off"&&/^[\w-]{1,128}$/.test(n)&&(i(s,n,m,t),l(s)!==n&&i(s,n,m)),e.searchParams.delete(s),history.replaceState(history.state,"",e.pathname+e.search+e.hash))}catch(e){}return l(s)}0&&(module.exports={emailFields,normalizeEmail,takeInternalToken});
2
+ //# sourceMappingURL=index-internal-traffic.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index-internal-traffic.ts","../src/storage-key.ts","../src/session.ts","../src/internal.ts"],"sourcesContent":["/**\n * `@sentientui/core/internal-traffic` — the lazily loaded half of the\n * internal-traffic signals (email normalization + SHA-256, the\n * `?sentient_internal=` link's cookie write/delete/strip, the token read).\n *\n * init() and identify() reach it only through a dynamic import of this BARE\n * subpath, and only when a page needs it (the link or cookie is present, or\n * identify() got an `email`). Every visitor used to download this code for a\n * feature only team browsers and identified users exercise; as a subpath the\n * app's bundler splits it out, and the snippet points the same specifier at\n * one of its own lazy chunks (see packages/snippet/tsup.config.ts). tsup keeps\n * it external, exactly like `@sentientui/core/local`.\n */\nexport { emailFields, normalizeEmail, takeInternalToken } from './internal.js';\nexport type { EmailFields } from './internal.js';\n","/**\n * Per-project browser-storage namespace suffix, derived from the public apiKey.\n *\n * Multiple SentientUI projects (different `pk_` keys) can run on the same exact\n * origin. Storage keyed only by name (`_snt_uid`, `_snt_asgn_*`,\n * `_snt_graph_nodes`) would then collide across projects — the visitor id in\n * particular, whose session row is keyed globally server-side, would let one\n * project's traffic land on another's session. Suffixing every browser key with\n * the apiKey prefix isolates projects, matching the queue's existing\n * `_snt_retry_${apiKey.slice(0,12)}` convention.\n *\n * Returns `''` when no apiKey is available (local mode) so keys stay stable\n * there.\n */\nexport function storageSuffix(apiKey?: string): string {\n return apiKey ? `_${apiKey.slice(0, 12)}` : '';\n}\n\n/**\n * The bare, pre-namespacing session cookie name. Still read as a FALLBACK\n * everywhere the suffixed name is read, so visitors who got their identity\n * before per-project namespacing keep it instead of being minted a fresh one.\n */\nexport const LEGACY_SESSION_COOKIE_NAME = '_snt_uid';\n\n/**\n * The one place the session cookie's name is decided. The writer (session.ts)\n * and every reader (core/server.ts SSR helper, graph sync, react devtools) must\n * call THIS — when namespacing landed, the writer moved to the suffixed name\n * while three readers kept the bare `_snt_uid`, so every SSR request for a\n * returning visitor missed the cookie and minted a fresh orphan session (quota\n * inflation, broken sticky assignments and persona continuity), and graph sync\n * sent `sessionId: undefined`. Deriving both sides from one function makes that\n * drift impossible, and index.test.ts pins the reader against the writer.\n */\nexport function sessionCookieName(apiKey?: string): string {\n return `${LEGACY_SESSION_COOKIE_NAME}${storageSuffix(apiKey)}`;\n}\n\n// Forget-me generation per project, on window so every bundle on the page\n// sees it (the snippet and its lazy chunks each carry their own copy of these\n// modules). Every client and queue captures it when created and persists only\n// while it is unchanged: a forget can never be undone by a later grant — the\n// old boolean marker was cleared by the next tracking client, and a paused\n// client's in-flight decide then wrote the forgotten visitor back (grader\n// NEW-1), as could its queues' failed final flush (F8).\nconst GENS = '__sntForgetGen';\ntype GenMap = Record<string, number>;\nconst genMap = (): GenMap | undefined => {\n try {\n return (window as unknown as Record<string, GenMap | undefined>)[GENS];\n } catch {\n return undefined;\n }\n};\nexport function markForgotten(apiKey: string): void {\n try {\n const w = window as unknown as Record<string, GenMap>;\n const m = (w[GENS] ??= {});\n m[apiKey] = (m[apiKey] ?? 0) + 1;\n } catch {\n /* no window */\n }\n}\n/** Bumped by every forget-me for this project in this page. */\nexport function forgetGeneration(apiKey: string): number {\n return genMap()?.[apiKey] ?? 0;\n}\n\n/**\n * The \"mark this browser internal\" cookie (internal-traffic plan, Interfaces).\n * One name for the browser writer (internal.ts) and the SSR reader\n * (@sentientui/react/server) — the same drift the session cookie name had\n * (writer renamed, readers not) would silently stop SSR upserts carrying the\n * token, so server-rendered first requests from a team browser would count.\n * Not namespaced per project: the value is the project-bound token itself,\n * and the server ignores a token that is not this project's.\n */\nexport const INTERNAL_COOKIE = 'sentient_internal';\n","/** Manages anonymous session identity with cookie + localStorage layers. */\n\nimport { randomUuidV4 } from './uuid.js';\nimport { sessionCookieName, storageSuffix } from './storage-key.js';\nimport { parentDomains, type CookieDomainOption } from './cookie-domain.js';\n\nexport type SessionConfig = {\n cookieName?: string;\n cookieTTLDays?: number;\n /**\n * Public apiKey — namespaces the `_snt_uid` cookie + storage per project, so\n * two projects on the same exact origin don't share a visitor id (which would\n * cross-contaminate sessions server-side). Omit in local mode.\n */\n apiKey?: string;\n /**\n * Session ID generated during SSR (e.g. from `loadAdaptiveAssignments`).\n * Used as the fallback when no existing cookie or localStorage entry is found,\n * so the client adopts the same session the server used for variant assignment\n * on first visit rather than generating a new, orphaned ID.\n */\n ssrSessionId?: string;\n /**\n * Where the visitor cookie lives. Default (undefined): the site's\n * registrable domain, auto-detected, so `example.com` and `app.example.com`\n * share one visitor. `false`: this host only. A string: that domain.\n */\n cookieDomain?: CookieDomainOption;\n};\n\nexport type SessionManager = {\n getSessionId(): string | null;\n /** True when neither cookie nor localStorage could be written — id is in-memory only. */\n isEphemeral(): boolean;\n /** The domain the visitor cookie is shared on (null = this host only) —\n * also the site's extent for referrer classification. */\n domain: string | null;\n destroy(): void;\n};\n\nconst DEFAULT_COOKIE_NAME = '_snt_uid';\nconst DEFAULT_COOKIE_TTL_DAYS = 365;\nconst STORAGE_KEY = '_snt_uid';\n\n/**\n * Generates a unique session identifier. Always an RFC 4122 v4 UUID — the id is\n * stored server-side in a Postgres `uuid` column, so the insecure-context\n * fallback must not emit a malformed value (see `randomUuidV4`).\n */\nfunction generateSessionId(): string {\n return randomUuidV4();\n}\n\nexport function readCookie(name: string): string | null {\n try {\n const match = document.cookie.match(new RegExp(`(?:^|; )${name}=([^;]*)`));\n return match ? decodeURIComponent(match[1]) : null;\n } catch {\n return null;\n }\n}\n\n// `Secure` on https pages (audit S21): without it the identity cookie also\n// rode any plain-http request to the same host. Never on http (localhost dev),\n// where the browser would refuse to store it at all.\nfunction secureAttr(): string {\n try {\n return location.protocol === 'https:' ? '; Secure' : '';\n } catch {\n return '';\n }\n}\n\n// SameSite=Lax, not Strict (grader N-B): a Strict cookie is withheld on\n// cross-site top-level navigations — a click from Google, an ad, an email — so\n// AdaptiveRoot's SSR read missed a returning visitor on exactly their landing\n// page and minted an orphan session whose slot trials never saw the visit's\n// conversions (the browser kept its own id). Lax still never rides cross-site\n// subresource or POST requests, and the cookie is first-party only.\nexport function writeCookie(name: string, value: string, maxAgeSeconds: number, domain?: string | null): void {\n try {\n document.cookie = `${name}=${encodeURIComponent(value)}; max-age=${maxAgeSeconds}; SameSite=lax; path=/${domain ? `; domain=${domain}` : ''}${secureAttr()}`;\n } catch {\n /* ignore */\n }\n}\n\nfunction readLocalStorage(key: string): string | null {\n try {\n return localStorage.getItem(key);\n } catch {\n return null;\n }\n}\n\nfunction writeLocalStorage(key: string, value: string): boolean {\n try {\n localStorage.setItem(key, value);\n return true;\n } catch {\n return false;\n }\n}\n\nfunction readSessionStorage(key: string): string | null {\n try {\n return sessionStorage.getItem(key);\n } catch {\n return null;\n }\n}\n\nfunction writeSessionStorage(key: string, value: string): boolean {\n try {\n sessionStorage.setItem(key, value);\n return true;\n } catch {\n return false;\n }\n}\n\nfunction removeSessionStorage(key: string): void {\n try {\n sessionStorage.removeItem(key);\n } catch {\n /* ignore */\n }\n}\n\nfunction probeCookieWritable(name: string): boolean {\n try {\n document.cookie = `${name}_probe=1; max-age=1; SameSite=lax; path=/${secureAttr()}`;\n return document.cookie.indexOf(`${name}_probe=1`) !== -1;\n } catch {\n return false;\n }\n}\n\nfunction removeLocalStorage(key: string): void {\n try {\n localStorage.removeItem(key);\n } catch {\n /* ignore */\n }\n}\n\nexport function clearCookie(name: string, domain?: string | null): void {\n writeCookie(name, '', 0, domain); // writeCookie already swallows a throw\n}\n\nconst SSR_MANAGER: SessionManager = {\n getSessionId: () => null,\n isEphemeral: () => false,\n domain: null,\n destroy: () => undefined,\n};\n\n/**\n * The domain to share the visitor cookie on (cookie-domain.ts), or null for\n * host-only. undefined → the shortest parent the browser accepts a probe\n * cookie on; false → host-only; a string → that domain (one that does not\n * cover this host is refused by the browser, and initSession then falls back\n * to host-only — see the write check there).\n */\nfunction detectCookieDomain(option: CookieDomainOption, probe: string): string | null {\n if (option === false) return null;\n if (typeof option === 'string') return option.replace(/^\\./, '');\n for (const d of parentDomains(location.hostname)) {\n writeCookie(probe, '1', 10, d);\n if (readCookie(probe) === '1') {\n clearCookie(probe, d);\n return d;\n }\n }\n return null;\n}\n\n/**\n * Initializes session management. Returns a no-op manager in SSR environments.\n */\nexport function initSession(config?: SessionConfig): SessionManager {\n if (typeof window === 'undefined') {\n return SSR_MANAGER;\n }\n\n // Namespace the visitor-id keys per project so multiple keys on one origin\n // don't share a `_snt_uid` (see storage-key.ts). An explicit cookieName still\n // wins for callers that manage their own naming. sessionCookieName is the\n // shared writer/reader name — the SSR reader and graph sync derive the same\n // string from it, so they can't drift back to the bare name.\n const suffix = storageSuffix(config?.apiKey);\n const cookieName = config?.cookieName ?? sessionCookieName(config?.apiKey);\n const storageKey = `${STORAGE_KEY}${suffix}`;\n // Forget-me tombstone for the legacy fallback below. destroy() deletes only\n // this project's SUFFIXED keys — deleting the bare pre-namespacing ones\n // would reset every other project on a shared origin — so without a marker\n // the next init()'s readLegacy() re-adopted the exact identity the visitor\n // had just asked to forget. The marker carries the same per-project suffix,\n // so other projects keep adopting the bare id exactly as before.\n const legacyTombstoneKey = `${STORAGE_KEY}_tomb${suffix}`;\n const cookieTTLDays = config?.cookieTTLDays ?? DEFAULT_COOKIE_TTL_DAYS;\n const maxAgeSeconds = cookieTTLDays * 24 * 60 * 60;\n\n // Treat an empty string from any layer as absent. A `_snt_uid=` cookie with no\n // value (or an empty localStorage/sessionStorage entry) decodes to '', which is\n // not nullish — a plain `??` chain would keep it and persist it for a year,\n // leaving getSessionId() falsy so every track/goal/upsert bails out and the\n // visitor is permanently muted with no way to regenerate. Coercing '' to null\n // lets the chain fall through to a real id (or a freshly generated one).\n const nonEmpty = (value: string | null | undefined): string | null =>\n value && value.length > 0 ? value : null;\n\n // Legacy fallback: visitors identified BEFORE per-project namespacing carry\n // their id under the bare `_snt_uid` names. Without this read, the rollout of\n // the suffixed names reset every existing visitor's identity — a fresh session\n // row per visitor, broken sticky assignments, persona continuity lost. The id\n // is adopted (re-written under the suffixed names below) but the legacy keys\n // are left in place: deleting them would reset the OTHER projects on a shared\n // origin that haven't migrated it yet. Skipped when the caller manages its own\n // cookieName — the bare `_snt_uid` was never theirs — and when there is no\n // suffix (local mode still uses the bare names directly).\n // The tombstone (written by destroy()) blocks this fallback for THIS project\n // only — a forgotten visitor must come back a stranger, not resurrected from\n // the bare keys that other projects still legitimately share.\n const readLegacy = (): string | null =>\n suffix && !config?.cookieName && readLocalStorage(legacyTombstoneKey) === null\n ? nonEmpty(readCookie(DEFAULT_COOKIE_NAME)) ??\n nonEmpty(readLocalStorage(STORAGE_KEY)) ??\n nonEmpty(readSessionStorage(STORAGE_KEY))\n : null;\n\n // Shared visitor cookie (cookie-domain.ts). JS cannot tell a host-only\n // cookie from a domain cookie of the same name — document.cookie lists both\n // as `name=value` — so this host's own copy is deleted and the cookie read\n // again: whatever survives is the SHARED id, and it wins. That is what\n // aligns two hosts that each minted an id before sharing existed (and after\n // Safari's 7-day cap expires the shared one): the first host to write the\n // shared cookie decides, the other adopts it on its next page.\n let domain = detectCookieDomain(config?.cookieDomain, `${cookieName}_dom`);\n const ownCopy = nonEmpty(readCookie(cookieName));\n const shared = domain ? (clearCookie(cookieName), nonEmpty(readCookie(cookieName))) : null;\n\n let sessionId: string | null =\n shared ??\n ownCopy ??\n nonEmpty(readLocalStorage(storageKey)) ??\n nonEmpty(readSessionStorage(storageKey)) ??\n readLegacy() ??\n nonEmpty(config?.ssrSessionId) ??\n generateSessionId();\n\n writeCookie(cookieName, sessionId, maxAgeSeconds, domain);\n // A domain the probe accepted but this write did not (a cookie-policy\n // extension, a jar at capacity) must not leave the visitor with no cookie:\n // the host-only copy was deleted above.\n if (domain && readCookie(cookieName) !== sessionId) {\n domain = null;\n writeCookie(cookieName, sessionId, maxAgeSeconds);\n }\n const lsOk = writeLocalStorage(storageKey, sessionId);\n const cookieOk = probeCookieWritable(cookieName);\n // Always write sessionStorage when localStorage fails — it covers same-tab\n // navigation even in strict storage environments.\n const ssOk = !lsOk ? writeSessionStorage(storageKey, sessionId) : false;\n const ephemeral = !lsOk && !cookieOk && !ssOk;\n\n return {\n getSessionId: () => sessionId,\n isEphemeral: () => ephemeral,\n domain,\n destroy: () => {\n sessionId = null;\n clearCookie(cookieName);\n clearCookie(cookieName, domain); // the shared copy (a repeat no-op when host-only)\n removeLocalStorage(storageKey);\n removeSessionStorage(storageKey);\n // See legacyTombstoneKey: the bare `_snt_uid` keys stay for the other\n // projects on this origin, but this project's next init() must not\n // re-adopt them — that quietly undid the forget-me it just performed.\n // Only when a bare id exists to block: an unconditional marker was a\n // storage write on every forget-me, for visitors with nothing to hide.\n if (\n suffix &&\n !config?.cookieName &&\n (readCookie(DEFAULT_COOKIE_NAME) !== null || readLocalStorage(STORAGE_KEY) !== null || readSessionStorage(STORAGE_KEY) !== null)\n ) {\n writeLocalStorage(legacyTombstoneKey, '1');\n }\n },\n };\n}\n","/**\n * Internal-traffic signals the browser SDK sends (plan 2026-11-04, Interfaces):\n * the hashed identify email and the \"mark this browser internal\" link. The\n * server decides what counts as internal; this module only makes sure the\n * signals reach it — and that a raw email never does.\n */\nimport { INTERNAL_COOKIE } from './storage-key.js';\nimport { clearCookie, readCookie, writeCookie } from './session.js';\n\n/** What identify() may send about an email: never the address itself. */\nexport type EmailFields = { emailHash?: string; emailDomain?: string };\n\n/**\n * `email.trim().toLowerCase()`, or null unless it has exactly one `@` with\n * something on both sides. Must stay byte-identical to the API's and the\n * dashboard's normalization: the server matches the hash against rules hashed\n * from what the operator typed, so `Name@Example.com ` hashed un-normalized\n * would never match `name@example.com` and the teammate would keep counting.\n */\nexport function normalizeEmail(email: unknown): string | null {\n if (typeof email !== 'string') return null;\n const n = email.trim().toLowerCase();\n const [local, domain, extra] = n.split('@');\n return local && domain && extra === undefined ? n : null;\n}\n\n/**\n * `{ emailHash: sha256_hex(norm), emailDomain }` for a valid email, `{}` for\n * anything else. Without SubtleCrypto (a non-secure http: page, where\n * `crypto.subtle` is undefined) the hash cannot be computed, so only the\n * domain is sent — never a fallback that would put the raw address on the\n * wire. A domain over 253 chars is not a hostname; the API would ignore it.\n */\nexport async function emailFields(email: unknown): Promise<EmailFields> {\n const n = normalizeEmail(email);\n const emailDomain = n?.split('@')[1];\n if (!emailDomain || emailDomain.length > 253) return {};\n try {\n const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(n!));\n let emailHash = '';\n for (const b of new Uint8Array(digest)) emailHash += b.toString(16).padStart(2, '0');\n return { emailHash, emailDomain };\n } catch {\n return { emailDomain };\n }\n}\n\nconst ONE_YEAR_S = 365 * 24 * 60 * 60;\n\n/**\n * Handles `?sentient_internal=<token>` / `?sentient_internal=off` on this page\n * load, then returns the browser's current token (or null).\n *\n * The cookie goes on the same domain as the visitor cookie (`domain`, which\n * initSession detected) so a team browser marked on `example.com` is also\n * internal on `app.example.com` — a host-only cookie would mark one host and\n * let the other keep counting the same person. The param is stripped with\n * replaceState so the token is not left in the address bar to be bookmarked,\n * shared in a screenshot, or sent onward as a Referer. Only base64url tokens\n * are stored: the server's token is 32 base64url chars, and anything else in\n * a cookie is just junk riding every request.\n */\nexport function takeInternalToken(domain: string | null): string | null {\n try {\n const url = new URL(location.href);\n const v = url.searchParams.get(INTERNAL_COOKIE);\n if (v !== null) {\n // Both copies: a host-only one (written when the domain write was\n // refused) would otherwise survive the \"stop marking\" link.\n clearCookie(INTERNAL_COOKIE);\n if (domain) clearCookie(INTERNAL_COOKIE, domain);\n if (v !== 'off' && /^[\\w-]{1,128}$/.test(v)) {\n writeCookie(INTERNAL_COOKIE, v, ONE_YEAR_S, domain);\n // Same fallback as the visitor cookie: a domain the browser refused\n // must not leave the browser unmarked.\n if (readCookie(INTERNAL_COOKIE) !== v) writeCookie(INTERNAL_COOKIE, v, ONE_YEAR_S);\n }\n url.searchParams.delete(INTERNAL_COOKIE);\n // history.state kept: routers (Next's app router) store their own\n // state there, and replacing it with null breaks back/forward.\n history.replaceState(history.state, '', url.pathname + url.search + url.hash);\n }\n } catch {\n /* no location/history (embedded, sandboxed): the cookie read still runs */\n }\n return readCookie(INTERNAL_COOKIE);\n}\n"],"mappings":"yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,iBAAAE,EAAA,mBAAAC,EAAA,sBAAAC,IAAA,eAAAC,EAAAL,GC8EO,IAAMM,EAAkB,oBCzBxB,SAASC,EAAWC,EAA6B,CACtD,GAAI,CACF,IAAMC,EAAQ,SAAS,OAAO,MAAM,IAAI,OAAO,WAAWD,CAAI,UAAU,CAAC,EACzE,OAAOC,EAAQ,mBAAmBA,EAAM,CAAC,CAAC,EAAI,IAChD,OAAQ,GACN,OAAO,IACT,CACF,CAKA,SAASC,GAAqB,CAC5B,GAAI,CACF,OAAO,SAAS,WAAa,SAAW,WAAa,EACvD,OAAQC,EAAA,C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AAYD,EAAiBZ,CAAM,EAC3CW,IAAM,OAAS,iBAAiB,KAAKA,CAAC,IACxCG,EAAYF,EAAiBD,EAAGH,EAAYR,CAAM,EAG9Ce,EAAWH,CAAe,IAAMD,GAAGG,EAAYF,EAAiBD,EAAGH,CAAU,GAEnFE,EAAI,aAAa,OAAOE,CAAe,EAGvC,QAAQ,aAAa,QAAQ,MAAO,GAAIF,EAAI,SAAWA,EAAI,OAASA,EAAI,IAAI,EAEhF,OAAQ,GAER,CACA,OAAOK,EAAWH,CAAe,CACnC","names":["index_internal_traffic_exports","__export","emailFields","normalizeEmail","takeInternalToken","__toCommonJS","INTERNAL_COOKIE","readCookie","name","match","secureAttr","e","writeCookie","value","maxAgeSeconds","domain","clearCookie","name","domain","writeCookie","normalizeEmail","email","n","local","domain","extra","emailFields","emailDomain","digest","emailHash","b","e","ONE_YEAR_S","takeInternalToken","url","v","INTERNAL_COOKIE","clearCookie","writeCookie","readCookie"]}
@@ -0,0 +1,2 @@
1
+ import{b as a,c as l,d as s}from"./chunk-LCYGZNFI.mjs";import"./chunk-BGZLWZUG.mjs";import{f as n}from"./chunk-WUFFNQHQ.mjs";import"./chunk-TMCGHANO.mjs";function m(r){if(typeof r!="string")return null;let t=r.trim().toLowerCase(),[e,i,o]=t.split("@");return e&&i&&o===void 0?t:null}async function u(r){let t=m(r),e=t==null?void 0:t.split("@")[1];if(!e||e.length>253)return{};try{let i=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(t)),o="";for(let f of new Uint8Array(i))o+=f.toString(16).padStart(2,"0");return{emailHash:o,emailDomain:e}}catch(i){return{emailDomain:e}}}var c=365*24*60*60;function p(r){try{let t=new URL(location.href),e=t.searchParams.get(n);e!==null&&(s(n),r&&s(n,r),e!=="off"&&/^[\w-]{1,128}$/.test(e)&&(l(n,e,c,r),a(n)!==e&&l(n,e,c)),t.searchParams.delete(n),history.replaceState(history.state,"",t.pathname+t.search+t.hash))}catch(t){}return a(n)}export{u as emailFields,m as normalizeEmail,p as takeInternalToken};
2
+ //# sourceMappingURL=index-internal-traffic.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/internal.ts"],"sourcesContent":["/**\n * Internal-traffic signals the browser SDK sends (plan 2026-11-04, Interfaces):\n * the hashed identify email and the \"mark this browser internal\" link. The\n * server decides what counts as internal; this module only makes sure the\n * signals reach it — and that a raw email never does.\n */\nimport { INTERNAL_COOKIE } from './storage-key.js';\nimport { clearCookie, readCookie, writeCookie } from './session.js';\n\n/** What identify() may send about an email: never the address itself. */\nexport type EmailFields = { emailHash?: string; emailDomain?: string };\n\n/**\n * `email.trim().toLowerCase()`, or null unless it has exactly one `@` with\n * something on both sides. Must stay byte-identical to the API's and the\n * dashboard's normalization: the server matches the hash against rules hashed\n * from what the operator typed, so `Name@Example.com ` hashed un-normalized\n * would never match `name@example.com` and the teammate would keep counting.\n */\nexport function normalizeEmail(email: unknown): string | null {\n if (typeof email !== 'string') return null;\n const n = email.trim().toLowerCase();\n const [local, domain, extra] = n.split('@');\n return local && domain && extra === undefined ? n : null;\n}\n\n/**\n * `{ emailHash: sha256_hex(norm), emailDomain }` for a valid email, `{}` for\n * anything else. Without SubtleCrypto (a non-secure http: page, where\n * `crypto.subtle` is undefined) the hash cannot be computed, so only the\n * domain is sent — never a fallback that would put the raw address on the\n * wire. A domain over 253 chars is not a hostname; the API would ignore it.\n */\nexport async function emailFields(email: unknown): Promise<EmailFields> {\n const n = normalizeEmail(email);\n const emailDomain = n?.split('@')[1];\n if (!emailDomain || emailDomain.length > 253) return {};\n try {\n const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(n!));\n let emailHash = '';\n for (const b of new Uint8Array(digest)) emailHash += b.toString(16).padStart(2, '0');\n return { emailHash, emailDomain };\n } catch {\n return { emailDomain };\n }\n}\n\nconst ONE_YEAR_S = 365 * 24 * 60 * 60;\n\n/**\n * Handles `?sentient_internal=<token>` / `?sentient_internal=off` on this page\n * load, then returns the browser's current token (or null).\n *\n * The cookie goes on the same domain as the visitor cookie (`domain`, which\n * initSession detected) so a team browser marked on `example.com` is also\n * internal on `app.example.com` — a host-only cookie would mark one host and\n * let the other keep counting the same person. The param is stripped with\n * replaceState so the token is not left in the address bar to be bookmarked,\n * shared in a screenshot, or sent onward as a Referer. Only base64url tokens\n * are stored: the server's token is 32 base64url chars, and anything else in\n * a cookie is just junk riding every request.\n */\nexport function takeInternalToken(domain: string | null): string | null {\n try {\n const url = new URL(location.href);\n const v = url.searchParams.get(INTERNAL_COOKIE);\n if (v !== null) {\n // Both copies: a host-only one (written when the domain write was\n // refused) would otherwise survive the \"stop marking\" link.\n clearCookie(INTERNAL_COOKIE);\n if (domain) clearCookie(INTERNAL_COOKIE, domain);\n if (v !== 'off' && /^[\\w-]{1,128}$/.test(v)) {\n writeCookie(INTERNAL_COOKIE, v, ONE_YEAR_S, domain);\n // Same fallback as the visitor cookie: a domain the browser refused\n // must not leave the browser unmarked.\n if (readCookie(INTERNAL_COOKIE) !== v) writeCookie(INTERNAL_COOKIE, v, ONE_YEAR_S);\n }\n url.searchParams.delete(INTERNAL_COOKIE);\n // history.state kept: routers (Next's app router) store their own\n // state there, and replacing it with null breaks back/forward.\n history.replaceState(history.state, '', url.pathname + url.search + url.hash);\n }\n } catch {\n /* no location/history (embedded, sandboxed): the cookie read still runs */\n }\n return readCookie(INTERNAL_COOKIE);\n}\n"],"mappings":"0JAmBO,SAASA,EAAeC,EAA+B,CAC5D,GAAI,OAAOA,GAAU,SAAU,OAAO,KACtC,IAAMC,EAAID,EAAM,KAAK,EAAE,YAAY,EAC7B,CAACE,EAAOC,EAAQC,CAAK,EAAIH,EAAE,MAAM,GAAG,EAC1C,OAAOC,GAASC,GAAUC,IAAU,OAAYH,EAAI,IACtD,CASA,eAAsBI,EAAYL,EAAsC,CACtE,IAAMC,EAAIF,EAAeC,CAAK,EACxBM,EAAcL,GAAA,YAAAA,EAAG,MAAM,KAAK,GAClC,GAAI,CAACK,GAAeA,EAAY,OAAS,IAAK,MAAO,CAAC,EACtD,GAAI,CACF,IAAMC,EAAS,MAAM,OAAO,OAAO,OAAO,UAAW,IAAI,YAAY,EAAE,OAAON,CAAE,CAAC,EAC7EO,EAAY,GAChB,QAAWC,KAAK,IAAI,WAAWF,CAAM,EAAGC,GAAaC,EAAE,SAAS,EAAE,EAAE,SAAS,EAAG,GAAG,EACnF,MAAO,CAAE,UAAAD,EAAW,YAAAF,CAAY,CAClC,OAAQI,EAAA,CACN,MAAO,CAAE,YAAAJ,CAAY,CACvB,CACF,CAEA,IAAMK,EAAa,IAAM,GAAK,GAAK,GAe5B,SAASC,EAAkBT,EAAsC,CACtE,GAAI,CACF,IAAMU,EAAM,IAAI,IAAI,SAAS,IAAI,EAC3BC,EAAID,EAAI,aAAa,IAAIE,CAAe,EAC1CD,IAAM,OAGRE,EAAYD,CAAe,EACvBZ,GAAQa,EAAYD,EAAiBZ,CAAM,EAC3CW,IAAM,OAAS,iBAAiB,KAAKA,CAAC,IACxCG,EAAYF,EAAiBD,EAAGH,EAAYR,CAAM,EAG9Ce,EAAWH,CAAe,IAAMD,GAAGG,EAAYF,EAAiBD,EAAGH,CAAU,GAEnFE,EAAI,aAAa,OAAOE,CAAe,EAGvC,QAAQ,aAAa,QAAQ,MAAO,GAAIF,EAAI,SAAWA,EAAI,OAASA,EAAI,IAAI,EAEhF,OAAQH,EAAA,CAER,CACA,OAAOQ,EAAWH,CAAe,CACnC","names":["normalizeEmail","email","n","local","domain","extra","emailFields","emailDomain","digest","emailHash","b","e","ONE_YEAR_S","takeInternalToken","url","v","INTERNAL_COOKIE","clearCookie","writeCookie","readCookie"]}
@@ -1,4 +1,4 @@
1
- import { f as DecideOutcome } from './index-DlJDNOWu.cjs';
1
+ import { f as DecideOutcome } from './index-Bz4QCRmF.cjs';
2
2
  import { f as SlotDeclInput } from './session-meta-BqBaLZag.cjs';
3
3
  import './style-vocabulary-Ba_g6_DD.cjs';
4
4
  import './region-skeleton-BRIVB-qf.cjs';
@@ -1,4 +1,4 @@
1
- import { f as DecideOutcome } from './index-C--aVpoo.js';
1
+ import { f as DecideOutcome } from './index-C36TXfry.js';
2
2
  import { f as SlotDeclInput } from './session-meta-D_kdNsaU.js';
3
3
  import './style-vocabulary-Ba_g6_DD.js';
4
4
  import './region-skeleton-BRIVB-qf.js';
@@ -1,2 +1,2 @@
1
- import{a as R,b as M,c as V}from"./chunk-EVF5PQ4U.mjs";import{a as E,b as y}from"./chunk-G6VP7HGJ.mjs";import{a as p,b}from"./chunk-TMCGHANO.mjs";function k(e){return e.replace(/\s+/g," ").trim().slice(0,300)}function D(e,o){let n=o>>>0;for(let t=0;t<e.length;t++)n^=e.charCodeAt(t),n=Math.imul(n,16777619)>>>0;return n.toString(16).padStart(8,"0")}function S(e){let o=e.join("");return D(o,2166136261)+D(o,1523705862)}var $=new Set(["A","BUTTON"]),O=/^H([1-6])$/,F=new Set(["P","LI","LABEL","BLOCKQUOTE","FIGCAPTION","DT","DD","TD","TH"]),H=new Set(["LABEL","FIGCAPTION","DT"]),U=new Set(["SCRIPT","STYLE","TEMPLATE","NOSCRIPT"]);function C(e){return $.has(e.tagName)||e.getAttribute("role")==="button"?!0:e.tagName==="INPUT"&&/^(submit|button)$/i.test(e.type)}function X(e){if(O.test(e.tagName)||F.has(e.tagName))return!0;let o=e.ownerDocument.defaultView,n=o?o.getComputedStyle(e).display:"";return n!==""&&n!=="inline"&&n!=="contents"}function j(e,o){let n=null;for(let t=e.parentElement;t&&t!==o.parentElement;t=t.parentElement){if(C(t)){n=t;break}if(t===o)break}if(n)return n;for(let t=e.parentElement;t;t=t.parentElement)if(t===o||X(t))return t;return o}function _(e,o){var n,t;if(e)try{let r=new URL(e,(t=(n=o.location)==null?void 0:n.href)!=null?t:"https://relative.invalid/");return r.protocol!=="https:"&&r.protocol!=="http:"?void 0:o.location&&r.origin===o.location.origin?r.pathname:`${r.origin}${r.pathname}`}catch(r){return}}function I(e){return e===""||e==="transparent"||/rgba\([^)]*,\s*0\)$/.test(e)}function z(e){let o=e.ownerDocument,n=o.defaultView;if(!n)return{bg:null};for(let t=e;t;t=t.parentElement){let r=n.getComputedStyle(t),l=y(r.backgroundImage,o);if(l.length>0)return p({bg:l[0]},l.length>1?{alt:l[l.length-1]}:{});let s=E(r.backgroundColor,o);if(!I(s))return{bg:s}}return{bg:null}}function B(e,o=40){var f,i,d;let n=e.ownerDocument.createTreeWalker(e,4),t=[];for(let a=n.nextNode();a;a=n.nextNode())if(((f=a.nodeValue)!=null?f:"").trim()!==""&&!U.has((d=(i=a.parentElement)==null?void 0:i.tagName)!=null?d:"")&&(t.push(a),t.length>120))return{reason:"too_large"};if(t.length===0)return{reason:"empty"};let r=[],l=[];for(let a of t){let u=j(a,e),g=r.indexOf(u);g===-1&&(r.push(u),g=r.length-1),l.push(g)}if(r.length>o)return{reason:"too_large"};let s=t.map(a=>{var u;return k((u=a.nodeValue)!=null?u:"")});return{textNodes:t,ownerEls:r,leafToNode:l,leaves:s,fp:S(s)}}function P(e,o=40){var h;let n=B(e,o);if(!("fp"in n))return{skeleton:null,reason:n.reason};let{textNodes:t,ownerEls:r,leafToNode:l,leaves:s}=n,f=e.ownerDocument,i=f.defaultView,d=[],a=r.map((c,v)=>{var w,L;let m=i==null?void 0:i.getComputedStyle(c),x=(w=c.parentElement)!=null?w:e,T=d.indexOf(x);T===-1&&(d.push(x),T=d.length-1);let N=O.exec(c.tagName),A=C(c)?"action":N?"heading":H.has(c.tagName)?"label":"text",G=k(s.filter((Y,K)=>l[K]===v).join(" "));return b(p(b(p({tag:c.tagName.toLowerCase(),role:A},N?{level:Number(N[1])}:{}),{text:G,classes:((L=c.getAttribute("class"))!=null?L:"").replace(/\s+/g," ").trim()}),A==="action"?p({filled:!!m&&(!I(E(m.backgroundColor,e.ownerDocument))||m.backgroundImage!==""&&m.backgroundImage!=="none")},_(c.getAttribute("href"),f)!==void 0?{href:_(c.getAttribute("href"),f)}:{}):{}),{color:E(m==null?void 0:m.color,e.ownerDocument),group:T,restylable:!0})}),u=z(e),g=i==null?void 0:i.getComputedStyle(e);return{skeleton:{v:1,root:b(p({tag:e.tagName.toLowerCase(),classes:((h=e.getAttribute("class"))!=null?h:"").replace(/\s+/g," ").trim(),ambientBg:u.bg},u.alt?{ambientBgAlt:u.alt}:{}),{ambientText:E(g==null?void 0:g.color,e.ownerDocument)}),nodes:a,leaves:s,leafToNode:l,fp:S(s)},textNodes:t,ownerEls:r}}function Q(e,o){try{let n=P(e,o==null?void 0:o.maxNodes);return n.skeleton?{skeleton:n.skeleton}:n}catch(n){return{skeleton:null,reason:"unaddressable"}}}export{P as captureRegionDom,Q as captureRegionSkeleton,k as normalizeLeafText,B as regionAddress,S as skeletonFingerprint};
1
+ import{a as E,b as y}from"./chunk-G6VP7HGJ.mjs";import{a as R,b as M,c as V}from"./chunk-EVF5PQ4U.mjs";import{a as p,b}from"./chunk-TMCGHANO.mjs";function k(e){return e.replace(/\s+/g," ").trim().slice(0,300)}function D(e,o){let n=o>>>0;for(let t=0;t<e.length;t++)n^=e.charCodeAt(t),n=Math.imul(n,16777619)>>>0;return n.toString(16).padStart(8,"0")}function S(e){let o=e.join("");return D(o,2166136261)+D(o,1523705862)}var $=new Set(["A","BUTTON"]),O=/^H([1-6])$/,F=new Set(["P","LI","LABEL","BLOCKQUOTE","FIGCAPTION","DT","DD","TD","TH"]),H=new Set(["LABEL","FIGCAPTION","DT"]),U=new Set(["SCRIPT","STYLE","TEMPLATE","NOSCRIPT"]);function C(e){return $.has(e.tagName)||e.getAttribute("role")==="button"?!0:e.tagName==="INPUT"&&/^(submit|button)$/i.test(e.type)}function X(e){if(O.test(e.tagName)||F.has(e.tagName))return!0;let o=e.ownerDocument.defaultView,n=o?o.getComputedStyle(e).display:"";return n!==""&&n!=="inline"&&n!=="contents"}function j(e,o){let n=null;for(let t=e.parentElement;t&&t!==o.parentElement;t=t.parentElement){if(C(t)){n=t;break}if(t===o)break}if(n)return n;for(let t=e.parentElement;t;t=t.parentElement)if(t===o||X(t))return t;return o}function _(e,o){var n,t;if(e)try{let r=new URL(e,(t=(n=o.location)==null?void 0:n.href)!=null?t:"https://relative.invalid/");return r.protocol!=="https:"&&r.protocol!=="http:"?void 0:o.location&&r.origin===o.location.origin?r.pathname:`${r.origin}${r.pathname}`}catch(r){return}}function I(e){return e===""||e==="transparent"||/rgba\([^)]*,\s*0\)$/.test(e)}function z(e){let o=e.ownerDocument,n=o.defaultView;if(!n)return{bg:null};for(let t=e;t;t=t.parentElement){let r=n.getComputedStyle(t),l=y(r.backgroundImage,o);if(l.length>0)return p({bg:l[0]},l.length>1?{alt:l[l.length-1]}:{});let s=E(r.backgroundColor,o);if(!I(s))return{bg:s}}return{bg:null}}function B(e,o=40){var f,i,d;let n=e.ownerDocument.createTreeWalker(e,4),t=[];for(let a=n.nextNode();a;a=n.nextNode())if(((f=a.nodeValue)!=null?f:"").trim()!==""&&!U.has((d=(i=a.parentElement)==null?void 0:i.tagName)!=null?d:"")&&(t.push(a),t.length>120))return{reason:"too_large"};if(t.length===0)return{reason:"empty"};let r=[],l=[];for(let a of t){let u=j(a,e),g=r.indexOf(u);g===-1&&(r.push(u),g=r.length-1),l.push(g)}if(r.length>o)return{reason:"too_large"};let s=t.map(a=>{var u;return k((u=a.nodeValue)!=null?u:"")});return{textNodes:t,ownerEls:r,leafToNode:l,leaves:s,fp:S(s)}}function P(e,o=40){var h;let n=B(e,o);if(!("fp"in n))return{skeleton:null,reason:n.reason};let{textNodes:t,ownerEls:r,leafToNode:l,leaves:s}=n,f=e.ownerDocument,i=f.defaultView,d=[],a=r.map((c,v)=>{var w,L;let m=i==null?void 0:i.getComputedStyle(c),x=(w=c.parentElement)!=null?w:e,T=d.indexOf(x);T===-1&&(d.push(x),T=d.length-1);let N=O.exec(c.tagName),A=C(c)?"action":N?"heading":H.has(c.tagName)?"label":"text",G=k(s.filter((Y,K)=>l[K]===v).join(" "));return b(p(b(p({tag:c.tagName.toLowerCase(),role:A},N?{level:Number(N[1])}:{}),{text:G,classes:((L=c.getAttribute("class"))!=null?L:"").replace(/\s+/g," ").trim()}),A==="action"?p({filled:!!m&&(!I(E(m.backgroundColor,e.ownerDocument))||m.backgroundImage!==""&&m.backgroundImage!=="none")},_(c.getAttribute("href"),f)!==void 0?{href:_(c.getAttribute("href"),f)}:{}):{}),{color:E(m==null?void 0:m.color,e.ownerDocument),group:T,restylable:!0})}),u=z(e),g=i==null?void 0:i.getComputedStyle(e);return{skeleton:{v:1,root:b(p({tag:e.tagName.toLowerCase(),classes:((h=e.getAttribute("class"))!=null?h:"").replace(/\s+/g," ").trim(),ambientBg:u.bg},u.alt?{ambientBgAlt:u.alt}:{}),{ambientText:E(g==null?void 0:g.color,e.ownerDocument)}),nodes:a,leaves:s,leafToNode:l,fp:S(s)},textNodes:t,ownerEls:r}}function Q(e,o){try{let n=P(e,o==null?void 0:o.maxNodes);return n.skeleton?{skeleton:n.skeleton}:n}catch(n){return{skeleton:null,reason:"unaddressable"}}}export{P as captureRegionDom,Q as captureRegionSkeleton,k as normalizeLeafText,B as regionAddress,S as skeletonFingerprint};
2
2
  //# sourceMappingURL=index-region.mjs.map
@@ -63,6 +63,20 @@ type ServerAssignConfig = {
63
63
  * server-side. Never a user id or email.
64
64
  */
65
65
  persona?: string;
66
+ /**
67
+ * Your team / a test site (the code flag, same contract as the client's
68
+ * `init({ internal })`): the visit is served normally but left out of
69
+ * reports and learning. Sent only when `true` — the flag is sticky
70
+ * server-side, so `false` never un-marks a visit.
71
+ */
72
+ internal?: boolean;
73
+ /**
74
+ * The request's `sentient_internal` cookie (`readInternalToken(cookies)`),
75
+ * set in a team browser by the project's "mark this browser" link. Without
76
+ * it the SSR upsert/decide of a marked browser's first page trains on it
77
+ * before the browser's own upsert can say otherwise.
78
+ */
79
+ internalToken?: string;
66
80
  /**
67
81
  * Milliseconds to wait for the API before returning default variants.
68
82
  * Prevents slow/cold API from blocking SSR. Defaults to 1000 — the hot path
@@ -135,6 +149,16 @@ declare function readSessionCookie(cookies: {
135
149
  value: string;
136
150
  } | undefined;
137
151
  }, apiKey?: string): string | null;
152
+ /**
153
+ * The request's "mark this browser internal" token (the `sentient_internal`
154
+ * cookie the browser SDK writes from the project's link), or undefined. Pass
155
+ * it as `internalToken` so the server-rendered upsert/decide is marked too.
156
+ */
157
+ declare function readInternalToken(cookies: {
158
+ get(name: string): {
159
+ value: string;
160
+ } | undefined;
161
+ }): string | undefined;
138
162
  type DecideResult = {
139
163
  layoutOrder: string[];
140
164
  assignments: Record<string, string>;
@@ -322,4 +346,4 @@ type ConnectRequest = {
322
346
  */
323
347
  declare function sentientAgentMiddleware(opts: Omit<AgentCaptureOptions, 'waitUntil' | 'source'>): (req: ConnectRequest, res: unknown, next: (err?: unknown) => void) => void;
324
348
 
325
- export { type AgentCaptureOptions, type CapturableRequest, type DecideResult, SERVER_GOAL_NAMESPACE, type ServerAssignConfig, type ServerAssignments, type ServerAssignmentsDetailed, SlotDeclInput, type TrackServerGoalOptions, captureAgentRequest, postAgentFetch, preloadAssignments, preloadAssignmentsDetailed, preloadDecisions, readSessionCookie, sentientAgentMiddleware, signUserId, trackServerGoal };
349
+ export { type AgentCaptureOptions, type CapturableRequest, type DecideResult, SERVER_GOAL_NAMESPACE, type ServerAssignConfig, type ServerAssignments, type ServerAssignmentsDetailed, SlotDeclInput, type TrackServerGoalOptions, captureAgentRequest, postAgentFetch, preloadAssignments, preloadAssignmentsDetailed, preloadDecisions, readInternalToken, readSessionCookie, sentientAgentMiddleware, signUserId, trackServerGoal };