@sentientui/core 0.37.0 → 0.39.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/README.md +43 -1
  2. package/dist/{chunk-NCLBL5V3.mjs → chunk-EVF5PQ4U.mjs} +1 -1
  3. package/dist/{chunk-NCLBL5V3.mjs.map → chunk-EVF5PQ4U.mjs.map} +1 -1
  4. package/dist/chunk-VE2K45X4.mjs +2 -0
  5. package/dist/chunk-VE2K45X4.mjs.map +1 -0
  6. package/dist/chunk-XZRKD2GS.mjs +2 -0
  7. package/dist/chunk-XZRKD2GS.mjs.map +1 -0
  8. package/dist/{index-C-meVCmm.d.cts → index-BAfi7_FG.d.cts} +90 -5
  9. package/dist/{index-DbpGK3Dj.d.ts → index-DyKtujwf.d.ts} +90 -5
  10. package/dist/index-consent.js.map +1 -1
  11. package/dist/index-consent.mjs +1 -1
  12. package/dist/index-engagement.js +1 -1
  13. package/dist/index-engagement.js.map +1 -1
  14. package/dist/index-engagement.mjs +1 -1
  15. package/dist/index-graph.d.cts +5 -5
  16. package/dist/index-graph.d.ts +5 -5
  17. package/dist/index-graph.js +1 -1
  18. package/dist/index-graph.js.map +1 -1
  19. package/dist/index-graph.mjs +1 -1
  20. package/dist/index-graph.mjs.map +1 -1
  21. package/dist/index-local.d.cts +3 -3
  22. package/dist/index-local.d.ts +3 -3
  23. package/dist/index-region.d.cts +1 -1
  24. package/dist/index-region.d.ts +1 -1
  25. package/dist/index-region.mjs +1 -1
  26. package/dist/index-server.d.cts +78 -5
  27. package/dist/index-server.d.ts +78 -5
  28. package/dist/index-server.js +1 -1
  29. package/dist/index-server.js.map +1 -1
  30. package/dist/index-server.mjs +1 -1
  31. package/dist/index-server.mjs.map +1 -1
  32. package/dist/index.d.cts +3 -3
  33. package/dist/index.d.ts +3 -3
  34. package/dist/index.js +1 -1
  35. package/dist/index.js.map +1 -1
  36. package/dist/index.mjs +1 -1
  37. package/dist/{region-skeleton-D2ahkcbe.d.cts → region-skeleton-BRIVB-qf.d.cts} +1 -0
  38. package/dist/{region-skeleton-D2ahkcbe.d.ts → region-skeleton-BRIVB-qf.d.ts} +1 -0
  39. package/dist/{session-meta-DlCp0tyi.d.ts → session-meta-BtRtwsHI.d.ts} +7 -2
  40. package/dist/{session-meta-CJ-QAskZ.d.cts → session-meta-qx4kIL5y.d.cts} +7 -2
  41. package/package.json +1 -1
  42. package/dist/chunk-5CCBWT6H.mjs +0 -2
  43. package/dist/chunk-5CCBWT6H.mjs.map +0 -1
  44. package/dist/chunk-DU3AXQHR.mjs +0 -2
  45. package/dist/chunk-DU3AXQHR.mjs.map +0 -1
package/README.md CHANGED
@@ -57,6 +57,7 @@ Reading a consent platform yourself: `import { consentWatcher } from '@sentientu
57
57
  | `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
58
  | `initialSlots` | `Record<string, string \| Record<string, string>>` | SSR-preloaded slot results (from `preloadDecisions`/`loadAdaptiveDecision`). |
59
59
  | `initialPersona` | `{ persona: string; confidence: number }` | SSR-preloaded persona, so client and server agree on first paint. |
60
+ | `initialUnified` | `string[]` | Component ids the SSR preload reported as moved onto the shared track (the `unified` field of `preloadAssignmentsDetailed` / `preloadDecisions`). Their cached assignments are ignored and the page renders them as slots. |
60
61
 
61
62
  ### `client.assign(componentId, variantIds?)` → `Promise<AssignResult | null>`
62
63
 
@@ -105,6 +106,10 @@ client.componentGoal('hero_headline', 'hero_contact', {
105
106
 
106
107
  No-ops (with a `debug` warning) if the component has not been assigned yet — render its `<Adaptive>` / call `assign()` first. Prefer this over a hand-rolled `client.track({ eventType: 'goal_achieved', … })`, which requires you to thread the `variantId` through yourself. In React, use the [`useAdaptiveGoal`](../react/README.md#useadaptivegoalcomponentid) hook.
107
108
 
109
+ ### `client.getVisitorId()` → `string | null`
110
+
111
+ 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
+
108
113
  ### `client.identify(userId)`
109
114
 
110
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`.
@@ -113,6 +118,10 @@ Attaches a stable user ID to the session. On the link, the server copies the hig
113
118
 
114
119
  Synchronously returns the cached assignment, or `null` if not yet assigned. Use when you need a non-async lookup.
115
120
 
121
+ ### `client.isUnified(componentId)` → `boolean`
122
+
123
+ True once this page knows the component was moved onto the shared track (from `initialUnified` or an assign answer), so you render it as a slot instead of a variant.
124
+
116
125
  ### `client.getGraph()`
117
126
 
118
127
  Returns the current `GraphSnapshot` (page nodes captured by the optional graph scanner — see "Optional: graph mode" below). Permanently returns an empty snapshot on the lean client; graph mode must be enabled at `init` time.
@@ -130,6 +139,8 @@ Everything `dispose()` does, plus **deletion of the visitor identity** — the 3
130
139
  What applications may rely on across minor versions:
131
140
 
132
141
  - `init(config)` → `SentientClient`, and every `SentientClient` method documented above
142
+ - `client.getVisitorId()` — the visitor id to pass to `trackServerGoal`; `null` without consent
143
+ - `trackServerGoal(options)` (from `@sentientui/core/server`) — record a conversion from your server
133
144
  - `grantConsent(apiKey?)` — upgrade a client created with `consent: false`
134
145
  - `isDoNotTrackEnabled()` — whether DNT/GPC gates tracking in this browser
135
146
  - `deriveSessionSegment({ userAgent, referer, appOrigin })` — the `device:source` segment key
@@ -137,6 +148,7 @@ What applications may rely on across minor versions:
137
148
  - `renderPrePaintScript(apiKey)` — the inline pre-paint script (see "Decision snapshot"); render it only once consent is known
138
149
  - `forgetVisitor(apiKey)` — delete everything the SDK stores for this visitor, with or without a
139
150
  live client (a refusal recorded before any grant; `client.destroy()` does the same for a client)
151
+ - `urlMatches(pattern, url)` / `normalizeUrlPattern(pattern)` — the page-visit goal URL matcher the dashboard, API and snippet share
140
152
  - the subpath entries `/server`, `/graph`, `/consent`, and every exported **type**
141
153
 
142
154
  Everything else the root entry exports (block vocabularies, snapshot I/O, agent-UA tables,
@@ -144,13 +156,41 @@ Everything else the root entry exports (block vocabularies, snapshot I/O, agent-
144
156
  `@sentientui/snippet`. It carries no semver promise and leaves the root entry at 1.0.
145
157
  `src/public-surface.test.ts` classifies every export, so the list can't grow silently.
146
158
 
159
+ ## Record a conversion from your server
160
+
161
+ 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).
162
+
163
+ **Same request** (the visitor's browser made the request, so their cookie is there):
164
+
165
+ ```ts
166
+ import { cookies } from 'next/headers';
167
+ import { readSessionCookie, trackServerGoal } from '@sentientui/core/server';
168
+
169
+ const sessionId = readSessionCookie(await cookies(), process.env.NEXT_PUBLIC_SENTIENT_API_KEY!);
170
+ await trackServerGoal({
171
+ serverKey: process.env.SENTIENT_SECRET_KEY!,
172
+ sessionId,
173
+ name: 'purchase',
174
+ dedupeKey: order.id, // your own id for this conversion
175
+ value: order.total,
176
+ currency: 'USD',
177
+ });
178
+ ```
179
+
180
+ **Later, from a webhook** (Stripe, Clerk, a queue: no cookie in sight). Save the visitor id when the visitor acts, then use it when the confirmation arrives:
181
+
182
+ 1. In the browser, read `client.getVisitorId()` and send it along with the checkout or sign-up (for example in its metadata). It is `null` until the visitor has agreed to tracking, so nothing is saved for people who haven't.
183
+ 2. In your webhook handler, read that id back from the event and pass it as `sessionId`.
184
+
185
+ `trackServerGoal` resolves `'recorded'`, `'skipped_no_visitor'` (no id, so nothing is sent) or `'failed'`. It never throws. Sending the same `name` and `dedupeKey` for the same visitor again, for example when a webhook is redelivered, counts once. The id is scoped to the visitor's session, so another site using the same order number never collides with yours. It refuses to run in a browser and never sends the secret key there.
186
+
147
187
  ## SSR helpers
148
188
 
149
189
  ```ts
150
190
  import { preloadAssignments, readSessionCookie } from '@sentientui/core/server';
151
191
 
152
192
  // In your server loader / getServerSideProps / Server Component.
153
- // `cookies` must expose `get(name)` — Next.js `req.cookies`, `headers().cookies()`, or any
193
+ // `cookies` must expose `get(name)` — Next.js `req.cookies`, `cookies()` from `next/headers`, or any
154
194
  // object with the same shape.
155
195
  const sessionId = readSessionCookie(cookies) ?? crypto.randomUUID();
156
196
 
@@ -177,6 +217,8 @@ Pass `initialAssignments` and the same `sessionSegment` to `init()` on the clien
177
217
 
178
218
  For pages with a section layout, use `preloadDecisions` instead — same options, plus a `sections: string[]` request field. The return value carries both `assignments` and `layoutOrder`.
179
219
 
220
+ `preloadAssignmentsDetailed(components, sessionId, config, { unified: true })` is `preloadAssignments` that also returns `unified`: the components you moved onto the shared track. They are left out of `assignments` (nothing is recorded for them); pass the ids to `init({ initialUnified })`. On `preloadDecisions`, set `unifiedCaps: true` for the same behaviour.
221
+
180
222
  ## decide() — slots, layout, and persona in one call
181
223
 
182
224
  ```ts
@@ -1,2 +1,2 @@
1
1
  var e=40,t=120,o=300;export{e as a,t as b,o as c};
2
- //# sourceMappingURL=chunk-NCLBL5V3.mjs.map
2
+ //# sourceMappingURL=chunk-EVF5PQ4U.mjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/region-skeleton.ts"],"sourcesContent":["// Region skeleton (spec 2026-09-23 §4.1). The generator used to see a region\n// as its flattened textContent — \"Get in touch WhatsApp photos\" — and wrote a\n// heading + paragraph for what were two buttons. The skeleton is the region's\n// STRUCTURE: every element that carries text, its role, link, emphasis and\n// colour, so generation can write per-element edits and both SDKs can apply\n// them to the developer's own elements.\n//\n// Only the wrapped region is ever read (same scope as baselineText); query\n// strings and hashes never leave the page (tracking ids, sometimes PII).\n\nexport const MAX_SKELETON_NODES = 40;\nexport const MAX_SKELETON_LEAVES = 120;\nexport const MAX_SKELETON_TEXT = 300;\n\nexport type SkeletonRole = 'action' | 'heading' | 'text' | 'label' | 'image';\nexport type SkeletonNode = {\n tag: string;\n role: SkeletonRole;\n level?: 1 | 2 | 3 | 4 | 5 | 6;\n text: string; // joined normalized leaves of this node (image: alt)\n classes: string; // class attribute, whitespace-normalized\n filled?: boolean; // action only\n href?: string; // action only; same-origin → path; else origin+path; never query/hash\n src?: string; // image only; same rule\n color: string; // computed `color`\n group: number; // index of the node owner's parentElement among distinct parents\n restylable: boolean; // snippet: always true; React: set by annotateSkeletonForReact\n};\nexport type RegionSkeleton = {\n v: 1;\n root: { tag: string; classes: string; ambientBg: string | null; ambientBgAlt?: string; ambientText: string };\n nodes: SkeletonNode[];\n leaves: string[]; // normalized non-blank text leaves, document order\n leafToNode: number[]; // leaves[i] belongs to nodes[leafToNode[i]]\n fp: string;\n /** false = the page can't address these elements for per-element edits\n * (React: the region wraps a component whose text the element tree can't\n * see). The capture still describes the region — enough to REDESIGN it,\n * which replaces the whole region — but no Rewrite arm may target it. */\n editable?: false;\n};\nexport type ArmEdits = {\n nodes: Record<string, { text?: string; hidden?: true; like?: number }>;\n order?: Record<string, number[]>;\n};\n/** What the requesting page can render for one slot (decide `render` field). */\nexport type RenderCaps = {\n fp?: string; // omitted = unknown (SSR): server assumes the stored skeleton\n forms: boolean; // a form-arm handler exists\n compose: boolean; // phase 2; always false in phase 1\n authored?: string[]; // phase 3\n content?: boolean; // false = a content arm cannot land (0 or >1 text leaves). Omitted = true.\n children?: boolean; // phase 3: false = no children to render, the first authored key is the baseline. Omitted = true.\n};\n/** How the server serves an `edits` arm (SlotConfigEntry.edits). */\nexport type ServedEdits = { edits: ArmEdits; fp: string; leafToNode: number[] };\n\n// DOM capture lives in ./region-capture.ts, exported from\n// `@sentientui/core/region`: only React and the snippet need it, and it would\n// otherwise ship in the lean entry every plain-JS install downloads.\n"],"mappings":"AAUO,IAAMA,EAAqB,GACrBC,EAAsB,IACtBC,EAAoB","names":["MAX_SKELETON_NODES","MAX_SKELETON_LEAVES","MAX_SKELETON_TEXT"]}
1
+ {"version":3,"sources":["../src/region-skeleton.ts"],"sourcesContent":["// Region skeleton (spec 2026-09-23 §4.1). The generator used to see a region\n// as its flattened textContent — \"Get in touch WhatsApp photos\" — and wrote a\n// heading + paragraph for what were two buttons. The skeleton is the region's\n// STRUCTURE: every element that carries text, its role, link, emphasis and\n// colour, so generation can write per-element edits and both SDKs can apply\n// them to the developer's own elements.\n//\n// Only the wrapped region is ever read (same scope as baselineText); query\n// strings and hashes never leave the page (tracking ids, sometimes PII).\n\nexport const MAX_SKELETON_NODES = 40;\nexport const MAX_SKELETON_LEAVES = 120;\nexport const MAX_SKELETON_TEXT = 300;\n\nexport type SkeletonRole = 'action' | 'heading' | 'text' | 'label' | 'image';\nexport type SkeletonNode = {\n tag: string;\n role: SkeletonRole;\n level?: 1 | 2 | 3 | 4 | 5 | 6;\n text: string; // joined normalized leaves of this node (image: alt)\n classes: string; // class attribute, whitespace-normalized\n filled?: boolean; // action only\n href?: string; // action only; same-origin → path; else origin+path; never query/hash\n src?: string; // image only; same rule\n color: string; // computed `color`\n group: number; // index of the node owner's parentElement among distinct parents\n restylable: boolean; // snippet: always true; React: set by annotateSkeletonForReact\n};\nexport type RegionSkeleton = {\n v: 1;\n root: { tag: string; classes: string; ambientBg: string | null; ambientBgAlt?: string; ambientText: string };\n nodes: SkeletonNode[];\n leaves: string[]; // normalized non-blank text leaves, document order\n leafToNode: number[]; // leaves[i] belongs to nodes[leafToNode[i]]\n fp: string;\n /** false = the page can't address these elements for per-element edits\n * (React: the region wraps a component whose text the element tree can't\n * see). The capture still describes the region — enough to REDESIGN it,\n * which replaces the whole region — but no Rewrite arm may target it. */\n editable?: false;\n};\nexport type ArmEdits = {\n nodes: Record<string, { text?: string; hidden?: true; like?: number }>;\n order?: Record<string, number[]>;\n};\n/** What the requesting page can render for one slot (decide `render` field). */\nexport type RenderCaps = {\n fp?: string; // omitted = unknown (SSR): server assumes the stored skeleton\n forms: boolean; // a form-arm handler exists\n compose: boolean; // phase 2; always false in phase 1\n authored?: string[]; // phase 3\n content?: boolean; // false = a content arm cannot land (0 or >1 text leaves). Omitted = true.\n ops?: boolean; // false = cannot apply ops (React). Omitted = true.\n children?: boolean; // phase 3: false = no children to render, the first authored key is the baseline. Omitted = true.\n};\n/** How the server serves an `edits` arm (SlotConfigEntry.edits). */\nexport type ServedEdits = { edits: ArmEdits; fp: string; leafToNode: number[] };\n\n// DOM capture lives in ./region-capture.ts, exported from\n// `@sentientui/core/region`: only React and the snippet need it, and it would\n// otherwise ship in the lean entry every plain-JS install downloads.\n"],"mappings":"AAUO,IAAMA,EAAqB,GACrBC,EAAsB,IACtBC,EAAoB","names":["MAX_SKELETON_NODES","MAX_SKELETON_LEAVES","MAX_SKELETON_TEXT"]}
@@ -0,0 +1,2 @@
1
+ import{a as Ge,b as me,c as ye,e as ce,f as $e,g as Ue,h as Mt,i as Kt,j as Nt,k as Gt,l as $t,m as je}from"./chunk-XZRKD2GS.mjs";import{b as Fe,g as We,h as Ve,i as He,k as ze,l as qe,o as Je,p as we,r as Xe}from"./chunk-MKM7TD3L.mjs";import{a as le,c as Ne,d as Bt,e as xe}from"./chunk-J5EL7HKC.mjs";import{a as C,b as ne}from"./chunk-TMCGHANO.mjs";var Ye;function Qe(e){Ye=typeof e=="string"&&e!==""?e:void 0}function Ut(e=document){if(Ye)return Ye;try{let n=e.querySelector("script[nonce]");return(n==null?void 0:n.nonce)||(n==null?void 0:n.getAttribute("nonce"))||void 0}catch(n){return}}function Ze(e,n=document){let c=Ut(n);return c&&e.setAttribute("nonce",c),e}function Ee(){try{if(typeof crypto!="undefined"&&typeof crypto.randomUUID=="function")return crypto.randomUUID()}catch(e){}try{if(typeof crypto!="undefined"&&typeof crypto.getRandomValues=="function"){let e=new Uint8Array(16);crypto.getRandomValues(e),e[6]=e[6]&15|64,e[8]=e[8]&63|128;let n="";for(let c=0;c<16;c++)n+=e[c].toString(16).padStart(2,"0"),(c===3||c===5||c===7||c===9)&&(n+="-");return n}}catch(e){}return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let n=Math.random()*16|0;return(e==="x"?n:n&3|8).toString(16)})}var jt="_snt_uid",cn=365,de="_snt_uid";function dn(){return Ee()}function et(e){try{let n=document.cookie.match(new RegExp(`(?:^|; )${e}=([^;]*)`));return n?decodeURIComponent(n[1]):null}catch(n){return null}}function nt(){try{return location.protocol==="https:"?"; Secure":""}catch(e){return""}}function un(e,n,c){try{document.cookie=`${e}=${encodeURIComponent(n)}; max-age=${c}; SameSite=lax; path=/${nt()}`}catch(S){}}function Ce(e){try{return localStorage.getItem(e)}catch(n){return null}}function Ft(e,n){try{return localStorage.setItem(e,n),!0}catch(c){return!1}}function tt(e){try{return sessionStorage.getItem(e)}catch(n){return null}}function pn(e,n){try{return sessionStorage.setItem(e,n),!0}catch(c){return!1}}function gn(e){try{sessionStorage.removeItem(e)}catch(n){}}function fn(e){try{return document.cookie=`${e}_probe=1; max-age=1; SameSite=lax; path=/${nt()}`,document.cookie.indexOf(`${e}_probe=1`)!==-1}catch(n){return!1}}function mn(e){try{localStorage.removeItem(e)}catch(n){}}function yn(e){try{document.cookie=`${e}=; max-age=0; SameSite=lax; path=/${nt()}`}catch(n){}}var Sn={getSessionId:()=>null,isEphemeral:()=>!1,destroy:()=>{}};function Ie(e){var O,P,G,J,Y,oe,ie;if(typeof window=="undefined")return Sn;let n=le(e==null?void 0:e.apiKey),c=(O=e==null?void 0:e.cookieName)!=null?O:Ne(e==null?void 0:e.apiKey),S=`${de}${n}`,w=`${de}_tomb${n}`,I=((P=e==null?void 0:e.cookieTTLDays)!=null?P:cn)*24*60*60,o=z=>z&&z.length>0?z:null,p=()=>{var z,j;return n&&!(e!=null&&e.cookieName)&&Ce(w)===null?(j=(z=o(et(jt)))!=null?z:o(Ce(de)))!=null?j:o(tt(de)):null},l=(ie=(oe=(Y=(J=(G=o(et(c)))!=null?G:o(Ce(S)))!=null?J:o(tt(S)))!=null?Y:p())!=null?oe:o(e==null?void 0:e.ssrSessionId))!=null?ie:dn();un(c,l,I);let a=Ft(S,l),i=fn(c),v=a?!1:pn(S,l),R=!a&&!i&&!v;return{getSessionId:()=>l,isEphemeral:()=>R,destroy:()=>{l=null,yn(c),mn(S),gn(S),n&&!(e!=null&&e.cookieName)&&(et(jt)!==null||Ce(de)!==null||tt(de)!==null)&&Ft(w,"1")}}}var hn=1800*1e3;function _e(e,n){return`${encodeURIComponent(e)}:${encodeURIComponent(n)}`}function Wt(e=hn,n){let c=new Map,S=`_snt_asgn${le(n)}_`,w=(l,a)=>`${S}${encodeURIComponent(l)}:${encodeURIComponent(a)}`,m=l=>{let a=l.slice(S.length),i=a.indexOf(":");if(i<0)return null;try{return{componentId:decodeURIComponent(a.slice(0,i)),segment:decodeURIComponent(a.slice(i+1))}}catch(v){return null}},I=()=>{try{let l=[];for(let a=0;a<localStorage.length;a++){let i=localStorage.key(a);i!=null&&i.startsWith(S)&&l.push(i)}return l}catch(l){return[]}},o=l=>l.assignedAt+(l.ttlMs&&l.ttlMs>0?l.ttlMs:e)<Date.now();return typeof window!="undefined"&&(()=>{for(let l of I())try{let a=localStorage.getItem(l);if(!a)continue;let i=JSON.parse(a);if(o(i)){localStorage.removeItem(l);continue}let v=m(l);if(!v)continue;c.set(_e(v.componentId,v.segment),i)}catch(a){}})(),{get(l,a){let i=c.get(_e(l,a));return i?o(i)?(c.delete(_e(l,a)),null):i:null},set(l,a,i){let v=_e(l,a);c.set(v,i);try{localStorage.setItem(w(l,a),JSON.stringify(i))}catch(R){}},clear(){c.clear();for(let l of I())try{localStorage.removeItem(l)}catch(a){}}}}import{STAGE_KEYS as kn}from"@sentientui/policy";var ot="data-sentient-stage";function st(e,n){return!n||typeof e!="string"||!(e==="returning"||kn.includes(e))?null:n!=="detailed"&&(e==="customer"||e==="lapsed")?"returning":e}function rt(e,n=document){try{e?n.documentElement.setAttribute(ot,e):n.documentElement.removeAttribute(ot)}catch(c){}}import{confidenceBand as Qt}from"@sentientui/policy";import{confidenceBand as it}from"@sentientui/policy";var at="[sentient] No API key configured \u2014 nothing is being learned. Set NEXT_PUBLIC_SENTIENT_API_KEY or pass localMode: true for local development.",Ht="[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.",Vt=!1,Ae=!1;function bn(){var e;try{return(e=new URLSearchParams(window.location.search).get("sentient_persona"))!=null?e:void 0}catch(n){return}}function zt(e){var l;let n=Ie({ssrSessionId:e.ssrSessionId,apiKey:e.apiKey}),c=(l=n.getSessionId())!=null?l:"local",S=bn(),w=import("@sentientui/core/local").then(a=>{let i=a;return i.LOCAL_ENGINE_AVAILABLE?(Vt||(Vt=!0,console.info(Ht)),i):(Ae||(Ae=!0,console.error(at)),null)}).catch(()=>(Ae||(Ae=!0,console.error(at)),null)),m=null,I={low:.15,medium:.5,high:.85},o=(()=>{var i;if(e.initialPersona)return C({},e.initialPersona);let a=me(e.apiKey||"local");return a?{persona:a.persona,confidence:(i=I[a.band])!=null?i:.15}:null})();function p(a){let i=document.documentElement;i.dataset.sentientPersona===void 0&&(i.dataset.sentientPersona=a.persona,i.dataset.sentientConfidence=it(a.confidence))}return{isLocal:!0,async decide(a){var R,O,P;let i=await w;if(!i)return null;let v=i.createLocalEngine({sessionId:c,forcedPersona:S}).decide(a);return m=ne(C({},v),{layoutOrder:(O=(R=v.layoutOrder)!=null?R:m==null?void 0:m.layoutOrder)!=null?O:null,slots:C(C({},(P=m==null?void 0:m.slots)!=null?P:{}),v.slots)}),ye(e.apiKey||"local",{v:1,persona:m.persona,band:it(m.confidence),slots:m.slots,layoutOrder:m.layoutOrder,savedAt:Date.now()}),p(v),v},getSlotResult(a){var i,v,R;return(R=(v=m==null?void 0:m.slots[a])!=null?v:(i=e.initialSlots)==null?void 0:i[a])!=null?R:null},getSlotConfig(a){var i,v;return(v=(i=e.initialSlotConfig)==null?void 0:i[a])!=null?v:null},getSitePalette(){var a;return(a=e.initialPalette)!=null?a:null},reportSlots(){},getVisitorId:()=>null,getPersona(){let a=m!=null?m:o;return a?{persona:a.persona,confidence:a.confidence,band:it(a.confidence)}:null},async assign(a,i){var O;let v=await w;return!v||!i||i.length===0?i!=null&&i[0]?{variantId:i[0],assignmentTtlMs:0}:null:{variantId:(O=v.createLocalEngine({sessionId:c,forcedPersona:S}).decide({components:[{id:a,variantIds:i}]}).assignments[a])!=null?O:i[0],assignmentTtlMs:0}},track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},getAssignment:()=>null,fetchWeights:()=>Promise.resolve([]),getGraph:()=>({pageNodes:[],capturedAt:0}),flush:()=>{},dispose:()=>{},destroy:()=>n.destroy()}}var qt=/^(\*|\/[^\s?#*]*(\/\*)?)$/;function lt(e){let n=e.split(/[?#]/)[0]||"/";return n.length>1?n.replace(/\/+$/,"")||"/":n}function vn(e,n){if(e===void 0||!qt.test(e))return!1;if(e==="*")return!0;let c=lt(n);if(e.endsWith("/*")){let S=lt(e.slice(0,-2));return c.startsWith(S==="/"?"/":`${S}/`)&&c!==S}return c===lt(e)}function xn(e,n){if(!e)return!1;if(e==="/")return n==="/";let c=e.endsWith("/")?e.slice(0,-1):e;return n===c||n.startsWith(`${c}/`)}function wn(e){if(!/^https?:\/\//i.test(e))return e;try{return new URL(e).pathname||"/"}catch(n){return e}}var Zn=["none","sm","md","lg"],eo=["start","center","end","stretch"],to=["start","center","end","between"],no=["sm","md","lg"],oo=["normal","medium","bold"],so=["default","muted","accent"],ro=["primary","secondary","ghost"],io=["left","center","right"],ao=["auto","square","landscape","wide"],lo=["cover","contain"],co=[2,3,4],uo=[1,2,3,4],po=["default","raised"],go=["none","sm","md","lg"],fo=["measure"],mo=["input","textarea","select"],yo=["text","email","number","tel"],So=5,ho=8,ko=64,bo=5,vo=12,xo=4,wo=500;function En(e){if(e==null||typeof e!="object"||Array.isArray(e))return!1;let n=e;return n.type==="form"?!0:Array.isArray(n.children)?n.children.some(En):!1}var ct="sentient-reveal",ue="sentient-revealed",Jt=240,Re=!1;function Cn(){var e;Re=!1,typeof document!="undefined"&&((e=document.getElementById(ct))==null||e.remove())}function In(e){if(Re||e.getElementById(ct)){Re=!0;return}let n=Ze(e.createElement("style"),e);n.id=ct,n.textContent=`@media (prefers-reduced-motion: no-preference){@keyframes ${ue}{from{opacity:.55;transform:translateY(2px)}to{opacity:1;transform:none}}.${ue}{animation:${ue} ${Jt}ms cubic-bezier(.2,.6,.2,1) both}}`,e.head.appendChild(n),Re=!0}function _n(e,n={}){var w;let c=(w=n.doc)!=null?w:typeof document!="undefined"?document:void 0;if(!c||!(e instanceof Element)||(n.arm!==void 0&&e.setAttribute("data-sentient-arm",n.arm),n.persona!==void 0&&e.setAttribute("data-sentient-persona",n.persona),n.previous!==void 0&&n.previous===e.textContent))return!1;In(c),e.classList.remove(ue),e.offsetWidth,e.classList.add(ue);let S=()=>{e.classList.remove(ue),e.removeEventListener("animationend",S)};return e.addEventListener("animationend",S),!0}function An(e,n,c,S){let w=[];{let o=!1,p=[],l=()=>{if(o)return;let a=Date.now();for(p.push(a);p.length>0&&a-p[0]>500;)p.shift();p.length>=3&&(o=!0,e("rage_click"))};n.addEventListener("click",l),w.push(()=>n.removeEventListener("click",l))}{let m=!1,I=o=>{if(m||!(o.target instanceof Node)||!n.contains(o.target)&&n!==o.target)return;m=!0;let p=typeof window!="undefined"?window.getSelection():null,l=p?p.toString().length:0;e("text_copy",{selectionLength:l})};document.addEventListener("copy",I),w.push(()=>document.removeEventListener("copy",I))}{let m=!1,I=!1,o=null,p=()=>{o!==null&&(clearTimeout(o),o=null)},l=()=>{m||!I||(p(),o=setTimeout(()=>{!m&&I&&(m=!0,e("scroll_hesitation"))},3e3))},a=()=>{p(),l()},i=R=>{for(let O of R)I=O.intersectionRatio>.3,I?l():p()},v=new IntersectionObserver(i,{threshold:[.3]});v.observe(n),window.addEventListener("scroll",a,{passive:!0}),w.push(()=>{v.disconnect(),window.removeEventListener("scroll",a),p()})}if((S==null?void 0:S.tabLoss)!==!1){let m=!1,I=c!=null?c:Date.now(),o=()=>{if(m||document.visibilityState!=="hidden")return;let p=Date.now()-I;p<15e3&&(m=!0,e("tab_loss",{timeOnPage:p}))};document.addEventListener("visibilitychange",o),w.push(()=>document.removeEventListener("visibilitychange",o))}return()=>{for(let m of w)m()}}function Rn(){var e;return typeof process=="undefined"||((e=process.env)==null?void 0:e.NODE_ENV)!=="production"}var en="https://api.sentient-ui.com/v1/events",F=new Map,tn=null;function es(e,n){let c=F.get(e);c&&c.upgrade&&(c.reinit=n)}function Tn(e){return"value"in e||"currency"in e||"externalId"in e||"metadata"in e||"weight"in e||"stepIndex"in e}var On=3;function dt(){return Ee()}function Te(){var e;if(typeof window!="undefined")return((e=window.location)==null?void 0:e.pathname)||void 0}function Dn(){let e=new WeakMap,n=new Map,c=!1,S=(o,p,l)=>{let a=o.get(p);return l===null?a?!0:(o.set(p,new Set),!1):a?a.has(l)?!0:(a.add(l),!1):(o.set(p,new Set([l])),!1)},w=typeof window!="undefined"&&"event"in window,m=()=>{if(!w)return;let o=window.event;return typeof Event=="function"&&o instanceof Event?o:void 0},I=()=>{if(w){Promise.resolve().then(()=>{c=!1,n.clear()});return}let o=!1,p=()=>{o||(o=!0,c=!1,n.clear())};if(setTimeout(p,0),typeof MessageChannel=="function"){let l=new MessageChannel;l.port1.onmessage=()=>{l.port1.close(),l.port2.close(),p()},l.port2.postMessage(0)}};return{firedBefore(o,p){let l=m();if(l){let i=e.get(l);return i||(i=new Map,e.set(l,i)),S(i,o,p)}let a=S(n,o,p);return!a&&!c&&(c=!0,I()),a}}}var nn=new Set;function Ln(e,n,c){let S=typeof window=="undefined"?null:window.history;if(!S)return()=>{};let w=!1,m,I=()=>{if(w)return;let l=Te();!l||l===m||(m=l,e.track({projectId:n,componentId:"__page__",eventType:"pageview",payload:{}}),c(`${n}:${l}`))},o=[];for(let l of["pushState","replaceState"]){let a=S[l],i=function(...v){let R=a.apply(this,v);return I(),R};S[l]=i,o.push([l,a,i])}window.addEventListener("popstate",I);let p=Te();return p&&nn.has(`${n}:${p}`)?m=p:I(),()=>{if(!w){w=!0,window.removeEventListener("popstate",I);for(let[l,a,i]of o)S[l]===i&&(S[l]=a)}}}var Se={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 Pn(){try{return ze(window.location.search)}catch(e){return{utmParams:{},clickIds:{}}}}function on(e){return e.replace(/\/events\/?$/,"")}function sn(){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(n=>n==="1"||n==="yes")}function ts(e){var p;if(typeof window=="undefined")return;let n=e!=null?e:tn;if(!n){console.warn("[sentient] grantConsent() called before init()");return}let c=F.get(n);if(!c){console.warn("[sentient] grantConsent() called before init()");return}let{config:S,upgrade:w,reinit:m}=c;if(!w){c.upgradeBlockedReason&&console.warn(c.upgradeBlockedReason);return}if(S.respectDoNotTrack!==!1&&sn())return;let I=(m!=null?m:Mn)(ne(C({},S),{consent:!0}));w(I);let o=(p=F.get(n))==null?void 0:p.dispose;F.set(n,{config:ne(C({},S),{consent:!0}),upgrade:null,dispose:o})}function Bn(e,n){var j;let c=e.preConsentBehavior==="statistical_winner",S=on((j=e.ingestUrl)!=null?j:en),w={"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`},m=new Map,I=new Map,o={track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},getAssignment:()=>null,fetchWeights:()=>Promise.resolve([]),assign(r,u,h){if(!c)return Promise.resolve(null);let E=m.get(r);return E?Promise.resolve(E):pt(I,r,async()=>{try{let D=new URLSearchParams({componentId:r});for(let se of u!=null?u:[])D.append("variantIds[]",se);let $=ce(5e3),W;try{let se=await fetch(`${S}/winner?${D.toString()}`,{headers:w,signal:$.signal});if(!se.ok)return u!=null&&u[0]?{variantId:u[0],assignmentTtlMs:0}:null;W=await se.json()}finally{$.clear()}let T={variantId:W.variantId,assignmentTtlMs:0};return m.set(r,T),T}catch(D){return u!=null&&u[0]?{variantId:u[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:()=>{}},p=!1,l=new Set,a=[],i=[],v=[],R=()=>{for(let[,,r]of v.splice(0))r(null);O.length=0},O=[],P=!1,G=()=>{if(p)return;P=!0;let r=F.get(e.apiKey);(r==null?void 0:r.upgrade)===z&&F.set(e.apiKey,{config:e,upgrade:null,upgradeBlockedReason:"[sentient] grantConsent(): client released before consent; call init() again"})},J=[],Y=()=>{setTimeout(()=>{var r;try{(r=J.shift())==null||r(o)}catch(u){}J.length&&Y()})},oe=r=>{p?J.length?J.push(r):r(o):!n&&!P&&O.length<100?O.push(r):P&&e.debug&&console.warn("[sentient] goal dropped: client released")},ie={get gated(){return!p&&!n},get released(){return P&&!p},takeHeld:()=>O.splice(0),track:r=>o.track(r),goal:((r,u,h,E)=>oe(D=>D.goal(r,u,h,E))),componentGoal:(r,u,h)=>o.componentGoal(r,u,h),identify:r=>o.identify(r),getAssignment:(r,u)=>o.getAssignment(r,u),isUnified:r=>{var u,h;return(h=(u=o.isUnified)==null?void 0:u.call(o,r))!=null?h:!1},assign:(r,u,h,E,D)=>o.assign(r,u,h,E,D),decide:r=>p?o.decide(r):P||n?Promise.resolve(null):new Promise(u=>v.push([r,Zt(),u])),getSlotResult:r=>o.getSlotResult(r),isSlotDecided:r=>{var u,h;return(h=(u=o.isSlotDecided)==null?void 0:u.call(o,r))!=null?h:!0},getSlotConfig:r=>o.getSlotConfig(r),getSitePalette:()=>o.getSitePalette(),getStyleVocabulary:()=>{var r,u;return(u=(r=o.getStyleVocabulary)==null?void 0:r.call(o))!=null?u:null},reportSlots:(r,u,h,E)=>o.reportSlots(r,u,h,E),reportSkeleton:(r,u)=>{var h;return(h=o.reportSkeleton)==null?void 0:h.call(o,r,u)},reportAgentData:(r,u,h)=>{var E;return(E=o.reportAgentData)==null?void 0:E.call(o,r,u,h)},reportDrift:(r,u,h,E)=>{var D;return(D=o.reportDrift)==null?void 0:D.call(o,r,u,h,E)},requestSlots:(r,u,h)=>{var E;return p?(E=o.requestSlots)==null?void 0:E.call(o,r,u,h):a.push([r,u,h])},decideSlots:r=>{var u;return p?(u=o.decideSlots)==null?void 0:u.call(o,r):i.push(...r)},cancelSlots:r=>{var h;if(p)return(h=o.cancelSlots)==null?void 0:h.call(o,r);let u=new Set(r);for(let E of a)E[0]=E[0].filter(D=>!u.has(D));i=i.filter(E=>!u.has(E.id))},onSlotsChanged:r=>(l.add(r),()=>{l.delete(r)}),getPersona:()=>o.getPersona(),getVisitorId:()=>{var r,u;return(u=(r=o.getVisitorId)==null?void 0:r.call(o))!=null?u:null},fetchWeights:()=>o.fetchWeights(),getGraph:()=>o.getGraph(),flush:()=>o.flush(),dispose:()=>(G(),R(),o.dispose()),destroy:()=>(G(),R(),p?o.destroy():je(e.apiKey))};function z(r){var h,E,D;o=r,p=!0,O.length&&(J.push(...O.splice(0)),Y());let u=Zt();for(let[$,W,T]of v.splice(0))W!==u?T(null):r.decide($).then(T,()=>T(null));(h=r.onSlotsChanged)==null||h.call(r,()=>l.forEach($=>$()));for(let[$,W,T]of a.splice(0))$.length>0&&((E=r.requestSlots)==null||E.call(r,$,W,T));i.length>0&&((D=r.decideSlots)==null||D.call(r,i.splice(0)))}return{proxy:ie,setInner:z}}function Zt(){return typeof location=="undefined"?"":location.pathname+(/^#!?\//.test(location.hash)?location.hash:"")}function pt(e,n,c){let S=e.get(n);if(S)return S;let w=(async()=>{try{return await c()}finally{e.delete(n)}})();return e.set(n,w),w}function Mn(e){var xt,wt,Et,Ct,It,_t,At,Rt,Tt,Ot,Dt;if(typeof window=="undefined")return Se;e.nonce&&Qe(e.nonce),tn=e.apiKey||"local";let n=F.get(e.apiKey||"local");if(n!=null&&n.dispose)try{n.dispose()}catch(t){}let c=e.respectDoNotTrack!==!1&&sn(),S=e.consent===!1||c,w=typeof e.apiKey=="string"&&e.apiKey.startsWith("pk_");if(e.localMode===!0||!w&&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."}),S?Se:zt(e);if(S){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."}),Se;let{proxy:t,setInner:s}=Bn(e,c);return F.set(e.apiKey,{config:e,upgrade:c?null:s}),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."),Se;if(e.ingestUrl==="")return console.warn("[sentient] init() called with an empty ingestUrl. SDK disabled."),Se;let m=(xt=e.ingestUrl)!=null?xt:en,I=Date.now(),o=Ie({ssrSessionId:e.ssrSessionId,apiKey:e.apiKey}),p=Wt(void 0,e.apiKey),l=!1,a=xe(e.apiKey),i=()=>!l&&xe(e.apiKey)===a,v=new Set((wt=e.initialUnified)!=null?wt:[]),R=ne(C({},p),{get:(t,s)=>v.has(t)?null:p.get(t,s),set:(...t)=>{i()&&p.set(...t)}}),O=Nt({ingestUrl:m,apiKey:e.apiKey}),P=on(m),G={"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`},J=new Set,Y=$t({url:`${P}/goals`,apiKey:e.apiKey,headers:G,onDrop:(t,s)=>{if(!e.debug){if(J.has(s))return;J.add(s)}console.warn(`[sentient] goal dropped (HTTP ${s}) \u2014 this will not be retried. `+(s===400?"The session was not found: call init() and let the session upsert complete before firing goals.":s===401||s===403?"Check the API key and that this origin is on the project allowlist.":"See the response status for the cause."),t)}}),oe=We((Et=navigator.userAgent)!=null?Et:""),ie=window.location.origin,z=Ve((Ct=document.referrer)!=null?Ct:"",ie),j=(It=e.sessionSegment)!=null?It:`${oe}:${z}`,r=new Map,u=new Map,h=new Map,E=new Set,D=new Map,$=null,W=null,T=null,se=new Set,he=new Set,Oe=new Map,De=new Map,gt=new Set,ft=new Set,mt=new Set,yt=new Set,Le=null,pe=/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,127}$/,St=new Set,ke=new Set,be=new Set,ge=new Map,Pe=null,ve=new Set,fe=new Map,Be=null,rn=2,ht=new Map,X=!1,kt=(t,s,d)=>{var g;let b=new Set,x=1;for(let f of t){s.delete(f);let y=((g=ht.get(f))!=null?g:0)+1;ht.set(f,y),y<=rn&&(b.add(f),y>x&&(x=y))}b.size>0&&setTimeout(()=>{X||d(b)},Ue(x))},Me=t=>{for(let s of t)h.has(s.id)||h.set(s.id,we(s))};if(e.initialSlots)for(let[t,s]of Object.entries(e.initialSlots))h.set(t,s),E.add(t);if(e.initialSlotConfig)for(let[t,s]of Object.entries(e.initialSlotConfig))D.set(t,s);e.initialPalette&&($=e.initialPalette),e.initialVocabulary&&(W=e.initialVocabulary);let Q=me(e.apiKey);if(Q){for(let[t,s]of Object.entries(Q.slots))h.has(t)||h.set(t,s);for(let[t,s]of Object.entries((_t=Q.slotConfig)!=null?_t:{}))D.has(t)||D.set(t,s);!$&&Q.palette&&($=Q.palette),!W&&Q.vocabulary&&(W=Q.vocabulary)}let bt={low:.15,medium:.5,high:.85};if(e.initialPersona)T=C({},e.initialPersona);else{let t=document.documentElement.dataset;t.sentientPersona?T={persona:t.sentientPersona,confidence:(Rt=bt[(At=t.sentientConfidence)!=null?At:"low"])!=null?Rt:.15}:Q&&(T={persona:Q.persona,confidence:(Tt=bt[Q.band])!=null?Tt:.15})}if(e.initialAssignments)for(let[t,s]of Object.entries(e.initialAssignments))R.set(t,j,{variantId:s,assignedAt:Date.now(),segment:j,confidence:1});let te=Promise.resolve(),vt=o.getSessionId();if(vt){let t=He((Ot=document.referrer)!=null?Ot:""),{utmParams:s,clickIds:d}=Pn(),b=C(C(C(C({sessionId:vt,deviceClass:oe,trafficSource:z,referrerDomain:t,utmParams:s,clickIds:d,landingPath:typeof location!="undefined"?location.pathname:void 0,timeOfDay:qe(new Date),dayOfWeek:["sun","mon","tue","wed","thu","fri","sat"][new Date().getDay()],ephemeral:o.isEphemeral(),automation:typeof navigator!="undefined"&&navigator.webdriver===!0||Fe((Dt=navigator.userAgent)!=null?Dt:"")},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}:{}),x=async()=>{for(let g=0;;g++){if(X||!i())return;let f=ce(5e3);try{let y=await fetch(`${P}/sessions`,{method:"POST",keepalive:!0,body:JSON.stringify(b),headers:G,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||Mt(y)==="dropped")return}catch(y){}finally{f.clear()}if(g>=On){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,Ue(g+1)))}};try{te=x()}catch(g){}}e.debug&&(console.log("[sentient] initialized",{context:e.context}),window.__sentient={client:null,queue:O});let an=Dn(),re=null,Ke=!1,N={goal(t,s={},d=1,b=0){var K,A,V,q,H,U,k;let x=o.getSessionId();if(!x||X||!i())return;let g=Tn(s)?s:{metadata:s},f=[t,(K=g.externalId)!=null?K:"",(A=g.stepIndex)!=null?A:b,(V=g.weight)!=null?V:d].join("\0"),y=g.value!==void 0?`${g.value}\0${(q=g.currency)!=null?q:""}`:null;if(an.firedBefore(f,y)){e.debug&&console.log(`[sentient] goal("${t}") already recorded for this action \u2014 not sent twice`);return}let L=dt(),_={sessionId:x,name:t,metadata:(H=g.metadata)!=null?H:{},weight:(U=g.weight)!=null?U:d,stepIndex:(k=g.stepIndex)!=null?k:b,goalId:L,value:g.value,currency:g.currency,externalId:g.externalId};e.debug&&console.log("[sentient] goal",_);let B={id:L,body:JSON.stringify(_)};te.then(()=>Y.send(B))},componentGoal(t,s,d){var L,_,B;let b=o.getSessionId();if(!b||X||!i())return;let x=R.get(t,j),g=x?null:(L=h.get(t))!=null?L:null;if(!x&&g===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(!x&&!E.has(t)){e.debug&&console.warn(`[sentient] componentGoal("${t}"): slot not decided this session \u2014 not attributed`);return}let f=x?x.variantId:Xe(g),y={id:dt(),sessionId:b,projectId:e.apiKey,componentId:t,variantId:f,eventType:"goal_achieved",goalType:s,payload:C({reward:(_=d==null?void 0:d.reward)!=null?_:1,goalValue:d==null?void 0:d.value,currency:d==null?void 0:d.currency},(B=d==null?void 0:d.metadata)!=null?B:{}),timestamp:Date.now(),timeInSession:Date.now()-I,path:Te()};e.debug&&console.log("[sentient] componentGoal",y),te.then(()=>{!X&&i()&&O.push(y)})},identify(t){let s=o.getSessionId();!s||X||!i()||te.then(()=>{fetch(`${P}/sessions`,{method:"POST",keepalive:!0,body:JSON.stringify({sessionId:s,userId:t,ephemeral:o.isEphemeral()}),headers:G}).catch(()=>{})})},track(t){let s=o.getSessionId();if(!s||X||!i()||t.eventType==="variant_assigned"&&h.get(t.componentId)!==void 0&&!E.has(t.componentId)&&!R.get(t.componentId,j))return;let d=ne(C({path:Te()},t),{id:dt(),sessionId:s,timestamp:Date.now(),timeInSession:Date.now()-I});e.debug&&console.log("[sentient] track",d),te.then(()=>O.push(d))},getAssignment(t,s){return R.get(t,s)},isUnified:t=>v.has(t),async assign(t,s,d,b,x){var L;let g=o.getSessionId();if(!g)return null;let f=(x==null?void 0:x.unified)===!0;if(f&&v.has(t))return{variantId:(L=s==null?void 0:s[0])!=null?L:"",assignmentTtlMs:0,unified:!0};let y=R.get(t,j);if(y&&(s!=null&&s.length||y.content!==void 0)){let _=y.ttlMs&&y.ttlMs>0?Math.max(0,y.assignedAt+y.ttlMs-Date.now()):0;return{variantId:y.variantId,assignmentTtlMs:_,content:y.content}}return pt(r,f?`${t}\0unified`:t,async()=>{if(!await $e(te,2500)||X||!i())return null;let _=ce(3e4);try{let B={sessionId:g,componentId:t,variantIds:s};b!==void 0?B.agentDataByVariant=b:d!==void 0&&(B.agentData=d),f&&(B.caps={unified:!0});let K=await fetch(`${P}/assign`,{method:"POST",body:JSON.stringify(B),headers:G,signal:_.signal});if(!K.ok)return null;let A=await K.json();return A.unified===!0?f?(v.add(t),{variantId:A.variantId,assignmentTtlMs:0,unified:!0}):null:(R.set(t,j,C({variantId:A.variantId,assignedAt:Date.now(),segment:j,confidence:1,content:A.content},A.assignmentTtlMs&&A.assignmentTtlMs>0?{ttlMs:A.assignmentTtlMs}:{})),A)}catch(B){return null}finally{_.clear()}})},async decide(t){var g,f;let s=o.getSessionId();if(!s)return null;let d=(g=t.slots)!=null?g:[],b={sessionId:s};t.sections&&t.sections.length>0&&(b.sections=t.sections.map(y=>({id:y}))),b.components=(f=t.components)!=null?f:[],d.length>0&&(b.slots=d.map(Je)),t.slotsFrom==="registry"&&(b.slotsFrom="registry",t.registrySlotIds&&(b.registrySlotIds=t.registrySlotIds),t.bootstrap===!1&&(b.bootstrap=!1),t.render&&Object.keys(t.render).length>0&&(b.render=t.render)),t.v&&(b.v=t.v),typeof t.pp=="number"&&(b.pp=t.pp),e.persona&&(b.persona=e.persona);let x=JSON.stringify(b);return pt(u,x,async()=>{var L,_,B,K,A,V,q,H;if(!await $e(te,2500)||X||!i())return Me(d),null;let y=ce(3e4);try{let U=await fetch(`${P}/decide`,{method:"POST",body:x,headers:G,signal:y.signal});if(!U.ok)return Me(d),null;let k=await U.json(),Z=st(k.stage,e.stageAttributes);e.stageAttributes&&rt(Z);let ae={};for(let M of d){let ee=(L=k.slots)==null?void 0:L[M.id];if(ee!==void 0){ae[M.id]=ee,h.set(M.id,ee),E.add(M.id);continue}let Lt=h.get(M.id);if(Lt!==void 0)ae[M.id]=Lt;else{let Pt=we(M);ae[M.id]=Pt,h.set(M.id,Pt)}}if(k.slots)for(let[M,ee]of Object.entries(k.slots))M in ae||(ae[M]=ee,h.set(M,ee),E.add(M));let ln=T!=null&&T.persona!=="unknown";k.persona&&!(k.persona==="unknown"&&ln)?T={persona:k.persona,confidence:(_=k.confidence)!=null?_:0}:T||(T={persona:"unknown",confidence:0});for(let[M,ee]of Object.entries((B=k.assignments)!=null?B:{}))R.set(M,j,{variantId:ee,assignedAt:Date.now(),segment:j,confidence:1});if(k.slotConfig)for(let[M,ee]of Object.entries(k.slotConfig))D.set(M,ee);k.palette&&($=k.palette),k.vocabulary&&(W=k.vocabulary);for(let M of(K=t.registrySlotIds)!=null?K:[])(A=k.slotConfig)!=null&&A[M]||(D.delete(M),h.delete(M),E.delete(M));return i()&&ye(e.apiKey,C(C(C(C({v:1,persona:T.persona,band:Qt(T.confidence),slots:Object.fromEntries(h),layoutOrder:(V=k.layoutOrder)!=null?V:null,savedAt:Date.now()},D.size>0?{slotConfig:Object.fromEntries(D)}:{}),$?{palette:$}:{}),W?{vocabulary:W}:{}),Z?{stage:Z}:{})),C(C(C(C(C(C(C({layoutOrder:(q=k.layoutOrder)!=null?q:null,assignments:(H=k.assignments)!=null?H:{},slots:ae,persona:T.persona,confidence:T.confidence},k.slotConfig?{slotConfig:k.slotConfig}:{}),k.goals?{goals:k.goals}:{}),k.sectionMap?{sectionMap:k.sectionMap}:{}),k.palette?{palette:k.palette}:{}),k.vocabulary?{vocabulary:k.vocabulary}:{}),k.stage?{stage:k.stage}:{}),k.context?{context:k.context}:{})}catch(U){return Me(d),null}finally{y.clear()}})},getSlotResult(t){var s;return(s=h.get(t))!=null?s:null},isSlotDecided(t){return E.has(t)},getSlotConfig(t){var s;return(s=D.get(t))!=null?s:null},reportSlots(t,s,d,b){var g;let x={};for(let[f,y]of Object.entries(b!=null?b:{}))for(let L of y){let _=`${f}|${L.key}`;!pe.test(f)||mt.has(_)||(mt.add(_),((g=x[f])!=null?g:x[f]=[]).push(L))}Object.keys(x).length>0&&fetch(`${P}/slots/observed`,{method:"POST",headers:G,body:JSON.stringify({slotIds:Object.keys(x),authoredArms:x})}).catch(()=>{});for(let f of t)if(!(typeof f!="string"||f.length===0)){if(!pe.test(f)){Rn()&&!St.has(f)&&(St.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(!se.has(f)){se.add(f),he.add(f);let y=s==null?void 0:s[f];if(typeof y=="string"){let _=y.replace(/\s+/g," ").trim().slice(0,400);_!==""&&Oe.set(f,_)}let L=d==null?void 0:d[f];L!==void 0&&De.set(f,L)}}he.size===0||Le!=null||(Le=setTimeout(()=>{Le=null;let f=[...he];he.clear();for(let y=0;y<f.length;y+=20){let L=f.slice(y,y+20),_={},B={};for(let K of L){let A=Oe.get(K);A!==void 0&&(_[K]=A,Oe.delete(K));let V=De.get(K);V!==void 0&&(B[K]=V,De.delete(K))}fetch(`${P}/slots/observed`,{method:"POST",headers:G,body:JSON.stringify(C(ne(C(C({slotIds:L},Object.keys(_).length>0?{baselineTexts:_}:{}),Object.keys(B).length>0?{baselineSkeletons:B}:{}),{pagePaths:Object.fromEntries(L.map(K=>[K,location.pathname]))}),Object.keys(_).length>0&&o.getSessionId()?{sessionId:o.getSessionId()}:{}))}).catch(()=>{})}},1e3))},reportSkeleton(t,s){!pe.test(t)||gt.has(t)||(gt.add(t),fetch(`${P}/slots/observed`,{method:"POST",headers:G,body:JSON.stringify({slotIds:[t],baselineSkeletons:{[t]:s}})}).catch(()=>{}))},reportAgentData(t,s,d){let b=`${t}|${s}`;!pe.test(t)||yt.has(b)||(yt.add(b),fetch(`${P}/slots/observed`,{method:"POST",headers:G,body:JSON.stringify(C({slotIds:[t],agentData:{[t]:{[s]:d}}},s.startsWith("authored.")?{authoredArms:{[t]:[{key:s.slice(9)}]}}:{}))}).catch(()=>{}))},reportDrift(t,s,d,b){let x=`${t}|${s}`,g=o.getSessionId();!g||ft.has(x)||(ft.add(x),fetch(`${P}/slots/drift`,{method:"POST",headers:G,body:JSON.stringify({sessionId:g,reports:[{slotId:t,expectedFp:s,observedFp:d,reason:b}]})}).catch(()=>{}))},requestSlots(t,s,d){var b,x;for(let g of t)be.has(g)||(be.add(g),pe.test(g)?ge.set(g,{text:s==null?void 0:s[g],render:(b=d==null?void 0:d.render)==null?void 0:b[g],skeleton:(x=d==null?void 0:d.skeletons)==null?void 0:x[g]}):N.reportSlots([g]));ge.size===0||Pe!=null||(Pe=setTimeout(()=>{Pe=null;let g=[...ge];ge.clear();for(let f=0;f<g.length;f+=50){let y=g.slice(f,f+50),L={};for(let[_,B]of y)B.render&&(L[_]=B.render);N.decide({slotsFrom:"registry",registrySlotIds:y.map(([_])=>_),bootstrap:!1,render:L}).then(_=>{var B,K;if(_){let A={},V={},q=[];for(let[H,U]of y){let k=(B=_.slotConfig)==null?void 0:B[H];if(k){k.needsSkeleton&&U.skeleton&&((K=N.reportSkeleton)==null||K.call(N,H,U.skeleton));continue}q.push(H),U.text&&(A[H]=U.text),U.skeleton&&(V[H]=U.skeleton)}q.length>0&&N.reportSlots(q,A,V)}else kt(y.map(([A])=>A),be,A=>{var U;let V={},q={},H={};for(let[k,Z]of y)A.has(k)&&(Z.text&&(V[k]=Z.text),Z.render&&(q[k]=Z.render),Z.skeleton&&(H[k]=Z.skeleton));(U=N.requestSlots)==null||U.call(N,[...A],V,{render:q,skeletons:H})});ke.forEach(A=>A())})}},0))},decideSlots(t){for(let s of t)ve.has(s.id)||(ve.add(s.id),fe.set(s.id,s));fe.size===0||Be!=null||(Be=setTimeout(()=>{Be=null;let s=[...fe.values()];fe.clear();for(let d=0;d<s.length;d+=30){let b=s.slice(d,d+30);N.decide({slots:b}).then(x=>{x||kt(b.map(g=>g.id),ve,g=>{var f;return(f=N.decideSlots)==null?void 0:f.call(N,b.filter(y=>g.has(y.id)))}),ke.forEach(g=>g())})}},0))},cancelSlots(t){for(let s of t)ge.delete(s)&&be.delete(s),fe.delete(s)&&ve.delete(s)},onSlotsChanged(t){return ke.add(t),()=>{ke.delete(t)}},getStyleVocabulary(){return W},getSitePalette(){return $},getVisitorId:()=>i()?o.getSessionId():null,getPersona(){return T?{persona:T.persona,confidence:T.confidence,band:Qt(T.confidence)}:null},async fetchWeights(){var s;let t=ce(5e3);try{let d=await fetch(`${P}/weights`,{headers:G,signal:t.signal});return d.ok?(s=(await d.json()).components)!=null?s:[]:[]}catch(d){return[]}finally{t.clear()}},getGraph(){return{pageNodes:[],capturedAt:0}},flush(){O.flush(),Y.flush()},dispose(){var t;re==null||re(),Ke=!0,X=!0,O.destroy(),Y.destroy(),((t=F.get(e.apiKey))==null?void 0:t.dispose)===N.dispose&&F.delete(e.apiKey),e.debug&&console.log("[sentient] disposed")},destroy(){var t;re==null||re(),Ke=!0,X=!0,l=!0,Bt(e.apiKey),O.destroy({forget:!0}),Y.destroy({forget:!0}),o.destroy(),R.clear(),((t=F.get(e.apiKey))==null?void 0:t.dispose)===N.dispose&&F.delete(e.apiKey);try{localStorage.removeItem(Ge+e.apiKey),localStorage.removeItem(Kt(e.apiKey)),localStorage.removeItem(Gt(e.apiKey)),localStorage.removeItem(`_snt_graph_nodes${le(e.apiKey)}`),localStorage.removeItem("_snt_graph_edges")}catch(s){}e.debug&&console.log("[sentient] destroyed")}};if(F.set(e.apiKey,{config:e,upgrade:null,dispose:N.dispose}),re=Ln(N,e.apiKey,t=>{te.then(()=>{Ke||nn.add(t)})}),e.debug){let t=window;t.__sentient&&(t.__sentient.client=N)}return N}export{Qe as a,Ut as b,Ze as c,ot as d,st as e,rt as f,at as g,Ht as h,qt as i,vn as j,xn as k,wn as l,Zn as m,eo as n,to as o,no as p,oo as q,so as r,ro as s,io as t,ao as u,lo as v,co as w,uo as x,po as y,go as z,fo as A,mo as B,yo as C,So as D,ho as E,ko as F,bo as G,vo as H,xo as I,wo as J,En as K,Jt as L,Cn as M,_n as N,An as O,es as P,sn as Q,ts as R,Zt as S,Mn as T};
2
+ //# sourceMappingURL=chunk-VE2K45X4.mjs.map