@sentientui/core 0.41.2 → 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.
- package/README.md +31 -2
- package/dist/chunk-BGZLWZUG.mjs +2 -0
- package/dist/chunk-BGZLWZUG.mjs.map +1 -0
- package/dist/chunk-JNQY3XNF.mjs +2 -0
- package/dist/chunk-JNQY3XNF.mjs.map +1 -0
- package/dist/chunk-LCYGZNFI.mjs +2 -0
- package/dist/chunk-LCYGZNFI.mjs.map +1 -0
- package/dist/chunk-QPJ6TL6L.mjs +2 -0
- package/dist/chunk-QPJ6TL6L.mjs.map +1 -0
- package/dist/chunk-WUFFNQHQ.mjs +2 -0
- package/dist/{chunk-J5EL7HKC.mjs.map → chunk-WUFFNQHQ.mjs.map} +1 -1
- package/dist/{index-DlJDNOWu.d.cts → index-Bz4QCRmF.d.cts} +26 -5
- package/dist/{index-C--aVpoo.d.ts → index-C36TXfry.d.ts} +26 -5
- package/dist/index-consent.js +1 -1
- package/dist/index-consent.js.map +1 -1
- package/dist/index-consent.mjs +1 -1
- package/dist/index-consent.mjs.map +1 -1
- package/dist/index-engagement.js +1 -1
- package/dist/index-engagement.js.map +1 -1
- package/dist/index-engagement.mjs +1 -1
- package/dist/index-engagement.mjs.map +1 -1
- package/dist/index-graph.d.cts +2 -2
- package/dist/index-graph.d.ts +2 -2
- package/dist/index-graph.js +1 -1
- package/dist/index-graph.js.map +1 -1
- package/dist/index-graph.mjs +1 -1
- package/dist/index-graph.mjs.map +1 -1
- package/dist/index-internal-traffic.d.cts +37 -0
- package/dist/index-internal-traffic.d.ts +37 -0
- package/dist/index-internal-traffic.js +2 -0
- package/dist/index-internal-traffic.js.map +1 -0
- package/dist/index-internal-traffic.mjs +2 -0
- package/dist/index-internal-traffic.mjs.map +1 -0
- package/dist/index-local.d.cts +1 -1
- package/dist/index-local.d.ts +1 -1
- package/dist/index-region.mjs +1 -1
- package/dist/index-server.d.cts +25 -1
- package/dist/index-server.d.ts +25 -1
- package/dist/index-server.js +1 -1
- package/dist/index-server.js.map +1 -1
- package/dist/index-server.mjs +1 -1
- package/dist/index-server.mjs.map +1 -1
- package/dist/index.d.cts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1 -1
- package/llms.txt +2 -1
- package/package.json +6 -1
- package/dist/chunk-FPOHOWJP.mjs +0 -2
- package/dist/chunk-FPOHOWJP.mjs.map +0 -1
- package/dist/chunk-J5EL7HKC.mjs +0 -2
- package/dist/chunk-KXA3X6T3.mjs +0 -2
- package/dist/chunk-KXA3X6T3.mjs.map +0 -1
package/README.md
CHANGED
|
@@ -53,6 +53,7 @@ Reading a consent platform yourself: `import { consentWatcher } from '@sentientu
|
|
|
53
53
|
| `userId` | `string` | Optional cross-session identity. Persists portraits across sessions for the same user. |
|
|
54
54
|
| `persona` | `string` | Declared persona — the role your app already knows for this visitor (e.g. `'admin'`, `'evaluator'`). Must be a key in the project's persona vocabulary (dashboard → Matrix → Audiences); unrecognized values are ignored server-side and surfaced in the dashboard so you can add them. Served at full confidence, overriding the inferred persona. Keep it a low-cardinality role label — never a user id or email. |
|
|
55
55
|
| `country` | `string` | ISO 3166-1 alpha-2 country code, if you already know it server-side. |
|
|
56
|
+
| `internal` | `boolean \| () => boolean` | Your own team or a test site: served normally, left out of reports and learning. A function is called once, at init. See [Excluding your team and test sites](#excluding-your-team-and-test-sites). |
|
|
56
57
|
| `debug` | `boolean` | Logs events to the console and exposes `window.__sentient`. |
|
|
57
58
|
| `localMode` | `'auto' \| boolean` | Keyless local engine. `'auto'` (default) enables it only under the `development` export condition; production builds without a key short-circuit to defaults with one `console.error`. |
|
|
58
59
|
| `initialSlots` | `Record<string, string \| Record<string, string>>` | SSR-preloaded slot results (from `preloadDecisions`/`loadAdaptiveDecision`). |
|
|
@@ -110,9 +111,9 @@ No-ops (with a `debug` warning) if the component has not been assigned yet — r
|
|
|
110
111
|
|
|
111
112
|
The visitor id to carry to your server for a later conversion (see "Record a conversion from your server"). `null` before the visitor has agreed to tracking, and after forget-me.
|
|
112
113
|
|
|
113
|
-
### `client.identify(userId)`
|
|
114
|
+
### `client.identify(userId, { userHash?, email? })`
|
|
114
115
|
|
|
115
|
-
Attaches a stable user ID to the session. On the link, the server copies the highest-reliability portrait from the user's other sessions onto this one, so portraits and cluster assignment carry forward across devices for the same `userId`.
|
|
116
|
+
Attaches a stable user ID to the session. On the link, the server copies the highest-reliability portrait from the user's other sessions onto this one, so portraits and cluster assignment carry forward across devices for the same `userId`. `userHash` (`signUserId(userId, secretKey)` from your server) makes the link verified. `email` is only for your project's team-email rules: it is hashed on the device and never sent as written (see below).
|
|
116
117
|
|
|
117
118
|
### `client.getAssignment(componentId, segment)`
|
|
118
119
|
|
|
@@ -156,6 +157,34 @@ Everything else the root entry exports (block vocabularies, snapshot I/O, agent-
|
|
|
156
157
|
`@sentientui/snippet`. It carries no semver promise and leaves the root entry at 1.0.
|
|
157
158
|
`src/public-surface.test.ts` classifies every export, so the list can't grow silently.
|
|
158
159
|
|
|
160
|
+
## Excluding your team and test sites
|
|
161
|
+
|
|
162
|
+
Visits from your own team, staging and local development can be left out of every number and out of learning. They are still served versions as usual, so you can keep testing on any site. There are three ways to mark a visit as internal from the SDK. You can also list internal sites and team emails in the dashboard (Settings).
|
|
163
|
+
|
|
164
|
+
**1. A flag in your code.** You already know who is signed in:
|
|
165
|
+
|
|
166
|
+
```ts
|
|
167
|
+
init({ apiKey: 'pk_…', internal: user.email.endsWith('@example.com') });
|
|
168
|
+
// or a function, called once at init:
|
|
169
|
+
init({ apiKey: 'pk_…', internal: () => location.hostname !== 'www.example.com' });
|
|
170
|
+
```
|
|
171
|
+
|
|
172
|
+
The check runs in your code, so the email never leaves your site. Only `internal: true` is sent. Once a visit is marked it stays marked: `false` later on does not unmark it.
|
|
173
|
+
|
|
174
|
+
**2. `identify(userId, { email })`.** For the team-email rules you set in the dashboard (`name@example.com` or `@example.com`):
|
|
175
|
+
|
|
176
|
+
```ts
|
|
177
|
+
client.identify(user.id, { email: user.email });
|
|
178
|
+
```
|
|
179
|
+
|
|
180
|
+
The SDK trims and lowercases the email, then sends its SHA-256 hash (`emailHash`) and its domain (`emailDomain`, for example `example.com`). The address itself is never sent, logged or stored. On a page served over plain `http:` the browser has no hashing API, so only the domain is sent there.
|
|
181
|
+
|
|
182
|
+
**3. A browser link.** Settings gives your project a link like `https://your-site.com/?sentient_internal=<token>`. Opening it once in a browser stores a first-party `sentient_internal` cookie (one year, on the same domain as the visitor cookie) and removes the parameter from the address bar. From then on every visit from that browser is marked. `?sentient_internal=off` removes the cookie. Rotating the link in Settings unmarks every browser at once. For server-rendered pages, pass `readInternalToken(cookies)` from `@sentientui/core/server` as `internalToken` (and your flag as `internal`) in the `ServerAssignConfig`, so the first server-rendered request is marked too.
|
|
183
|
+
|
|
184
|
+
A visit marked internal before it is scored never trains your versions. One marked later (a late `identify`, a rule added afterwards) drops out of reports on the next read, but anything it already taught a version stays.
|
|
185
|
+
|
|
186
|
+
These fields need a SentientUI API that knows internal traffic. Older APIs ignore them, so sending them early is harmless. Visitors who have not consented are not tracked, so nothing is sent or stored for them.
|
|
187
|
+
|
|
159
188
|
## Record a conversion from your server
|
|
160
189
|
|
|
161
190
|
Some conversions happen where the browser can't see them: a payment confirmed by a webhook, an order saved by a server action. `trackServerGoal` records one with your secret key (`sk_…`, server-only).
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/cookie-domain.ts"],"sourcesContent":["/**\n * Candidate domains for the shared visitor cookie. The visitor id lives on the\n * site's registrable domain (`example.com` for `app.example.com`), so a marketing\n * site and its app subdomain see ONE visitor: host-only cookies gave each host\n * its own id, and a journey that started on the landing page and converted in\n * the app (or the app's backend) could never be joined to the decisions that\n * earned it.\n *\n * Detection (session.ts `detectCookieDomain`) works the way analytics.js and\n * GA's `cookieDomain: 'auto'` do: try the shortest parent first and keep the\n * first one the browser accepts. The browser refuses public suffixes\n * (`co.uk`, `vercel.app`, `herokuapp.com`), so no suffix list ships in the\n * bundle — those fall through to the next candidate, and a host with no\n * acceptable parent stays host-only.\n */\n\n/** `false` = host-only (the pre-sharing behaviour); a string = that domain. */\nexport type CookieDomainOption = string | false | undefined;\n\n/**\n * Domains to try for `hostname`, shortest first, ENDING WITH THE HOST ITSELF.\n * The host is a candidate because the site's own bare domain is the common\n * case: a landing page on `example.com` must write `Domain=example.com` to share\n * with `app.example.com` — without it the bare domain stayed host-only while\n * its subdomains shared, so the landing-to-app journey was still two\n * visitors, and forget-me there left the shared copy behind.\n */\nexport function parentDomains(hostname: string | undefined): string[] {\n // `|| ''`: a stubbed or embedded `location` without a hostname must cost\n // the visitor cookie sharing, never crash init().\n const host = (hostname || '').toLowerCase();\n // localhost, a bare intranet name, an IP literal: nothing to share across.\n if (!host.includes('.') || /^[\\d.]+$|:/.test(host)) return [];\n const labels = host.split('.');\n const out: string[] = [];\n for (let i = labels.length - 2; i >= 0; i--) out.push(labels.slice(i).join('.'));\n return out;\n}\n"],"mappings":"AA2BO,SAASA,EAAcC,EAAwC,CAGpE,IAAMC,GAAQD,GAAY,IAAI,YAAY,EAE1C,GAAI,CAACC,EAAK,SAAS,GAAG,GAAK,aAAa,KAAKA,CAAI,EAAG,MAAO,CAAC,EAC5D,IAAMC,EAASD,EAAK,MAAM,GAAG,EACvBE,EAAgB,CAAC,EACvB,QAASC,EAAIF,EAAO,OAAS,EAAGE,GAAK,EAAGA,IAAKD,EAAI,KAAKD,EAAO,MAAME,CAAC,EAAE,KAAK,GAAG,CAAC,EAC/E,OAAOD,CACT","names":["parentDomains","hostname","host","labels","out","i"]}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{a as oe}from"./chunk-BGZLWZUG.mjs";import{a as te,b as U,c as ne,d as re,e as O}from"./chunk-WUFFNQHQ.mjs";var Q="_snt_snap:";var ie=["low","medium","high"];function ue(t){try{let o=localStorage.getItem(Q+t);if(!o)return null;let e=JSON.parse(o);if(!e||typeof e!="object"||e.v!==1||typeof e.persona!="string"||typeof e.band!="string"||!ie.includes(e.band)||typeof e.slots!="object"||e.slots===null||Array.isArray(e.slots)||!(e.layoutOrder===null||Array.isArray(e.layoutOrder))||typeof e.savedAt!="number"||!(Date.now()-e.savedAt<2592e6)||!(e.slotConfig===void 0||typeof e.slotConfig=="object"&&e.slotConfig!==null&&!Array.isArray(e.slotConfig)))return null;let i=e.vocabulary;return i!==void 0&&(typeof i!="object"||i===null||!Array.isArray(i.entries)||!Array.isArray(i.images))&&delete e.vocabulary,e.stage!==void 0&&typeof e.stage!="string"&&delete e.stage,e}catch(o){return null}}function fe(t,o){try{localStorage.setItem(Q+t,JSON.stringify(o))}catch(e){}}function pe(t,o){return'(function(){try{var N=navigator,W=window;if(N.doNotTrack=="1"||N.doNotTrack=="yes"||W.doNotTrack=="1"||N.msDoNotTrack=="1"||N.globalPrivacyControl)return;var r=localStorage.getItem('+JSON.stringify(Q+t).replace(/</g,"\\u003c")+');if(!r)return;var s=JSON.parse(r);if(!s||s.v!==1||typeof s.persona!=="string"||typeof s.band!=="string")return;if(!('+2592e6+">Date.now()-s.savedAt))return;var d=document.documentElement;"+(o!=null&&o.stage?'if(typeof s.stage=="string"&&!d.hasAttribute("data-sentient-stage"))d.setAttribute("data-sentient-stage",s.stage);':"")+'if(d.hasAttribute("data-sentient-persona"))return;d.setAttribute("data-sentient-persona",s.persona);d.setAttribute("data-sentient-confidence",s.band);}catch(e){}})();'}function J(t){if(typeof AbortController!="function")return{clear:()=>{}};let o=new AbortController,e=setTimeout(()=>o.abort(),t);return{signal:o.signal,clear:()=>clearTimeout(e)}}function me(t,o){return new Promise(e=>{let i=setTimeout(()=>e(!1),o),d=()=>{clearTimeout(i),e(!0)};t.then(d,d)})}function P(t){return Math.min(6e4,1e3*2**Math.min(t,6))}function K(t){if(t.ok===!0)return"delivered";let{status:o}=t;return typeof o!="number"?"retry":o>=200&&o<300?"delivered":o>=400&&o<500&&o!==429?"dropped":"retry"}function X(t,o){try{let e=localStorage.getItem(t);if(!e)return[];let i=JSON.parse(e);return Array.isArray(i)?(localStorage.removeItem(t),i.slice(-o)):[]}catch(e){return[]}}function F(t,o,e){try{let i=(()=>{try{let s=localStorage.getItem(e);if(!s)return[];let l=JSON.parse(s);return Array.isArray(l)?l:[]}catch(s){return[]}})(),d=new Map;for(let s of i)d.set(s.id,s);for(let s of t)d.set(s.id,s);localStorage.setItem(e,JSON.stringify([...d.values()].slice(-o)))}catch(i){}}function Y(t,o){try{let e=localStorage.getItem(o);if(!e)return;let i=JSON.parse(e);if(!Array.isArray(i))return;let d=new Set(t),s=i.filter(l=>!d.has(l.id));if(s.length===i.length)return;s.length===0?localStorage.removeItem(o):localStorage.setItem(o,JSON.stringify(s))}catch(e){}}var se=500,ae=56*1024;function W(t){return`_snt_retry_${t.slice(0,12)}`}var de={push:()=>{},flush:()=>{},destroy:()=>{}};function _e(t){var T,C,D;if(typeof window=="undefined")return de;let o=(T=t.flushIntervalMs)!=null?T:5e3,e=(C=t.maxBatchSize)!=null?C:20,i=(D=t.maxRetrySize)!=null?D:100,d=t.ingestUrl,s=t.apiKey,l=W(s),f=!1,g=O(s),p=(...n)=>{!f&&O(s)===g&&F(...n)},c=[],m=new Set,y=[],w=n=>{for(let a of n)v.delete(a),!m.has(a)&&(m.add(a),y.push(a));for(;y.length>se;){let a=y.shift();a&&m.delete(a)}Y(n,l)},v=new Set,L=()=>{for(;c.length>i;){let n=c.shift();n&&v.delete(n.id)}},k=n=>{m.has(n.id)||v.has(n.id)||(v.add(n.id),c.push(n),L())},A=n=>{for(let a of n)m.has(a.id)||(v.add(a.id),c.push(a));L()},b=X(l,i);for(let n of b)k(n);let h=0,S=0,R=(n,a=!0)=>{if(n.length===0)return;let I=JSON.stringify(n),z=n.map(B=>B.id),_,H=J(15e3);try{_=fetch(d,{method:"POST",keepalive:!0,signal:H.signal,body:I,headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`}})}catch(B){p(n,i,l),A(n),S++,h=Date.now()+P(S);return}Promise.resolve(_).then(H.clear,H.clear);let ee=B=>{if(K(B)!=="retry"){if(!B.ok&&a){let q=n.filter(G=>G.eventType!=="pageview");if(q.length>0&&q.length<n.length){w(n.filter(G=>G.eventType==="pageview").map(G=>G.id)),R(q,!1);return}}w(z),S=0,h=0;return}p(n,i,l),A(n),S++,h=Date.now()+P(S)};_&&typeof _.then=="function"?_.then(ee).catch(()=>{p(n,i,l),A(n),S++,h=Date.now()+P(S)}):ee(_)},N=typeof TextEncoder!="undefined"?new TextEncoder:null,$=n=>N?N.encode(n).length:n.length,j=n=>{let a=[],I=2;for(let z of n){let _=$(JSON.stringify(z))+1;if(a.length>0&&I+_>ae||a.length>=e)break;a.push(z),I+=_}return a},E=()=>{try{if(Date.now()<h)return;for(;c.length>0&&!(Date.now()<h);){let n=c.filter(I=>!m.has(I.id));if(c.length=0,n.length===0)break;let a=j(n);if(a.length===0)break;a.length<n.length&&c.push(...n.slice(a.length)),R(a)}}catch(n){}},r=!0,u=null;u=setInterval(()=>{r&&E()},o);let x=()=>{document.visibilityState==="hidden"&&E()},M=()=>{E()};return document.addEventListener("visibilitychange",x),window.addEventListener("pagehide",M),{push(n){k(n),c.length>=e&&E()},flush:E,destroy(n){n!=null&&n.forget&&(f=!0),r=!1,u!==null&&(clearInterval(u),u=null),document.removeEventListener("visibilitychange",x),window.removeEventListener("pagehide",M),E()}}}var le=200;function Z(t){return`_snt_goal_retry_${t.slice(0,12)}`}var ce={send:()=>{},flush:()=>{},destroy:()=>{}};function xe(t){var $,j,E;if(typeof window=="undefined")return ce;let o=($=t.flushIntervalMs)!=null?$:5e3,e=(j=t.maxRetrySize)!=null?j:100,i=(E=t.maxPerFlush)!=null?E:5,d=Z(t.apiKey),s=!1,l=O(t.apiKey),f=(...r)=>{!s&&O(t.apiKey)===l&&F(...r)},g=[],p=new Set,c=new Set,m=[],y=0,w=0,v=!1,L=r=>{for(p.delete(r.id),c.has(r.id)||(c.add(r.id),m.push(r.id));m.length>le;){let u=m.shift();u&&c.delete(u)}Y([r.id],d)},k=r=>{f([r],e,d),!c.has(r.id)&&!p.has(r.id)&&(p.add(r.id),g.push(r)),Date.now()>=y&&(w++,y=Date.now()+P(w))},A=r=>{let u,x=J(15e3);try{u=fetch(t.url,{method:"POST",keepalive:!0,signal:x.signal,body:r.body,headers:t.headers})}catch(T){k(r);return}let M=T=>{var D;let C=K(T);if(C==="retry"){k(r);return}C==="dropped"&&((D=t.onDrop)==null||D.call(t,r,T.status)),L(r),w=0,y=0};Promise.resolve(u).then(x.clear,x.clear),u&&typeof u.then=="function"?u.then(M).catch(()=>k(r)):M(u)},b=()=>{try{if(v||Date.now()<y)return;let r=0;for(;g.length>0&&r<i&&!(Date.now()<y);){let u=g.shift();p.delete(u.id),!c.has(u.id)&&(r++,A(u))}}catch(r){}},h=X(d,e);for(let r of h)p.has(r.id)||(p.add(r.id),g.push(r));h.length>0&&F(h,e,d);let S=setInterval(b,o),R=()=>{document.visibilityState==="hidden"&&b()},N=()=>b();return document.addEventListener("visibilitychange",R),window.addEventListener("pagehide",N),{send(r){if(v){c.has(r.id)||f([r],e,d);return}if(!(c.has(r.id)||p.has(r.id))){if(Date.now()<y){f([r],e,d),p.add(r.id),g.push(r);return}A(r)}},flush:b,destroy(r){r!=null&&r.forget&&(s=!0),clearInterval(S),document.removeEventListener("visibilitychange",R),window.removeEventListener("pagehide",N),b(),v=!0}}}function Me(t){if(typeof window=="undefined"||!t)return!1;re(t);let o=!1,e=ne(t);try{if(new RegExp(`(?:^|; )${e}=`).test(document.cookie)){let l=location.protocol==="https:"?"; Secure":"";for(let f of["",...oe(location.hostname)])document.cookie=`${e}=; max-age=0; SameSite=lax; path=/${f?`; domain=${f}`:""}${l}`;o=!0}}catch(l){}let i=te(t),d=[e,"_snt_graph_edges",Q+t,W(t),Z(t),`_snt_graph_nodes${i}`],s=[`_snt_asgn${i}_`];for(let l of["localStorage","sessionStorage"])try{let f=window[l];for(let g of d)f.getItem(g)!==null&&(f.removeItem(g),o=!0);for(let g=f.length-1;g>=0;g--){let p=f.key(g);p&&s.some(c=>p.startsWith(c))&&(f.removeItem(p),o=!0)}}catch(f){}try{(new RegExp(`(?:^|; )${U}=[^;]`).test(document.cookie)||localStorage.getItem(U)!==null||sessionStorage.getItem(U)!==null)&&localStorage.setItem(`${U}_tomb${i}`,"1")}catch(l){}return o}export{Q as a,ue as b,fe as c,pe as d,J as e,me as f,P as g,K as h,W as i,_e as j,Z as k,xe as l,Me as m};
|
|
2
|
+
//# sourceMappingURL=chunk-JNQY3XNF.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/snapshot.ts","../src/timeout.ts","../src/durable.ts","../src/queue.ts","../src/goal-queue.ts","../src/forget.ts"],"sourcesContent":["/**\n * Decision snapshot: the SPA / return-visit pre-paint source. Written after\n * every successful decide; read by the inline pre-paint script (before any\n * framework code runs) and by init() to seed slot/persona state.\n */\nimport type { ServedEdits } from './region-skeleton.js';\nimport type { SlotResult } from './slots.js';\nimport type { BlockNode, SitePalette } from './blocks.js';\n\nexport const SNAPSHOT_STORAGE_KEY_PREFIX = '_snt_snap:';\n/** A snapshot older than this is ignored (the inline pre-paint's 2592e6). */\nexport const SNAPSHOT_MAX_AGE_MS = 30 * 24 * 60 * 60 * 1000;\n\n/** Versioned compound locator: resolve id → dataAttr → selector, then verify\n * against fingerprint. Lets a slot survive DOM/markup drift. */\nexport type CompoundLocator = {\n v?: number;\n id?: string;\n dataAttr?: { name: string; value: string };\n selector?: string;\n urlMatch?: string;\n /** Where the element is expected to exist — see page-scope.ts. Health only, never serving. */\n page?: string;\n fingerprint?: { tag?: string; text?: string };\n semanticId?: string;\n};\n\n/** Bounded, declarative operations a registry arm may apply to its element.\n * The style set is a fixed whitelist (validated server-side); no arbitrary CSS,\n * HTML, or JS ever. `text` is applied via textContent; https-only URLs.\n * moveBefore/moveAfter (exactly one) reposition the element relative to a\n * uniquely-resolving sibling anchor — post-decide only, never pre-paint. */\nexport type SlotOps = {\n text?: string;\n style?: Record<string, string>;\n hidden?: boolean;\n href?: string;\n imageSrc?: string;\n imageAlt?: string;\n moveBefore?: CompoundLocator;\n moveAfter?: CompoundLocator;\n};\n\n/** Registry-mode apply info per slot: where to apply and what to set. Stored so\n * a returning visitor's pre-paint can reapply it. `target` is the Phase-2 bare\n * selector; `locator` (Phase 3) is the compound locator, preferred when present. */\nexport type SlotConfigEntry = {\n kind: 'tokens' | 'arms';\n target?: string;\n locator?: CompoundLocator;\n content?: string;\n ops?: SlotOps;\n /** Composition Blocks per arm — ALL arms, not just the served one, because\n * Option-B rendering pre-paints every arm hidden and reveals the served one\n * (spec §6). Holdout sessions receive the baseline arm's tree only, so the\n * control group's DOM stays meaningful. Absent for non-composition slots. */\n blocks?: Record<string, BlockNode>;\n /** The served Rewrite arm (spec 2026-09-23 §4.3): per-node edits plus the\n * skeleton fingerprint and leaf map they were written against. */\n edits?: ServedEdits;\n /** The server has no skeleton for this region — capture and report one. */\n needsSkeleton?: true;\n /** Redesign arms per arm id — ALL arms, same Option-B reason as `blocks`.\n * Served only to pages that declared RenderCaps.compose. */\n compose?: Record<string, import('./style-vocabulary.js').ComposeArm>;\n /** A hybrid <Adaptive> held back: its id still has un-migrated variant\n * history, so the page renders its original until the operator migrates. */\n blocked?: 'variant_history';\n};\n\nexport type DecisionSnapshot = {\n v: 1;\n persona: string;\n band: 'low' | 'medium' | 'high';\n slots: Record<string, SlotResult>;\n layoutOrder: string[] | null;\n savedAt: number;\n // Additive (kept at v:1 so existing snapshots stay valid — bumping the version\n // would flush every returning visitor's snapshot and flash the baseline once).\n // Present only for registry-mode (no-code) installs.\n slotConfig?: Record<string, SlotConfigEntry>;\n /** Derived site palette for Composition Block rendering — cached so the\n * pre-paint render already looks native (a palette that pops in post-decide\n * would be its own flash). */\n palette?: SitePalette;\n /** The site-style entries the served compose arms reference — cached so the\n * pre-paint render already borrows the site's classes. Additive (v stays 1). */\n vocabulary?: import('./style-vocabulary.js').StyleVocabulary;\n /** The `data-sentient-stage` value last decided — already coarsened, and\n * present only for a `stageAttributes` install (additive, v stays 1). */\n stage?: string;\n};\n\nconst BANDS = ['low', 'medium', 'high'];\n\n/** Returns null on missing, corrupt, or wrong-version data — never throws. */\nexport function readSnapshot(apiKey: string): DecisionSnapshot | null {\n try {\n const raw = localStorage.getItem(SNAPSHOT_STORAGE_KEY_PREFIX + apiKey);\n if (!raw) return null;\n const p = JSON.parse(raw) as Partial<DecisionSnapshot> | null;\n if (\n !p ||\n typeof p !== 'object' ||\n p.v !== 1 ||\n typeof p.persona !== 'string' ||\n typeof p.band !== 'string' ||\n !BANDS.includes(p.band) ||\n typeof p.slots !== 'object' ||\n p.slots === null ||\n Array.isArray(p.slots) ||\n !(p.layoutOrder === null || Array.isArray(p.layoutOrder)) ||\n typeof p.savedAt !== 'number' ||\n // The documented 30-day life, the same bound the inline pre-paint script\n // applies: an older decision is ignored everywhere (grader NEW-5).\n !(Date.now() - p.savedAt < SNAPSHOT_MAX_AGE_MS) ||\n // slotConfig is optional; when present it must be a plain object.\n !(p.slotConfig === undefined || (typeof p.slotConfig === 'object' && p.slotConfig !== null && !Array.isArray(p.slotConfig)))\n ) {\n return null;\n }\n // A malformed cached vocabulary degrades to palette styling, never throws.\n const v = p.vocabulary as { entries?: unknown; images?: unknown } | undefined;\n if (v !== undefined && (typeof v !== 'object' || v === null || !Array.isArray(v.entries) || !Array.isArray(v.images))) {\n delete p.vocabulary;\n }\n // Same for the stage: a non-string never reaches setAttribute.\n if (p.stage !== undefined && typeof p.stage !== 'string') delete p.stage;\n return p as DecisionSnapshot;\n } catch {\n return null;\n }\n}\n\n/** Best-effort persist — storage failures are swallowed. */\nexport function writeSnapshot(apiKey: string, snap: DecisionSnapshot): void {\n try {\n localStorage.setItem(SNAPSHOT_STORAGE_KEY_PREFIX + apiKey, JSON.stringify(snap));\n } catch {\n /* private mode / quota — the snapshot is an optimization, never a requirement */\n }\n}\n\n/**\n * Inline pre-paint script (Rung 1a): reads the snapshot and sets\n * `data-sentient-persona` / `data-sentient-confidence` on <html> before\n * first paint. Single-writer: it never overwrites attributes already set.\n *\n * Safety properties (pinned by tests):\n * - apiKey goes through JSON.stringify, then '<' is escaped to <, so a\n * hostile key can neither break the JS string nor terminate the <script>.\n * - Built by string concatenation and contains no backticks, so the output\n * survives being embedded in template-literal-based renderers.\n */\nexport function renderPrePaintScript(apiKey: string, opts?: { stage?: boolean }): string {\n const key = JSON.stringify(SNAPSHOT_STORAGE_KEY_PREFIX + apiKey).replace(/</g, '\\\\u003c');\n return (\n '(function(){try{' +\n // DNT/GPC: the SDK never reads what it stored for an opted-out browser\n // (grader F3 — this fallback had no gate at all).\n // Every signal isDoNotTrackEnabled reads, not just the standard one.\n 'var N=navigator,W=window;if(N.doNotTrack==\"1\"||N.doNotTrack==\"yes\"||W.doNotTrack==\"1\"||N.msDoNotTrack==\"1\"||N.globalPrivacyControl)return;' +\n 'var r=localStorage.getItem(' + key + ');if(!r)return;' +\n 'var s=JSON.parse(r);' +\n 'if(!s||s.v!==1||typeof s.persona!==\"string\"||typeof s.band!==\"string\")return;' +\n // The same 30-day life readSnapshot enforces.\n 'if(!(' + SNAPSHOT_MAX_AGE_MS + '>Date.now()-s.savedAt))return;' +\n 'var d=document.documentElement;' +\n // Opt-in stage attribute (`stageAttributes`): the snapshot holds only the\n // already-coarsened value, so this copies it as-is. Before the persona\n // single-writer return below — an SSR persona must not stop it — but with\n // its own single-writer check, so an SSR-written stage wins. Absent from\n // the output entirely without the option (the default bytes are pinned).\n (opts?.stage\n ? 'if(typeof s.stage==\"string\"&&!d.hasAttribute(\"data-sentient-stage\"))d.setAttribute(\"data-sentient-stage\",s.stage);'\n : '') +\n 'if(d.hasAttribute(\"data-sentient-persona\"))return;' +\n 'd.setAttribute(\"data-sentient-persona\",s.persona);' +\n 'd.setAttribute(\"data-sentient-confidence\",s.band);' +\n '}catch(e){}})();'\n );\n}\n","// Browser request ceilings (audit S8). No browser fetch had a timeout, so a\n// stalled connection — captive portal, dropped mobile radio, an overloaded\n// edge — held a decide or an assign open indefinitely while the page sat on\n// its baseline, and a hung ingest POST wedged a queue's in-flight slot.\n\n/** Read-only calls (winner, weights) and each session upsert. */\nexport const REQUEST_TIMEOUT_MS = 5000;\n/** A SENT decide or assign. The server records them whether or not we read\n * the answer (decide's slot_decisions rows are trials; assign logs the\n * exposure at draw time) — so neither is ever cut short on latency (a slow answer is still applied late, which is\n * what makes the trial real). This ceiling only frees a dead connection. */\nexport const DECIDE_TIMEOUT_MS = 30000;\n/** Durable queue POSTs. Retried on abort, and deduplicated server-side by\n * event id / goal id, so a timeout never double-counts. */\nexport const QUEUE_TIMEOUT_MS = 15000;\n/** How long decide/assign wait for the session upsert before giving up\n * WITHOUT sending: the session retry chain can run ~14 s under 429s, and a\n * decision that is never requested writes no trial (a late decide would —\n * close-out books every slot_decisions row, CONTRACTS §2 \"Which decisions\n * exist\"). The page keeps its baseline; the next page view decides. */\nexport const SESSION_WAIT_MS = 2500;\n\n/** An AbortSignal that fires after `ms`, and a `clear` for when the request\n * settles. No-op where AbortController is missing (the signal is optional). */\nexport function timeoutSignal(ms: number): { signal?: AbortSignal; clear: () => void } {\n if (typeof AbortController !== 'function') return { clear: () => undefined };\n const ctl = new AbortController();\n const t = setTimeout(() => ctl.abort(), ms);\n return { signal: ctl.signal, clear: () => clearTimeout(t) };\n}\n\n/** Resolves true when `p` settles within `ms`, false otherwise. */\nexport function settlesWithin(p: Promise<unknown>, ms: number): Promise<boolean> {\n return new Promise((resolve) => {\n const t = setTimeout(() => resolve(false), ms);\n const done = (): void => {\n clearTimeout(t);\n resolve(true);\n };\n p.then(done, done);\n });\n}\n","/**\n * Reliability primitives shared by every outbound SDK transport.\n *\n * Extracted from queue.ts so the goal sender cannot drift from the event\n * queue on the three decisions that decide whether data survives: which\n * responses are worth retrying, how long to wait, and how the cross-reload\n * bucket is read and written. Behaviour is byte-identical to the versions\n * these replace.\n */\n\nconst MAX_BACKOFF_MS = 60_000;\n/** 2^6 s = 64 s, already past MAX_BACKOFF_MS — the cap that stops the shift overflowing. */\nconst BACKOFF_EXPONENT_CAP = 6;\n\n/** Delay before the next attempt after `consecutiveFailures` failed ones (1-based). */\nexport function backoffDelayMs(consecutiveFailures: number): number {\n return Math.min(MAX_BACKOFF_MS, 1000 * 2 ** Math.min(consecutiveFailures, BACKOFF_EXPONENT_CAP));\n}\n\n/** What one delivery attempt achieved. `dropped` is terminal but unsuccessful. */\nexport type DeliveryOutcome = 'delivered' | 'dropped' | 'retry';\n\n/**\n * Classifies a response into the three outcomes that matter to a transport.\n *\n * 2xx delivered. A 4xx other than 429 will never succeed however many times we\n * try it (bad key, rejected body, unknown session), so retrying it loops\n * forever and starves real data out of the bucket — drop it, but distinctly,\n * so callers can tell the developer. 429 and 5xx are transient.\n *\n * `ok` is consulted before `status` deliberately: it is the semantic check, and\n * it keeps stubs that set only `ok` (used throughout the SDK test suite)\n * behaving as they did before this was extracted. An unrecognizable response\n * with neither is treated as retryable, matching the original queue.\n */\nexport function classifyResponse(res: { ok?: boolean; status?: number }): DeliveryOutcome {\n if (res.ok === true) return 'delivered';\n const { status } = res;\n if (typeof status !== 'number') return 'retry';\n if (status >= 200 && status < 300) return 'delivered';\n if (status >= 400 && status < 500 && status !== 429) return 'dropped';\n return 'retry';\n}\n\n/** Anything a persisted bucket can hold: it needs a stable server-side dedupe id. */\nexport type Identified = { id: string };\n\n/**\n * Reads a persisted bucket AND clears it — the caller takes ownership of the\n * items and is responsible for re-persisting any that fail again. Returns the\n * newest `max` entries; a corrupt or absent bucket reads as empty.\n */\nexport function drainBucket<T extends Identified>(storageKey: string, max: number): T[] {\n try {\n const raw = localStorage.getItem(storageKey);\n if (!raw) return [];\n const parsed = JSON.parse(raw) as T[];\n if (!Array.isArray(parsed)) return [];\n localStorage.removeItem(storageKey);\n return parsed.slice(-max);\n } catch {\n return [];\n }\n}\n\n/**\n * Merges `items` into the persisted bucket, de-duped by id (last write wins)\n * before the size cap. The dedupe matters: a batch that 5xx's repeatedly\n * in-session hands the same ids back on every retry, and without it each retry\n * appends another copy and `slice(-max)` evicts other distinct failed items to\n * make room for the duplicates.\n */\nexport function writeBucket<T extends Identified>(items: T[], max: number, storageKey: string): void {\n try {\n const existing = (() => {\n try {\n const raw = localStorage.getItem(storageKey);\n if (!raw) return [] as T[];\n const parsed = JSON.parse(raw) as T[];\n return Array.isArray(parsed) ? parsed : ([] as T[]);\n } catch {\n return [] as T[];\n }\n })();\n const byId = new Map<string, T>();\n for (const e of existing) byId.set(e.id, e);\n for (const e of items) byId.set(e.id, e);\n localStorage.setItem(storageKey, JSON.stringify([...byId.values()].slice(-max)));\n } catch {\n /* storage unavailable — the in-memory retry path still applies */\n }\n}\n\n/**\n * Removes the given ids from the persisted bucket. Called once an item is\n * acknowledged so a transient failure that was written to localStorage isn't\n * replayed on the next page load after the in-session retry succeeded.\n */\nexport function purgeBucket(ids: string[], storageKey: string): void {\n try {\n const raw = localStorage.getItem(storageKey);\n if (!raw) return;\n const parsed = JSON.parse(raw) as Identified[];\n if (!Array.isArray(parsed)) return;\n const drop = new Set(ids);\n const remaining = parsed.filter((e) => !drop.has(e.id));\n if (remaining.length === parsed.length) return; // nothing to remove\n if (remaining.length === 0) localStorage.removeItem(storageKey);\n else localStorage.setItem(storageKey, JSON.stringify(remaining));\n } catch {\n /* ignore */\n }\n}\n","/** Batched event queue with reliable transport (fetch + keepalive, localStorage retry). */\n\nimport { forgetGeneration } from './storage-key.js';\nimport { QUEUE_TIMEOUT_MS, timeoutSignal } from './timeout.js';\nimport { backoffDelayMs, classifyResponse, drainBucket, purgeBucket, writeBucket } from './durable.js';\n\nexport type EventType =\n | 'variant_assigned'\n | 'goal_achieved'\n | 'scroll_depth'\n | 'dwell'\n | 'cursor_signal'\n | 'component_visible'\n | 'component_exited'\n | 'micro_signal'\n // A funnel DECLARATION, not telemetry: the server upserts the funnel entity\n // and never stores it in raw_events. Listed here so callers can express it\n // without casting through the track() signature.\n | 'funnel_declared'\n // A goal DECLARATION (React `useGoal`, the snippet's `primaryGoal`): the\n // server creates the goal so it shows at 0 before it first fires, and with\n // `primary: true` makes it the main goal. Never stored in raw_events.\n | 'goal_declared'\n // One per page load and per SPA route change, so a visit's journey through the\n // site is reconstructable. Carries `path` and nothing else.\n | 'pageview'\n // Session-level interaction aggregates for the browser-agent axis (one\n // cumulative snapshot per bank point on the `__session__` sentinel). Read by\n // the bot scorer only; never attributed to a component, never a reward.\n | 'interaction_stats';\n\nexport type SentientEvent = {\n id: string;\n sessionId: string;\n projectId: string;\n componentId: string;\n variantId?: string;\n eventType: EventType;\n goalType?: string;\n /**\n * Page path the event happened on, e.g. `/pricing`. Set automatically from\n * `location.pathname` — deliberately NOT `location.href`, so query strings\n * (which routinely carry emails, reset tokens and order ids) never leave the\n * browser. The server re-strips them anyway; this is the first of two gates.\n * Undefined outside a browser (SSR), where there is no page to name.\n */\n path?: string;\n payload: Record<string, unknown>;\n timestamp: number;\n timeInSession: number;\n};\n\nexport type QueueConfig = {\n ingestUrl: string;\n apiKey: string;\n flushIntervalMs?: number;\n maxBatchSize?: number;\n maxRetrySize?: number;\n};\n\nexport type EventQueue = {\n push(event: SentientEvent): void;\n flush(): void;\n /** Stop the queue with a final flush. `forget`: the visitor asked to be\n * forgotten — a failed final delivery must NOT be persisted for retry\n * (it re-created the retry bucket after forget-me removed it). */\n destroy(opts?: { forget?: boolean }): void;\n};\n\nconst MAX_SENT_IDS = 500;\n// 64 KB is the per-origin keepalive budget on every modern browser. We split unload\n// flushes into chunks below this to avoid the whole batch being dropped.\nconst KEEPALIVE_BUDGET_BYTES = 56 * 1024;\n\n/**\n * Persisted retry-bucket key, namespaced by apiKey prefix so multiple projects\n * on the same origin each get their own bucket. Exported so the client's\n * forget-me teardown can remove it.\n */\nexport function retryStorageKey(apiKey: string): string {\n return `_snt_retry_${apiKey.slice(0, 12)}`;\n}\n\nconst SSR_QUEUE: EventQueue = {\n push: () => undefined,\n flush: () => undefined,\n destroy: () => undefined,\n};\n\n/**\n * Creates a batched event queue with periodic and lifecycle-triggered flushes.\n */\nexport function createEventQueue(config: QueueConfig): EventQueue {\n if (typeof window === 'undefined') {\n return SSR_QUEUE;\n }\n\n const flushIntervalMs = config.flushIntervalMs ?? 5000;\n const maxBatchSize = config.maxBatchSize ?? 20;\n const maxRetrySize = config.maxRetrySize ?? 100;\n const ingestUrl = config.ingestUrl;\n const apiKey = config.apiKey;\n const RETRY_KEY = retryStorageKey(apiKey);\n // Set by destroy({ forget: true }); see the type's doc.\n let forgotten = false;\n const createdGen = forgetGeneration(apiKey);\n const persistBucket: typeof writeBucket = (...a) => {\n if (!forgotten && forgetGeneration(apiKey) === createdGen) writeBucket(...a);\n };\n\n const queue: SentientEvent[] = [];\n const sentIds = new Set<string>();\n const sentIdOrder: string[] = [];\n\n const markSent = (ids: string[]): void => {\n for (const id of ids) {\n queuedIds.delete(id); // free the in-flight slot\n if (sentIds.has(id)) continue;\n sentIds.add(id);\n sentIdOrder.push(id);\n }\n while (sentIdOrder.length > MAX_SENT_IDS) {\n const oldest = sentIdOrder.shift();\n if (oldest) sentIds.delete(oldest);\n }\n // A batch that previously 5xx'd was persisted to the cross-reload retry\n // backstop. Now that it's acknowledged (delivered, or 4xx-dropped as\n // unretryable), drop those ids from localStorage too — otherwise the next\n // page load would replay an already-handled event. `sentIds` is in-memory\n // only, so it can't suppress that cross-reload duplicate on its own.\n purgeBucket(ids, RETRY_KEY);\n };\n\n // Tracks IDs currently in `queue` or in flight (handed to transportBatch\n // but not yet confirmed). Entries are removed on markSent or when an event\n // is dropped, so the set stays bounded by in-flight + queued size.\n const queuedIds = new Set<string>();\n\n // Bound the in-memory queue at the same cap as the persisted retry bucket\n // (maxRetrySize). During a sustained outage flush() keeps re-enqueueing every\n // failed batch while the page keeps producing events, and only the\n // localStorage bucket was capped — so a multi-hour outage on a long-lived\n // SPA tab grew this array without limit. Drop-oldest, matching writeBucket's\n // slice(-max) shed policy: the newest events are the ones a recovering\n // server can still use.\n const capQueue = (): void => {\n while (queue.length > maxRetrySize) {\n const dropped = queue.shift();\n if (dropped) queuedIds.delete(dropped.id);\n }\n };\n\n const enqueue = (event: SentientEvent): void => {\n if (sentIds.has(event.id) || queuedIds.has(event.id)) return;\n queuedIds.add(event.id);\n queue.push(event);\n capQueue();\n };\n\n // A retryable failure hands the batch back to the in-memory queue so the\n // backoff-gated interval flush retries it in-session (localStorage is only the\n // cross-reload backstop). The ids are still tracked in queuedIds — they were\n // pulled from `queue` on flush but never markSent — so we re-add them WITHOUT\n // going through enqueue (which would skip them as already-queued) and without\n // deleting/re-adding queuedIds. Already-sent events are never re-queued, and a\n // single event stays a single copy: `queue` is fully drained each flush.\n const requeueFailed = (batch: SentientEvent[]): void => {\n for (const event of batch) {\n if (sentIds.has(event.id)) continue;\n queuedIds.add(event.id); // idempotent — keeps id-tracking consistent\n queue.push(event);\n }\n // Failed batches count against the same bound as fresh pushes — this path\n // is exactly the one that grew unbounded during an outage (see capQueue).\n capQueue();\n };\n\n const retryEvents = drainBucket<SentientEvent>(RETRY_KEY, maxRetrySize);\n for (const event of retryEvents) {\n enqueue(event);\n }\n\n // Pause flushing until backoff expires.\n let backoffUntil = 0;\n let consecutiveFailures = 0;\n\n // Authenticated transport. keepalive: true gives unload-survival; we still await\n // the response so 5xx/429 actually surface and we can retry.\n const transportBatch = (batch: SentientEvent[], salvage = true): void => {\n if (batch.length === 0) return;\n const body = JSON.stringify(batch);\n const ids = batch.map((e) => e.id);\n\n let pending: Promise<Response> | Response;\n const queueTimer = timeoutSignal(QUEUE_TIMEOUT_MS);\n try {\n // Bounded (QUEUE_TIMEOUT_MS): a hung POST never settles, which held this\n // batch in flight forever. An abort is a retry; ids dedupe server-side.\n pending = fetch(ingestUrl, {\n method: 'POST',\n keepalive: true,\n signal: queueTimer.signal,\n body,\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${apiKey}`,\n },\n });\n } catch {\n // Synchronous throw (typically jsdom in tests, or extreme browser failure).\n persistBucket(batch, maxRetrySize, RETRY_KEY);\n requeueFailed(batch);\n consecutiveFailures++;\n backoffUntil = Date.now() + backoffDelayMs(consecutiveFailures);\n return;\n }\n\n Promise.resolve(pending).then(queueTimer.clear, queueTimer.clear);\n // fetch can sometimes return a value directly (tests using stubGlobal). Handle both.\n const handleResponse = (res: Response): void => {\n if (classifyResponse(res) !== 'retry') {\n // An API older than migration 108 400s the whole batch over the unknown\n // 'pageview' type, and a 4xx is terminal — which silently dropped the\n // co-batched exposures and goals too. Re-send once without the\n // pageviews (valid on the old API); the pageviews themselves are\n // unsendable there and are dropped as delivered.\n if (!res.ok && salvage) {\n const rest = batch.filter((e) => e.eventType !== 'pageview');\n if (rest.length > 0 && rest.length < batch.length) {\n markSent(batch.filter((e) => e.eventType === 'pageview').map((e) => e.id));\n transportBatch(rest, false);\n return;\n }\n }\n // 2xx = success. 4xx (except 429) will never succeed — drop them rather than loop.\n markSent(ids);\n consecutiveFailures = 0;\n backoffUntil = 0;\n return;\n }\n // 5xx / 429 → retry with backoff.\n persistBucket(batch, maxRetrySize, RETRY_KEY);\n requeueFailed(batch);\n consecutiveFailures++;\n backoffUntil = Date.now() + backoffDelayMs(consecutiveFailures);\n };\n\n // Thenable, not instanceof: another realm's Promise failed it (N11-4).\n if (pending && typeof (pending as PromiseLike<unknown>).then === 'function') {\n pending.then(handleResponse).catch(() => {\n persistBucket(batch, maxRetrySize, RETRY_KEY);\n requeueFailed(batch);\n consecutiveFailures++;\n backoffUntil = Date.now() + backoffDelayMs(consecutiveFailures);\n });\n } else {\n handleResponse(pending as unknown as Response); // test stubs return a plain value\n }\n };\n\n // Pack events into a batch that stays under the keepalive byte budget AND the\n // configured event-count cap. Returns the prefix of `pool` that fits.\n // Uses UTF-8 byte length (not char count) — emoji/CJK payloads can be 3–4×\n // larger as bytes and would otherwise blow the keepalive budget.\n const encoder = typeof TextEncoder !== 'undefined' ? new TextEncoder() : null;\n const byteLength = (s: string): number =>\n encoder ? encoder.encode(s).length : s.length;\n const packBatch = (pool: SentientEvent[]): SentientEvent[] => {\n const out: SentientEvent[] = [];\n let bytes = 2; // for the surrounding []\n for (const e of pool) {\n const size = byteLength(JSON.stringify(e)) + 1; // +1 for comma\n if (out.length > 0 && bytes + size > KEEPALIVE_BUDGET_BYTES) break;\n if (out.length >= maxBatchSize) break;\n out.push(e);\n bytes += size;\n }\n return out;\n };\n\n const flush = (): void => {\n try {\n if (Date.now() < backoffUntil) return;\n while (queue.length > 0) {\n // Re-check inside the loop: transportBatch can set backoffUntil\n // synchronously (a sync throw or a same-tick Response) and re-enqueue the\n // failed batch, so a mid-drain backoff must stop further chunks this tick\n // (otherwise the just-re-enqueued batch would immediately retry-loop).\n if (Date.now() < backoffUntil) break;\n const pending = queue.filter((e) => !sentIds.has(e.id));\n queue.length = 0;\n if (pending.length === 0) break;\n const batch = packBatch(pending);\n if (batch.length === 0) break;\n // Put anything we didn't pack back on the queue for the next tick.\n if (batch.length < pending.length) {\n queue.push(...pending.slice(batch.length));\n }\n transportBatch(batch);\n }\n } catch {\n /* never throw */\n }\n };\n\n let flushTimerActive = true;\n let intervalId: ReturnType<typeof setInterval> | null = null;\n\n intervalId = setInterval(() => {\n if (!flushTimerActive) return;\n flush();\n }, flushIntervalMs);\n\n const onVisibilityChange = (): void => {\n if (document.visibilityState === 'hidden') {\n flush();\n }\n };\n\n // `pagehide` (not `beforeunload`): a `beforeunload` listener can disqualify a\n // page from the back/forward cache. `pagehide` fires on real unloads AND on\n // bfcache eviction, and `visibilitychange:hidden` already covers most leaves,\n // so flush-on-leave stays covered without inhibiting bfcache.\n const onPageHide = (): void => {\n flush();\n };\n\n document.addEventListener('visibilitychange', onVisibilityChange);\n window.addEventListener('pagehide', onPageHide);\n\n return {\n push(event: SentientEvent): void {\n enqueue(event);\n if (queue.length >= maxBatchSize) {\n flush();\n }\n },\n flush,\n destroy(opts?: { forget?: boolean }): void {\n if (opts?.forget) forgotten = true;\n flushTimerActive = false;\n if (intervalId !== null) {\n clearInterval(intervalId);\n intervalId = null;\n }\n document.removeEventListener('visibilitychange', onVisibilityChange);\n window.removeEventListener('pagehide', onPageHide);\n flush();\n },\n };\n}\n","/**\n * Durable transport for `POST /v1/goals`.\n *\n * A conversion is the single most valuable event the SDK emits, and it used to\n * be the least reliable one: `goal()` fired a bare `fetch(...).catch(() => {})`,\n * which only observes network-layer failures. A 429 (the per-IP limit is 100\n * req/min, and shared egress — corporate NAT, carriers, storefront proxies —\n * hits it routinely), a 5xx, or a 400 all RESOLVE, so the catch never ran and\n * the response was discarded unread. The conversion was gone with no retry and\n * nothing surfaced to the developer.\n *\n * This gives goals the same guarantees the event queue has always had: retry\n * with backoff in-session, a localStorage bucket that survives reload, and\n * dedupe by id. Retry is safe because `goalId` is a client-generated UUID that\n * the server dedupes on (`ON CONFLICT DO NOTHING`) — the safety was already\n * there, it just wasn't used.\n *\n * Unlike events, `/v1/goals` takes ONE goal per request, so this is a serial\n * sender rather than a batcher, and a flush sends at most `maxPerFlush` so a\n * backlog drains at a pace the rate limiter tolerates instead of re-triggering\n * the 429 that created it.\n */\n\nimport { forgetGeneration } from './storage-key.js';\nimport { QUEUE_TIMEOUT_MS, timeoutSignal } from './timeout.js';\nimport { backoffDelayMs, classifyResponse, drainBucket, purgeBucket, writeBucket } from './durable.js';\n\n/** One queued conversion. `id` is the goalId — the server's dedupe key. */\nexport type PendingGoal = {\n id: string;\n /** Pre-serialized request body, so a persisted goal replays byte-identically. */\n body: string;\n};\n\nexport type GoalQueueConfig = {\n /** Absolute URL of the goals endpoint. */\n url: string;\n apiKey: string;\n headers: Record<string, string>;\n flushIntervalMs?: number;\n maxRetrySize?: number;\n maxPerFlush?: number;\n /** Called when a goal is permanently dropped (non-retryable status), so the\n * client can warn in debug mode. Never called for retryable failures. */\n onDrop?: (goal: PendingGoal, status: number) => void;\n};\n\nexport type GoalQueue = {\n /** Sends immediately; on a retryable failure the goal is queued and retried. */\n send(goal: PendingGoal): void;\n flush(): void;\n /** Stop the queue with a final flush. `forget`: the visitor asked to be\n * forgotten — a failed final delivery must NOT be persisted for retry\n * (it re-created the retry bucket after forget-me removed it). */\n destroy(opts?: { forget?: boolean }): void;\n};\n\nconst MAX_SENT_IDS = 200;\n\n/**\n * Persisted goal-retry bucket key, namespaced by apiKey prefix so multiple\n * projects on one origin keep separate buckets. Exported so the client's\n * forget-me teardown can remove it.\n */\nexport function goalRetryStorageKey(apiKey: string): string {\n return `_snt_goal_retry_${apiKey.slice(0, 12)}`;\n}\n\nconst SSR_GOAL_QUEUE: GoalQueue = {\n send: () => undefined,\n flush: () => undefined,\n destroy: () => undefined,\n};\n\nexport function createGoalQueue(config: GoalQueueConfig): GoalQueue {\n if (typeof window === 'undefined') return SSR_GOAL_QUEUE;\n\n const flushIntervalMs = config.flushIntervalMs ?? 5000;\n const maxRetrySize = config.maxRetrySize ?? 100;\n const maxPerFlush = config.maxPerFlush ?? 5;\n const RETRY_KEY = goalRetryStorageKey(config.apiKey);\n // Set by destroy({ forget: true }); see the type's doc.\n let forgotten = false;\n const createdGen = forgetGeneration(config.apiKey);\n const persistBucket: typeof writeBucket = (...a) => {\n if (!forgotten && forgetGeneration(config.apiKey) === createdGen) writeBucket(...a);\n };\n\n const pending: PendingGoal[] = [];\n const pendingIds = new Set<string>();\n const sentIds = new Set<string>();\n const sentIdOrder: string[] = [];\n\n let backoffUntil = 0;\n let consecutiveFailures = 0;\n let disposed = false;\n\n const markSent = (goal: PendingGoal): void => {\n pendingIds.delete(goal.id);\n if (!sentIds.has(goal.id)) {\n sentIds.add(goal.id);\n sentIdOrder.push(goal.id);\n }\n while (sentIdOrder.length > MAX_SENT_IDS) {\n const oldest = sentIdOrder.shift();\n if (oldest) sentIds.delete(oldest);\n }\n // Acknowledged (delivered, or dropped as unretryable) — clear it from the\n // cross-reload bucket so the next page load doesn't replay it.\n purgeBucket([goal.id], RETRY_KEY);\n };\n\n const markFailed = (goal: PendingGoal): void => {\n persistBucket([goal], maxRetrySize, RETRY_KEY);\n if (!sentIds.has(goal.id) && !pendingIds.has(goal.id)) {\n pendingIds.add(goal.id);\n pending.push(goal);\n }\n // One failed ROUND counts once, however many goals were in flight. flush()\n // launches up to maxPerFlush transports synchronously, so counting per goal\n // turned a single bad tick into consecutiveFailures=5 and a 32s backoff\n // where the first failure warrants 2s. queue.ts counts per batch; match it.\n if (Date.now() >= backoffUntil) {\n consecutiveFailures++;\n backoffUntil = Date.now() + backoffDelayMs(consecutiveFailures);\n }\n };\n\n const transport = (goal: PendingGoal): void => {\n let res: Promise<Response> | Response;\n const queueTimer = timeoutSignal(QUEUE_TIMEOUT_MS);\n try {\n // Bounded like the event queue: an abort retries, the goalId dedupes.\n res = fetch(config.url, {\n method: 'POST',\n keepalive: true,\n signal: queueTimer.signal,\n body: goal.body,\n headers: config.headers,\n });\n } catch {\n // Synchronous throw (jsdom in tests, or extreme browser failure).\n markFailed(goal);\n return;\n }\n\n const handle = (r: Response): void => {\n const outcome = classifyResponse(r);\n if (outcome === 'retry') {\n markFailed(goal);\n return;\n }\n // Terminal either way, but a drop is a wiring bug the developer can fix —\n // a 400 \"session not found\", a 401 from a misconfigured origin allowlist —\n // and used to be swallowed entirely. Say so instead of failing silently.\n if (outcome === 'dropped') config.onDrop?.(goal, r.status);\n markSent(goal);\n consecutiveFailures = 0;\n backoffUntil = 0;\n };\n\n Promise.resolve(res).then(queueTimer.clear, queueTimer.clear);\n // fetch can return a plain value under test stubs. Handle both.\n // A thenable check, not instanceof: a fetch wrapper returning another\n // realm's Promise was handled as a Response and retried (grader N11-4).\n if (res && typeof (res as PromiseLike<unknown>).then === 'function') (res as Promise<Response>).then(handle).catch(() => markFailed(goal));\n else handle(res as unknown as Response); // test stubs return a plain value\n };\n\n const flush = (): void => {\n try {\n if (disposed) return;\n if (Date.now() < backoffUntil) return;\n let sentThisTick = 0;\n while (pending.length > 0 && sentThisTick < maxPerFlush) {\n if (Date.now() < backoffUntil) break; // a same-tick failure re-armed backoff\n const goal = pending.shift()!;\n pendingIds.delete(goal.id);\n if (sentIds.has(goal.id)) continue;\n sentThisTick++;\n transport(goal);\n }\n } catch {\n /* never throw from a lifecycle handler */\n }\n };\n\n // Replay anything a previous page load failed to deliver. Left for the first\n // interval tick rather than sent now, so a page that reloads under an ongoing\n // outage doesn't stampede the endpoint during init.\n const restored = drainBucket<PendingGoal>(RETRY_KEY, maxRetrySize);\n for (const goal of restored) {\n if (!pendingIds.has(goal.id)) {\n pendingIds.add(goal.id);\n pending.push(goal);\n }\n }\n // drainBucket CLEARS storage as it reads, but only maxPerFlush goals leave per\n // tick — so a 40-goal backlog moved to memory and the visitor navigating two\n // seconds later lost the 35 that hadn't been sent yet. Put them straight back;\n // markSent purges each id individually once it is actually acknowledged.\n if (restored.length > 0) writeBucket(restored, maxRetrySize, RETRY_KEY);\n\n const intervalId = setInterval(flush, flushIntervalMs);\n const onVisibilityChange = (): void => {\n if (document.visibilityState === 'hidden') flush();\n };\n const onPageHide = (): void => flush();\n document.addEventListener('visibilitychange', onVisibilityChange);\n window.addEventListener('pagehide', onPageHide);\n\n return {\n send(goal: PendingGoal): void {\n if (disposed) {\n // A goal fired before a pause, still waiting on the first session\n // upsert, arrives after dispose(): banked for the next page's queue\n // instead of dropped unreported (grader R9-3, CONTRACTS §7). Never\n // after a forget — persistBucket checks that.\n if (!sentIds.has(goal.id)) persistBucket([goal], maxRetrySize, RETRY_KEY);\n return;\n }\n if (sentIds.has(goal.id) || pendingIds.has(goal.id)) return;\n // A conversion goes out now — it is often the last thing that happens\n // before a redirect to a thank-you page. Only a failure makes it queued.\n if (Date.now() < backoffUntil) {\n // Persist BEFORE parking it in memory. A goal only ever reached the\n // cross-reload bucket via markFailed — i.e. only after a failed attempt\n // — so a conversion queued during someone else's backoff lived in memory\n // alone, and flush() early-returns while backoff is armed, so pagehide\n // could not rescue it either. A purchase firing 300ms after a rate-limited\n // add_to_cart was lost on the checkout redirect: exactly the outage this\n // queue exists to survive.\n persistBucket([goal], maxRetrySize, RETRY_KEY);\n pendingIds.add(goal.id);\n pending.push(goal);\n return;\n }\n transport(goal);\n },\n flush,\n destroy(opts?: { forget?: boolean }): void {\n if (opts?.forget) forgotten = true;\n clearInterval(intervalId);\n document.removeEventListener('visibilitychange', onVisibilityChange);\n window.removeEventListener('pagehide', onPageHide);\n flush();\n disposed = true;\n },\n };\n}\n","import { sessionCookieName, storageSuffix, LEGACY_SESSION_COOKIE_NAME, markForgotten } from './storage-key.js';\nimport { SNAPSHOT_STORAGE_KEY_PREFIX } from './snapshot.js';\nimport { retryStorageKey } from './queue.js';\nimport { goalRetryStorageKey } from './goal-queue.js';\nimport { parentDomains } from './cookie-domain.js';\n\n/**\n * Forget-me WITHOUT a client: delete everything the SDK stores for `apiKey`'s\n * visitor. `client.destroy()` does this for a live tracking client, which only\n * exists when consent was granted in this page view — so a visitor who said\n * \"no\" somewhere the SDK wasn't watching (a CMP settings page, checkout)\n * kept the 365-day id, the decision snapshot and the retry buckets for good,\n * and the pre-paint script kept personalizing from that snapshot (audit N2).\n * Callers run this when the consent source reports a refusal at boot.\n *\n * Writes nothing unless something was stored: the legacy tombstone (which\n * stops this project re-adopting the shared bare `_snt_uid`) is only written\n * when there is a bare id to block. Returns whether anything was removed.\n */\nexport function forgetVisitor(apiKey: string): boolean {\n if (typeof window === 'undefined' || !apiKey) return false;\n markForgotten(apiKey);\n let removed = false;\n const name = sessionCookieName(apiKey);\n try {\n if (new RegExp(`(?:^|; )${name}=`).test(document.cookie)) {\n const secure = location.protocol === 'https:' ? '; Secure' : '';\n // The visitor cookie may be shared on a parent domain (cookie-domain.ts),\n // and a host-only delete leaves that copy for every sibling host to\n // re-adopt. Which domain was configured is not known here, so every\n // parent is cleared — deleting a cookie that isn't there is a no-op.\n for (const d of ['', ...parentDomains(location.hostname)]) {\n document.cookie = `${name}=; max-age=0; SameSite=lax; path=/${d ? `; domain=${d}` : ''}${secure}`;\n }\n removed = true;\n }\n } catch {\n /* cookies unavailable */\n }\n const suffix = storageSuffix(apiKey);\n const exact = [\n name,\n // Written by builds before 2026; current SDKs only ever delete it.\n '_snt_graph_edges',\n SNAPSHOT_STORAGE_KEY_PREFIX + apiKey,\n retryStorageKey(apiKey),\n goalRetryStorageKey(apiKey),\n `_snt_graph_nodes${suffix}`,\n ];\n const prefixes = [`_snt_asgn${suffix}_`];\n for (const store of ['localStorage', 'sessionStorage'] as const) {\n try {\n const s = window[store];\n for (const k of exact) {\n if (s.getItem(k) !== null) {\n s.removeItem(k);\n removed = true;\n }\n }\n for (let i = s.length - 1; i >= 0; i--) {\n const k = s.key(i);\n if (k && prefixes.some((p) => k.startsWith(p))) {\n s.removeItem(k);\n removed = true;\n }\n }\n } catch {\n /* storage unavailable */\n }\n }\n try {\n // Every layer session.ts's legacy read adopts from, sessionStorage too.\n const bare =\n new RegExp(`(?:^|; )${LEGACY_SESSION_COOKIE_NAME}=[^;]`).test(document.cookie) ||\n localStorage.getItem(LEGACY_SESSION_COOKIE_NAME) !== null ||\n sessionStorage.getItem(LEGACY_SESSION_COOKIE_NAME) !== null;\n if (bare) localStorage.setItem(`${LEGACY_SESSION_COOKIE_NAME}_tomb${suffix}`, '1');\n } catch {\n /* storage unavailable */\n }\n return removed;\n}\n"],"mappings":"kHASO,IAAMA,EAA8B,aAoF3C,IAAMC,GAAQ,CAAC,MAAO,SAAU,MAAM,EAG/B,SAASC,GAAaC,EAAyC,CACpE,GAAI,CACF,IAAMC,EAAM,aAAa,QAAQC,EAA8BF,CAAM,EACrE,GAAI,CAACC,EAAK,OAAO,KACjB,IAAME,EAAI,KAAK,MAAMF,CAAG,EACxB,GACE,CAACE,GACD,OAAOA,GAAM,UACbA,EAAE,IAAM,GACR,OAAOA,EAAE,SAAY,UACrB,OAAOA,EAAE,MAAS,UAClB,CAACL,GAAM,SAASK,EAAE,IAAI,GACtB,OAAOA,EAAE,OAAU,UACnBA,EAAE,QAAU,MACZ,MAAM,QAAQA,EAAE,KAAK,GACrB,EAAEA,EAAE,cAAgB,MAAQ,MAAM,QAAQA,EAAE,WAAW,IACvD,OAA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EAAS,SAAS,WAAa,SAAW,WAAa,GAK7D,QAAWC,IAAK,CAAC,GAAI,GAAGC,GAAc,SAAS,QAAQ,CAAC,EACtD,SAAS,OAAS,GAAGJ,CAAI,qCAAqCG,EAAI,YAAYA,CAAC,GAAK,EAAE,GAAGD,CAAM,GAEjGH,EAAU,EACZ,CACF,OAAQM,EAAA,CAER,CACA,IAAMC,EAASC,GAAcV,CAAM,EAC7BW,EAAQ,CACZR,EAEA,mBACAS,EAA8BZ,EAC9Ba,EAAgBb,CAAM,EACtBc,EAAoBd,CAAM,EAC1B,mBAAmBS,CAAM,EAC3B,EACMM,EAAW,CAAC,YAAYN,CAAM,GAAG,EACvC,QAAWO,IAAS,CAAC,eAAgB,gBAAgB,EACnD,GAAI,CACF,IAAMC,EAAI,OAAOD,CAAK,EACtB,QAAWE,KAAKP,EACVM,EAAE,QAAQC,CAAC,IAAM,OACnBD,EAAE,WAAWC,CAAC,EACdhB,EAAU,IAGd,QAASiB,EAAIF,EAAE,OAAS,EAAGE,GAAK,EAAGA,IAAK,CACtC,IAAMD,EAAID,EAAE,IAAIE,CAAC,EACbD,GAAKH,EAAS,KAAMK,GAAMF,EAAE,WAAWE,CAAC,CAAC,IAC3CH,EAAE,WAAWC,CAAC,EACdhB,EAAU,GAEd,CACF,OAAQM,EAAA,CAER,CAEF,GAAI,EAGA,IAAI,OAAO,WAAWa,CAA0B,OAAO,EAAE,KAAK,SAAS,MAAM,GAC7E,aAAa,QAAQA,CAA0B,IAAM,MACrD,eAAe,QAAQA,CAA0B,IAAM,OAC/C,aAAa,QAAQ,GAAGA,CAA0B,QAAQZ,CAAM,GAAI,GAAG,CACnF,OAAQD,EAAA,CAER,CACA,OAAON,CACT","names":["SNAPSHOT_STORAGE_KEY_PREFIX","BANDS","readSnapshot","apiKey","raw","SNAPSHOT_STORAGE_KEY_PREFIX","p","v","e","writeSnapshot","snap","renderPrePaintScript","opts","timeoutSignal","ms","ctl","t","settlesWithin","p","resolve","done","backoffDelayMs","consecutiveFailures","classifyResponse","res","status","drainBucket","storageKey","max","raw","parsed","writeBucket","items","existing","e","byId","purgeBucket","ids","drop","remaining","MAX_SENT_IDS","KEEPALIVE_BUDGET_BYTES","retryStorageKey","apiKey","SSR_QUEUE","createEventQueue","config","_a","_b","_c","flushIntervalMs","maxBatchSize","maxRetrySize","ingestUrl","RETRY_KEY","forgotten","createdGen","forgetGeneration","persistBucket","a","writeBucket","queue","sentIds","sentIdOrder","markSent","ids","id","queuedIds","oldest","purgeBucket","capQueue","dropped","enqueue","event","requeueFailed","batch","retryEvents","drainBucket","backoffUntil","consecutiveFailures","transportBatch","salvage","body","e","pending","queueTimer","timeoutSignal","backoffDelayMs","handleResponse","res","classifyResponse","rest","encoder","byteLength","s","packBatch","pool","out","bytes","size","flush","flushTimerActive","intervalId","onVisibilityChange","onPageHide","opts","MAX_SENT_IDS","goalRetryStorageKey","apiKey","SSR_GOAL_QUEUE","createGoalQueue","config","_a","_b","_c","flushIntervalMs","maxRetrySize","maxPerFlush","RETRY_KEY","forgotten","createdGen","forgetGeneration","persistBucket","a","writeBucket","pending","pendingIds","sentIds","sentIdOrder","backoffUntil","consecutiveFailures","disposed","markSent","goal","oldest","purgeBucket","markFailed","backoffDelayMs","transport","res","queueTimer","timeoutSignal","e","handle","r","outcome","classifyResponse","flush","sentThisTick","restored","drainBucket","intervalId","onVisibilityChange","onPageHide","opts","forgetVisitor","apiKey","markForgotten","removed","name","sessionCookieName","secure","d","parentDomains","e","suffix","storageSuffix","exact","SNAPSHOT_STORAGE_KEY_PREFIX","retryStorageKey","goalRetryStorageKey","prefixes","store","s","k","i","p","LEGACY_SESSION_COOKIE_NAME"]}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{a as O}from"./chunk-BGZLWZUG.mjs";import{a as T,c as E}from"./chunk-WUFFNQHQ.mjs";function b(){try{if(typeof crypto!="undefined"&&typeof crypto.randomUUID=="function")return crypto.randomUUID()}catch(t){}try{if(typeof crypto!="undefined"&&typeof crypto.getRandomValues=="function"){let t=new Uint8Array(16);crypto.getRandomValues(t),t[6]=t[6]&15|64,t[8]=t[8]&63|128;let e="";for(let n=0;n<16;n++)e+=t[n].toString(16).padStart(2,"0"),(n===3||n===5||n===7||n===9)&&(e+="-");return e}}catch(t){}return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{let e=Math.random()*16|0;return(t==="x"?e:e&3|8).toString(16)})}var L="_snt_uid",M=365,l="_snt_uid";function V(){return b()}function u(t){try{let e=document.cookie.match(new RegExp(`(?:^|; )${t}=([^;]*)`));return e?decodeURIComponent(e[1]):null}catch(e){return null}}function A(){try{return location.protocol==="https:"?"; Secure":""}catch(t){return""}}function d(t,e,n,o){try{document.cookie=`${t}=${encodeURIComponent(e)}; max-age=${n}; SameSite=lax; path=/${o?`; domain=${o}`:""}${A()}`}catch(x){}}function c(t){try{return localStorage.getItem(t)}catch(e){return null}}function U(t,e){try{return localStorage.setItem(t,e),!0}catch(n){return!1}}function y(t){try{return sessionStorage.getItem(t)}catch(e){return null}}function F(t,e){try{return sessionStorage.setItem(t,e),!0}catch(n){return!1}}function G(t){try{sessionStorage.removeItem(t)}catch(e){}}function Y(t){try{return document.cookie=`${t}_probe=1; max-age=1; SameSite=lax; path=/${A()}`,document.cookie.indexOf(`${t}_probe=1`)!==-1}catch(e){return!1}}function W(t){try{localStorage.removeItem(t)}catch(e){}}function m(t,e){d(t,"",0,e)}var j={getSessionId:()=>null,isEphemeral:()=>!1,domain:null,destroy:()=>{}};function q(t,e){if(t===!1)return null;if(typeof t=="string")return t.replace(/^\./,"");for(let n of O(location.hostname))if(d(e,"1",10,n),u(e)==="1")return m(e,n),n;return null}function Q(t){var k,h,f,I,C,D,_;if(typeof window=="undefined")return j;let e=T(t==null?void 0:t.apiKey),n=(k=t==null?void 0:t.cookieName)!=null?k:E(t==null?void 0:t.apiKey),o=`${l}${e}`,x=`${l}_tomb${e}`,S=((h=t==null?void 0:t.cookieTTLDays)!=null?h:M)*24*60*60,r=a=>a&&a.length>0?a:null,w=()=>{var a,$;return e&&!(t!=null&&t.cookieName)&&c(x)===null?($=(a=r(u(L)))!=null?a:r(c(l)))!=null?$:r(y(l)):null},i=q(t==null?void 0:t.cookieDomain,`${n}_dom`),K=r(u(n)),p=i?(m(n),r(u(n))):null,s=(_=(D=(C=(I=(f=p!=null?p:K)!=null?f:r(c(o)))!=null?I:r(y(o)))!=null?C:w())!=null?D:r(t==null?void 0:t.ssrSessionId))!=null?_:V();d(n,s,S,i),i&&u(n)!==s&&(i=null,d(n,s,S));let g=U(o,s),N=Y(n),R=g?!1:F(o,s),v=!g&&!N&&!R;return{getSessionId:()=>s,isEphemeral:()=>v,domain:i,destroy:()=>{s=null,m(n),m(n,i),W(o),G(o),e&&!(t!=null&&t.cookieName)&&(u(L)!==null||c(l)!==null||y(l)!==null)&&U(x,"1")}}}export{b as a,u as b,d as c,m as d,Q as e};
|
|
2
|
+
//# sourceMappingURL=chunk-LCYGZNFI.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/uuid.ts","../src/session.ts"],"sourcesContent":["/** Shared RFC 4122 v4 UUID generator. */\n\n/**\n * Returns a random RFC 4122 v4 UUID.\n *\n * Resolution order, each falling through only on absence/throw:\n * 1. `crypto.randomUUID()` — requires a **secure context** (HTTPS/localhost),\n * so it is absent on plain `http://` (non-localhost) pages.\n * 2. `crypto.getRandomValues()` — a CSPRNG that, unlike `randomUUID`, *is*\n * available in insecure contexts, so ids stay cryptographically random\n * exactly where step 1 is unavailable.\n * 3. `Math.random()` — last resort only when no Web Crypto exists at all.\n * These ids are anonymous analytics session/event keys (not secrets or\n * authenticators), so a well-formed value the Postgres `uuid` column accepts\n * matters more than PRNG quality here — and the generator must never throw\n * (a missing/malformed id would break session creation and the host page).\n */\nexport function randomUuidV4(): string {\n try {\n if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {\n return crypto.randomUUID();\n }\n } catch {\n /* fall through to getRandomValues */\n }\n try {\n if (typeof crypto !== 'undefined' && typeof crypto.getRandomValues === 'function') {\n const buf = new Uint8Array(16);\n crypto.getRandomValues(buf);\n buf[6] = (buf[6]! & 0x0f) | 0x40; // version 4\n buf[8] = (buf[8]! & 0x3f) | 0x80; // variant 10\n let out = '';\n for (let i = 0; i < 16; i++) {\n out += buf[i]!.toString(16).padStart(2, '0');\n if (i === 3 || i === 5 || i === 7 || i === 9) out += '-';\n }\n return out;\n }\n } catch {\n /* fall through to the Math.random() builder */\n }\n return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {\n const r = (Math.random() * 16) | 0;\n return (c === 'x' ? r : (r & 0x3) | 0x8).toString(16);\n });\n}\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"],"mappings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,GAAAD,GAAAD,EAAAc,GAAA,KAAAA,EACAD,IADA,KAAAb,EAEAW,EAAS9B,EAAiB4B,CAAU,CAAC,IAFrC,KAAAR,EAGAU,EAAS3B,EAAmByB,CAAU,CAAC,IAHvC,KAAAP,EAIAU,EAAW,IAJX,KAAAT,EAKAQ,EAASd,GAAA,YAAAA,EAAQ,YAAY,IAL7B,KAAAO,EAMAlC,EAAkB,EAEpBO,EAAY8B,EAAYQ,EAAWpC,EAAeC,CAAM,EAIpDA,GAAUR,EAAWmC,CAAU,IAAMQ,IACvCnC,EAAS,KACTH,EAAY8B,EAAYQ,EAAWpC,CAAa,GAElD,IAAMqC,EAAOjC,EAAkB0B,EAAYM,CAAS,EAC9CE,EAAW9B,EAAoBoB,CAAU,EAGzCW,EAAQF,EAAoD,GAA7C/B,EAAoBwB,EAAYM,CAAS,EACxDI,EAAY,CAACH,GAAQ,CAACC,GAAY,CAACC,EAEzC,MAAO,CACL,aAAc,IAAMH,EACpB,YAAa,IAAMI,EACnB,OAAAvC,EACA,QAAS,IAAM,CACbmC,EAAY,KACZ1B,EAAYkB,CAAU,EACtBlB,EAAYkB,EAAY3B,CAAM,EAC9BQ,EAAmBqB,CAAU,EAC7BvB,EAAqBuB,CAAU,EAO7BJ,GACA,EAACR,GAAA,MAAAA,EAAQ,cACRzB,EAAWL,CAAmB,IAAM,MAAQc,EAAiBZ,CAAW,IAAM,MAAQe,EAAmBf,CAAW,IAAM,OAE3Hc,EAAkB2B,EAAoB,GAAG,CAE7C,CACF,CACF","names":["randomUuidV4","e","buf","out","i","c","r","DEFAULT_COOKIE_NAME","DEFAULT_COOKIE_TTL_DAYS","STORAGE_KEY","generateSessionId","randomUuidV4","readCookie","name","match","secureAttr","e","writeCookie","value","maxAgeSeconds","domain","readLocalStorage","key","writeLocalStorage","readSessionStorage","writeSessionStorage","removeSessionStorage","probeCookieWritable","removeLocalStorage","clearCookie","SSR_MANAGER","detectCookieDomain","option","probe","d","parentDomains","initSession","config","_a","_b","_c","_d","_e","_f","_g","suffix","storageSuffix","cookieName","sessionCookieName","storageKey","legacyTombstoneKey","nonEmpty","readLegacy","ownCopy","shared","sessionId","lsOk","cookieOk","ssOk","ephemeral"]}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{a as Ke,b as pe,c as ge,e as ie,f as Ee,g as Ne,h as Dt,i as Pt,j as Bt,k as Lt,l as Mt,m as Ge}from"./chunk-JNQY3XNF.mjs";import{a as Kt,e as Ce}from"./chunk-LCYGZNFI.mjs";import{b as $e,i as je,j as Ue,k as We,m as Fe,n as Ve,q as He,r as xe,t as ze}from"./chunk-3HMJERH4.mjs";import{a as ve,d as Ot,e as we}from"./chunk-WUFFNQHQ.mjs";import{a as v,b as te}from"./chunk-TMCGHANO.mjs";var qe;function Je(e){qe=typeof e=="string"&&e!==""?e:void 0}function Nt(e=document){if(qe)return qe;try{let s=e.querySelector("script[nonce]");return(s==null?void 0:s.nonce)||(s==null?void 0:s.getAttribute("nonce"))||void 0}catch(s){return}}function Xe(e,s=document){let g=Nt(s);return g&&e.setAttribute("nonce",g),e}var on=1800*1e3;function Ie(e,s){return`${encodeURIComponent(e)}:${encodeURIComponent(s)}`}function Gt(e=on,s){let g=new Map,b=`_snt_asgn${ve(s)}_`,x=(a,i)=>`${b}${encodeURIComponent(a)}:${encodeURIComponent(i)}`,m=a=>{let i=a.slice(b.length),l=i.indexOf(":");if(l<0)return null;try{return{componentId:decodeURIComponent(i.slice(0,l)),segment:decodeURIComponent(i.slice(l+1))}}catch(w){return null}},_=()=>{try{let a=[];for(let i=0;i<localStorage.length;i++){let l=localStorage.key(i);l!=null&&l.startsWith(b)&&a.push(l)}return a}catch(a){return[]}},n=a=>a.assignedAt+(a.ttlMs&&a.ttlMs>0?a.ttlMs:e)<Date.now();return typeof window!="undefined"&&(()=>{for(let a of _())try{let i=localStorage.getItem(a);if(!i)continue;let l=JSON.parse(i);if(n(l)){localStorage.removeItem(a);continue}let w=m(a);if(!w)continue;g.set(Ie(w.componentId,w.segment),l)}catch(i){}})(),{get(a,i){let l=g.get(Ie(a,i));return l?n(l)?(g.delete(Ie(a,i)),null):l:null},set(a,i,l){let w=Ie(a,i);g.set(w,l);try{localStorage.setItem(x(a,i),JSON.stringify(l))}catch(A){}},clear(){g.clear();for(let a of _())try{localStorage.removeItem(a)}catch(i){}}}}import{STAGE_KEYS as sn}from"@sentientui/policy";var Ye="data-sentient-stage";function Qe(e,s){return!s||typeof e!="string"||!(e==="returning"||sn.includes(e))?null:s!=="detailed"&&(e==="customer"||e==="lapsed")?"returning":e}function Ze(e,s=document){try{e?s.documentElement.setAttribute(Ye,e):s.documentElement.removeAttribute(Ye)}catch(g){}}import{confidenceBand as Ht}from"@sentientui/policy";import{confidenceBand as et}from"@sentientui/policy";var tt="[sentient] No API key configured \u2014 nothing is being learned. Set NEXT_PUBLIC_SENTIENT_API_KEY or pass localMode: true for local development.",jt="[sentient] Local mode \u2014 decisions are simulated on-device and nothing is sent over the network. Add an API key to learn from real traffic.",$t=!1,_e=!1;function rn(){var e;try{return(e=new URLSearchParams(window.location.search).get("sentient_persona"))!=null?e:void 0}catch(s){return}}function Ut(e){var a;let s=Ce({ssrSessionId:e.ssrSessionId,apiKey:e.apiKey}),g=(a=s.getSessionId())!=null?a:"local",b=rn(),x=import("@sentientui/core/local").then(i=>{let l=i;return l.LOCAL_ENGINE_AVAILABLE?($t||($t=!0,console.info(jt)),l):(_e||(_e=!0,console.error(tt)),null)}).catch(()=>(_e||(_e=!0,console.error(tt)),null)),m=null,_={low:.15,medium:.5,high:.85},n=(()=>{var l;if(e.initialPersona)return v({},e.initialPersona);let i=pe(e.apiKey||"local");return i?{persona:i.persona,confidence:(l=_[i.band])!=null?l:.15}:null})();function u(i){let l=document.documentElement;l.dataset.sentientPersona===void 0&&(l.dataset.sentientPersona=i.persona,l.dataset.sentientConfidence=et(i.confidence))}return{isLocal:!0,async decide(i){var A,L,K;let l=await x;if(!l)return null;let w=l.createLocalEngine({sessionId:g,forcedPersona:b}).decide(i);return m=te(v({},w),{layoutOrder:(L=(A=w.layoutOrder)!=null?A:m==null?void 0:m.layoutOrder)!=null?L:null,slots:v(v({},(K=m==null?void 0:m.slots)!=null?K:{}),w.slots)}),ge(e.apiKey||"local",{v:1,persona:m.persona,band:et(m.confidence),slots:m.slots,layoutOrder:m.layoutOrder,savedAt:Date.now()}),u(w),w},getSlotResult(i){var l,w,A;return(A=(w=m==null?void 0:m.slots[i])!=null?w:(l=e.initialSlots)==null?void 0:l[i])!=null?A:null},getSlotConfig(i){var l,w;return(w=(l=e.initialSlotConfig)==null?void 0:l[i])!=null?w:null},getSitePalette(){var i;return(i=e.initialPalette)!=null?i:null},reportSlots(){},getVisitorId:()=>null,getPersona(){let i=m!=null?m:n;return i?{persona:i.persona,confidence:i.confidence,band:et(i.confidence)}:null},async assign(i,l){var L;let w=await x;return!w||!l||l.length===0?l!=null&&l[0]?{variantId:l[0],assignmentTtlMs:0}:null:{variantId:(L=w.createLocalEngine({sessionId:g,forcedPersona:b}).decide({components:[{id:i,variantIds:l}]}).assignments[i])!=null?L:l[0],assignmentTtlMs:0}},track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},getAssignment:()=>null,fetchWeights:()=>Promise.resolve([]),getGraph:()=>({pageNodes:[],capturedAt:0}),flush:()=>{},dispose:()=>{},destroy:()=>s.destroy()}}var Wt=/^(\*|\/[^\s?#*]*(\/\*)?)$/;function nt(e){let s=e.split(/[?#]/)[0]||"/";return s.length>1?s.replace(/\/+$/,"")||"/":s}function an(e,s){if(e===void 0||!Wt.test(e))return!1;if(e==="*")return!0;let g=nt(s);if(e.endsWith("/*")){let b=nt(e.slice(0,-2));return g.startsWith(b==="/"?"/":`${b}/`)&&g!==b}return g===nt(e)}function ln(e,s){if(!e)return!1;if(e==="/")return s==="/";let g=e.endsWith("/")?e.slice(0,-1):e;return s===g||s.startsWith(`${g}/`)}function cn(e){if(!/^https?:\/\//i.test(e))return e;try{return new URL(e).pathname||"/"}catch(s){return e}}var Ln=["none","sm","md","lg"],Mn=["start","center","end","stretch"],Kn=["start","center","end","between"],Nn=["sm","md","lg"],Gn=["normal","medium","bold"],$n=["default","muted","accent"],jn=["primary","secondary","ghost"],Un=["left","center","right"],Wn=["auto","square","landscape","wide"],Fn=["cover","contain"],Vn=[2,3,4],Hn=[1,2,3,4],zn=["default","raised"],qn=["none","sm","md","lg"],Jn=["measure"],Xn=["input","textarea","select"],Yn=["text","email","number","tel"],Qn=5,Zn=8,eo=64,to=5,no=12,oo=4,so=500;function dn(e){if(e==null||typeof e!="object"||Array.isArray(e))return!1;let s=e;return s.type==="form"?!0:Array.isArray(s.children)?s.children.some(dn):!1}var ot="sentient-reveal",ae="sentient-revealed",Ft=240,Re=!1;function un(){var e;Re=!1,typeof document!="undefined"&&((e=document.getElementById(ot))==null||e.remove())}function pn(e){if(Re||e.getElementById(ot)){Re=!0;return}let s=Xe(e.createElement("style"),e);s.id=ot,s.textContent=`@media (prefers-reduced-motion: no-preference){@keyframes ${ae}{from{opacity:.55;transform:translateY(2px)}to{opacity:1;transform:none}}.${ae}{animation:${ae} ${Ft}ms cubic-bezier(.2,.6,.2,1) both}}`,e.head.appendChild(s),Re=!0}function gn(e,s={}){var x;let g=(x=s.doc)!=null?x:typeof document!="undefined"?document:void 0;if(!g||!(e instanceof Element)||(s.arm!==void 0&&e.setAttribute("data-sentient-arm",s.arm),s.persona!==void 0&&e.setAttribute("data-sentient-persona",s.persona),s.previous!==void 0&&s.previous===e.textContent))return!1;pn(g),e.classList.remove(ae),e.offsetWidth,e.classList.add(ae);let b=()=>{e.classList.remove(ae),e.removeEventListener("animationend",b)};return e.addEventListener("animationend",b),!0}function fn(e,s,g,b){let x=[];{let n=!1,u=[],a=()=>{if(n)return;let i=Date.now();for(u.push(i);u.length>0&&i-u[0]>500;)u.shift();u.length>=3&&(n=!0,e("rage_click"))};s.addEventListener("click",a),x.push(()=>s.removeEventListener("click",a))}{let m=!1,_=n=>{if(m||!(n.target instanceof Node)||!s.contains(n.target)&&s!==n.target)return;m=!0;let u=typeof window!="undefined"?window.getSelection():null,a=u?u.toString().length:0;e("text_copy",{selectionLength:a})};document.addEventListener("copy",_),x.push(()=>document.removeEventListener("copy",_))}{let m=!1,_=!1,n=null,u=()=>{n!==null&&(clearTimeout(n),n=null)},a=()=>{m||!_||(u(),n=setTimeout(()=>{!m&&_&&(m=!0,e("scroll_hesitation"))},3e3))},i=()=>{u(),a()},l=A=>{for(let L of A)_=L.intersectionRatio>.3,_?a():u()},w=new IntersectionObserver(l,{threshold:[.3]});w.observe(s),window.addEventListener("scroll",i,{passive:!0}),x.push(()=>{w.disconnect(),window.removeEventListener("scroll",i),u()})}if((b==null?void 0:b.tabLoss)!==!1){let m=!1,_=g!=null?g:Date.now(),n=()=>{if(m||document.visibilityState!=="hidden")return;let u=Date.now()-_;u<15e3&&(m=!0,e("tab_loss",{timeOnPage:u}))};document.addEventListener("visibilitychange",n),x.push(()=>document.removeEventListener("visibilitychange",n))}return()=>{for(let m of x)m()}}function mn(){var e;return typeof process=="undefined"||((e=process.env)==null?void 0:e.NODE_ENV)!=="production"}var Jt="https://api.sentient-ui.com/v1/events",zt=()=>import("@sentientui/core/internal-traffic"),F=new Map,Xt=null;function Go(e,s){let g=F.get(e);g&&g.upgrade&&(g.reinit=s)}function yn(e){return"value"in e||"currency"in e||"externalId"in e||"metadata"in e||"weight"in e||"stepIndex"in e}var Sn=3;function rt(){return Kt()}function Ae(){var e;if(typeof window!="undefined")return((e=window.location)==null?void 0:e.pathname)||void 0}function hn(){let e=new WeakMap,s=new Map,g=!1,b=(n,u,a)=>{let i=n.get(u);return a===null?i?!0:(n.set(u,new Set),!1):i?i.has(a)?!0:(i.add(a),!1):(n.set(u,new Set([a])),!1)},x=typeof window!="undefined"&&"event"in window,m=()=>{if(!x)return;let n=window.event;return typeof Event=="function"&&n instanceof Event?n:void 0},_=()=>{if(x){Promise.resolve().then(()=>{g=!1,s.clear()});return}let n=!1,u=()=>{n||(n=!0,g=!1,s.clear())};if(setTimeout(u,0),typeof MessageChannel=="function"){let a=new MessageChannel;a.port1.onmessage=()=>{a.port1.close(),a.port2.close(),u()},a.port2.postMessage(0)}};return{firedBefore(n,u){let a=m();if(a){let l=e.get(a);return l||(l=new Map,e.set(a,l)),b(l,n,u)}let i=b(s,n,u);return!i&&!g&&(g=!0,_()),i}}}var Yt=new Set;function kn(e,s,g){let b=typeof window=="undefined"?null:window.history;if(!b)return()=>{};let x=!1,m,_=()=>{if(x)return;let a=Ae();!a||a===m||(m=a,e.track({projectId:s,componentId:"__page__",eventType:"pageview",payload:{}}),g(`${s}:${a}`))},n=[];for(let a of["pushState","replaceState"]){let i=b[a],l=function(...w){let A=i.apply(this,w);return _(),A};b[a]=l,n.push([a,i,l])}window.addEventListener("popstate",_);let u=Ae();return u&&Yt.has(`${s}:${u}`)?m=u:_(),()=>{if(!x){x=!0,window.removeEventListener("popstate",_);for(let[a,i,l]of n)b[a]===l&&(b[a]=i)}}}var fe={track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},getAssignment:()=>null,assign:()=>Promise.resolve(null),decide:()=>Promise.resolve(null),getSlotResult:()=>null,getSlotConfig:()=>null,getSitePalette:()=>null,reportSlots:()=>{},getPersona:()=>null,getVisitorId:()=>null,fetchWeights:()=>Promise.resolve([]),getGraph:()=>({pageNodes:[],capturedAt:0}),flush:()=>{},dispose:()=>{},destroy:()=>{}};function bn(){try{return Fe(window.location.search)}catch(e){return{utmParams:{},clickIds:{}}}}function Qt(e){return e.replace(/\/events\/?$/,"")}function Zt(){return typeof navigator!="undefined"&&navigator.globalPrivacyControl===!0?!0:[typeof navigator!="undefined"?navigator.doNotTrack:void 0,typeof window!="undefined"?window.doNotTrack:void 0,typeof navigator!="undefined"?navigator.msDoNotTrack:void 0].some(s=>s==="1"||s==="yes")}function $o(e){var u;if(typeof window=="undefined")return;let s=e!=null?e:Xt;if(!s){console.warn("[sentient] grantConsent() called before init()");return}let g=F.get(s);if(!g){console.warn("[sentient] grantConsent() called before init()");return}let{config:b,upgrade:x,reinit:m}=g;if(!x){g.upgradeBlockedReason&&console.warn(g.upgradeBlockedReason);return}if(b.respectDoNotTrack!==!1&&Zt())return;let _=(m!=null?m:wn)(te(v({},b),{consent:!0}));x(_);let n=(u=F.get(s))==null?void 0:u.dispose;F.set(s,{config:te(v({},b),{consent:!0}),upgrade:null,dispose:n})}function vn(e,s){var ye;let g=e.preConsentBehavior==="statistical_winner",b=Qt((ye=e.ingestUrl)!=null?ye:Jt),x={"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`},m=new Map,_=new Map,n={track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},getAssignment:()=>null,fetchWeights:()=>Promise.resolve([]),assign(r,c,E){if(!g)return Promise.resolve(null);let T=m.get(r);return T?Promise.resolve(T):at(_,r,async()=>{try{let I=new URLSearchParams({componentId:r});for(let q of c!=null?c:[])I.append("variantIds[]",q);let G=ie(5e3),W;try{let q=await fetch(`${b}/winner?${I.toString()}`,{headers:x,signal:G.signal});if(!q.ok)return c!=null&&c[0]?{variantId:c[0],assignmentTtlMs:0}:null;W=await q.json()}finally{G.clear()}let $={variantId:W.variantId,assignmentTtlMs:0};return m.set(r,$),$}catch(I){return c!=null&&c[0]?{variantId:c[0],assignmentTtlMs:0}:null}})},decide:()=>Promise.resolve(null),getSlotResult:()=>null,getSlotConfig:()=>null,getSitePalette:()=>null,reportSlots:()=>{},getPersona:()=>null,getVisitorId:()=>null,getGraph:()=>({pageNodes:[],capturedAt:0}),flush:()=>{},dispose:()=>{},destroy:()=>{}},u=!1,a=new Set,i=[],l=[],w=[],A=()=>{for(let[,,r]of w.splice(0))r(null);L.length=0},L=[],K=!1,ee=()=>{if(u)return;K=!0;let r=F.get(e.apiKey);(r==null?void 0:r.upgrade)===le&&F.set(e.apiKey,{config:e,upgrade:null,upgradeBlockedReason:"[sentient] grantConsent(): client released before consent; call init() again"})},N=[],V=()=>{setTimeout(()=>{var r;try{(r=N.shift())==null||r(n)}catch(c){}N.length&&V()})},me=r=>{u?N.length?N.push(r):r(n):!s&&!K&&L.length<100?L.push(r):K&&e.debug&&console.warn("[sentient] goal dropped: client released")},se={get gated(){return!u&&!s},get released(){return K&&!u},takeHeld:()=>L.splice(0),track:r=>n.track(r),goal:((r,c,E,T)=>me(I=>I.goal(r,c,E,T))),componentGoal:(r,c,E)=>n.componentGoal(r,c,E),identify:(r,c)=>n.identify(r,c),getAssignment:(r,c)=>n.getAssignment(r,c),isUnified:r=>{var c,E;return(E=(c=n.isUnified)==null?void 0:c.call(n,r))!=null?E:!1},assign:(r,c,E,T,I)=>n.assign(r,c,E,T,I),decide:r=>u?n.decide(r):K||s?Promise.resolve(null):new Promise(c=>w.push([r,qt(),c])),getSlotResult:r=>n.getSlotResult(r),isSlotDecided:r=>{var c,E;return(E=(c=n.isSlotDecided)==null?void 0:c.call(n,r))!=null?E:!0},getSlotConfig:r=>n.getSlotConfig(r),getSitePalette:()=>n.getSitePalette(),getStyleVocabulary:()=>{var r,c;return(c=(r=n.getStyleVocabulary)==null?void 0:r.call(n))!=null?c:null},reportSlots:(r,c,E,T)=>n.reportSlots(r,c,E,T),reportSkeleton:(r,c)=>{var E;return(E=n.reportSkeleton)==null?void 0:E.call(n,r,c)},reportAgentData:(r,c,E)=>{var T;return(T=n.reportAgentData)==null?void 0:T.call(n,r,c,E)},reportDrift:(r,c,E,T)=>{var I;return(I=n.reportDrift)==null?void 0:I.call(n,r,c,E,T)},requestSlots:(r,c,E)=>{var T;return u?(T=n.requestSlots)==null?void 0:T.call(n,r,c,E):i.push([r,c,E])},decideSlots:r=>{var c;return u?(c=n.decideSlots)==null?void 0:c.call(n,r):l.push(...r)},cancelSlots:r=>{var E;if(u)return(E=n.cancelSlots)==null?void 0:E.call(n,r);let c=new Set(r);for(let T of i)T[0]=T[0].filter(I=>!c.has(I));l=l.filter(T=>!c.has(T.id))},onSlotsChanged:r=>(a.add(r),()=>{a.delete(r)}),getPersona:()=>n.getPersona(),getVisitorId:()=>{var r,c;return(c=(r=n.getVisitorId)==null?void 0:r.call(n))!=null?c:null},fetchWeights:()=>n.fetchWeights(),getGraph:()=>n.getGraph(),flush:()=>n.flush(),dispose:()=>(ee(),A(),n.dispose()),destroy:()=>(ee(),A(),u?n.destroy():Ge(e.apiKey))};function le(r){var E,T,I;n=r,u=!0,L.length&&(N.push(...L.splice(0)),V());let c=qt();for(let[G,W,$]of w.splice(0))W!==c?$(null):r.decide(G).then($,()=>$(null));(E=r.onSlotsChanged)==null||E.call(r,()=>a.forEach(G=>G()));for(let[G,W,$]of i.splice(0))G.length>0&&((T=r.requestSlots)==null||T.call(r,G,W,$));l.length>0&&((I=r.decideSlots)==null||I.call(r,l.splice(0)))}return{proxy:se,setInner:le}}function qt(){return typeof location=="undefined"?"":location.pathname+(/^#!?\//.test(location.hash)?location.hash:"")}function at(e,s,g){let b=e.get(s);if(b)return b;let x=(async()=>{try{return await g()}finally{e.delete(s)}})();return e.set(s,x),x}function wn(e){var ht,kt,bt,vt,wt,Et,Ct,xt,It,_t,Rt;if(typeof window=="undefined")return fe;e.nonce&&Je(e.nonce),Xt=e.apiKey||"local";let s=F.get(e.apiKey||"local");if(s!=null&&s.dispose)try{s.dispose()}catch(t){}let g=e.respectDoNotTrack!==!1&&Zt(),b=e.consent===!1||g,x=typeof e.apiKey=="string"&&e.apiKey.startsWith("pk_");if(e.localMode===!0||!x&&e.localMode!==!1)return F.set(e.apiKey||"local",{config:e,upgrade:null,upgradeBlockedReason:"[sentient] grantConsent(): this client is keyless/local \u2014 there is no hosted client to upgrade to. Configure a pk_ API key to enable tracking."}),b?fe:Ut(e);if(b){if(!e.apiKey||!e.apiKey.startsWith("pk_"))return e.preConsentBehavior==="statistical_winner"&&console.warn("[sentient] init() called with an invalid apiKey \u2014 expected a pk_ public key. SDK disabled."),F.set(e.apiKey||"local",{config:e,upgrade:null,upgradeBlockedReason:"[sentient] grantConsent(): the client was initialized with an invalid apiKey (expected a pk_ public key) \u2014 consent cannot enable tracking."}),fe;let{proxy:t,setInner:o}=vn(e,g);return F.set(e.apiKey,{config:e,upgrade:g?null:o}),t}if(!e.apiKey||!e.apiKey.startsWith("pk_"))return console.warn("[sentient] init() called with an invalid apiKey \u2014 expected a pk_ public key. SDK disabled."),fe;if(e.ingestUrl==="")return console.warn("[sentient] init() called with an empty ingestUrl. SDK disabled."),fe;let m=(ht=e.ingestUrl)!=null?ht:Jt,_=Date.now(),n=Ce({ssrSessionId:e.ssrSessionId,apiKey:e.apiKey,cookieDomain:e.cookieDomain}),u={},a;try{/sentient_internal=/.test(location.search+document.cookie)&&(a=zt().then(async t=>{u.internalToken=await t.takeInternalToken(n.domain)||void 0}).catch(()=>{})),(typeof e.internal=="function"?e.internal():e.internal)===!0&&(u.internal=!0)}catch(t){}let i=Gt(void 0,e.apiKey),l=!1,w=we(e.apiKey),A=()=>!l&&we(e.apiKey)===w,L=new Set((kt=e.initialUnified)!=null?kt:[]),K=te(v({},i),{get:(t,o)=>L.has(t)?null:i.get(t,o),set:(...t)=>{A()&&i.set(...t)}}),ee=Bt({ingestUrl:m,apiKey:e.apiKey}),N=Qt(m),V={"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`},me=new Set,se=Mt({url:`${N}/goals`,apiKey:e.apiKey,headers:V,onDrop:(t,o)=>{if(!e.debug){if(me.has(o))return;me.add(o)}console.warn(`[sentient] goal dropped (HTTP ${o}) \u2014 this will not be retried. `+(o===400?"The session was not found: call init() and let the session upsert complete before firing goals.":o===401||o===403?"Check the API key and that this origin is on the project allowlist.":"See the response status for the cause."),t)}}),le=je((bt=navigator.userAgent)!=null?bt:""),ye=window.location.origin,r=Ue((vt=document.referrer)!=null?vt:"",ye,n.domain),c=(wt=e.sessionSegment)!=null?wt:`${le}:${r}`,E=new Map,T=new Map,I=new Map,G=new Set,W=new Map,$=null,q=null,j=null,lt=new Set,Se=new Set,Te=new Map,Oe=new Map,ct=new Set,dt=new Set,ut=new Set,pt=new Set,De=null,ce=/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,127}$/,gt=new Set,he=new Set,ke=new Set,de=new Map,Pe=null,be=new Set,ue=new Map,Be=null,en=2,ft=new Map,X=!1,mt=(t,o,d)=>{var p;let S=new Set,k=1;for(let f of t){o.delete(f);let y=((p=ft.get(f))!=null?p:0)+1;ft.set(f,y),y<=en&&(S.add(f),y>k&&(k=y))}S.size>0&&setTimeout(()=>{X||d(S)},Ne(k))},Le=t=>{for(let o of t)I.has(o.id)||I.set(o.id,xe(o))};if(e.initialSlots)for(let[t,o]of Object.entries(e.initialSlots))I.set(t,o),G.add(t);if(e.initialSlotConfig)for(let[t,o]of Object.entries(e.initialSlotConfig))W.set(t,o);e.initialPalette&&($=e.initialPalette),e.initialVocabulary&&(q=e.initialVocabulary);let Y=pe(e.apiKey);if(Y){for(let[t,o]of Object.entries(Y.slots))I.has(t)||I.set(t,o);for(let[t,o]of Object.entries((Et=Y.slotConfig)!=null?Et:{}))W.has(t)||W.set(t,o);!$&&Y.palette&&($=Y.palette),!q&&Y.vocabulary&&(q=Y.vocabulary)}let yt={low:.15,medium:.5,high:.85};if(e.initialPersona)j=v({},e.initialPersona);else{let t=document.documentElement.dataset;t.sentientPersona?j={persona:t.sentientPersona,confidence:(xt=yt[(Ct=t.sentientConfidence)!=null?Ct:"low"])!=null?xt:.15}:Y&&(j={persona:Y.persona,confidence:(It=yt[Y.band])!=null?It:.15})}if(e.initialAssignments)for(let[t,o]of Object.entries(e.initialAssignments))K.set(t,c,{variantId:o,assignedAt:Date.now(),segment:c,confidence:1});let ne=Promise.resolve(),St=n.getSessionId();if(St){let t=We((_t=document.referrer)!=null?_t:""),{utmParams:o,clickIds:d}=bn(),S=v(v(v(v({sessionId:St,deviceClass:le,trafficSource:r,referrerDomain:t,utmParams:o,clickIds:d,landingPath:typeof location!="undefined"?location.pathname:void 0,timeOfDay:Ve(new Date),dayOfWeek:["sun","mon","tue","wed","thu","fri","sat"][new Date().getDay()],ephemeral:n.isEphemeral(),automation:typeof navigator!="undefined"&&navigator.webdriver===!0||$e((Rt=navigator.userAgent)!=null?Rt:"")},e.userId?{userId:e.userId}:{}),e.persona?{persona:e.persona}:{}),e.country?{country:e.country}:{}),e.sdk?{sdk:e.sdk.name,sdkVersion:e.sdk.version}:{}),k=async()=>{a&&await Ee(a,2500);for(let p=0;;p++){if(X||!A())return;let f=ie(5e3);try{let y=await fetch(`${N}/sessions`,{method:"POST",keepalive:!0,body:JSON.stringify(Object.assign(S,u)),headers:V,signal:f.signal});if(y.status===402){console.warn("[SentientUI] Session limit exceeded for this project. The bandit will stop learning until the limit resets. Upgrade at sentient-ui.com/pricing");return}if(y.ok||Dt(y)==="dropped")return}catch(y){}finally{f.clear()}if(p>=Sn){console.warn("[SentientUI] Could not register the session after retries. Conversions in this visit may not be recorded.");return}await new Promise(y=>setTimeout(y,Ne(p+1)))}};try{ne=k()}catch(p){}}e.debug&&(console.log("[sentient] initialized",{context:e.context}),window.__sentient={client:null,queue:ee});let tn=hn(),oe=null,Me=!1,M={goal(t,o={},d=1,S=0){var B,R,H,J,z,U,h;let k=n.getSessionId();if(!k||X||!A())return;let p=yn(o)?o:{metadata:o},f=[t,(B=p.externalId)!=null?B:"",(R=p.stepIndex)!=null?R:S,(H=p.weight)!=null?H:d].join("\0"),y=p.value!==void 0?`${p.value}\0${(J=p.currency)!=null?J:""}`:null;if(tn.firedBefore(f,y)){e.debug&&console.log(`[sentient] goal("${t}") already recorded for this action \u2014 not sent twice`);return}let O=rt(),C={sessionId:k,name:t,metadata:(z=p.metadata)!=null?z:{},weight:(U=p.weight)!=null?U:d,stepIndex:(h=p.stepIndex)!=null?h:S,goalId:O,value:p.value,currency:p.currency,externalId:p.externalId};e.debug&&console.log("[sentient] goal",C);let D={id:O,body:JSON.stringify(C)};ne.then(()=>se.send(D))},componentGoal(t,o,d){var O,C,D;let S=n.getSessionId();if(!S||X||!A())return;let k=K.get(t,c),p=k?null:(O=I.get(t))!=null?O:null;if(!k&&p===null){e.debug&&console.warn(`[sentient] componentGoal("${t}"): no assignment or slot decision yet \u2014 render its <Adaptive>/adaptive hook or call assign()/decide() before recording a goal.`);return}if(!k&&!G.has(t)){e.debug&&console.warn(`[sentient] componentGoal("${t}"): slot not decided this session \u2014 not attributed`);return}let f=k?k.variantId:ze(p),y={id:rt(),sessionId:S,projectId:e.apiKey,componentId:t,variantId:f,eventType:"goal_achieved",goalType:o,payload:v({reward:(C=d==null?void 0:d.reward)!=null?C:1,goalValue:d==null?void 0:d.value,currency:d==null?void 0:d.currency},(D=d==null?void 0:d.metadata)!=null?D:{}),timestamp:Date.now(),timeInSession:Date.now()-_,path:Ae()};e.debug&&console.log("[sentient] componentGoal",y),ne.then(()=>{!X&&A()&&ee.push(y)})},identify(t,o){let d=n.getSessionId();if(!d||X||!A())return;let S=(o==null?void 0:o.email)!==void 0?zt().then(k=>k.emailFields(o.email)).catch(()=>({})):{};Promise.all([ne,S]).then(([,k])=>{fetch(`${N}/sessions`,{method:"POST",keepalive:!0,body:JSON.stringify(te(v(v({sessionId:d,userId:t,userHash:o==null?void 0:o.userHash},k),u),{ephemeral:n.isEphemeral()})),headers:V}).catch(()=>{})})},track(t){let o=n.getSessionId();if(!o||X||!A()||t.eventType==="variant_assigned"&&I.get(t.componentId)!==void 0&&!G.has(t.componentId)&&!K.get(t.componentId,c))return;let d=te(v({path:Ae()},t),{id:rt(),sessionId:o,timestamp:Date.now(),timeInSession:Date.now()-_});e.debug&&console.log("[sentient] track",d),ne.then(()=>ee.push(d))},getAssignment(t,o){return K.get(t,o)},isUnified:t=>L.has(t),async assign(t,o,d,S,k){var O;let p=n.getSessionId();if(!p)return null;let f=(k==null?void 0:k.unified)===!0;if(f&&L.has(t))return{variantId:(O=o==null?void 0:o[0])!=null?O:"",assignmentTtlMs:0,unified:!0};let y=K.get(t,c);if(y&&(o!=null&&o.length||y.content!==void 0)){let C=y.ttlMs&&y.ttlMs>0?Math.max(0,y.assignedAt+y.ttlMs-Date.now()):0;return{variantId:y.variantId,assignmentTtlMs:C,content:y.content}}return at(E,f?`${t}\0unified`:t,async()=>{if(!await Ee(ne,2500)||X||!A())return null;let C=ie(3e4);try{let D={sessionId:p,componentId:t,variantIds:o};S!==void 0?D.agentDataByVariant=S:d!==void 0&&(D.agentData=d),f&&(D.caps={unified:!0});let B=await fetch(`${N}/assign`,{method:"POST",body:JSON.stringify(D),headers:V,signal:C.signal});if(!B.ok)return null;let R=await B.json();return R.unified===!0?f?(L.add(t),{variantId:R.variantId,assignmentTtlMs:0,unified:!0}):null:(K.set(t,c,v({variantId:R.variantId,assignedAt:Date.now(),segment:c,confidence:1,content:R.content},R.assignmentTtlMs&&R.assignmentTtlMs>0?{ttlMs:R.assignmentTtlMs}:{})),R)}catch(D){return null}finally{C.clear()}})},async decide(t){var p,f;let o=n.getSessionId();if(!o)return null;let d=(p=t.slots)!=null?p:[],S={sessionId:o};t.sections&&t.sections.length>0&&(S.sections=t.sections.map(y=>({id:y}))),S.components=(f=t.components)!=null?f:[],d.length>0&&(S.slots=d.map(He)),t.slotsFrom==="registry"&&(S.slotsFrom="registry",t.registrySlotIds&&(S.registrySlotIds=t.registrySlotIds),t.bootstrap===!1&&(S.bootstrap=!1),t.render&&Object.keys(t.render).length>0&&(S.render=t.render)),t.v&&(S.v=t.v),typeof t.pp=="number"&&(S.pp=t.pp),e.persona&&(S.persona=e.persona),Object.assign(S,u);let k=JSON.stringify(S);return at(T,k,async()=>{var O,C,D,B,R,H,J,z;if(!await Ee(ne,2500)||X||!A())return Le(d),null;let y=ie(3e4);try{let U=await fetch(`${N}/decide`,{method:"POST",body:k,headers:V,signal:y.signal});if(!U.ok)return Le(d),null;let h=await U.json(),Q=Qe(h.stage,e.stageAttributes);e.stageAttributes&&Ze(Q);let re={};for(let P of d){let Z=(O=h.slots)==null?void 0:O[P.id];if(Z!==void 0){re[P.id]=Z,I.set(P.id,Z),G.add(P.id);continue}let At=I.get(P.id);if(At!==void 0)re[P.id]=At;else{let Tt=xe(P);re[P.id]=Tt,I.set(P.id,Tt)}}if(h.slots)for(let[P,Z]of Object.entries(h.slots))P in re||(re[P]=Z,I.set(P,Z),G.add(P));let nn=j!=null&&j.persona!=="unknown";h.persona&&!(h.persona==="unknown"&&nn)?j={persona:h.persona,confidence:(C=h.confidence)!=null?C:0}:j||(j={persona:"unknown",confidence:0});for(let[P,Z]of Object.entries((D=h.assignments)!=null?D:{}))K.set(P,c,{variantId:Z,assignedAt:Date.now(),segment:c,confidence:1});if(h.slotConfig)for(let[P,Z]of Object.entries(h.slotConfig))W.set(P,Z);h.palette&&($=h.palette),h.vocabulary&&(q=h.vocabulary);for(let P of(B=t.registrySlotIds)!=null?B:[])(R=h.slotConfig)!=null&&R[P]||(W.delete(P),I.delete(P),G.delete(P));return A()&&ge(e.apiKey,v(v(v(v({v:1,persona:j.persona,band:Ht(j.confidence),slots:Object.fromEntries(I),layoutOrder:(H=h.layoutOrder)!=null?H:null,savedAt:Date.now()},W.size>0?{slotConfig:Object.fromEntries(W)}:{}),$?{palette:$}:{}),q?{vocabulary:q}:{}),Q?{stage:Q}:{})),v(v(v(v(v(v(v({layoutOrder:(J=h.layoutOrder)!=null?J:null,assignments:(z=h.assignments)!=null?z:{},slots:re,persona:j.persona,confidence:j.confidence},h.slotConfig?{slotConfig:h.slotConfig}:{}),h.goals?{goals:h.goals}:{}),h.sectionMap?{sectionMap:h.sectionMap}:{}),h.palette?{palette:h.palette}:{}),h.vocabulary?{vocabulary:h.vocabulary}:{}),h.stage?{stage:h.stage}:{}),h.context?{context:h.context}:{})}catch(U){return Le(d),null}finally{y.clear()}})},getSlotResult(t){var o;return(o=I.get(t))!=null?o:null},isSlotDecided(t){return G.has(t)},getSlotConfig(t){var o;return(o=W.get(t))!=null?o:null},reportSlots(t,o,d,S){var p;let k={};for(let[f,y]of Object.entries(S!=null?S:{}))for(let O of y){let C=`${f}|${O.key}`;!ce.test(f)||ut.has(C)||(ut.add(C),((p=k[f])!=null?p:k[f]=[]).push(O))}Object.keys(k).length>0&&fetch(`${N}/slots/observed`,{method:"POST",headers:V,body:JSON.stringify({slotIds:Object.keys(k),authoredArms:k})}).catch(()=>{});for(let f of t)if(!(typeof f!="string"||f.length===0)){if(!ce.test(f)){mn()&&!gt.has(f)&&(gt.add(f),console.warn(`[sentient] reportSlots: slot id ${JSON.stringify(f)} will not register \u2014 ids must start with a letter or digit and contain only letters, digits, '_' or '-' (max 128 chars): /^[a-zA-Z0-9][a-zA-Z0-9_-]{0,127}$/.`));continue}if(!lt.has(f)){lt.add(f),Se.add(f);let y=o==null?void 0:o[f];if(typeof y=="string"){let C=y.replace(/\s+/g," ").trim().slice(0,400);C!==""&&Te.set(f,C)}let O=d==null?void 0:d[f];O!==void 0&&Oe.set(f,O)}}Se.size===0||De!=null||(De=setTimeout(()=>{De=null;let f=[...Se];Se.clear();for(let y=0;y<f.length;y+=20){let O=f.slice(y,y+20),C={},D={};for(let B of O){let R=Te.get(B);R!==void 0&&(C[B]=R,Te.delete(B));let H=Oe.get(B);H!==void 0&&(D[B]=H,Oe.delete(B))}fetch(`${N}/slots/observed`,{method:"POST",headers:V,body:JSON.stringify(v(te(v(v({slotIds:O},Object.keys(C).length>0?{baselineTexts:C}:{}),Object.keys(D).length>0?{baselineSkeletons:D}:{}),{pagePaths:Object.fromEntries(O.map(B=>[B,location.pathname]))}),Object.keys(C).length>0&&n.getSessionId()?{sessionId:n.getSessionId()}:{}))}).catch(()=>{})}},1e3))},reportSkeleton(t,o){!ce.test(t)||ct.has(t)||(ct.add(t),fetch(`${N}/slots/observed`,{method:"POST",headers:V,body:JSON.stringify({slotIds:[t],baselineSkeletons:{[t]:o}})}).catch(()=>{}))},reportAgentData(t,o,d){let S=`${t}|${o}`;!ce.test(t)||pt.has(S)||(pt.add(S),fetch(`${N}/slots/observed`,{method:"POST",headers:V,body:JSON.stringify(v(v({slotIds:[t],agentData:{[t]:{[o]:d}}},o.startsWith("authored.")?{authoredArms:{[t]:[{key:o.slice(9)}]}}:{}),n.getSessionId()?{sessionId:n.getSessionId()}:{}))}).catch(()=>{}))},reportDrift(t,o,d,S){let k=`${t}|${o}`,p=n.getSessionId();!p||dt.has(k)||(dt.add(k),fetch(`${N}/slots/drift`,{method:"POST",headers:V,body:JSON.stringify({sessionId:p,reports:[{slotId:t,expectedFp:o,observedFp:d,reason:S}]})}).catch(()=>{}))},requestSlots(t,o,d){var S,k;for(let p of t)ke.has(p)||(ke.add(p),ce.test(p)?de.set(p,{text:o==null?void 0:o[p],render:(S=d==null?void 0:d.render)==null?void 0:S[p],skeleton:(k=d==null?void 0:d.skeletons)==null?void 0:k[p]}):M.reportSlots([p]));de.size===0||Pe!=null||(Pe=setTimeout(()=>{Pe=null;let p=[...de];de.clear();for(let f=0;f<p.length;f+=50){let y=p.slice(f,f+50),O={};for(let[C,D]of y)D.render&&(O[C]=D.render);M.decide({slotsFrom:"registry",registrySlotIds:y.map(([C])=>C),bootstrap:!1,render:O}).then(C=>{var D,B;if(C){let R={},H={},J=[];for(let[z,U]of y){let h=(D=C.slotConfig)==null?void 0:D[z];if(h){h.needsSkeleton&&U.skeleton&&((B=M.reportSkeleton)==null||B.call(M,z,U.skeleton));continue}J.push(z),U.text&&(R[z]=U.text),U.skeleton&&(H[z]=U.skeleton)}J.length>0&&M.reportSlots(J,R,H)}else mt(y.map(([R])=>R),ke,R=>{var U;let H={},J={},z={};for(let[h,Q]of y)R.has(h)&&(Q.text&&(H[h]=Q.text),Q.render&&(J[h]=Q.render),Q.skeleton&&(z[h]=Q.skeleton));(U=M.requestSlots)==null||U.call(M,[...R],H,{render:J,skeletons:z})});he.forEach(R=>R())})}},0))},decideSlots(t){for(let o of t)be.has(o.id)||(be.add(o.id),ue.set(o.id,o));ue.size===0||Be!=null||(Be=setTimeout(()=>{Be=null;let o=[...ue.values()];ue.clear();for(let d=0;d<o.length;d+=30){let S=o.slice(d,d+30);M.decide({slots:S}).then(k=>{k||mt(S.map(p=>p.id),be,p=>{var f;return(f=M.decideSlots)==null?void 0:f.call(M,S.filter(y=>p.has(y.id)))}),he.forEach(p=>p())})}},0))},cancelSlots(t){for(let o of t)de.delete(o)&&ke.delete(o),ue.delete(o)&&be.delete(o)},onSlotsChanged(t){return he.add(t),()=>{he.delete(t)}},getStyleVocabulary(){return q},getSitePalette(){return $},getVisitorId:()=>A()?n.getSessionId():null,getPersona(){return j?{persona:j.persona,confidence:j.confidence,band:Ht(j.confidence)}:null},async fetchWeights(){var o;let t=ie(5e3);try{let d=await fetch(`${N}/weights`,{headers:V,signal:t.signal});return d.ok?(o=(await d.json()).components)!=null?o:[]:[]}catch(d){return[]}finally{t.clear()}},getGraph(){return{pageNodes:[],capturedAt:0}},flush(){ee.flush(),se.flush()},dispose(){var t;oe==null||oe(),Me=!0,X=!0,ee.destroy(),se.destroy(),((t=F.get(e.apiKey))==null?void 0:t.dispose)===M.dispose&&F.delete(e.apiKey),e.debug&&console.log("[sentient] disposed")},destroy(){var t;oe==null||oe(),Me=!0,X=!0,l=!0,Ot(e.apiKey),ee.destroy({forget:!0}),se.destroy({forget:!0}),n.destroy(),K.clear(),((t=F.get(e.apiKey))==null?void 0:t.dispose)===M.dispose&&F.delete(e.apiKey);try{localStorage.removeItem(Ke+e.apiKey),localStorage.removeItem(Pt(e.apiKey)),localStorage.removeItem(Lt(e.apiKey)),localStorage.removeItem(`_snt_graph_nodes${ve(e.apiKey)}`),localStorage.removeItem("_snt_graph_edges")}catch(o){}e.debug&&console.log("[sentient] destroyed")}};if(F.set(e.apiKey,{config:e,upgrade:null,dispose:M.dispose}),oe=kn(M,e.apiKey,t=>{ne.then(()=>{Me||Yt.add(t)})}),e.debug){let t=window;t.__sentient&&(t.__sentient.client=M)}return M}export{Je as a,Nt as b,Xe as c,Ye as d,Qe as e,Ze as f,tt as g,jt as h,Wt as i,an as j,ln as k,cn as l,Ln as m,Mn as n,Kn as o,Nn as p,Gn as q,$n as r,jn as s,Un as t,Wn as u,Fn as v,Vn as w,Hn as x,zn as y,qn as z,Jn as A,Xn as B,Yn as C,Qn as D,Zn as E,eo as F,to as G,no as H,oo as I,so as J,dn as K,Ft as L,un as M,gn as N,fn as O,Go as P,Zt as Q,$o as R,qt as S,wn as T};
|
|
2
|
+
//# sourceMappingURL=chunk-QPJ6TL6L.mjs.map
|