@sentientui/react 0.44.1 → 0.44.3

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.
@@ -0,0 +1,123 @@
1
+ import * as _sentientui_core from '@sentientui/core';
2
+ import * as _sentientui_core_server from '@sentientui/core/server';
3
+ import { ServerAssignments } from '@sentientui/core/server';
4
+ export { DecideResult, ServerAssignConfig, ServerAssignments, SlotDeclInput, SlotResult, preloadAssignments, preloadDecisions, readSessionCookie, signUserId, trackServerGoal } from '@sentientui/core/server';
5
+
6
+ /** Return value of `loadAdaptiveAssignments` — includes the session ID used for SSR. */
7
+ type LoadAdaptiveAssignmentsResult = {
8
+ assignments: ServerAssignments;
9
+ /** The session ID used for SSR assignment. Pass as `ssrSessionId` to `<AdaptiveProvider>`. */
10
+ sessionId: string;
11
+ /** Components the operator moved onto the shared track: not in
12
+ * `assignments`. Pass as `initialUnified` to `<AdaptiveProvider>`. */
13
+ unified: string[];
14
+ };
15
+ type LoadAdaptiveAssignmentsOptions = {
16
+ /** Next.js `cookies()` return value, or any object with `get(name)`. */
17
+ cookies: {
18
+ get(name: string): {
19
+ value: string;
20
+ } | undefined;
21
+ };
22
+ apiKey: string;
23
+ baseUrl: string;
24
+ /** Used when `_snt_uid` is absent (e.g. first visit, many crawlers). */
25
+ createSessionId?: () => string;
26
+ /** Must match a value in the project's `allowed_origins` (e.g. `http://localhost:3001`). */
27
+ origin?: string;
28
+ /** From Next.js `headers().get('user-agent')` — aligns SSR segment with the client. */
29
+ userAgent?: string;
30
+ /** From Next.js `headers().get('referer')`. */
31
+ referer?: string;
32
+ /**
33
+ * `utm_*` params from the landing URL. The Referer header never carries the
34
+ * page's OWN query string, so without this the SSR-minted session has no
35
+ * campaign attribution until the client SDK hydrates and re-upserts.
36
+ * Derive with `extractTrackedParams(searchParams)` from `@sentientui/core/server`.
37
+ */
38
+ utmParams?: Record<string, string>;
39
+ /** Ad-platform click IDs (gclid, fbclid, ttclid, …) from the landing URL — same derivation as `utmParams`. */
40
+ clickIds?: Record<string, string>;
41
+ /** The landing page's path (no query string) — recognises a paid click to a product page or a `/discount/` link on the first decision. */
42
+ landingPath?: string;
43
+ /** Set true when the request carries `DNT: 1` or `Sec-GPC: 1` — skips the SSR session upsert + assignment so no session is minted for an opted-out visitor (audit P4). `AdaptiveRoot` sets this automatically from the request headers. */
44
+ doNotTrack?: boolean;
45
+ /** Milliseconds to wait for the API before returning default variants. Defaults to 1000 (typical decide is well under 150 ms; the full budget is only reached on a cold start or a distant API). */
46
+ timeoutMs?: number;
47
+ /**
48
+ * Declared persona — the role your app already knows for this visitor (e.g.
49
+ * from your auth context: 'admin', 'evaluator'). Must be a key in the
50
+ * project's persona vocabulary; unrecognized values are ignored server-side.
51
+ * Never a user id or email.
52
+ */
53
+ persona?: string;
54
+ /**
55
+ * Your team / a test site — the same flag as `<AdaptiveProvider internal>`,
56
+ * sent on the SSR upsert and decide so a server-rendered first page is
57
+ * never counted or learned from. The request's `sentient_internal` cookie
58
+ * (the "mark this browser" link) is read from `cookies` and forwarded too.
59
+ */
60
+ internal?: boolean;
61
+ };
62
+ /**
63
+ * Fetches bandit assignments on the server for SEO-safe HTML.
64
+ * Pass `assignments` as `initialAssignments` and `sessionId` as `ssrSessionId`
65
+ * on `<AdaptiveProvider>` so the client adopts the same session on first visit.
66
+ */
67
+ declare function loadAdaptiveAssignments(components: Array<{
68
+ id: string;
69
+ variantIds: string[];
70
+ }>, options: LoadAdaptiveAssignmentsOptions): Promise<LoadAdaptiveAssignmentsResult>;
71
+
72
+ /** Return value of `loadAdaptiveDecision` — includes the session ID used for SSR. */
73
+ type LoadAdaptiveDecisionResult = _sentientui_core_server.DecideResult & {
74
+ sessionId: string;
75
+ };
76
+ type LoadAdaptiveDecisionOptions = LoadAdaptiveAssignmentsOptions & {
77
+ /**
78
+ * Section IDs in default order. Passed to /v1/decide as the candidate
79
+ * layout. Optional since 0.13.0 — slot-only pages may omit it (at least
80
+ * one of `sections`/`components`/`slots` must be non-empty).
81
+ */
82
+ sections?: string[];
83
+ /** Components to assign in the same decide call. */
84
+ components?: Array<{
85
+ id: string;
86
+ variantIds?: string[];
87
+ }>;
88
+ /** Adaptive-slot declarations (useAdaptiveTokens / AdaptiveGroup) to decide server-side. */
89
+ slots?: _sentientui_core_server.SlotDeclInput[];
90
+ /** 'registry' serves the project's published slot definitions (`<Adaptive id>`)
91
+ * and is the only way `slotConfig`/`palette` come back. Default 'request'.
92
+ * Requires `registrySlotIds`. */
93
+ slotsFrom?: 'request' | 'registry';
94
+ /**
95
+ * Registry mode: the `<Adaptive id>`s THIS page renders — the decide is
96
+ * scoped to exactly these. Required with `slotsFrom: 'registry'`; without it
97
+ * the call downgrades to request mode (with a console.error) instead of
98
+ * recording a close-out trial for every published slot on every page.
99
+ */
100
+ registrySlotIds?: string[];
101
+ /**
102
+ * Registry mode: what each slot on this page can render, keyed by slot id
103
+ * (see `preloadDecisions`). Ids without an entry get core's default caps.
104
+ * A hybrid `<Adaptive variants>{children}</Adaptive>` needs its entry: the
105
+ * server draws `authored.<key>` only for keys the page declares here.
106
+ */
107
+ renderCaps?: Record<string, Omit<_sentientui_core.RenderCaps, 'fp'>>;
108
+ };
109
+ /**
110
+ * SSR helper for pages with a declared section layout and/or adaptive slots.
111
+ * Calls `/v1/decide` instead of multiple `/v1/assign` round trips.
112
+ * Pass `sessionId` as `ssrSessionId` on `<AdaptiveProvider>` so the client
113
+ * adopts the same session on first visit.
114
+ *
115
+ * Keyless: with no valid `pk_` key this never fetches (no timeout burn).
116
+ * Under the `development` export condition the decision is computed by the
117
+ * deterministic local engine with the same sessionId the client will adopt —
118
+ * server and client agree by construction. In production the engine resolves
119
+ * to a stub and defaults are returned with one console.error.
120
+ */
121
+ declare function loadAdaptiveDecision(options: LoadAdaptiveDecisionOptions): Promise<LoadAdaptiveDecisionResult>;
122
+
123
+ export { type LoadAdaptiveAssignmentsOptions, type LoadAdaptiveAssignmentsResult, type LoadAdaptiveDecisionOptions, type LoadAdaptiveDecisionResult, loadAdaptiveAssignments, loadAdaptiveDecision };
package/dist/server.js CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";var T=Object.create;var d=Object.defineProperty,U=Object.defineProperties,x=Object.getOwnPropertyDescriptor,K=Object.getOwnPropertyDescriptors,h=Object.getOwnPropertyNames,P=Object.getOwnPropertySymbols,_=Object.getPrototypeOf,C=Object.prototype.hasOwnProperty,w=Object.prototype.propertyIsEnumerable;var R=(e,r,s)=>r in e?d(e,r,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[r]=s,u=(e,r)=>{for(var s in r||(r={}))C.call(r,s)&&R(e,s,r[s]);if(P)for(var s of P(r))w.call(r,s)&&R(e,s,r[s]);return e},m=(e,r)=>U(e,K(r));var M=(e,r)=>{for(var s in r)d(e,s,{get:r[s],enumerable:!0})},N=(e,r,s,i)=>{if(r&&typeof r=="object"||typeof r=="function")for(let n of h(r))!C.call(e,n)&&n!==s&&d(e,n,{get:()=>r[n],enumerable:!(i=x(r,n))||i.enumerable});return e};var O=(e,r,s)=>(s=e!=null?T(_(e)):{},N(r||!e||!e.__esModule?d(s,"default",{value:e,enumerable:!0}):s,e)),V=e=>N(d({},"__esModule",{value:!0}),e);var G={};M(G,{loadAdaptiveAssignments:()=>B,loadAdaptiveDecision:()=>F,preloadAssignments:()=>t.preloadAssignments,preloadDecisions:()=>E.preloadDecisions,readSessionCookie:()=>t.readSessionCookie,signUserId:()=>t.signUserId,trackServerGoal:()=>t.trackServerGoal});module.exports=V(G);var t=require("@sentientui/core/server"),E=require("@sentientui/core/server");function b(){return typeof crypto!="undefined"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`snt-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}async function B(e,r){var l,c,a;let s=(a=(c=(0,t.readSessionCookie)(r.cookies,r.apiKey))!=null?c:(l=r.createSessionId)==null?void 0:l.call(r))!=null?a:b(),{assignments:i,unified:n}=await(0,t.preloadAssignmentsDetailed)(e,s,{apiKey:r.apiKey,baseUrl:r.baseUrl,origin:r.origin,userAgent:r.userAgent,referer:r.referer,utmParams:r.utmParams,clickIds:r.clickIds,landingPath:r.landingPath,doNotTrack:r.doNotTrack,timeoutMs:r.timeoutMs,persona:r.persona,internal:r.internal,internalToken:(0,t.readInternalToken)(r.cookies)},{unified:!0});return{assignments:i,sessionId:s,unified:n}}async function F(e){var a,A,y,p,f,I,k,v,L,S;let{preloadDecisions:r,readSessionCookie:s,readInternalToken:i}=await import("@sentientui/core/server"),n=(y=(A=s(e.cookies,e.apiKey))!=null?A:(a=e.createSessionId)==null?void 0:a.call(e))!=null?y:b();if(!(typeof e.apiKey=="string"&&e.apiKey.startsWith("pk_"))){let D={layoutOrder:(p=e.sections)!=null?p:[],assignments:{},slots:{},persona:"unknown",confidence:0,sessionId:n};try{let g=await import("@sentientui/core/local");if(!g.LOCAL_ENGINE_AVAILABLE)return console.error("[sentient] No API key configured \u2014 nothing is being learned. Set NEXT_PUBLIC_SENTIENT_API_KEY or pass localMode: true for local development."),D;let o=g.createLocalEngine({sessionId:n}).decide({sections:e.sections,components:(f=e.components)!=null?f:[],slots:(I=e.slots)!=null?I:[]});return{layoutOrder:(v=(k=o.layoutOrder)!=null?k:e.sections)!=null?v:[],assignments:o.assignments,slots:o.slots,persona:o.persona,confidence:o.confidence,sessionId:n}}catch(g){return D}}let c=await r(m(u({sections:e.sections,components:(L=e.components)!=null?L:[],slots:(S=e.slots)!=null?S:[],slotsFrom:e.slotsFrom,registrySlotIds:e.registrySlotIds},e.renderCaps?{renderCaps:e.renderCaps}:{}),{unifiedCaps:!0}),n,{apiKey:e.apiKey,baseUrl:e.baseUrl,origin:e.origin,userAgent:e.userAgent,referer:e.referer,utmParams:e.utmParams,clickIds:e.clickIds,landingPath:e.landingPath,doNotTrack:e.doNotTrack,timeoutMs:e.timeoutMs,persona:e.persona,internal:e.internal,internalToken:i(e.cookies)});return m(u({},c),{sessionId:n})}0&&(module.exports={loadAdaptiveAssignments,loadAdaptiveDecision,preloadAssignments,preloadDecisions,readSessionCookie,signUserId,trackServerGoal});
1
+ "use strict";var b=Object.create;var d=Object.defineProperty,_=Object.defineProperties,K=Object.getOwnPropertyDescriptor,U=Object.getOwnPropertyDescriptors,x=Object.getOwnPropertyNames,E=Object.getOwnPropertySymbols,h=Object.getPrototypeOf,N=Object.prototype.hasOwnProperty,w=Object.prototype.propertyIsEnumerable;var P=(e,r,s)=>r in e?d(e,r,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[r]=s,u=(e,r)=>{for(var s in r||(r={}))N.call(r,s)&&P(e,s,r[s]);if(E)for(var s of E(r))w.call(r,s)&&P(e,s,r[s]);return e},m=(e,r)=>_(e,U(r));var M=(e,r)=>{for(var s in r)d(e,s,{get:r[s],enumerable:!0})},R=(e,r,s,i)=>{if(r&&typeof r=="object"||typeof r=="function")for(let n of x(r))!N.call(e,n)&&n!==s&&d(e,n,{get:()=>r[n],enumerable:!(i=K(r,n))||i.enumerable});return e};var T=(e,r,s)=>(s=e!=null?b(h(e)):{},R(r||!e||!e.__esModule?d(s,"default",{value:e,enumerable:!0}):s,e)),V=e=>R(d({},"__esModule",{value:!0}),e);var G={};M(G,{loadAdaptiveAssignments:()=>B,loadAdaptiveDecision:()=>F,preloadAssignments:()=>t.preloadAssignments,preloadDecisions:()=>O.preloadDecisions,readSessionCookie:()=>t.readSessionCookie,signUserId:()=>t.signUserId,trackServerGoal:()=>t.trackServerGoal});module.exports=V(G);var t=require("@sentientui/core/server"),O=require("@sentientui/core/server");function C(){return typeof crypto!="undefined"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`snt-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}async function B(e,r){var g,c,a;let s=(a=(c=(0,t.readSessionCookie)(r.cookies,r.apiKey))!=null?c:(g=r.createSessionId)==null?void 0:g.call(r))!=null?a:C(),{assignments:i,unified:n}=await(0,t.preloadAssignmentsDetailed)(e,s,{apiKey:r.apiKey,baseUrl:r.baseUrl,origin:r.origin,userAgent:r.userAgent,referer:r.referer,utmParams:r.utmParams,clickIds:r.clickIds,landingPath:r.landingPath,doNotTrack:r.doNotTrack,timeoutMs:r.timeoutMs,persona:r.persona,internal:r.internal,internalToken:(0,t.readInternalToken)(r.cookies)},{unified:!0});return{assignments:i,sessionId:s,unified:n}}async function F(e){var a,A,y,I,p,f,k,v,L,S;let{preloadDecisions:r,readSessionCookie:s,readInternalToken:i}=await import("@sentientui/core/server"),n=(y=(A=s(e.cookies,e.apiKey))!=null?A:(a=e.createSessionId)==null?void 0:a.call(e))!=null?y:C();if(!(typeof e.apiKey=="string"&&e.apiKey.startsWith("pk_"))){let D={layoutOrder:(I=e.sections)!=null?I:[],assignments:{},slots:{},persona:"unknown",confidence:0,sessionId:n};try{let l=await import("@sentientui/core/local");if(!l.LOCAL_ENGINE_AVAILABLE)return console.error("[sentient] No API key configured \u2014 nothing is being learned. Set NEXT_PUBLIC_SENTIENT_API_KEY (Vite: VITE_SENTIENT_API_KEY) or localMode: true."),D;let o=l.createLocalEngine({sessionId:n}).decide({sections:e.sections,components:(p=e.components)!=null?p:[],slots:(f=e.slots)!=null?f:[]});return{layoutOrder:(v=(k=o.layoutOrder)!=null?k:e.sections)!=null?v:[],assignments:o.assignments,slots:o.slots,persona:o.persona,confidence:o.confidence,sessionId:n}}catch(l){return D}}let c=await r(m(u({sections:e.sections,components:(L=e.components)!=null?L:[],slots:(S=e.slots)!=null?S:[],slotsFrom:e.slotsFrom,registrySlotIds:e.registrySlotIds},e.renderCaps?{renderCaps:e.renderCaps}:{}),{unifiedCaps:!0}),n,{apiKey:e.apiKey,baseUrl:e.baseUrl,origin:e.origin,userAgent:e.userAgent,referer:e.referer,utmParams:e.utmParams,clickIds:e.clickIds,landingPath:e.landingPath,doNotTrack:e.doNotTrack,timeoutMs:e.timeoutMs,persona:e.persona,internal:e.internal,internalToken:i(e.cookies)});return m(u({},c),{sessionId:n})}0&&(module.exports={loadAdaptiveAssignments,loadAdaptiveDecision,preloadAssignments,preloadDecisions,readSessionCookie,signUserId,trackServerGoal});
2
2
  //# sourceMappingURL=server.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/server.ts"],"sourcesContent":["/**\n * Server-only helpers for Next.js / SSR. No React or DOM APIs.\n */\nimport {\n preloadAssignments,\n preloadAssignmentsDetailed,\n readInternalToken,\n readSessionCookie,\n signUserId,\n trackServerGoal,\n type ServerAssignConfig,\n type ServerAssignments,\n} from '@sentientui/core/server';\n\nexport { preloadAssignments, readSessionCookie, signUserId, trackServerGoal };\nexport type { ServerAssignConfig, ServerAssignments };\n\n/** Return value of `loadAdaptiveAssignments` — includes the session ID used for SSR. */\nexport type LoadAdaptiveAssignmentsResult = {\n assignments: ServerAssignments;\n /** The session ID used for SSR assignment. Pass as `ssrSessionId` to `<AdaptiveProvider>`. */\n sessionId: string;\n /** Components the operator moved onto the shared track: not in\n * `assignments`. Pass as `initialUnified` to `<AdaptiveProvider>`. */\n unified: string[];\n};\n\nexport type LoadAdaptiveAssignmentsOptions = {\n /** Next.js `cookies()` return value, or any object with `get(name)`. */\n cookies: { get(name: string): { value: string } | undefined };\n apiKey: string;\n baseUrl: string;\n /** Used when `_snt_uid` is absent (e.g. first visit, many crawlers). */\n createSessionId?: () => string;\n /** Must match a value in the project's `allowed_origins` (e.g. `http://localhost:3001`). */\n origin?: string;\n /** From Next.js `headers().get('user-agent')` — aligns SSR segment with the client. */\n userAgent?: string;\n /** From Next.js `headers().get('referer')`. */\n referer?: string;\n /**\n * `utm_*` params from the landing URL. The Referer header never carries the\n * page's OWN query string, so without this the SSR-minted session has no\n * campaign attribution until the client SDK hydrates and re-upserts.\n * Derive with `extractTrackedParams(searchParams)` from `@sentientui/core/server`.\n */\n utmParams?: Record<string, string>;\n /** Ad-platform click IDs (gclid, fbclid, ttclid, …) from the landing URL — same derivation as `utmParams`. */\n clickIds?: Record<string, string>;\n /** The landing page's path (no query string) — recognises a paid click to a product page or a `/discount/` link on the first decision. */\n landingPath?: string;\n /** Set true when the request carries `DNT: 1` or `Sec-GPC: 1` — skips the SSR session upsert + assignment so no session is minted for an opted-out visitor (audit P4). `AdaptiveRoot` sets this automatically from the request headers. */\n doNotTrack?: boolean;\n /** Milliseconds to wait for the API before returning default variants. Defaults to 1000 (typical decide is well under 150 ms; the full budget is only reached on a cold start or a distant API). */\n timeoutMs?: number;\n /**\n * Declared persona — the role your app already knows for this visitor (e.g.\n * from your auth context: 'admin', 'evaluator'). Must be a key in the\n * project's persona vocabulary; unrecognized values are ignored server-side.\n * Never a user id or email.\n */\n persona?: string;\n /**\n * Your team / a test site — the same flag as `<AdaptiveProvider internal>`,\n * sent on the SSR upsert and decide so a server-rendered first page is\n * never counted or learned from. The request's `sentient_internal` cookie\n * (the \"mark this browser\" link) is read from `cookies` and forwarded too.\n */\n internal?: boolean;\n};\n\nfunction defaultSessionId(): string {\n if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {\n return crypto.randomUUID();\n }\n return `snt-${Date.now()}-${Math.random().toString(36).slice(2, 11)}`;\n}\n\n/**\n * Fetches bandit assignments on the server for SEO-safe HTML.\n * Pass `assignments` as `initialAssignments` and `sessionId` as `ssrSessionId`\n * on `<AdaptiveProvider>` so the client adopts the same session on first visit.\n */\nexport async function loadAdaptiveAssignments(\n components: Array<{ id: string; variantIds: string[] }>,\n options: LoadAdaptiveAssignmentsOptions,\n): Promise<LoadAdaptiveAssignmentsResult> {\n // apiKey is not optional here: the client writes the per-project suffixed\n // cookie, so an un-keyed read missed every returning visitor and minted a\n // fresh orphan session per SSR request (see readSessionCookie in core).\n const sessionId =\n readSessionCookie(options.cookies, options.apiKey) ??\n options.createSessionId?.() ??\n defaultSessionId();\n\n // With the unified cap: a moved component is not assigned (nothing is\n // recorded) and comes back in `unified`, so the page renders it on the\n // shared track instead of seeding the frozen variant it would otherwise get.\n const { assignments, unified } = await preloadAssignmentsDetailed(components, sessionId, {\n apiKey: options.apiKey,\n baseUrl: options.baseUrl,\n origin: options.origin,\n userAgent: options.userAgent,\n referer: options.referer,\n utmParams: options.utmParams,\n clickIds: options.clickIds,\n landingPath: options.landingPath,\n doNotTrack: options.doNotTrack,\n timeoutMs: options.timeoutMs,\n persona: options.persona,\n internal: options.internal,\n internalToken: readInternalToken(options.cookies),\n }, { unified: true });\n\n return { assignments, sessionId, unified };\n}\n\nexport { preloadDecisions } from '@sentientui/core/server';\nexport type { DecideResult, SlotDeclInput, SlotResult } from '@sentientui/core/server';\n\n/** Return value of `loadAdaptiveDecision` — includes the session ID used for SSR. */\nexport type LoadAdaptiveDecisionResult = import('@sentientui/core/server').DecideResult & {\n sessionId: string;\n};\n\nexport type LoadAdaptiveDecisionOptions = LoadAdaptiveAssignmentsOptions & {\n /**\n * Section IDs in default order. Passed to /v1/decide as the candidate\n * layout. Optional since 0.13.0 — slot-only pages may omit it (at least\n * one of `sections`/`components`/`slots` must be non-empty).\n */\n sections?: string[];\n /** Components to assign in the same decide call. */\n components?: Array<{ id: string; variantIds?: string[] }>;\n /** Adaptive-slot declarations (useAdaptiveTokens / AdaptiveGroup) to decide server-side. */\n slots?: import('@sentientui/core/server').SlotDeclInput[];\n /** 'registry' serves the project's published slot definitions (`<Adaptive id>`)\n * and is the only way `slotConfig`/`palette` come back. Default 'request'.\n * Requires `registrySlotIds`. */\n slotsFrom?: 'request' | 'registry';\n /**\n * Registry mode: the `<Adaptive id>`s THIS page renders — the decide is\n * scoped to exactly these. Required with `slotsFrom: 'registry'`; without it\n * the call downgrades to request mode (with a console.error) instead of\n * recording a close-out trial for every published slot on every page.\n */\n registrySlotIds?: string[];\n /**\n * Registry mode: what each slot on this page can render, keyed by slot id\n * (see `preloadDecisions`). Ids without an entry get core's default caps.\n * A hybrid `<Adaptive variants>{children}</Adaptive>` needs its entry: the\n * server draws `authored.<key>` only for keys the page declares here.\n */\n renderCaps?: Record<string, Omit<import('@sentientui/core').RenderCaps, 'fp'>>;\n};\n\n/**\n * SSR helper for pages with a declared section layout and/or adaptive slots.\n * Calls `/v1/decide` instead of multiple `/v1/assign` round trips.\n * Pass `sessionId` as `ssrSessionId` on `<AdaptiveProvider>` so the client\n * adopts the same session on first visit.\n *\n * Keyless: with no valid `pk_` key this never fetches (no timeout burn).\n * Under the `development` export condition the decision is computed by the\n * deterministic local engine with the same sessionId the client will adopt —\n * server and client agree by construction. In production the engine resolves\n * to a stub and defaults are returned with one console.error.\n */\nexport async function loadAdaptiveDecision(\n options: LoadAdaptiveDecisionOptions,\n): Promise<LoadAdaptiveDecisionResult> {\n const { preloadDecisions, readSessionCookie, readInternalToken } = await import('@sentientui/core/server');\n\n // Keyed read — the client's cookie name is suffixed per project (see\n // loadAdaptiveAssignments above). Works for keyless too: with no pk_ key the\n // client writes the bare legacy name, which the un-suffixed read falls back to.\n const sessionId =\n readSessionCookie(options.cookies, options.apiKey) ??\n options.createSessionId?.() ??\n defaultSessionId();\n\n const keyValid = typeof options.apiKey === 'string' && options.apiKey.startsWith('pk_');\n if (!keyValid) {\n const fallback: LoadAdaptiveDecisionResult = {\n layoutOrder: options.sections ?? [],\n assignments: {},\n slots: {},\n persona: 'unknown',\n confidence: 0,\n sessionId,\n };\n try {\n const mod = (await import('@sentientui/core/local')) as unknown as {\n LOCAL_ENGINE_AVAILABLE: boolean;\n createLocalEngine(opts: { sessionId: string }): {\n decide(input: {\n sections?: string[];\n components?: Array<{ id: string; variantIds?: string[] }>;\n slots?: LoadAdaptiveDecisionOptions['slots'];\n }): {\n layoutOrder: string[] | null;\n assignments: Record<string, string>;\n slots: Record<string, string | Record<string, string>>;\n persona: string;\n confidence: number;\n };\n };\n };\n if (!mod.LOCAL_ENGINE_AVAILABLE) {\n // Pinned message — must byte-match PROD_KEYLESS_ERROR in @sentientui/core.\n console.error(\n '[sentient] No API key configured — nothing is being learned. Set NEXT_PUBLIC_SENTIENT_API_KEY or pass localMode: true for local development.',\n );\n return fallback;\n }\n const outcome = mod.createLocalEngine({ sessionId }).decide({\n sections: options.sections,\n components: options.components ?? [],\n slots: options.slots ?? [],\n });\n return {\n layoutOrder: outcome.layoutOrder ?? options.sections ?? [],\n assignments: outcome.assignments,\n slots: outcome.slots,\n persona: outcome.persona,\n confidence: outcome.confidence,\n sessionId,\n };\n } catch {\n return fallback;\n }\n }\n\n const result = await preloadDecisions(\n {\n sections: options.sections,\n components: options.components ?? [],\n slots: options.slots ?? [],\n slotsFrom: options.slotsFrom,\n registrySlotIds: options.registrySlotIds,\n ...(options.renderCaps ? { renderCaps: options.renderCaps } : {}),\n // Moved components come back in `unified`, not as assignments (see\n // loadAdaptiveAssignments). Pass them as `initialUnified`.\n unifiedCaps: true,\n },\n sessionId,\n {\n apiKey: options.apiKey,\n baseUrl: options.baseUrl,\n origin: options.origin,\n userAgent: options.userAgent,\n referer: options.referer,\n utmParams: options.utmParams,\n clickIds: options.clickIds,\n landingPath: options.landingPath,\n doNotTrack: options.doNotTrack,\n timeoutMs: options.timeoutMs,\n persona: options.persona,\n internal: options.internal,\n internalToken: readInternalToken(options.cookies),\n },\n );\n\n return { ...result, sessionId };\n}\n"],"mappings":"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","names":["server_exports","__export","loadAdaptiveAssignments","loadAdaptiveDecision","__toCommonJS","import_server","defaultSessionId","loadAdaptiveAssignments","components","options","_a","_b","_c","sessionId","assignments","unified","loadAdaptiveDecision","_d","_e","_f","_g","_h","_i","_j","preloadDecisions","readSessionCookie","readInternalToken","fallback","mod","outcome","e","result","__spreadProps","__spreadValues"]}
1
+ {"version":3,"sources":["../src/server.ts"],"sourcesContent":["/**\n * Server-only helpers for Next.js / SSR. No React or DOM APIs.\n */\nimport {\n preloadAssignments,\n preloadAssignmentsDetailed,\n readInternalToken,\n readSessionCookie,\n signUserId,\n trackServerGoal,\n type ServerAssignConfig,\n type ServerAssignments,\n} from '@sentientui/core/server';\n\nexport { preloadAssignments, readSessionCookie, signUserId, trackServerGoal };\nexport type { ServerAssignConfig, ServerAssignments };\n\n/** Return value of `loadAdaptiveAssignments` — includes the session ID used for SSR. */\nexport type LoadAdaptiveAssignmentsResult = {\n assignments: ServerAssignments;\n /** The session ID used for SSR assignment. Pass as `ssrSessionId` to `<AdaptiveProvider>`. */\n sessionId: string;\n /** Components the operator moved onto the shared track: not in\n * `assignments`. Pass as `initialUnified` to `<AdaptiveProvider>`. */\n unified: string[];\n};\n\nexport type LoadAdaptiveAssignmentsOptions = {\n /** Next.js `cookies()` return value, or any object with `get(name)`. */\n cookies: { get(name: string): { value: string } | undefined };\n apiKey: string;\n baseUrl: string;\n /** Used when `_snt_uid` is absent (e.g. first visit, many crawlers). */\n createSessionId?: () => string;\n /** Must match a value in the project's `allowed_origins` (e.g. `http://localhost:3001`). */\n origin?: string;\n /** From Next.js `headers().get('user-agent')` — aligns SSR segment with the client. */\n userAgent?: string;\n /** From Next.js `headers().get('referer')`. */\n referer?: string;\n /**\n * `utm_*` params from the landing URL. The Referer header never carries the\n * page's OWN query string, so without this the SSR-minted session has no\n * campaign attribution until the client SDK hydrates and re-upserts.\n * Derive with `extractTrackedParams(searchParams)` from `@sentientui/core/server`.\n */\n utmParams?: Record<string, string>;\n /** Ad-platform click IDs (gclid, fbclid, ttclid, …) from the landing URL — same derivation as `utmParams`. */\n clickIds?: Record<string, string>;\n /** The landing page's path (no query string) — recognises a paid click to a product page or a `/discount/` link on the first decision. */\n landingPath?: string;\n /** Set true when the request carries `DNT: 1` or `Sec-GPC: 1` — skips the SSR session upsert + assignment so no session is minted for an opted-out visitor (audit P4). `AdaptiveRoot` sets this automatically from the request headers. */\n doNotTrack?: boolean;\n /** Milliseconds to wait for the API before returning default variants. Defaults to 1000 (typical decide is well under 150 ms; the full budget is only reached on a cold start or a distant API). */\n timeoutMs?: number;\n /**\n * Declared persona — the role your app already knows for this visitor (e.g.\n * from your auth context: 'admin', 'evaluator'). Must be a key in the\n * project's persona vocabulary; unrecognized values are ignored server-side.\n * Never a user id or email.\n */\n persona?: string;\n /**\n * Your team / a test site — the same flag as `<AdaptiveProvider internal>`,\n * sent on the SSR upsert and decide so a server-rendered first page is\n * never counted or learned from. The request's `sentient_internal` cookie\n * (the \"mark this browser\" link) is read from `cookies` and forwarded too.\n */\n internal?: boolean;\n};\n\nfunction defaultSessionId(): string {\n if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {\n return crypto.randomUUID();\n }\n return `snt-${Date.now()}-${Math.random().toString(36).slice(2, 11)}`;\n}\n\n/**\n * Fetches bandit assignments on the server for SEO-safe HTML.\n * Pass `assignments` as `initialAssignments` and `sessionId` as `ssrSessionId`\n * on `<AdaptiveProvider>` so the client adopts the same session on first visit.\n */\nexport async function loadAdaptiveAssignments(\n components: Array<{ id: string; variantIds: string[] }>,\n options: LoadAdaptiveAssignmentsOptions,\n): Promise<LoadAdaptiveAssignmentsResult> {\n // apiKey is not optional here: the client writes the per-project suffixed\n // cookie, so an un-keyed read missed every returning visitor and minted a\n // fresh orphan session per SSR request (see readSessionCookie in core).\n const sessionId =\n readSessionCookie(options.cookies, options.apiKey) ??\n options.createSessionId?.() ??\n defaultSessionId();\n\n // With the unified cap: a moved component is not assigned (nothing is\n // recorded) and comes back in `unified`, so the page renders it on the\n // shared track instead of seeding the frozen variant it would otherwise get.\n const { assignments, unified } = await preloadAssignmentsDetailed(components, sessionId, {\n apiKey: options.apiKey,\n baseUrl: options.baseUrl,\n origin: options.origin,\n userAgent: options.userAgent,\n referer: options.referer,\n utmParams: options.utmParams,\n clickIds: options.clickIds,\n landingPath: options.landingPath,\n doNotTrack: options.doNotTrack,\n timeoutMs: options.timeoutMs,\n persona: options.persona,\n internal: options.internal,\n internalToken: readInternalToken(options.cookies),\n }, { unified: true });\n\n return { assignments, sessionId, unified };\n}\n\nexport { preloadDecisions } from '@sentientui/core/server';\nexport type { DecideResult, SlotDeclInput, SlotResult } from '@sentientui/core/server';\n\n/** Return value of `loadAdaptiveDecision` — includes the session ID used for SSR. */\nexport type LoadAdaptiveDecisionResult = import('@sentientui/core/server').DecideResult & {\n sessionId: string;\n};\n\nexport type LoadAdaptiveDecisionOptions = LoadAdaptiveAssignmentsOptions & {\n /**\n * Section IDs in default order. Passed to /v1/decide as the candidate\n * layout. Optional since 0.13.0 — slot-only pages may omit it (at least\n * one of `sections`/`components`/`slots` must be non-empty).\n */\n sections?: string[];\n /** Components to assign in the same decide call. */\n components?: Array<{ id: string; variantIds?: string[] }>;\n /** Adaptive-slot declarations (useAdaptiveTokens / AdaptiveGroup) to decide server-side. */\n slots?: import('@sentientui/core/server').SlotDeclInput[];\n /** 'registry' serves the project's published slot definitions (`<Adaptive id>`)\n * and is the only way `slotConfig`/`palette` come back. Default 'request'.\n * Requires `registrySlotIds`. */\n slotsFrom?: 'request' | 'registry';\n /**\n * Registry mode: the `<Adaptive id>`s THIS page renders — the decide is\n * scoped to exactly these. Required with `slotsFrom: 'registry'`; without it\n * the call downgrades to request mode (with a console.error) instead of\n * recording a close-out trial for every published slot on every page.\n */\n registrySlotIds?: string[];\n /**\n * Registry mode: what each slot on this page can render, keyed by slot id\n * (see `preloadDecisions`). Ids without an entry get core's default caps.\n * A hybrid `<Adaptive variants>{children}</Adaptive>` needs its entry: the\n * server draws `authored.<key>` only for keys the page declares here.\n */\n renderCaps?: Record<string, Omit<import('@sentientui/core').RenderCaps, 'fp'>>;\n};\n\n/**\n * SSR helper for pages with a declared section layout and/or adaptive slots.\n * Calls `/v1/decide` instead of multiple `/v1/assign` round trips.\n * Pass `sessionId` as `ssrSessionId` on `<AdaptiveProvider>` so the client\n * adopts the same session on first visit.\n *\n * Keyless: with no valid `pk_` key this never fetches (no timeout burn).\n * Under the `development` export condition the decision is computed by the\n * deterministic local engine with the same sessionId the client will adopt —\n * server and client agree by construction. In production the engine resolves\n * to a stub and defaults are returned with one console.error.\n */\nexport async function loadAdaptiveDecision(\n options: LoadAdaptiveDecisionOptions,\n): Promise<LoadAdaptiveDecisionResult> {\n const { preloadDecisions, readSessionCookie, readInternalToken } = await import('@sentientui/core/server');\n\n // Keyed read — the client's cookie name is suffixed per project (see\n // loadAdaptiveAssignments above). Works for keyless too: with no pk_ key the\n // client writes the bare legacy name, which the un-suffixed read falls back to.\n const sessionId =\n readSessionCookie(options.cookies, options.apiKey) ??\n options.createSessionId?.() ??\n defaultSessionId();\n\n const keyValid = typeof options.apiKey === 'string' && options.apiKey.startsWith('pk_');\n if (!keyValid) {\n const fallback: LoadAdaptiveDecisionResult = {\n layoutOrder: options.sections ?? [],\n assignments: {},\n slots: {},\n persona: 'unknown',\n confidence: 0,\n sessionId,\n };\n try {\n const mod = (await import('@sentientui/core/local')) as unknown as {\n LOCAL_ENGINE_AVAILABLE: boolean;\n createLocalEngine(opts: { sessionId: string }): {\n decide(input: {\n sections?: string[];\n components?: Array<{ id: string; variantIds?: string[] }>;\n slots?: LoadAdaptiveDecisionOptions['slots'];\n }): {\n layoutOrder: string[] | null;\n assignments: Record<string, string>;\n slots: Record<string, string | Record<string, string>>;\n persona: string;\n confidence: number;\n };\n };\n };\n if (!mod.LOCAL_ENGINE_AVAILABLE) {\n // Pinned message — must byte-match PROD_KEYLESS_ERROR in @sentientui/core.\n console.error(\n '[sentient] No API key configured — nothing is being learned. Set NEXT_PUBLIC_SENTIENT_API_KEY (Vite: VITE_SENTIENT_API_KEY) or localMode: true.',\n );\n return fallback;\n }\n const outcome = mod.createLocalEngine({ sessionId }).decide({\n sections: options.sections,\n components: options.components ?? [],\n slots: options.slots ?? [],\n });\n return {\n layoutOrder: outcome.layoutOrder ?? options.sections ?? [],\n assignments: outcome.assignments,\n slots: outcome.slots,\n persona: outcome.persona,\n confidence: outcome.confidence,\n sessionId,\n };\n } catch {\n return fallback;\n }\n }\n\n const result = await preloadDecisions(\n {\n sections: options.sections,\n components: options.components ?? [],\n slots: options.slots ?? [],\n slotsFrom: options.slotsFrom,\n registrySlotIds: options.registrySlotIds,\n ...(options.renderCaps ? { renderCaps: options.renderCaps } : {}),\n // Moved components come back in `unified`, not as assignments (see\n // loadAdaptiveAssignments). Pass them as `initialUnified`.\n unifiedCaps: true,\n },\n sessionId,\n {\n apiKey: options.apiKey,\n baseUrl: options.baseUrl,\n origin: options.origin,\n userAgent: options.userAgent,\n referer: options.referer,\n utmParams: options.utmParams,\n clickIds: options.clickIds,\n landingPath: options.landingPath,\n doNotTrack: options.doNotTrack,\n timeoutMs: options.timeoutMs,\n persona: options.persona,\n internal: options.internal,\n internalToken: readInternalToken(options.cookies),\n },\n );\n\n return { ...result, sessionId };\n}\n"],"mappings":"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","names":["server_exports","__export","loadAdaptiveAssignments","loadAdaptiveDecision","__toCommonJS","import_server","defaultSessionId","loadAdaptiveAssignments","components","options","_a","_b","_c","sessionId","assignments","unified","loadAdaptiveDecision","_d","_e","_f","_g","_h","_i","_j","preloadDecisions","readSessionCookie","readInternalToken","fallback","mod","outcome","e","result","__spreadProps","__spreadValues"]}
package/dist/server.mjs CHANGED
@@ -1,2 +1,2 @@
1
- var R=Object.defineProperty,C=Object.defineProperties;var N=Object.getOwnPropertyDescriptors;var S=Object.getOwnPropertySymbols;var O=Object.prototype.hasOwnProperty,b=Object.prototype.propertyIsEnumerable;var D=(e,r,s)=>r in e?R(e,r,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[r]=s,l=(e,r)=>{for(var s in r||(r={}))O.call(r,s)&&D(e,s,r[s]);if(S)for(var s of S(r))b.call(r,s)&&D(e,s,r[s]);return e},g=(e,r)=>C(e,N(r));import{preloadAssignments as h,preloadAssignmentsDetailed as E,readInternalToken as T,readSessionCookie as U,signUserId as _,trackServerGoal as w}from"@sentientui/core/server";import{preloadDecisions as G}from"@sentientui/core/server";function P(){return typeof crypto!="undefined"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`snt-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}async function M(e,r){var d,a,t;let s=(t=(a=U(r.cookies,r.apiKey))!=null?a:(d=r.createSessionId)==null?void 0:d.call(r))!=null?t:P(),{assignments:o,unified:n}=await E(e,s,{apiKey:r.apiKey,baseUrl:r.baseUrl,origin:r.origin,userAgent:r.userAgent,referer:r.referer,utmParams:r.utmParams,clickIds:r.clickIds,landingPath:r.landingPath,doNotTrack:r.doNotTrack,timeoutMs:r.timeoutMs,persona:r.persona,internal:r.internal,internalToken:T(r.cookies)},{unified:!0});return{assignments:o,sessionId:s,unified:n}}async function V(e){var t,u,m,A,y,p,f,I,k,v;let{preloadDecisions:r,readSessionCookie:s,readInternalToken:o}=await import("@sentientui/core/server"),n=(m=(u=s(e.cookies,e.apiKey))!=null?u:(t=e.createSessionId)==null?void 0:t.call(e))!=null?m:P();if(!(typeof e.apiKey=="string"&&e.apiKey.startsWith("pk_"))){let L={layoutOrder:(A=e.sections)!=null?A:[],assignments:{},slots:{},persona:"unknown",confidence:0,sessionId:n};try{let c=await import("@sentientui/core/local");if(!c.LOCAL_ENGINE_AVAILABLE)return console.error("[sentient] No API key configured \u2014 nothing is being learned. Set NEXT_PUBLIC_SENTIENT_API_KEY or pass localMode: true for local development."),L;let i=c.createLocalEngine({sessionId:n}).decide({sections:e.sections,components:(y=e.components)!=null?y:[],slots:(p=e.slots)!=null?p:[]});return{layoutOrder:(I=(f=i.layoutOrder)!=null?f:e.sections)!=null?I:[],assignments:i.assignments,slots:i.slots,persona:i.persona,confidence:i.confidence,sessionId:n}}catch(c){return L}}let a=await r(g(l({sections:e.sections,components:(k=e.components)!=null?k:[],slots:(v=e.slots)!=null?v:[],slotsFrom:e.slotsFrom,registrySlotIds:e.registrySlotIds},e.renderCaps?{renderCaps:e.renderCaps}:{}),{unifiedCaps:!0}),n,{apiKey:e.apiKey,baseUrl:e.baseUrl,origin:e.origin,userAgent:e.userAgent,referer:e.referer,utmParams:e.utmParams,clickIds:e.clickIds,landingPath:e.landingPath,doNotTrack:e.doNotTrack,timeoutMs:e.timeoutMs,persona:e.persona,internal:e.internal,internalToken:o(e.cookies)});return g(l({},a),{sessionId:n})}export{M as loadAdaptiveAssignments,V as loadAdaptiveDecision,h as preloadAssignments,G as preloadDecisions,U as readSessionCookie,_ as signUserId,w as trackServerGoal};
1
+ var P=Object.defineProperty,N=Object.defineProperties;var R=Object.getOwnPropertyDescriptors;var S=Object.getOwnPropertySymbols;var T=Object.prototype.hasOwnProperty,C=Object.prototype.propertyIsEnumerable;var D=(e,r,s)=>r in e?P(e,r,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[r]=s,g=(e,r)=>{for(var s in r||(r={}))T.call(r,s)&&D(e,s,r[s]);if(S)for(var s of S(r))C.call(r,s)&&D(e,s,r[s]);return e},l=(e,r)=>N(e,R(r));import{preloadAssignments as x,preloadAssignmentsDetailed as O,readInternalToken as b,readSessionCookie as _,signUserId as h,trackServerGoal as w}from"@sentientui/core/server";import{preloadDecisions as G}from"@sentientui/core/server";function E(){return typeof crypto!="undefined"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`snt-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}async function M(e,r){var d,a,t;let s=(t=(a=_(r.cookies,r.apiKey))!=null?a:(d=r.createSessionId)==null?void 0:d.call(r))!=null?t:E(),{assignments:o,unified:n}=await O(e,s,{apiKey:r.apiKey,baseUrl:r.baseUrl,origin:r.origin,userAgent:r.userAgent,referer:r.referer,utmParams:r.utmParams,clickIds:r.clickIds,landingPath:r.landingPath,doNotTrack:r.doNotTrack,timeoutMs:r.timeoutMs,persona:r.persona,internal:r.internal,internalToken:b(r.cookies)},{unified:!0});return{assignments:o,sessionId:s,unified:n}}async function V(e){var t,u,m,A,y,I,p,f,k,v;let{preloadDecisions:r,readSessionCookie:s,readInternalToken:o}=await import("@sentientui/core/server"),n=(m=(u=s(e.cookies,e.apiKey))!=null?u:(t=e.createSessionId)==null?void 0:t.call(e))!=null?m:E();if(!(typeof e.apiKey=="string"&&e.apiKey.startsWith("pk_"))){let L={layoutOrder:(A=e.sections)!=null?A:[],assignments:{},slots:{},persona:"unknown",confidence:0,sessionId:n};try{let c=await import("@sentientui/core/local");if(!c.LOCAL_ENGINE_AVAILABLE)return console.error("[sentient] No API key configured \u2014 nothing is being learned. Set NEXT_PUBLIC_SENTIENT_API_KEY (Vite: VITE_SENTIENT_API_KEY) or localMode: true."),L;let i=c.createLocalEngine({sessionId:n}).decide({sections:e.sections,components:(y=e.components)!=null?y:[],slots:(I=e.slots)!=null?I:[]});return{layoutOrder:(f=(p=i.layoutOrder)!=null?p:e.sections)!=null?f:[],assignments:i.assignments,slots:i.slots,persona:i.persona,confidence:i.confidence,sessionId:n}}catch(c){return L}}let a=await r(l(g({sections:e.sections,components:(k=e.components)!=null?k:[],slots:(v=e.slots)!=null?v:[],slotsFrom:e.slotsFrom,registrySlotIds:e.registrySlotIds},e.renderCaps?{renderCaps:e.renderCaps}:{}),{unifiedCaps:!0}),n,{apiKey:e.apiKey,baseUrl:e.baseUrl,origin:e.origin,userAgent:e.userAgent,referer:e.referer,utmParams:e.utmParams,clickIds:e.clickIds,landingPath:e.landingPath,doNotTrack:e.doNotTrack,timeoutMs:e.timeoutMs,persona:e.persona,internal:e.internal,internalToken:o(e.cookies)});return l(g({},a),{sessionId:n})}export{M as loadAdaptiveAssignments,V as loadAdaptiveDecision,x as preloadAssignments,G as preloadDecisions,_ as readSessionCookie,h as signUserId,w as trackServerGoal};
2
2
  //# sourceMappingURL=server.mjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/server.ts"],"sourcesContent":["/**\n * Server-only helpers for Next.js / SSR. No React or DOM APIs.\n */\nimport {\n preloadAssignments,\n preloadAssignmentsDetailed,\n readInternalToken,\n readSessionCookie,\n signUserId,\n trackServerGoal,\n type ServerAssignConfig,\n type ServerAssignments,\n} from '@sentientui/core/server';\n\nexport { preloadAssignments, readSessionCookie, signUserId, trackServerGoal };\nexport type { ServerAssignConfig, ServerAssignments };\n\n/** Return value of `loadAdaptiveAssignments` — includes the session ID used for SSR. */\nexport type LoadAdaptiveAssignmentsResult = {\n assignments: ServerAssignments;\n /** The session ID used for SSR assignment. Pass as `ssrSessionId` to `<AdaptiveProvider>`. */\n sessionId: string;\n /** Components the operator moved onto the shared track: not in\n * `assignments`. Pass as `initialUnified` to `<AdaptiveProvider>`. */\n unified: string[];\n};\n\nexport type LoadAdaptiveAssignmentsOptions = {\n /** Next.js `cookies()` return value, or any object with `get(name)`. */\n cookies: { get(name: string): { value: string } | undefined };\n apiKey: string;\n baseUrl: string;\n /** Used when `_snt_uid` is absent (e.g. first visit, many crawlers). */\n createSessionId?: () => string;\n /** Must match a value in the project's `allowed_origins` (e.g. `http://localhost:3001`). */\n origin?: string;\n /** From Next.js `headers().get('user-agent')` — aligns SSR segment with the client. */\n userAgent?: string;\n /** From Next.js `headers().get('referer')`. */\n referer?: string;\n /**\n * `utm_*` params from the landing URL. The Referer header never carries the\n * page's OWN query string, so without this the SSR-minted session has no\n * campaign attribution until the client SDK hydrates and re-upserts.\n * Derive with `extractTrackedParams(searchParams)` from `@sentientui/core/server`.\n */\n utmParams?: Record<string, string>;\n /** Ad-platform click IDs (gclid, fbclid, ttclid, …) from the landing URL — same derivation as `utmParams`. */\n clickIds?: Record<string, string>;\n /** The landing page's path (no query string) — recognises a paid click to a product page or a `/discount/` link on the first decision. */\n landingPath?: string;\n /** Set true when the request carries `DNT: 1` or `Sec-GPC: 1` — skips the SSR session upsert + assignment so no session is minted for an opted-out visitor (audit P4). `AdaptiveRoot` sets this automatically from the request headers. */\n doNotTrack?: boolean;\n /** Milliseconds to wait for the API before returning default variants. Defaults to 1000 (typical decide is well under 150 ms; the full budget is only reached on a cold start or a distant API). */\n timeoutMs?: number;\n /**\n * Declared persona — the role your app already knows for this visitor (e.g.\n * from your auth context: 'admin', 'evaluator'). Must be a key in the\n * project's persona vocabulary; unrecognized values are ignored server-side.\n * Never a user id or email.\n */\n persona?: string;\n /**\n * Your team / a test site — the same flag as `<AdaptiveProvider internal>`,\n * sent on the SSR upsert and decide so a server-rendered first page is\n * never counted or learned from. The request's `sentient_internal` cookie\n * (the \"mark this browser\" link) is read from `cookies` and forwarded too.\n */\n internal?: boolean;\n};\n\nfunction defaultSessionId(): string {\n if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {\n return crypto.randomUUID();\n }\n return `snt-${Date.now()}-${Math.random().toString(36).slice(2, 11)}`;\n}\n\n/**\n * Fetches bandit assignments on the server for SEO-safe HTML.\n * Pass `assignments` as `initialAssignments` and `sessionId` as `ssrSessionId`\n * on `<AdaptiveProvider>` so the client adopts the same session on first visit.\n */\nexport async function loadAdaptiveAssignments(\n components: Array<{ id: string; variantIds: string[] }>,\n options: LoadAdaptiveAssignmentsOptions,\n): Promise<LoadAdaptiveAssignmentsResult> {\n // apiKey is not optional here: the client writes the per-project suffixed\n // cookie, so an un-keyed read missed every returning visitor and minted a\n // fresh orphan session per SSR request (see readSessionCookie in core).\n const sessionId =\n readSessionCookie(options.cookies, options.apiKey) ??\n options.createSessionId?.() ??\n defaultSessionId();\n\n // With the unified cap: a moved component is not assigned (nothing is\n // recorded) and comes back in `unified`, so the page renders it on the\n // shared track instead of seeding the frozen variant it would otherwise get.\n const { assignments, unified } = await preloadAssignmentsDetailed(components, sessionId, {\n apiKey: options.apiKey,\n baseUrl: options.baseUrl,\n origin: options.origin,\n userAgent: options.userAgent,\n referer: options.referer,\n utmParams: options.utmParams,\n clickIds: options.clickIds,\n landingPath: options.landingPath,\n doNotTrack: options.doNotTrack,\n timeoutMs: options.timeoutMs,\n persona: options.persona,\n internal: options.internal,\n internalToken: readInternalToken(options.cookies),\n }, { unified: true });\n\n return { assignments, sessionId, unified };\n}\n\nexport { preloadDecisions } from '@sentientui/core/server';\nexport type { DecideResult, SlotDeclInput, SlotResult } from '@sentientui/core/server';\n\n/** Return value of `loadAdaptiveDecision` — includes the session ID used for SSR. */\nexport type LoadAdaptiveDecisionResult = import('@sentientui/core/server').DecideResult & {\n sessionId: string;\n};\n\nexport type LoadAdaptiveDecisionOptions = LoadAdaptiveAssignmentsOptions & {\n /**\n * Section IDs in default order. Passed to /v1/decide as the candidate\n * layout. Optional since 0.13.0 — slot-only pages may omit it (at least\n * one of `sections`/`components`/`slots` must be non-empty).\n */\n sections?: string[];\n /** Components to assign in the same decide call. */\n components?: Array<{ id: string; variantIds?: string[] }>;\n /** Adaptive-slot declarations (useAdaptiveTokens / AdaptiveGroup) to decide server-side. */\n slots?: import('@sentientui/core/server').SlotDeclInput[];\n /** 'registry' serves the project's published slot definitions (`<Adaptive id>`)\n * and is the only way `slotConfig`/`palette` come back. Default 'request'.\n * Requires `registrySlotIds`. */\n slotsFrom?: 'request' | 'registry';\n /**\n * Registry mode: the `<Adaptive id>`s THIS page renders — the decide is\n * scoped to exactly these. Required with `slotsFrom: 'registry'`; without it\n * the call downgrades to request mode (with a console.error) instead of\n * recording a close-out trial for every published slot on every page.\n */\n registrySlotIds?: string[];\n /**\n * Registry mode: what each slot on this page can render, keyed by slot id\n * (see `preloadDecisions`). Ids without an entry get core's default caps.\n * A hybrid `<Adaptive variants>{children}</Adaptive>` needs its entry: the\n * server draws `authored.<key>` only for keys the page declares here.\n */\n renderCaps?: Record<string, Omit<import('@sentientui/core').RenderCaps, 'fp'>>;\n};\n\n/**\n * SSR helper for pages with a declared section layout and/or adaptive slots.\n * Calls `/v1/decide` instead of multiple `/v1/assign` round trips.\n * Pass `sessionId` as `ssrSessionId` on `<AdaptiveProvider>` so the client\n * adopts the same session on first visit.\n *\n * Keyless: with no valid `pk_` key this never fetches (no timeout burn).\n * Under the `development` export condition the decision is computed by the\n * deterministic local engine with the same sessionId the client will adopt —\n * server and client agree by construction. In production the engine resolves\n * to a stub and defaults are returned with one console.error.\n */\nexport async function loadAdaptiveDecision(\n options: LoadAdaptiveDecisionOptions,\n): Promise<LoadAdaptiveDecisionResult> {\n const { preloadDecisions, readSessionCookie, readInternalToken } = await import('@sentientui/core/server');\n\n // Keyed read — the client's cookie name is suffixed per project (see\n // loadAdaptiveAssignments above). Works for keyless too: with no pk_ key the\n // client writes the bare legacy name, which the un-suffixed read falls back to.\n const sessionId =\n readSessionCookie(options.cookies, options.apiKey) ??\n options.createSessionId?.() ??\n defaultSessionId();\n\n const keyValid = typeof options.apiKey === 'string' && options.apiKey.startsWith('pk_');\n if (!keyValid) {\n const fallback: LoadAdaptiveDecisionResult = {\n layoutOrder: options.sections ?? [],\n assignments: {},\n slots: {},\n persona: 'unknown',\n confidence: 0,\n sessionId,\n };\n try {\n const mod = (await import('@sentientui/core/local')) as unknown as {\n LOCAL_ENGINE_AVAILABLE: boolean;\n createLocalEngine(opts: { sessionId: string }): {\n decide(input: {\n sections?: string[];\n components?: Array<{ id: string; variantIds?: string[] }>;\n slots?: LoadAdaptiveDecisionOptions['slots'];\n }): {\n layoutOrder: string[] | null;\n assignments: Record<string, string>;\n slots: Record<string, string | Record<string, string>>;\n persona: string;\n confidence: number;\n };\n };\n };\n if (!mod.LOCAL_ENGINE_AVAILABLE) {\n // Pinned message — must byte-match PROD_KEYLESS_ERROR in @sentientui/core.\n console.error(\n '[sentient] No API key configured — nothing is being learned. Set NEXT_PUBLIC_SENTIENT_API_KEY or pass localMode: true for local development.',\n );\n return fallback;\n }\n const outcome = mod.createLocalEngine({ sessionId }).decide({\n sections: options.sections,\n components: options.components ?? [],\n slots: options.slots ?? [],\n });\n return {\n layoutOrder: outcome.layoutOrder ?? options.sections ?? [],\n assignments: outcome.assignments,\n slots: outcome.slots,\n persona: outcome.persona,\n confidence: outcome.confidence,\n sessionId,\n };\n } catch {\n return fallback;\n }\n }\n\n const result = await preloadDecisions(\n {\n sections: options.sections,\n components: options.components ?? [],\n slots: options.slots ?? [],\n slotsFrom: options.slotsFrom,\n registrySlotIds: options.registrySlotIds,\n ...(options.renderCaps ? { renderCaps: options.renderCaps } : {}),\n // Moved components come back in `unified`, not as assignments (see\n // loadAdaptiveAssignments). Pass them as `initialUnified`.\n unifiedCaps: true,\n },\n sessionId,\n {\n apiKey: options.apiKey,\n baseUrl: options.baseUrl,\n origin: options.origin,\n userAgent: options.userAgent,\n referer: options.referer,\n utmParams: options.utmParams,\n clickIds: options.clickIds,\n landingPath: options.landingPath,\n doNotTrack: options.doNotTrack,\n timeoutMs: options.timeoutMs,\n persona: options.persona,\n internal: options.internal,\n internalToken: readInternalToken(options.cookies),\n },\n );\n\n return { ...result, sessionId };\n}\n"],"mappings":"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","names":["preloadAssignments","preloadAssignmentsDetailed","readInternalToken","readSessionCookie","signUserId","trackServerGoal","preloadDecisions","defaultSessionId","loadAdaptiveAssignments","components","options","_a","_b","_c","sessionId","readSessionCookie","assignments","unified","preloadAssignmentsDetailed","readInternalToken","loadAdaptiveDecision","_d","_e","_f","_g","_h","_i","_j","preloadDecisions","fallback","mod","outcome","e","result","__spreadProps","__spreadValues"]}
1
+ {"version":3,"sources":["../src/server.ts"],"sourcesContent":["/**\n * Server-only helpers for Next.js / SSR. No React or DOM APIs.\n */\nimport {\n preloadAssignments,\n preloadAssignmentsDetailed,\n readInternalToken,\n readSessionCookie,\n signUserId,\n trackServerGoal,\n type ServerAssignConfig,\n type ServerAssignments,\n} from '@sentientui/core/server';\n\nexport { preloadAssignments, readSessionCookie, signUserId, trackServerGoal };\nexport type { ServerAssignConfig, ServerAssignments };\n\n/** Return value of `loadAdaptiveAssignments` — includes the session ID used for SSR. */\nexport type LoadAdaptiveAssignmentsResult = {\n assignments: ServerAssignments;\n /** The session ID used for SSR assignment. Pass as `ssrSessionId` to `<AdaptiveProvider>`. */\n sessionId: string;\n /** Components the operator moved onto the shared track: not in\n * `assignments`. Pass as `initialUnified` to `<AdaptiveProvider>`. */\n unified: string[];\n};\n\nexport type LoadAdaptiveAssignmentsOptions = {\n /** Next.js `cookies()` return value, or any object with `get(name)`. */\n cookies: { get(name: string): { value: string } | undefined };\n apiKey: string;\n baseUrl: string;\n /** Used when `_snt_uid` is absent (e.g. first visit, many crawlers). */\n createSessionId?: () => string;\n /** Must match a value in the project's `allowed_origins` (e.g. `http://localhost:3001`). */\n origin?: string;\n /** From Next.js `headers().get('user-agent')` — aligns SSR segment with the client. */\n userAgent?: string;\n /** From Next.js `headers().get('referer')`. */\n referer?: string;\n /**\n * `utm_*` params from the landing URL. The Referer header never carries the\n * page's OWN query string, so without this the SSR-minted session has no\n * campaign attribution until the client SDK hydrates and re-upserts.\n * Derive with `extractTrackedParams(searchParams)` from `@sentientui/core/server`.\n */\n utmParams?: Record<string, string>;\n /** Ad-platform click IDs (gclid, fbclid, ttclid, …) from the landing URL — same derivation as `utmParams`. */\n clickIds?: Record<string, string>;\n /** The landing page's path (no query string) — recognises a paid click to a product page or a `/discount/` link on the first decision. */\n landingPath?: string;\n /** Set true when the request carries `DNT: 1` or `Sec-GPC: 1` — skips the SSR session upsert + assignment so no session is minted for an opted-out visitor (audit P4). `AdaptiveRoot` sets this automatically from the request headers. */\n doNotTrack?: boolean;\n /** Milliseconds to wait for the API before returning default variants. Defaults to 1000 (typical decide is well under 150 ms; the full budget is only reached on a cold start or a distant API). */\n timeoutMs?: number;\n /**\n * Declared persona — the role your app already knows for this visitor (e.g.\n * from your auth context: 'admin', 'evaluator'). Must be a key in the\n * project's persona vocabulary; unrecognized values are ignored server-side.\n * Never a user id or email.\n */\n persona?: string;\n /**\n * Your team / a test site — the same flag as `<AdaptiveProvider internal>`,\n * sent on the SSR upsert and decide so a server-rendered first page is\n * never counted or learned from. The request's `sentient_internal` cookie\n * (the \"mark this browser\" link) is read from `cookies` and forwarded too.\n */\n internal?: boolean;\n};\n\nfunction defaultSessionId(): string {\n if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {\n return crypto.randomUUID();\n }\n return `snt-${Date.now()}-${Math.random().toString(36).slice(2, 11)}`;\n}\n\n/**\n * Fetches bandit assignments on the server for SEO-safe HTML.\n * Pass `assignments` as `initialAssignments` and `sessionId` as `ssrSessionId`\n * on `<AdaptiveProvider>` so the client adopts the same session on first visit.\n */\nexport async function loadAdaptiveAssignments(\n components: Array<{ id: string; variantIds: string[] }>,\n options: LoadAdaptiveAssignmentsOptions,\n): Promise<LoadAdaptiveAssignmentsResult> {\n // apiKey is not optional here: the client writes the per-project suffixed\n // cookie, so an un-keyed read missed every returning visitor and minted a\n // fresh orphan session per SSR request (see readSessionCookie in core).\n const sessionId =\n readSessionCookie(options.cookies, options.apiKey) ??\n options.createSessionId?.() ??\n defaultSessionId();\n\n // With the unified cap: a moved component is not assigned (nothing is\n // recorded) and comes back in `unified`, so the page renders it on the\n // shared track instead of seeding the frozen variant it would otherwise get.\n const { assignments, unified } = await preloadAssignmentsDetailed(components, sessionId, {\n apiKey: options.apiKey,\n baseUrl: options.baseUrl,\n origin: options.origin,\n userAgent: options.userAgent,\n referer: options.referer,\n utmParams: options.utmParams,\n clickIds: options.clickIds,\n landingPath: options.landingPath,\n doNotTrack: options.doNotTrack,\n timeoutMs: options.timeoutMs,\n persona: options.persona,\n internal: options.internal,\n internalToken: readInternalToken(options.cookies),\n }, { unified: true });\n\n return { assignments, sessionId, unified };\n}\n\nexport { preloadDecisions } from '@sentientui/core/server';\nexport type { DecideResult, SlotDeclInput, SlotResult } from '@sentientui/core/server';\n\n/** Return value of `loadAdaptiveDecision` — includes the session ID used for SSR. */\nexport type LoadAdaptiveDecisionResult = import('@sentientui/core/server').DecideResult & {\n sessionId: string;\n};\n\nexport type LoadAdaptiveDecisionOptions = LoadAdaptiveAssignmentsOptions & {\n /**\n * Section IDs in default order. Passed to /v1/decide as the candidate\n * layout. Optional since 0.13.0 — slot-only pages may omit it (at least\n * one of `sections`/`components`/`slots` must be non-empty).\n */\n sections?: string[];\n /** Components to assign in the same decide call. */\n components?: Array<{ id: string; variantIds?: string[] }>;\n /** Adaptive-slot declarations (useAdaptiveTokens / AdaptiveGroup) to decide server-side. */\n slots?: import('@sentientui/core/server').SlotDeclInput[];\n /** 'registry' serves the project's published slot definitions (`<Adaptive id>`)\n * and is the only way `slotConfig`/`palette` come back. Default 'request'.\n * Requires `registrySlotIds`. */\n slotsFrom?: 'request' | 'registry';\n /**\n * Registry mode: the `<Adaptive id>`s THIS page renders — the decide is\n * scoped to exactly these. Required with `slotsFrom: 'registry'`; without it\n * the call downgrades to request mode (with a console.error) instead of\n * recording a close-out trial for every published slot on every page.\n */\n registrySlotIds?: string[];\n /**\n * Registry mode: what each slot on this page can render, keyed by slot id\n * (see `preloadDecisions`). Ids without an entry get core's default caps.\n * A hybrid `<Adaptive variants>{children}</Adaptive>` needs its entry: the\n * server draws `authored.<key>` only for keys the page declares here.\n */\n renderCaps?: Record<string, Omit<import('@sentientui/core').RenderCaps, 'fp'>>;\n};\n\n/**\n * SSR helper for pages with a declared section layout and/or adaptive slots.\n * Calls `/v1/decide` instead of multiple `/v1/assign` round trips.\n * Pass `sessionId` as `ssrSessionId` on `<AdaptiveProvider>` so the client\n * adopts the same session on first visit.\n *\n * Keyless: with no valid `pk_` key this never fetches (no timeout burn).\n * Under the `development` export condition the decision is computed by the\n * deterministic local engine with the same sessionId the client will adopt —\n * server and client agree by construction. In production the engine resolves\n * to a stub and defaults are returned with one console.error.\n */\nexport async function loadAdaptiveDecision(\n options: LoadAdaptiveDecisionOptions,\n): Promise<LoadAdaptiveDecisionResult> {\n const { preloadDecisions, readSessionCookie, readInternalToken } = await import('@sentientui/core/server');\n\n // Keyed read — the client's cookie name is suffixed per project (see\n // loadAdaptiveAssignments above). Works for keyless too: with no pk_ key the\n // client writes the bare legacy name, which the un-suffixed read falls back to.\n const sessionId =\n readSessionCookie(options.cookies, options.apiKey) ??\n options.createSessionId?.() ??\n defaultSessionId();\n\n const keyValid = typeof options.apiKey === 'string' && options.apiKey.startsWith('pk_');\n if (!keyValid) {\n const fallback: LoadAdaptiveDecisionResult = {\n layoutOrder: options.sections ?? [],\n assignments: {},\n slots: {},\n persona: 'unknown',\n confidence: 0,\n sessionId,\n };\n try {\n const mod = (await import('@sentientui/core/local')) as unknown as {\n LOCAL_ENGINE_AVAILABLE: boolean;\n createLocalEngine(opts: { sessionId: string }): {\n decide(input: {\n sections?: string[];\n components?: Array<{ id: string; variantIds?: string[] }>;\n slots?: LoadAdaptiveDecisionOptions['slots'];\n }): {\n layoutOrder: string[] | null;\n assignments: Record<string, string>;\n slots: Record<string, string | Record<string, string>>;\n persona: string;\n confidence: number;\n };\n };\n };\n if (!mod.LOCAL_ENGINE_AVAILABLE) {\n // Pinned message — must byte-match PROD_KEYLESS_ERROR in @sentientui/core.\n console.error(\n '[sentient] No API key configured — nothing is being learned. Set NEXT_PUBLIC_SENTIENT_API_KEY (Vite: VITE_SENTIENT_API_KEY) or localMode: true.',\n );\n return fallback;\n }\n const outcome = mod.createLocalEngine({ sessionId }).decide({\n sections: options.sections,\n components: options.components ?? [],\n slots: options.slots ?? [],\n });\n return {\n layoutOrder: outcome.layoutOrder ?? options.sections ?? [],\n assignments: outcome.assignments,\n slots: outcome.slots,\n persona: outcome.persona,\n confidence: outcome.confidence,\n sessionId,\n };\n } catch {\n return fallback;\n }\n }\n\n const result = await preloadDecisions(\n {\n sections: options.sections,\n components: options.components ?? [],\n slots: options.slots ?? [],\n slotsFrom: options.slotsFrom,\n registrySlotIds: options.registrySlotIds,\n ...(options.renderCaps ? { renderCaps: options.renderCaps } : {}),\n // Moved components come back in `unified`, not as assignments (see\n // loadAdaptiveAssignments). Pass them as `initialUnified`.\n unifiedCaps: true,\n },\n sessionId,\n {\n apiKey: options.apiKey,\n baseUrl: options.baseUrl,\n origin: options.origin,\n userAgent: options.userAgent,\n referer: options.referer,\n utmParams: options.utmParams,\n clickIds: options.clickIds,\n landingPath: options.landingPath,\n doNotTrack: options.doNotTrack,\n timeoutMs: options.timeoutMs,\n persona: options.persona,\n internal: options.internal,\n internalToken: readInternalToken(options.cookies),\n },\n );\n\n return { ...result, sessionId };\n}\n"],"mappings":"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","names":["preloadAssignments","preloadAssignmentsDetailed","readInternalToken","readSessionCookie","signUserId","trackServerGoal","preloadDecisions","defaultSessionId","loadAdaptiveAssignments","components","options","_a","_b","_c","sessionId","readSessionCookie","assignments","unified","preloadAssignmentsDetailed","readInternalToken","loadAdaptiveDecision","_d","_e","_f","_g","_h","_i","_j","preloadDecisions","fallback","mod","outcome","e","result","__spreadProps","__spreadValues"]}
@@ -1,3 +1,3 @@
1
1
  'use client';
2
- "use strict";var Le=Object.create;var G=Object.defineProperty,Ge=Object.defineProperties,Fe=Object.getOwnPropertyDescriptor,Ue=Object.getOwnPropertyDescriptors,We=Object.getOwnPropertyNames,ce=Object.getOwnPropertySymbols,Me=Object.getPrototypeOf,ue=Object.prototype.hasOwnProperty,$e=Object.prototype.propertyIsEnumerable;var de=(e,t,n)=>t in e?G(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,v=(e,t)=>{for(var n in t||(t={}))ue.call(t,n)&&de(e,n,t[n]);if(ce)for(var n of ce(t))$e.call(t,n)&&de(e,n,t[n]);return e},$=(e,t)=>Ge(e,Ue(t));var Ke=(e,t)=>{for(var n in t)G(e,n,{get:t[n],enumerable:!0})},fe=(e,t,n,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let a of We(t))!ue.call(e,a)&&a!==n&&G(e,a,{get:()=>t[a],enumerable:!(i=Fe(t,a))||i.enumerable});return e};var F=(e,t,n)=>(n=e!=null?Le(Me(e)):{},fe(t||!e||!e.__esModule?G(n,"default",{value:e,enumerable:!0}):n,e)),Be=e=>fe(G({},"__esModule",{value:!0}),e);var lt={};Ke(lt,{renderWithSentient:()=>at});module.exports=Be(lt);var Ve=require("@testing-library/react");var o=require("react"),B=require("@sentientui/core");var He=new Map,je=new Map;function ge(e,t){He.set(e,t);let n=je.get(e);if(n)for(let i of n)try{i(t)}catch(a){}}var ze={on:!1,listeners:new Set};function H(){if(typeof window=="undefined")return ze;let e=window;return e.__sentient_preview||(e.__sentient_preview={on:!1,listeners:new Set}),e.__sentient_preview}function pe(e){let t=H();if(t.on!==e){t.on=e;for(let n of t.listeners)n()}}function j(){return H().on}function me(e){let t=H().listeners;return t.add(e),()=>{t.delete(e)}}function ye(e){return{isLocal:e.isLocal,track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},fetchWeights:()=>Promise.resolve([]),getAssignment:(t,n)=>e.getAssignment(t,n),isUnified:t=>{var n,i;return(i=(n=e.isUnified)==null?void 0:n.call(e,t))!=null?i:!1},assign:(t,n,i,a,d)=>e.assign(t,n,i,a,d),decide:()=>Promise.resolve(null),getSlotResult:t=>e.getSlotResult(t),getSlotConfig:t=>e.getSlotConfig(t),getSitePalette:()=>e.getSitePalette(),reportSlots:t=>e.reportSlots(t),getPersona:()=>e.getPersona(),getGraph:()=>e.getGraph(),flush:()=>e.flush(),dispose:()=>e.dispose(),destroy:()=>e.destroy()}}var Je="sentient:overrides-changed";function U(){var t;if(typeof window=="undefined")return;let e=window;e.__sentient_overrides_version=((t=e.__sentient_overrides_version)!=null?t:0)+1,window.dispatchEvent(new Event(Je))}function ve(e){typeof window!="undefined"&&(window.__sentient_devtools_config=e)}function W(){var e;return typeof process=="undefined"||((e=process.env)==null?void 0:e.NODE_ENV)!=="production"}var Xe={components:new Map,slots:new Map,sections:[],listeners:new Set,version:0};function z(){if(typeof window=="undefined")return Xe;let e=window;return e.__sentient_registry||(e.__sentient_registry={components:new Map,slots:new Map,sections:[],listeners:new Set,version:0}),e.__sentient_registry}function qe(){z().version+=1;for(let e of z().listeners)e()}function J(e){W()&&(z().sections=[...e],qe())}var he="0.44.1",X=he!=="0.0.0-dev"?{name:"react",version:he}:void 0;function Ye(){let e=window;return e.__sentient_slot_config_overrides||(e.__sentient_slot_config_overrides={}),e.__sentient_slot_config_overrides}function T(e,t){Ye()[e]=t}function _e(e){window.__sentient_vocabulary_override=e}function Qe(){let e=window;return e.__sentient_slot_overrides||(e.__sentient_slot_overrides={}),e.__sentient_slot_overrides}function V(e,t){Qe()[e]=t}function Se(e){let t=null;try{let n=location.hash.slice(1),i=RegExp("(^|[?&])"+e+"=([^&]*)").exec(n);if(i){t=i[2];let a=n.slice(i.index+i[0].length);i[1]!="&"&&a[0]=="&"&&(a=i[1]+a.slice(1));let d=n.slice(0,i.index)+a;history.replaceState(history.state,"",d?"#"+d:location.pathname+location.search)}}catch(n){}return t}var Y="__snt_editor_token",D=null,q=!1;function we(){return q}function Ze(){try{return sessionStorage.getItem(Y)}catch(e){return null}}function K(e){if(D)return D;let t=typeof window=="undefined"?null:Se("sentient_editor_code");if(!t){let n=typeof window=="undefined"?null:Ze();return q=!!n,D=Promise.resolve(n?{token:n,fresh:!1}:null),D}return q=!0,D=fetch(`${e}/editor/exchange`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({code:t})}).then(async n=>{let i=n.ok?(await n.json()).token:void 0;if(!i)return{error:n.ok?500:n.status};try{sessionStorage.setItem(Y,i)}catch(a){}return{token:i,fresh:!0}}).catch(()=>({error:0})),D}function be(){try{sessionStorage.removeItem(Y)}catch(e){}}var Ce="sentient_preview_cell",xe="sentient_refresh_region",Q="sentient-cell-preview-bar",P="__preview__",et=null;function ke(e){if(typeof window=="undefined"||typeof document=="undefined"||document.getElementById(Q))return;let t,n;try{let l=new URLSearchParams(window.location.search);t=l.get(Ce),n=l.get(xe)}catch(l){return}if(!t&&!n)return;let i=(e!=null?e:"https://api.sentient-ui.com/v1").replace(/\/$/,""),a=K(i);if(!we())return;if(n){et={slotId:n,session:a,base:i},T(n,{kind:"arms"}),V(n,P),U();return}if(!t)return;let d=t.lastIndexOf("~");if(d<=0)return;let g=t.slice(0,d),O=t.slice(d+1);a.then(l=>l?"token"in l?fetch(`${i}/editor/cell-preview?slotId=${encodeURIComponent(g)}&persona=${encodeURIComponent(O)}`,{headers:{authorization:`Bearer ${l.token}`}}):(M(l.error===401?"This preview link has expired \u2014 reopen it from your dashboard.":"Couldn\u2019t load this preview \u2014 reopen it from your dashboard."),null):null).then(async l=>{if(!l)return;if(!l.ok){M(l.status===401?"This preview link has expired \u2014 reopen it from your dashboard.":"Couldn\u2019t load this preview \u2014 reopen it from your dashboard.");return}let c=await l.json();if(c.vocabulary&&Array.isArray(c.vocabulary.entries)&&_e(c.vocabulary),c.compose!=null)T(g,{kind:"arms",compose:{[P]:c.compose}}),V(g,P);else if(c.edits!=null&&typeof c.skeletonFp=="string"&&Array.isArray(c.leafToNode))T(g,{kind:"arms",edits:{edits:c.edits,fp:c.skeletonFp,leafToNode:c.leafToNode}}),V(g,P);else if(c.blocks!=null)T(g,{kind:"arms",blocks:{[P]:c.blocks}}),V(g,P);else if(c.content!=null)T(g,{kind:"arms",content:c.content}),V(g,P);else{M("Nothing to preview in that square yet.");return}U(),M(`Previewing \u201C${c.slotName}\u201D for ${c.personaDisplay}${c.status==="review"?" \u2014 waiting for your approval":""}. Nothing is being tracked.`),setTimeout(()=>{var p;try{(p=document.querySelector(`[data-sentient-slot="${g}"]`))==null||p.scrollIntoView({block:"center"})}catch(y){}},300)}).catch(()=>M("Couldn\u2019t load this preview \u2014 check your connection and reopen it from your dashboard."))}function M(e){var a;if(document.getElementById(Q))return;let t=document.createElement("div");t.id=Q,Object.assign(t.style,{position:"fixed",bottom:"16px",left:"50%",transform:"translateX(-50%)",zIndex:"2147483647",display:"flex",alignItems:"center",gap:"10px",padding:"10px 14px",borderRadius:"12px",maxWidth:"90vw",background:"#111827",color:"#fff",font:"13px system-ui, sans-serif",border:"1px solid rgba(139,92,246,0.6)",boxShadow:"0 10px 34px rgba(0,0,0,0.45)"});let n=document.createElement("span");n.textContent=e;let i=document.createElement("button");i.textContent="Exit preview",Object.assign(i.style,{padding:"4px 10px",borderRadius:"999px",border:"1px solid rgba(255,255,255,0.35)",background:"transparent",color:"#fff",font:"12px system-ui, sans-serif",cursor:"pointer"}),i.onclick=()=>{be();let d=new URL(window.location.href);d.searchParams.delete(Ce),d.searchParams.delete(xe),window.location.assign(d.toString())},t.append(n,i),((a=document.body)!=null?a:document.documentElement).append(t)}var Re=!1;function Ee(e){if(Re||typeof window=="undefined")return;Re=!0;let t=(e!=null?e:"https://api.sentient-ui.com/v1").replace(/\/$/,"");K(t).then(n=>{!n||!("token"in n)||!n.fresh||tt(t,n.token)})}function tt(e,t){let n=()=>{window.setTimeout(()=>{import("@sentientui/core/style-sample").then(({sampleStyleVocabulary:i})=>fetch(`${e}/editor/style-vocabulary`,{method:"POST",headers:{authorization:`Bearer ${t}`,"content-type":"application/json"},body:JSON.stringify(i(document))})).catch(()=>{})},1e3)};document.readyState==="complete"?n():window.addEventListener("load",n,{once:!0})}var Ie=require("react/jsx-runtime");function nt(){var e,t;if(typeof window=="undefined")return"desktop:direct";try{return(0,B.deriveSessionSegment)({userAgent:(e=navigator.userAgent)!=null?e:"",referer:(t=document.referrer)!=null?t:"",appOrigin:window.location.origin})}catch(n){return"desktop:direct"}}var Pe="https://api.sentient-ui.com/v1",it=(0,o.createContext)({client:null,apiKey:"",initialAssignments:{},initialUnified:[],sessionSegment:"desktop:direct",ssrFallback:"first",onAssignment:void 0,initialLayoutOrder:null,initialSlots:{},initialSlotConfig:{},initialPalette:null,initialVocabulary:null,initialPersona:null,apiBaseUrl:Pe,debug:!1}),Ae=!1,Z=new Set;function rt(e,t,n){let i=(0,o.useRef)(n);i.current=n;let[a,d]=(0,o.useState)(null),[g,O]=(0,o.useState)(!1),l=(0,o.useRef)(e);l.current=e;let c=e===void 0?"":typeof e=="string"?e:JSON.stringify($(v({},e),{check:typeof e.check,refused:typeof e.refused}));return(0,o.useEffect)(()=>{let p=l.current;if(p===void 0||typeof window=="undefined")return;let y,R=!1;return import("@sentientui/core/consent").then(({consentWatcher:x,forgetVisitor:I})=>{if(R)return;let E=x(typeof p=="object"&&p.cmp===void 0&&p.check?v($(v({},p),{check:()=>l.current.check()}),p.refused?{refused:()=>{var _,S;return((S=(_=l.current).refused)==null?void 0:S.call(_))===!0}}:{}):p),w=!1,N=()=>{let _=E.refused()&&E.read()!==!0;_&&!w&&(I(t),i.current()),w=_,O(_);let S=E.read();S!==null&&Z.add(t),d(S!=null?S:Z.has(t)?!1:null)};N(),y=E.subscribe(N)}),()=>{R=!0,y==null||y()}},[c,t]),{granted:a,refused:g}}function Oe(e){var ne,ie,re,oe,se,ae;let[t,n]=(0,o.useState)(null),[i]=(0,o.useState)(()=>{var r;return(r=e.sessionSegment)!=null?r:nt()}),[a,d]=(0,o.useState)(j());(0,o.useEffect)(()=>me(()=>d(j())),[]),(0,o.useEffect)(()=>{ke(e.apiBaseUrl),typeof window!="undefined"&&/[?&]sentient_preview=[^&]*(:|%3A)/i.test(window.location.search)&&(pe(!0),import("@sentientui/react/version-preview").then(r=>r.maybeStartVersionPreview(e.apiKey,e.apiBaseUrl)).catch(()=>{})),Ee(e.apiBaseUrl)},[]);let g=(0,o.useRef)(()=>{}),O=rt(e.consentFrom,e.apiKey,()=>g.current()),l=e.consentFrom?(ne=O.granted)!=null?ne:Z.has(e.apiKey)?!1:e.consent===!0:e.consent,c=e.consentFrom?O.refused:!0,p=(0,o.useRef)(c);p.current=c;let y=(0,o.useRef)(null),R=(0,o.useRef)(!1),x=(0,o.useRef)([]),I=(0,o.useRef)(!1);g.current=()=>{var f;x.current=[],I.current=!0;let r=y.current;r!=null&&r.gated?r.dispose():(f=r==null?void 0:r.takeHeld)==null||f.call(r)},(0,o.useEffect)(()=>{var L,le;if(p.current&&l===!1&&(x.current=[]),l===!1&&R.current&&(p.current&&((L=y.current)==null||L.destroy()),y.current=null,R.current=!1),l===!1&&!e.preConsentBehavior){p.current&&((le=y.current)==null||le.destroy()),y.current=null,n(null);return}let r=l!==!1;r&&(I.current=!1);let f=h=>{!r&&I.current&&h.gated&&h.dispose()},m=v({apiKey:e.apiKey,context:e.context,debug:e.debug,initialAssignments:e.initialAssignments,initialUnified:e.initialUnified,sessionSegment:i,consent:l,preConsentBehavior:e.preConsentBehavior,respectDoNotTrack:e.respectDoNotTrack,ssrSessionId:e.ssrSessionId,cookieDomain:e.cookieDomain,country:e.country,persona:e.persona,internal:e.internal,stageAttributes:e.stageAttributes,localMode:e.localMode,initialSlots:e.initialSlots,initialSlotConfig:e.initialSlotConfig,initialPalette:e.initialPalette,initialVocabulary:e.initialVocabulary,initialPersona:e.initialPersona,ingestUrl:e.apiBaseUrl?`${e.apiBaseUrl.replace(/\/$/,"")}/events`:void 0,nonce:e.nonce},X?{sdk:X}:{}),u=!1,s=null,b=null,C=h=>{for(let A of x.current.splice(0))setTimeout(()=>{if(y.current!==h){I.current||x.current.push(A);return}try{A(h)}catch(ct){}},0)},k=h=>{e.engagement===!1||!r||import("@sentientui/core/engagement").then(({startEngagementCapture:A})=>{u||(b=A(h,{apiKey:e.apiKey,sectionTypes:e.sectionTypes,apiBase:e.apiBaseUrl?e.apiBaseUrl.replace(/\/$/,""):void 0}))})};return e.enableGraph!==!1?import("@sentientui/core/graph").then(({init:h})=>{u||(s=h($(v({},m),{graph:!0,captureDomText:e.captureDomText===!0,sectionTypes:e.sectionTypes})),f(s),y.current=s,R.current=r,C(s),n(s),k(s))}):(s=(0,B.init)(m),f(s),y.current=s,R.current=r,C(s),n(s),k(s)),()=>{var h,A;u=!0,b==null||b(),x.current=x.current.concat((A=(h=s==null?void 0:s.takeHeld)==null?void 0:h.call(s))!=null?A:[]),s==null||s.dispose()}},[l]),(0,o.useEffect)(()=>{if(!t)return;let r=!1,f=async()=>{if(r)return;let u;try{u=await t.fetchWeights()}catch(s){return}if(!r)for(let s of u){let b={componentId:s.componentId,updatedAt:s.updatedAt,variants:s.variants.map(C=>{var k;return{variantId:C.variantId,pulls:C.pulls,avgReward:(k=C.avgReward)!=null?k:0}})};ge(s.componentId,b)}};f();let m=setInterval(()=>{f()},6e4);return()=>{r=!0,clearInterval(m)}},[t]);let E=(ie=e.ssrFallback)!=null?ie:"first",w=((re=e.apiBaseUrl)!=null?re:Pe).replace(/\/$/,""),N=(0,o.useRef)(null);(0,o.useEffect)(()=>{var m;if(typeof process!="undefined"&&((m=process.env)==null?void 0:m.NODE_ENV)==="production")return;let r={apiKey:e.apiKey,context:e.context,country:e.country,persona:e.persona,internal:e.internal,apiBaseUrl:w},f=N.current;if(N.current=r,f!==null)for(let u of["apiKey","context","country","persona","internal","apiBaseUrl"])Object.is(f[u],r[u])||console.warn(`[sentient] AdaptiveProvider: \`${u}\` changed after initialisation, but the SDK client is stable for the session and only re-inits on \`consent\` \u2014 the new value is ignored. Remount the provider (e.g. via a changing \`key\` prop) to apply it.`)},[e.apiKey,e.context,e.country,e.persona,e.internal,w]),(0,o.useEffect)(()=>{var r;typeof process!="undefined"&&((r=process.env)==null?void 0:r.NODE_ENV)==="production"||ve({apiKey:e.apiKey,apiBaseUrl:w,isLocal:(t==null?void 0:t.isLocal)===!0})},[t,e.apiKey,w]);let _=(oe=e.identity)==null?void 0:oe.userId,S=(se=e.identity)==null?void 0:se.userHash,ee=(ae=e.identity)==null?void 0:ae.email;(0,o.useEffect)(()=>{t&&_&&t.identify(_,{userHash:S,email:ee})},[t,_,S,ee]),(0,o.useEffect)(()=>{let r=e.initialLayoutOrder;if(r&&r.length>0){J(r);return}e.declaredSections&&e.declaredSections.length>0&&J(e.declaredSections)},[e.initialLayoutOrder,e.declaredSections]),(0,o.useEffect)(()=>{!W()||e.consent!==void 0||e.consentFrom!==void 0||Ae||(Ae=!0,console.warn('[SentientUI] No consent gate: every visitor is tracked from first paint. Pass consentFrom="<your CMP>" (or consent={true} to silence). https://sentient-ui.com/docs#consent'))},[]),(0,o.useEffect)(()=>{if(!W())return;let r=e.declaredSections;if(!r||r.length===0||typeof document=="undefined")return;let f=new Set(Array.from(document.querySelectorAll("[data-sentient-id]"),u=>u.getAttribute("data-sentient-id"))),m=r.filter(u=>!f.has(u));m.length>0&&console.warn(`[SentientUI] Declared section${m.length>1?"s":""} ${m.map(u=>`"${u}"`).join(", ")} ${m.length>1?"have":"has"} no matching data-sentient-id element, so the layout engine cannot learn what they are and will serve the same order to every persona. Add data-sentient-id="<sectionId>" to each section's element.`)},[e.declaredSections]);let te=(0,o.useMemo)(()=>t&&a?ye(t):t,[t,a]),Ne=(0,o.useMemo)(()=>{var r,f,m,u,s,b,C,k,L;return{client:te,apiKey:e.apiKey,initialAssignments:(r=e.initialAssignments)!=null?r:{},initialUnified:(f=e.initialUnified)!=null?f:ot,sessionSegment:i,ssrFallback:E,onAssignment:e.onAssignment,initialLayoutOrder:(m=e.initialLayoutOrder)!=null?m:null,initialSlots:(u=e.initialSlots)!=null?u:{},initialSlotConfig:(s=e.initialSlotConfig)!=null?s:{},initialPalette:(b=e.initialPalette)!=null?b:null,initialVocabulary:(C=e.initialVocabulary)!=null?C:null,initialPersona:(k=e.initialPersona)!=null?k:null,apiBaseUrl:w,debug:(L=e.debug)!=null?L:!1}},[te,e.apiKey,e.initialAssignments,e.initialUnified,i,E,e.onAssignment,e.initialLayoutOrder,e.initialSlots,e.initialSlotConfig,e.initialPalette,e.initialVocabulary,e.initialPersona,w,e.debug]);return(0,Ie.jsx)(it.Provider,{value:Ne,children:e.children})}var ot=[];function st(e){return e<.3?"low":e<.7?"medium":"high"}function Te(e={}){var n,i,a;let t=window;if(t.__sentient_overrides=v({},(n=e.variants)!=null?n:{}),e.layout?t.__sentient_layout_override=e.layout:delete t.__sentient_layout_override,e.slots?t.__sentient_slot_overrides=v({},e.slots):delete t.__sentient_slot_overrides,e.slotConfig?t.__sentient_slot_config_overrides=v({},e.slotConfig):delete t.__sentient_slot_config_overrides,e.persona){t.__sentient_persona_override={persona:e.persona,confidence:(i=e.confidence)!=null?i:1};try{let d=document.documentElement;d.setAttribute("data-sentient-persona",e.persona),d.setAttribute("data-sentient-confidence",st((a=e.confidence)!=null?a:1))}catch(d){}}else delete t.__sentient_persona_override;U()}var De=require("react/jsx-runtime");function at(e,t={},n){return Te(t),(0,Ve.render)((0,De.jsx)(Oe,{apiKey:"pk_test",consent:!1,children:e}),n)}0&&(module.exports={renderWithSentient});
2
+ "use strict";var Ge=Object.create;var F=Object.defineProperty,Ne=Object.defineProperties,Fe=Object.getOwnPropertyDescriptor,Ue=Object.getOwnPropertyDescriptors,We=Object.getOwnPropertyNames,ce=Object.getOwnPropertySymbols,Me=Object.getPrototypeOf,ue=Object.prototype.hasOwnProperty,$e=Object.prototype.propertyIsEnumerable;var de=(e,t,n)=>t in e?F(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,v=(e,t)=>{for(var n in t||(t={}))ue.call(t,n)&&de(e,n,t[n]);if(ce)for(var n of ce(t))$e.call(t,n)&&de(e,n,t[n]);return e},$=(e,t)=>Ne(e,Ue(t));var Ke=(e,t)=>{for(var n in t)F(e,n,{get:t[n],enumerable:!0})},fe=(e,t,n,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let a of We(t))!ue.call(e,a)&&a!==n&&F(e,a,{get:()=>t[a],enumerable:!(i=Fe(t,a))||i.enumerable});return e};var U=(e,t,n)=>(n=e!=null?Ge(Me(e)):{},fe(t||!e||!e.__esModule?F(n,"default",{value:e,enumerable:!0}):n,e)),Be=e=>fe(F({},"__esModule",{value:!0}),e);var lt={};Ke(lt,{renderWithSentient:()=>at});module.exports=Be(lt);var Ve=require("@testing-library/react");var o=require("react"),B=require("@sentientui/core");var He=new Map,je=new Map;function ge(e,t){He.set(e,t);let n=je.get(e);if(n)for(let i of n)try{i(t)}catch(a){}}var ze={on:!1,listeners:new Set};function H(){if(typeof window=="undefined")return ze;let e=window;return e.__sentient_preview||(e.__sentient_preview={on:!1,listeners:new Set}),e.__sentient_preview}function pe(e){let t=H();if(t.on!==e){t.on=e;for(let n of t.listeners)n()}}function j(){return H().on}function me(e){let t=H().listeners;return t.add(e),()=>{t.delete(e)}}function ye(e){return{isLocal:e.isLocal,track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},fetchWeights:()=>Promise.resolve([]),getAssignment:(t,n)=>e.getAssignment(t,n),isUnified:t=>{var n,i;return(i=(n=e.isUnified)==null?void 0:n.call(e,t))!=null?i:!1},assign:(t,n,i,a,d)=>e.assign(t,n,i,a,d),decide:()=>Promise.resolve(null),getSlotResult:t=>e.getSlotResult(t),getSlotConfig:t=>e.getSlotConfig(t),getSitePalette:()=>e.getSitePalette(),reportSlots:t=>e.reportSlots(t),getPersona:()=>e.getPersona(),getGraph:()=>e.getGraph(),flush:()=>e.flush(),dispose:()=>e.dispose(),destroy:()=>e.destroy()}}var Je="sentient:overrides-changed";function W(){var t;if(typeof window=="undefined")return;let e=window;e.__sentient_overrides_version=((t=e.__sentient_overrides_version)!=null?t:0)+1,window.dispatchEvent(new Event(Je))}function ve(e){typeof window!="undefined"&&(window.__sentient_devtools_config=e)}function R(){try{return process.env.NODE_ENV!=="production"}catch(e){return!0}}var Xe={components:new Map,slots:new Map,sections:[],listeners:new Set,version:0};function z(){if(typeof window=="undefined")return Xe;let e=window;return e.__sentient_registry||(e.__sentient_registry={components:new Map,slots:new Map,sections:[],listeners:new Set,version:0}),e.__sentient_registry}function qe(){z().version+=1;for(let e of z().listeners)e()}function J(e){R()&&(z().sections=[...e],qe())}var he="0.44.3",X=he!=="0.0.0-dev"?{name:"react",version:he}:void 0;function Ye(){let e=window;return e.__sentient_slot_config_overrides||(e.__sentient_slot_config_overrides={}),e.__sentient_slot_config_overrides}function V(e,t){Ye()[e]=t}function _e(e){window.__sentient_vocabulary_override=e}function Qe(){let e=window;return e.__sentient_slot_overrides||(e.__sentient_slot_overrides={}),e.__sentient_slot_overrides}function D(e,t){Qe()[e]=t}function Se(e){let t=null;try{let n=location.hash.slice(1),i=RegExp("(^|[?&])"+e+"=([^&]*)").exec(n);if(i){t=i[2];let a=n.slice(i.index+i[0].length);i[1]!="&"&&a[0]=="&"&&(a=i[1]+a.slice(1));let d=n.slice(0,i.index)+a;history.replaceState(history.state,"",d?"#"+d:location.pathname+location.search)}}catch(n){}return t}var Y="__snt_editor_token",L=null,q=!1;function we(){return q}function Ze(){try{return sessionStorage.getItem(Y)}catch(e){return null}}function K(e){if(L)return L;let t=typeof window=="undefined"?null:Se("sentient_editor_code");if(!t){let n=typeof window=="undefined"?null:Ze();return q=!!n,L=Promise.resolve(n?{token:n,fresh:!1}:null),L}return q=!0,L=fetch(`${e}/editor/exchange`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({code:t})}).then(async n=>{let i=n.ok?(await n.json()).token:void 0;if(!i)return{error:n.ok?500:n.status};try{sessionStorage.setItem(Y,i)}catch(a){}return{token:i,fresh:!0}}).catch(()=>({error:0})),L}function be(){try{sessionStorage.removeItem(Y)}catch(e){}}var Ce="sentient_preview_cell",xe="sentient_refresh_region",Q="sentient-cell-preview-bar",O="__preview__",et=null;function ke(e){if(typeof window=="undefined"||typeof document=="undefined"||document.getElementById(Q))return;let t,n;try{let l=new URLSearchParams(window.location.search);t=l.get(Ce),n=l.get(xe)}catch(l){return}if(!t&&!n)return;let i=(e!=null?e:"https://api.sentient-ui.com/v1").replace(/\/$/,""),a=K(i);if(!we())return;if(n){et={slotId:n,session:a,base:i},V(n,{kind:"arms"}),D(n,O),W();return}if(!t)return;let d=t.lastIndexOf("~");if(d<=0)return;let g=t.slice(0,d),I=t.slice(d+1);a.then(l=>l?"token"in l?fetch(`${i}/editor/cell-preview?slotId=${encodeURIComponent(g)}&persona=${encodeURIComponent(I)}`,{headers:{authorization:`Bearer ${l.token}`}}):(M(l.error===401?"This preview link has expired \u2014 reopen it from your dashboard.":"Couldn\u2019t load this preview \u2014 reopen it from your dashboard."),null):null).then(async l=>{if(!l)return;if(!l.ok){M(l.status===401?"This preview link has expired \u2014 reopen it from your dashboard.":"Couldn\u2019t load this preview \u2014 reopen it from your dashboard.");return}let c=await l.json();if(c.vocabulary&&Array.isArray(c.vocabulary.entries)&&_e(c.vocabulary),c.compose!=null)V(g,{kind:"arms",compose:{[O]:c.compose}}),D(g,O);else if(c.edits!=null&&typeof c.skeletonFp=="string"&&Array.isArray(c.leafToNode))V(g,{kind:"arms",edits:{edits:c.edits,fp:c.skeletonFp,leafToNode:c.leafToNode}}),D(g,O);else if(c.blocks!=null)V(g,{kind:"arms",blocks:{[O]:c.blocks}}),D(g,O);else if(c.content!=null)V(g,{kind:"arms",content:c.content}),D(g,O);else{M("Nothing to preview in that square yet.");return}W(),M(`Previewing \u201C${c.slotName}\u201D for ${c.personaDisplay}${c.status==="review"?" \u2014 waiting for your approval":""}. Nothing is being tracked.`),setTimeout(()=>{var p;try{(p=document.querySelector(`[data-sentient-slot="${g}"]`))==null||p.scrollIntoView({block:"center"})}catch(y){}},300)}).catch(()=>M("Couldn\u2019t load this preview \u2014 check your connection and reopen it from your dashboard."))}function M(e){var a;if(document.getElementById(Q))return;let t=document.createElement("div");t.id=Q,Object.assign(t.style,{position:"fixed",bottom:"16px",left:"50%",transform:"translateX(-50%)",zIndex:"2147483647",display:"flex",alignItems:"center",gap:"10px",padding:"10px 14px",borderRadius:"12px",maxWidth:"90vw",background:"#111827",color:"#fff",font:"13px system-ui, sans-serif",border:"1px solid rgba(139,92,246,0.6)",boxShadow:"0 10px 34px rgba(0,0,0,0.45)"});let n=document.createElement("span");n.textContent=e;let i=document.createElement("button");i.textContent="Exit preview",Object.assign(i.style,{padding:"4px 10px",borderRadius:"999px",border:"1px solid rgba(255,255,255,0.35)",background:"transparent",color:"#fff",font:"12px system-ui, sans-serif",cursor:"pointer"}),i.onclick=()=>{be();let d=new URL(window.location.href);d.searchParams.delete(Ce),d.searchParams.delete(xe),window.location.assign(d.toString())},t.append(n,i),((a=document.body)!=null?a:document.documentElement).append(t)}var Re=!1;function Ee(e){if(Re||typeof window=="undefined")return;Re=!0;let t=(e!=null?e:"https://api.sentient-ui.com/v1").replace(/\/$/,"");K(t).then(n=>{!n||!("token"in n)||!n.fresh||tt(t,n.token)})}function tt(e,t){let n=()=>{window.setTimeout(()=>{import("@sentientui/core/style-sample").then(({sampleStyleVocabulary:i})=>fetch(`${e}/editor/style-vocabulary`,{method:"POST",headers:{authorization:`Bearer ${t}`,"content-type":"application/json"},body:JSON.stringify(i(document))})).catch(()=>{})},1e3)};document.readyState==="complete"?n():window.addEventListener("load",n,{once:!0})}var Ie=require("react/jsx-runtime");function nt(){var e,t;if(typeof window=="undefined")return"desktop:direct";try{return(0,B.deriveSessionSegment)({userAgent:(e=navigator.userAgent)!=null?e:"",referer:(t=document.referrer)!=null?t:"",appOrigin:window.location.origin})}catch(n){return"desktop:direct"}}var Pe="https://api.sentient-ui.com/v1",it=(0,o.createContext)({client:null,apiKey:"",initialAssignments:{},initialUnified:[],sessionSegment:"desktop:direct",ssrFallback:"first",onAssignment:void 0,initialLayoutOrder:null,initialSlots:{},initialSlotConfig:{},initialPalette:null,initialVocabulary:null,initialPersona:null,apiBaseUrl:Pe,debug:!1}),Ae=!1,Z=new Set;function rt(e,t,n){let i=(0,o.useRef)(n);i.current=n;let[a,d]=(0,o.useState)(null),[g,I]=(0,o.useState)(!1),l=(0,o.useRef)(e);l.current=e;let c=e===void 0?"":typeof e=="string"?e:JSON.stringify($(v({},e),{check:typeof e.check,refused:typeof e.refused}));return(0,o.useEffect)(()=>{let p=l.current;if(p===void 0||typeof window=="undefined")return;let y,E=!1;return import("@sentientui/core/consent").then(({consentWatcher:x,forgetVisitor:T})=>{if(E)return;let A=x(typeof p=="object"&&p.cmp===void 0&&p.check?v($(v({},p),{check:()=>l.current.check()}),p.refused?{refused:()=>{var _,S;return((S=(_=l.current).refused)==null?void 0:S.call(_))===!0}}:{}):p),w=!1,G=()=>{let _=A.refused()&&A.read()!==!0;_&&!w&&(T(t),i.current()),w=_,I(_);let S=A.read();S!==null&&Z.add(t),d(S!=null?S:Z.has(t)?!1:null)};G(),y=A.subscribe(G)}),()=>{E=!0,y==null||y()}},[c,t]),{granted:a,refused:g}}function Oe(e){var ne,ie,re,oe,se,ae;let[t,n]=(0,o.useState)(null),[i]=(0,o.useState)(()=>{var r;return(r=e.sessionSegment)!=null?r:nt()}),[a,d]=(0,o.useState)(j());(0,o.useEffect)(()=>me(()=>d(j())),[]),(0,o.useEffect)(()=>{ke(e.apiBaseUrl),typeof window!="undefined"&&/[?&]sentient_preview=[^&]*(:|%3A)/i.test(window.location.search)&&(pe(!0),import("@sentientui/react/version-preview").then(r=>r.maybeStartVersionPreview(e.apiKey,e.apiBaseUrl)).catch(()=>{})),Ee(e.apiBaseUrl)},[]);let g=(0,o.useRef)(()=>{}),I=rt(e.consentFrom,e.apiKey,()=>g.current()),l=e.consentFrom?(ne=I.granted)!=null?ne:Z.has(e.apiKey)?!1:e.consent===!0:e.consent,c=e.consentFrom?I.refused:!0,p=(0,o.useRef)(c);p.current=c;let y=(0,o.useRef)(null),E=(0,o.useRef)(!1),x=(0,o.useRef)([]),T=(0,o.useRef)(!1);g.current=()=>{var u;x.current=[],T.current=!0;let r=y.current;r!=null&&r.gated?r.dispose():(u=r==null?void 0:r.takeHeld)==null||u.call(r)},(0,o.useEffect)(()=>{var N,le;if(p.current&&l===!1&&(x.current=[]),l===!1&&E.current&&(p.current&&((N=y.current)==null||N.destroy()),y.current=null,E.current=!1),l===!1&&!e.preConsentBehavior){p.current&&((le=y.current)==null||le.destroy()),y.current=null,n(null);return}let r=l!==!1;r&&(T.current=!1);let u=h=>{!r&&T.current&&h.gated&&h.dispose()},f=v({apiKey:e.apiKey,context:e.context,debug:e.debug,initialAssignments:e.initialAssignments,initialUnified:e.initialUnified,sessionSegment:i,consent:l,preConsentBehavior:e.preConsentBehavior,respectDoNotTrack:e.respectDoNotTrack,ssrSessionId:e.ssrSessionId,cookieDomain:e.cookieDomain,country:e.country,persona:e.persona,internal:e.internal,stageAttributes:e.stageAttributes,localMode:e.localMode,initialSlots:e.initialSlots,initialSlotConfig:e.initialSlotConfig,initialPalette:e.initialPalette,initialVocabulary:e.initialVocabulary,initialPersona:e.initialPersona,ingestUrl:e.apiBaseUrl?`${e.apiBaseUrl.replace(/\/$/,"")}/events`:void 0,nonce:e.nonce},X?{sdk:X}:{}),m=!1,s=null,b=null,C=h=>{for(let P of x.current.splice(0))setTimeout(()=>{if(y.current!==h){T.current||x.current.push(P);return}try{P(h)}catch(ct){}},0)},k=h=>{e.engagement===!1||!r||import("@sentientui/core/engagement").then(({startEngagementCapture:P})=>{m||(b=P(h,{apiKey:e.apiKey,sectionTypes:e.sectionTypes,apiBase:e.apiBaseUrl?e.apiBaseUrl.replace(/\/$/,""):void 0}))})};return e.enableGraph!==!1?import("@sentientui/core/graph").then(({init:h})=>{m||(s=h($(v({},f),{graph:!0,captureDomText:e.captureDomText===!0,sectionTypes:e.sectionTypes})),u(s),y.current=s,E.current=r,C(s),n(s),k(s))}):(s=(0,B.init)(f),u(s),y.current=s,E.current=r,C(s),n(s),k(s)),()=>{var h,P;m=!0,b==null||b(),x.current=x.current.concat((P=(h=s==null?void 0:s.takeHeld)==null?void 0:h.call(s))!=null?P:[]),s==null||s.dispose()}},[l]),(0,o.useEffect)(()=>{if(!t)return;let r=!1,u=async()=>{if(r)return;let m;try{m=await t.fetchWeights()}catch(s){return}if(!r)for(let s of m){let b={componentId:s.componentId,updatedAt:s.updatedAt,variants:s.variants.map(C=>{var k;return{variantId:C.variantId,pulls:C.pulls,avgReward:(k=C.avgReward)!=null?k:0}})};ge(s.componentId,b)}};u();let f=setInterval(()=>{u()},6e4);return()=>{r=!0,clearInterval(f)}},[t]);let A=(ie=e.ssrFallback)!=null?ie:"first",w=((re=e.apiBaseUrl)!=null?re:Pe).replace(/\/$/,""),G=(0,o.useRef)(null);(0,o.useEffect)(()=>{if(!R())return;let r={apiKey:e.apiKey,context:e.context,country:e.country,persona:e.persona,internal:e.internal,apiBaseUrl:w},u=G.current;if(G.current=r,u!==null)for(let f of["apiKey","context","country","persona","internal","apiBaseUrl"])Object.is(u[f],r[f])||console.warn(`[sentient] AdaptiveProvider: \`${f}\` changed after initialisation, but the SDK client is stable for the session and only re-inits on \`consent\` \u2014 the new value is ignored. Remount the provider (e.g. via a changing \`key\` prop) to apply it.`)},[e.apiKey,e.context,e.country,e.persona,e.internal,w]),(0,o.useEffect)(()=>{R()&&ve({apiKey:e.apiKey,apiBaseUrl:w,isLocal:(t==null?void 0:t.isLocal)===!0})},[t,e.apiKey,w]);let _=(oe=e.identity)==null?void 0:oe.userId,S=(se=e.identity)==null?void 0:se.userHash,ee=(ae=e.identity)==null?void 0:ae.email;(0,o.useEffect)(()=>{t&&_&&t.identify(_,{userHash:S,email:ee})},[t,_,S,ee]),(0,o.useEffect)(()=>{let r=e.initialLayoutOrder;if(r&&r.length>0){J(r);return}e.declaredSections&&e.declaredSections.length>0&&J(e.declaredSections)},[e.initialLayoutOrder,e.declaredSections]),(0,o.useEffect)(()=>{!R()||e.consent!==void 0||e.consentFrom!==void 0||Ae||(Ae=!0,console.warn('[SentientUI] No consent gate: every visitor is tracked from first paint. Pass consentFrom="<your CMP>" (or consent={true} to silence). https://sentient-ui.com/docs#consent'))},[]),(0,o.useEffect)(()=>{if(!R())return;let r=e.declaredSections;if(!r||r.length===0||typeof document=="undefined")return;let u=new Set(Array.from(document.querySelectorAll("[data-sentient-id]"),m=>m.getAttribute("data-sentient-id"))),f=r.filter(m=>!u.has(m));f.length>0&&console.warn(`[SentientUI] Declared section${f.length>1?"s":""} ${f.map(m=>`"${m}"`).join(", ")} ${f.length>1?"have":"has"} no matching data-sentient-id element, so the layout engine cannot learn what they are and will serve the same order to every persona. Add data-sentient-id="<sectionId>" to each section's element.`)},[e.declaredSections]);let te=(0,o.useMemo)(()=>t&&a?ye(t):t,[t,a]),Le=(0,o.useMemo)(()=>{var r,u,f,m,s,b,C,k,N;return{client:te,apiKey:e.apiKey,initialAssignments:(r=e.initialAssignments)!=null?r:{},initialUnified:(u=e.initialUnified)!=null?u:ot,sessionSegment:i,ssrFallback:A,onAssignment:e.onAssignment,initialLayoutOrder:(f=e.initialLayoutOrder)!=null?f:null,initialSlots:(m=e.initialSlots)!=null?m:{},initialSlotConfig:(s=e.initialSlotConfig)!=null?s:{},initialPalette:(b=e.initialPalette)!=null?b:null,initialVocabulary:(C=e.initialVocabulary)!=null?C:null,initialPersona:(k=e.initialPersona)!=null?k:null,apiBaseUrl:w,debug:(N=e.debug)!=null?N:!1}},[te,e.apiKey,e.initialAssignments,e.initialUnified,i,A,e.onAssignment,e.initialLayoutOrder,e.initialSlots,e.initialSlotConfig,e.initialPalette,e.initialVocabulary,e.initialPersona,w,e.debug]);return(0,Ie.jsx)(it.Provider,{value:Le,children:e.children})}var ot=[];function st(e){return e<.3?"low":e<.7?"medium":"high"}function Te(e={}){var n,i,a;let t=window;if(t.__sentient_overrides=v({},(n=e.variants)!=null?n:{}),e.layout?t.__sentient_layout_override=e.layout:delete t.__sentient_layout_override,e.slots?t.__sentient_slot_overrides=v({},e.slots):delete t.__sentient_slot_overrides,e.slotConfig?t.__sentient_slot_config_overrides=v({},e.slotConfig):delete t.__sentient_slot_config_overrides,e.persona){t.__sentient_persona_override={persona:e.persona,confidence:(i=e.confidence)!=null?i:1};try{let d=document.documentElement;d.setAttribute("data-sentient-persona",e.persona),d.setAttribute("data-sentient-confidence",st((a=e.confidence)!=null?a:1))}catch(d){}}else delete t.__sentient_persona_override;W()}var De=require("react/jsx-runtime");function at(e,t={},n){return Te(t),(0,Ve.render)((0,De.jsx)(Oe,{apiKey:"pk_test",consent:!1,children:e}),n)}0&&(module.exports={renderWithSentient});
3
3
  //# sourceMappingURL=react.js.map